diff --git a/CMakeLists.txt b/CMakeLists.txt index e8104369..e0c61046 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.12.0 LANGUAGES C CXX) +project(radiance VERSION 1.13.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index 0b741430..b30cb6fa 100644 --- a/NOTICE +++ b/NOTICE @@ -16,8 +16,10 @@ Written by Deadcode, with contributions from: 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, the - Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, and Gemma 4's E2B/E4B form (KV-shared - layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B + Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, Gemma 4's E2B/E4B form (KV-shared + layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B, its audio + encoder, its i8a8 linears and its KV heads replicated over ranks, 4-bit weights at decode heights + through w4a16_asym, and the Ornith-1.5-122B compose files - mechkbfan: the token embedding in the pinned host pool - Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft coupling with its cooperative verify (--draft-coupling) @@ -31,14 +33,17 @@ Written by Deadcode, with contributions from: - hazyumps: static YaRN for the Qwen rotary paths - malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit - asymmetric GEMMs + asymmetric GEMMs, and the int8 tiled GEMMs loading the weight a slab ahead - Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host emulator that tests them, the prefill split into two slices with their all-reduces beside the compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused with the junctions, overlapped with the compute and sent compressed, chained launches with block - drafters), the embedding scale rounded as Hugging Face rounds it, and block drafters' drafts - accepted on the card + drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts + accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's + GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no + step queued behind one that ends its requests, and a step's tokens streamed before the drafter's + passes end - redxherring: --model taking a Hugging Face repo id - Smellyyyy: the idea behind --prefill-interleave - gearwave00001: /v1/messages as Claude Code sends it @@ -56,7 +61,10 @@ Written by Deadcode, with contributions from: decodes them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the fp8 and int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second lane, Gemma 3's junctions under a lossy wire, the block drafter's short block - (--draft-short-from) and the f16 delta-net state cache + (--draft-short-from), the f16 delta-net state cache, the two-rank all-reduce checking a peer's push + has landed, the MXFP4 decode gate_up folded with its activation and fp8 quantiser, the head-256 + split-KV decode attention, weight reads beside the decode all-reduces (--weight-prefetch), the + head-256 prefill attention's KV split for small launches, and the GUIDE's two engines on one pair - eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8 linears' operands directly @@ -67,7 +75,8 @@ Written by Deadcode, with contributions from: name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA - row form (--tp-attn-split rows) and DELETE /sessions + row form (--tp-attn-split rows), DELETE /sessions, and the dispatch stamps of a played pass with + stampgaps.py - 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 @@ -76,13 +85,19 @@ Written by Deadcode, with contributions from: the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped rotation - C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual - projection + projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's + request history - J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter - thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8) -- lortht: Krea 2's rebalance of the text taps +- lortht: Krea 2's rebalance of the text taps and its presets, and MiniMax-H3's modulation rows - Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory - farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix -- gostar: snapshot-backed prefix KV kept across recomputes +- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its + BF16, FP8 and GGUF adapters, its KV scales, and its native sectioned tool calls +- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the + per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch +- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2 + drafter -- and the ParoQuant M2XFP4 import 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 708bc5a0..30b47eb2 100644 --- a/README.md +++ b/README.md @@ -119,8 +119,9 @@ soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned host memory. With LBH-123-AI's latent upscaler in the container, `"latent_upscale": 2` runs the first steps at half the size and refines at the full size: MiniMax-H3's clip then takes 3.4 minutes -(docs/GUIDE.md §5.16). MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK, -the Republic of Korea or the USA. +(docs/GUIDE.md §5.16). A ComfyUI node, `integrations/comfyui/ComfyUI-Radiance-MiniMax`, renders +through `/v1/videos` from a ComfyUI graph as a client of the server. MiniMax-H3's license, which +FastH3 carries, does not cover the EU, the UK, the Republic of Korea or the USA. MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and @@ -328,6 +329,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o | [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server | | [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax | | [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files | +| [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model | | [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card | | [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry | | [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 7399a732..0894c15a 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -16,45 +16,8 @@ extern "C" { * rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or * rad_spechub.h. Every kind of plugin reports it, and a plugin that does not report exactly this * version is refused at load with both versions printed. A new optional export (e.g. - * rad_plugin_reference) is not a - * change of shape: a plugin without it gets the default. - * - * 26: RadKVGroupBatch grows one trailing, zero-defaulted field (`stream`, a RadKVStream) so a - * plugin can see a streamed KV group's ring, residency map and host mirror, and RadBuildCtx grows - * `kv_resident_blocks` and `kv_stream_ok` (--kv-resident and the architecture's capability). Every - * earlier field keeps its offset, but the structs are larger, so out-of-tree plugins must be - * rebuilt against 26. - * - * 27: RadBuildCtx grows `cvec`, a rank's control-vector direction table (control vectors). Trailing - * and zero-defaulted as above, so a plugin built against 26 keeps every offset. - * - * 28: RadArchProbe grows two trailing, zero-defaulted fields that met in the same merge: - * `chain_pays` (the plugin measured its speculative step faster with chained launches) and - * `kv_stream_ok` (the architecture can move a KV group between host memory and a resident ring). - * Both are additions a 27 plugin never reads; a plugin that does set them must be built against - * 28, since 27's struct ends where these begin. - * - * 29: radiance 1.11.0's Unlimited-OCR and control-vector work meets KV streaming. RadBuildCtx - * grows `attn_prefill_fp8` (--attn-prefill-fp8, the prefill attention's products accepted in - * e4m3); it fills the four padding bytes ABI 28 already had after `kv_quant`, so no field moves. - * RadArchProbe grows `control_vector_ok` after ABI 28's `kv_stream_ok`: upstream 1.11.0 had it at - * the offset `kv_stream_ok` took in 28, so it moves to 80 and the struct grows, which is why this - * is a bump. Both trailing fields are zero-defaulted, but a plugin that sets either must be built - * against 29. - * - * 30: radiance 1.12.0 meets KV streaming. Upstream spent 27 on its own additions and this tree had - * already spent it, so the merge takes the next number for both: upstream's `RadBuildCtx` grows - * `tp_attn_rows`, `state_dtype` (--state-cache-dtype f16) and `draft_coupling`, and gains - * `rad_lane1_window_begin/end` and `rad_drafter_short_block`; `RadArchProbe` grows - * `tp_attn_rows_ok` and `state_f16_ok`; `RadAudioGenBatch` grows `prev_slot`/`prev_pos`/ - * `prev_used` and the reference prompt's `n_ref`/`ref_samples`/`ref_audio`/`ref_cu`/`ref_cu_h`/ - * `ref_frame`/`ref_frame_h`; `RadAudioGenDecl` grows `branches`, `input_special` and the - * `tmpl_ref`/`ref_*` reference template; and the plugin ABI gains `rad_spechub.h` (a whole new - * header) with the per-row `rad_kernel_reference` override. Every upstream field is trailing and - * zero-defaulted, and `RadKVStream` loses our never-read `scratch` (80 -> 72 bytes), so a plugin - * built against 26-29 keeps the offsets it reads only if it is rebuilt; the loss of a middle - * pointer in `RadKVStream` is why this is a bump even before upstream's additions. */ -#define RAD_ABI_VERSION 30u + * rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */ +#define RAD_ABI_VERSION 31u /* ================================================================== 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 4e1062e7..1dd92868 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -188,11 +188,20 @@ typedef struct RadBuildCtx { * 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel * takes it, so a plugin that ignores the field is refused rather than silently exact. * - * Zero-defaulted and in the padding after kv_quant, so no other field moves and a plugin built - * against the older struct is unchanged. */ + * Zero-defaulted and in the padding after kv_quant, so no other field moves. */ int attn_prefill_fp8; - /* ---- appended in ABI 26 (control vectors) */ + /* ---- appended in ABI 30 (KV streaming) */ + /* --kv-resident in tokens, 0 when nothing streams: the ring a streamed group carves is this in + * whole blocks, raised to the engine's floors and clamped to the context. A plugin states it as + * its `kv_resolve`'s ring depth. */ + int64_t kv_resident_blocks; + /* RadArchProbe::kv_stream_ok. The streamed-only ops (`kv_store_streamed`, its folded form, + * `kv_resolve`) are declared only when this is set and kv_resident_blocks asks for a ring; + * otherwise rad_op_declared says no and the plugin takes its resident path. */ + int kv_stream_ok; + + /* ---- appended in ABI 27 (control vectors) */ /* A control vector loaded from a GGUF `controlvector` file found for this model, or null. * * The engine loads and validates it once, at bringup, and the plugin only reads it: the @@ -240,6 +249,17 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int draft_coupling; + + /* ---- appended in ABI 28 (weight prefetch) */ + /* Nonzero from --weight-prefetch off: the plugin declares none of its weight prefetches, the + * reads of a following GEMM's weight beside a collective (arch/common/rad_arch.h + * prefetch_beside). An engine that shares its cards with another server sets it: where the + * read goes on the second lane, the two servers hold more compute queues than a card has + * slots, and the join from the first lane puts a queue switch into every decode step. 0, the + * zero-initialised default, prefetches where the plugin does. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int weight_prefetch_off; } RadBuildCtx; /* ================================================================== control vectors */ @@ -428,6 +448,10 @@ typedef struct RadKVGroupDecl { rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d); /* Valid only after the op that reads this group has been declared. 0 before that. */ int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g); +/* Bytes one block of one layer of a paged group occupies: its pool slot's pitch and its host + * mirror row's. 0 for a group that is not paged, or before the block size is known. Additive + * export. */ +int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g); /* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */ int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g); @@ -526,9 +550,16 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g); * rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and * cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would * have written and the leader compares. Paged groups only, and never a group this rank declared - * zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */ + * zero. No effect at one rank, and none on a group that streams, whose host mirror is its tier. + * Additive export. */ int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g); +/* The group is read over its whole history every decode step (an indexer's block keys), so it + * cannot stream. While a sibling group streams, its carve holds every sequence's full context + * rather than the split's share, as the sibling's host mirror holds --max-num-seqs sequences. + * Additive export. */ +int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g); + #define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \ (int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf)) @@ -1206,9 +1237,24 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); * pass carries the geometry its latent has at that point: a step before the VUPSCALE pass is at * W' x H'. The schedule is the request's own, whatever size each evaluation runs at. * + * Reference conditioning, for a plugin with the VAE encoders (`max_enc_side`, `max_enc_samples`, + * below): before the prompt pass each of a request's reference media and keyframes is encoded, + * one a pass, into the lane, where the steps read it. Nothing an encode makes is read back. + * + * RAD_GEN_PASS_VENCODE one picture or video, its frames in `enc_pixels` (RadVideoGenBatch), + * through the video VAE's encoder. + * RAD_GEN_PASS_AENCODE one soundtrack, its samples in `enc_samples`, through the audio VAE's + * encoder. + * + * `enc_kind` (RAD_ENC_*, rad_runtime.h) and `enc_slot`, the media's 1-based number within its kind, + * say where the latents go. The media's shape is the plugin's to accept: rad_arch_encode_geom + * (below) refuses what the encoders cannot take, and the step's packed sequence with the encoded + * media in it is the plugin's rad_arch_video_pack. + * * A program declares exactly one of this, the other generators, logits or pooled vectors. */ enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10, - RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12 }; + RAD_GEN_PASS_VDECODE = 11, RAD_GEN_PASS_VUPSCALE = 12, + RAD_GEN_PASS_VENCODE = 13, RAD_GEN_PASS_AENCODE = 14 }; typedef struct RadVideoGenDecl { const char* name; /* "minimax-h3" -- the served model id and messages */ @@ -1326,6 +1372,20 @@ typedef struct RadVideoGenDecl { * Null: one decoder. */ const char* decoders; const int64_t* decoder_max_area; + + /* ---- appended in ABI 31 (MiniMax-H3 reference conditioning, above) */ + /* The reference media a request may carry: pictures, videos (each with an optional soundtrack + * of its own) and standalone soundtracks. 0 for none of a kind; a plugin that declares any + * exports rad_arch_video_pack. */ + int64_t max_ref_images, max_ref_videos, max_ref_audios; + /* What one encode pass carries: a video's frames after rad_arch_encode_geom pads them to whole + * clips, a frame's longer side and a soundtrack's samples. `max_enc_side` 0: no video encoder, + * `max_enc_samples` 0: no audio encoder. A picture's sides are multiples of `enc_ratio`. */ + int64_t max_enc_frames, max_enc_side, max_enc_samples; + int32_t enc_ratio; + /* The distinct modulations a step's groups may read (rad_arch_video_pack's `mod`, the highest + * cell + 1); a request needing more is refused at submit. 0: no limit. */ + int32_t max_mod_cells; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); @@ -1429,6 +1489,12 @@ typedef struct RadArchProbe { * then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin * that never measured them asks for nothing. */ int32_t chain_pays; + /* ---- appended in ABI 30 (KV streaming) */ + /* Nonzero when the architecture can stream a KV group between host memory and a VRAM ring: its + * attention is sparse and block-addressed and it declares a streamed store and `kv_resolve`. + * --kv-resident on an architecture that says 0 is turned off at startup, and nothing streamed + * is declared (RadBuildCtx::kv_stream_ok). */ + int32_t kv_stream_ok; /* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is * refused at startup with the plugin named when this is 0. */ int32_t control_vector_ok; @@ -1646,6 +1712,27 @@ typedef struct RadVideoGeom { enum { RAD_VPOS_STEP = 1, RAD_VPOS_DECODE = 2 }; int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap); +/* The geometry of an encode pass (RAD_GEN_PASS_VENCODE, RAD_GEN_PASS_AENCODE): the int32s the + * driver stages verbatim in RadVideoGenBatch::enc_geom_d for the plugin's kernels. `kind` is the + * pass; `in` is {frames or samples, height, width, channels}, 0 where unused. With `out` null it + * returns the count, with `out` it fills out[cap]; negative for media the encoders cannot take. + * Entry 0 of an Aencode geometry is the samples padded to the encoder's hop, entry 23 of a Vencode + * geometry the frames padded to whole clips and entry 24 its latent frames: the driver stages the + * media padded to those lengths. A plugin with encoders exports it. Called on any thread. */ +int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, int64_t cap); + +/* The packed sequence of a step with reference media or keyframes in: `ref_tab` is + * RadVideoGenBatch::ref_tab. Returns the sequence's rows, the rows RAD_VPOS_STEP would position, or + * a negative status. `seg` receives the segment boundaries (seg[0] = 0, the last the rows) and + * `mod` the boundaries of the modulation groups, then the cell each group reads (groups that read + * the same modulation share a cell, numbered from 0); `*n_seg` and `*n_mod` are their capacities + * in and their counts out, and a null array asks for the count alone. `pos` receives the rotary + * positions, f32 [3, rows], when `cap_pos` holds 3 x rows. A plugin that declares reference media + * exports it. Called on any thread. */ +int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, int32_t* seg, + int32_t* n_seg, int32_t* mod, int32_t* n_mod, float* pos, + int64_t cap_pos); + int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx); /* Forward declaration; the signature is in rad_runtime.h. */ struct RadCtx; diff --git a/abi/rad_device.h b/abi/rad_device.h index 72a12511..be5a1d0f 100644 --- a/abi/rad_device.h +++ b/abi/rad_device.h @@ -42,10 +42,9 @@ int rad_dev_count(void); int rad_dev_set(int device); int rad_dev_props(int device, RadDeviceProps* out); int rad_dev_enable_peer(int self, int peer); -/* Whether the driver reports that `self` can reach `peer`'s memory, 1 or 0, asked before anything - * is enabled: this is the fact collectives constrain (rad_types.h's RAD_FACT_P2P), so a tool that - * declares a multi-rank graph must measure it and set the fact as Engine does. Negative on a - * device error. */ +/* 1 when the driver reports that `self` can reach `peer`'s memory, 0 when not, negative on a + * device error. A tool that declares a multi-rank graph sets the device.p2p fact from it, as the + * engine does (RAD_FACT_P2P). */ int rad_dev_peer_access(int self, int peer); void* rad_dev_alloc(int64_t bytes, int kind); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 013094b6..59dd2ed3 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -23,52 +23,34 @@ typedef struct RadCtx RadCtx; enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 }; /* ================================================================== KV streaming */ -/* A streamed KV group keeps its whole context in pinned host memory and only a ring of blocks on - * the card (docs/KV-STREAMING.md §3.2, §3.6, §4.2). The step batch carries this view of that - * group; a group whose KV is fully resident has none. +/* A streamed KV group keeps its whole context in pinned host memory and a ring of blocks on the + * card (docs/KV-STREAMING.md). The step batch points every group that streams at this view, which + * is fixed from bring-up (so a recorded pass replays a resolve); a resident group's is null. * - * Why one pointer to a struct rather than fields inside RadKVGroupBatch: the data is per group - * and fixed at bring-up, while the batch is rebuilt per step for every rank, so copying its - * pointers and geometry per group into every step's batch would be work that never changes. One - * trailing pointer also keeps a group's own layout as it was for every plugin that does not - * stream: the field is zero-defaulted, and a null `stream` means the group is fully resident and - * has no ring, no map and no host copy. - * - * The layout mirrors the pool, layer by layer: a layer's mirror is a dense run of `blocks` rows - * of `block_bytes`, and `host_layer_stride` is `blocks * block_bytes`. So layer l's row for block - * b is at `host + l * host_layer_stride + b * block_bytes`, and `block_bytes` is both the row - * pitch `kv_resolve` reads the mirror at and the length of every copy into the ring. - * - * `res`, `slot_block`, `slot_state` and `ctl` are device memory: a resolve launch reads and - * rewrites them every step, so a host round trip per lookup would cost the link latency the ring - * exists to avoid. Nothing here changes address for the engine's life, which is what lets a - * recorded pass replay a resolve. */ + * The mirror is laid out like the pool, layer by layer: layer l's row for block b is at + * `host + l * host_layer_stride + b * block_bytes`. `res`, `slot_block`, `slot_state` and `ctl` + * are device memory, read and rewritten by every resolve launch. */ typedef struct RadKVStream { - /* The group's mirror, pinned host memory, RAD_MEM_HOST_MAPPED so a device kernel reads it over - * the link in place. `blocks * bytes_per_block` bytes, all layers, zeroed at bring-up: a block - * no store has written yet reads as zeros rather than as whatever the page held. */ + /* The mirror: pinned host memory a kernel reads over the link in place, every layer, zeroed at + * bring-up. */ uint8_t* host; - /* Residency, both directions, ONE SLICE A LAYER: `res` is block -> ring slot or -1 (device, - * `n_layers * blocks` entries, layer l at `res + l * blocks`), `slot_block` is slot -> block or - * -1 (`n_layers * slots`), `slot_state` is `n_layers * slots * 2`: the epoch of a slot's last - * use and its CLOCK reference bit. A block is resident per layer because the resolve copies one - * layer's bytes; a group-wide map would call a block resident for a layer that was never - * copied. `ctl` is shared: its counters and overflow latch are the group's. */ + /* Residency, one slice a layer: `res` is block -> ring slot or -1 (layer l at `res + l * + * blocks`), `slot_block` is slot -> block or -1, `slot_state` is [slots, 2]: the epoch of a + * slot's last use and its CLOCK reference bit. Per layer, because the resolve copies one + * layer's bytes. */ int32_t* res; int32_t* slot_block; int32_t* slot_state; - /* The control block: epoch, clock hand, the last launch's miss count, the overflow latch, and - * the cumulative misses/lookups/calls counters (docs/OPS.md "kv_resolve"). */ + /* The group's control block: epoch, clock hand, the last launch's miss count, the overflow + * latch and cumulative counters (docs/OPS.md "kv_resolve"). */ int32_t* ctl; - /* Bytes one block of ONE layer occupies: the mirror's row pitch and the ring's slot pitch. */ + /* Bytes one block of one layer occupies: the mirror's row pitch and the ring's slot pitch. */ int64_t block_bytes; - /* Bytes one layer of the mirror occupies, i.e. the distance between layer l and layer l+1. */ + /* Bytes between one layer's mirror and the next. */ int64_t host_layer_stride; - /* Ring depth in blocks: the group's device pool is `slots` blocks deep while a selection names - * block ids over the group's whole context. */ + /* The ring's depth in blocks; a selection names block ids over the whole context. */ int64_t slots; - /* Bytes the host mirror occupies, all layers (`blocks * block_bytes * n_layers`), so a caller - * that only has this view can report or check the off-card tier. */ + /* The whole mirror's bytes, every layer. */ int64_t host_bytes; } RadKVStream; @@ -86,9 +68,7 @@ typedef struct RadKVGroupBatch { int64_t state_index_pitch; int64_t block_size; int64_t max_blocks; - /* Null unless this group's KV streams: the mirror, the residency map and the ring's geometry - * (RadKVStream above). Trailing and zero-defaulted, so a plugin built against ABI 25 reads - * every field it knows at the same offset and simply never sees the ring. */ + /* Null unless this group streams (RadKVStream). Trailing and zero-defaulted. */ const RadKVStream* stream; } RadKVGroupBatch; @@ -593,8 +573,11 @@ enum { * ADECODE no rows of the pass's own. * VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE). * VUPSCALE no rows of the pass's own: the lane's video latent from `geom_from` to `geom`. + * VENCODE no rows of the pass's own: a picture's or a video's frames in `enc_pixels`. + * AENCODE no rows of the pass's own: a soundtrack's samples in `enc_samples`. * * Every pointer is device memory unless the name ends in _h. */ + typedef struct RadVideoGenBatch { int32_t lane; RadVideoGeom geom; /* the request's geometry */ @@ -603,9 +586,10 @@ typedef struct RadVideoGenBatch { /* The same lane, i32 [1], and 1 on a request's first step (0 otherwise), i32 [1]. */ const int32_t* lane_d; const int32_t* first_d; - /* i32 [4]: the packed sequence's segments, {0, n_text, n_text + audio rows, n_tok} -- text, - * soundtrack, video -- and i32 [4] {0, video rows, 0, audio rows}, the bounds of the lane's two - * latents counted from each one's first row. */ + /* i32: the packed sequence's segment boundaries, {0, n_text, n_text + audio rows, n_tok} -- + * text, soundtrack, video -- or rad_arch_video_pack's for a request with references; and i32 + * [4] {0, video rows, 0, audio rows}, the bounds of the lane's two latents counted from each + * one's first row. */ const int32_t* seg_cu; const int32_t* lat_cu; @@ -616,7 +600,8 @@ typedef struct RadVideoGenBatch { /* ---- VSTEP */ int32_t step; /* from 0; the first draws the lane's noise */ - /* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */ + /* f32 [16]: the video's timestep, sigma and next sigma, then the soundtrack's; from [6] the + * res_multistep scalars of the video, then of the soundtrack (`sampler`, below). */ const float* sched; const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */ /* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and @@ -656,8 +641,55 @@ typedef struct RadVideoGenBatch { /* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the * default. */ int32_t decoder; + + /* ---- appended in ABI 31 (rad_builder.h, "Reference conditioning") */ + /* The sampler a VSTEP advances the latents with: RAD_SAMPLER_EULER, the first-order step on + * sched[0..5], or RAD_SAMPLER_RES_MULTISTEP, the second-order one on the clean estimate + * (k-diffusion's res_multistep at eta 0), which keeps the previous step's estimate. Its scalars + * are sched[6..10] for the video and sched[11..15] for the soundtrack: sigma, r = next sigma / + * sigma, the weights hb1 and hb2 of this step's estimate and the previous one, and the order, + * 1 where there is no previous estimate on the same grid. */ + int32_t sampler; + /* VENCODE: f32 [enc_frames, enc_height, enc_width, 3] RGB in 0..255, the frames padded to + * whole clips by repeating the last (rad_arch_encode_geom's entry 23). AENCODE: f32 + * [enc_channels, enc_n_samples], each channel padded with zeros to the hop (entry 0). Both: + * the pass's geometry as rad_arch_encode_geom gave it, i32 on the device, and the media's + * kind (RAD_ENC_*, below) and its number within the kind from 1. */ + const float* enc_pixels; + int32_t enc_frames, enc_height, enc_width; + const float* enc_samples; + int64_t enc_n_samples; + int32_t enc_channels; + const int32_t* enc_geom_d; + int32_t enc_kind, enc_slot; + /* VCOND and VSTEP of a request with reference media or keyframes: their table, host i32, null + * without. [0] the references, [1] the keyframes, then 6 words a reference {kind, slot, latent + * height, latent width, latent frames, soundtrack latents} in presentation order and 3 a + * keyframe {frame, latent frames, soundtrack latents}, then the prompt's vision pads: a count + * and {first token, tokens} of each picture's run. A reference's kind is RAD_VREF_PICTURE, + * _AUDIO or _VIDEO; its slot is its encode pass's. */ + const int32_t* ref_tab; + /* VSTEP: i32, rad_arch_video_pack's `mod`: the boundaries of the modulation groups, then the + * cell each reads; `seg_cu` then holds the segment boundaries. A request without references + * stages `seg_cu`'s four and no cells. */ + const int32_t* mod_cu; } RadVideoGenBatch; +enum { RAD_SAMPLER_EULER = 0, RAD_SAMPLER_RES_MULTISTEP = 1 }; + +/* RadVideoGenBatch::enc_kind: the media an encode pass carries, numbered from 1 within a kind. A + * keyframe is 1 for the first frame and 2 for the last. */ +enum { + RAD_ENC_IMAGE = 1, /* a reference picture; Vencode */ + RAD_ENC_VIDEO = 2, /* a reference video; Vencode */ + RAD_ENC_VAUDIO = 3, /* the soundtrack of reference video `enc_slot`; Aencode */ + RAD_ENC_AUDIO = 4, /* a standalone soundtrack; Aencode */ + RAD_ENC_KEYFRAME = 5 /* a first or last frame; Vencode */ +}; + +/* RadVideoGenBatch::ref_tab: a reference's kind. */ +enum { RAD_VREF_PICTURE = 0, RAD_VREF_AUDIO = 1, RAD_VREF_VIDEO = 2 }; + /* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent * frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w, * first, last) is one run, and the same chunk in patches. */ @@ -780,19 +812,18 @@ int rad_step_fail(RadCtx* c, const char* what); /* ================================================================== run-phase queries */ const RadBatch* rad_batch(RadCtx* c); -/* The position of absolute model layer `layer` in the cache `group` holds, or -1 when this rank - * has no pool for it or the group does not hold that layer. It is the same lookup a RAD_KV operand - * makes (KVPoolBinding::layer_slot), and the index a streamed group's host mirror is laid out by: - * layer `i` of the group is at `stream->host + i * stream->host_layer_stride`. A group's bound - * layers need not be contiguous, so this is never `layer` itself. */ +/* The position of model layer `layer` among `group`'s bound layers, or -1 when this rank has no + * pool for it or the group does not hold the layer: the lookup a RAD_KV operand makes, and the + * index of the layer's host mirror row. Bound layers need not be contiguous. */ int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer); -/* Prefill staging (docs/KV-STREAMING.md §4.1). When the group's pass selected the one-layer stage - * view, copy this layer's whole host-mirror row into it, on the compute stream, after the layer's - * store and before its attention; returns 1 and the caller must not resolve. Returns 0 when the - * group has no stage view (a resident group, or the parity configuration's context-sized ring) and - * the caller proceeds normally. The ordering rule is in core/kvstream/stage.h. */ +/* Prefill staging of a streamed group (the ordering rule is in core/kvstream/stage.h). + * rad_kv_stage_layer, before the layer's store: when the pass uses the one-layer stage view, make + * the layer's mirror row whole in it (once a pass) and return 1, after which the caller reads + * block ids directly and must not resolve; 0 when the group has no stage view. + * rad_kv_stage_next, after every attention launch of the layer: start the next layer's copy. */ int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer); +int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer); int rad_rank(RadCtx* c); int rad_world_size(RadCtx* c); RadStream rad_stream(RadCtx* c); diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index aa20f665..3b8f19ac 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -608,18 +608,8 @@ constexpr int64_t kPrefetchRows = 16; * would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane * 0. */ inline bool prefetch_lane0() { return rad_chain_on() != 0; } -/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card - * the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two - * servers have queues, and the join puts a queue switch into every decode step. */ -inline bool prefetch_beside_on() { - static const bool on = [] { - const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE"); - return !(e && e[0] == '0' && e[1] == 0); - }(); - return on; -} inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) { - if (!op || T > kPrefetchRows || !prefetch_beside_on()) return; + if (!op || T > kPrefetchRows) return; if (prefetch_lane0()) { RAD_ISSUE(c, op, RAD_W(w)); return; @@ -627,7 +617,8 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) { if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w)); rad_lane(c, 0); } -/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */ +/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. A plugin declares + * none where the deployment turns the reads off (RadBuildCtx::weight_prefetch_off). */ inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) { if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0; return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w)); @@ -673,6 +664,9 @@ struct Geom { int64_t max_tok = 0; int64_t max_seqs = 0; int64_t max_ctx = 0; + /* --kv-resident in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams: what + * kv_resolve_declare states as the ring's depth. */ + int64_t kv_resident = 0; int max_spec = 0; /* Most rows the sampler can want in one step: one per sequence, or one per draft position per * sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather @@ -949,6 +943,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, g.max_tok = c->max_tok; g.max_seqs = c->max_seqs; g.max_ctx = c->max_ctx; + g.kv_resident = c->kv_resident_blocks; g.max_spec = c->max_spec; g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1); if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok; @@ -1069,6 +1064,95 @@ inline int64_t vocab_head_rows(const Geom& g) { * handle. */ inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); } +/* One layer of a streamed group (RadKVStream): its rows of the host mirror and the ring's maps. + * The mirror is layer-major over the group's bound layers in KVPoolBinding::layer_slot order, not + * over model layers (Flash-Next's full-attention layers are every other layer, plus the MTP head), + * so the row comes from rad_kv_layer_index. `host` is null when the group does not stream on this + * rank or has no row for the layer. */ +struct KVStreamLayer { + const RadKVStream* st = nullptr; + const uint8_t* host = nullptr; /* [blocks, bbytes] mirror row */ + int32_t* res = nullptr; /* [blocks] block -> ring slot, -1 when absent */ + int32_t* slot_block = nullptr; /* [slots] ring slot -> block */ + int32_t* slot_state = nullptr; /* [slots, 2] */ + int64_t blocks = 0, bbytes = 0, slots = 0; +}; +inline KVStreamLayer kv_stream_layer(RadCtx* c, rad_kvgroup group, int layer, + const RadKVGroupBatch* kvb) { + KVStreamLayer L; + const RadKVStream* st = kvb ? kvb->stream : nullptr; + if (!st || !st->host || st->block_bytes <= 0) return L; + const int64_t li = rad_kv_layer_index(c, group, layer); + if (li < 0) return L; + L.st = st; + L.bbytes = st->block_bytes; + L.blocks = st->host_layer_stride / L.bbytes; + L.slots = st->slots; + L.host = st->host + li * st->host_layer_stride; + L.res = st->res + li * L.blocks; + L.slot_block = st->slot_block + li * L.slots; + L.slot_state = st->slot_state + li * L.slots * 2; + return L; +} + +/* The prefill stage of a streamed group (the ordering rule is in core/kvstream/stage.h): + * + * kv_stage_wait -- immediately before the layer's store: the copy from the mirror must land + * before the store writes this chunk's newer bytes into the stage; + * kv_stage_layer -- before the attention: true when the pass uses the stage, so the caller + * reads block ids directly and must not resolve; + * kv_stage_next -- after every attention launch of the layer: the next layer's copy starts + * once the last read of the aliased stage is behind it. + * + * Both of the first two are rad_kv_stage_layer, which stages a layer once per pass. */ +inline bool kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) { + return rad_kv_stage_layer(c, group, kvb, layer) != 0; +} +inline bool kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) { + return rad_kv_stage_layer(c, group, kvb, layer) != 0; +} +inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) { + (void)rad_kv_stage_next(c, group, layer); +} + +/* The `kv_resolve` a streamed group's block declares. None of its geometry is free: + * + * blocks the block-id space a selection can name: max_seqs sequences of the context; + * slots the ring --kv-resident carves, in whole blocks, raised to one decode step's + * selection (max_seqs x (1 + n_spec) x sel_pitch) as kvstream_ring raises it, and + * at most `blocks`; the resolve is issued with the pool's depth, so declaring the + * context would size its scratch for slots it cannot reach; + * sel_pitch the selection row's pitch, which the attention declares its rows with + * (`qsa_topk + 1` on the sparse path, the indexer's count on GLM). + * + * The kernel sizes its claim list from these (`M * sel_pitch`, r4d_kv_resolve.hip's + * kv_claim_cap); ctl[12] reports the largest claim count a launch made, so a wrong declaration + * shows in the engine's stream report. `sel` is read as well as written, so the arena keeps it + * live from its producer to the attention. Returns 0 when the op is not declared or the group has + * nothing to address. */ +inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, rad_buf sel, + rad_buf nsel, int64_t sel_pitch) { + if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0; + const int64_t bs = rad_kv_block_size(b, kv); + const int64_t bbytes = rad_kv_layer_bytes(b, kv); + const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0; + if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0; + const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0; + const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch; + const int64_t want = ring > 0 && step > ring ? step : ring; + const int64_t slots = want > 0 && want < blocks ? want : blocks; + const rad_op op = RAD_OP(b, "kv_resolve", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", blocks), + RAD_INT("slots", slots), RAD_INT("sel_pitch", sel_pitch), + RAD_INT("block_bytes", bbytes)), + RAD_NOWEIGHTS); + if (!op) return 0; + const rad_buf rd[2] = { sel, nsel }; + rad_op_reads(b, op, rd, 2); + rad_op_writes(b, op, &sel, 1); + return op; +} + /* ================================================================== step-sized operands */ /* Every operand a step issues carries the step's row count, not the buffer's. * @@ -1134,6 +1218,16 @@ inline RadOperand praw(const void* p, uint32_t dtype, int64_t rows) { return o; } +/* kv_resolve over `rows` selection rows (kv_resolve_declare): makes the blocks they name resident + * in the ring and rewrites `sel` from block ids to ring slots. */ +inline void kv_resolve_issue(RadCtx* c, rad_op op, const KVStreamLayer& L, RadOperand sel, + RadOperand nsel, rad_kvgroup group, int layer, int64_t rows) { + RAD_ISSUE_N(c, op, rows, sel, nsel, praw(L.res, RAD_I32, L.blocks), + praw(L.slot_block, RAD_I32, L.slots), praw2(L.slot_state, RAD_I32, L.slots, 2), + praw(L.st->ctl, RAD_I32, 16), praw2(L.host, RAD_U8, L.blocks, L.bbytes), + kv_cache(group, layer)); +} + /* Rotary positions of a pass, in the two forms consumers take. * * `rope_pos1`: one component per token, RadBatch::rope_pos's plane 0 if present, else @@ -1317,6 +1411,28 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) { return nullptr; } +/* ================================================================== calibration in slices */ +/* The layers [lo, hi) of n a calibration taps: the environment variable `var` as "lo:hi", else + * all of them. A large model's Grams do not fit beside its weights at once, so it is calibrated + * in slices of layers, the corpus pushed through once a slice. */ +inline int calib_layers(const char* who, const char* var, int64_t n, int64_t* lo, int64_t* hi) { + *lo = 0; + *hi = n; + const char* s = std::getenv(var); + if (!s) return RAD_OK; + long long l = 0, h = 0; + int used = 0; + if (std::sscanf(s, "%lld:%lld%n", &l, &h, &used) != 2 || s[used] != '\0' || l < 0 || h > n || + l >= h) { + fprintf(stderr, "radiance: %s: %s '%s' is not lo:hi within 0:%lld\n", who, var, s, + (long long)n); + return RAD_E_INVAL; + } + *lo = l; + *hi = h; + return RAD_OK; +} + /* ================================================================== a block drafter */ /* A drafter's Geom: the target's (n_embd, vocabulary, deployment bounds, rank, wire) with the * layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h index bbc70474..ca9365d4 100644 --- a/arch/common/rad_block_attn_gated_fp8.h +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -21,21 +21,17 @@ #include "rad_fp8.h" -#include #include namespace rad { namespace arch { -/* RADIANCE_ATTN_BAND_SPLIT=0 issues a mixed step's dense attention as one launch at the step's - * widest band, as before the per-band issue in AttnGatedFP8::step; unset or anything else splits. - * An A/B and debugging knob, not configuration. Read once. */ -inline bool attn_band_split() { - static const bool on = [] { - const char* e = std::getenv("RADIANCE_ATTN_BAND_SPLIT"); - return !(e && !std::strcmp(e, "0")); - }(); - return on; +/* Whether the streamed store has a row for this cache layout: libr4d's are E4M3 and bf16 only. A + * packed cache (fp8_v4, k6_v4) must not declare it, since a weightless op with no row is a hole + * that refuses startup even with --kv-resident off; kvstream_configure then names the layout. */ +inline bool kv_store_streamed_dtype(const char* kv_dtype) { + return kv_dtype && (std::strcmp(kv_dtype, "fp8_e4m3") == 0 || + std::strcmp(kv_dtype, "bf16") == 0); } struct AttnGatedFP8 { @@ -81,6 +77,7 @@ struct AttnGatedFP8 { * block table and context length: same op, same kernel, different list. `sel` is `topk + 1` * wide and the kernel takes its block-table pitch from the operand. */ rad_buf qsa_sel = 0; + rad_buf qsa_nsel = 0; /* [max_tok] i32, the valid entries of each `qsa_sel` row */ rad_buf qsa_sequ = 0; /* Context length up to which dense attention gives the same result, `budget + ratio - 1`. * Below it every complete block is selected, the paths agree to the bit, and dense is cheaper @@ -122,10 +119,19 @@ struct AttnGatedFP8 { rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */ rad_op op_fused_kv = 0; /* the same with kv_store folded in */ + /* The same with the streamed store folded in, issued instead when the batch hands this group a + * stream (its mirror and map are the batch's). */ + rad_op op_fused_stream = 0; int64_t fused_rows = 0; /* widest T the fused ops take */ rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0; rad_op op_attn = 0, op_kv_store = 0, op_gq = 0; rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */ + /* kv_store_streamed: the host mirror always, the ring slot when `res` says the block is resident + * (docs/OPS.md). Zero when no row serves it; a streamed group then fails the step. */ + rad_op op_kv_stream = 0; + /* kv_resolve: this layer's selection made resident and rewritten as ring slots, issued before + * each sparse launch. */ + rad_op op_resolve = 0; /* The output gate as `sigmoid` then `mul`: the bf16-linear form (Geom::w_bf16), and with fp8 * linears the chain gate_quant_fp8 fuses, where it is not served. `gate` is the sigmoid's * output (the wire's with bf16 linears, the block's own otherwise) and `q_gate` the chain's @@ -155,6 +161,13 @@ struct AttnGatedFP8 { * by passes that only leave layer state behind, such as the MTP head's history pass over a * prompt chunk with no drafting row. */ void store_kv(RadCtx* c, const RadBatch* batch) const; + /* The layer's cache store, before its resolve and attention: `kv_store`, or for a streamed + * group the stage wait and `kv_store_streamed`. */ + void store_cache(RadCtx* c, const RadKVGroupBatch* kvb, const int32_t* slot, int64_t T) const; + /* A staged pass reads the pool at block-id identity, while the streamed store writes only + * where the residency map names a ring slot (none before the group's first decode). This + * stores the same bytes at identity, after the mirror writer. */ + void store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const; /* The block's tail, declared last by every rank: the all-reduce and the trailing add. */ int declare_out(RadBuilder* b, bool add_out); @@ -174,7 +187,8 @@ struct AttnGatedFP8 { * normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a * span of 1 makes, on the unfused prologue with one rotary component per token (every token's * components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and - * the gate quantised by gate_quant_fp8. */ + * the gate quantised by gate_quant_fp8. A streamed group never takes it: the pieces path's + * plain store never writes the host mirror. */ bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const { const int64_t T = batch->n_tok; const RadKVGroupBatch* kvb = kv_batch(batch, kv); @@ -182,7 +196,7 @@ struct AttnGatedFP8 { T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel && batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL && !(T <= fused_rows) && batch->positions && !rope_mixed(batch) && - kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused; + kvb && !kvb->stream && kvb->slot_mapping && kvb->block_table && kvb->seqused; } }; @@ -338,11 +352,18 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int * ids: an aperture violation outside the cache. rad_op_reads rather than rw() because the list * depends on whether the layer has an indexer. */ if (op_attn) { - const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ }; - rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1); + const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, qsa_nsel }; + rad_op_reads(b, op_attn, rd, + (qsa_sel && qsa_sequ) ? (qsa_nsel ? 4 : 3) : 1); rad_op_writes(b, op_attn, &w.attn.x, 1); } + /* The resolve belongs here rather than in the indexer: it must follow this layer's store, + * since a block copied in from the mirror has to carry this step's tokens. Its band is the + * step's widest launch and its row `qsa_topk + 1` wide, as the attention declares. */ + if (qsa_sel && qsa_nsel) + op_resolve = kv_resolve_declare(b, g, kv, qsa_sel, qsa_nsel, qsa_topk + 1); + op_kv_store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), RAD_INT("n_head_kv", g.n_head_kv), @@ -351,6 +372,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int RAD_NOWEIGHTS), {w.k, w.v}, {}); + /* The streamed store: kv_store's operands and parameters plus the residency map and the layer's + * mirror row, which the batch carries (store_cache). `block_size` does not bind the group; + * `attn_paged` already has. Only for a layout with a row (kv_store_streamed_dtype). */ + if (kv_store_streamed_dtype(g.kv_dtype) && rad_op_declared(b, "kv_store_streamed")) + op_kv_stream = rw(b, RAD_OP(b, "kv_store_streamed", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), + RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + /* The fused prologue with the cache store folded in: a k head's block already holds its * token's rotated k, so it also writes k and v into the cache, byte-identical to kv_store. * Declared here because the cache block size is read back from the attention op above. @@ -367,6 +401,21 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int RAD_WEIGHTS(w_q_norm, w_k_norm)), {w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k}); + /* The fold for a streamed group: also writes the mirror and consults the residency map, whose + * operands are added at issue. Gated on the same layouts. */ + if (op_fused && kv_store_streamed_dtype(g.kv_dtype) && + rad_op_declared(b, "qk_norm_rope_gate_kv_store_streamed")) + op_fused_stream = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store_streamed", + RAD_PARAMS(RAD_RANGE("M", 1, fused_rows), + RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot), + RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps), + RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_q_norm, w_k_norm)), + {w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k}); + /* Output gate, multiply and quantiser in one pass (`gate_quant_fp8`); at decode the dispatch * gaps between three small ops are comparable to the work. Each row is a (token, head) pair: * the gate is a fixed stride inside [q|gate], the attention output is contiguous, and the @@ -481,6 +530,34 @@ inline int AttnGatedFP8::declare_out(RadBuilder* b, bool add_out) { return RAD_OK; } +inline void AttnGatedFP8::store_stage_identity(RadCtx* c, const int32_t* slot, int64_t T) const { + RAD_ISSUE_N(c, op_kv_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), + kv_cache(kv, layer)); +} + +inline void AttnGatedFP8::store_cache(RadCtx* c, const RadKVGroupBatch* kvb, + const int32_t* slot, int64_t T) const { + if (!kvb || !kvb->stream) { + RAD_ISSUE(c, op_kv_store, + brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + return; + } + /* A streamed group writes its host mirror, and the ring slot only where the block is resident + * (docs/OPS.md "kv_store_streamed"). kv_store alone would treat a block id as a ring slot, so + * a build without the streamed store fails the step. */ + const bool staged = kv_stage_wait(c, kv, kvb, layer); + const KVStreamLayer L = kv_stream_layer(c, kv, layer, kvb); + if (!op_kv_stream || !L.host || L.blocks <= 0) { + rad_step_fail(c, "kv streaming: this layer's KV group streams but the build has no " + "kv_store_streamed row to write its host mirror with"); + return; + } + RAD_ISSUE(c, op_kv_stream, + brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer), + praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes)); + if (staged) store_stage_identity(c, slot, T); +} + inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const { const int64_t T = batch->n_tok; if (!ext_in) nq_h.step(c, T); @@ -491,8 +568,7 @@ inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const { vp.step(c, w.h, w.v, T); RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T)); RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T)); - RAD_ISSUE(c, op_kv_store, - brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + store_cache(c, kvb, slot, T); } inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, @@ -567,8 +643,24 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, * token, so a pass with media tokens (differing components) takes the unfused path with the * full [3, T] positions. */ const bool fuse_ok = T <= fused_rows && !rope_mixed(batch); - const bool fused_kv = op_fused_kv && fuse_ok; - if (fused_kv) { + /* A streamed group folds the streamed store into the prologue instead (op_fused_stream); one + * whose layer has no mirror row leaves the store to store_cache, which fails the step. */ + const bool streamed = kvb && kvb->stream; + const bool fused_kv = op_fused_kv && fuse_ok && !streamed; + const KVStreamLayer L = streamed && op_fused_stream && fuse_ok + ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{}; + const bool folded_stream = L.host && L.blocks > 0; + if (folded_stream) { + /* The prologue is the store, so the stage copy must land before it (kv_stage_wait). */ + const bool staged = kv_stage_wait(c, kv, kvb, layer); + RAD_ISSUE_N(c, op_fused_stream, T, + brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T), + RAD_W(w_q_norm), RAD_W(w_k_norm), + brows(w.q, T), brows(w.k, T), RAD_NONE, + brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer), + praw(L.res, RAD_I32, L.blocks), praw2(L.host, RAD_U8, L.blocks, L.bbytes)); + if (staged) store_stage_identity(c, slot, T); + } else if (fused_kv) { RAD_ISSUE_N(c, op_fused_kv, T, brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm), @@ -588,9 +680,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T)); } - if (!fused_kv) - RAD_ISSUE(c, op_kv_store, - brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + if (!fused_kv && !folded_stream) store_cache(c, kvb, slot, T); /* Sparse attention issues one row per query. `attn_paged` indexes its block table and length * by row, and a row need not be a sequence, so T queries issued as T rows of q_len 1, each with @@ -604,9 +694,31 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, * `q_len` (rows = max_seqs * q_len_max * heads); more rows are refused as RAD_E_SCRATCH at * issue. Rows of q_len 1 up to the declared max_seqs always fit. */ const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len; + /* A pass on a streamed group's ring (a ring smaller than the id space, and not staged) must + * take the sparse path: on the ring a block id is not a pool address, so the dense path would + * read ring slots as pages. `T == n_seq` alone misses a verify pass, whose T is + * n_seq x (1 + n_spec), on a context under qsa_exact_to. A ring that covers the context keeps + * the dense path, where ids and slots coincide. */ + const RadKVStream* st = kvb ? kvb->stream : nullptr; + const int64_t st_blocks = + (st && st->block_bytes > 0) ? st->host_layer_stride / st->block_bytes : 0; + const bool ring_addressed = st && st->slots > 0 && st_blocks > 0 && st->slots < st_blocks; + const bool ring_bound = ring_addressed && !kv_stage_layer(c, kv, kvb, layer); const bool sparse = qsa_sel && qsa_sequ && - (T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to); + (ring_bound || T == batch->n_seq || qsa_exact_to <= 0 || + reach > qsa_exact_to); const bool gated = sparse && op_attn_gq; + /* A streamed group's selection, per launch: make the rows' blocks resident and rewrite `sel` + * as ring slots, after this layer's store (a block copied in from the mirror must carry this + * step's tokens) and before the attention. A pass on the stage view leaves `sel` as block ids + * and never resolves, so a prefill cannot overflow the ring. */ + const KVStreamLayer res_l = op_resolve ? kv_stream_layer(c, kv, layer, kvb) : KVStreamLayer{}; + auto resolve_sel = [&](int64_t off, int64_t rows) { + if (kv_stage_layer(c, kv, kvb, layer)) return; + if (!res_l.host || res_l.blocks <= 0 || res_l.slots <= 0 || rows <= 0) return; + kv_resolve_issue(c, op_resolve, res_l, brow_slice(qsa_sel, off, rows, qsa_topk + 1), + brow_slice(qsa_nsel, off, rows, 1), kv, layer, rows); + }; /* A piece at a time where the caller takes the all-reduce that way (ArPieces). On the gated * sparse path every query row is its own (q_len 1) and the gate rides in the merge, so the * attention and out projection can finish a piece's rows and hand off its reduction while the @@ -619,6 +731,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, const int64_t pn = T - p0 < pieces->rows ? T - p0 : pieces->rows; for (int64_t off = p0; off < p0 + pn; off += chunk) { const int64_t rows = (p0 + pn - off) < chunk ? (p0 + pn - off) : chunk; + resolve_sel(off, rows); RAD_ISSUE_N(c, op_attn_gq, 1, brow_slice(w.q, off, rows, qw), kv_cache(kv, layer), @@ -633,6 +746,8 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, o.step(c, w.attn, w.h.x, T, p0, pn); if (p0 + pn < T) pieces->hand(p0, pn); } + /* Every attention launch of this layer is issued: start the next layer's stage copy. */ + if (kvb && kvb->stream) kv_stage_next(c, kv, layer); return; } if (gated) { @@ -640,6 +755,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, const int64_t qw = g.q_dim(), hd = g.head_dim; for (int64_t off = 0; off < T; off += chunk) { const int64_t rows = (T - off) < chunk ? (T - off) : chunk; + resolve_sel(off, rows); RAD_ISSUE_N(c, op_attn_gq, 1, brow_slice(w.q, off, rows, qw), kv_cache(kv, layer), @@ -656,6 +772,7 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, const int64_t qw = g.q_dim(); for (int64_t off = 0; off < T; off += chunk) { const int64_t rows = (T - off) < chunk ? (T - off) : chunk; + resolve_sel(off, rows); RAD_ISSUE_N(c, op_attn, 1, brow_slice(w.q, off, rows, qw), kv_cache(kv, layer), @@ -665,34 +782,35 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, brow_slice(w.attn.x, off, rows, qw)); } } else { - /* A mixed step once per band, as the GDN blocks issue theirs (rad_block_gdn_fp8.h): one - * launch at the chunk's band would serve the decode rows by the query-tiled prefill kernel, - * one workgroup a kv head walking each decode sequence's whole context, the step's tail - * beside a chunk of thousands of rows (one sequence decoding at 188k beside a 25k prompt's - * 2048-row chunks: 512 ms a mixed step against 218 ms at 0.7k of context, the prompt's - * prefill 5.1 -> 11.3 s). The decode half, sequences [0, D) and rows [0, DT), is the prefix: - * its own band (the split-KV decode row) over its rows, tables and cu. The prefill half - * takes its per-sequence arrays past the decode sequences and keeps q, out and cu at their - * absolute rows (the kernels index q and out by cu, and the merge of a split launch keeps - * to cu's span). + /* Below qsa_exact_to the dense path reads block ids straight from the table and never + * resolves, so a staged pass stages this layer here (a no-op without a stage view). A + * ring-bound pass with no selection to resolve cannot be served at all. */ + if (ring_bound) { + rad_step_fail(c, "kv streaming: a pass on the streamed group's ring has no selection " + "to resolve, so its block ids are not pool addresses"); + } else if (kvb && kvb->stream) { + (void)kv_stage_layer(c, kv, kvb, layer); + } + /* A mixed step issues its attention once per band, as the GDN blocks do: one launch at + * the chunk's band would walk every decode sequence's whole context with one query-tiled + * workgroup a KV head, the step's tail beside a long chunk. The decode half (sequences + * [0, D), rows [0, DT)) is a prefix at its own band. The prefill half takes its + * per-sequence arrays past the decode sequences and keeps q, out and cu at their absolute + * rows, as the kernels index q and out by cu. * - * The prefill half is issued at the op's top band (max_tok), not at its own query length: - * a launch over part of the step (q and out whole, cu past row 0, as ArPieces issues its - * pieces) is served by the query-tiled row, while the band of a short chunk (10 rows or - * fewer at gqa 6) is the split-KV decode row's, whose partials are laid out by the step's - * rows and sized at declare for its own band: 1.10-next6u issued it there and stopped - * under load on RAD_E_SCRATCH. Kernels read exact lengths from cu, so the loose band costs - * nothing. A chunk no longer than the verify blocks beside it keeps the one launch at - * their band, as before the split: the whole step is decode-shaped then. - * - * Pure steps issue one launch, as before. */ + * The prefill half is issued at the op's top band, not at its own query length: a launch + * over part of the step must be served by the query-tiled row, while a short chunk's band + * (10 rows or fewer at gqa 6) is the split-KV decode row's, whose partials are sized at + * declare for that band and would overflow the scratch. Kernels read exact lengths from + * cu, so the loose band costs nothing. A chunk no longer than the verify blocks beside it + * keeps one launch at their band: the whole step is decode-shaped then. */ int64_t D = 0, DT = 0; batch_split(batch, &D, &DT); const int64_t pitch = kvb ? kvb->block_table_pitch : 0; const int32_t qp = batch->max_q_len_prefill > 0 ? batch->max_q_len_prefill : batch->max_q_len; if (batch->phase == RAD_PHASE_MIXED && D > 0 && D < batch->n_seq && - batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode && attn_band_split()) { + batch->max_q_len_decode > 0 && qp > batch->max_q_len_decode) { const int64_t P = batch->n_seq - D; RAD_ISSUE_N(c, op_attn, batch->max_q_len_decode, brows(w.q, DT), kv_cache(kv, layer), @@ -711,13 +829,15 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, praw2(table, RAD_I32, batch->n_seq, pitch), praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, - /* cu_seqlens: the batch may be ragged (verify rows of different - * lengths; a chunk beside decode rows at RADIANCE_ATTN_BAND_SPLIT=0). */ + /* cu_seqlens: verify rows may be of different lengths. */ praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn.x, T)); } } + /* Every attention launch of this layer is issued: start the next layer's stage copy, which + * crosses the link under the out projection and the next layer's projections. */ + if (kvb && kvb->stream) kv_stage_next(c, kv, layer); if (gated) { /* the sparse attention gated and quantised in its merge */ } else if (op_sig) { diff --git a/arch/common/rad_block_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h index 78e08c58..8b8b4724 100644 --- a/arch/common/rad_block_gdn_fp8.h +++ b/arch/common/rad_block_gdn_fp8.h @@ -109,6 +109,11 @@ struct GdnFP8 { rad_weight w_norm = 0, w_ab = 0, w_conv = 0; /* The input was normed and quantised by the caller; this block declares no norm. */ bool ext_in = false; + /* Set by the architecture before declare: the a|b projection runs on the second lane beside the + * in-projection at decode and verify sizes. Not where lane 1 carries collectives, which the + * projection would queue behind. Its concurrent buffers cost memory (at Qwen3.8-27B TP2: +70 + * MiB arena and +33 MiB queues a card) for about +1 % at one stream. */ + bool ab_lane = false; rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0; LinearFP8 in{}, out{}; NormQuantFP8 nq_h{}; @@ -271,6 +276,10 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim), RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab}); + if (ab_lane) { + RAD_ARCH_TRY(rad_buf_concurrent(b, w.h.x)); + RAD_ARCH_TRY(rad_buf_concurrent(b, w.ab)); + } /* ---- the chunked path. As in the bf16 block, except `a` and `b_gate` are views of `ab`. */ op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep", @@ -436,8 +445,19 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, } if (!ext_in) nq_h.step(c, T); - in.step(c, w.h, w.in.x, T); - RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T)); + /* At decode and verify sizes the a|b projection is nearly all launch cost and reads only the + * norm's output, as the in-projection does, so it runs beside it on lane 1 and is joined before + * the convolution reads `ab`. A prefill chunk keeps one lane, where the two would share + * bandwidth. */ + if (ab_lane && T <= 64 && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) { + RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T)); + rad_lane(c, 0); + in.step(c, w.h, w.in.x, T); + rad_lane_join(c, 1, 0); + } else { + in.step(c, w.h, w.in.x, T); + RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T)); + } /* Each path runs over its own run of sequences. The step is sorted decode-first: decode rows * are sequences [0, D) with tokens [0, DT), prefill chunks are [D, S) with the rest. A pure diff --git a/arch/common/rad_block_glm_indexer.h b/arch/common/rad_block_glm_indexer.h index de68ff66..c69b93ea 100644 --- a/arch/common/rad_block_glm_indexer.h +++ b/arch/common/rad_block_glm_indexer.h @@ -90,6 +90,9 @@ struct DsaCache { d.n_head_kv = 1; d.head_dim = 17; *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); + /* dsa_score reads this group over the whole history every step, so it stays resident and + * holds every sequence's context while a sibling streams (kvstream/carve.cpp). */ + RAD_ARCH_TRY(rad_kv_group_dense_read(b, *index_group)); } index = *index_group; if (!index) return RAD_E_INVAL; diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index ac209466..e033c687 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -29,6 +29,9 @@ struct MlaLatent { }; struct Wire { rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; + /* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`. + * Never `length`, which is a token count. */ + rad_buf nsel = 0; }; Geom g{}; Config c{}; @@ -128,7 +131,7 @@ struct GlmMla { QuantFP8 attn_quant{}; MlaLatent core{}; rad_weight q_gain = 0, kv_gain = 0; - rad_op op_kv_norm = 0, op_store = 0, op_ar = 0; + rad_op op_kv_norm = 0, op_store = 0, op_store_stream = 0, op_resolve = 0, op_ar = 0; LinearFP8 rows_q_b{}, rows_output{}; QuantFP8 rows_quant{}; rad_weight rows_kv_b = 0; @@ -189,6 +192,20 @@ struct GlmMla { RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096, GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); + /* The streamed store: kv_store's operands plus the residency map and the layer's mirror row, + * added at issue (prepare). */ + if (rad_op_declared(b, "kv_store_streamed") && rad_kv_block_size(b, kv) == 4) + op_store_stream = rw(b, + RAD_OP(b, "kv_store_streamed", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), + RAD_INT("head_dim", 256), RAD_INT("n_head_kv", 1), + RAD_INT("block_size", 4), + RAD_STR("kv_dtype", "bf16")), + RAD_NOWEIGHTS), + { w.latent }, {}); + /* Issued in finish, after this layer's indexer selects and before the attention reads + * `selected`. `sel_pitch` is the row pitch MlaLatent declares its attention with. */ + op_resolve = kv_resolve_declare(b, g, kv, w.core.selected, w.core.nsel, core.c.blocks); if (reduce) op_ar = GlmTp::reduce(b, g, w.out); if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL; return reduce ? declare_rows(b, nm, prefix) : RAD_OK; @@ -265,20 +282,59 @@ struct GlmMla { kv_a.step(ctx, w.input, w.kv_raw, T); q_norm.step(ctx, T); RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T)); + /* The row form splits the query projection into finish_rows (per rank), so q_b runs here + * only in the head form; the latent store below is full length either way. */ if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T); - RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), - praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); + if (!kb->stream) { + RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), + praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); + return; + } + /* A streamed group writes its host mirror, and the ring slot only where the block is + * resident; the stage wait goes immediately before the store (core/kvstream/stage.h). A + * staged pass also stores at block-id identity, which is how the stage view is read. */ + const bool staged = kv_stage_wait(ctx, kv, kb, layer); + const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb); + if (!op_store_stream || !L.host || L.blocks <= 0) { + rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no " + "kv_store_streamed row to write its host mirror with"); + return; + } + RAD_ISSUE_N(ctx, op_store_stream, T, bcol(w.latent, 0, 256, T), + bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T), + kv_cache(kv, layer), praw(L.res, RAD_I32, L.blocks), + praw2(L.host, RAD_U8, L.blocks, L.bbytes)); + if (staged) + RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), + praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); } void finish(RadCtx* ctx, const RadBatch* batch) const { const int64_t T = batch->n_tok; + const auto* kb = kv_batch(batch, kv); + /* A streamed group's selection is resolved here, after this layer's indexer wrote fresh + * block ids into the one `selected` buffer every layer shares and before either form of + * the attention reads it. A pass on the stage view reads block ids and never resolves. */ + if (kb && kb->stream && !kv_stage_layer(ctx, kv, kb, layer) && T > 0) { + const KVStreamLayer L = kv_stream_layer(ctx, kv, layer, kb); + if (!op_resolve || !w.core.nsel || !L.host || L.blocks <= 0 || L.slots <= 0) { + rad_step_fail(ctx, "GLM MLA: this layer's KV group streams but the build has no " + "kv_resolve for its selection"); + return; + } + /* The count is qsa_select's entry count, never `length` (a token count). */ + kv_resolve_issue(ctx, op_resolve, L, brow_slice(w.core.selected, 0, T, core.c.blocks), + brow_slice(w.core.nsel, 0, T, 1), kv, layer, T); + } if (rows_take(T)) { finish_rows(ctx, T); - return; + } else { + core.step(ctx, T); + attn_quant.step(ctx, T); + output.step(ctx, w.attn, w.out, T); + if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); } - core.step(ctx, T); - attn_quant.step(ctx, T); - output.step(ctx, w.attn, w.out, T); - if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); + /* After every attention launch of this layer (core/kvstream/stage.h). */ + if (kb && kb->stream) kv_stage_next(ctx, kv, layer); } /* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the * gather sends its unwritten tail rows, which land past T. */ diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index b6d056e5..9433bba2 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -119,11 +119,10 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, swiglu_limit)); - /* The fold: decl_gated_fold, an fp8a8 tile, for block-fp8 weights; decl_gated_fold_mx for a - * plain MXFP4 one at one to eight rows. bf16, f32-scaled, rotated MXFP4, rotated 5-bit, 4-bit - * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product, which - * neither fold computes. Declared over int8 codes, only a host kernel would take it, and that - * would pin the layer's weights to the host. An M2XFP4 gate_up takes the pair too. */ + /* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain + * MXFP4 at one to eight rows. Other gate_up encodings (M2XFP4 included), and a clamped + * (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would take it, which + * would pin the layer's weights to the host. */ const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale; if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index 446504fa..3986fb24 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -106,11 +106,9 @@ struct PleLayer { rad_op op_gate = 0, op_conv = 0, op_add = 0; int64_t hn() const { return c.hc * g.n_embd; } - /* The read-ahead queue's depth, in steps: the scheduler stages this many steps of the - * following prompt per step (batch.cpp, k_ahead_chunks) and the gather hands them to the - * reader thread, which prefetches their rows off the step path while the current chunk runs. - * Clamped to what `b_ids` was declared to hold, so a scheduler that offers more degrades the - * queue's depth, never an overflow. */ + /* The read-ahead queue's depth in steps: batch.cpp's k_ahead_chunks steps of the following + * prompt, whose rows the gather's reader thread prefetches. Clamped to what `b_ids` holds, so + * a larger offer only shortens the queue. */ static constexpr int64_t kAheadChunks = 8; /* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */ int64_t ahead_rows(const RadBatch* batch) const { @@ -283,9 +281,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C * follows declared order, where the two ops are adjacent, so a transient could be overwritten * in between. */ { - /* The step's rows, then the read-ahead queue's: up to kAheadChunks further steps of the - * following prompt (RadBatch::n_ahead), which the gather's reader prefetches while the - * step runs, so a prefill's table rows are read at disk speed off the step path. */ + /* The step's rows, then kAheadChunks further steps of the following prompt + * (RadBatch::n_ahead) for the reader to prefetch. */ RadBufDecl d{}; d.dtype = RAD_I32; d.rank = 2; d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads; diff --git a/arch/common/rad_block_vit.h b/arch/common/rad_block_vit.h index 9d0186e2..32eb3ed5 100644 --- a/arch/common/rad_block_vit.h +++ b/arch/common/rad_block_vit.h @@ -78,16 +78,33 @@ struct VisionTower { return rad_meta_geti(m, "vision_config.depth", 0) > 0; } + /* With `gate_weights`, a checkpoint or container without the tower's weights declares nothing + * and leaves `on` false, for a model whose config names a tower its weights may not have. */ int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, - int64_t model_embd, int first_group, bool deepstack = false); + int64_t model_embd, int first_group, bool deepstack = false, + bool gate_weights = false); void step(RadCtx* c, const RadBatch* batch) const; }; inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, - Names& nm, int64_t model_embd, int first_group, bool deepstack) { + Names& nm, int64_t model_embd, int first_group, bool deepstack, + bool gate_weights) { on = false; if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + /* Whether the stem is there: its map first, then its encoding, which convert answers from the + * checkpoint and load from the container alike. A map left behind is inert. */ + if (gate_weights) { + if (map_copy(b, nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight")) < 0) + return RAD_E_INVAL; + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) { + std::fprintf(stderr, "radiance: vision_config names a tower the checkpoint does not " + "ship; declaring without it\n"); + return RAD_OK; + } + } + depth = rad_meta_geti(m, "vision_config.depth", 0); width = rad_meta_geti(m, "vision_config.hidden_size", 0); heads = rad_meta_geti(m, "vision_config.num_heads", 0); @@ -173,8 +190,12 @@ inline int VisionTower::declare(RadBuilder* b, const RadModelMeta* m, const RadB if (map_copy(b, dn, src) < 0) return 0; return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g); }; - w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"), - RAD_BF16, { width, patch_dim }, grp_model()); + /* Mapped above with `gate_weights`. */ + w_patch = gate_weights + ? decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, + RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_model()) + : bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"), + RAD_BF16, { width, patch_dim }, grp_model()); b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"), RAD_BF16, { width }, grp_model()); w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"), diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index fd597c12..6b47f3ce 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -77,25 +77,29 @@ struct ActFP8 { rad_buf cq() const { return q8_fed ? q8 : q; } rad_buf cs() const { return q8_fed ? s8 : s; } - /* Declares the codes (and the int8 pair with `i8`); `x` is set by the caller. + /* Declares the codes: the E4M3 pair with `fp8_pair`, the int8 pair with `i8` (an int8 model's + * activations need no E4M3 plane taking arena); `x` is set by the caller. * * `rows` defaults to g.max_tok and must be given for any buffer that is not one row per token * (a MoE expert plane is `rows * top_k`, an encoder tower's its patch count); too small a value * overruns the arena (core/runtime/issue.cpp refuses such an issue). */ int declare_qs(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t n, - int64_t rows = 0, bool i8 = false) { + int64_t rows = 0, bool i8 = false, bool fp8_pair = true) { /* bf16 linears read only `x` (Geom::w_bf16), so declare no codes; an unused plane would * still take arena space. */ if (g.w_bf16) { q = s = q8 = s8 = 0; return RAD_OK; } const int64_t m = rows > 0 ? rows : g.max_tok; - q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n }); - s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) }); + if (fp8_pair) { + q = decl_b(b, nm.f("%s.q", name), RAD_F8E4M3, { m, n }); + s = decl_b(b, nm.f("%s.s", name), RAD_F32, { m, fp8_blocks(n) }); + if (!q || !s) return RAD_E_INVAL; + } if (i8) { q8 = decl_b(b, nm.f("%s.q8", name), RAD_I8, { m, n }); s8 = decl_b(b, nm.f("%s.s8", name), RAD_F32, { m, fp8_blocks(n) }); if (!q8 || !s8) return RAD_E_INVAL; } - return (q && s) ? RAD_OK : RAD_E_INVAL; + return (fp8_pair || i8) ? RAD_OK : RAD_E_INVAL; } }; @@ -525,6 +529,10 @@ struct GateQuantFP8 { * codes (`op_q`). */ rad_op op_q = 0; + /* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that + * quantises its input itself (an int8 linear's op_q). */ + bool silu_only = false; + int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n, const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true, bool rot = false, double limit = 0); @@ -541,15 +549,16 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, want_x = bf16_out; op_quant = 0; this->n = n; - /* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no - * rotation. */ - bf16 = g.w_bf16; + /* bf16 linears and `silu_only` read the product itself: `silu_mul` into the bf16 plane only, + * and no rotation. */ + bf16 = g.w_bf16 || silu_only; clipped = limit > 0; clamped_fused = false; if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL; if (clipped) { - /* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. */ - if (!gate_up || !a.x || n <= 0 || rot || (a.q8_fed && a.q8_rot) || + /* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp + * with `silu_only`. */ + if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) || std::strcmp(act_name, "silu")) return RAD_E_INVAL; const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; @@ -725,10 +734,8 @@ struct LinearFP8 { * view whose layout hook reduces it). Read from the weight's encoding. */ bool mx = false; rad_weight wref = 0; - /* The M2XFP4 sibling (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group, - * read by `gemm_nt_q` at dtype m2xfp4 with the same E4M3 pair, `b_scale` and `b_ref` as MXFP4's - * are, the meta plane riding the weight operand's stored blob. Read from the weight's - * encoding. */ + /* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand, + * read by `gemm_nt_q` at dtype m2xfp4. */ bool m2x = false; /* Rotated (ParoQuant) variant of `mx`: the same GEMM over an activation that * `givens_dense_quant` makes from the bf16 plane (channel scale, dense per-group rotation and @@ -898,10 +905,9 @@ inline bool linear_is_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } -/* The M2XFP4 sibling (arXiv 2601.19213, the paper's weight-side Sg-EM): the MXFP4 weight plus one - * metadata byte per group of 32, four 2-bit subgroup extra mantissas that refine the exponent to - * (1 + k/4) . 2^E (libquant's `m2xfp4` quantiser; libr4d's m2xfp4 layout hook). The exponent byte - * carries the adaptive bias; the GEMM applies nothing beyond the planes. */ +/* M2XFP4 (arXiv 2601.19213, weight-side Sg-EM): the MXFP4 weight plus one metadata byte per group + * of 32, four 2-bit subgroup extra mantissas that refine the scale to (1 + k/4) . 2^E. The + * exponent byte carries the adaptive bias; the GEMM applies nothing beyond the planes. */ inline bool linear_is_m2xfp4(const RadEncoding& e) { if (!rad_enc_is(&e, "m2xfp4") || e.n_planes != 3 || e.transform[0]) return false; const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *mt = rad_enc_plane(&e, "meta"); @@ -1165,10 +1171,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha rot8 ? "unrotated" : "rotated"); return RAD_E_DTYPE; } - if (!a.x || !a.q8 || !a.s8) { - fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the bf16 plane " - "or the int8 code pair (the model declared its input before learning " - "the trunk is int8)\n", wn); + /* The bf16 plane only when this linear quantises it itself. */ + if (!a.q8 || !a.s8 || (!a.q8_fed && !a.x)) { + fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the int8 code " + "pair%s (the model declared its input before learning the trunk is " + "int8)\n", wn, a.q8_fed ? "" : " or the bf16 plane it quantises"); return RAD_E_DTYPE; } if (N % 16 || K % RAD_FP8_BLOCK) { @@ -1358,12 +1365,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha return RAD_E_DTYPE; } - /* ---- OCP-MXFP4 weight over the E4M3 pair. Three views: codes, exponents as `b_scale`, and - * the same plane as `b_ref`. Row parts apply as is (the exponent grid is one row tall); column - * slices must be whole 128s, the activation's scale block. */ - paro = known && linear_is_paro_mxfp4(enc); - mx = known && (linear_is_mxfp4(enc) || paro); - if (mx) { + /* ---- OCP-MXFP4 or M2XFP4 weight over an E4M3 pair, the producer's or, for a rotated + * (ParoQuant) weight, its own. Three views: codes (M2XFP4's with its meta plane, which rides + * the weight operand), exponents as `b_scale`, and the same plane as `b_ref`. Row parts apply + * as is (the exponent grid is one row tall); column slices must be whole 128s, the + * activation's scale block. */ + const bool paro_mx = known && linear_is_paro_mxfp4(enc); + const bool paro_m2 = known && linear_is_paro_m2xfp4(enc); + paro = paro_mx || paro_m2; + mx = known && (linear_is_mxfp4(enc) || paro_mx); + m2x = known && (linear_is_m2xfp4(enc) || paro_m2); + if (mx || m2x) { + const char* fmt = m2x ? "M2XFP4" : "MXFP4"; if (stored) { fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " "may\n", wn, stored); @@ -1373,29 +1386,29 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* The rotation is applied to the activation, so this linear needs the input's bf16 * plane (probe() set reads_x) and quantises it itself. */ if (!a.x) { - fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight, rotated and quantised " - "from its input's bf16 plane, and its input has none\n", wn); + fprintf(stderr, "radiance: '%s' is a rotated %s weight, rotated and quantised " + "from its input's bf16 plane, and its input has none\n", wn, fmt); return RAD_E_DTYPE; } if (g.world > 1 || span_hi > 0) { - fprintf(stderr, "radiance: '%s' is a rotated MXFP4 weight; its rotation is per " + fprintf(stderr, "radiance: '%s' is a rotated %s weight; its rotation is per " "projection and is not cut by a tensor-parallel shard (world %d)\n", - wn, g.world); + wn, fmt, g.world); return RAD_E_UNSUPPORTED; } } else if (!a.q || !a.s) { - fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 " - "pair, and its input has none\n", wn); + fprintf(stderr, "radiance: '%s' is an %s weight read against its input's E4M3 " + "pair, and its input has none\n", wn, fmt); return RAD_E_DTYPE; } if (N % 16 || K % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in " + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows in " "16s and K in whole %d-column activation scale blocks\n", - base, (long long)N, (long long)K, RAD_FP8_BLOCK); + base, (long long)N, (long long)K, fmt, RAD_FP8_BLOCK); return RAD_E_INVAL; } RowParts rp; - RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles")); + RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles")); int64_t pb1 = 0, pb2 = 0; if (paro) { std::vector cut; @@ -1413,8 +1426,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } const char* sn = nm.f("%s.scale", base); const char* rn = nm.f("%s.ref", base); - w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, - shard, grp, rp.w, rp.n); + w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K }, + access, shard, grp, rp.w, rp.n); ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, access, shard, grp, rp.w, rp.n); wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, @@ -1435,100 +1448,12 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi)); } /* One GEMM: a rotated weight reads its own rotated pair, a plain one the producer's. */ - op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "mxfp4a8", pb1, pb2, + op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, + m2x ? "m2xfp4" : "mxfp4a8", pb1, pb2, { w, ws, wref }, { paro ? rot_q : a.q, paro ? rot_s : a.s }, y); return op ? RAD_OK : RAD_E_INVAL; } - /* ---- M2XFP4 weight over the E4M3 pair: the MXFP4 weight's views plus the metadata plane, - * which rides the weight operand -- the declared view takes codes and meta together, and the - * stored blob carries the meta in its tail (libr4d's m2xfp4 layout). The exponent plane is - * `b_scale` and `b_ref` as MXFP4's is; the row parts, the shape bounds and the column-shard - * rule are the MXFP4 ones. - * - * A rotated weight (ParoQuant) carries the same planes in the basis its "givens" tables name - * and is declared like the rotated MXFP4 one: `givens_dense_quant` makes the E4M3 pair from - * the input's bf16 plane, once per rotated part, and the GEMM meets copy p with part p's rows - * (`pb1`/`pb2`). `paro` makes step() issue that rotation first. */ - const bool m2rot = known && linear_is_paro_m2xfp4(enc); - m2x = known && (linear_is_m2xfp4(enc) || m2rot); - if (m2x) { - paro = m2rot; - if (stored) { - fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " - "may\n", wn, stored); - return RAD_E_INVAL; - } - if (m2rot) { - if (!a.x) { - fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight, rotated and quantised " - "from its input's bf16 plane, and its input has none\n", wn); - return RAD_E_DTYPE; - } - if (g.world > 1 || span_hi > 0) { - fprintf(stderr, "radiance: '%s' is a rotated M2XFP4 weight; its rotation is per " - "projection and is not cut by a tensor-parallel shard (world %d)\n", - wn, g.world); - return RAD_E_UNSUPPORTED; - } - } else if (!a.q || !a.s) { - fprintf(stderr, "radiance: '%s' is an M2XFP4 weight read against its input's E4M3 " - "pair, and its input has none\n", wn); - return RAD_E_DTYPE; - } - if (N % 16 || K % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows in " - "16s and K in whole %d-column activation scale blocks\n", - base, (long long)N, (long long)K, RAD_FP8_BLOCK); - return RAD_E_INVAL; - } - RowParts rp; - RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles")); - int64_t pb1 = 0, pb2 = 0; - if (m2rot) { - std::vector cut; - for (int64_t p : rot_part_rows) cut.push_back(p); - if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p); - RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); - const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; - rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K }); - rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, - { rows, rot_parts * (K / RAD_FP8_BLOCK) }); - if (!rot_q || !rot_s) return RAD_E_INVAL; - rot_dense = decl_dense(b, nm, base, wn, enc, K, grp); - if (!rot_dense) return RAD_E_INVAL; - op_rot = decl_dense_op(b, g, a, "fp8", 1, rows, { rot_q, rot_s }); - if (!op_rot) return RAD_E_INVAL; - } - const char* sn = nm.f("%s.scale", base); - const char* rn = nm.f("%s.ref", base); - w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp, - rp.w, rp.n); - ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, - access, shard, grp, rp.w, rp.n); - wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, - access, shard, grp, rp.w, rp.n); - if (!w || !ws || !wref) return RAD_E_INVAL; - if (span_hi > 0) { - const bool col = shard == RAD_SHARD_COL; - if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) { - fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a " - "%d-column activation scale block\n", base, (long long)span_lo, - (long long)span_hi, RAD_FP8_BLOCK); - return RAD_E_INVAL; - } - const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo; - const int64_t hi = col ? span_hi / RAD_MX_GROUP : span_hi; - RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); - RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi)); - RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi)); - } - /* One GEMM: a rotated weight reads its own rotated pair, a plain one the producer's. */ - op = decl_gemm_q(b, 1, max_rows > 0 ? max_rows : g.max_tok, RAD_MX_GROUP, "m2xfp4", pb1, - pb2, { w, ws, wref }, { m2rot ? rot_q : a.q, m2rot ? rot_s : a.s }, y); - return op ? RAD_OK : RAD_E_INVAL; - } - /* Block fp8 is the last form; any other encoding is refused by name with the ones read. */ if (known) { const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); @@ -1652,17 +1577,9 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } - if (m2x && !paro) { - /* The MXFP4 operands over the producer's pair; the meta rides the weight's stored blob. */ - RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), - brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref)); - return; - } if (mx || m2x) { - /* A rotated weight first rotates its input into its own codes, `rot_parts` copies side by - * side; a plain weight reads the producer's. A rotated M2XFP4 weight is issued here as the - * rotated MXFP4 one is, its meta riding the weight operand's stored blob. */ + /* A rotated weight (MXFP4 or M2XFP4) first rotates its input into its own codes, + * `rot_parts` copies side by side; a plain weight reads the producer's. */ const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s; const int64_t ak = rot_parts * K; if (paro) @@ -1697,10 +1614,7 @@ struct DenseFP8 { * works against the same E4M3 activation pair. */ rad_weight ref = 0; bool mx = false; - /* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 weight plus one metadata byte a group, read by - * `gemm_nt_q` at dtype m2xfp4 with the same views and the same `b_ref`. The meta plane rides - * the weight operand's stored blob (libr4d's m2xfp4 layout), so the declared weight takes the - * codes and meta planes together. */ + /* Or M2XFP4 (libquant `m2xfp4`): the MXFP4 views, the meta plane riding the weight operand. */ bool m2x = false; /* `mapped`: the caller made the name map already, to ask the encoding before choosing this @@ -1739,16 +1653,11 @@ struct DenseFP8 { rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, std::initializer_list reads, std::initializer_list writes, int64_t split_n = 0) const { - if (m2x) + if (mx || m2x) return rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "m2xfp4")), - RAD_WEIGHTS(w, s, ref)), - reads, writes); - if (mx) - return rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), + RAD_INT("group", RAD_MX_GROUP), + RAD_STR("dtype", m2x ? "m2xfp4" : "mxfp4a8")), RAD_WEIGHTS(w, s, ref)), reads, writes); if (split_n > 0) @@ -1775,44 +1684,27 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t std::initializer_list row_parts, bool mapped) { if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; - /* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need - * only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) scale. */ + /* ---- OCP-MXFP4 or M2XFP4, from the weight's encoding. The exponent grid is one row tall, so + * parts need only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) + * scale. */ { const char* wn = nm.f("%s.weight", base); if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); RadEncoding enc{}; - mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc); - m2x = !mx && linear_is_m2xfp4(enc); /* enc stays zero when there is no encoding */ - if (mx) { + const bool known = weight_enc(b, wn, &enc); + mx = known && linear_is_mxfp4(enc); + m2x = known && linear_is_m2xfp4(enc); + if (mx || m2x) { if (N % 16 || K % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows " + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an %s weight takes rows " "in 16s and K in whole %d-column activation scale blocks\n", - base, (long long)N, (long long)K, RAD_FP8_BLOCK); + base, (long long)N, (long long)K, m2x ? "M2XFP4" : "MXFP4", RAD_FP8_BLOCK); return RAD_E_INVAL; } RowParts rp; - RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "MXFP4 tiles")); - w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, - rp.w, rp.n); - s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, + RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, m2x ? "M2XFP4 tiles" : "MXFP4 tiles")); + w = decl_view(b, wn, nullptr, m2x ? "codes,meta" : "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, rp.w, rp.n); - ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, - access, shard, grp, rp.w, rp.n); - return w && s && ref ? RAD_OK : RAD_E_INVAL; - } - /* ---- M2XFP4: the MXFP4 views with the metadata plane riding the weight operand, the - * same bounds. */ - if (m2x) { - if (N % 16 || K % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an M2XFP4 weight takes rows " - "in 16s and K in whole %d-column activation scale blocks\n", - base, (long long)N, (long long)K, RAD_FP8_BLOCK); - return RAD_E_INVAL; - } - RowParts rp; - RAD_ARCH_TRY(rp.set(row_parts, 16, 1, base, "M2XFP4 tiles")); - w = decl_view(b, wn, nullptr, "codes,meta", RAD_FP4E2M1, { N, K }, access, shard, grp, - rp.w, rp.n); s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, access, shard, grp, rp.w, rp.n); ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, @@ -1859,10 +1751,9 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, } /* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0 - * plane and that plane again as the per-row reference), declared for M up to min(rows, 8), the band - * of libr4d's one-to-eight-row GEMM it is built on. Optional like decl_gated_fold, and asked for - * only when a loaded library declares the op: libref does not, so a CPU-only engine takes the pair - * without ever naming it. */ + * plane and that plane again as the per-row reference), up to min(rows, 8) rows, the band of + * libr4d's one-to-eight-row GEMM. Declared only when a loaded library declares the op (libref + * does not), so a CPU-only engine takes the pair. */ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight ws, rad_weight wref, std::initializer_list reads, @@ -1880,6 +1771,31 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t return op; } +/* ================================================== a calibration tap */ +/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the + * corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */ +struct CalibTap { + rad_buf h = 0; + rad_op op = 0; + int64_t K = 0; + + int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) { + K = k; + h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST); + if (!h) return RAD_E_INVAL; + op = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", k), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, h }, { h }); + return op ? RAD_OK : RAD_E_INVAL; + } + /* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */ + void step(RadCtx* c, rad_buf a, int64_t T, bool live) const { + if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K)); + } +}; + } /* namespace arch */ } /* namespace rad */ diff --git a/arch/common/rad_qsa.h b/arch/common/rad_qsa.h index b8ad9223..19e3a5fc 100644 --- a/arch/common/rad_qsa.h +++ b/arch/common/rad_qsa.h @@ -216,6 +216,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l d.head_dim = c.head_dim / (2 * c.ratio); *bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d); if (!*bk) return RAD_E_INVAL; + /* qsa_score reads every complete block of the history each step, so this group stays resident + * and holds every sequence's context while a sibling streams (kvstream/carve.h). */ + RAD_ARCH_TRY(rad_kv_group_dense_read(b, *bk)); } kv_bk = *bk; /* Under M-RoPE a block key rotates at its first token's three components, which qsa_work @@ -255,6 +258,9 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)), RAD_NOWEIGHTS), {w.score, w.nc}, {w.sel, w.nsel, w.sequ}); + + /* When the attention group streams, the attention block resolves `sel` to ring slots after its + * layer's store (AttnGatedFP8::step); prefill runs on the stage and never resolves. */ return RAD_OK; } diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index a002e689..702d7b16 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -347,33 +347,6 @@ inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int gemm_rows(c, y, r0, n); } -/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input, - * summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set, - * for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's - * Gram is 10752^2 f32 a rank at TP2, so 62 layers of four taps do not fit beside the weights and a - * calibration runs in slices of layers, the corpus pushed through once per slice. */ -struct G3Tap { - rad_buf h = 0; - rad_op op = 0; - int64_t K = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, rad_buf a, int64_t k) { - K = k; - h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST); - if (!h) return RAD_E_INVAL; - op = rw(b, RAD_OP(b, "gram_accum", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", k), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { a, h }, { h }); - return op ? RAD_OK : RAD_E_INVAL; - } - /* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */ - void step(RadCtx* c, rad_buf a, int64_t T, const bool* live) const { - if (op && live && *live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K)); - } -}; - /* ---- one attention block, parameterised by class. */ struct Gemma3Attn { struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; }; @@ -393,7 +366,7 @@ struct Gemma3Attn { * resolves; byte-identical to the four */ rad_op op_qnr = 0; /* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */ - G3Tap tap_in{}, tap_o{}; + CalibTap tap_in{}, tap_o{}; const bool* tap_live = nullptr; /* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a * launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every @@ -410,10 +383,6 @@ struct Gemma3Attn { void post(RadCtx* c, int64_t T) const { RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); } - /* The block's all-reduce alone, as Gemma3Mlp::ar. */ - void ar(RadCtx* c, int64_t T) const { - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - } /* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces, * its input pair already written; hands the first piece behind its out projection. */ void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const; @@ -615,7 +584,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta ln_q.step(c, w.h, w.q, T); ln_k.step(c, w.h, w.k, T); ln_v.step(c, w.h, w.v, T); - tap_in.step(c, w.h, T, tap_live); + tap_in.step(c, w.h, T, tap_live && *tap_live); } if (op_qnr) { @@ -639,7 +608,7 @@ void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); - tap_o.step(c, w.attn, T, tap_live); + tap_o.step(c, w.attn, T, tap_live && *tap_live); ln_o.step(c, w.attn, w.h, T); /* All-reduce before the post-norm: o_proj is column-sharded, and the norm is of the sum. */ if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); @@ -659,17 +628,13 @@ struct Gemma3Mlp { G3Linear ln_gu{}, ln_down{}; rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; rad_op op_gq = 0; - /* gate|up, the GeGLU and down's E4M3 quantiser in one launch (libr4d gemm_nt_q_gated_mx at - * gelu_tanh) at up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the - * GEMM, gelu_mul and quant_act_fp8 it replaces. */ + /* gate|up, the GeGLU and down's E4M3 quantiser in one launch (gemm_nt_q_gated_mx at gelu_tanh) + * up to `fold_rows` rows, when both linears are MXFP4: byte-identical to the GEMM, gelu_mul and + * quant_act_fp8 it replaces. */ rad_op op_fold = 0; int64_t fold_rows = 0; - /* Set before declare: the band the fold is declared over (RADIANCE_G3_FOLD_ROWS). libr4d's - * gemm_mxfp4a8_gated_gemv serves 1..8 rows and _gated_gemv_wide 9..64, each byte-identical to - * the GEMM row of its band (gemv, gemv_wide) followed by gelu_mul and quant_act_fp8. */ - int64_t fold_max = 8; /* Calibration: gate|up's input and down's (this rank's columns). */ - G3Tap tap_gu{}, tap_dn{}; + CalibTap tap_gu{}, tap_dn{}; const bool* tap_live = nullptr; /* Set before declare by a pipelined deployment, as Gemma3Attn's. */ int ar_overlap = 0; @@ -682,11 +647,6 @@ struct Gemma3Mlp { void post(RadCtx* c, int64_t T) const { RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); } - /* The block's all-reduce alone, for a caller that issues it after something of its own (the - * step's read beside it, RADIANCE_G3_PF_EARLY). */ - void ar(RadCtx* c, int64_t T) const { - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - } /* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up * to the down projection; then the tail a piece at a time on the second lane. */ void body_rows(RadCtx* c, int64_t r0, int64_t n) const { @@ -745,6 +705,10 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const {w.gu}, {ln_down.q8, ln_down.s8}); // Not under calibration either: the down tap reads the bf16 product, which the fold never writes. { + /* libr4d folds 1..8 rows (gemm_mxfp4a8_gated_gemv) and, from K 2688, 9..64 + * (_gated_gemv_wide), each byte-identical to its band's GEMM row followed by gelu_mul and + * quant_act_fp8. At 2-8 sequences with speculation a decode step is 16-64 rows. */ + const int64_t fold_max = ln_gu.K >= 2688 ? 64 : 8; const int64_t hi = g.max_tok < fold_max ? g.max_tok : fold_max; // G3Linear's mx is linear_is_mxfp4, never a rotated (ParoQuant) weight, so one part. if (ln_gu.mx && ln_down.mx && !ln_down.shared_in && !calib_dir() && hi > 0 && @@ -797,7 +761,7 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai ln_gu.step(c, w.h, w.gu, T); else if (!ln_gu.shared_in) RAD_ISSUE_N(c, ln_gu.op_q, T, brows(w.h, T), brows(ln_gu.q8, T), brows(ln_gu.s8, T)); - tap_gu.step(c, w.h, T, tap_live); + tap_gu.step(c, w.h, T, tap_live && *tap_live); } if (fold) { RAD_ISSUE_N(c, op_fold, T, brows(ln_gu.q8, T), brows(ln_gu.s8, T), RAD_W(ln_gu.w), @@ -809,7 +773,7 @@ void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai ln_down.gemm(c, w.h, T); } else { RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T)); - tap_dn.step(c, w.ffn, T, tap_live); + tap_dn.step(c, w.ffn, T, tap_live && *tap_live); ln_down.step(c, w.ffn, w.h, T); } if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); @@ -929,82 +893,23 @@ struct G3JunctionFP8 { /* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows (a verify of four sequences at - * speculation 7, as qwen35_fp8's). TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (Gen5 x8), - * no speculation, two rounds each, x1 / x4 / x8 tok/s against none (56.8 / 182.0 / 325.0): 8 MB 63.3 / - * 203.1 / 354.9; 12 MB 63.0 / 202.6 / 354.9; 16 MB 63.5 / 203.9 / 356.6; 20 MB 64.1 / 204.0 / 359.4; - * 24 MB 64.4 / 206.4 / 359.3; 32 MB 63.1 / 201.4 / 351.9. Larger than qwen35_fp8's 12 MB: this - * model's hidden width (5376) and weights are larger, so its all-reduces take longer and its GEMMs - * read more; past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it should - * feed. With speculation 7 (three rounds, greedy, medians) x1 / x4 / x8 / x16 158.1 / 409.0 / 592.0 / 710.8 -> 177.3 / 428.4 / 592.3 / 717.6. The drafter's reads (Dflash2::Config::prefetch) take the same size. */ + * speculation 7). TranslateGemma-27B MXFP4 + DFlash2, tp 2 on two R9700s: 24 MB was best, +13 % + * at one stream and +10 % at eight with no speculation, +12 % / +5 % at one / four streams with + * speculation 7. Larger than qwen35_fp8's 12 MB, since this model's wider all-reduces take longer; + * past ~24 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds. The + * drafter's reads (Dflash2::Config::prefetch) take the same size. */ constexpr int64_t kPrefetchBytes = (int64_t)24 << 20; constexpr int64_t kPrefetchStepRows = 32; -/* A/B knobs over the decode steps, read at declare; unset, each is today's behaviour and the graph - * and steps are the ones pinned before they existed (arch_test, - * gemma3_served_knobs_at_their_defaults_keep_the_pinned_graph_and_steps). - * - * RADIANCE_G3_PF_ROWS the tallest decode step that reads beside its reductions (default - * kPrefetchStepRows, 32, qwen35_fp8's). Eight sequences at speculation 7 - * verify 64 rows, and every all-reduce of such a step runs with the card's - * memory idle (~5.8 ms eager a step on 2x R9700). - * RADIANCE_G3_PF_MIB the read's size on the steps above 32 rows (default kPrefetchBytes, whose - * sweep was at 1..32-row steps): a 64-row step's GEMMs are partly compute- - * bound, so the size that fits beside its longer reduction may differ. - * RADIANCE_G3_PF_EARLY 1: issue the read between the GEMM and a bare (unfused) all-reduce - * rather than after it. Above ar_wire_is_exact's rows the lossy wire's - * all-reduce is issued by the block itself, so the read's join on lane 1 - * comes after the reduction and the read runs beside the post-norm, the - * junction and the next GEMM, not beside the reduction. The fused steps - * (exact wire) have it in front either way. - * RADIANCE_G3_FOLD_ROWS the gated fold's band (Gemma3Mlp::fold_max): 0 is today's 8; up to 64. */ -struct G3Knobs { - int64_t pf_rows = kPrefetchStepRows; - int64_t pf_wide = kPrefetchBytes; /* bytes, steps of more than kPrefetchStepRows rows */ - bool pf_early = false; - int64_t fold = 8; -}; - -/* An integer knob in [lo, hi], or `dflt` when unset; anything else is refused by name, so a typo - * in an A/B does not silently measure the default. */ -static int g3_knob(const char* name, long long lo, long long hi, long long dflt, long long* out) { - *out = dflt; - const char* s = std::getenv(name); - if (!s || !*s) return RAD_OK; - char* end = nullptr; - const long long v = std::strtoll(s, &end, 10); - if (!end || *end != '\0' || v < lo || v > hi) { - fprintf(stderr, "radiance: gemma3: %s='%s' is not an integer in %lld..%lld\n", name, s, lo, hi); - return RAD_E_INVAL; - } - *out = v; - return RAD_OK; -} - -static int g3_knobs(G3Knobs* k) { - long long v = 0; - RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_ROWS", 1, 1 << 20, kPrefetchStepRows, &v)); - k->pf_rows = v; - RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_MIB", 1, 256, kPrefetchBytes >> 20, &v)); - k->pf_wide = (int64_t)v << 20; - RAD_ARCH_TRY(g3_knob("RADIANCE_G3_PF_EARLY", 0, 1, 0, &v)); - k->pf_early = v != 0; - RAD_ARCH_TRY(g3_knob("RADIANCE_G3_FOLD_ROWS", 0, 64, 0, &v)); - k->fold = v == 0 ? 8 : v; - return RAD_OK; -} - struct Layer { bool global = false; Gemma3Attn attn{}; Gemma3Mlp mlp{}; G3Junction j_am{}, j_ma{}; G3JunctionFP8 jf_am{}, jf_ma{}; - /* The reads beside the decode all-reduces: gate|up's leading bytes beside the attention block's - * reduction, the next layer's q's beside the feed-forward's. 0 where none is declared. The - * `_wide` pair serves the steps above kPrefetchStepRows rows; it is the narrow pair itself - * unless RADIANCE_G3_PF_MIB gives those steps another size. */ + /* gate|up's leading bytes beside the attention block's reduction, the next layer's q's beside + * the feed-forward's; 0 where none is declared. */ rad_op op_pf_gu = 0, op_pf_next = 0; - rad_op op_pf_gu_wide = 0, op_pf_next_wide = 0; rad_weight pf_gu_w = 0, pf_next_w = 0; }; @@ -1024,7 +929,6 @@ struct Model { rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0; std::vector layers; - G3Knobs knobs{}; G3Junction j0{}; bool fuse = false; @@ -1220,7 +1124,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED); m = Model{}; m.nm = Names(ctx->scope); - RAD_ARCH_TRY(g3_knobs(&m.knobs)); RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); /* The rotary scaling (linear, factor 8 on the 27B) into g.rope_scale, for the global class. */ RAD_ARCH_TRY(yarn_from(m.g, meta, "", m.g.head_dim)); @@ -1377,7 +1280,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c lay.attn.ar_overlap = lay.mlp.ar_overlap = 1; lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in; } - lay.mlp.fold_max = m.knobs.fold; RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale)); RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw)); } @@ -1445,9 +1347,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } m.fuse_mx_ar = ar; } - /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). Only at - * more than one rank; RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ - if (g.world > 1 && rad_op_declared(b, "prefetch")) { + /* ---- the weight reads beside the decode all-reduces, at more than one rank; + * --weight-prefetch off declares none. */ + if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) { for (int64_t l = 0; l < g.n_layer; ++l) { Layer& lay = m.layers[(size_t)l]; lay.pf_gu_w = lay.mlp.ln_gu.w; @@ -1456,14 +1358,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c lay.pf_next_w = m.layers[(size_t)l + 1].attn.ln_q.w; lay.op_pf_next = decl_prefetch(b, lay.pf_next_w, kPrefetchBytes); } - /* A size of their own for the steps above kPrefetchStepRows, declared only when some - * step can take it, so an unused RADIANCE_G3_PF_MIB leaves the graph as it was. */ - lay.op_pf_gu_wide = lay.op_pf_gu; - lay.op_pf_next_wide = lay.op_pf_next; - if (m.knobs.pf_rows > kPrefetchStepRows && m.knobs.pf_wide != kPrefetchBytes) { - lay.op_pf_gu_wide = decl_prefetch(b, lay.pf_gu_w, m.knobs.pf_wide); - if (lay.pf_next_w) lay.op_pf_next_wide = decl_prefetch(b, lay.pf_next_w, m.knobs.pf_wide); - } } } /* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */ @@ -1502,26 +1396,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions * never write, so under it none is declared (above): any container calibrates, unfused. */ if (calib_dir()) { - m.calib_lo = 0; - m.calib_hi = g.n_layer; - if (const char* s = std::getenv("RADIANCE_G3_CALIB_LAYERS")) { - long long lo = 0, hi = 0; - int used = 0; - if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 || - hi > g.n_layer || lo >= hi) { - fprintf(stderr, "radiance: gemma3: RADIANCE_G3_CALIB_LAYERS '%s' is not lo:hi within " - "0:%lld\n", s, (long long)g.n_layer); - return RAD_E_INVAL; - } - m.calib_lo = lo; - m.calib_hi = hi; - } + RAD_ARCH_TRY(calib_layers("gemma3", "RADIANCE_G3_CALIB_LAYERS", g.n_layer, &m.calib_lo, + &m.calib_hi)); for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { Layer& lay = m.layers[(size_t)l]; - RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd)); - RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim())); - RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd)); - RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff)); + RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd)); + RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g.max_tok, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim())); + RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd)); + RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g.max_tok, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff)); } m.calib = true; m.tap_live = true; @@ -1783,11 +1665,8 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE); - /* The reads beside the reductions go on decode steps of up to RADIANCE_G3_PF_ROWS rows - * (kPrefetchStepRows by default), none on a step that carries a prompt's rows (as - * qwen35_fp8's); the steps above kPrefetchStepRows take the `_wide` reads. */ - const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= m.knobs.pf_rows ? 1 : INT64_MAX; - const bool pf_wide = T > kPrefetchStepRows; + /* Decode steps of up to kPrefetchStepRows rows only, as qwen35_fp8's. */ + const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && T <= kPrefetchStepRows ? 1 : INT64_MAX; if (m.fuse_mx) { /* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction; * the last block's tail runs unfused into the final norm. */ @@ -1797,20 +1676,13 @@ static void step(RadCtx* c, const RadBatch* batch) { const bool last = li + 1 == m.layers.size(); /* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */ const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T); - /* RADIANCE_G3_PF_EARLY: a bare all-reduce issued here, behind the read, rather than by - * the block (the last feed-forward, with no read after it, keeps its own). */ - const bool early = m.knobs.pf_early && !far; - const rad_op pf_gu = pf_wide ? l.op_pf_gu_wide : l.op_pf_gu; - const rad_op pf_next = pf_wide ? l.op_pf_next_wide : l.op_pf_next; - l.attn.step(c, batch, true, true, far || early); - prefetch_beside(c, pf_gu, l.pf_gu_w, pf_h); - if (early) l.attn.ar(c, T); + l.attn.step(c, batch, true, true, far); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (!far) l.attn.post(c, T); l.jf_am.step(c, T, far); - l.mlp.step(c, batch, true, !last, far || early); - prefetch_beside(c, pf_next, l.pf_next_w, pf_h); + l.mlp.step(c, batch, true, !last, far); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (!last) { - if (early) l.mlp.ar(c, T); if (!far) l.mlp.post(c, T); l.jf_ma.step(c, T, far); } @@ -1823,10 +1695,10 @@ static void step(RadCtx* c, const RadBatch* batch) { const bool last = li + 1 == m.layers.size(); const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */ l.attn.step(c, batch, m.fuse, m.fuse, ar); - prefetch_beside(c, pf_wide ? l.op_pf_gu_wide : l.op_pf_gu, l.pf_gu_w, pf_h); + prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h); if (m.fuse) l.j_am.step(c, T, ar); l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar); - prefetch_beside(c, pf_wide ? l.op_pf_next_wide : l.op_pf_next, l.pf_next_w, pf_h); + prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h); if (m.fuse && !last) l.j_ma.step(c, T, ar); tap(li); } diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 1fe63426..06762818 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -141,33 +141,6 @@ struct Kind { int64_t kv_dim() const { return nkv * hd; } }; -/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one bf16 linear's input, - * summed over a corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set, - * for the dense layers RADIANCE_G4_CALIB_LAYERS names ("lo:hi", default every layer): the 31B's - * four taps a layer are ~364 MiB a rank at --tp 4, so its 60 layers do not fit beside the bf16 - * weights and a calibration runs in slices of layers, the corpus pushed through once per slice. */ -struct G4Tap { - rad_buf h = 0; - rad_op op = 0; - int64_t K = 0; - - int declare(RadBuilder* b, Names& nm, int64_t max_tok, const char* name, rad_buf a, int64_t k) { - K = k; - h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST); - if (!h) return RAD_E_INVAL; - op = rw(b, RAD_OP(b, "gram_accum", - RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", k), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { a, h }, { h }); - return op ? RAD_OK : RAD_E_INVAL; - } - /* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */ - void step(RadCtx* c, rad_buf a, int64_t T, bool live) const { - if (op && live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K)); - } -}; - struct Layer { int full = 0; /* attention */ @@ -217,7 +190,7 @@ struct Layer { /* Calibration: the attention's input (q, k and v share it), its output (this rank's columns, * o_proj's input), the dense arm's input and its gated product (this rank's columns, down's * input). */ - G4Tap tap_in{}, tap_o{}, tap_gu{}, tap_dn{}; + CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_dn{}; }; struct Model { @@ -1269,20 +1242,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (calib_dir()) { m.overlap = false; m.arms = false; - m.calib_lo = 0; - m.calib_hi = (int64_t)m.layers.size(); - if (const char* s = std::getenv("RADIANCE_G4_CALIB_LAYERS")) { - long long lo = 0, hi = 0; - int used = 0; - if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 || - hi > (long long)m.layers.size() || lo >= hi) { - fprintf(stderr, "radiance: gemma4: RADIANCE_G4_CALIB_LAYERS '%s' is not lo:hi within " - "0:%zu\n", s, m.layers.size()); - return RAD_E_INVAL; - } - m.calib_lo = lo; - m.calib_hi = hi; - } + RAD_ARCH_TRY(calib_layers("gemma4", "RADIANCE_G4_CALIB_LAYERS", (int64_t)m.layers.size(), + &m.calib_lo, &m.calib_hi)); for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { Layer& y = m.layers[(size_t)l]; const Kind& k = y.full ? m.kf : m.ks; diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index df0f0743..52a56ffb 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -1867,7 +1867,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui dc.group = df2_geti(meta, "conv_group_size", 16); dc.sel_rank = df2_geti(meta, "selector_rank", 0); dc.sel_topk = df2_geti(meta, "selector_top_k", 0); - dc.prefetch = gemma4::kPrefetchBytes; + dc.prefetch = ctx->weight_prefetch_off ? 0 : gemma4::kPrefetchBytes; if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { fprintf(stderr, "radiance: gemma4: the DFlash2 drafter states no selector geometry (rank " "%lld, top_k %lld)\n", (long long)dc.sel_rank, (long long)dc.sel_topk); @@ -2454,8 +2454,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last * layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's * first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank, - * where there are reductions to sit beside. */ - if (g.world > 1 && rad_op_declared(b, "prefetch")) { + * where there are reductions to sit beside, and not under --weight-prefetch off. */ + if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) { for (size_t l = 0; l < m.layers.size(); ++l) { Layer& lay = m.layers[l]; lay.attn.pf_w = lay.mlp.ln_gu.w; diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 299a64dc..2a9a61fa 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -214,6 +214,8 @@ static int indexer_buffers(RadBuilder* b, Model& m) { c.selected = m.aw.core.selected; c.length = m.aw.core.length; c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); + /* The MLA block's resolve count: qsa_select's second output, never `length`. */ + m.aw.core.nsel = c.nsel; if (g.world > 1) { c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 }); c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 }); @@ -396,6 +398,9 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i g.max_ctx = ctx->max_ctx; g.max_seqs = ctx->max_seqs; g.max_spec = ctx->max_spec; + /* Filled by hand here, not by geom_from: without it kv_resolve would declare the whole context as + * the ring. */ + g.kv_resident = ctx->kv_resident_blocks; g.max_logit_rows = std::min(g.max_tok, g.max_seqs * (g.max_spec + 1)); if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows; g.eps = meta->rms_eps; @@ -593,6 +598,8 @@ static void step(RadCtx* c, const RadBatch* batch) { } static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; + /* The MLA block declares the streamed store and the resolve (rad_block_glm_mla.h). */ + out->kv_stream_ok = 1; if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth; // The tower's merged block, so a pass size the core picks itself is whole output rows. if (GlmVision::present(meta)) { diff --git a/arch/minimaxh3/CMakeLists.txt b/arch/minimaxh3/CMakeLists.txt index 6ad47f4d..04a7de0e 100644 --- a/arch/minimaxh3/CMakeLists.txt +++ b/arch/minimaxh3/CMakeLists.txt @@ -7,4 +7,9 @@ if(NOT COMMAND rad_add_plugin) rad_plugin_defaults() endif() -rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp) +# rad_ref2va_pack.cpp holds the reference sequence's packing and rad_vae_geom.cpp the encoders' +# geometry: pure host arithmetic, which tests/ref2va_pack_test.cpp and tests/vae_geom_test.cpp +# compile in directly. +rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rad_ref2va_pack.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rad_vae_geom.cpp) diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 3f297b64..57aa7196 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -1,4 +1,5 @@ -/* minimaxh3 -- MiniMax-H3: a video and its stereo soundtrack from text. +/* minimaxh3 -- MiniMax-H3: a video and its stereo soundtrack from text, between keyframes or from + * reference media. * * ============================== THE MODEL ============================== * @@ -28,6 +29,15 @@ * The passes, their batches and the lanes a request's state lives in are the core's video * generator (abi/rad_builder.h, rad_declare_video_generator; core/gen/video_driver.h). * + * ============================== KEYFRAMES AND REFERENCES ============================== + * + * The workflows i2va, l2va, fl2va and ref2va (ComfyUI's MiniMax-H3 nodes) add rows to the packed + * sequence: a keyframe's latents, pinned at its frame of the video, or a reference picture's, + * video's or soundtrack's in its own grid (rad_ref2va_pack.h). The VAEs' encoders make them, one + * Vencode or Aencode pass a media into the lane before the prompt pass. Their rows take a + * near-clean timestep, so the modulation table has a cell for every run of segments that share + * one. A reference picture is also shown to the text encoder, through Qwen3-VL's vision tower. + * * ============================== A DISTILLED RELEASE ============================== * * FastVideo's FastH3 is the same denoiser distilled to eight evaluations on fixed timesteps with @@ -65,7 +75,9 @@ * ============================== WHAT IS QUANTISED ============================== * * Every linear of the text encoder, of the refiner and of the DiT's blocks, and the modulation - * projections, are block fp8 (LinearFP8 / DenseFP8 read what the container holds). The small + * projections, are block fp8, or the DiT's int8 at int8 activations (LinearFP8 / DenseFP8 read what + * the container holds). A curve-form checkpoint reads its timestep embeddings off a table it + * ships, and its modulation projections, eight wide, are bf16. The small * linears around them keep the checkpoint's precision: the timestep MLP and the four patch * projections in f32, `context_embedder` and `norm_out` in bf16. The DiT's dense attention takes * its scores in int8 (keys per row and head, the query inside the op; P.V in bf16), which runs the @@ -81,8 +93,12 @@ * tiles; the audio decoder runs whole on every rank. */ #include +#include #include +#include "rad_ref2va_pack.h" +#include "rad_vae_geom.h" + #include #include #include @@ -99,8 +115,9 @@ using namespace rad::arch; /* ================================================================== the model's constants */ /* The text encoder's layer the conditioning is read after. */ enum { kTextLayers = 50 }; -/* The longest prompt, in tokens; a structured prompt in the model's own style is about 1500. */ -enum { kMaxText = 2048 }; +/* The longest prompt, in tokens. A structured prompt in the model's own style is about 1500; one + * that shows reference pictures carries their vision tokens too, about 3000 for a few. */ +enum { kMaxText = 8192 }; /* Requests holding state at once: one denoising, one conditioned and waiting. */ enum { kMaxLanes = 2 }; /* Model evaluations a request may take (kMaxSteps), and the default sigma grid points (the @@ -144,6 +161,11 @@ static const char* kPixStd = "0.229 0.224 0.225"; enum { kSegText = 0, kSegAudio = 1, kSegVideo = 2, kSegs = 3 }; static const int kSegMod[kSegs] = { 1, 2, 0 }; +/* The modulation groups a step's sequence may change through (rad_ref2va_pack.h): the plain + * sequence's three, or with references at most the prompt, keyframes or pictures, each video's + * soundtrack and video, standalone soundtracks and the two latents in their runs. */ +enum { kMaxSegs = 8 }; + /* ================================================================== geometry, on the host */ /* diffusers' AutoencoderKLMiniMaxH3._split_tiles in latents: the first latent of each tile across * a side of `L` latents. The overlaps start at the minimum and the slack goes to them round-robin, @@ -212,59 +234,19 @@ static void vsa_bounds(double sparsity, int64_t* tiles, int64_t* keep) { *keep = vsa_keep(sparsity, best); } -/* The packed sequence's rotary positions (diffusers' MiniMaxH3PrepareLayoutStep), in f64 as the - * reference builds them, f32 as its rope reads them. Text rows count up on the time axis; the - * media's clock starts after them. A latent frame spans 5/3 (1, 4, 4, 4, 4)[i % 5] units of time, - * a soundtrack latent one; the spatial axes are each side's latents over the square root of the - * frame's area, centred on the unit interval and scaled by 32 (numpy's linspace without its - * endpoint), and a soundtrack's two channels sit at the two ends of the width axis. */ +/* The packed sequence's rotary positions (diffusers' MiniMaxH3PrepareLayoutStep), the pack's + * with no references (rad_ref2va_pack.h). */ 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 < kPatch || g->lat_w < kPatch || g->n_audio < 1) return RAD_E_INVAL; - const int64_t nt = g->n_text, na = g->n_audio, F = g->lat_frames; - const int64_t ph = g->lat_h / kPatch, pw = g->lat_w / kPatch; - const int64_t rows = nt + kAudioCh * na + F * ph * pw; - if (!pos) return rows; - if (cap < rows) return RAD_E_INVAL; - float* P0 = pos; - float* P1 = pos + rows; - float* P2 = pos + 2 * rows; - const double sq = std::sqrt((double)g->lat_h * (double)g->lat_w); - auto grid = [&](int64_t dim, std::vector* out) { - const int64_t n = dim / kPatch; - const double ratio = (double)dim / sq, left = (1.0 - ratio) / 2.0; - const double step = ((left + ratio) - left) / (double)n; - out->resize((size_t)n); - for (int64_t i = 0; i < n; ++i) (*out)[(size_t)i] = ((double)i * step + left) * 32.0; - }; - std::vector hg, wg; - grid(g->lat_h, &hg); - grid(g->lat_w, &wg); - int64_t r = 0; - for (int64_t i = 0; i < nt; ++i, ++r) { - P0[r] = (float)(double)i; - P1[r] = 0.0f; - P2[r] = 0.0f; - } - for (int64_t c = 0; c < kAudioCh; ++c) - for (int64_t k = 0; k < na; ++k, ++r) { - P0[r] = (float)((double)nt + (double)k); - P1[r] = 0.0f; - P2[r] = (float)(c == 0 ? wg.front() : wg.back()); - } - static const int kPattern[5] = { 1, 4, 4, 4, 4 }; - double t = (double)nt; - for (int64_t f = 0; f < F; ++f) { - for (int64_t y = 0; y < ph; ++y) - for (int64_t x = 0; x < pw; ++x, ++r) { - P0[r] = (float)t; - P1[r] = (float)hg[(size_t)y]; - P2[r] = (float)wg[(size_t)x]; - } - t += 5.0 / 3.0 * (double)kPattern[f % 5]; - } - return rows; + const Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, (int)g->n_audio }; + Ref2VAPack p; + if (ref2va_build((int)g->n_text, pg, {}, {}, &p, pos != nullptr) != 0) return RAD_E_INVAL; + if (!pos) return p.rows; + if (cap < p.rows) return RAD_E_INVAL; + std::copy(p.pos.begin(), p.pos.end(), pos); + return p.rows; } /* A decode pass's rows: every tile of the frame, each kPeriod rows. */ @@ -281,6 +263,7 @@ struct TeLayer { GateQuantFP8 gq{}; rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; + rad_op op_qkr_m = 0; /* `op_qkr` at interleaved M-RoPE, for a prompt with pictures */ }; /* A token refiner block: a plain pre-norm transformer block, no rotary, no modulation. */ @@ -304,9 +287,10 @@ struct DitBlock { rad_op op_sel = 0; /* video sparse attention's tile selection */ rad_op op_kq = 0; /* the keys to int8 codes for the attention's scores */ rad_op op_vq = 0; /* the values to E4M3 codes for the attention's P.V */ - /* The three modulation projections, one a modality, this rank's share of their rows. */ + /* The three modulation projections, one a modality, this rank's share of their rows; a + * curve-form checkpoint's are bf16 (ada_w). */ DenseFP8 ada[3]; - rad_weight ada_b[3] = {}; + rad_weight ada_w[3] = {}, ada_b[3] = {}; rad_op op_ada[3] = {}; }; @@ -368,8 +352,30 @@ enum : int { kGrpVae = 3000, kGrpAudio = 3100, kGrpUps = 3200, + kGrpTower = 3300, + kGrpVenc = 3400, + kGrpAenc = 3500, + /* The encoders' weights only a host kernel reads (conv_in, the k=1 convs, the snake alphas): + * placement keeps a group with a host-only reader in host memory whole, so they are a group + * of their own. */ + kGrpVencH = 3450, + kGrpAencH = 3550, }; +/* ---- the VAE encoders. A reference frame is at most 256 x 256 (ComfyUI's tile), a video at + * most 289 frames (17 clips), a soundtrack 500 000 samples (625 latents). The lane keeps a slot a + * media: a video's 82 latent frames at 256 x 256 are 82 x 8 x 8 patch rows, a soundtrack's two + * channels 2 x 625 rows. */ +enum { kEncMaxSide = 256, kEncMaxFrames = 289, kEncMaxSamples = 500000 }; +/* A keyframe is encoded at the video's size, up to the whole canvas, as one frame, which the + * temporal downsamplers do not shrink: every level holds at least this many frames at 256 x 256, + * the canvas's area. */ +enum { kEncOneFrames = ((int64_t)kDefW * kDefH + (int64_t)kEncMaxSide * kEncMaxSide - 1) / + ((int64_t)kEncMaxSide * kEncMaxSide) }; +enum { kEncSlotsV = 12, kEncSlotsA = 6 }; +enum { kEncSlotRowsV = 82 * (kEncMaxSide / 32) * (kEncMaxSide / 32), + kEncSlotRowsA = kAudioCh * (kEncMaxSamples / kAudioHop) }; + /* The evaluations a request runs at the full size after a latent upscale, by default: of a * distilled release's eight, and of the base model's 49. */ enum { kUpsRefineDistilled = 3, kUpsRefineBase = 12 }; @@ -389,6 +395,13 @@ struct Model { ActFP8 a_th{}, a_tattn{}, a_tffn{}; std::vector te; + /* ---- the text encoder's Qwen3-VL vision tower, for the pictures a prompt shows, when the + * container carries it (every config names one). Its rows replace the pictures' placeholder + * tokens and its deepstack taps join the first layers. */ + VisionTower tv{}; + bool media = false; + rad_op op_mm = 0, op_ds[VisionTower::MAX_DS] = {}; + /* ---- context_embedder and the refiner, over the prompt's rows */ rad_weight w_ce = 0, b_ce = 0, w_fn = 0; rad_op op_ce = 0, op_fn = 0; @@ -396,9 +409,13 @@ struct Model { ActFP8 a_rh{}, a_rattn{}, a_rffn{}; RefBlock rb[2]; - /* ---- the timestep MLP and the per-step tables */ - rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_no = 0, b_no = 0; - rad_op op_temb = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_ts2 = 0, op_no = 0; + /* ---- the timestep MLP and the per-step tables. A curve-form checkpoint has a table of + * embeddings in place of the sinusoid and the MLP: `curve` rows of it (0 without), and + * `temb_w` is the embedding's width either way. */ + int64_t curve = 0, temb_w = 2688; + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_no = 0, b_no = 0, w_ttable = 0; + rad_op op_temb = 0, op_temb_pv = 0, op_temb_pa = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, + op_ts2 = 0, op_no = 0; QuantFP8 q_temb{}; rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0; ActFP8 a_temb{}; @@ -409,6 +426,8 @@ struct Model { rad_buf b_nout = 0; /* [lanes * S, 3 * 2D] bf16: norm_out's, by segment */ rad_buf b_vstate = 0; /* [lanes * maxV, 96] f32 */ rad_buf b_astate = 0; /* [lanes * maxA, 32] f32 */ + rad_buf b_vx0 = 0; /* [lanes * maxV, 96] f32: res_multistep's last estimate */ + rad_buf b_ax0 = 0; /* [lanes * maxA, 32] f32 */ rad_buf b_prev = 0; /* [lanes * 5 * area, 3] bf16: the decoder's frames across chunks */ /* ---- the DiT */ @@ -426,11 +445,15 @@ struct Model { rad_buf b_v8 = 0, b_vs = 0; /* its values at E4M3 codes and their column scales */ /* The trained schedule's base times (a few-step checkpoint's), or none. */ std::vector rungs; - rad_buf b_h = 0, b_qkv = 0, b_ao = 0, b_gu = 0, b_hn = 0, b_hf = 0, b_vel = 0, b_avel = 0; + rad_buf b_h = 0, b_qkv = 0, b_ao = 0, b_gu = 0, b_hn = 0, b_hf = 0, b_vel = 0, + b_avel = 0; ActFP8 a_hm{}, a_attn{}, a_ffn{}; + /* The DiT's linears are int8 (W8A8): their activations are int8 codes as well. */ + bool dit_i8 = false; std::vector dit; rad_weight w_no_n = 0, w_vout = 0, b_vout = 0, w_aout = 0, b_aout = 0; rad_op op_nout = 0, op_hcast = 0, op_vout = 0, op_aout = 0, op_ev = 0, op_ea = 0; + rad_op op_rmv = 0, op_rma = 0; /* res_multistep, video and soundtrack */ /* ---- the audio decoder */ std::string a_mean, a_std; @@ -469,6 +492,73 @@ struct Model { rad_buf b_uin32 = 0, b_uin = 0, b_ua = 0, b_ub = 0, b_uc = 0, b_uout = 0, b_ust = 0; rad_buf b_ufac = 0, b_ue0 = 0, b_ue0s = 0, b_ue1 = 0, b_ue1s = 0, b_uemb = 0; std::vector u_in, u_out; + + /* ---- the video VAE's encoder, when the container carries it: bf16 voxel rows, causal + * reflect-padded convolutions, six levels of two residual blocks and four strided + * downsamplers. A level's stream is `a`, `b` and `c` are a block's temporaries, and `in` the + * input of a level whose first block changes the width (it has a 1x1x1 shortcut). */ + struct VEncBlock { + rad_weight n1w = 0, n1b = 0, c1w = 0, c1b = 0, n2w = 0, n2b = 0, c2w = 0, c2b = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0; + }; + struct VEncLevel { + int64_t cin = 0, cout = 0, rows = 0, pf = 0, frames = 0; /* pf: rows a frame */ + rad_buf in = 0, a = 0, b = 0, c = 0; + rad_weight scw = 0, scb = 0, dnw = 0, dnb = 0; + rad_op op_sc = 0, op_dn = 0; + VEncBlock blk[2]; + }; + std::vector v_lv; + bool venc = false; + rad_weight ve_cinw = 0, ve_cinb = 0, ve_now = 0, ve_nob = 0, ve_coutw = 0, ve_coutb = 0; + rad_weight ve_qw = 0, ve_qb = 0; + rad_op op_ve_pix = 0, op_ve_pcast = 0, op_ve_cin = 0, op_ve_nout = 0, op_ve_cout = 0; + rad_op op_ve_q = 0, op_ve_fold = 0, op_eaug = 0; + std::string ve_pix_mul, ve_pix_add, ve_fold_mul, ve_fold_add; /* pixel and latent norms */ + rad_buf b_epix32 = 0, b_epix = 0, b_eq48 = 0, b_eq2 = 0, b_egn = 0; + rad_buf b_evc = 0; /* [kEncSlotsV * kEncSlotRowsV, kPatchVals] f32 PERSIST */ + /* The tiled encode of a picture too big for one volume (step_venc_tiled): the tiles' geometry + * rows (read back through raw pointers, so PERSIST), the pixels and the moments tile-major. */ + rad_buf b_tplan = 0, b_vtile = 0, b_eqt = 0; + rad_op op_vt_plan = 0, op_vt_crop = 0, op_vt_join = 0; + + /* ---- the audio VAE's encoder, when the container carries it: f32 like its decoder, a + * channel a sequence, conv_in and five strided blocks of three units [snake, conv k7, snake, + * conv k1 + residual]. The strided convolutions and the attention block run in bf16, the + * only dtype those ops take for every operand. Every convolution but mean_proj is + * weight-normalised. */ + struct AEncUnit { + rad_weight a1 = 0, c1w = 0, c1b = 0, a2 = 0, c2w = 0, c2b = 0; + rad_op op_a1 = 0, op_c1 = 0, op_a2 = 0, op_c2 = 0; + }; + struct AEncBlk { + AEncUnit u[3]; + rad_weight al = 0, dnw = 0, dnb = 0; /* the block's last snake, its downsampler */ + rad_op op_al = 0, op_dn = 0; + /* The strided convolution's bf16 input and output. */ + rad_buf bi = 0, bo = 0; + rad_op op_ci = 0, op_co = 0; + }; + bool aenc = false; + AEncBlk ae_blk[5]; + rad_weight ae_cinw = 0, ae_cinb = 0, ae_al6 = 0, ae_finw = 0, ae_finb = 0; + rad_op op_ae_cin = 0, op_ae_snk6 = 0, op_ae_fin = 0; + /* The attention block (causal attention, then a GeGLU MLP at 32 channels), bf16. */ + rad_weight p_ln1w = 0, p_ln1b = 0, p_qkvw = 0, p_qkvb = 0, p_apw = 0, p_apb = 0; + rad_weight p_ln3w = 0, p_ln3b = 0, p_prw = 0, p_prb = 0, p_ln2w = 0, p_ln2b = 0; + rad_weight p_mlw = 0, p_mlb = 0, p_guw = 0, p_gub = 0, p_w2w = 0, p_w2b = 0; + rad_op p_op_ln3 = 0, p_op_qkv = 0, p_op_attn = 0, p_op_pool = 0, p_op_aproj = 0; + rad_op p_op_ln1 = 0, p_op_proj = 0, p_op_hadd = 0, p_op_ln2 = 0, p_op_mln = 0; + rad_op p_op_gu = 0, p_op_act = 0, p_op_w2 = 0, p_op_xadd = 0; + rad_op p_op_hs = 0, p_op_hsd = 0; /* the heads' mean: six adds, then an add over eight */ + rad_weight ae_mpw = 0, ae_mpb = 0; /* mean_proj, f32 */ + rad_op op_ae_mp = 0, op_ae_norm = 0, op_ae_cast6 = 0, op_ae_castx = 0; + std::string ae_norm_mul, ae_norm_add; /* the latents' normalisation */ + rad_buf b_ax[6] = {}, b_et1[5] = {}, b_et2[5] = {}, b_a6t = 0, b_ax6 = 0; + rad_buf b_apb = 0, b_aln3 = 0, b_aqkv = 0, b_aatt = 0, b_ahsum = 0, b_apool = 0; + rad_buf b_eh = 0, b_a32a = 0, b_a32b = 0, b_a32c = 0, b_a32d = 0, b_agu = 0, b_agu64 = 0; + rad_buf b_ax2 = 0, b_amb = 0, b_amb2 = 0; + rad_buf b_enca = 0; /* [kEncSlotsA * kEncSlotRowsA, kAudioC] f32 PERSIST */ }; static Model g_model[MAX_RANKS]; @@ -631,6 +721,28 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_INT("vocab_offset", 0)), RAD_WEIGHTS(m.w_tok)), {}, { m.b_tx }); + if (m.media) { + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.tv.b_out, m.b_tx }, { m.b_tx }); + for (int t = 0; t < m.tv.n_ds; ++t) + m.op_ds[t] = rw(b, RAD_OP(b, "scatter_add_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.tv.b_ds[t], m.b_tx }, { m.b_tx }); + } + + /* With the tower every layer also has its rotary at interleaved M-RoPE, Qwen3-VL's sections, + * for a prompt with pictures; text alone is the same rotation at NeoX. */ + 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"); m.te.resize((size_t)g.n_layer); for (int64_t l = 0; l < g.n_layer; ++l) { @@ -667,6 +779,18 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_INT("rotary_dim", g.head_dim)), RAD_WEIGHTS(L.w_qn, L.w_kn)), { m.b_tkv }, { m.b_tkv }); + if (m.media) + L.op_qkr_m = 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), @@ -860,41 +984,100 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { const int64_t fd = rad_meta_geti(meta, "transformer.freq_dim", 256); const int64_t hd1 = rad_meta_geti(meta, "transformer.time_embed_hidden_dim", 5376); const int64_t td = rad_meta_geti(meta, "transformer.time_embed_dim", 2688); + const int64_t G = rad_meta_geti(meta, "transformer.adaln_curve_grid", 0); + m.curve = G; + m.temb_w = td; const int acc = RAD_ACCESS_PER_REQUEST; const int gx = kGrpTemb; - if (td % RAD_FP8_BLOCK) { + if (!G && td % RAD_FP8_BLOCK) { fprintf(stderr, "radiance: minimaxh3: the timestep embedding is %lld wide, not whole " "%d-column blocks\n", (long long)td, RAD_FP8_BLOCK); return RAD_E_INVAL; } - m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { 2 * S, fd }); - m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { 2 * S, hd1 }); - m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { 2 * S, hd1 }); - m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { 2 * S, td }); - m.op_temb = rw(b, RAD_OP(b, "timestep_embed", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), - RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {}, { m.b_tproj }); - m.op_t1 = dense_bias(b, nm, "tmb.l1", "transformer.time_embedder.linear_1", RAD_F32, "f32", hd1, - fd, 2 * S, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); - m.op_ts = unary(b, "silu", 2 * S, hd1, "f32", m.b_te1, m.b_te1s); - m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32", td, - hd1, 2 * S, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); - /* silu(temb) in f32, rounded once to the bf16 the projections take. */ - Geom gs = g; - gs.max_tok = 2 * S; - m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { 2 * S, td }); - m.op_ts2 = unary(b, "silu", 2 * S, td, "f32", m.b_temb, m.a_temb.x); - RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, 2 * S)); - RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td)); - if (!m.op_temb || !m.op_t1 || !m.op_ts || !m.op_t2 || !m.op_ts2) return RAD_E_INVAL; + /* Every step's embeddings in four blocks of S: the video's schedule, the soundtrack's, then + * each again at max(t, pin) for the keyframes and references (`clamp_min`), which a request + * without them does not read. */ + const int64_t TT = 4 * S; + if (G > 0) { + /* A curve-form checkpoint reads each embedding off its table, between the two rows + * around the timestep, in bf16: that is the projections' input itself, with no MLP, SiLU + * or codes. */ + m.w_ttable = wcopy(b, nm.f("tmb.table"), nm.ckpt("transformer.adaln_t_table"), + RAD_F32, { G, td }, acc, gx); + m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_BF16, { TT, td }); + m.a_temb.x = m.b_temb; + if (!m.w_ttable || !m.b_temb) return RAD_E_INVAL; + /* `scale` and `max_period` are required and unused with a curve. */ + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), + RAD_F64("clamp_min", kR2VVisualPin), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", td), + RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), + RAD_INT("curve", G), + RAD_F64("clamp_min", kR2VAudioPin), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ttable)), + {}, { m.b_temb }); + if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa) return RAD_E_INVAL; + } else { + m.b_tproj = decl_b(b, nm.f("tmb.proj"), RAD_F32, { TT, fd }); + m.b_te1 = decl_b(b, nm.f("tmb.h1"), RAD_F32, { TT, hd1 }); + m.b_te1s = decl_b(b, nm.f("tmb.h1s"), RAD_F32, { TT, hd1 }); + m.b_temb = decl_b(b, nm.f("tmb.emb"), RAD_F32, { TT, td }); + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_temb_pv = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kR2VVisualPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_temb_pa = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", fd), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_F64("clamp_min", kR2VAudioPin), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense_bias(b, nm, "tmb.l1", "transformer.time_embedder.linear_1", RAD_F32, "f32", + hd1, fd, TT, m.b_tproj, m.b_te1, &m.w_t1, &m.b_t1, acc, gx); + m.op_ts = unary(b, "silu", TT, hd1, "f32", m.b_te1, m.b_te1s); + m.op_t2 = dense_bias(b, nm, "tmb.l2", "transformer.time_embedder.linear_2", RAD_F32, "f32", + td, hd1, TT, m.b_te1s, m.b_temb, &m.w_t2, &m.b_t2, acc, gx); + /* silu(temb) in f32, rounded once to the bf16 the projections take. */ + Geom gs = g; + gs.max_tok = TT; + m.a_temb.x = decl_b(b, nm.f("tmb.act"), RAD_BF16, { TT, td }); + m.op_ts2 = unary(b, "silu", TT, td, "f32", m.b_temb, m.a_temb.x); + RAD_ARCH_TRY(m.a_temb.declare_qs(b, nm, gs, "tmb.act", td, TT)); + RAD_ARCH_TRY(m.q_temb.declare(b, gs, m.a_temb, td)); + if (!m.op_temb || !m.op_temb_pv || !m.op_temb_pa || !m.op_t1 || !m.op_ts || !m.op_t2 + || !m.op_ts2) return RAD_E_INVAL; + } - /* The lane's tables. */ - m.b_ada = decl_b(b, nm.f("lane.ada"), RAD_BF16, { (int64_t)kMaxLanes * S, L * kSegs * m.Ws }, + /* The lane's tables, a cell a modulation group, kMaxSegs of them. */ + m.b_ada = decl_b(b, nm.f("lane.ada"), RAD_BF16, { (int64_t)kMaxLanes * S, L * kMaxSegs * m.Ws }, RAD_BUF_PERSIST); - m.b_nout = decl_b(b, nm.f("lane.nout"), RAD_BF16, { (int64_t)kMaxLanes * S, kSegs * 2 * D }, + m.b_nout = decl_b(b, nm.f("lane.nout"), RAD_BF16, { (int64_t)kMaxLanes * S, kMaxSegs * 2 * D }, RAD_BUF_PERSIST); const int64_t ada_rows = 6 * D; /* one modality's six vectors */ m.dit.resize((size_t)L); @@ -910,17 +1093,30 @@ static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { const char* bn = nm.f("%s.bias", base); RAD_ARCH_TRY(map_rows(b, wn, { { src_w, (int)(md * ada_rows), ada_rows } })); RAD_ARCH_TRY(map_rows(b, bn, { { src_b, (int)(md * ada_rows), ada_rows } })); - /* The row slice is mapped above (DenseFP8 takes that as its argument). */ - RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW, - grp_layer(grp), { src_w }, {}, true)); B.ada_b[md] = decl_w(b, bn, RAD_BF16, { m.Ws }, acc, RAD_SHARD_ROW, grp_layer(grp)); if (!B.ada_b[md]) return RAD_E_INVAL; - B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias", - RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), - RAD_INT("K", td), RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", "fp8a8")), - RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])), - { m.a_temb.q, m.a_temb.s }, { m.b_ada }); + if (G > 0) { + /* A curve's embedding is 8 wide, too narrow for E4M3 blocks: bf16 throughout. */ + B.ada_w[md] = decl_w(b, wn, RAD_BF16, { m.Ws, td }, acc, RAD_SHARD_ROW, + grp_layer(grp)); + if (!B.ada_w[md]) return RAD_E_INVAL; + B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), + RAD_INT("K", td), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.ada_w[md], B.ada_b[md])), + { m.a_temb.x }, { m.b_ada }); + } else { + /* The row slice is mapped above (DenseFP8 takes that as its argument). */ + RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW, + grp_layer(grp), { src_w }, {}, true)); + B.op_ada[md] = rw(b, RAD_OP(b, "gemm_nt_q_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", m.Ws), + RAD_INT("K", td), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8")), + RAD_WEIGHTS(B.ada[md].w, B.ada[md].s, B.ada_b[md])), + { m.a_temb.q, m.a_temb.s }, { m.b_ada }); + } if (!B.op_ada[md]) return RAD_E_INVAL; } } @@ -944,6 +1140,8 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { /* ---- the lanes' latents, and the first step's noise */ m.b_vstate = decl_b(b, nm.f("lane.video"), RAD_F32, { La * m.maxV, kPatchVals }, RAD_BUF_PERSIST); m.b_astate = decl_b(b, nm.f("lane.audio"), RAD_F32, { La * m.maxA, kAudioC }, RAD_BUF_PERSIST); + m.b_vx0 = decl_b(b, nm.f("lane.video.x0"), RAD_F32, { La * m.maxV, kPatchVals }, RAD_BUF_PERSIST); + m.b_ax0 = decl_b(b, nm.f("lane.audio.x0"), RAD_F32, { La * m.maxA, kAudioC }, RAD_BUF_PERSIST); m.op_rnd_v = rw(b, RAD_OP(b, "randn_lanes", RAD_PARAMS(RAD_RANGE("M", 1, m.maxV), RAD_INT("n", kPatchVals), RAD_INT("stride", m.maxV), RAD_STR("dtype", "f32")), @@ -956,8 +1154,8 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { { m.b_astate }, { m.b_astate }); /* ---- this step's modulation, every rank's share of it */ - const int64_t row = L * kSegs * m.Ws; - m.b_modg = decl_b(b, nm.f("dit.mod"), RAD_BF16, { (int64_t)g.world * L * kSegs, m.Ws }); + const int64_t row = L * kMaxSegs * m.Ws; + m.b_modg = decl_b(b, nm.f("dit.mod"), RAD_BF16, { (int64_t)g.world * L * kMaxSegs, m.Ws }); if (g.world > 1) m.op_modg = rw(b, RAD_OP(b, "all_gather", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -974,6 +1172,12 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { /* ---- the packed sequence: the lane's prompt rows, the soundtrack's and the video's latents * through their f32 projections, rounded to bf16 as the reference packs them */ m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + /* The linears' format, from block 0's down projection (one source, so declare() does not map + * it again), before the activations' codes are declared. An int8 DiT takes int8 activations, + * from the same producers as the E4M3 one. */ + RAD_ARCH_TRY(m.dit[0].down.probe(b, nm, g, nm.f("dit.blk.0.ffn_down"), + { nm.ckpt("transformer.transformer_blocks.0.ff.net.2.weight") })); + m.dit_i8 = m.dit[0].down.probed_i8; m.op_text = rw(b, RAD_OP(b, "lane_gather", RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxText), RAD_INT("n", D), RAD_INT("stride", (int64_t)kMaxText), @@ -990,7 +1194,9 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { return RAD_E_INVAL; /* ---- the blocks */ - RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D, 0, m.dit_i8, !m.dit_i8)); + /* rms_mod_quant_i8 writes a_hm's int8 codes, as rms_mod_quant_fp8 writes its E4M3 ones. */ + m.a_hm.q8_fed = m.dit_i8; /* With video sparse attention a fourth projection beside q, k and v gates the pooled-tile * attention into each row's output. */ const int64_t nparts = m.vsa ? 4 : 3; @@ -1004,26 +1210,30 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { m.b_v8 = decl_b(b, nm.f("dit.v8"), RAD_F8E4M3, { T, qd }); m.b_vs = decl_b(b, nm.f("dit.vs"), RAD_F32, { qd }); m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); - RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd, 0, m.dit_i8, !m.dit_i8)); + /* q_attn writes the int8 codes the output projection reads. */ + m.a_attn.q8_fed = m.dit_i8; m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); /* More than one rank: the all-reduces of b_ao's halves run on the second lane (step_dit). */ if (g.world > 1) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ao)); m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); - RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff, 0, m.dit_i8, !m.dit_i8)); const char* sections = nm.f("%lld %lld %lld", (long long)rf, (long long)rf, (long long)rf); const int64_t ff_all = g.n_ff_all; + /* A block's modulated norm: the previous block's delta added to `b_h`, the norm, and `a_hm`'s + * codes, int8 or E4M3, in one op. */ auto mod_q = [&](rad_weight w, bool gated) { - rad_op op = RAD_OP(b, "rms_mod_quant_fp8", + rad_op op = RAD_OP(b, m.dit_i8 ? "rms_mod_quant_i8" : "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_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)); if (!op) return op; rad_buf rd[3] = { m.b_modg, m.b_h, m.b_ao }; - rad_buf wr[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; rad_op_reads(b, op, rd, gated ? 3 : 2); + rad_buf wr[3] = { m.a_hm.cq(), m.a_hm.cs(), m.b_h }; rad_op_writes(b, op, wr, 3); return op; }; @@ -1131,11 +1341,17 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { B.op_mq2 = mod_q(B.w_n2, true); const char* fw = nm.f("%s.ffn_gate_up.weight", dn); const char* fsrc = nm.ckpt("%s.ff.net.0.proj.weight", pre); + /* The gate half first, as in the refiner. diffusers' SwiGLU (`ff.net.0.proj`) takes + * `value, gate = chunk(2)` and computes value * silu(gate), so the checkpoint stores the + * gate second, while silu_mul and gated_quant_fp8 gate with the first half. Left in + * checkpoint order, every frame renders as scrambled colour tiles. The int8 path's group + * scales are quantised from the mapped rows, so they follow the swap. */ RAD_ARCH_TRY(map_rows(b, fw, { { fsrc, (int)ff_all, ff_all }, { fsrc, 0, ff_all } })); B.gate_up.mapped = 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), { fsrc }, m.a_hm, m.b_gu, 0, { g.n_ff, g.n_ff })); + B.gq.silu_only = m.dit_i8; RAD_ARCH_TRY(B.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", 0, false)); 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.net.2.weight", pre) }, @@ -1195,7 +1411,19 @@ static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), { m.b_avel, m.b_astate }, { m.b_astate }); - return m.op_hcast && m.op_vout && m.op_aout && m.op_ev && m.op_ea ? RAD_OK : RAD_E_INVAL; + /* res_multistep reads and rewrites the last estimate as well as the latent. */ + m.op_rmv = rw(b, RAD_OP(b, "flow_res_multistep", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxV), RAD_INT("n", kPatchVals), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_vel, m.b_vx0, m.b_vstate }, { m.b_vx0, m.b_vstate }); + m.op_rma = rw(b, RAD_OP(b, "flow_res_multistep", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxA), RAD_INT("n", kAudioC), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_avel, m.b_ax0, m.b_astate }, { m.b_ax0, m.b_astate }); + return m.op_hcast && m.op_vout && m.op_aout && m.op_ev && m.op_ea && m.op_rmv && m.op_rma + ? RAD_OK : RAD_E_INVAL; } /* ================================================================== the audio decoder */ @@ -1847,6 +2075,726 @@ static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) { return RAD_OK; } +/* ================================================================== the VAE encoders */ +/* An encode pass's geometry (rad_arch_encode_geom). Vencode, 25 int32s: the five volumes (T, H, W) + * of the clip and after each downsampler, the fold's (frames, h, w) for a full and for the last + * clip, then the clip's frames, the clips, the padded frames and the latent frames. Aencode, 13: + * the padded samples, then each of the six stages' length as a {0, n} cu. */ +const int kVEncGeomN = 25, kAEncGeomN = 13; + +static bool venc_geom(int64_t frames, int64_t h, int64_t w, int32_t* out) { + if (frames < 1 || frames > kEncMaxFrames || h < kVaeRatio || w < kVaeRatio || + h % kVaeRatio || w % kVaeRatio) + return false; + const int64_t clip = frames == 1 ? 1 : kVaeClipLength; + const int64_t n_clips = frames == 1 ? 1 : (frames + kVaeClipLength - 1) / kVaeClipLength; + const int64_t t1 = (clip + 1) / 2, t2 = (t1 + 1) / 2; + /* Every level's volume fits its buffers (declare_venc's R): a video's clip at most 256 x 256, + * a single frame up to the canvas. The spatial divisors cancel, leaving the frames. */ + { + const int64_t tv[5] = { clip, clip, t1, t2, t2 }; + const int64_t tf5[5] = { kVaeClipLength, kVaeClipLength, (kVaeClipLength + 1) / 2, + ((kVaeClipLength + 1) / 2 + 1) / 2, + ((kVaeClipLength + 1) / 2 + 1) / 2 }; + for (int i = 0; i < 5; ++i) + if (tv[i] * h * w > std::max(tf5[i], (int64_t)kEncOneFrames) * + (int64_t)kEncMaxSide * kEncMaxSide) + return false; + } + const int64_t lat = vae_latent_frames(frames); + const int64_t full = vae_clip_latents(clip); + const int64_t last = lat - full * (n_clips - 1); + if (lat < 1 || full < 1 || last < 1 || last > full) return false; + if (!out) return true; + const int64_t g[5][3] = { { clip, h, w }, { clip, h / 2, w / 2 }, { t1, h / 4, w / 4 }, + { t2, h / 8, w / 8 }, { t2, h / 16, w / 16 } }; + int32_t* o = out; + for (const auto& v : g) + for (int64_t x : v) *o++ = (int32_t)x; + const int64_t f[2][3] = { { full, h / (kVaeRatio * kPatch), w / (kVaeRatio * kPatch) }, + { last, h / (kVaeRatio * kPatch), w / (kVaeRatio * kPatch) } }; + for (const auto& v : f) + for (int64_t x : v) *o++ = (int32_t)x; + *o++ = (int32_t)clip; + *o++ = (int32_t)n_clips; + *o++ = (int32_t)(n_clips * clip); + *o++ = (int32_t)lat; + return o - out == kVEncGeomN; +} + +static bool aenc_geom(int64_t samples, int64_t ch, int32_t* out) { + if (samples < 1 || samples > kEncMaxSamples || ch < 1 || ch > kAudioCh) return false; + const int64_t n0 = vae_audio_latents(samples) * kAudioHop; + if (n0 > kEncMaxSamples) return false; + if (!out) return true; + static const int64_t kStr[5] = { 2, 4, 4, 5, 5 }; + out[0] = (int32_t)n0; + int64_t n = n0; + for (int i = 0; i <= 5; ++i) { + out[1 + 2 * i] = 0; + out[2 + 2 * i] = (int32_t)n; + if (i < 5) n /= kStr[i]; + } + return true; +} + +/* A media's first row in b_evc / b_enca: nine pictures then three videos, three videos' + * soundtracks then three standalone ones. A request with keyframes carries no references, so + * its two keyframes take the first two pictures' rows. -1 for no slot. */ +static int64_t venc_slot_row(int32_t kind, int32_t slot) { + int64_t idx = -1; + if (kind == RAD_ENC_IMAGE && slot >= 1 && slot <= 9) idx = slot - 1; + else if (kind == RAD_ENC_KEYFRAME && slot >= 1 && slot <= 2) idx = slot - 1; + else if (kind == RAD_ENC_VIDEO && slot >= 1 && slot <= 3) idx = 9 + slot - 1; + return idx < 0 ? -1 : idx * (int64_t)kEncSlotRowsV; +} +static int64_t aenc_slot_row(int32_t kind, int32_t slot) { + int64_t idx = -1; + if (kind == RAD_ENC_VAUDIO && slot >= 1 && slot <= 3) idx = slot - 1; + else if (kind == RAD_ENC_AUDIO && slot >= 1 && slot <= 3) idx = 3 + slot - 1; + return idx < 0 ? -1 : idx * (int64_t)kEncSlotRowsA; +} + +/* The encoder's CausalConv3d: causal in time, reflect-padded in space, on bf16 rows. */ +static rad_op venc_conv(RadBuilder* b, int64_t M, int64_t cin, int64_t cout, int64_t k, + rad_weight w, rad_weight bias, rad_buf x, rad_buf res, rad_buf y) { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, M), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("kt", k), + RAD_INT("causal", 1), RAD_INT("reflect", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return res ? rw(b, op, { x, res }, { y }) : rw(b, op, { x }, { y }); +} + +/* GroupNorm over a level's whole clip volume, then SiLU. */ +static rad_op venc_gn(RadBuilder* b, int64_t M, int64_t n, int64_t G, double eps, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y, rad_buf st) { + if (!w || !bias) return 0; + const rad_op op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, M), RAD_INT("n", n), + RAD_INT("groups", G), RAD_F64("eps", eps), + RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + return rw(b, op, { x, st }, { y, st }); +} + +/* The video VAE's encoder (AutoencoderKLMiniMaxH3), when the container carries it: pixels in + * 0..255 normalised to bf16, then the levels a clip at a time, at the geometry `enc_geom_d` gives + * each pass. */ +static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + /* Whether the container has it, as the vision tower asks (rad_block_vit.h). */ + if (map_copy(b, nm.f("venc.cin.weight"), nm.ckpt("vae.encoder.conv_in.weight")) < 0) + return RAD_E_INVAL; + { + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("venc.cin.weight"), &enc, nullptr, nullptr) != RAD_OK) { + fprintf(stderr, "radiance: minimaxh3: the container ships no video VAE encoder; " + "declaring without it\n"); + return RAD_OK; + } + } + const std::vector dims = meta_list(meta, "vae.block_out_channels"); + const std::vector sds = meta_list(meta, "vae.spatial_downsample_factors"); + const std::vector tds = meta_list(meta, "vae.temporal_downsample_factors"); + const double eps = rad_meta_getf(meta, "vae.norm_eps", 1e-6); + const int64_t G = rad_meta_geti(meta, "vae.norm_num_groups", 32); + if (dims.size() != 6 || sds.size() != 6 || tds.size() != 6 || + rad_meta_geti(meta, "vae.layers_per_block", 2) != 2 || + rad_meta_geti(meta, "vae.clip_length", kVaeClipLength) != kVaeClipLength || + rad_meta_geti(meta, "vae.in_channels", 3) != 3 || + rad_meta_geti(meta, "vae.latent_channels", kC) != kC || + std::strcmp(rad_meta_gets(meta, "vae.spatial_padding_mode", "reflect"), "reflect") || + G < 1 || eps <= 0.0) { + fprintf(stderr, "radiance: minimaxh3: the video VAE is not the released encoder (six " + "levels of two blocks, 17-frame clips, reflect padding)\n"); + return RAD_E_UNSUPPORTED; + } + for (size_t i = 0; i < 6; ++i) + if ((int64_t)dims[i] % G || ((int64_t)sds[i] != 1 && (int64_t)sds[i] != 2) || + ((int64_t)tds[i] != 1 && (int64_t)tds[i] != 2)) + return RAD_E_UNSUPPORTED; + m.venc = true; + /* Read once a media, so they live in pinned host memory like the text encoder. */ + const int acc = RAD_ACCESS_PER_REQUEST; + const int gv = kGrpVenc; + auto wt = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_F32, shape, acc, gv); + }; + /* The 3x3x3 convolutions' weights, bf16 as the implicit-GEMM kernel stores them. */ + auto wb = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_BF16, shape, acc, gv); + }; + /* conv_in's and the k=1 convolutions', f32, read by a host kernel (kGrpVencH). */ + auto wh = [&](const char* dn, const char* src, std::initializer_list shape) { + return wcopy(b, dn, src, RAD_F32, shape, acc, kGrpVencH); + }; + + /* Each level's frames, rows and rows a frame: a full clip at 256 x 256, or a frame of the + * canvas, whichever is more. */ + int64_t tf[6], sd[6] = { 1, 1, 1, 1, 1, 1 }, R[6], PF[6]; + tf[0] = kVaeClipLength; + for (int i = 1; i < 6; ++i) { + tf[i] = (tf[i - 1] + (int64_t)tds[i - 1] - 1) / (int64_t)tds[i - 1]; + sd[i] = sd[i - 1] * (int64_t)sds[i - 1]; + } + const int64_t HW = kEncMaxSide * kEncMaxSide; + for (int i = 0; i < 6; ++i) { + PF[i] = HW / (sd[i] * sd[i]); + R[i] = std::max(tf[i], (int64_t)kEncOneFrames) * PF[i]; + } + const int64_t Rmax = R[0]; + + /* Pixels: f32 normalised, then bf16; the statistics every GroupNorm shares. */ + std::vector pm(3), pa(3); + for (int c = 0; c < 3; ++c) { + pm[(size_t)c] = 1.0 / (255.0 * kVaePixelStd[c]); + pa[(size_t)c] = -kVaePixelMean[c] / kVaePixelStd[c]; + } + m.ve_pix_mul = join_list(pm); + m.ve_pix_add = join_list(pa); + std::vector fm(kC), fa(kC); + for (int64_t c = 0; c < kC; ++c) { + fm[(size_t)c] = 1.0 / kVaeLatentsStd[c]; + fa[(size_t)c] = -kVaeLatentsMean[c] / kVaeLatentsStd[c]; + } + m.ve_fold_mul = join_list(fm); + m.ve_fold_add = join_list(fa); + m.b_epix32 = decl_b(b, nm.f("venc.pix32"), RAD_F32, { Rmax, 3 }); + m.b_epix = decl_b(b, nm.f("venc.pix"), RAD_BF16, { Rmax, 3 }); + m.b_egn = decl_b(b, nm.f("venc.gn"), RAD_F32, { G * (2 + 3 * 1024) }); + const rad_buf st = m.b_egn; + /* The tiled encode's two planes and the quant_conv are declared ahead of the trunk, and the + * tiled ops last. The arena packs by declared lifetime (core/build/rad_bufplan.cpp), and the + * tiled pass reruns the whole trunk once a tile while `b_vtile` holds every tile's pixels and + * `b_eqt` the finished tiles' moments, so both lifetimes must span the trunk's ops (from + * op_ve_pix's and op_ve_q's use to op_vt_crop and op_vt_join). */ + m.b_tplan = decl_b(b, nm.f("venc.tplan"), RAD_I32, { m.tiles, 22 }, RAD_BUF_PERSIST); + m.b_vtile = decl_b(b, nm.f("venc.vtile"), RAD_F32, + { m.tiles * (int64_t)kEncMaxSide * kEncMaxSide, 3 }); + m.b_eq48 = decl_b(b, nm.f("venc.q48"), RAD_BF16, { R[5], 48 }); + m.b_eq2 = decl_b(b, nm.f("venc.q"), RAD_BF16, { R[5], 48 }); + m.b_eqt = decl_b(b, nm.f("venc.qt"), RAD_BF16, { m.tiles * (int64_t)kTile * kTile, 48 }); + m.ve_qw = wh(nm.f("venc.q.weight"), nm.ckpt("vae.quant_conv.weight"), { 48, 48, 1, 1, 1 }); + m.ve_qb = wh(nm.f("venc.q.bias"), nm.ckpt("vae.quant_conv.bias"), { 48 }); + /* The whole-canvas pass writes b_eq2; the tiled pass writes a tile's slice of b_eqt, which + * op_vt_join blends into b_eq2. */ + m.op_ve_q = rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("cin", 48), + RAD_INT("cout", 48), RAD_INT("k", 1), RAD_INT("kt", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.ve_qw, m.ve_qb)), + { m.b_eq48 }, { m.b_eq2, m.b_eqt }); + if (!m.op_ve_q) return RAD_E_INVAL; + m.op_ve_pix = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), + RAD_STR("mul", m.ve_pix_mul.c_str()), + RAD_STR("add", m.ve_pix_add.c_str()), + RAD_STR("mode", "fma"), RAD_INT("round", 0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_vtile }, { m.b_epix32 }); + m.op_ve_pcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, Rmax), RAD_INT("n", 3), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_epix32 }, { m.b_epix }); + /* Mapped by the presence check above. */ + m.ve_cinw = decl_w(b, nm.f("venc.cin.weight"), RAD_F32, { (int64_t)dims[0], 3, 3, 3, 3 }, + acc, RAD_SHARD_NONE, grp_layer(kGrpVencH)); + m.ve_cinb = wh(nm.f("venc.cin.bias"), nm.ckpt("vae.encoder.conv_in.bias"), { (int64_t)dims[0] }); + if (!m.op_ve_pix || !m.op_ve_pcast) return RAD_E_INVAL; + m.v_lv.reserve(6); + for (int L = 0; L < 6; ++L) { + m.v_lv.emplace_back(); + Model::VEncLevel& E = m.v_lv.back(); + const int64_t cout = (int64_t)dims[L], cin = L == 0 ? cout : (int64_t)dims[L - 1]; + const bool sc = L > 0 && cout != cin; + E.cin = cin, E.cout = cout, E.rows = R[L], E.pf = PF[L], E.frames = tf[L]; + E.a = decl_b(b, nm.f("venc.l%d.a", L), RAD_BF16, { R[L], cout }); + E.b = decl_b(b, nm.f("venc.l%d.b", L), RAD_BF16, { R[L], cout }); + E.c = decl_b(b, nm.f("venc.l%d.c", L), RAD_BF16, { R[L], cout }); + /* A level that changes the width takes its input in a buffer of that width, which the + * downsampler before it writes, or which is the level before's stream where there is + * none. */ + if (sc) { + const bool dn_in = (int64_t)sds[L - 1] == 2 || (int64_t)tds[L - 1] == 2; + E.in = dn_in ? decl_b(b, nm.f("venc.l%d.in", L), RAD_BF16, { R[L], cin }) + : m.v_lv[(size_t)L - 1].a; + const char* sc_src = nm.ckpt("vae.encoder.down_blocks.%d.resnets.0.conv_shortcut", L); + E.scw = wh(nm.f("venc.l%d.sc.weight", L), nm.ckpt("%s.weight", sc_src), + { cout, cin, 1, 1, 1 }); + E.scb = wh(nm.f("venc.l%d.sc.bias", L), nm.ckpt("%s.bias", sc_src), { cout }); + if (!E.scw || !E.scb) return RAD_E_INVAL; + E.op_sc = rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, R[L]), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 1), + RAD_INT("kt", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.scw, E.scb)), + { E.in }, { E.a }); + if (!E.op_sc) return RAD_E_INVAL; + } + for (int blk = 0; blk < 2; ++blk) { + Model::VEncBlock& B = E.blk[blk]; + const char* bs = nm.ckpt("vae.encoder.down_blocks.%d.resnets.%d", L, blk); + /* norm1 at the block's input width: a widening level's first block normalises `in` + * in place. */ + const int64_t w1 = blk == 0 && sc ? cin : cout; + const rad_buf xa = blk == 0 && sc ? E.in : E.a; + const rad_buf nb = blk == 0 && sc ? E.in : E.b; + B.n1w = wt(nm.f("venc.l%d.b%d.n1w", L, blk), nm.ckpt("%s.norm1.weight", bs), { w1 }); + B.n1b = wt(nm.f("venc.l%d.b%d.n1b", L, blk), nm.ckpt("%s.norm1.bias", bs), { w1 }); + B.c1w = wb(nm.f("venc.l%d.b%d.c1w", L, blk), nm.ckpt("%s.conv1.weight", bs), { cout, w1, 3, 3, 3 }); + B.c1b = wt(nm.f("venc.l%d.b%d.c1b", L, blk), nm.ckpt("%s.conv1.bias", bs), { cout }); + B.n2w = wt(nm.f("venc.l%d.b%d.n2w", L, blk), nm.ckpt("%s.norm2.weight", bs), { cout }); + B.n2b = wt(nm.f("venc.l%d.b%d.n2b", L, blk), nm.ckpt("%s.norm2.bias", bs), { cout }); + B.c2w = wb(nm.f("venc.l%d.b%d.c2w", L, blk), nm.ckpt("%s.conv2.weight", bs), { cout, cout, 3, 3, 3 }); + B.c2b = wt(nm.f("venc.l%d.b%d.c2b", L, blk), nm.ckpt("%s.conv2.bias", bs), { cout }); + if (!B.n1w || !B.n1b || !B.c1w || !B.c1b || !B.n2w || !B.n2b || !B.c2w || !B.c2b) + return RAD_E_INVAL; + B.op_n1 = venc_gn(b, R[L], w1, G, eps, B.n1w, B.n1b, xa, nb, st); + B.op_c1 = venc_conv(b, R[L], w1, cout, 3, B.c1w, B.c1b, nb, 0, E.c); + B.op_n2 = venc_gn(b, R[L], cout, G, eps, B.n2w, B.n2b, E.c, E.b, st); + B.op_c2 = venc_conv(b, R[L], cout, cout, 3, B.c2w, B.c2b, E.b, E.a, E.a); + if (!B.op_n1 || !B.op_c1 || !B.op_n2 || !B.op_c2) return RAD_E_INVAL; + } + } + /* conv_in, into level 0. */ + m.op_ve_cin = venc_conv(b, Rmax, 3, (int64_t)dims[0], 3, m.ve_cinw, m.ve_cinb, m.b_epix, 0, + m.v_lv[0].a); + if (!m.op_ve_cin) return RAD_E_INVAL; + + /* The downsamplers after the first four levels (Downsample3D): padded below and right, + * strided in space and, where the config says, in time. */ + for (int L = 0; L < 4; ++L) { + Model::VEncLevel& E = m.v_lv[(size_t)L]; + Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const char* bs = nm.ckpt("vae.encoder.down_blocks.%d.downsamplers.0.conv", L); + E.dnw = wb(nm.f("venc.l%d.dnw", L), nm.ckpt("%s.weight", bs), { E.cout, E.cout, 3, 3, 3 }); + E.dnb = wt(nm.f("venc.l%d.dnb", L), nm.ckpt("%s.bias", bs), { E.cout }); + if (!E.dnw || !E.dnb) return RAD_E_INVAL; + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, E.rows), RAD_INT("cin", E.cout), + RAD_INT("cout", E.cout), RAD_INT("k", 3), + RAD_INT("kt", 3), RAD_INT("stride", (int64_t)sds[L]), + RAD_INT("stride_t", (int64_t)tds[L]), + RAD_INT("causal", 1), RAD_STR("pad", "down"), + RAD_INT("reflect", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.dnw, E.dnb)); + rad_buf y = X.op_sc ? X.in : X.a; + E.op_dn = rw(b, op, { E.a }, { y }); + if (!E.op_dn) return RAD_E_INVAL; + } + + /* norm_out, conv_out and quant_conv, then the fold of the means, the first 24 of the 48 + * columns, normalised into patch rows of 96. */ + m.ve_now = wt(nm.f("venc.nout.weight"), nm.ckpt("vae.encoder.norm_out.weight"), + { (int64_t)dims[5] }); + m.ve_nob = wt(nm.f("venc.nout.bias"), nm.ckpt("vae.encoder.norm_out.bias"), { (int64_t)dims[5] }); + m.op_ve_nout = venc_gn(b, R[5], (int64_t)dims[5], G, eps, m.ve_now, m.ve_nob, m.v_lv[5].a, + m.v_lv[5].b, st); + m.ve_coutw = wb(nm.f("venc.cout.weight"), nm.ckpt("vae.encoder.conv_out.weight"), + { 48, (int64_t)dims[5], 3, 3, 3 }); + m.ve_coutb = wt(nm.f("venc.cout.bias"), nm.ckpt("vae.encoder.conv_out.bias"), { 48 }); + m.op_ve_cout = venc_conv(b, R[5], (int64_t)dims[5], 48, 3, m.ve_coutw, m.ve_coutb, + m.v_lv[5].b, 0, m.b_eq48); + m.b_evc = decl_b(b, nm.f("lane.evc"), RAD_F32, + { (int64_t)kEncSlotsV * kEncSlotRowsV, kPatchVals }, RAD_BUF_PERSIST); + m.op_ve_fold = rw(b, RAD_OP(b, "patch_fold", + RAD_PARAMS(RAD_RANGE("M", 1, kEncSlotRowsV), RAD_INT("C", kC), + RAD_INT("pt", 1), RAD_INT("ph", kPatch), + RAD_INT("pw", kPatch), + RAD_STR("mul", m.ve_fold_mul.c_str()), + RAD_STR("add", m.ve_fold_add.c_str()), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_eq2 }, { m.b_evc }); + /* ComfyUI blends every visual condition's latents with noise, a r + (1 - a) z at a = 0.999 + * (_cond_video_rows); its audio conditions take none. z is stream 2 of the request's seed, + * restarted at each item, as ComfyUI reseeds each. */ + m.op_eaug = rw(b, RAD_OP(b, "cond_aug", + RAD_PARAMS(RAD_RANGE("M", 1, kEncSlotRowsV), RAD_INT("n", kPatchVals), + RAD_INT("stream", 2), RAD_F64("aug", 0.999), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_evc }, { m.b_evc }); + if (!m.op_ve_nout || !m.op_ve_cout || !m.op_ve_q || !m.op_ve_fold || !m.op_eaug) + return RAD_E_INVAL; + /* The tiled encode's ops, declared last: b_vtile and b_eqt then live across the whole trunk, + * which the tiled pass runs once a tile, so no trunk buffer shares their bytes. */ + m.op_vt_plan = rw(b, RAD_OP(b, "vtile_plan", + RAD_PARAMS(RAD_RANGE("M", 1, m.tiles), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), + RAD_INT("ratio", kVaeRatio)), + RAD_NOWEIGHTS), + {}, { m.b_tplan }); + m.op_vt_crop = rw(b, RAD_OP(b, "vtile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, m.tiles * (int64_t)kEncMaxSide * kEncMaxSide), + RAD_INT("tile", kTile), RAD_INT("overlap", kOverlap), + RAD_INT("ratio", kVaeRatio), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_vtile }); + m.op_vt_join = rw(b, RAD_OP(b, "vtile_join", + RAD_PARAMS(RAD_RANGE("M", 1, R[5]), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), RAD_INT("n", 48), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eqt }, { m.b_eq2 }); + if (!m.op_vt_plan || !m.op_vt_crop || !m.op_vt_join) return RAD_E_INVAL; + return RAD_OK; +} + +/* The audio VAE's encoder (audio_vae.py's Encoder and AttnProjection), when the container + * carries it, a channel at a time; the weight norms are folded at convert. */ +static int declare_aenc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + if (map_copy(b, nm.f("aenc.mp.weight"), nm.ckpt("audio_vae.mean_proj.weight")) < 0) + return RAD_E_INVAL; + { + RadEncoding enc; + if (rad_weight_encoding(b, nm.f("aenc.mp.weight"), &enc, nullptr, nullptr) != RAD_OK) { + fprintf(stderr, "radiance: minimaxh3: the container ships no audio VAE encoder; " + "declaring without it\n"); + return RAD_OK; + } + } + const std::vector rates = meta_list(meta, "audio_vae.encoder_rates"); + const int64_t ld = rad_meta_geti(meta, "audio_vae.latent_dim", 2048); + const std::vector mean = meta_list(meta, "audio_vae.latents_mean"); + const std::vector sd = meta_list(meta, "audio_vae.latents_std"); + const int64_t heads = rad_meta_geti(meta, "audio_vae.num_attention_heads", 8); + if (rates.size() != 5 || ld != 2048 || (int64_t)mean.size() != kAudioC || + (int64_t)sd.size() != kAudioC || heads != 8 || + rad_meta_geti(meta, "audio_vae.encoder_dim", 64) != 64 || + rad_meta_geti(meta, "audio_vae.latent_channels", kAudioC) != kAudioC) { + fprintf(stderr, "radiance: minimaxh3: the audio VAE is not the released encoder (five " + "strides to 800 samples a latent, eight attention heads)\n"); + return RAD_E_UNSUPPORTED; + } + m.aenc = true; + /* Read once a media, as the video encoder's. */ + const int acc = RAD_ACCESS_PER_REQUEST; + const int ga = kGrpAenc; + /* The snake alphas: `snake` in f32 is a host kernel (kGrpVencH). */ + const int gh = kGrpAencH; + static const int64_t kStr[5] = { 2, 4, 4, 5, 5 }; + for (int i = 0; i < 5; ++i) + if ((int64_t)rates[(size_t)i] != kStr[i]) return RAD_E_UNSUPPORTED; + int64_t nn[6], uu[5]; + nn[0] = kEncMaxSamples; + for (int i = 0; i < 5; ++i) nn[i + 1] = nn[i] / kStr[i]; + for (int i = 0; i < 5; ++i) uu[i] = 64 << i; + const int64_t hd = ld / 8; /* a head's width */ + + /* The latents' normalisation, the chain's last op. */ + std::vector nm_(kAudioC), na(kAudioC); + for (int64_t c = 0; c < kAudioC; ++c) { + nm_[(size_t)c] = 1.0 / sd[(size_t)c]; + na[(size_t)c] = -mean[(size_t)c] / sd[(size_t)c]; + } + m.ae_norm_mul = join_list(nm_); + m.ae_norm_add = join_list(na); + + /* conv_in: a sample a row. */ + const char* bs = nm.ckpt("audio_vae.encoder.block.0"); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.cin.weight"), nm.ckpt("%s.weight_g", bs), + nm.ckpt("%s.weight_v", bs))); + m.ae_cinw = decl_w(b, nm.f("aenc.cin.weight"), RAD_F32, { 64, 1, 7 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + m.ae_cinb = wcopy(b, nm.f("aenc.cin.bias"), nm.ckpt("%s.bias", bs), RAD_F32, { 64 }, acc, ga); + m.b_ax[0] = decl_b(b, nm.f("aenc.x0"), RAD_F32, { nn[0], 64 }); + if (!m.ae_cinw || !m.ae_cinb || !m.b_ax[0]) return RAD_E_INVAL; + m.op_ae_cin = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, nn[0]), RAD_INT("cin", 1), + RAD_INT("cout", 64), RAD_INT("k", 7), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_cinw, m.ae_cinb)), + {}, { m.b_ax[0] }); + if (!m.op_ae_cin) return RAD_E_INVAL; + + for (int blk = 0; blk < 5; ++blk) { + Model::AEncBlk& A = m.ae_blk[blk]; + const int64_t u = uu[blk], d = u * 2, np = nn[blk], no = nn[blk + 1]; + const int64_t s = kStr[blk]; + m.b_et1[blk] = decl_b(b, nm.f("aenc.t1_%d", blk), RAD_F32, { np, u }); + m.b_et2[blk] = decl_b(b, nm.f("aenc.t2_%d", blk), RAD_F32, { np, u }); + m.b_ax[blk + 1] = decl_b(b, nm.f("aenc.x%d", blk + 1), RAD_F32, { no, d }); + A.bi = decl_b(b, nm.f("aenc.bf1_%d", blk), RAD_BF16, { np, u }); + A.bo = decl_b(b, nm.f("aenc.bf2_%d", blk), RAD_BF16, { no, d }); + if (!m.b_et1[blk] || !m.b_et2[blk] || !m.b_ax[blk + 1] || !A.bi || !A.bo) + return RAD_E_INVAL; + const int64_t R = np; + /* Three units: snake, conv k7, snake, conv k1 with the residual. */ + for (int r = 0; r < 3; ++r) { + Model::AEncUnit& U = A.u[r]; + const char* us = nm.ckpt("audio_vae.encoder.block.%d.block.%d.block", blk + 1, r); + U.a1 = wcopy(b, nm.f("aenc.b%d.u%d.a1", blk, r), nm.ckpt("%s.0.alpha", us), RAD_F32, + { u }, acc, gh); + if (!U.a1) return RAD_E_INVAL; + U.op_a1 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.a1)), + { m.b_ax[blk] }, { m.b_et1[blk] }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.b%d.u%d.c1.weight", blk, r), + nm.ckpt("%s.1.weight_g", us), nm.ckpt("%s.1.weight_v", us))); + U.c1w = decl_w(b, nm.f("aenc.b%d.u%d.c1.weight", blk, r), RAD_F32, { u, u, 7 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + U.c1b = wcopy(b, nm.f("aenc.b%d.u%d.c1.bias", blk, r), nm.ckpt("%s.1.bias", us), + RAD_F32, { u }, acc, ga); + if (!U.c1w || !U.c1b) return RAD_E_INVAL; + U.op_c1 = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", u), RAD_INT("k", 7), + RAD_INT("dil", 2 * r + 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.c1w, U.c1b)), + { m.b_et1[blk] }, { m.b_et2[blk] }); + U.a2 = wcopy(b, nm.f("aenc.b%d.u%d.a2", blk, r), nm.ckpt("%s.2.alpha", us), RAD_F32, + { u }, acc, gh); + if (!U.a2) return RAD_E_INVAL; + U.op_a2 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.a2)), + { m.b_et2[blk] }, { m.b_et1[blk] }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.b%d.u%d.c2.weight", blk, r), + nm.ckpt("%s.3.weight_g", us), nm.ckpt("%s.3.weight_v", us))); + U.c2w = decl_w(b, nm.f("aenc.b%d.u%d.c2.weight", blk, r), RAD_F32, { u, u, 1 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + U.c2b = wcopy(b, nm.f("aenc.b%d.u%d.c2.bias", blk, r), nm.ckpt("%s.3.bias", us), + RAD_F32, { u }, acc, ga); + if (!U.c2w || !U.c2b) return RAD_E_INVAL; + U.op_c2 = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", u), RAD_INT("k", 1), + RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(U.c2w, U.c2b)), + { m.b_et1[blk], m.b_ax[blk] }, { m.b_ax[blk] }); + if (!U.op_a1 || !U.op_c1 || !U.op_a2 || !U.op_c2) return RAD_E_INVAL; + } + /* The block's last snake, then the strided convolution in bf16. */ + const char* ds = nm.ckpt("audio_vae.encoder.block.%d.block", blk + 1); + A.al = wcopy(b, nm.f("aenc.b%d.al", blk), nm.ckpt("%s.3.alpha", ds), RAD_F32, { u }, acc, + gh); + if (!A.al) return RAD_E_INVAL; + A.op_al = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(A.al)), + { m.b_ax[blk] }, { m.b_et1[blk] }); + A.op_ci = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", u), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_et1[blk] }, { A.bi }); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.d%d.w", blk), nm.ckpt("%s.4.weight_g", ds), + nm.ckpt("%s.4.weight_v", ds))); + A.dnw = decl_w(b, nm.f("aenc.d%d.w", blk), RAD_BF16, { d, u, 2 * s }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + RAD_ARCH_TRY(map_copy(b, nm.f("aenc.d%d.b", blk), nm.ckpt("%s.4.bias", ds))); + A.dnb = decl_w(b, nm.f("aenc.d%d.b", blk), RAD_BF16, { d }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + if (!A.dnw || !A.dnb) return RAD_E_INVAL; + A.op_dn = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", u), + RAD_INT("cout", d), RAD_INT("k", 2 * s), + RAD_INT("dil", 1), RAD_INT("stride", s), + RAD_INT("pad", (s + 1) / 2), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(A.dnw, A.dnb)), + { A.bi }, { A.bo }); + A.op_co = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, no), RAD_INT("n", d), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { A.bo }, { m.b_ax[blk + 1] }); + if (!A.op_al || !A.op_ci || !A.op_dn || !A.op_co) return RAD_E_INVAL; + } + + /* The last snake and convolution, then the attention block. */ + const int64_t T = nn[5]; + const char* f6 = nm.ckpt("audio_vae.encoder.block.6"); + const char* f7 = nm.ckpt("audio_vae.encoder.block.7"); + m.ae_al6 = wcopy(b, nm.f("aenc.al6"), nm.ckpt("%s.alpha", f6), RAD_F32, { ld }, acc, gh); + RAD_ARCH_TRY(map_wnorm(b, nm.f("aenc.fin.weight"), nm.ckpt("%s.weight_g", f7), + nm.ckpt("%s.weight_v", f7))); + m.ae_finw = decl_w(b, nm.f("aenc.fin.weight"), RAD_F32, { ld, ld, 3 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + m.ae_finb = wcopy(b, nm.f("aenc.fin.bias"), nm.ckpt("%s.bias", f7), RAD_F32, { ld }, acc, ga); + m.b_a6t = decl_b(b, nm.f("aenc.snk6"), RAD_F32, { T, ld }); + m.b_ax6 = decl_b(b, nm.f("aenc.x6"), RAD_F32, { T, ld }); + if (!m.ae_al6 || !m.ae_finw || !m.ae_finb || !m.b_a6t || !m.b_ax6) return RAD_E_INVAL; + m.op_ae_snk6 = rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", ld), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_al6)), + { m.b_ax[5] }, { m.b_a6t }); + m.op_ae_fin = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", ld), + RAD_INT("cout", ld), RAD_INT("k", 3), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_finw, m.ae_finb)), + { m.b_a6t }, { m.b_ax6 }); + if (!m.op_ae_snk6 || !m.op_ae_fin) return RAD_E_INVAL; + + /* The attention block, bf16: LayerNorms over the 2048-wide stream, qkv (the checkpoint's q, + * zero k and v biases joined), eight causal heads averaged, pooled to 32 and projected; then + * the gated MLP. */ + const char* pb = nm.ckpt("audio_vae.pre_block"); + auto pw_ = [&](const char* dn, const char* src, uint32_t dt, + std::initializer_list shape) { + return wcopy(b, nm.f("aenc.pb.%s", dn), nm.ckpt("%s.%s", pb, src), dt, shape, acc, ga); + }; + m.p_ln1w = pw_("ln1w", "norm1.weight", RAD_BF16, { ld }); + m.p_ln1b = pw_("ln1b", "norm1.bias", RAD_BF16, { ld }); + m.p_ln3w = pw_("ln3w", "norm3.weight", RAD_BF16, { ld }); + m.p_ln3b = pw_("ln3b", "norm3.bias", RAD_BF16, { ld }); + m.p_ln2w = pw_("ln2w", "norm2.weight", RAD_BF16, { kAudioC }); + m.p_ln2b = pw_("ln2b", "norm2.bias", RAD_BF16, { kAudioC }); + m.p_mlw = pw_("mlnw", "mlp.norm.weight", RAD_BF16, { kAudioC }); + m.p_mlb = pw_("mlnb", "mlp.norm.bias", RAD_BF16, { kAudioC }); + m.p_prw = pw_("prw", "proj.weight", RAD_BF16, { kAudioC, ld }); + m.p_prb = pw_("prb", "proj.bias", RAD_BF16, { kAudioC }); + m.p_apw = pw_("apw", "attn.proj.weight", RAD_BF16, { kAudioC, kAudioC }); + m.p_apb = pw_("apb", "attn.proj.bias", RAD_BF16, { kAudioC }); + m.p_w2w = pw_("w2w", "mlp.w2.weight", RAD_BF16, { kAudioC, 2 * kAudioC }); + m.p_w2b = pw_("w2b", "mlp.w2.bias", RAD_BF16, { kAudioC }); + if (!m.p_ln1w || !m.p_ln1b || !m.p_ln3w || !m.p_ln3b || !m.p_ln2w || !m.p_ln2b || + !m.p_mlw || !m.p_mlb || !m.p_prw || !m.p_prb || !m.p_apw || !m.p_apb || !m.p_w2w || + !m.p_w2b) + return RAD_E_INVAL; + RAD_ARCH_TRY(map_copy(b, nm.f("aenc.pb.qkvw"), nm.ckpt("%s.attn.qkv.weight", pb))); + m.p_qkvw = decl_w(b, nm.f("aenc.pb.qkvw"), RAD_BF16, { 3 * ld, ld }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.qkvb"), + { nm.ckpt("%s.attn.q_bias", pb), nm.ckpt("%s.attn.zero_k_bias", pb), + nm.ckpt("%s.attn.v_bias", pb) })); + m.p_qkvb = decl_w(b, nm.f("aenc.pb.qkvb"), RAD_BF16, { 3 * ld }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + /* w0 (the gate) then w1, as gelu_mul splits them. */ + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.guw"), + { nm.ckpt("%s.mlp.w0.weight", pb), nm.ckpt("%s.mlp.w1.weight", pb) })); + m.p_guw = decl_w(b, nm.f("aenc.pb.guw"), RAD_BF16, { 2 * kAudioC * 2, kAudioC }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + RAD_ARCH_TRY(map_concat(b, nm.f("aenc.pb.gub"), + { nm.ckpt("%s.mlp.w0.bias", pb), nm.ckpt("%s.mlp.w1.bias", pb) })); + m.p_gub = decl_w(b, nm.f("aenc.pb.gub"), RAD_BF16, { 2 * kAudioC * 2 }, acc, RAD_SHARD_NONE, + grp_layer(ga)); + if (!m.p_qkvw || !m.p_qkvb || !m.p_guw || !m.p_gub) return RAD_E_INVAL; + + m.b_apb = decl_b(b, nm.f("aenc.pb"), RAD_BF16, { T, ld }); + m.b_aln3 = decl_b(b, nm.f("aenc.ln3"), RAD_BF16, { T, ld }); + m.b_aqkv = decl_b(b, nm.f("aenc.qkv"), RAD_BF16, { T, 3 * ld }); + m.b_aatt = decl_b(b, nm.f("aenc.att"), RAD_BF16, { T, hd }); + m.b_ahsum = decl_b(b, nm.f("aenc.hsum"), RAD_BF16, { T, hd }); + m.b_apool = decl_b(b, nm.f("aenc.pool"), RAD_BF16, { T, kAudioC }); + m.b_eh = decl_b(b, nm.f("aenc.h"), RAD_BF16, { T, kAudioC }); + m.b_a32a = decl_b(b, nm.f("aenc.r32a"), RAD_BF16, { T, kAudioC }); + m.b_a32b = decl_b(b, nm.f("aenc.r32b"), RAD_BF16, { T, kAudioC }); + m.b_a32c = decl_b(b, nm.f("aenc.r32c"), RAD_BF16, { T, kAudioC }); + m.b_a32d = decl_b(b, nm.f("aenc.r32d"), RAD_BF16, { T, kAudioC }); + m.b_agu = decl_b(b, nm.f("aenc.gu"), RAD_BF16, { T, 4 * kAudioC }); + m.b_agu64 = decl_b(b, nm.f("aenc.gu64"), RAD_BF16, { T, 2 * kAudioC }); + m.b_ax2 = decl_b(b, nm.f("aenc.xfin"), RAD_BF16, { T, kAudioC }); + m.b_amb = decl_b(b, nm.f("aenc.mono"), RAD_F32, { T, kAudioC }); + m.b_amb2 = decl_b(b, nm.f("aenc.mp"), RAD_F32, { T, kAudioC }); + m.op_ae_cast6 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", ld), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_ax6 }, { m.b_apb }); + if (!m.op_ae_cast6) return RAD_E_INVAL; + auto ln = [&](rad_weight w, rad_weight b2, int64_t n, rad_buf x, rad_buf y) -> rad_op { + if (!w || !b2) return 0; + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, b2)), + { x }, { y }); + }; + auto gemm = [&](rad_weight w, rad_weight b2, int64_t N, int64_t K, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !b2) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, b2)), + { x }, { y }); + }; + m.p_op_ln3 = ln(m.p_ln3w, m.p_ln3b, ld, m.b_apb, m.b_aln3); + m.p_op_qkv = gemm(m.p_qkvw, m.p_qkvb, 3 * ld, ld, m.b_aln3, m.b_aqkv); + m.p_op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + /* The first head writes b_ahsum, the others b_aatt: both are outputs. */ + { m.b_aqkv }, { m.b_aatt, m.b_ahsum }); + m.p_op_pool = rw(b, RAD_OP(b, "pool_cols", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", hd), + RAD_INT("k", hd / kAudioC), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ahsum }, { m.b_apool }); + m.p_op_aproj = gemm(m.p_apw, m.p_apb, kAudioC, kAudioC, m.b_apool, m.b_a32a); + m.p_op_ln1 = ln(m.p_ln1w, m.p_ln1b, ld, m.b_apb, m.b_aln3); + m.p_op_proj = gemm(m.p_prw, m.p_prb, kAudioC, ld, m.b_aln3, m.b_eh); + m.p_op_hadd = add_op(b, T, kAudioC, "bf16", m.b_eh, m.b_a32a, m.b_a32b); + m.p_op_ln2 = ln(m.p_ln2w, m.p_ln2b, kAudioC, m.b_a32b, m.b_a32c); + m.p_op_mln = ln(m.p_mlw, m.p_mlb, kAudioC, m.b_a32c, m.b_a32d); + m.p_op_gu = gemm(m.p_guw, m.p_gub, 4 * kAudioC, kAudioC, m.b_a32d, m.b_agu); + m.p_op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 2 * kAudioC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_agu }, { m.b_agu64 }); + m.p_op_w2 = gemm(m.p_w2w, m.p_w2b, kAudioC, 2 * kAudioC, m.b_agu64, m.b_a32c); + m.p_op_xadd = add_op(b, T, kAudioC, "bf16", m.b_a32b, m.b_a32c, m.b_ax2); + /* The heads' mean: six adds into b_ahsum, and the seventh divides by eight. */ + m.p_op_hs = add_op(b, T, hd, "bf16", m.b_ahsum, m.b_aatt, m.b_ahsum); + m.p_op_hsd = add_div_op(b, T, hd, "bf16", m.b_ahsum, m.b_aatt, m.b_ahsum, 8.0); + if (!m.p_op_ln3 || !m.p_op_qkv || !m.p_op_attn || !m.p_op_pool || !m.p_op_aproj || + !m.p_op_ln1 || !m.p_op_proj || !m.p_op_hadd || !m.p_op_ln2 || !m.p_op_mln || !m.p_op_gu || + !m.p_op_act || !m.p_op_w2 || !m.p_op_xadd || !m.p_op_hs || !m.p_op_hsd) + return RAD_E_INVAL; + m.op_ae_castx = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kAudioC), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_ax2 }, { m.b_amb }); + if (!m.op_ae_castx) return RAD_E_INVAL; + /* Mapped by the presence check above. */ + m.ae_mpw = decl_w(b, nm.f("aenc.mp.weight"), RAD_F32, { kAudioC, kAudioC, 1 }, acc, + RAD_SHARD_NONE, grp_layer(ga)); + m.ae_mpb = wcopy(b, nm.f("aenc.mp.bias"), nm.ckpt("audio_vae.mean_proj.bias"), RAD_F32, + { kAudioC }, acc, ga); + if (!m.ae_mpw || !m.ae_mpb) return RAD_E_INVAL; + m.op_ae_mp = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", kAudioC), + RAD_INT("cout", kAudioC), RAD_INT("k", 1), + RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.ae_mpw, m.ae_mpb)), + { m.b_amb }, { m.b_amb2 }); + m.b_enca = decl_b(b, nm.f("lane.enca"), RAD_F32, + { (int64_t)kEncSlotsA * kEncSlotRowsA, kAudioC }, RAD_BUF_PERSIST); + m.op_ae_norm = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kAudioC), + RAD_STR("mul", m.ae_norm_mul.c_str()), + RAD_STR("add", m.ae_norm_add.c_str()), + RAD_STR("mode", "fma"), RAD_INT("round", 0), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_amb2 }, { m.b_enca }); + if (!m.op_ae_mp || !m.op_ae_norm || !m.b_enca) return RAD_E_INVAL; + return RAD_OK; +} + /* ================================================================== declare */ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx) return RAD_E_INVAL; @@ -1956,6 +2904,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_E_INVAL; } + /* The vision tower, when the checkpoint or container has its weights: every MiniMax-H3 config + * names one. */ + m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0; + if (m.media) { + if (m.tv.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpTower, true, true) != RAD_OK) + return RAD_E_UNSUPPORTED; + m.media = m.tv.on; + } + /* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */ m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D }, RAD_BUF_PERSIST); @@ -1966,12 +2923,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(declare_dit(b, meta, m)); if (m.dit[0].qkv.bf16) { fprintf(stderr, "radiance: minimaxh3: the DiT's linears are bf16; this plugin serves the " - "block-fp8 container (data/recipes/minimax-h3-fp8.recipe)\n"); + "block-fp8 container (data/recipes/minimax-h3-fp8.recipe) or the int8 one " + "(data/recipes/minimax-h3-w8a8.recipe)\n"); return RAD_E_UNSUPPORTED; } RAD_ARCH_TRY(declare_ups(b, meta, m)); RAD_ARCH_TRY(declare_audio(b, meta, m)); RAD_ARCH_TRY(declare_video(b, meta, m)); + RAD_ARCH_TRY(declare_venc(b, meta, m)); + RAD_ARCH_TRY(declare_aenc(b, meta, m)); if (!ctx->shape_probe) { RadVideoGenDecl d{}; @@ -2024,6 +2984,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.upscale_max = m.ups_max; d.upscale_refine = m.rungs.empty() ? kUpsRefineBase : kUpsRefineDistilled; } + /* Keyframes and reference media as far as the container has the encoders, and the + * vision tower for pictures. The counts are ComfyUI's ref2va workflow's. */ + if (m.venc) { + d.max_ref_images = m.media ? 9 : 0; + d.max_ref_videos = 3; + d.max_enc_frames = kEncMaxFrames; + d.max_enc_side = kEncMaxSide; + d.enc_ratio = kVaeRatio; + } + if (m.aenc) { + d.max_ref_audios = 3; + d.max_enc_samples = kEncMaxSamples; + } + if (m.venc || m.aenc) d.max_mod_cells = kMaxSegs; RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); } @@ -2041,6 +3015,64 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ================================================================== step */ +/* RadVideoGenBatch::ref_tab's reference kinds are the pack's. */ +static_assert((int)RAD_VREF_PICTURE == (int)kR2VRefImage && + (int)RAD_VREF_AUDIO == (int)kR2VRefAudioOnly && + (int)RAD_VREF_VIDEO == (int)kR2VRefVideo, "ref_tab kinds"); + +/* The packed sequence of a request with references (RadVideoGenBatch::ref_tab), as + * rad_arch_video_pack laid it out for the driver; false for a table the pack refuses. */ +static bool ref_pack_of(const RadVideoGeom* g, const int32_t* ref_tab, Ref2VAPack* p, + bool positions) { + const int32_t nr = ref_tab[0], nk = ref_tab[1]; + if (nr < 0 || nk < 0 || nr > 64 || nk > 2) return false; + std::vector refs; + std::vector keys; + const int32_t* w = ref_tab + 2; + for (int32_t i = 0; i < nr; ++i, w += 6) { + if (w[0] < RAD_VREF_PICTURE || w[0] > RAD_VREF_VIDEO || w[1] < 1) return false; + refs.push_back(Ref2VARef{ w[0], w[2], w[3], w[4], w[5] }); + } + /* A keyframe is a picture: its soundtrack has no slot to be encoded into. */ + for (int32_t i = 0; i < nk; ++i, w += 3) { + if (w[2] != 0) return false; + keys.push_back(Ref2VAKeyframe{ w[0], w[1], w[2] }); + } + const Ref2VAGeom pg{ (int)g->lat_frames, (int)g->lat_h, (int)g->lat_w, (int)g->n_audio }; + return ref2va_build((int)g->n_text, pg, keys, refs, p, positions) == 0; +} + +/* The prompt's vision pads, the table's tail after the keyframes: a count, then {start, length} + * of each picture's tokens. They read the video's projection, as ComfyUI tags them. */ +static std::vector ref_pads_of(const int32_t* ref_tab) { + const int32_t* w = ref_tab + 2 + 6 * (int64_t)ref_tab[0] + 3 * (int64_t)ref_tab[1]; + std::vector runs; + for (int32_t i = 0, n = w[0]; i < n; ++i) + runs.push_back({ w[1 + 2 * i], (int64_t)w[1 + 2 * i] + w[2 + 2 * i], 0 }); + return runs; +} + +/* Where each reference block's latents are, in the order the pack lays the blocks down: the + * keyframes, then the references, a video's soundtrack before the video. `audio` picks b_enca + * over b_evc; `row` is -1 for a slot no encode pass wrote. */ +struct RefPart { int audio; int64_t row; }; +static void ref_parts(const int32_t* ref_tab, std::vector* out) { + const int32_t nr = ref_tab[0], nk = ref_tab[1]; + for (int32_t i = 0; i < nk; ++i) out->push_back({ 0, venc_slot_row(RAD_ENC_KEYFRAME, i + 1) }); + const int32_t* w = ref_tab + 2; + for (int32_t i = 0; i < nr; ++i, w += 6) { + const int32_t kind = w[0], slot = w[1]; + if (kind == RAD_VREF_AUDIO) { + out->push_back({ 1, aenc_slot_row(RAD_ENC_AUDIO, slot) }); + } else if (kind == RAD_VREF_PICTURE) { + out->push_back({ 0, venc_slot_row(RAD_ENC_IMAGE, slot) }); + } else { + if (w[5] > 0) out->push_back({ 1, aenc_slot_row(RAD_ENC_VAUDIO, slot) }); + out->push_back({ 0, venc_slot_row(RAD_ENC_VIDEO, slot) }); + } + } +} + /* The conditioning pass: the text encoder, context_embedder and the refiner into the lane's prompt * rows, then every step's modulation into the lane's tables. */ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { @@ -2048,14 +3080,23 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { const Geom& g = m.gt; const int64_t T = batch->n_tok, lane = V->lane, S = V->n_steps; const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int64_t nmm = batch->n_mm_rows; + if (m.media && batch->enc_n_patch > 0) m.tv.step(c, batch); RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); - const RadOperand pos = praw(batch->positions, RAD_I32, T); + if (m.media && nmm > 0) + RAD_ISSUE_N(c, m.op_mm, nmm, brows(m.tv.b_out, nmm), praw(batch->mm_rows, RAD_I32, nmm), + brows(m.b_tx, T)); + /* A prompt with pictures has M-RoPE positions. */ + const RadOperand pos = batch->rope_pos ? praw2(batch->rope_pos, RAD_I32, 3, T) + : praw(batch->positions, RAD_I32, T); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); - for (const TeLayer& L : m.te) { + for (size_t li = 0; li < m.te.size(); ++li) { + const TeLayer& L = m.te[li]; RAD_ISSUE(c, L.op_n1, 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(c, L.op_qkr, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE(c, batch->rope_pos ? L.op_qkr_m : L.op_qkr, 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); @@ -2069,6 +3110,10 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { 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(c, L.op_add2, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + /* Deepstack: tap l joins the pictures' rows after layer l. */ + if (m.media && nmm > 0 && (int)li < m.tv.n_ds) + RAD_ISSUE_N(c, m.op_ds[li], nmm, brows(m.tv.b_ds[li], nmm), + praw(batch->mm_rows, RAD_I32, nmm), brows(m.b_tx, T)); } const Geom& r = m.gr; @@ -2097,39 +3142,80 @@ static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { RAD_ISSUE_N(c, m.op_fn, T, brows(m.b_rh, T), RAD_W(m.w_fn), brow_slice(m.b_text, lane * kMaxText, T, D)); - /* ---- every step's timestep embedding, video rows then soundtrack rows */ - const int64_t fd = 256, td = 2688, S2 = 2 * S; - RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), brow_slice(m.b_tproj, 0, S, fd)); - RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), brow_slice(m.b_tproj, S, S, fd)); - RAD_ISSUE_N(c, m.op_t1, S2, brows(m.b_tproj, S2), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, - brows(m.b_te1, S2)); - RAD_ISSUE_N(c, m.op_ts, S2, brows(m.b_te1, S2), brows(m.b_te1s, S2)); - RAD_ISSUE_N(c, m.op_t2, S2, brows(m.b_te1s, S2), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, - brows(m.b_temb, S2)); - RAD_ISSUE_N(c, m.op_ts2, S2, brows(m.b_temb, S2), brows(m.a_temb.x, S2)); - /* At its own rows: QuantFP8::step bands by the batch's tokens, which here are the prompt's, - * and the quantiser is declared for the 2 S rows of the steps' embeddings. */ - RAD_ISSUE_N(c, m.q_temb.op, S2, brows(m.a_temb.x, S2), brows(m.a_temb.cq(), S2), - brows(m.a_temb.cs(), S2)); + /* ---- every step's timestep embedding, the four blocks of declare_tables. At its own rows: + * QuantFP8::step bands by the rows it is issued for. */ + const int64_t fd = 256, td = m.temb_w, TT = 4 * S; + if (m.curve > 0) { + /* The table is operand 2, after the output. */ + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_temb, 0, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_temb, S, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_temb, 2 * S, S, td), RAD_W(m.w_ttable)); + RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_temb, 3 * S, S, td), RAD_W(m.w_ttable)); + } else { + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_video, RAD_F32, S), brow_slice(m.b_tproj, 0, S, fd)); + RAD_ISSUE_N(c, m.op_temb, S, praw(V->t_audio, RAD_F32, S), brow_slice(m.b_tproj, S, S, fd)); + RAD_ISSUE_N(c, m.op_temb_pv, S, praw(V->t_video, RAD_F32, S), + brow_slice(m.b_tproj, 2 * S, S, fd)); + RAD_ISSUE_N(c, m.op_temb_pa, S, praw(V->t_audio, RAD_F32, S), + brow_slice(m.b_tproj, 3 * S, S, fd)); + RAD_ISSUE_N(c, m.op_t1, TT, brows(m.b_tproj, TT), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, TT)); + RAD_ISSUE_N(c, m.op_ts, TT, brows(m.b_te1, TT), brows(m.b_te1s, TT)); + RAD_ISSUE_N(c, m.op_t2, TT, brows(m.b_te1s, TT), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, TT)); + RAD_ISSUE_N(c, m.op_ts2, TT, brows(m.b_temb, TT), brows(m.a_temb.x, TT)); + RAD_ISSUE_N(c, m.q_temb.op, TT, brows(m.a_temb.x, TT), brows(m.a_temb.cq(), TT), + brows(m.a_temb.cs(), TT)); + } - /* ---- the modulation table: block l, segment e from its modality's projection of its - * timestep's rows, at the table's column block (l, e) */ - const int64_t L = m.gd.n_layer, row = L * kSegs * m.Ws, base = lane * m.S; + /* ---- the modulation table: block l, cell e from its modality's projection of its + * timestep's rows, at the table's column block (l, e). A request with references has a cell + * for each distinct modulation its groups read (rad_ref2va_pack.h); every step's row is laid + * at the table's full width, kMaxSegs cells a block. */ + const int64_t L = m.gd.n_layer, base = lane * m.S; + std::vector> cell; + if (V->ref_tab) { + Ref2VAPack p; + Ref2VAModGroups grp; + if (!ref_pack_of(&V->geom, V->ref_tab, &p, false)) { + rad_step_fail(c, "minimaxh3: a reference table the pack refuses"); + return; + } + ref2va_mod_groups(p, S, ref_pads_of(V->ref_tab), &grp); + for (size_t i = 0; i < grp.md.size(); ++i) cell.emplace_back(grp.md[i], grp.r0[i]); + } else { + for (int e = 0; e < kSegs; ++e) + cell.emplace_back(kSegMod[e], e == kSegAudio ? S : 0); + } + const int64_t ncell = (int64_t)cell.size(); + if (ncell > kMaxSegs) { + rad_step_fail(c, "minimaxh3: the references read more modulations than the table holds"); + return; + } for (int64_t l = 0; l < L; ++l) { const DitBlock& B = m.dit[(size_t)l]; - for (int e = 0; e < kSegs; ++e) { - const int md = kSegMod[e]; - const int64_t r0 = e == kSegAudio ? S : 0; - RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td), - brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w), - RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), - bcol_at(m.b_ada, base, row, (l * kSegs + e) * m.Ws, m.Ws, S)); + for (int64_t e = 0; e < ncell; ++e) { + const int md = cell[(size_t)e].first; + const int64_t r0 = cell[(size_t)e].second; + const RadOperand out = + bcol_at(m.b_ada, base, L * kMaxSegs * m.Ws, (l * kMaxSegs + e) * m.Ws, m.Ws, S); + if (m.curve > 0) + RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.x, r0, S, td), + RAD_W(B.ada_w[md]), RAD_W(B.ada_b[md]), RAD_NONE, out); + else + RAD_ISSUE_N(c, B.op_ada[md], S, brow_slice(m.a_temb.q, r0, S, td), + brow_slice(m.a_temb.s, r0, S, td / RAD_FP8_BLOCK), RAD_W(B.ada[md].w), + RAD_W(B.ada[md].s), RAD_W(B.ada_b[md]), out); } } - for (int e = 0; e < kSegs; ++e) { - const int64_t r0 = e == kSegAudio ? S : 0; + for (int64_t e = 0; e < ncell; ++e) { + const int64_t r0 = cell[(size_t)e].second; RAD_ISSUE_N(c, m.op_no, S, brow_slice(m.a_temb.x, r0, S, td), RAD_W(m.w_no), RAD_W(m.b_no), - RAD_NONE, bcol_at(m.b_nout, base, kSegs * 2 * D, e * 2 * D, 2 * D, S)); + RAD_NONE, bcol_at(m.b_nout, base, (int64_t)kMaxSegs * 2 * D, e * 2 * D, 2 * D, S)); } } @@ -2139,10 +3225,35 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { const RadVideoGenBatch* V = batch->vgen_b; const Geom& g = m.gd; const int64_t R = batch->n_tok, lane = V->lane, nt = V->geom.n_text; - const int64_t arows = (int64_t)kAudioCh * V->geom.n_audio, vrows = R - nt - arows; + const int64_t arows = (int64_t)kAudioCh * V->geom.n_audio; const int64_t D = m.D, qd = g.q_dim(), L = g.n_layer, La = kMaxLanes; const RadOperand lane_d = praw(V->lane_d, RAD_I32, 1); + /* With references the sequence is the pack's: the reference blocks between the prompt and + * the two latents, which stay last, and the modulation in groups (rad_ref2va_pack.h). */ + Ref2VAPack pk; + Ref2VAModGroups grp; + int64_t ng = kSegs, ncell = kSegs, nfine = kSegs; + int64_t vrows = R - nt - arows, aseg = nt, vseg = nt + arows; + if (V->ref_tab) { + if (!ref_pack_of(&V->geom, V->ref_tab, &pk, false) || pk.rows != R) { + rad_step_fail(c, "minimaxh3: a step whose reference table is not its sequence"); + return; + } + ref2va_mod_groups(pk, m.S, ref_pads_of(V->ref_tab), &grp); + ng = (int64_t)grp.col.size(); + ncell = (int64_t)grp.md.size(); + if (ncell > kMaxSegs) { + rad_step_fail(c, "minimaxh3: the references read more modulations than the table holds"); + return; + } + nfine = (int64_t)pk.segs.size(); + const Ref2VASeg& vid = pk.segs.back(); + vrows = vid.end - vid.start; + aseg = pk.segs[pk.segs.size() - 2].start; + vseg = vid.start; + } + if (V->step == 0) { RAD_ISSUE_N(c, m.op_rnd_v, vrows, 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.maxV)); @@ -2150,47 +3261,80 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { praw(V->seed + 2, RAD_U32, 2), lane_d, praw(V->lat_cu + 2, RAD_I32, 2), brows(m.b_astate, La * m.maxA)); } - const int64_t row = L * kSegs * m.Ws, ti = lane * m.S + V->step; + /* The whole row whatever the groups: the gather's kernel is specialised to the width it was + * declared at. */ + const int64_t row = L * kMaxSegs * m.Ws, ti = lane * m.S + V->step; if (g.world > 1) RAD_ISSUE_N(c, m.op_modg, row, brow_slice(m.b_ada, ti, 1, row), - brows(m.b_modg, (int64_t)g.world * L * kSegs)); + brows(m.b_modg, (int64_t)g.world * L * kMaxSegs)); else RAD_ISSUE_N(c, m.op_modg, 1, brow_slice(m.b_ada, ti, 1, row), RAD_P_T2(rad_buf_ptr(c, m.b_modg), RAD_BF16, 1, row)); RAD_ISSUE_N(c, m.op_text, nt, brows(m.b_text, La * kMaxText), lane_d, praw(V->seg_cu, RAD_I32, 2), brows(m.b_h, nt)); + /* The two latents, through their input projections. */ RAD_ISSUE_N(c, m.op_ain, arows, brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC), - RAD_W(m.w_ain), RAD_W(m.b_ain), RAD_NONE, brow_slice(m.b_h, nt, arows, D)); + RAD_W(m.w_ain), RAD_W(m.b_ain), RAD_NONE, brow_slice(m.b_h, aseg, arows, D)); RAD_ISSUE_N(c, m.op_vin, vrows, brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals), - RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, brow_slice(m.b_h, nt + arows, vrows, D)); + RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, brow_slice(m.b_h, vseg, vrows, D)); + /* Then each keyframe's and reference's block, through the same projection from the rows its + * encode pass wrote. */ + if (V->ref_tab) { + std::vector parts; + ref_parts(V->ref_tab, &parts); + size_t pi = 0; + for (const Ref2VASeg& s : pk.segs) { + if (s.update || s.kind == kR2VText) continue; + const bool aud = ref2va_is_audio(s.kind) != 0; + const int64_t n = s.end - s.start; + if (pi >= parts.size() || parts[pi].row < 0 || (parts[pi].audio == 1) != aud) { + rad_step_fail(c, "minimaxh3: a reference block with no encoded latents"); + return; + } + const int64_t row = parts[pi++].row; + if (aud) + RAD_ISSUE_N(c, m.op_ain, n, brow_slice(m.b_enca, row, n, kAudioC), RAD_W(m.w_ain), + RAD_W(m.b_ain), RAD_NONE, brow_slice(m.b_h, s.start, n, D)); + else + RAD_ISSUE_N(c, m.op_vin, n, brow_slice(m.b_evc, row, n, kPatchVals), + RAD_W(m.w_vin), RAD_W(m.b_vin), RAD_NONE, + brow_slice(m.b_h, s.start, n, D)); + } + } - const RadOperand segs = praw(V->seg_cu, RAD_I32, kSegs + 1); + const RadOperand segs = praw(V->seg_cu, RAD_I32, nfine + 1); + /* The attention takes the segments, the modulated norms the modulation groups and, with + * references, the cell each group reads (mod_cu's tail). */ + const RadOperand mod_segs = praw(V->mod_cu, RAD_I32, ng + 1); + const RadOperand mod_col = V->ref_tab ? praw(V->mod_cu + ng + 1, RAD_I32, ng) : RAD_NONE; + const int64_t vcell = V->ref_tab ? grp.col.back() : kSegs - 1; const RadOperand geom = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); const RadOperand pos = praw2(V->pos, RAD_F32, 3, R); - /* Chunk k of block l's six, for the three segments: on rank k / (6 / world), at its column. */ + /* Chunk k of block l's six, for every group: on rank k / (6 / world), at its column. */ const int64_t per = 6 / g.world, nD = D / RAD_FP8_BLOCK; auto mod = [&](int64_t l, int k, int chunks) { const int64_t r = k / per; - return bcol_at(m.b_modg, r * L * kSegs + l * kSegs, m.Ws, (k % per) * D, chunks * D, kSegs); + return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs, m.Ws, (k % per) * D, chunks * D, + ncell); }; /* Two halves of the rows with more than one rank. Everything between two attentions is * row-local, so a half computes exactly the bits the whole would, and each half's all-reduces * run on lane 1 while lane 0 computes the other half; the attention stays whole. The second * half starts at the video's middle row, so it is video alone: the batch's one-sequence - * cu_seqlens and the video's modulation row stand for the segment table. Lane 0 waits for a - * half's all-reduce before its first reader, issued before the next all-reduce goes to lane 1 - * (a join orders a lane behind everything issued on the other). */ + * cu_seqlens and the video's modulation (its cell alone) stand for the tables. Lane 0 waits + * for a half's all-reduce before its first reader, issued before the next all-reduce goes to + * lane 1 (a join orders a lane behind everything issued on the other). */ const bool split = g.world > 1; - const int64_t cut = split ? nt + arows + vrows / 2 : R; + const int64_t cut = split ? vseg + vrows / 2 : R; const int64_t hr0[2] = { 0, cut }, hn[2] = { cut, R - cut }; const int nh = split ? 2 : 1; - const RadOperand segh[2] = { segs, cu }; + const RadOperand segh[2] = { mod_segs, cu }, colh[2] = { mod_col, RAD_NONE }; auto modh = [&](int h, int64_t l, int k, int chunks) { if (h == 0) return mod(l, k, chunks); const int64_t r = k / per; - return bcol_at(m.b_modg, r * L * kSegs + l * kSegs + kSegVideo, m.Ws, (k % per) * D, + return bcol_at(m.b_modg, r * L * kMaxSegs + l * kMaxSegs + vcell, m.Ws, (k % per) * D, chunks * D, 1); }; /* A half's partial sums across the ranks, kArRows rows a message, on lane 1 when split. */ @@ -2215,9 +3359,10 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { const int64_t r0 = hr0[h], n = hn[h]; if (h > 0 && l > 0) wait_ar(); RAD_ISSUE_N(c, B.op_mq1, n, l > 0 ? brow_slice(m.b_ao, r0, n, D) : RAD_NONE, - l > 0 ? modh(h, l - 1, 5, 1) : RAD_NONE, modh(h, l, 0, 2), RAD_W(B.w_n1), - segh[h], brow_slice(m.b_h, r0, n, D), brow_slice(m.a_hm.q, r0, n, D), - brow_slice(m.a_hm.s, r0, n, nD), RAD_NONE); + l > 0 ? modh(h, l - 1, 5, 1) : RAD_NONE, modh(h, l, 0, 2), + RAD_W(B.w_n1), segh[h], brow_slice(m.b_h, r0, n, D), + brow_slice(m.a_hm.cq(), r0, n, D), brow_slice(m.a_hm.cs(), r0, n, nD), + RAD_NONE, colh[h]); B.qkv.step(c, m.a_hm, m.b_qkv, R, r0, n); } RAD_ISSUE_N(c, B.op_qkr, R, bcol(m.b_qkv, 0, 3 * qd, R), pos, RAD_W(B.w_qn), @@ -2250,7 +3395,8 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { const int64_t r0 = hr0[h], n = hn[h]; RAD_ISSUE_N(c, B.op_mq2, n, brow_slice(m.b_ao, r0, n, D), modh(h, l, 2, 1), modh(h, l, 3, 2), RAD_W(B.w_n2), segh[h], brow_slice(m.b_h, r0, n, D), - brow_slice(m.a_hm.q, r0, n, D), brow_slice(m.a_hm.s, r0, n, nD), RAD_NONE); + brow_slice(m.a_hm.cq(), r0, n, D), brow_slice(m.a_hm.cs(), r0, n, nD), + RAD_NONE, colh[h]); B.gate_up.step(c, m.a_hm, m.b_gu, R, r0, n); B.gq.step(c, m.b_gu, R, r0, n); B.down.step(c, m.a_ffn, m.b_ao, R, r0, n); @@ -2259,11 +3405,12 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { } } wait_ar(); + /* Row (lane, step) of the table, kMaxSegs cells of 2 D. */ const char* nout = (const char*)rad_buf_ptr(c, m.b_nout) + - (lane * m.S + V->step) * kSegs * 2 * D * (int64_t)sizeof(uint16_t); + (lane * m.S + V->step) * (int64_t)kMaxSegs * 2 * D * (int64_t)sizeof(uint16_t); RAD_ISSUE_N(c, m.op_nout, R, brows(m.b_ao, R), mod(L - 1, 5, 1), - RAD_P_T2(nout, RAD_BF16, kSegs, 2 * D), RAD_W(m.w_no_n), segs, brows(m.b_h, R), - brows(m.b_hn, R)); + RAD_P_T2(nout, RAD_BF16, ncell, 2 * D), RAD_W(m.w_no_n), mod_segs, brows(m.b_h, R), + brows(m.b_hn, R), mod_col); /* The heads, in f32 over parts of the rows. */ auto heads = [&](rad_op op, rad_weight w, rad_weight bias, int64_t first, int64_t n, int64_t nout_c, @@ -2275,14 +3422,30 @@ static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { brow_slice(y, r0, k, nout_c)); } }; - heads(m.op_aout, m.w_aout, m.b_aout, nt, arows, kAudioC, m.b_avel); - heads(m.op_vout, m.w_vout, m.b_vout, nt + arows, vrows, kPatchVals, m.b_vel); - RAD_ISSUE_N(c, m.op_ev, vrows, brows(m.b_vel, vrows), praw(V->sched, RAD_F32, 1), - praw(V->sched + 1, RAD_F32, 1), praw(V->sched + 2, RAD_F32, 1), - brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals)); - RAD_ISSUE_N(c, m.op_ea, arows, brows(m.b_avel, arows), praw(V->sched + 3, RAD_F32, 1), - praw(V->sched + 4, RAD_F32, 1), praw(V->sched + 5, RAD_F32, 1), - brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); + heads(m.op_aout, m.w_aout, m.b_aout, aseg, arows, kAudioC, m.b_avel); + heads(m.op_vout, m.w_vout, m.b_vout, vseg, vrows, kPatchVals, m.b_vel); + /* The sampler's step (RadVideoGenBatch::sched and sampler). */ + if (V->sampler == RAD_SAMPLER_RES_MULTISTEP) { + RAD_ISSUE_N(c, m.op_rmv, vrows, brows(m.b_vel, vrows), + brow_slice(m.b_vx0, lane * m.maxV, vrows, kPatchVals), + praw(V->sched + 6, RAD_F32, 1), praw(V->sched + 7, RAD_F32, 1), + praw(V->sched + 8, RAD_F32, 1), praw(V->sched + 9, RAD_F32, 1), + praw(V->sched + 10, RAD_F32, 1), + brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals)); + RAD_ISSUE_N(c, m.op_rma, arows, brows(m.b_avel, arows), + brow_slice(m.b_ax0, lane * m.maxA, arows, kAudioC), + praw(V->sched + 11, RAD_F32, 1), praw(V->sched + 12, RAD_F32, 1), + praw(V->sched + 13, RAD_F32, 1), praw(V->sched + 14, RAD_F32, 1), + praw(V->sched + 15, RAD_F32, 1), + brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); + } else { + RAD_ISSUE_N(c, m.op_ev, vrows, brows(m.b_vel, vrows), praw(V->sched, RAD_F32, 1), + praw(V->sched + 1, RAD_F32, 1), praw(V->sched + 2, RAD_F32, 1), + brow_slice(m.b_vstate, lane * m.maxV, vrows, kPatchVals)); + RAD_ISSUE_N(c, m.op_ea, arows, brows(m.b_avel, arows), praw(V->sched + 3, RAD_F32, 1), + praw(V->sched + 4, RAD_F32, 1), praw(V->sched + 5, RAD_F32, 1), + brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); + } } /* The soundtrack: both channels, each a sequence, through the audio decoder, then interleaved. */ @@ -2466,6 +3629,310 @@ static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) { brow_slice(m.b_astate, lane * m.maxA, arows, kAudioC)); } +/* A picture larger than a tile, encoded as ComfyUI's vae.py tiled_encode does: overlapping tiles, + * each through the trunk alone (GroupNorm sees only its tile), and each tile's moments blended + * with its unblended top and left neighbours into the canvas (vtile_join). A tile's geometries are + * its row of b_tplan, which vtile_plan writes as vae.py splits. Returns the slot row past the + * media's latents. */ +static int64_t step_venc_tiled(RadCtx* c, const RadVideoGenBatch* V, const Model& m, + const int32_t* gd, int64_t H, int64_t W, int64_t ppc, + const RadOperand st, int64_t row0) { + const int64_t lat_h = H / kVaeRatio, lat_w = W / kVaeRatio; + const std::vector ty = tile_starts(lat_h), tx = tile_starts(lat_w); + const int64_t nh = (int64_t)ty.size(), nw = (int64_t)tx.size(), nt = nh * nw; + if (nt > m.tiles) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose picture splits into more tiles than " + "the encoder declares room for"); + return row0; + } + /* vtile_plan's split on the host: each tile's side in latents and its first row in the two + * tile-major planes. */ + struct Tile { int64_t prow, mrow, ny, nx; }; + std::vector tl; + tl.reserve((size_t)nt); + int64_t spx = 0, smom = 0; + for (int64_t i = 0; i < nh; ++i) + for (int64_t j = 0; j < nw; ++j) { + const int64_t ny = std::min((int64_t)kTile, lat_h - ty[(size_t)i]), + nx = std::min((int64_t)kTile, lat_w - tx[(size_t)j]); + tl.push_back({ spx, smom, ny, nx }); + spx += ny * nx * (int64_t)kVaeRatio * kVaeRatio; + smom += ny * nx; + } + RAD_ISSUE_N(c, m.op_vt_plan, nt, praw(gd, RAD_I32, 3), brows(m.b_tplan, nt)); + RAD_ISSUE_N(c, m.op_vt_crop, spx, praw2(V->enc_pixels, RAD_F32, H * W, 3), + praw(gd, RAD_I32, 3), brows(m.b_vtile, spx)); + const int32_t* tp = static_cast(rad_buf_ptr(c, m.b_tplan)); + for (size_t t = 0; t < tl.size(); ++t) { + const Tile& T = tl[t]; + const int64_t th = T.ny * kVaeRatio, tw = T.nx * kVaeRatio; /* the tile, in pixels */ + const int64_t Rpix = th * tw, R5 = T.ny * T.nx; + int64_t R[6]; + for (int L = 0; L < 6; ++L) { + const int64_t d = 1 << std::min(L, 4); /* the level's spatial divisor */ + R[L] = (th / d) * (tw / d); + } + /* The tile's plan row: its six {1, side, side} geometry entries, one frame deep. */ + const int32_t* tr = tp + 22 * (int64_t)t; + const RadOperand gg[6] = { praw(tr + 4, RAD_I32, 3), praw(tr + 7, RAD_I32, 3), + praw(tr + 10, RAD_I32, 3), praw(tr + 13, RAD_I32, 3), + praw(tr + 16, RAD_I32, 3), praw(tr + 19, RAD_I32, 3) }; + RAD_ISSUE_N(c, m.op_ve_pix, Rpix, brow_slice(m.b_vtile, T.prow, Rpix, 3), + brows(m.b_epix32, Rpix)); + RAD_ISSUE_N(c, m.op_ve_pcast, Rpix, brows(m.b_epix32, Rpix), brows(m.b_epix, Rpix)); + RAD_ISSUE_N(c, m.op_ve_cin, Rpix, brows(m.b_epix, Rpix), RAD_W(m.ve_cinw), + RAD_W(m.ve_cinb), gg[0], RAD_NONE, brows(m.v_lv[0].a, Rpix)); + for (int L = 0; L < 6; ++L) { + const Model::VEncLevel& E = m.v_lv[(size_t)L]; + const bool sc = E.op_sc; + for (int blk = 0; blk < 2; ++blk) { + const Model::VEncBlock& B = E.blk[blk]; + const bool f0 = blk == 0 && sc; + const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b; + /* The shortcut convolves the raw input, before norm1 (as in the plain loop). */ + if (f0) + RAD_ISSUE_N(c, E.op_sc, R[L], brows(E.in, R[L]), RAD_W(E.scw), RAD_W(E.scb), + gg[L], RAD_NONE, brows(E.a, R[L])); + RAD_ISSUE_N(c, B.op_n1, R[L], brows(xa, R[L]), RAD_W(B.n1w), RAD_W(B.n1b), + RAD_NONE, st, brows(nb, R[L])); + RAD_ISSUE_N(c, B.op_c1, R[L], brows(nb, R[L]), RAD_W(B.c1w), RAD_W(B.c1b), + gg[L], RAD_NONE, brows(E.c, R[L])); + RAD_ISSUE_N(c, B.op_n2, R[L], brows(E.c, R[L]), RAD_W(B.n2w), RAD_W(B.n2b), + RAD_NONE, st, brows(E.b, R[L])); + RAD_ISSUE_N(c, B.op_c2, R[L], brows(E.b, R[L]), RAD_W(B.c2w), RAD_W(B.c2b), + gg[L], brows(E.a, R[L]), brows(E.a, R[L])); + } + if (L < 4) { + const Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const rad_buf y = X.op_sc ? X.in : X.a; + RAD_ISSUE_N(c, E.op_dn, R[L + 1], brows(E.a, R[L]), RAD_W(E.dnw), RAD_W(E.dnb), + gg[L], RAD_NONE, brows(y, R[L + 1])); + } + } + RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob), + RAD_NONE, st, brows(m.v_lv[5].b, R5)); + RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw), + RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5)); + RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5], + RAD_NONE, brow_slice(m.b_eqt, T.mrow, R5, 48)); + } + /* The blend over the canvas (gd's level-4/5 entry, in latents), then the plain path's fold: + * the canvas has a one-clip encode's b_eq2 layout. */ + RAD_ISSUE_N(c, m.op_vt_join, lat_h * lat_w, brows(m.b_eqt, smom), praw(gd + 12, RAD_I32, 3), + brows(m.b_eq2, lat_h * lat_w)); + RAD_ISSUE_N(c, m.op_ve_fold, ppc, bcol(m.b_eq2, 0, kC, lat_h * lat_w), + praw(gd + 18, RAD_I32, 3), brow_slice(m.b_evc, row0, ppc, kPatchVals)); + return row0 + ppc; +} + + +/* A Vencode pass: each clip of `enc_pixels` through the levels, its latents folded into the + * media's slot of b_evc. The geometry is derived again from the batch, which checks it. */ +static void step_venc(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + int32_t g[25]; + if (!V->enc_pixels || + !venc_geom(V->enc_frames, V->enc_height, V->enc_width, g)) { + rad_step_fail(c, "minimaxh3: a Vencode pass with no pixels, or frames, height or width " + "the video encoder does not take"); + return; + } + const int64_t row0 = venc_slot_row(V->enc_kind, V->enc_slot); + if (row0 < 0) { + rad_step_fail(c, "minimaxh3: a Vencode pass naming an encode kind or slot this plugin " + "does not know"); + return; + } + if ((int64_t)V->enc_frames != g[23]) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose frames are not the clip-padded count " + "rad_arch_encode_geom reports"); + return; + } + const int32_t* gd = V->enc_geom_d; + const int64_t H = V->enc_height, W = V->enc_width; + const int64_t ppc = (H / (kVaeRatio * kPatch)) * (W / (kVaeRatio * kPatch)); + const int64_t n_clips = g[22], full = g[15], short_last = g[18]; + if ((full * (n_clips - 1) + short_last) * ppc > kEncSlotRowsV) { + rad_step_fail(c, "minimaxh3: a Vencode pass whose latents overflow the lane's slot"); + return; + } + const RadOperand st = RAD_B(m.b_egn); + /* Each level's volume in the geometry; the last two levels have no downsampler between + * them. */ + static const int kVOrg[6] = { 0, 3, 6, 9, 12, 12 }; + int64_t frow = row0; + /* A one-frame media larger than a tile goes through the tiled path, as vae.py tiles its image + * encodes; a clip never does, since venc_geom bounds its sides to kEncMaxSide. */ + const bool tiled = V->enc_frames == 1 && (H / kVaeRatio > kTile || W / kVaeRatio > kTile); + if (tiled) + frow = step_venc_tiled(c, V, m, gd, H, W, ppc, st, row0); + else + for (int64_t cc = 0; cc < n_clips; ++cc) { + const bool last = cc == n_clips - 1; + const int64_t R0 = (int64_t)g[0] * H * W; + const RadOperand gg[6] = { praw(gd + kVOrg[0], RAD_I32, 3), praw(gd + kVOrg[1], RAD_I32, 3), + praw(gd + kVOrg[2], RAD_I32, 3), praw(gd + kVOrg[3], RAD_I32, 3), + praw(gd + kVOrg[4], RAD_I32, 3), praw(gd + kVOrg[5], RAD_I32, 3) }; + RAD_ISSUE_N(c, m.op_ve_pix, R0, praw2(V->enc_pixels + cc * R0 * 3, RAD_F32, R0, 3), + brows(m.b_epix32, R0)); + RAD_ISSUE_N(c, m.op_ve_pcast, R0, brows(m.b_epix32, R0), brows(m.b_epix, R0)); + RAD_ISSUE_N(c, m.op_ve_cin, R0, brows(m.b_epix, R0), RAD_W(m.ve_cinw), RAD_W(m.ve_cinb), + gg[0], RAD_NONE, brows(m.v_lv[0].a, R0)); + for (int L = 0; L < 6; ++L) { + const Model::VEncLevel& E = m.v_lv[(size_t)L]; + const int64_t R = (int64_t)g[kVOrg[L]] * g[kVOrg[L] + 1] * g[kVOrg[L] + 2]; + const bool sc = E.op_sc; + for (int blk = 0; blk < 2; ++blk) { + const Model::VEncBlock& B = E.blk[blk]; + const bool f0 = blk == 0 && sc; + const rad_buf xa = f0 ? E.in : E.a, nb = f0 ? E.in : E.b; + /* The shortcut convolves the raw input, so it runs before norm1 normalises `in` in + * place. */ + if (f0) + RAD_ISSUE_N(c, E.op_sc, R, brows(E.in, R), RAD_W(E.scw), RAD_W(E.scb), gg[L], + RAD_NONE, brows(E.a, R)); + RAD_ISSUE_N(c, B.op_n1, R, brows(xa, R), RAD_W(B.n1w), RAD_W(B.n1b), RAD_NONE, st, + brows(nb, R)); + RAD_ISSUE_N(c, B.op_c1, R, brows(nb, R), RAD_W(B.c1w), RAD_W(B.c1b), gg[L], + RAD_NONE, brows(E.c, R)); + RAD_ISSUE_N(c, B.op_n2, R, brows(E.c, R), RAD_W(B.n2w), RAD_W(B.n2b), RAD_NONE, st, + brows(E.b, R)); + RAD_ISSUE_N(c, B.op_c2, R, brows(E.b, R), RAD_W(B.c2w), RAD_W(B.c2b), gg[L], + brows(E.a, R), brows(E.a, R)); + } + if (L < 4) { + const Model::VEncLevel& X = m.v_lv[(size_t)L + 1]; + const int64_t RX = (int64_t)g[3 * (L + 1)] * g[3 * (L + 1) + 1] * g[3 * (L + 1) + 2]; + const rad_buf y = X.op_sc ? X.in : X.a; + RAD_ISSUE_N(c, E.op_dn, RX, brows(E.a, R), RAD_W(E.dnw), RAD_W(E.dnb), gg[L], + RAD_NONE, brows(y, RX)); + } + } + const int64_t R5 = (int64_t)g[12] * g[13] * g[14]; + RAD_ISSUE_N(c, m.op_ve_nout, R5, brows(m.v_lv[5].a, R5), RAD_W(m.ve_now), RAD_W(m.ve_nob), + RAD_NONE, st, brows(m.v_lv[5].b, R5)); + RAD_ISSUE_N(c, m.op_ve_cout, R5, brows(m.v_lv[5].b, R5), RAD_W(m.ve_coutw), + RAD_W(m.ve_coutb), gg[5], RAD_NONE, brows(m.b_eq48, R5)); + RAD_ISSUE_N(c, m.op_ve_q, R5, brows(m.b_eq48, R5), RAD_W(m.ve_qw), RAD_W(m.ve_qb), gg[5], + RAD_NONE, brows(m.b_eq2, R5)); + const int64_t flat = last ? short_last : full; + RAD_ISSUE_N(c, m.op_ve_fold, flat * ppc, + bcol(m.b_eq2, 0, kC, flat * (H / kVaeRatio) * (W / kVaeRatio)), + praw(gd + (last ? 18 : 15), RAD_I32, 3), + brow_slice(m.b_evc, frow, flat * ppc, kPatchVals)); + frow += flat * ppc; + } + /* The condition noise over the item's rows, numbered from its first row (ComfyUI reseeds each + * item). b_evc persists, so once an encode is the blend every step reads. */ + if (frow > row0) + RAD_ISSUE_N(c, m.op_eaug, frow - row0, praw(V->seed, RAD_U32, 2), + brow_slice(m.b_evc, row0, frow - row0, kPatchVals)); +} + +/* An Aencode pass: each channel of `enc_samples` through the encoder, its latents into the media's + * slot of b_enca. The stages' lengths are the staged geometry's cus. */ +static void step_aenc(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + int32_t g[13]; + if (!V->enc_samples || !aenc_geom(V->enc_n_samples, V->enc_channels, g)) { + rad_step_fail(c, "minimaxh3: an Aencode pass with no samples, or a length and channel " + "count the audio encoder does not take"); + return; + } + const int64_t row0 = aenc_slot_row(V->enc_kind, V->enc_slot); + if (row0 < 0) { + rad_step_fail(c, "minimaxh3: an Aencode pass naming an encode kind or slot this plugin " + "does not know"); + return; + } + const int64_t n_pad = g[0]; + if ((int64_t)V->enc_n_samples != n_pad) { + rad_step_fail(c, "minimaxh3: an Aencode pass whose samples are not padded to the length " + "rad_arch_encode_geom reports"); + return; + } + const int32_t* gd = V->enc_geom_d; + const int64_t ld = 2048, hd = ld / 8; + const RadOperand cu6 = praw(gd + 11, RAD_I32, 2); + for (int32_t ch = 0; ch < V->enc_channels; ++ch) { + RAD_ISSUE_N(c, m.op_ae_cin, n_pad, praw2(V->enc_samples + ch * n_pad, RAD_F32, n_pad, 1), + RAD_W(m.ae_cinw), praw(gd + 1, RAD_I32, 2), RAD_NONE, + brows(m.b_ax[0], n_pad), RAD_W(m.ae_cinb)); + int64_t rows = n_pad; + for (int blk = 0; blk < 5; ++blk) { + const Model::AEncBlk& A = m.ae_blk[blk]; + const RadOperand cu = praw(gd + 1 + 2 * blk, RAD_I32, 2); + const int64_t R = rows, no = g[2 + 2 * (blk + 1)]; + const rad_buf S = m.b_ax[blk]; + for (int r = 0; r < 3; ++r) { + const Model::AEncUnit& U = A.u[r]; + RAD_ISSUE_N(c, U.op_a1, R, brows(S, R), RAD_W(U.a1), brows(m.b_et1[blk], R), + RAD_NONE); + RAD_ISSUE_N(c, U.op_c1, R, brows(m.b_et1[blk], R), RAD_W(U.c1w), cu, + RAD_NONE, brows(m.b_et2[blk], R), RAD_W(U.c1b)); + RAD_ISSUE_N(c, U.op_a2, R, brows(m.b_et2[blk], R), RAD_W(U.a2), + brows(m.b_et1[blk], R), RAD_NONE); + RAD_ISSUE_N(c, U.op_c2, R, brows(m.b_et1[blk], R), RAD_W(U.c2w), cu, + brows(S, R), brows(S, R), RAD_W(U.c2b)); + } + RAD_ISSUE_N(c, A.op_al, R, brows(S, R), RAD_W(A.al), brows(m.b_et1[blk], R), + RAD_NONE); + RAD_ISSUE_N(c, A.op_ci, R, brows(m.b_et1[blk], R), brows(A.bi, R)); + RAD_ISSUE_N(c, A.op_dn, no, brows(A.bi, R), RAD_W(A.dnw), cu, RAD_NONE, + brows(A.bo, no), RAD_W(A.dnb)); + RAD_ISSUE_N(c, A.op_co, no, brows(A.bo, no), brows(m.b_ax[blk + 1], no)); + rows = no; + } + RAD_ISSUE_N(c, m.op_ae_snk6, rows, brows(m.b_ax[5], rows), RAD_W(m.ae_al6), + brows(m.b_a6t, rows), RAD_NONE); + RAD_ISSUE_N(c, m.op_ae_fin, rows, brows(m.b_a6t, rows), RAD_W(m.ae_finw), cu6, + RAD_NONE, brows(m.b_ax6, rows), RAD_W(m.ae_finb)); + RAD_ISSUE_N(c, m.op_ae_cast6, rows, brows(m.b_ax6, rows), brows(m.b_apb, rows)); + /* The attention block. AttnProjection.forward feeds the attention from norm1 and the + * projection from norm3, and the two differ: each reads its own through b_aln3. */ + RAD_ISSUE_N(c, m.p_op_ln1, rows, brows(m.b_apb, rows), RAD_W(m.p_ln1w), RAD_W(m.p_ln1b), + brows(m.b_aln3, rows)); + RAD_ISSUE_N(c, m.p_op_qkv, rows, brows(m.b_aln3, rows), RAD_W(m.p_qkvw), RAD_W(m.p_qkvb), + RAD_NONE, brows(m.b_aqkv, rows)); + for (int h = 0; h < 8; ++h) { + /* The first head writes the sum, the next six add to it and the last divides it. */ + const rad_buf y = h == 0 ? m.b_ahsum : m.b_aatt; + RAD_ISSUE_N(c, m.p_op_attn, rows, bcol(m.b_aqkv, h * hd, hd, rows), + bcol(m.b_aqkv, ld + h * hd, hd, rows), + bcol(m.b_aqkv, 2 * ld + h * hd, hd, rows), cu6, brows(y, rows)); + if (h > 0) + RAD_ISSUE_N(c, h == 7 ? m.p_op_hsd : m.p_op_hs, rows, brows(m.b_ahsum, rows), + brows(m.b_aatt, rows), brows(m.b_ahsum, rows)); + } + RAD_ISSUE_N(c, m.p_op_pool, rows, brows(m.b_ahsum, rows), brows(m.b_apool, rows)); + RAD_ISSUE_N(c, m.p_op_aproj, rows, brows(m.b_apool, rows), RAD_W(m.p_apw), RAD_W(m.p_apb), + RAD_NONE, brows(m.b_a32a, rows)); + RAD_ISSUE_N(c, m.p_op_ln3, rows, brows(m.b_apb, rows), RAD_W(m.p_ln3w), RAD_W(m.p_ln3b), + brows(m.b_aln3, rows)); + RAD_ISSUE_N(c, m.p_op_proj, rows, brows(m.b_aln3, rows), RAD_W(m.p_prw), RAD_W(m.p_prb), + RAD_NONE, brows(m.b_eh, rows)); + RAD_ISSUE_N(c, m.p_op_hadd, rows, brows(m.b_eh, rows), brows(m.b_a32a, rows), + brows(m.b_a32b, rows)); + RAD_ISSUE_N(c, m.p_op_ln2, rows, brows(m.b_a32b, rows), RAD_W(m.p_ln2w), RAD_W(m.p_ln2b), + brows(m.b_a32c, rows)); + RAD_ISSUE_N(c, m.p_op_mln, rows, brows(m.b_a32c, rows), RAD_W(m.p_mlw), RAD_W(m.p_mlb), + brows(m.b_a32d, rows)); + RAD_ISSUE_N(c, m.p_op_gu, rows, brows(m.b_a32d, rows), RAD_W(m.p_guw), RAD_W(m.p_gub), + RAD_NONE, brows(m.b_agu, rows)); + RAD_ISSUE_N(c, m.p_op_act, rows, brows(m.b_agu, rows), brows(m.b_agu64, rows)); + RAD_ISSUE_N(c, m.p_op_w2, rows, brows(m.b_agu64, rows), RAD_W(m.p_w2w), RAD_W(m.p_w2b), + RAD_NONE, brows(m.b_a32c, rows)); + RAD_ISSUE_N(c, m.p_op_xadd, rows, brows(m.b_a32b, rows), brows(m.b_a32c, rows), + brows(m.b_ax2, rows)); + RAD_ISSUE_N(c, m.op_ae_castx, rows, brows(m.b_ax2, rows), brows(m.b_amb, rows)); + RAD_ISSUE_N(c, m.op_ae_mp, rows, brows(m.b_amb, rows), RAD_W(m.ae_mpw), cu6, + RAD_NONE, brows(m.b_amb2, rows), RAD_W(m.ae_mpb)); + RAD_ISSUE_N(c, m.op_ae_norm, rows, brows(m.b_amb2, rows), + brow_slice(m.b_enca, row0 + (int64_t)ch * (kEncSlotRowsA / (int64_t)kAudioCh), + rows, kAudioC)); + } +} + static void step(RadCtx* c, const RadBatch* batch) { const Model& m = g_model[rad_rank(c)]; if (!batch->gen || !batch->vgen_b) { @@ -2485,6 +3952,22 @@ static void step(RadCtx* c, const RadBatch* batch) { } step_upscale(c, batch, m); return; + case RAD_GEN_PASS_VENCODE: + if (!m.venc) { + rad_step_fail(c, "minimaxh3: a Vencode pass, and this container has no video VAE " + "encoder"); + return; + } + step_venc(c, batch, m); + return; + case RAD_GEN_PASS_AENCODE: + if (!m.aenc) { + rad_step_fail(c, "minimaxh3: an Aencode pass, and this container has no audio VAE " + "encoder"); + return; + } + step_aenc(c, batch, m); + return; default: rad_step_fail(c, "minimaxh3: a generator pass of a kind this plugin does not know"); } @@ -2505,9 +3988,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PROBE(minimaxh3) RAD_ARCH_PLUGIN(minimaxh3, "minimaxh3", "", "0.1.0", - "MiniMax-H3 (t2va): Qwen3-VL-32B conditioning, a 33B single-stream diffusion " - "transformer over text, soundtrack and video, a tiled ViT video decoder and a " - "BigVGAN audio decoder; block-fp8 linears") + "MiniMax-H3 (t2va, i2va, l2va, fl2va, ref2va): Qwen3-VL-32B conditioning, a 33B " + "single-stream diffusion transformer over text, soundtrack and video, a tiled ViT " + "video decoder, a BigVGAN audio decoder and the VAEs' encoders; block-fp8 or " + "int8 linears") extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) { @@ -2516,4 +4000,48 @@ extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, fl if (which == RAD_VPOS_DECODE) return minimaxh3::decode_rows(g); return RAD_E_INVAL; } + +/* The encode passes' geometry (kVEncGeomN, kAEncGeomN above); the steps derive it again from the + * batch's own fields. */ +extern "C" int64_t rad_arch_encode_geom(int32_t kind, const int64_t* in, int32_t* out, + int64_t cap) { + using namespace minimaxh3; + if (!in) return RAD_E_INVAL; + const bool video = kind == RAD_GEN_PASS_VENCODE; + if (!video && kind != RAD_GEN_PASS_AENCODE) return RAD_E_INVAL; + const int64_t n = video ? kVEncGeomN : kAEncGeomN; + if (out && cap < n) return RAD_E_INVAL; + const bool ok = video ? venc_geom(in[0], in[1], in[2], out) : aenc_geom(in[0], in[3], out); + return ok ? n : (int64_t)RAD_E_INVAL; +} + +extern "C" int64_t rad_arch_video_pack(const RadVideoGeom* g, const int32_t* ref_tab, + int32_t* seg, int32_t* n_seg, int32_t* mod, + int32_t* n_mod, float* pos, int64_t cap_pos) { + using namespace minimaxh3; + if (!g || !ref_tab || g->n_text < 1 || g->n_text > kMaxText || g->lat_frames < 1 || + g->lat_h < kPatch || g->lat_w < kPatch || g->n_audio < 1) + return RAD_E_INVAL; + Ref2VAPack p; + if (!ref_pack_of(g, ref_tab, &p, pos != nullptr)) return RAD_E_INVAL; + Ref2VAModGroups grp; + ref2va_mod_groups(p, 1, ref_pads_of(ref_tab), &grp); + const int32_t ns = (int32_t)p.segs.size() + 1, nb = (int32_t)grp.bound.size(); + const int32_t nm = nb + (int32_t)grp.col.size(); + if ((seg && (!n_seg || *n_seg < ns)) || (mod && (!n_mod || *n_mod < nm)) || + (pos && cap_pos < 3 * p.rows)) + return RAD_E_INVAL; + if (seg) { + for (int32_t k = 0; k + 1 < ns; ++k) seg[k] = (int32_t)p.segs[(size_t)k].start; + seg[ns - 1] = (int32_t)p.rows; + } + if (mod) { + for (int32_t k = 0; k < nb; ++k) mod[k] = (int32_t)grp.bound[(size_t)k]; + for (size_t k = 0; k < grp.col.size(); ++k) mod[nb + k] = grp.col[k]; + } + if (pos) std::copy(p.pos.begin(), p.pos.end(), pos); + if (n_seg) *n_seg = ns; + if (n_mod) *n_mod = nm; + return p.rows; +} #endif diff --git a/arch/minimaxh3/rad_ref2va_pack.cpp b/arch/minimaxh3/rad_ref2va_pack.cpp new file mode 100644 index 00000000..0f7994b0 --- /dev/null +++ b/arch/minimaxh3/rad_ref2va_pack.cpp @@ -0,0 +1,301 @@ +/* rad_ref2va_pack.cpp -- see rad_ref2va_pack.h. The positions are computed in f64 as ComfyUI + * computes them and stored in f32. */ + +#include "rad_ref2va_pack.h" + +#include +#include + +namespace minimaxh3 { + +/* The pixel frames the k-th latent frame of a video covers, cycling, and the time a pixel frame + * spans in soundtrack latents. */ +static const int kFramePerToken[5] = { 1, 4, 4, 4, 4 }; +static const double kFrameRescale = 5.0 / 3.0; + +int ref2va_seg_tag(int kind) { + switch (kind) { + case kR2VText: return 1; + case kR2VAudio: case kR2VCondAudio: case kR2VRefAudio: return 2; + default: return 0; + } +} + +int ref2va_is_img(int kind) { + return kind == kR2VCond || kind == kR2VRefImg || kind == kR2VVideo; +} + +int ref2va_is_audio(int kind) { + return kind == kR2VCondAudio || kind == kR2VRefAudio || kind == kR2VAudio; +} + +/* A side of `dim` latents in 2x2 patches: dim / 2 positions over + * [(1 - ratio) / 2, (1 + ratio) / 2) x 32, ratio = dim / sqrt(h w), so every aspect spans the same + * area. */ +static std::vector axis_from_sqrt_area(int dim, int patch, double sqrt_area) { + const double ratio = (double)dim / sqrt_area; + const int n = dim / patch; + std::vector v((size_t)n); + for (int i = 0; i < n; ++i) + v[(size_t)i] = ((double)i * (ratio / n) + (1.0 - ratio) / 2.0) * 32.0; + return v; +} + +/* A latent frame's patches as (row, column) pairs, row-major, and the column axis, whose ends the + * two soundtrack channels sit at. */ +static void frame_grid(int h, int w, std::vector* frame, std::vector* w_grid) { + const double area = std::sqrt((double)h * (double)w); + std::vector hg = axis_from_sqrt_area(h, 2, area), wg = axis_from_sqrt_area(w, 2, area); + frame->clear(); + frame->reserve(hg.size() * wg.size() * 2); + for (const double& r : hg) + for (const double& c : wg) { frame->push_back(r); frame->push_back(c); } + *w_grid = std::move(wg); +} + +/* The time n latent frames of video span. */ +static double video_t_span_sum(int n) { + double s = 0.0; + for (int k = 0; k < n; ++k) s += kFrameRescale * (double)kFramePerToken[k % 5]; + return s; +} + +/* Each latent frame's time: where the frames before it end. */ +static std::vector video_t_grid(int n, double origin) { + std::vector g((size_t)n); + double t = origin; + for (int k = 0; k < n; ++k) { + g[(size_t)k] = t; + t += kFrameRescale * (double)kFramePerToken[k % 5]; + } + return g; +} + +/* The time a reference spans: a picture 1, a soundtrack its length, a video the longer of its two + * streams. */ +static double ref_t_span(const Ref2VARef& r) { + if (r.kind == kR2VRefImage) return 1.0; + if (r.kind == kR2VRefAudioOnly) return (double)r.audio_t; + return std::max((double)r.audio_t, video_t_span_sum(r.latent_t)); +} + +/* A soundtrack's rows, the first channel's then the second's, a latent each at `cursor` onwards; + * the channels sit at the two ends of the width axis, row 0. */ +static void audio_grid(double cursor, int t, double w_low, double w_high, std::vector* pos) { + if (!pos) return; + for (int ch = 0; ch < 2; ++ch) { + const double w = ch == 0 ? w_low : w_high; + for (int i = 0; i < t; ++i) { + pos->push_back((float)(cursor + (double)i)); + pos->push_back(0.0f); + pos->push_back((float)w); + } + } +} + +/* A video's rows: each latent frame's patches at its time. */ +static void video_grid(int vt, const std::vector& frame, double origin, + std::vector* pos) { + if (!pos) return; + const std::vector tg = video_t_grid(vt, origin); + for (int k = 0; k < vt; ++k) + for (size_t j = 0; j < frame.size(); j += 2) { + pos->push_back((float)tg[(size_t)k]); + pos->push_back((float)frame[j]); + pos->push_back((float)frame[j + 1]); + } +} + +int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector& keyframes, + const std::vector& refs, Ref2VAPack* out, bool positions) { + if (text_len < 0 || g.latent_t < 0 || g.latent_h < 0 || g.latent_w < 0 || g.audio_t < 0) + return -1; + for (const Ref2VAKeyframe& kf : keyframes) + if (kf.frame < 0 || kf.video_t < 0 || kf.audio_t < 0) return -1; + for (const Ref2VARef& r : refs) { + if (r.kind < kR2VRefImage || r.kind > kR2VRefVideoAudio) return -1; + if (r.lat_h < 0 || r.lat_w < 0 || r.latent_t < 0 || r.audio_t < 0) return -1; + } + + Ref2VAPack p; + std::vector frame, w_grid; + frame_grid(g.latent_h, g.latent_w, &frame, &w_grid); + const size_t frame_rows = frame.size() / 2; + const double w_low = w_grid.empty() ? 0.0 : w_grid.front(); + const double w_high = w_grid.empty() ? 0.0 : w_grid.back(); + + /* The prompt: its token positions on the time axis. */ + p.segs.push_back({ kR2VText, 0, (int64_t)text_len, 0 }); + std::vector* pos = positions ? &p.pos : nullptr; + for (int i = 0; i < text_len && pos; ++i) { + p.pos.push_back((float)i); + p.pos.push_back(0.0f); + p.pos.push_back(0.0f); + } + int64_t row = text_len; + + /* The video's clock, and the keyframes on it, starts after every reference's span. */ + double cursor = (double)text_len; + for (const Ref2VARef& r : refs) cursor += ref_t_span(r); + + /* A keyframe is on the video's grid, at its frame's time. */ + for (const Ref2VAKeyframe& kf : keyframes) { + const double cond_t = cursor + kFrameRescale * (double)kf.frame; + if (kf.video_t > 0) { + const int64_t n = (int64_t)kf.video_t * (int64_t)frame_rows; + video_grid(kf.video_t, frame, cond_t, pos); + p.segs.push_back({ kR2VCond, row, row + n, 0 }); + row += n; + } + if (kf.audio_t > 0) { + const int64_t n = (int64_t)kf.audio_t * 2; + audio_grid(cond_t, kf.audio_t, w_low, w_high, pos); + p.segs.push_back({ kR2VCondAudio, row, row + n, 0 }); + row += n; + } + } + + /* The references in request order, each after the last. */ + cursor = (double)text_len; + for (const Ref2VARef& r : refs) { + if (r.kind == kR2VRefImage) { + std::vector rf, rw; + frame_grid(r.lat_h, r.lat_w, &rf, &rw); + const int64_t n = (int64_t)rf.size() / 2; + for (int64_t i = 0; i < n && pos; ++i) { + p.pos.push_back((float)cursor); + p.pos.push_back((float)rf[(size_t)i * 2]); + p.pos.push_back((float)rf[(size_t)i * 2 + 1]); + } + p.segs.push_back({ kR2VRefImg, row, row + n, 0 }); + row += n; + cursor += 1.0; + } else if (r.kind == kR2VRefAudioOnly) { + if (r.audio_t > 0) { + const int64_t n = (int64_t)r.audio_t * 2; + audio_grid(cursor, r.audio_t, w_low, w_high, pos); + p.segs.push_back({ kR2VRefAudio, row, row + n, 0 }); + row += n; + } + cursor += (double)r.audio_t; + } else { + /* A video's soundtrack, at the video's time and the ends of the video's own width + * axis, comes right before it. */ + std::vector rf, rw; + frame_grid(r.lat_h, r.lat_w, &rf, &rw); + if (r.audio_t > 0) { + const int64_t n = (int64_t)r.audio_t * 2; + audio_grid(cursor, r.audio_t, rw.empty() ? 0.0 : rw.front(), + rw.empty() ? 0.0 : rw.back(), pos); + p.segs.push_back({ kR2VRefAudio, row, row + n, 0 }); + row += n; + } + const int64_t n = (int64_t)r.latent_t * (int64_t)(rf.size() / 2); + video_grid(r.latent_t, rf, cursor, pos); + p.segs.push_back({ kR2VRefImg, row, row + n, 0 }); + row += n; + cursor += std::max((double)r.audio_t, video_t_span_sum(r.latent_t)); + } + } + + /* The soundtrack and the video the sampler steps, last. */ + { + const int64_t n = (int64_t)g.audio_t * 2; + audio_grid(cursor, g.audio_t, w_low, w_high, pos); + p.segs.push_back({ kR2VAudio, row, row + n, 1 }); + row += n; + } + { + const int64_t n = (int64_t)g.latent_t * (int64_t)frame_rows; + video_grid(g.latent_t, frame, cursor, pos); + p.segs.push_back({ kR2VVideo, row, row + n, 1 }); + row += n; + } + + p.rows = row; + if (positions) { + /* From (t, h, w) triples to [3, rows]. */ + std::vector tri = std::move(p.pos); + p.pos.assign((size_t)row * 3, 0.0f); + for (int64_t r = 0; r < row; ++r) { + p.pos[(size_t)r] = tri[(size_t)r * 3]; + p.pos[(size_t)row + r] = tri[(size_t)r * 3 + 1]; + p.pos[2 * (size_t)row + r] = tri[(size_t)r * 3 + 2]; + } + } + *out = std::move(p); + return 0; +} + +/* A kind's modulation cell (rad_ref2va_pack.h): the latents and the prompt read their schedule's + * embeddings, a keyframe or reference its stream's pinned ones. */ +static void cell_of_kind(int kind, int64_t S, int* md, int64_t* r0) { + switch (kind) { + case kR2VAudio: *md = 2; *r0 = S; break; + case kR2VCondAudio: + case kR2VRefAudio: *md = 2; *r0 = 3 * S; break; + case kR2VText: *md = 1; *r0 = 0; break; + case kR2VCond: + case kR2VRefImg: *md = 0; *r0 = 2 * S; break; + default: *md = 0; *r0 = 0; break; + } +} + +void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector& runs, + Ref2VAModGroups* out) { + out->bound.clear(); out->col.clear(); out->md.clear(); out->r0.clear(); + std::vector sorted; + for (const Ref2VATagRun& r : runs) + if (r.end > r.start) sorted.push_back(r); + std::sort(sorted.begin(), sorted.end(), + [](const Ref2VATagRun& a, const Ref2VATagRun& b) { return a.start < b.start; }); + + /* The rows in pieces of one cell each: a segment is one, except the prompt, which the runs cut + * into text and pad pieces, every one on the text's block. */ + struct Piece { int64_t start, end; int md; int64_t r0; }; + std::vector pieces; + for (const Ref2VASeg& s : p.segs) { + if (s.end <= s.start) continue; + if (s.kind != kR2VText) { + Piece pc{ s.start, s.end, 0, 0 }; + cell_of_kind(s.kind, S, &pc.md, &pc.r0); + pieces.push_back(pc); + continue; + } + int64_t at = s.start; + for (const Ref2VATagRun& r : sorted) { + const int64_t a = std::max(r.start, at), b = std::min(r.end, s.end); + if (a >= s.end) break; + if (b <= a) continue; + if (a > at) pieces.push_back({ at, a, 1, 0 }); + pieces.push_back({ a, b, r.tag, 0 }); + at = b; + } + if (at < s.end) pieces.push_back({ at, s.end, 1, 0 }); + } + + /* A group opens where the cell changes; cells are numbered in their first group's order. */ + auto column_of = [&](int md, int64_t r0) { + for (size_t c = 0; c < out->md.size(); ++c) + if (out->md[c] == md && out->r0[c] == r0) return (int)c; + out->md.push_back(md); + out->r0.push_back(r0); + return (int)out->md.size() - 1; + }; + int cur = -1; + bool open = false; + int64_t prev_end = 0; + for (const Piece& pc : pieces) { + const int col = column_of(pc.md, pc.r0); + if (!open || col != cur || pc.start != prev_end) { + out->bound.push_back(open ? pc.start : 0); + cur = col; + open = true; + out->col.push_back(col); + } + prev_end = pc.end; + } + if (open) out->bound.push_back(p.rows); +} + +} /* namespace minimaxh3 */ diff --git a/arch/minimaxh3/rad_ref2va_pack.h b/arch/minimaxh3/rad_ref2va_pack.h new file mode 100644 index 00000000..b217ff2a --- /dev/null +++ b/arch/minimaxh3/rad_ref2va_pack.h @@ -0,0 +1,107 @@ +/* rad_ref2va_pack.h -- MiniMax-H3's packed sequence with keyframes and reference media, on the + * host: ComfyUI's PackedLayout (comfy/ldm/minimax/model.py), tested against that code's own numbers + * (tests/data/ref2va). + * + * The sequence is [text | keyframes | references in request order | soundtrack | video]. The + * video's clock starts after every reference's time span; a keyframe sits on it at 5/3 a pixel + * frame; a reference clip's soundtrack rows come right before its video rows, at the same time + * origin. Keyframes and references keep a near-clean timestep; the sampler steps the last two + * segments only. + */ + +#ifndef RAD_ARCH_MINIMAXH3_REF2VA_PACK_H +#define RAD_ARCH_MINIMAXH3_REF2VA_PACK_H + +#include +#include + +namespace minimaxh3 { + +/* Segment kinds, named as the reference implementation names them. */ +enum Ref2VAKind { + kR2VText = 0, /* the prompt's hidden states */ + kR2VCond, /* a keyframe's video latent rows */ + kR2VCondAudio, /* a keyframe's soundtrack latent rows */ + kR2VRefImg, /* a reference photo, or a reference clip's video */ + kR2VRefAudio, /* a reference clip's (or standalone audio's) soundtrack */ + kR2VAudio, /* the target soundtrack -- sampler-owned */ + kR2VVideo, /* the target video -- sampler-owned */ + kR2VKinds +}; + +/* A reference's kind; a video with a soundtrack of its own is either of the last two. */ +enum Ref2VARefKind { kR2VRefImage = 0, kR2VRefAudioOnly = 1, kR2VRefVideo = 2, kR2VRefVideoAudio = 3 }; + +/* A keyframe: the frame of the video it is pinned at and its latent frames of each stream. */ +struct Ref2VAKeyframe { + int frame; /* >= 0 */ + int video_t; /* 0: none */ + int audio_t; /* 0: none */ +}; + +/* A reference, in latents: its own grid and frames for a picture or video, its soundtrack's + * length for one that has sound. */ +struct Ref2VARef { + int kind; /* Ref2VARefKind */ + int lat_h, lat_w; + int latent_t; + int audio_t; +}; + +/* The target, in latent units. */ +struct Ref2VAGeom { + int latent_t, latent_h, latent_w, audio_t; +}; + +struct Ref2VASeg { + int kind; + int64_t start, end; /* rows [start, end) */ + int update; /* 1 for the soundtrack and the video the sampler steps */ +}; + +struct Ref2VAPack { + std::vector segs; + int64_t rows = 0; + /* The rotary positions, [3, rows]: every row's time, then row, then column. */ + std::vector pos; +}; + +/* A kind's modality in the modulation (ComfyUI's seg_tag): 0 video, 1 text, 2 sound. */ +int ref2va_seg_tag(int kind); +/* Whether a kind's rows are video latents or soundtrack latents; text is neither. */ +int ref2va_is_img(int kind); +int ref2va_is_audio(int kind); +/* A keyframe's or reference's timestep is the larger of its stream's and these. */ +constexpr double kR2VVisualPin = 0.999, kR2VAudioPin = 1.0; + +/* The modulation groups: runs of consecutive rows that read the same modulation cell, which the + * segment's kind fixes (`md` its modality's projection, `r0` its block of timestep embeddings) -- + * except inside the prompt, where a picture's vision pads read the video projection on the text's + * block, as ComfyUI tags them (`runs`). The modulated norm takes the group boundaries, the attention + * the segments'. Groups that share a cell read one column of the modulation table (`col`), so the + * table grows with the distinct cells, not with the references or the pads: nine pictures add one + * cell. The groups cover the sequence; an empty segment opens none. */ +struct Ref2VATagRun { + int64_t start, end; /* prompt rows [start, end) */ + int tag; /* the projection they read: 0 video for vision pads */ +}; +struct Ref2VAModGroups { + std::vector bound; /* [groups + 1], from 0 to the rows */ + std::vector col; /* [groups]: the cell the group reads */ + std::vector md; /* [cells]: 0 video, 1 text, 2 sound */ + std::vector r0; /* [cells] */ +}; +/* `S` is the steps a schedule has, and the embeddings are [0, S) the video's, [S, 2S) the + * soundtrack's, then each again with its pin, [2S, 3S) and [3S, 4S). The boundaries do not depend + * on S. `runs` may come in any order; the parts outside the prompt are ignored. Without runs every + * group has a cell of its own. */ +void ref2va_mod_groups(const Ref2VAPack& p, int64_t S, const std::vector& runs, + Ref2VAModGroups* out); + +/* The sequence, and its positions when `positions`; -1 for a negative size or an unknown kind. */ +int ref2va_build(int text_len, const Ref2VAGeom& g, const std::vector& keyframes, + const std::vector& refs, Ref2VAPack* out, bool positions = true); + +} /* namespace minimaxh3 */ + +#endif diff --git a/arch/minimaxh3/rad_vae_geom.cpp b/arch/minimaxh3/rad_vae_geom.cpp new file mode 100644 index 00000000..3c43e491 --- /dev/null +++ b/arch/minimaxh3/rad_vae_geom.cpp @@ -0,0 +1,48 @@ +/* rad_vae_geom.cpp -- see rad_vae_geom.h. */ + +#include "rad_vae_geom.h" + +namespace minimaxh3 { + +/* vae.py's encode_temporal for more than one frame, its plain encode for one. */ +int64_t vae_latent_frames(int64_t frames) { + if (frames <= 0) return -1; + if (frames == 1) return 1; + const int64_t clips = (frames + kVaeClipLength - 1) / kVaeClipLength; + return clips * kVaeClipLatents - kVaeTokenDrop; +} + +int64_t vae_clip_latents(int64_t frames) { + if (frames <= 0) return -1; + if (frames == 1) return 1; + return (frames + 3) / 4; /* ceil(ceil(T / 2) / 2) */ +} + +/* Every strided convolution (k = 2 s, pad ceil(s / 2)) divides a padded length exactly. */ +int64_t vae_audio_latents(int64_t samples) { + if (samples < 0) return -1; + return (samples + kAudioHop - 1) / kAudioHop; +} + +const double kVaeLatentsMean[24] = { + 0.858090341091156, -0.9606591463088989, 1.0661640167236328, -0.5090325474739075, + -0.2727581858634949, -1.3675414323806763, -0.2553254961967468, -0.26907554268836975, + -0.5376840829849243, -0.0464097298681736, 0.6657370328903198, 0.19690127670764923, + -0.5460608005523682, -0.4035342037677765, -0.23683024942874908, 0.25928452610969543, + -0.30133944749832153, 0.211341992020607, -1.1206848621368408, 0.3581933379173279, + -0.04225143790245056, 0.2604829967021942, 0.22864092886447906, 0.7056031823158264, +}; + +const double kVaePixelMean[3] = { 0.485, 0.456, 0.406 }; +const double kVaePixelStd[3] = { 0.229, 0.224, 0.225 }; + +const double kVaeLatentsStd[24] = { + 1.2223774194717407, 1.2767263650894165, 1.68317747116088865, 1.7549455165863037, + 1.5636216402053833, 2.194143533706665, 0.96531379222869875, 1.05698859691619875, + 0.841948926448822, 0.7729952931404114, 1.8955937623977661, 0.946841835975647, + 0.7996809482574463, 0.44988900423049925, 0.7197399735450745, 0.69362932443618775, + 2.961095094680786, 2.7694199085235595, 3.0496184825897215, 2.1088054180145265, + 3.276226282119751, 3.1627357006073, 2.28168129920959475, 2.6127843856811525, +}; + +} /* namespace minimaxh3 */ diff --git a/arch/minimaxh3/rad_vae_geom.h b/arch/minimaxh3/rad_vae_geom.h new file mode 100644 index 00000000..3da0f13f --- /dev/null +++ b/arch/minimaxh3/rad_vae_geom.h @@ -0,0 +1,43 @@ +/* rad_vae_geom.h -- the latents MiniMax-H3's VAE encoders make of a media's frames or samples, + * and their normalisation constants, on the host. ComfyUI's comfy/ldm/minimax/vae.py and + * audio_vae.py, tested against those encoders' own outputs (tests/data/vae_geom). */ + +#ifndef RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H +#define RADIANCE_ARCH_MINIMAXH3_RAD_VAE_GEOM_H + +#include + +namespace minimaxh3 { + +/* The video VAE: 16 pixels a latent side, and in time clips of 17 frames to 5 latent frames + * (17 -> 9 -> 5), of which an encode of more than one frame drops the last 3. */ +constexpr int kVaeRatio = 16; +constexpr int kVaeClipLength = 17; +constexpr int kVaeClipLatents = 5; +constexpr int kVaeTokenDrop = 3; + +/* The audio VAE: strides 2 4 4 5 5, a latent per 800 samples (40 a second at 32 kHz), the samples + * padded with zeros to a whole latent. */ +constexpr int kAudioHop = 800; + +/* The latent frames of `frames` pixel frames: 1 for a picture, else 5 a clip of 17 (the last + * padded by repeating its last frame) less 3. -1 for no frames. */ +int64_t vae_latent_frames(int64_t frames); + +/* The latent frames one clip of `frames` encodes to, ceil(T / 4) (one frame stays one). */ +int64_t vae_clip_latents(int64_t frames); + +/* The latents of `samples` samples; -1 for a negative count. */ +int64_t vae_audio_latents(int64_t samples); + +/* A video latent is normalised as (moments - mean) / std, vae.py's LATENTS_MEAN and LATENTS_STD. */ +extern const double kVaeLatentsMean[24]; +extern const double kVaeLatentsStd[24]; + +/* A pixel x in [0, 1] goes in as (x - mean) / std, ImageNet's. */ +extern const double kVaePixelMean[3]; +extern const double kVaePixelStd[3]; + +} /* namespace minimaxh3 */ + +#endif diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 4700ad48..5b3aa5ba 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -107,16 +107,11 @@ using MtpHead = MtpFP8; #endif /* The weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h): a weight's first - * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2 at tp 2 - * on 2x R9700 (Gen5 x8), one round each, no speculation, x1 / x4 / x8 / x16 tok/s against none - * (61.2 / 225.0 / 403.7 / 650.8): 8 MB 65.1 / 246.4 / 410.9 / 663.3; 10 MB 66.0 / 250.1 / 425.0 / - * 668.5; 12 MB 67.9 / 251.2 / 438.6 / 668.1; 14 MB 67.8 / 249.5 / 432.4 / 659.1; 16 MB 67.0 / 244.9 / - * 422.7 / 649.4; 20 MB 63.4 / 232.0 / 408.1 / 630.7; 32 MB 57.9 / 210.2 / 372.8 / 605.9 -- past - * ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it should feed. Reads up - * to 128 rows: x32 963.8 against 956.0, x64 1206.7 against 1216.6, so the ceiling is 32 rows (a - * verify of four sequences at speculation 7). With speculation 7 (three rounds) x1..x16 +0.1..+1.9 %. - * The drafter's reads (Dflash2::Config::prefetch) take the same size: speculation 7, eight rounds, - * median x1 +6 %, x16 unchanged. */ + * kPrefetchBytes, on decode steps of up to kPrefetchStepRows rows. Qwen3.8-27B MXFP4 + DFlash2, tp + * 2 on two R9700s, no speculation: 12 MB was best, +11 % at one stream, +9 % at eight, +3 % at + * sixteen; past ~12 MB the read outlasts the reduction and takes bandwidth from the GEMM it feeds. + * Up to 32 rows (a verify of four sequences at speculation 7): at 32 and 64 rows the reads are a + * wash. The drafter's reads (Dflash2::Config::prefetch) take the same size. */ constexpr int64_t kPrefetchBytes = (int64_t)12 << 20; constexpr int64_t kPrefetchStepRows = 32; @@ -125,9 +120,8 @@ struct Layer { AttnGatedFP8 attn; GdnFP8 gdn; Ffn mlp; - /* The reads beside the decode all-reduces (prefetch_beside, rad_arch.h): gate_up's leading - * bytes beside the mixer's reduction, the next layer's first projection's beside the - * feed-forward's. 0 where none is declared. */ + /* gate_up's leading bytes beside the mixer's reduction, the next layer's first projection's + * beside the feed-forward's; 0 where none is declared. */ rad_op op_pf_gu = 0, op_pf_next = 0; rad_weight pf_gu_w = 0, pf_next_w = 0; }; @@ -1017,6 +1011,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l); RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state)); RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv)); + /* Lane 1 carries no collectives here (rad_block_gdn_fp8.h, ab_lane). */ + lay.gdn.ab_lane = true; RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs, f.mix_fold, false, f.mix_ar_in, f.mix_ar_out)); } @@ -1047,13 +1043,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c #endif #if !QWEN35_MOE - /* ---- the weight reads beside the decode all-reduces (prefetch_beside, rad_arch.h). At decode - * heights each block's reduction leaves the card's memory idle for its round trip over the link, - * so the GEMM behind it has its weight's leading bytes read into the on-die cache there: gate_up - * behind the mixer's reduction, the next layer's first projection (the delta net's in-projection, - * an attention layer's q|gate) behind the feed-forward's. Only at more than one rank; - * RADIANCE_PREFETCH_BESIDE=0 issues none (prefetch_beside). */ - if (g.world > 1 && rad_op_declared(b, "prefetch")) { + /* ---- the weight reads beside the decode all-reduces. A decode-height reduction leaves the + * card's memory idle for its round trip, so the next GEMM's leading weight bytes are read + * into the on-die cache then: gate_up behind the mixer's, the next layer's first projection + * behind the feed-forward's. At more than one rank; --weight-prefetch off declares none. */ + if (g.world > 1 && !ctx->weight_prefetch_off && rad_op_declared(b, "prefetch")) { for (int64_t l = 0; l < m.n_main; ++l) { Layer& lay = m.layers[(size_t)l]; lay.pf_gu_w = lay.mlp.gate_up.w; @@ -1538,9 +1532,8 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_ISSUE_N(c, m.op_rope_cs, batch->n_tok, rope_pos1(batch, batch->n_tok), RAD_B(m.b_rope_cs)); - /* The reads beside the reductions go on decode steps of up to kPrefetchStepRows rows, none on a - * step that carries a prompt's rows. This ceiling, not prefetch_beside's own (16), decides: it - * is passed a height of 1 where the step qualifies. */ + /* Decode steps of up to kPrefetchStepRows rows only. This ceiling decides, not + * prefetch_beside's own (16): it is passed a height of 1 where the step qualifies. */ const int64_t pf_h = batch->phase == RAD_PHASE_DECODE && batch->n_tok <= kPrefetchStepRows ? 1 : INT64_MAX; for (int64_t li = 0; li < (int64_t)m.layers.size(); ++li) { diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 0beb8561..27ef3467 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -1090,6 +1090,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * paths must give identical text; any difference is a defect. */ if (m.qsaw.qk) { lay.attn.qsa_sel = m.qsaw.sel; + lay.attn.qsa_nsel = m.qsaw.nsel; lay.attn.qsa_sequ = m.qsaw.sequ; lay.attn.qsa_topk = m.qsacfg.topk; /* The exactness bound, below which prefill issues the cheaper dense attention. @@ -1357,6 +1358,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.mtp.attn.kv_block = 4; if (m.qsaw.qk) { m.mtp.attn.qsa_sel = m.qsaw.sel; + m.mtp.attn.qsa_nsel = m.qsaw.nsel; m.mtp.attn.qsa_sequ = m.qsaw.sequ; m.mtp.attn.qsa_topk = m.qsacfg.topk; m.mtp.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1; @@ -1692,6 +1694,9 @@ static void step(RadCtx* c, const RadBatch* batch) { * mapped table). */ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; + /* The gated attention block declares the streamed store and the resolve + * (rad_block_attn_gated_fp8.h). */ + out->kv_stream_ok = 1; out->draft_depth = 0; if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0) out->draft_depth = 3; diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index ddac9118..921debd6 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -4,7 +4,7 @@ # Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not # appear. set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen - lora) + lora kvstream) set(RAD_CORE_SRC "") foreach(d ${RAD_CORE_DIRS}) diff --git a/core/build/rad_build.h b/core/build/rad_build.h index ae7d954c..53de59f2 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -115,6 +115,7 @@ public: rad_buf decl_buffer (const char* name, const RadBufDecl* d); rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d); int64_t kv_block_size(rad_kvgroup g); + int64_t kv_layer_bytes(rad_kvgroup g); int bind_layer_kv(int layer, rad_kvgroup g); rad_op decl_op (const char* op, const RadParam* p, int n_p, const rad_weight* w, int n_w); @@ -146,6 +147,7 @@ public: int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); int kv_group_zero(rad_kvgroup g); + int kv_group_dense_read(rad_kvgroup g); int kv_group_replicated(rad_kvgroup g); /* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns @@ -240,6 +242,9 @@ private: * per rank). */ std::unordered_map weight_by_name_; + /* tune_key() -> index in prog_.tune_requests: one request per kernel instantiation. */ + std::unordered_map tune_index_; + /* The model's answers, cached per source: a routed model declares each expert's codes and * scales as two weights over one source, and a checkpoint lookup walks the name map. */ WeightSourceFn sources_; diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index ad8c7f8e..c55c95ef 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -9,6 +9,7 @@ * which makes fusion a selection rather than a compiler pass (spec §2.3). */ #include "rad_build.h" +#include "kvstream/bringup.h" #include "lora/lora.h" #include "../device/device.h" @@ -466,20 +467,31 @@ int64_t Builder::kv_block_size(rad_kvgroup g) { return 0; } +/* One layer's bytes of a paged group's block: what a kernel addressing one layer sees, and the + * pitch of a streamed group's host mirror rows. */ +int64_t Builder::kv_layer_bytes(rad_kvgroup g) { + if (g == 0 || g >= prog_.kv_groups.size()) return 0; + KVGroupInfo& gi = prog_.kv_groups[g]; + if (gi.decl.kind != RAD_KV_FULL && gi.decl.kind != RAD_KV_WINDOW) return 0; + const int64_t bs = kv_block_size(g); + if (bs <= 0) return 0; + const int64_t nh = gi.decl.n_head_kv > 0 ? gi.decl.n_head_kv : 1; + return rad_dtype_bytes(gi.decl.dtype, 2 * bs * nh * gi.decl.head_dim); +} + /* ================================================================== ops */ +/* A kernel instantiation: (kernel, plugin, resolved input params). Keyed on geom_key, not + * geom.str(), so tuner and selector key identically: geom_key is tunecache.h's canonical sorted + * spelling without the tuned axes, while geom.str() keeps declaration order and includes them. */ +static std::string tune_key(const Resolved& r) { + return r.row->info->name + std::string("\x1f") + r.row->plugin + std::string("\x1f") + + r.geom_key; +} + void Builder::record_tune_request(const Resolved& r) { if (!r.row || !r.row->info || r.row->info->n_tunables <= 0) return; - /* One request per kernel instantiation: (kernel, plugin, resolved input params). The same - * shape requested by many layers is one benchmark (spec §15). - * - * Keyed on geom_key, not geom.str(), so tuner and selector key identically: geom_key is - * tunecache.h's canonical sorted spelling without the tuned axes, while geom.str() keeps - * declaration order and includes the axes. */ - const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin + - std::string("\x1f") + r.geom_key; - for (auto& t : prog_.tune_requests) - if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + t.geom_key == key) - return; + /* The same shape requested by many layers is one benchmark (spec §15). */ + if (!tune_index_.emplace(tune_key(r), prog_.tune_requests.size()).second) return; Program::TuneRequest req; req.kernel = r.row->info->name; @@ -599,26 +611,19 @@ void Builder::finish_instances() { } } -/* The instances are made in finish_instances(), after record_tune_request ran, so the requests - * now carry the instance their kernel will launch with. A collective's launch cannot be formed - * without it -- the peer bundle (scratch, flags, sequence counters) is what init() builds and - * RadArgs reaches the exchange through nothing else -- so the tuner forms its launches from this. - * Keyed exactly as record_tune_request keyed. */ +/* Hand each tune request the instance finish_instances() made for its kernel: a collective's + * launch reaches its peer bundle (scratch, flags, sequence counters) only through the instance, so + * the tuner forms its launches from this. */ void Builder::fill_tune_instances() { - for (size_t i = 1; i < prog_.ops.size(); ++i) { - const OpInfo& oi = prog_.ops[i]; - for (const Band& b : oi.bands) + if (prog_.tune_requests.empty()) return; + for (size_t i = 1; i < prog_.ops.size(); ++i) + for (const Band& b : prog_.ops[i].bands) for (int d = 0; d < RAD_N_DOMAINS; ++d) { const Resolved& r = b.dom[d]; - if (!r || !r.row || !r.row->info) continue; - const std::string key = r.row->info->name + std::string("\x1f") + r.row->plugin + - std::string("\x1f") + r.geom_key; - for (auto& t : prog_.tune_requests) - if (t.kernel + std::string("\x1f") + t.plugin + std::string("\x1f") + - t.geom_key == key) - t.instance = r.instance; + if (!r || !r.row || !r.row->info || r.row->info->n_tunables <= 0) continue; + const auto it = tune_index_.find(tune_key(r)); + if (it != tune_index_.end()) prog_.tune_requests[it->second].instance = r.instance; } - } } rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, @@ -827,6 +832,7 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, } int Builder::op_declared(const char* op) const { + if (kvstream_op_gated(prog_.ctx, op)) return 0; /* kvstream_op_gated */ return op && reg_.schema(op) ? 1 : 0; } @@ -982,6 +988,21 @@ int Builder::kv_group_zero(rad_kvgroup h) { return RAD_OK; } +int Builder::kv_group_dense_read(rad_kvgroup h) { + if (finished_) { err(RAD_E_STATE, "kv_group_dense_read after declare finished"); return RAD_E_STATE; } + if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL; + /* Full groups only: a state slot is already per sequence, and a window bounds its own + * history. */ + const KVGroupInfo& gi = prog_.kv_groups[h]; + if (gi.decl.kind != RAD_KV_FULL) { + err(RAD_E_INVAL, "kv group '%s': dense_read on a group that is not a full attention group", + gi.name.c_str()); + return RAD_E_INVAL; + } + prog_.kv_groups[h].dense_read = true; + return RAD_OK; +} + int Builder::kv_group_replicated(rad_kvgroup h) { if (finished_) { err(RAD_E_STATE, "kv_group_replicated after declare finished"); @@ -2473,6 +2494,11 @@ int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { return B(b)->kv_block_size(g); } +int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g) { + if (!b) return 0; + return B(b)->kv_layer_bytes(g); +} + int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { if (!b) return RAD_E_INVAL; return B(b)->bind_layer_kv(layer, g); @@ -2535,6 +2561,11 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { return B(b)->kv_group_zero(g); } +int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g) { + if (!b) return RAD_E_INVAL; + return B(b)->kv_group_dense_read(g); +} + int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) { if (!b) return RAD_E_INVAL; return B(b)->kv_group_replicated(g); diff --git a/core/build/startup.cpp b/core/build/startup.cpp index b08ee817..a2e3468c 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -291,6 +291,16 @@ VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) { return ap ? ap->arch_video_positions : nullptr; } +VideoPackFn rad_tools_video_pack(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_video_pack : nullptr; +} + +EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_encode_geom : nullptr; +} + const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) { const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); if (!ap || !ap->arch_audio_format) return nullptr; diff --git a/core/build/startup.h b/core/build/startup.h index 78fe62d1..a8333ead 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -100,6 +100,13 @@ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::s using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins); +/* Its rad_arch_video_pack and rad_arch_encode_geom, null when it does not export them. */ +using VideoPackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int32_t*, int32_t*, + int32_t*, float*, int64_t); +VideoPackFn rad_tools_video_pack(const LoadedPlugins& plugins); +using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t); +EncodeGeomFn rad_tools_encode_geom(const LoadedPlugins& plugins); + /* Run declare. * * `also` declares into the same builder after the architecture plugin, which is how the sampler diff --git a/core/config.cpp b/core/config.cpp index fa8ffc0b..20db0b2d 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -60,6 +60,9 @@ static const Flag g_flags[] = { "attention splits over the ranks: rows gives each rank all\n" "heads of its rows, a faster prefill for the projections at\n" "full width on every card; not bit-identical to heads" }, + { "--weight-prefetch", "MODE", "on (default) | off -- read a GEMM's weight into the cache\n" + "beside the collective before it; off for an engine that\n" + "shares its cards with another server" }, { "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n" "asks the driver, on requires peer access and stops without\n" "it, off exchanges through pinned host memory" }, @@ -85,6 +88,11 @@ static const Flag g_flags[] = { { "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n" "Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n" "k6_v4 cache: faster at long context, and lossy" }, + { "--kv-resident", "N", "stream the sparse attention group's KV from host memory,\n" + " keeping N tokens of it in a VRAM ring (0, the default, is\n" + " off). Raised to 32768 and to what one decode step selects;\n" + " a ring that covers the context (sequences x\n" + " --max-model-len) streams nothing" }, { "--host-pool-mib", "N", "pinned host tier" }, { "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n" " pins its host memory at startup (default 4096)" }, @@ -109,7 +117,8 @@ static const Flag g_flags[] = { { "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n" " so their VRAM can go to experts and a return restores\n" " instead of re-prefilling. A full tier drops its least\n" - " recently used entries. 0 is off" }, + " recently used entries. 0 is off. Off while a KV group\n" + " streams (--kv-resident)" }, { "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n" " or host memory (default 3600). 0 keeps it until the memory\n" " is wanted" }, @@ -461,6 +470,12 @@ int config_parse(int argc, char** argv, Config* c) { else if (!std::strcmp(v, "rows")) c->tp_attn_rows = 1; else { RAD_ERR("--tp-attn-split takes heads or rows, not '%s'", v); return RAD_E_INVAL; } } + else if (S("--weight-prefetch")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "on")) c->weight_prefetch = true; + else if (!std::strcmp(v, "off")) c->weight_prefetch = false; + else { RAD_ERR("--weight-prefetch takes on or off, not '%s'", v); return RAD_E_INVAL; } + } else if (S("--p2p")) { if (!(v = need(i))) return RAD_E_INVAL; if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO; @@ -531,6 +546,7 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } } + else if (S("--kv-resident")) { if (!num(0, INT64_MAX, &c->kv_resident)) return RAD_E_INVAL; } else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; } else if (S("--embedding-placement") || S("--ngram-placement")) { const bool emb = S("--embedding-placement"); @@ -1073,6 +1089,7 @@ const ShowRow kShow[] = { { "--tp", [](const Config& c) { return num(c.tp); } }, { "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } }, { "--tp-attn-split", [](const Config& c) { return std::string(c.tp_attn_rows ? "rows" : "heads"); } }, + { "--weight-prefetch", [](const Config& c) { return onoff(c.weight_prefetch); } }, { "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } }, { "--p2p", [](const Config& c) { return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } }, @@ -1091,6 +1108,8 @@ const ShowRow kShow[] = { { "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } }, { "--attn-prefill-fp8", [](const Config& c) { return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } }, + { "--kv-resident", [](const Config& c) { + return c.kv_resident > 0 ? num(c.kv_resident) : std::string("0 (off)"); } }, { "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } }, { "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } }, { "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } }, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 40502c13..68759da8 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -2934,8 +2934,7 @@ int64_t a_gate_room(RadStream rs) { /* Waits for the mark, then for the card's link gate if a collective has ever held it (under TP * the all-reduce shares the link and the step waits on it, not on these copies), copies, writes - * `done`, then the list's number. RAD_XP_NO_YIELD skips the gate: a list the compute stream waits on - * cannot outlast a hold whose release is behind that wait (core/kvstream/stage.cpp). */ + * `done`, then the list's number. RAD_XP_NO_YIELD skips the gate (rad_xp_list). */ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, uint32_t* done, uint32_t done_val, unsigned flags) { DmaQueue* dq = xp_queue(ord); @@ -2987,15 +2986,10 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d return rc; } -/* An event the DMA engine completes (rad_event_dma): a fresh completion word for the event, which - * a rad_xp_list writes 0 to as its `done` once its bytes have landed, so a stream that waits on the - * event stops until the copy is done. - * - * The word comes back at 0 and the *caller* arms it with a write of 1 on the stream, because the arm - * must be ordered: a host store here would land ahead of a wait still queued for the group's previous - * copy (which would then block on this 1 and never see its 0), and an event record would not do - * either -- a record completes by decrementing its signal to 0, which is the value the wait is - * looking for. A fresh signal each time keeps two uses of one word from overlapping at all. */ +/* rad_event_dma: a fresh signal for the event, at 0. The caller arms it with a 1 written in stream + * order: a host store could land ahead of a wait still queued for the previous copy, and an event + * record completes by reaching 0, the value the wait looks for. A fresh signal each time keeps two + * uses from sharing one word. */ int a_event_dma(RadEvent re, RadStream rs, uint32_t** word) { if (!word) { device_set_error("rad_event_dma: null word"); return RAD_E_INVAL; } if (capturing()) { @@ -3672,17 +3666,9 @@ void* pin_pieces(int64_t bytes) { char* const p = (char*)at; prefer_numa_node(p, len, current_card_numa_node()); - /* RADIANCE_NO_HUGE_PAGES asks for small pages, before the pin faults them in: the KV mirror's - * scattered 2 KiB reads are the case page size is supposed to matter for, and this is how that - * is measured rather than assumed (core/kvstream/mirror.cpp). Not a supported mode. */ - const bool small_pages = std::getenv("RADIANCE_NO_HUGE_PAGES") != nullptr; if (len >= ((int64_t)2 << 20)) { - if (small_pages) { - ::madvise(p, (size_t)len, MADV_NOHUGEPAGE); - } else { - ::madvise(p, (size_t)len, MADV_HUGEPAGE); - warn_if_no_huge_pages(); - } + ::madvise(p, (size_t)len, MADV_HUGEPAGE); + warn_if_no_huge_pages(); } (void)::madvise(p, (size_t)len, MADV_DONTFORK); diff --git a/core/device/device.h b/core/device/device.h index 16f99d1e..4898f2ac 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -113,23 +113,20 @@ extern "C" void* rad_link_gate(RadStream s); * counts lists handed over and not yet finished. The prefetch ring is uncached device memory * (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a * slot's previous contents. */ -/* An event the DMA engine completes instead of a dispatch: it is recorded on `s` (a write of 1 to - * its completion word, in stream order) and `*word` returns that word for `rad_xp_list` to write 0 - * to as the list's `done`, once the list's bytes have landed. `rad_event_wait(s, ev)` then stops `s` - * until the copy is done, device-side: no host round trip on the step path. The caller waits for - * the group's previous copy before arming the next, so the word's older 0 cannot release a later - * wait. RAD_E_STATE while a tape is recording: a list is not a queue packet, so a recorded pass - * must re-run the call with the tape paused (core/kvstream/stage.cpp). */ +/* An event a DMA list completes instead of a dispatch. `*word` is its completion word, for + * rad_xp_list to write 0 to as the list's `done`; the caller arms it with a 1 in stream order (the + * weight table's patch dispatch). `rad_event_wait(s, ev)` then holds `s` on the device until the + * copy has landed. The caller waits for the previous copy before arming the next, so an older 0 + * cannot release a later wait. RAD_E_STATE while a tape records: the caller re-runs it with the + * tape paused (core/kvstream/stage.cpp). */ extern "C" int rad_event_dma(RadEvent ev, RadStream s, uint32_t** word); extern "C" int rad_xp_supported(int device); extern "C" int rad_xp_stream_create(RadStream* out); extern "C" int rad_ride(RadStream s, void** token); extern "C" int rad_ride_wait(RadStream s, void* token); extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets); -/* `flags` RAD_XP_NO_YIELD: the list does not give way to a link a stream of this card holds. A copy - * the compute stream itself waits on must set it -- a yield it cannot outlast is a deadlock (the - * hold's release is behind the wait) -- at the cost of taking its share of the link in one piece - * (core/kvstream/stage.cpp). The expert prefetch passes 0: nothing waits for it. */ +/* `flags` RAD_XP_NO_YIELD: the list does not yield the link to a hold by a stream of this card. A + * copy the compute stream waits on must set it, since the hold's release is behind that wait. */ #define RAD_XP_NO_YIELD 1u extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, uint32_t* done, uint32_t done_val, @@ -340,8 +337,7 @@ struct DeviceBackend { int (*gate_open)(void* gate); int64_t (*gate_room)(RadStream s); - /* ---- an event a DMA list completes: see rad_event_dma. Null (unsupported) on a backend with - * no DMA queue that writes a completion word. */ + /* ---- rad_event_dma; null on a backend with no DMA queue. */ int (*event_dma)(RadEvent e, RadStream s, uint32_t** word); }; diff --git a/core/device/host.cpp b/core/device/host.cpp index d66be6e4..e739d0ac 100644 --- a/core/device/host.cpp +++ b/core/device/host.cpp @@ -816,7 +816,7 @@ const DeviceBackend g_host = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, h_stream_gate, h_gate_open, h_gate_room, - nullptr, /* no DMA queue, so no event it could complete */ + nullptr, /* event_dma: no DMA queue */ }; } /* namespace */ diff --git a/core/engine.cpp b/core/engine.cpp index ee0478cd..4dd616e6 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -15,6 +15,7 @@ #include "device/device.h" #include "format/radfile.h" #include "gen_config.h" +#include "kvstream/stage.h" #include "sample/accept.h" #include "sched/scheduler.h" #include "server/adapters.h" @@ -73,6 +74,7 @@ Engine::~Engine() { /* --profile-ops prints its final table here, the last point where the program still holds * the op table the rows name. */ if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); + if (stream_ctl_p_) rad_dev_free(stream_ctl_p_, RAD_MEM_HOST_PINNED); for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED); for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED); @@ -96,6 +98,9 @@ Engine::~Engine() { for (auto& r : ranks_) if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s); for (auto& r : ranks_) r->ctx.shutdown(); + /* The streamed groups' host mirrors are pinned outside every pool; freed after the contexts, + * since a pass reads them. Safe after a failed bring-up. */ + for (auto& r : ranks_) r->kv.free_stream(rad_device_allocator()); step_state_fini(); ranks_.clear(); for (TableCopy& c : table_copies_) table_copy_free(&c); @@ -346,6 +351,9 @@ int Engine::prepare_release(const RadBatch* b) { step_status_.store(RAD_E_NOMEM, std::memory_order_release); } if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + /* The stage bound for every rank (kvstream/stage.h, "Volume"). Rank 0's allocator hands out the + * block ids every rank uses, and the ranks are parked, so no allocation races the read. */ + for (auto& rk : ranks_) kvstream_bound_live(&rk->ctx, ranks_[0]->kv); return RAD_OK; } @@ -409,21 +417,16 @@ int Engine::step_loop() { * pass issued ahead would overwrite them. */ pipelining_ = !cfg_.kld() && !embedding_ && (serial_drafting() || block_drafting() || cfg_.n_spec <= 0); - /* RADIANCE_IDS_EARLY=0 waits for the drafter's passes before reading the ids, as before, for - * an A/B. */ - early_ids_ = !cfg_.kld() && !embedding_ && [] { - const char* v = std::getenv("RADIANCE_IDS_EARLY"); - return !(v && *v == '0'); - }(); + early_ids_ = !cfg_.kld() && !embedding_; const bool t_on = (int)log_level() >= (int)Log::Debug; /* The next step's forward pass when already issued behind the previous step, before its * readback (Scheduler::step_next). */ const RadBatch* ahead = nullptr; - /* Names where the step loop waits when nothing has been logged for a while: a freeze reports - * the blocked thread, its syscall and its stack; long quiet generations report sparsely (the - * silence doubles) and the reports read as the ordinary GPU wait. */ + /* A step that runs for 20 s reports where the step loop waits: its syscall and its stack. + * Every iteration, idle or not, marks progress, so only a stuck step is reported. */ rad::StallWatch step_watch("step", 20000); while (!stopping_.load(std::memory_order_acquire)) { + step_watch.progress(); lora_epoch_.fetch_add(1, std::memory_order_acq_rel); phase_t_ = std::chrono::steady_clock::now(); /* Encode media for waiting requests while nothing is in flight. The scheduler issues no @@ -700,6 +703,9 @@ int Engine::step_loop() { st = block_drafting() ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so); if (st < 0) return fail_loop(st); + /* Behind the step's last resolve and before its end event, so collect_step's wait covers it. */ + st = stream_probe_issue(b); + if (st < 0) return fail_loop(st); st = mark_step_end(b, so); if (st < 0) return fail_loop(st); /* Then the next step's forward pass, before this step is read back. Its rows continue from @@ -764,11 +770,17 @@ int Engine::step_loop() { st = sched_.commit(res); if (t_on) phase_mark(PH_COMMIT); if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); } + /* The step has drained, so its counters are readable. A chunk that produced no row did not + * wait, so its copy is read on a later step; a finished prompt or request always produced + * a row. */ + if (so.n_rows > 0) { + st = stream_probe_take(b, res.n_prefill_done > 0, res.n_finished > 0); + if (st < 0) return fail_loop(st); + } - /* With the ids read ahead of the drafter's passes the commit has streamed the step's - * tokens while the card ran them. Their end now, before anything reads what they wrote - * (the slots below) or the next step reuses what the commit released: the commit issued - * no work of its own, so everything it freed is in use only by passes this wait covers. */ + /* With the ids read ahead of the drafter's passes, the commit streamed the tokens while + * the card ran them. Wait for the passes now, before the slots below are read and before + * anything reuses what the commit released. */ if (so.early) { st = rad_event_sync(step_end_); if (st < 0) { RAD_ERR("step %d: waiting for its draft passes: %s", b->step, @@ -819,10 +831,9 @@ int Engine::step_loop() { * Issued by a drafter before its passes (a head sampling through the sampler's buffer overwrites * the ids), otherwise just before the wait. * - * With `fence`, from a drafter that queues its passes behind the step, the copy is followed by - * tok_end_, so collect_step can wait for the ids alone and the commit can stream the step's - * tokens while the card runs the passes (StepOut::early). Not at -vv: the logits row below is a - * pageable copy, read in collect_step. */ + * With `fence` (a drafter queueing its passes behind the step) the copy records tok_end_, so + * collect_step waits for the ids alone (StepOut::early). Not at -vv, whose logits row is a + * pageable copy read in collect_step. */ int Engine::collect_issue(StepOut& so, bool fence) { so.rb = nullptr; so.lg.clear(); @@ -856,6 +867,119 @@ int Engine::collect_issue(StepOut& so, bool fence) { return RAD_OK; } +/* ================================================================== KV streaming's counters + * + * Each streamed group's device control block holds the resolve's cumulative counters, the largest + * union, misses and claims of one launch, and the overflow latch (libref/ref_kvstream.cpp, "The + * control block"). They show at run time whether the ring's depth holds; a launch that overflowed + * is failed, not served (docs/KV-STREAMING.md §3.4). + * + * The step path never waits on the card: the 64-byte copy per group is enqueued on rank 0's compute + * stream behind the step's last resolve and before its end event, and the commit that already + * waits for that event reads it. One rank's counters stand for all, since every rank resolves the + * same block ids through identically built maps. The counters are cumulative, so the metrics are + * charged the deltas. */ +int Engine::stream_probe_issue(const RadBatch* b) { + if (!b || b->n_kv_groups <= 0 || ranks_.empty()) return RAD_OK; + const size_t n = (size_t)b->n_kv_groups; + if (stream_ctl_n_ < n) { + if (stream_ctl_p_) rad_dev_free(stream_ctl_p_, RAD_MEM_HOST_PINNED); + stream_ctl_p_ = static_cast( + rad_dev_alloc((int64_t)n * 16 * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED)); + stream_ctl_n_ = stream_ctl_p_ ? n : 0; + if (!stream_ctl_p_) { + RAD_ERR("kv streaming: no pinned host memory for the resolve's counters"); + return RAD_E_NOMEM; + } + /* Zeroed, so a group whose first copy has not landed reads as no calls yet. */ + std::memset(stream_ctl_p_, 0, n * 16 * sizeof(int32_t)); + } + RadStream st = ranks_[0]->ctx.stream(); + for (size_t i = 0; i < n; ++i) { + const RadKVStream* sv = b->kv[i].stream; + if (!sv || !sv->ctl) continue; + if (rad_memcpy_async(stream_ctl_p_ + i * 16, sv->ctl, 16 * 4, st) < 0) { + RAD_ERR("kv streaming: the resolve's counters could not be copied to the host: %s", + rad_dev_last_error()); + return RAD_E_STATE; + } + } + return RAD_OK; +} + +/* Read what stream_probe_issue() enqueued, charge the metrics and, at a prompt's or request's + * end, log the group's line. A newly latched overflow fails every request prefilling in the step + * just committed and clears the latch on the card, so the next request is measured on its own; + * the map stays consistent, because the resolve reverts a claim it could not place. */ +int Engine::stream_probe_take(const RadBatch* b, bool prefill_done, bool request_end) { + if (!b || !stream_ctl_p_ || b->n_kv_groups <= 0) return RAD_OK; + const size_t n = (size_t)b->n_kv_groups; + if (stream_prev_.size() < n) stream_prev_.assign(n, StreamRead{}); + RadStream st = ranks_[0]->ctx.stream(); + bool overflowed = false; + std::string overflow_why; + for (size_t i = 0; i < n; ++i) { + const RadKVStream* sv = b->kv[i].stream; + if (!sv) continue; + const int32_t* c = stream_ctl_p_ + i * 16; + /* The counters are three u64s from ctl[4], hence the 8-byte alignment. */ + const uint64_t* ctr = (const uint64_t*)(c + 4); + StreamRead r; + r.group = (int32_t)b->kv[i].group; + r.misses = (int64_t)ctr[0]; + r.lookups = (int64_t)ctr[1]; + r.resolves = (int64_t)ctr[2]; + r.overflow = c[3] != 0; + r.max_union = c[10]; + r.max_misses = c[11]; + r.max_claims = c[12]; + r.slots = sv->slots; + r.block_bytes = sv->block_bytes; + const StreamRead& p = stream_prev_[i]; + const int64_t dm = r.misses - p.misses; + ranks_[0]->kv.note_stream_traffic(dm, dm * r.block_bytes); + if (request_end || prefill_done) stream_report(request_end ? "request end" : "prefill complete", r, p); + if (r.overflow && !p.overflow && !overflowed) { + overflowed = true; + const KVGroupPlan* gp = ranks_[0]->kv.plan(r.group); + const int64_t bs = gp && gp->block_size > 0 ? gp->block_size : 1; + /* The largest union since bring-up, which for the failing request is the launch that + * overflowed. */ + overflow_why = fmt( + "kv streaming overflow: group '%s' ring holds %lld blocks (%lld tokens) and one " + "resolve launch selected %lld distinct blocks, %lld of them not resident, so the " + "request is failed; raise --kv-resident above %lld tokens", + gp ? gp->name.c_str() : "?", (long long)r.slots, (long long)(r.slots * bs), + (long long)r.max_union, (long long)r.max_misses, + (long long)(r.max_union * bs)); + RAD_ERR("%s", overflow_why.c_str()); + } + stream_prev_[i] = r; + } + if (overflowed) { + (void)sched_.fail_prefilling(overflow_why.c_str()); + for (size_t i = 0; i < n; ++i) { + const RadKVStream* sv = b->kv[i].stream; + if (sv && sv->ctl) (void)rad_memset_async(sv->ctl + 3, 0, 4, st); + } + } + return RAD_OK; +} + +/* One line per group: the cumulative counters, the misses since the previous report and the three + * largest-launch figures a ring and a claim list are sized from. A launch claims at most + * `max_seqs * sel_pitch` blocks; a larger `largest launch claims` means that derivation is wrong. */ +void Engine::stream_report(const char* when, const StreamRead& r, const StreamRead& prev) { + const KVGroupPlan* gp = ranks_.empty() ? nullptr : ranks_[0]->kv.plan(r.group); + RAD_INFO("kv streaming: group '%s' %s: %lld resolves, %lld lookups, %lld misses (+%lld this " + "interval); ring %lld blocks, largest launch union %lld distinct blocks, largest " + "launch misses %lld, largest launch claims %lld, overflow %s", + gp ? gp->name.c_str() : "?", when, (long long)r.resolves, (long long)r.lookups, + (long long)r.misses, (long long)(r.misses - prev.misses), (long long)r.slots, + (long long)r.max_union, (long long)r.max_misses, (long long)r.max_claims, + r.overflow ? "LATCHED" : "no"); +} + int Engine::mark_step_end(const RadBatch* b, StepOut& so) { if (embedding_) RAD_TRY(collect_pooled_issue(b, so)); else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(so)); @@ -950,8 +1074,7 @@ int Engine::issue_scored_rows(Rank& r) { int Engine::collect_scored_rows() { if (score_rows_.empty()) return RAD_OK; - /* The wait collect_step made (step_end_, or tok_end_ behind the copies issued ahead of the - * sampler) fences rank 0's stream; every other rank's copies are fenced here. */ + /* collect_step's wait fences rank 0's stream; every other rank's copies are fenced here. */ for (size_t i = 1; i < ranks_.size(); ++i) { RAD_TRY(rad_dev_set(ranks_[i]->device)); RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream())); @@ -997,9 +1120,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) { if (so.n_rows <= 0) return RAD_OK; so.rows.resize((size_t)so.n_rows); - /* Wait on an event, not the stream: a step issued ahead is queued behind it. The ids' own - * event when they were fenced ahead of the drafter's passes (StepOut::early), whose end the - * step loop waits for after the commit; else the step's end. */ + /* Wait on an event, not the stream: a step issued ahead is queued behind it. With early ids + * that is the ids' own copy; the step loop waits for the rest after the commit. */ RAD_TRY(rad_event_sync(so.early ? tok_end_ : step_end_)); std::memcpy(so.rows.data(), so.rb, (size_t)so.n_rows * sizeof(int32_t)); so.rb = nullptr; @@ -1589,14 +1711,25 @@ int Engine::serve(std::unique_ptr watch) { * PCIe read and unordered against the copies that fill it (see Set in batch.h). */ std::vector rio; rio.reserve(ranks_.size()); - for (auto& rk : ranks_) - rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); + rank_stream_views_.assign(ranks_.size(), {}); + for (size_t r = 0; r < ranks_.size(); ++r) { + const size_t ng = ranks_[r]->program.kv_groups.size(); + rank_stream_views_[r].resize(ng, nullptr); + for (size_t g = 0; g < ng; ++g) + rank_stream_views_[r][g] = ranks_[r]->kv.stream_view((int32_t)g); + } + for (size_t r = 0; r < ranks_.size(); ++r) { + auto& rk = ranks_[r]; + rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(), + rank_stream_views_[r].data() }); + } if (video_gen) { /* As for the image generator below; the plugin lays out each request's rows. */ std::vector gio; for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); auto d = std::make_unique(); - RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio)); + RAD_TRY(d->init(ranks_[0]->program, rad_tools_video_positions(plugins_), gio, + rad_tools_video_pack(plugins_), rad_tools_encode_geom(plugins_))); vid_gen_ = d.get(); gen_ = std::move(d); RAD_TRY(rad_dev_set(ranks_[0]->device)); @@ -1731,6 +1864,7 @@ std::string Engine::engine_info() const { e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb; e["attn_prefill_fp8"] = attn_prefill_fp8_name(cfg_.attn_prefill_fp8); e["tp_attn_split"] = cfg_.tp_attn_rows ? "rows" : "heads"; + e["weight_prefetch"] = cfg_.weight_prefetch; e["max_num_batched_tokens"] = cfg_.max_tok; e["placement"] = cfg_.placement; /* Each lookup table's requested and resolved placement. */ @@ -2703,6 +2837,8 @@ int Engine::run_server() { in.default_steps = vd.default_steps; in.max_steps = vd.max_steps; in.fixed_steps = vd.n_rungs > 0; + in.shift_video = vd.shift_video; + in.shift_audio = vd.shift_audio; in.upscale_max = vd.upscale_max; in.upscale_refine = vd.upscale_refine; in.step_evals = vd.sched_kind == 1; @@ -2719,6 +2855,13 @@ int Engine::run_server() { "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; + in.max_ref_images = vd.max_ref_images; + in.max_ref_videos = vd.max_ref_videos; + in.max_ref_audios = vd.max_ref_audios; + in.max_enc_frames = vd.max_enc_frames; + in.max_enc_side = vd.max_enc_side; + in.max_enc_samples = vd.max_enc_samples; + in.enc_ratio = vd.enc_ratio; video_bridge.drv = vid_gen_; d.videos = &video_bridge; if (cfg_.served_model_name.empty() && !in.name.empty()) { diff --git a/core/engine.h b/core/engine.h index 488dc5c5..786b9870 100644 --- a/core/engine.h +++ b/core/engine.h @@ -114,6 +114,9 @@ private: * than broadcast (spec §1). */ struct Rank; std::vector> ranks_; + /* Per rank and KV group, that rank's stream view or null; the batch builder takes these, since it + * cannot reach each rank's manager. */ + std::vector> rank_stream_views_; /* The tiers' work in flight: the host-memory copies the transfer streams are running. */ std::unique_ptr pump_; /* serve()'s startup stall watch, released when the server listens (run_server) or the KL @@ -254,10 +257,8 @@ private: /* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them; * empty on a step with none. */ std::vector lp; - /* The ids' copy has its own event ahead of the drafter's passes (collect_issue's - * `fence`): collect_step waits on it, the commit streams the tokens, and the passes are - * waited for after that (step_end_), before anything reads what they wrote or reuses what - * the commit released. */ + /* The ids' copy recorded tok_end_ ahead of the drafter's passes: collect_step waits for + * it alone, and the step loop for step_end_ after the commit. */ bool early = false; }; @@ -328,9 +329,8 @@ private: void probe_arena_levels(); int step_loop(); /* Issue the copy of the step's sampled ids to the host, then wait for and interpret them. - * Split so the copy is issued before draft passes overwrite the ids. With `fence` (a drafter - * queueing its passes behind the step) the copy gets an event of its own, tok_end_, so the - * wait for the ids need not wait for the passes too (StepOut::early). */ + * Split so the copy is issued before draft passes overwrite the ids. With `fence` the copy + * records tok_end_, so the wait for the ids skips the passes (StepOut::early). */ int collect_issue(StepOut& so, bool fence = false); int collect_step(const RadBatch* b, StepOut& so); int row_logprobs(StepOut& so, int32_t row, int32_t token); @@ -342,9 +342,26 @@ private: /* The sampled ids' copy, ahead of the drafter's passes (collect_issue's `fence`). */ RadEvent tok_end_ = nullptr; /* Whether the ids may be read before the drafter's passes end: not in KL mode, whose scored - * rows are read out of the logits after collection, nor in an embedding program. */ + * rows are read from the logits after collection, nor for an embedding program. */ bool early_ids_ = false; + /* ---- KV streaming's counters (engine.cpp, "KV streaming's counters"). Pinned, because a + * device-to-host copy into pageable memory blocks the stream. */ + struct StreamRead { + int64_t resolves = 0, lookups = 0, misses = 0; + int64_t max_union = 0, max_misses = 0, max_claims = 0; + int64_t slots = 0, block_bytes = 0; + bool overflow = false; + int32_t group = -1; + }; + std::vector stream_prev_; /* what metrics have already been charged */ + /* Pinned landing area for the copies: [n_kv_groups][16] i32, grown on first use. */ + int32_t* stream_ctl_p_ = nullptr; + size_t stream_ctl_n_ = 0; + int stream_probe_issue(const RadBatch* b); + int stream_probe_take(const RadBatch* b, bool prefill_done, bool request_end); + void stream_report(const char* when, const StreamRead& r, const StreamRead& prev); + /* The draft head as declared (rad_declare_drafter), zeroed when no speculative window was * asked for. `kind` selects which of the two drivers below runs. `drafter_name_` owns the * string because RadDrafterDecl::name points into the Program. */ @@ -529,6 +546,9 @@ private: void decide(const std::string& key, const std::string& value, const std::string& why) { diag::decide(&decisions_, key, value, why); } + /* The architecture's RadArchProbe, asked once in declare(): a property of the model, so every + * RadBuildCtx carries the same answer (RadBuildCtx::kv_stream_ok). */ + RadArchProbe arch_probe_{}; std::string devnote_; /* the devices usable_devices left out, and why */ int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */ std::string p2p_blocked_; diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 89c38eb0..6cc4500e 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -21,6 +21,8 @@ #include "format/table_copy.h" #include "rad_plugin.h" #include "mem/vram_budget.h" +#include "kvstream/bringup.h" +#include "kvstream/plan.h" #include "runtime/arena.h" #include "runtime/kvbind.h" #include "runtime/xprefetch.h" @@ -329,14 +331,9 @@ static void memory_cgroups(const std::function 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0; + /* --kv-resident in tokens, raised to kStreamFloorTokens as kvstream_ring_shape raises it: the + * arch declares kv_resolve's ring depth from this, and the kernel refuses a carve deeper than + * the declared table. */ + bc.kv_resident_blocks = cfg_.kv_resident > 0 && cfg_.kv_resident < kStreamFloorTokens + ? kStreamFloorTokens + : cfg_.kv_resident; + /* A streamed-only op is declared only when the architecture streams and the flag asks + * (kvstream_op_gated). */ + bc.kv_stream_ok = arch_probe_.kv_stream_ok; /* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at * declare only (the direction table never changes); the per-request switch rides the derived * mask, not this struct. */ @@ -928,6 +935,15 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { } int Engine::declare() { + /* An architecture that declares no streamed ops cannot stream, so with --kv-resident set on one + * the flag is turned off here, with the decision named, before anything is planned for it. */ + (void)rad_tools_probe(plugins_, meta_, &arch_probe_); + if (cfg_.kv_resident > 0 && arch_probe_.kv_stream_ok == 0) { + cfg_.kv_resident = 0; + decide("--kv-resident", "0", + std::string("architecture '") + (meta_.arch_id ? meta_.arch_id : "?") + + "' has no streamed KV path"); + } RAD_TRY(lora_targets()); /* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit * would skip positions the reference holds, so both are off, and an explicit depth is refused @@ -990,7 +1006,14 @@ int Engine::declare() { decide("--max-model-len", std::to_string(cfg_.max_ctx), "a video generator: a step's rows"); } - if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + /* A video generator with a vision tower takes a pass of its patches, the size its + * plugin states. */ + if (cfg_.mm_max_patches < 0 && pb.gen_patches > 0) { + cfg_.mm_max_patches = pb.gen_patches; + decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches), + "a video generator: every reference media patch of one conditioning, " + "the pass size the plugin states"); + } if (cfg_.n_spec < 0) cfg_.n_spec = 0; cfg_.prefix_cache = false; } else if (pb.gen_rows > 0) { @@ -1589,6 +1612,18 @@ int Engine::plan() { if (declare_ring_windows(probe, r->program) == RAD_OK && probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { ck_slot += probe.checkpoint_bytes(); + /* The budget must see the streamed plan before it sizes the pool: a streamed group's + * ceiling is max(ring, one layer of its context), not its whole cache + * (docs/KV-STREAMING.md §4.1). */ + RAD_TRY(kvstream_cap_probe(probe, cfg_, r->program, ctx)); + /* No prefix-cache entry holding a streamed group can be demoted (its mirror is its only + * cold copy), so the host tier would be pinned and never used: turned off before + * the tables and the checkpoint store are sized. */ + if (const int64_t off = kvstream_prefix_host_off(cfg_)) { + RAD_INFO("a streamed KV group has no host cache: --prefix-cache-mib %lld is off, " + "since no entry holding the group could be demoted", + (long long)off); + } f.kv_ceiling = probe.ceiling(ctx); f.kv_fixed = probe.fixed_bytes(); /* One --max-model-len sequence's pool, as the inverse of the real plan: its @@ -3054,6 +3089,14 @@ int Engine::configure_kv() { "block and the linear-state chunk), so a checkpoint is a legal chunk split", (long long)geo_.quantum) : std::string("the model keeps no linear state to checkpoint")); + /* KV streaming's policy, refusals and ring (kvstream/bringup.h), decided once from rank 0's + * declarations: a streamed group must be the same group on every rank. */ + KVStreamSetup stream; + if (!ranks_.empty()) + RAD_TRY(kvstream_configure(cfg_, cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train, + ranks_[0]->program.kv_groups, ranks_[0]->program, &stream)); + if (stream.group >= 0) + for (auto& r : ranks_) r->kv.cap_resident_tokens(stream.group, stream.ring_tokens); /* One block table serves every rank (serve() checks it), so every rank carves the same number * of paged blocks. Under an uneven split the pools differ (more delta-net heads, or zero * attention weights), so each rank is planned first and all are capped at the least before @@ -3077,6 +3120,22 @@ int Engine::configure_kv() { if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */ if (least < 0 || t < least) least = t; } + /* The mirrors are checked once, before any rank pins one, against the host tiers still to be + * pinned after them: the prefix cache's, the activation arenas and, when sized already, the + * checkpoint store. */ + KVStreamHostUse stream_host; + for (auto& r : ranks_) kvstream_host_add(&stream_host, r->kv); + if (stream_host.sum.host_bytes > 0) { + const int64_t MiB = (int64_t)1 << 20; + int64_t still = cfg_.prefix_cache_mib * MiB; + for (auto& r : ranks_) still += arena_host_bytes(r->program); + if (cfg_.checkpoint_slots > 0) { + int64_t slot = 0; + for (auto& r : ranks_) slot += r->kv.checkpoint_bytes(); + still += slot * cfg_.checkpoint_slots; + } + RAD_TRY(kvstream_host_gate(stream_host, (int)ranks_.size(), still, host_headroom_bytes())); + } for (auto& r : ranks_) { LogRank lr(r->index); RAD_TRY(rad_dev_set(r->device)); /* allocates on the current device; see plan() */ @@ -3088,7 +3147,13 @@ int Engine::configure_kv() { (long long)least); r->kv.cap_paged_tokens(least); } + /* Before the carve, which refuses a streamed plan with no mirror and maps. The maps come out + * of this rank's KV pool, so the paged split sees them taken. */ + const KVManager::StreamCost sc = r->kv.stream_cost(); + if (sc.groups > 0) + RAD_TRY(r->kv.alloc_stream(rad_device_allocator(), r->pools.kv())); RAD_TRY(r->kv.carve(r->pools.kv())); + if (sc.groups > 0) RAD_TRY(kvstream_fill(r->kv)); /* the maps, after the elastic pool */ /* Without virtual memory management the cache cannot lend: everything still works, but * the expert slab never grows, which no counter shows, so log it once. */ if (r->index == 0 && !r->pools.kv().elastic()) @@ -3289,6 +3354,7 @@ int Engine::configure_kv() { } RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str()); + kvstream_report(stream, stream_host, (int)ranks_.size()); /* The prefix cache's report: on or off, groups covered and skipped. It names the two things * that silently disable caching on a hybrid model: a windowed group cannot be served a prefix, * and a linear model with no checkpoint interval replays from zero. */ @@ -3571,8 +3637,8 @@ int Engine::start() { const int64_t lbpb = p.layer_bytes_per_block(), stripe = p.layer_stride(); for (int64_t L = 0; L < p.n_layers; ++L) { LoanStrip st; - st.top = (char*)p.base + L * stripe + p.n_blocks * lbpb; - st.bytes = p.n_blocks * lbpb; + st.top = (char*)p.base + L * stripe + p.pool_blocks() * lbpb; + st.bytes = p.pool_blocks() * lbpb; st.unit_bytes = lbpb; st.unit_tokens = p.block_size; strips.push_back(st); diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 1ad7cadc..2e5ea5bc 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -30,7 +30,7 @@ int Engine::step_state_init() { if (vocab_) eog = vocab_->eog(); std::sort(eog.begin(), eog.end()); eog.erase(std::unique(eog.begin(), eog.end()), eog.end()); - /* The scheduler's rule for a step that ends its requests reads the same ids (step_next). */ + /* Scheduler::ends_every_request reads the same ids. */ sched_.set_eog(eog); const int64_t n_slot = cfg_.max_seqs > 0 ? cfg_.max_seqs : 1; const int64_t slot_bytes = n_slot * (int64_t)sizeof(StepSlot); @@ -182,9 +182,8 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) { /* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the * acceptance on every rank, the sampled-id readback (before a round can overwrite them), the * history pass and every round, then the final proposal into the slots and their readback. - * Nothing synchronises here. collect_step waits for the ids alone (their copy is fenced ahead of - * the passes), and the step loop for the passes after the commit, before finish_serial_drafter - * reads the slots. */ + * Nothing synchronises here: collect_step waits for the ids alone, and the step loop for the + * passes after the commit, before finish_serial_drafter reads the slots. */ int Engine::issue_serial_drafter(int step, StepOut& so) { serial_rounds_ = 0; serial_rows_ = 0; @@ -470,9 +469,9 @@ bool Engine::block_drafting() const { * The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK), * and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the * next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip. - * collect_step waits for the sampled ids alone, whose copy is fenced ahead of both passes, so the - * commit streams the step's tokens while the card runs them; the step loop waits for the passes - * and the slots' readback (step_end_) before finish_block_drafter reads the slots. */ + * collect_step waits for the sampled ids alone, so the commit streams the tokens while the card + * runs both passes; the step loop waits for them (step_end_) before finish_block_drafter reads the + * slots. */ void Engine::block_shape(int* block, int* steps) { *steps = drafter_.depth; /* The row count is the drafter's (defaulted and checked by declare_drafter). */ diff --git a/core/engine_hostmem.h b/core/engine_hostmem.h index 258425a6..20d4bf66 100644 --- a/core/engine_hostmem.h +++ b/core/engine_hostmem.h @@ -19,4 +19,12 @@ bool cgroup_room(const std::string& dir, bool v2, int64_t* room); void cgroup_levels(const std::string& root, std::string path, bool v2, const std::function& visit); +/* Whether `need` more bytes fit in host memory after `still` more this process will allocate + * first and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every + * memory cgroup from the process's own up to the visible root (Docker's --memory, enforced by the + * OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has + * CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK does + * not count. An unreadable limit is ignored, never guessed. */ +bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks, std::string* why); + } /* namespace rad */ diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index cb06107e..06828b71 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -1639,6 +1639,281 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) { return RAD_OK; } +/* PEFT exports wrap HF module paths in the name of the net the adapter trained: ai-toolkit spells + * a DiT module `diffusion_model.`, diffusers' wrappers `transformer.` or `unet.`. */ +static const char* const kLoraPrefixes[] = { "diffusion_model.", "transformer.", "unet." }; + +/* One `modules` rule of the map: the module pattern split at its single `*`, and the target + * patterns into which the matched run is substituted, in B-row order. */ +struct LoraRule { + bool star = false; + std::string pre, suf; + std::vector targets; + bool match(const std::string& m, std::string* tok) const { + if (!star) { + if (m != pre) return false; + tok->clear(); + return true; + } + if (m.size() < pre.size() + suf.size() || m.compare(0, pre.size(), pre) != 0) return false; + if (m.compare(m.size() - suf.size(), suf.size(), suf) != 0) return false; + *tok = m.substr(pre.size(), m.size() - pre.size() - suf.size()); + return !tok->empty(); + } +}; + +/* Read the map file: {"strip": [...], "modules": {"": ["", ...], ...}}. The module + * order is preserved (an nlohmann object keeps insertion order), so the first rule whose + * pattern matches a module wins. */ +static int lora_map_read(const std::string& file, std::vector* strip, + std::vector* rules) { + std::ifstream f(file); + if (!f) { RAD_ERR("lora: --lora-map %s cannot be read", file.c_str()); return RAD_E_NOTFOUND; } + nlohmann::ordered_json j; + try { + j = nlohmann::ordered_json::parse(f); + } catch (const std::exception& e) { + RAD_ERR("lora: --lora-map %s: %s", file.c_str(), e.what()); + return RAD_E_FORMAT; + } + if (!j.is_object()) { RAD_ERR("lora: --lora-map %s is not a JSON object", file.c_str()); + return RAD_E_FORMAT; } + if (j.contains("strip")) { + if (!j["strip"].is_array()) { RAD_ERR("lora: --lora-map 'strip' is not a list"); + return RAD_E_FORMAT; } + for (const auto& s : j["strip"]) { + if (!s.is_string()) { RAD_ERR("lora: --lora-map 'strip' holds a non-string"); + return RAD_E_FORMAT; } + strip->push_back(s.get()); + } + } + if (!j.contains("modules") || !j["modules"].is_object()) { + RAD_ERR("lora: --lora-map %s has no 'modules' object", file.c_str()); + return RAD_E_FORMAT; + } + for (const auto& [pat, t] : j["modules"].items()) { + if (!t.is_array() || t.empty()) { + RAD_ERR("lora: --lora-map rule '%s' is not a non-empty list", pat.c_str()); + return RAD_E_FORMAT; + } + const size_t star = pat.find('*'); + LoraRule r; + r.star = star != std::string::npos; + r.pre = r.star ? pat.substr(0, star) : pat; + r.suf = r.star ? pat.substr(star + 1) : ""; + for (const auto& x : t) { + if (!x.is_string()) { + RAD_ERR("lora: --lora-map rule '%s' holds a non-string target", pat.c_str()); + return RAD_E_FORMAT; + } + r.targets.push_back(x.get()); + } + rules->push_back(std::move(r)); + } + return RAD_OK; +} + +int Checkpoint::add_lora(const std::string& path, double strength, + std::vector* merged, const std::string* map_json) { + if (kind_ != SafeT) { + RAD_ERR("lora: an adapter merges into a safetensors source; %s is not one", path_.c_str()); + return RAD_E_UNSUPPORTED; + } + if (import_ != Import::None) { + RAD_ERR("lora: this checkpoint ships its weights packed by a quantiser; an adapter merges " + "into the plain tensors its training saw, not into the codes"); + return RAD_E_UNSUPPORTED; + } + std::vector files; + std::error_code ec; + if (std::filesystem::is_directory(path, ec)) { + for (const auto& e : std::filesystem::directory_iterator(path, ec)) + if (e.path().extension() == ".safetensors") files.push_back(e.path().string()); + std::sort(files.begin(), files.end()); + } else + files.push_back(path); + if (files.empty()) { + RAD_ERR("lora: %s holds no .safetensors file", path.c_str()); + return RAD_E_NOTFOUND; + } + + /* The module lookup strips wrapper prefixes: the map's first, then the builtin ones. */ + std::vector strips; + std::vector rules; + if (map_json && lora_map_read(*map_json, &strips, &rules) < 0) return RAD_E_FORMAT; + for (const char* pre : kLoraPrefixes) strips.push_back(pre); + + /* One pair's A/B/alpha, by module; `module` keeps the wrapper prefix, so the lookup below + * strips it. */ + struct Pair { std::string module; const StTensor *a = nullptr, *b = nullptr, *al = nullptr; }; + + int n_merged = 0; + for (const std::string& f : files) { + SafeTensorsFile st; + if (st.open(f) != RAD_OK) return RAD_E_FORMAT; + std::vector pairs; + std::map by_module; + for (const StTensor& t : st.tensors()) { + if (t.name.size() > 12 && t.name.compare(t.name.size() - 12, 12, ".dora.scalar") == 0) { + RAD_ERR("lora: '%s' is a DoRA adapter; only plain LoRA merges (a magnitude vector " + "has no place in a weight merge)", t.name.c_str()); + return RAD_E_UNSUPPORTED; + } + const char* suf = nullptr; + if (t.name.size() > 14 && t.name.compare(t.name.size() - 14, 14, ".lora_A.weight") == 0) + suf = ".lora_A.weight"; + else if (t.name.size() > 18 && + t.name.compare(t.name.size() - 18, 18, ".lora_down.weight") == 0) + suf = ".lora_down.weight"; + if (suf) { + Pair p; + p.module = t.name.substr(0, t.name.size() - std::strlen(suf)); + p.a = &t; + by_module[p.module] = pairs.size(); + pairs.push_back(std::move(p)); + } else if (t.name.size() > 14 && + t.name.compare(t.name.size() - 14, 14, ".lora_B.weight") == 0) { + auto it = by_module.find(t.name.substr(0, t.name.size() - 14)); + if (it != by_module.end()) pairs[it->second].b = &t; + } else if (t.name.size() > 6 && + t.name.compare(t.name.size() - 6, 6, ".alpha") == 0) { + auto it = by_module.find(t.name.substr(0, t.name.size() - 6)); + if (it != by_module.end()) pairs[it->second].al = &t; + } + } + if (pairs.empty()) { + RAD_ERR("lora: %s holds no .lora_A.weight / .lora_down.weight tensors", f.c_str()); + return RAD_E_NOTFOUND; + } + for (Pair& p : pairs) { + if (!p.b) { + RAD_ERR("lora: '%s' ships its A but no B", p.module.c_str()); + return RAD_E_FORMAT; + } + /* The targets: `.weight`, else the same with a wrapper prefix stripped, else + * the tensors the first map rule the stripped module matches names. */ + std::string norm = p.module; + for (const std::string& s : strips) + if (norm.size() > s.size() && norm.compare(0, s.size(), s) == 0) { + norm.erase(0, s.size()); + break; + } + std::vector tg; + if (const SrcTensor* W = find(p.module + ".weight")) tg.push_back(W); + if (tg.empty() && norm != p.module) + if (const SrcTensor* W = find(norm + ".weight")) tg.push_back(W); + for (const LoraRule& ru : rules) { + std::string tok; + if (!ru.match(norm, &tok)) continue; + for (const std::string& pat : ru.targets) { + std::string nm = pat; + const size_t star = nm.find('*'); + if (star != std::string::npos) nm.replace(star, 1, tok); + const SrcTensor* W = find(nm); + if (!W) { + RAD_ERR("lora: the map maps '%s' onto '%s', which this checkpoint does " + "not ship", p.module.c_str(), nm.c_str()); + return RAD_E_NOTFOUND; + } + tg.push_back(W); + } + break; + } + if (tg.empty()) { + RAD_ERR("lora: '%s' names a module this checkpoint does not ship as " + "'.weight' (nor stripped of a known wrapper prefix)%s", + p.module.c_str(), + map_json ? " and no --lora-map rule matches it" : ""); + return RAD_E_NOTFOUND; + } + const StTensor& A = *p.a; + const StTensor& B = *p.b; + if (A.shape.size() != 2 || B.shape.size() != 2 || A.shape[0] <= 0 || + A.shape[0] != B.shape[1]) { + RAD_ERR("lora: '%s' is not a rank-%lld pair of matrices: [a %lld x %lld, " + "b %lld x %lld]", + p.module.c_str(), (long long)A.shape[0], (long long)A.shape[0], + (long long)A.shape[1], (long long)B.shape[0], (long long)B.shape[1]); + return RAD_E_FORMAT; + } + const auto plain = [](uint32_t d) { + return d == RAD_BF16 || d == RAD_F16 || d == RAD_F32; + }; + if (!plain(A.dtype) || !plain(B.dtype)) { + RAD_ERR("lora: '%s' ships A/B in dtypes the merge cannot read", p.module.c_str()); + return RAD_E_UNSUPPORTED; + } + const int64_t K = A.shape[1], r = A.shape[0]; + int64_t rows = 0; + for (const SrcTensor* W : tg) { + if (W->gptq_bits || W->ct_group || W->rad_dtype == RAD_DT_INVALID || + !plain(W->rad_dtype)) { + RAD_ERR("lora: '%s' is not a plain bf16/f16/f32 matrix, so an adapter cannot " + "merge into it", W->name.c_str()); + return RAD_E_UNSUPPORTED; + } + if (W->shape.size() != 2 || W->shape[1] != K) { + RAD_ERR("lora: '%s' [a %lld x %lld, b %lld x %lld] does not fit '%s' " + "[%lld x %lld]", + p.module.c_str(), (long long)A.shape[0], (long long)A.shape[1], + (long long)B.shape[0], (long long)B.shape[1], W->name.c_str(), + (long long)W->shape[0], (long long)W->shape[1]); + return RAD_E_FORMAT; + } + rows += W->shape[0]; + } + if (rows != B.shape[0]) { + RAD_ERR("lora: '%s' merges into %zu target(s) whose rows sum to %lld, but its B " + "has %lld", p.module.c_str(), tg.size(), (long long)rows, + (long long)B.shape[0]); + return RAD_E_FORMAT; + } + float scale = (float)strength; + if (p.al) { + const int64_t n_el = p.al->shape.empty() ? 1 : p.al->numel(); + if (n_el != 1 || (p.al->dtype != RAD_F32 && p.al->dtype != RAD_BF16 && + p.al->dtype != RAD_F16)) { + RAD_ERR("lora: '%s.alpha' is not a single number", p.module.c_str()); + return RAD_E_FORMAT; + } + scale *= rad_load_f32(p.al->data, p.al->dtype, 0) / (float)r; + } + /* The module is the targets' concatenation: target i takes B's rows [off, off + N_i). + * A row at a time, rank-1 updates into an f32 row, with A taken to f32 once a pair so + * the sweep reads plain f32 (a dtype switch an element is hours on a large adapter). */ + std::vector Af((size_t)(r * K)); + for (int64_t i = 0; i < r * K; ++i) Af[(size_t)i] = rad_load_f32(A.data, A.dtype, i); + std::vector acc((size_t)K); + int64_t off = 0; + for (const SrcTensor* W : tg) { + const int64_t N = W->shape[0]; + auto out = std::make_unique((size_t)W->bytes); + for (int64_t n = 0; n < N; ++n) { + for (int64_t j = 0; j < r; ++j) { + const float b = scale * rad_load_f32(B.data, B.dtype, (off + n) * r + j); + if (b == 0.f) continue; + const float* ar = Af.data() + (size_t)j * K; + for (int64_t k = 0; k < K; ++k) acc[(size_t)k] += b * ar[k]; + } + for (int64_t k = 0; k < K; ++k) + rad_store_f32(out.get(), W->rad_dtype, n * K + k, + rad_load_f32(W->data, W->rad_dtype, n * K + k) + + acc[(size_t)k]); + std::fill(acc.begin(), acc.end(), 0.f); + } + SrcTensor& t = tensors_[index_[W->name]]; + t.data = out.get(); + owned_.push_back(std::move(out)); + if (merged) merged->push_back(t.name); + ++n_merged; + off += N; + } + } + } + RAD_INFO("lora %s: %d tensor(s) merged at strength %g", path.c_str(), n_merged, strength); + return RAD_OK; +} + int Checkpoint::add_file(const std::string& path) { if (kind_ != SafeT) { RAD_ERR("%s is merged into a safetensors checkpoint's namespace; %s is not one", diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index fba33cd6..5498f4dc 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -130,6 +130,23 @@ public: * text encoder's repository describes such a release). */ void set_meta_dir(const std::string& dir) { meta_dir_ = dir; } + /* Merge PEFT adapters into the tensors they name: `path` is a .safetensors file or a + * directory of them, of `.lora_A.weight` [r, K] and `.lora_B.weight` [N, r] + * pairs (or ComfyUI's `.lora_down` / `.lora_up`) and an optional `.alpha`. The target + * is `.weight`, or that with a wrapper prefix ("diffusion_model.", "transformer.", + * "unet.") stripped; a module the checkpoint does not have is refused by name. In f32, + * W += strength (alpha / r, or 1 without alpha) B A, stored in the target's dtype, a plain + * bf16, f16 or f32 matrix. Call right after open(): a merged tensor's bytes move, and views + * taken before read the old ones. `merged` receives the targets' names. + * + * `map_json` names a file of rules for adapters trained on other module names (a fused qkv, + * renamed blocks): `{"strip": ["prefix."], "modules": {"": ["", ...]}}`, + * a `*` in a pattern matching one run (the block index) that fills each target's `*`. With + * several targets the module is their concatenation, B's rows split along them in order. A + * rule's target the checkpoint lacks is refused. */ + int add_lora(const std::string& path, double strength, std::vector* merged, + const std::string* map_json = nullptr); + const SrcTensor* find(const std::string& n) const; const std::vector& tensors() const { return tensors_; } bool is_gguf() const { return kind_ == Gguf; } diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index fd86ce5c..9774239b 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -644,40 +644,14 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { /* Pictures for the conditioning network's encoder: every item's patches in prompt order, its * segments, and the prompt rows the encoder's output replaces. */ - int64_t n_patch = 0, n_seg = 0, n_mm = 0; - int32_t max_seg = 0; + StagedMedia sm; if (br.media) { - uint16_t* pix = hptr(R_ENCPIX); - int32_t* crd = hptr(R_ENCCRD); - int32_t* ecu = hptr(R_ENCCU); - int64_t total = 0; - for (const mm::Placed& p : br.media->items) total += p.item->n_patch; - ecu[0] = 0; - std::vector tmp; - for (const mm::Placed& p : br.media->items) { - const mm::Item& it = *p.item; - std::memcpy(pix + n_patch * patch_dim_, it.pixels.data(), - (size_t)(it.n_patch * patch_dim_) * 2); - tmp.resize((size_t)(4 * it.n_patch)); - it.coords(0, it.n_patch, tmp.data()); - for (int cc = 0; cc < 4; ++cc) - std::memcpy(crd + cc * total + n_patch, tmp.data() + cc * it.n_patch, - (size_t)it.n_patch * 4); - for (int32_t s = 0; s < it.n_seg; ++s) { - const int64_t a = it.patch_at(s), e = it.patch_at(s + 1); - ecu[n_seg + 1] = (int32_t)(n_patch + e); - max_seg = std::max(max_seg, (int32_t)(e - a)); - ++n_seg; - } - n_patch += it.n_patch; - } - int32_t* mmr = hptr(R_MMROW); - for (const mm::RopeLayout::Run& run : br.media->rope.runs) - for (int32_t k = 0; k < run.n; ++k) mmr[n_mm++] = run.tok + k; - reg_[R_ENCPIX].used = n_patch * patch_dim_ * 2; - reg_[R_ENCCRD].used = 4 * total * 4; - reg_[R_ENCCU].used = (n_seg + 1) * 4; - reg_[R_MMROW].used = n_mm * 4; + sm = stage_media(*br.media, patch_dim_, hptr(R_ENCPIX), hptr(R_ENCCRD), + hptr(R_ENCCU), hptr(R_MMROW)); + reg_[R_ENCPIX].used = sm.n_patch * patch_dim_ * 2; + reg_[R_ENCCRD].used = 4 * sm.n_patch * 4; + reg_[R_ENCCU].used = (sm.n_seg + 1) * 4; + reg_[R_MMROW].used = sm.n_rows * 4; } /* The generator's sequence, run by the plugin a segment at a time: per segment, its rotary @@ -787,16 +761,16 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { B.max_ctx_len = (int32_t)P; B.rope_pos = dptr(ri, R_ROPE); B.rope_mixed = br.media ? 1 : 0; - B.n_mm_rows = n_mm; - B.mm_rows = n_mm ? dptr(ri, R_MMROW) : nullptr; + B.n_mm_rows = sm.n_rows; + B.mm_rows = sm.n_rows ? dptr(ri, R_MMROW) : nullptr; B.mm_embd = nullptr; B.enc = 0; - B.enc_n_patch = n_patch; - B.enc_pixels = n_patch ? dptr(ri, R_ENCPIX) : nullptr; - B.enc_coord = n_patch ? dptr(ri, R_ENCCRD) : nullptr; - B.enc_n_seg = n_seg; - B.enc_cu = n_seg ? dptr(ri, R_ENCCU) : nullptr; - B.enc_max_seg = max_seg; + B.enc_n_patch = sm.n_patch; + B.enc_pixels = sm.n_patch ? dptr(ri, R_ENCPIX) : nullptr; + B.enc_coord = sm.n_patch ? dptr(ri, R_ENCCRD) : nullptr; + B.enc_n_seg = sm.n_seg; + B.enc_cu = sm.n_seg ? dptr(ri, R_ENCCU) : nullptr; + B.enc_max_seg = sm.max_seg; B.gen = RAD_GEN_PASS_COND; kout_[rr].block_table_pitch = (int64_t)bt.size(); G = RadGenBatch{}; diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp index 0ce151dd..9e67485e 100644 --- a/core/gen/gen.cpp +++ b/core/gen/gen.cpp @@ -2,6 +2,7 @@ * schedule, and the generator's sequence built from a conditioning prompt (gen.h). */ #include "gen.h" +#include #include #include #include @@ -396,5 +397,34 @@ int build_layout(const Branch& b, int64_t slot_rows, return RAD_OK; } +StagedMedia stage_media(const mm::PromptMedia& pm, int64_t patch_dim, uint16_t* pixels, + int32_t* coords, int32_t* cu, int32_t* rows) { + StagedMedia st; + int64_t total = 0; + for (const mm::Placed& p : pm.items) total += p.item->n_patch; + cu[0] = 0; + std::vector tmp; + for (const mm::Placed& p : pm.items) { + const mm::Item& it = *p.item; + std::memcpy(pixels + st.n_patch * patch_dim, it.pixels.data(), + (size_t)(it.n_patch * patch_dim) * 2); + tmp.resize((size_t)(4 * it.n_patch)); + it.coords(0, it.n_patch, tmp.data()); + for (int cc = 0; cc < 4; ++cc) + std::memcpy(coords + cc * total + st.n_patch, tmp.data() + cc * it.n_patch, + (size_t)it.n_patch * 4); + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t a = it.patch_at(s), e = it.patch_at(s + 1); + cu[st.n_seg + 1] = (int32_t)(st.n_patch + e); + st.max_seg = std::max(st.max_seg, (int32_t)(e - a)); + ++st.n_seg; + } + st.n_patch += it.n_patch; + } + for (const mm::RopeLayout::Run& run : pm.rope.runs) + for (int32_t k = 0; k < run.n; ++k) rows[st.n_rows++] = run.tok + k; + return st; +} + } /* namespace gen */ } /* namespace rad */ diff --git a/core/gen/gen.h b/core/gen/gen.h index cd23d240..d2342b5a 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -189,5 +189,16 @@ int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, b /* 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); +/* A prompt's pictures for the vision tower of a conditioning pass (RadBatch::enc_*, mm_rows), the + * image and the video drivers': every item's patches in prompt order at `patch_dim` bf16 each, their + * coordinates [4, patches], the segment boundaries and the prompt rows the tower's output + * replaces. */ +struct StagedMedia { + int64_t n_patch = 0, n_seg = 0, n_rows = 0; + int32_t max_seg = 0; +}; +StagedMedia stage_media(const mm::PromptMedia& pm, int64_t patch_dim, uint16_t* pixels, + int32_t* coords, int32_t* cu, int32_t* rows); + } /* namespace gen */ } /* namespace rad */ diff --git a/core/gen/video.h b/core/gen/video.h index 1d00161b..96e65474 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -8,6 +8,7 @@ */ #pragma once #include "rad_core.h" +#include "mm/processor.h" #include #include @@ -74,16 +75,51 @@ private: std::string why_; }; +/* A reference medium or a keyframe of a request: a picture, a video, a video's own soundtrack, a + * standalone soundtrack, or the first or last frame. `index` is its number within its kind from + * 1 (VIDEO_AUDIO i is VIDEO i's soundtrack); a keyframe's is its in the prompt, 1 the + * first and 2 the last. */ +struct VideoRefMedia { + enum Kind : int32_t { + IMAGE = 0, VIDEO = 1, VIDEO_AUDIO = 2, AUDIO = 3, FIRST_FRAME = 4, LAST_FRAME = 5 + }; + Kind kind = IMAGE; + int32_t index = 0; + std::string name, filename, content_type; /* the form part's */ + std::string data; /* the file's bytes */ + + /* The media as its encoder takes it, decoded by the server, before the driver pads it to the + * encoder's clips and hops. A picture's or video's frames, f32 [enc_frames, enc_h, enc_w, 3] RGB + * in 0..255: a reference's sides multiples of the VAE's ratio within max_enc_side, aspect + * kept, a keyframe at the video's size. A soundtrack, f32 [enc_channels, enc_n] at the + * model's rate, a mono one copied to every channel. */ + std::vector enc_pixels; + int32_t enc_frames = 0, enc_h = 0, enc_w = 0; + std::vector enc_samples; + int64_t enc_n = 0; + int32_t enc_channels = 0; +}; + struct VideoRequest { std::vector tokens; /* the prompt, rendered and tokenised */ int32_t width = 0, height = 0; /* pixels, within the declaration's limits */ int32_t chunks = 0; /* the length in chunks (RadVideoGenDecl) */ int32_t steps = 0; /* sigma grid points; 0: the model's default */ + /* RAD_SAMPLER_* (abi/rad_runtime.h). */ + int32_t sampler = 0; + /* Each stream's schedule shift; 0: the declaration's. */ + double shift_video = 0.0; + double shift_audio = 0.0; /* Latent upscaling (abi/rad_builder.h, RadVideoGenDecl): the factor, 0 for none, and the * evaluations at the full size after it, 0 for the model's default. */ double upscale = 0.0; int32_t refine = 0; uint64_t seed = 0; + /* The reference media and keyframes, sorted by (kind, index). */ + std::vector refs; + /* The pictures the prompt shows the text encoder's vision tower, placed in `tokens`; null for + * none. */ + std::shared_ptr media; /* 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 }; @@ -122,13 +158,15 @@ void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, d * 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. */ + * rungs instead of a 0, the evaluations their sum. `shift_video` and `shift_audio` replace the + * declaration's shifts of form 0 when above 0. */ struct VideoSchedule { std::vector sig_v, sig_a; int32_t steps = 0; }; VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0, - bool refine = false); + bool refine = false, double shift_video = 0.0, + double shift_audio = 0.0); } /* namespace gen */ } /* namespace rad */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 2f7066ad..41f6020a 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -1,6 +1,7 @@ /* video_driver.cpp -- the video generator's pass driver (video_driver.h), the ticket a caller * waits on, and a request's shape and schedule (video.h). */ #include "video_driver.h" +#include "gen.h" #include "rad_internal.h" #include "rad_plugin.h" @@ -144,7 +145,10 @@ static std::vector flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64 } VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens, - bool refine) { + bool refine, double shift_video, double shift_audio) { + /* A request's shift replaces the declaration's, form 0 only. */ + const double sv = shift_video > 0.0 ? shift_video : d.shift_video; + const double sa = shift_audio > 0.0 ? shift_audio : d.shift_audio; VideoSchedule v; if (d.sched_kind == 1) { if (d.n_rungs > 0) { @@ -164,13 +168,13 @@ VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t vi } if (d.n_rungs > 0) { if (steps != d.n_rungs + 1) return v; - v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs); - v.sig_a = rung_sigmas(d.shift_audio, d.rungs, d.n_rungs); + v.sig_v = rung_sigmas(sv, d.rungs, d.n_rungs); + v.sig_a = rung_sigmas(sa, d.rungs, d.n_rungs); v.steps = d.n_rungs; return v; } - v.sig_v = shifted_sigmas(d.shift_video, steps); - v.sig_a = shifted_sigmas(d.shift_audio, steps); + v.sig_v = shifted_sigmas(sv, steps); + v.sig_a = shifted_sigmas(sa, steps); const size_t n = std::min(v.sig_v.size(), v.sig_a.size()); v.steps = n > 0 ? (int32_t)(n - 1) : 0; return v; @@ -181,26 +185,42 @@ namespace { constexpr int64_t kAlign = 256; +/* The segment boundaries a step with references may have: text, keyframes, a segment or two a + * reference at nine pictures, three videos and three soundtracks, the two latents, the end. */ +constexpr int64_t kSegCap = 64; +/* An encode pass's geometry, rad_arch_encode_geom's int32s at most. */ +constexpr int64_t kEncGeomCap = 32; + /* 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) { + * allocation and the VRAM budget. `ep` and `pd` are the vision tower's patches a pass and patch + * width, 0 without one. */ +int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd, + 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[] = { 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 */ + 3 * max_tok * 4, /* R_ROPE: a step's positions, or the prompt's M-RoPE */ RAD_VGEOM_N * 4, /* R_GEOM */ - 6 * 4, /* R_SCHED */ + 16 * 4, /* R_SCHED */ d.max_steps * 4, /* R_TV */ d.max_steps * 4, /* R_TA */ 4 * 4, /* R_SEED */ 4, /* R_LANE */ 4, /* R_FIRST */ - 4 * 4, /* R_SEG */ + kSegCap * 4, /* R_SEG */ + 2 * kSegCap * 4, /* R_MOD: the boundaries, then a cell a group */ 4 * 4, /* R_LAT */ 4, /* R_UP */ + d.max_text * 4, /* R_MMROW: a row a placeholder token */ + ep * pd * 2, /* R_ENCPIX: [ep, pd] bf16 */ + 4 * ep * 4, /* R_ENCCRD: [4, ep] i32 */ + (ep + 2) * 4, /* R_ENCCU */ + d.max_enc_frames * d.max_enc_side * d.max_enc_side * 3 * 4, /* R_ENCPX: f32 */ + d.max_enc_samples * d.audio_channels * 4, /* R_ENCSM: f32 */ + kEncGeomCap * 4, /* R_ENCG */ d.image_cond ? d.max_area * 3 * 2 : 0, /* R_IMG: a first frame, bf16 */ 8 * 4, /* R_GUIDE */ }; @@ -224,16 +244,23 @@ int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) { return (num / d.fps_num + 1) * (d.sample_rate / d.audio_rate); } +/* The vision tower's patches a pass and patch width, 0 without a tower. */ +void encoder_bounds(const Program& prog, int64_t* ep, int64_t* pd) { + *ep = prog.encoder.modalities != 0 ? prog.ctx.max_enc_patches : 0; + *pd = prog.encoder.modalities != 0 ? prog.encoder.patch_dim : 0; +} } /* namespace */ int64_t VideoDriver::device_bytes(const Program& prog) { if (!prog.is_video_generator()) return 0; + int64_t ep = 0, pd = 0; + encoder_bounds(prog, &ep, &pd); int64_t b[R_N][2]; - return carve(prog.video_gen, prog.ctx.max_tok, b, R_N); + return carve(prog.video_gen, prog.ctx.max_tok, ep, pd, b, R_N); } int VideoDriver::init(const Program& prog, PositionsFn positions, - const std::vector& ranks) { + const std::vector& ranks, PackFn pack, EncodeGeomFn enc_geom) { fini(); if (!prog.is_video_generator()) return RAD_E_STATE; decl_ = prog.video_gen; @@ -242,7 +269,10 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, name_ = prog.vgen_str.name; ranks_ = ranks; positions_ = positions; + pack_ = pack; + enc_geom_ = enc_geom; max_tok_ = prog.ctx.max_tok; + encoder_bounds(prog, &max_enc_, &patch_dim_); if (!positions_) { RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a " "video generator must", name_.c_str()); @@ -262,7 +292,7 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, return RAD_E_UNSUPPORTED; } int64_t b[R_N][2]; - bytes_ = carve(decl_, max_tok_, b, R_N); + bytes_ = carve(decl_, max_tok_, max_enc_, patch_dim_, b, R_N); for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; } frames_bytes_ = frames_bytes_of(decl_); @@ -349,6 +379,137 @@ int32_t VideoDriver::predicted_chunks(double log_seconds, std::string* note) con return (int32_t)n; } +/* The encode passes and the reference table (RadVideoGenBatch::ref_tab) of a request's media, in + * the order of `refs`. A video's soundtrack is in the video's row and encoded under its number. + * The latent counts are rad_arch_encode_geom's, which refuses here the media an encode pass would + * fail the engine on. */ +int VideoDriver::plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::string* why) const { + const RadVideoGenDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + j.ref_tab.clear(); + j.enc_q.clear(); + if (r.refs.empty()) return RAD_OK; + if (!pack_ || !enc_geom_) + return no("this model conditions on no reference media"); + int32_t eg[kEncGeomCap]; + /* A picture's or video's latent frames or a soundtrack's latents, -1 for media refused. */ + auto latents = [&](const VideoRefMedia& m) -> int64_t { + const bool audio = m.kind == VideoRefMedia::AUDIO || m.kind == VideoRefMedia::VIDEO_AUDIO; + if (audio ? d.max_enc_samples <= 0 : d.max_enc_side <= 0) return -1; + if (audio ? m.enc_samples.empty() : m.enc_pixels.empty()) return -1; + const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : m.enc_h, + audio ? 0 : m.enc_w, audio ? m.enc_channels : 3 }; + const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE; + if (enc_geom_(kind, in, eg, kEncGeomCap) < 0) return -1; + return audio ? eg[12] : eg[24]; + }; + auto refused = [&](const VideoRefMedia& m) { + return no("'" + m.name + "' is not media this model's encoders take (" + + (m.kind == VideoRefMedia::AUDIO || m.kind == VideoRefMedia::VIDEO_AUDIO + ? std::to_string(m.enc_n) + " samples" + : std::to_string(m.enc_w) + "x" + std::to_string(m.enc_h) + ", " + + std::to_string(m.enc_frames) + " frames") + ")"); + }; + auto grid = [&](const VideoRefMedia& m, int32_t* lh, int32_t* lw) { + if (d.enc_ratio < 1 || m.enc_h % d.enc_ratio || m.enc_w % d.enc_ratio) return false; + *lh = m.enc_h / d.enc_ratio; + *lw = m.enc_w / d.enc_ratio; + return true; + }; + std::vector keys; + j.ref_tab.assign(2, 0); + for (size_t i = 0; i < r.refs.size(); ++i) { + const VideoRefMedia& m = r.refs[i]; + if (m.kind == VideoRefMedia::VIDEO_AUDIO) continue; + const int64_t t = latents(m); + int32_t lh = 0, lw = 0; + if (t < 1 || (m.kind != VideoRefMedia::AUDIO && !grid(m, &lh, &lw))) return refused(m); + if (m.kind == VideoRefMedia::FIRST_FRAME || m.kind == VideoRefMedia::LAST_FRAME) { + if (lh != j.geom.lat_h || lw != j.geom.lat_w) + return no("'" + m.name + "' is not the video's size"); + const int32_t n = (int32_t)keys.size() / 3 + 1; + j.enc_q.push_back({ RAD_ENC_KEYFRAME, n, (int32_t)i }); + keys.insert(keys.end(), { m.kind == VideoRefMedia::FIRST_FRAME ? 0 : frames - 1, + (int32_t)t, 0 }); + continue; + } + int32_t kind = RAD_VREF_PICTURE, enc = RAD_ENC_IMAGE, sound = 0; + int64_t cap = d.max_ref_images; + if (m.kind == VideoRefMedia::AUDIO) { + kind = RAD_VREF_AUDIO; + enc = RAD_ENC_AUDIO; + cap = d.max_ref_audios; + } else if (m.kind == VideoRefMedia::VIDEO) { + kind = RAD_VREF_VIDEO; + enc = RAD_ENC_VIDEO; + cap = d.max_ref_videos; + for (size_t k = 0; k < r.refs.size(); ++k) { + const VideoRefMedia& a = r.refs[k]; + if (a.kind != VideoRefMedia::VIDEO_AUDIO || a.index != m.index) continue; + const int64_t at = latents(a); + if (at < 1) return refused(a); + sound = (int32_t)at; + j.enc_q.push_back({ RAD_ENC_VAUDIO, m.index, (int32_t)k }); + } + } + if (m.index < 1 || m.index > cap) + return no("'" + m.name + "' is reference " + std::to_string(m.index) + " of its kind " + "and this model takes " + std::to_string(cap)); + j.enc_q.push_back({ enc, m.index, (int32_t)i }); + ++j.ref_tab[0]; + j.ref_tab.insert(j.ref_tab.end(), + { kind, m.index, lh, lw, kind == RAD_VREF_AUDIO ? 0 : (int32_t)t, + kind == RAD_VREF_AUDIO ? (int32_t)t : sound }); + } + j.ref_tab[1] = (int32_t)keys.size() / 3; + j.ref_tab.insert(j.ref_tab.end(), keys.begin(), keys.end()); + /* The prompt's vision pads: each picture's tokens, which ComfyUI modulates as video. */ + const size_t at = j.ref_tab.size(); + j.ref_tab.push_back(0); + if (r.media) + for (const mm::Placed& pl : r.media->items) { + if (!pl.item || pl.item->kind != mm::Kind::Image) continue; + const int64_t n = (int64_t)pl.item->expand.size(); + if (pl.tok < 0 || n < 1 || pl.tok + n > j.geom.n_text) continue; + ++j.ref_tab[at]; + j.ref_tab.insert(j.ref_tab.end(), { pl.tok, (int32_t)n }); + } + return RAD_OK; +} + +/* A step's packed sequence with the request's references in, at geometry `g`. */ +int VideoDriver::lay_out(const RadVideoGeom& g, const std::vector& tab, Pack* out, + std::string* why) const { + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + int32_t n_seg = 0, n_mod = 0; + const int64_t rows = pack_(&g, tab.data(), nullptr, &n_seg, nullptr, &n_mod, nullptr, 0); + if (rows <= 0 || n_seg < 2 || n_mod < 3 || n_mod % 2 == 0 || n_seg > kSegCap || + n_mod > 2 * kSegCap) + return no("the model cannot lay these references out"); + if (rows > max_tok_) + return no("a step with these references is " + std::to_string(rows) + " rows and a pass " + "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video, " + "or fewer references"); + out->rows = rows; + out->seg.assign((size_t)n_seg, 0); + out->mod.assign((size_t)n_mod, 0); + out->pos.assign((size_t)(3 * rows), 0.0f); + if (pack_(&g, tab.data(), out->seg.data(), &n_seg, out->mod.data(), &n_mod, out->pos.data(), + 3 * rows) != rows) + return no("the model cannot lay these references out"); + const int32_t cells = 1 + *std::max_element(out->mod.begin() + (n_mod + 1) / 2, out->mod.end()); + if (decl_.max_mod_cells > 0 && cells > decl_.max_mod_cells) + return no("these references read " + std::to_string(cells) + " modulations and this " + "model's table holds " + std::to_string(decl_.max_mod_cells)); + return RAD_OK; +} + /* 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. */ @@ -380,6 +541,17 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ 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"); + RAD_TRY(plan_refs(j, r, s.frames, why)); + j.pack = Pack{}; + j.pack_small = Pack{}; + if (!j.ref_tab.empty()) { + /* A keyframe is pinned on the video's grid, which an upscale's small steps are not on. */ + if (r.upscale > 1.0 && j.ref_tab[1] > 0) + return no("a keyframe pins a frame of the video at its size, and latent_upscale " + "denoises a smaller one first: send the keyframe request without " + "latent_upscale"); + RAD_TRY(lay_out(j.geom, j.ref_tab, &j.pack, why)); + } /* 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; @@ -389,7 +561,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ 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); + j.sched = video_schedule(d, steps, first_tokens, own_refine, r.shift_video, r.shift_audio); if (j.sched.steps < 1) return no("the schedule has no steps"); int32_t first_w = r.width, first_h = r.height; if (upscaling) { @@ -437,6 +609,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ 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"); + if (!j.ref_tab.empty()) RAD_TRY(lay_out(j.geom_small, j.ref_tab, &j.pack_small, why)); j.split = evals - refine; j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0); r.ticket->small_width = sw; @@ -456,7 +629,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_ VideoTicket& t = *r.ticket; t.frames = s.frames; t.steps = j.sched.steps; - t.rows = j.rows; + t.rows = j.pack.rows > 0 ? j.pack.rows : j.rows; return RAD_OK; } @@ -471,6 +644,21 @@ 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)); + /* A reference picture is shown to the text encoder too: `media` places it in the prompt. */ + for (const VideoRefMedia& m : r->refs) + if (m.kind == VideoRefMedia::IMAGE && !r->media) + return no("'" + m.name + "' is a reference picture and the prompt does not show it"); + if (r->media) { + int64_t n_patch = 0; + for (const mm::Placed& p : r->media->items) { + if ((int64_t)p.tok + (int64_t)p.item->expand.size() > T) + return no("a reference's placeholder run is placed past the end of the prompt"); + n_patch += p.item->n_patch; + } + if (n_patch > max_enc_) + return no("the pictures are " + std::to_string(n_patch) + " patches; this model " + "encodes at most " + std::to_string(max_enc_) + " in one pass"); + } 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"); @@ -607,7 +795,8 @@ int VideoDriver::upload() { /* The geometry a pass's ops read off the device (RAD_VGEOM_*) for a pass at geometry `g` of * `rows` step rows, with chunk `chunk`'s span when it is a decode's and both grids when the job * upscales. */ -void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk) { +void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, int32_t chunk, + const Pack* pack) { int32_t* g = hptr(R_GEOM); std::memset(g, 0, RAD_VGEOM_N * 4); g[RAD_VGEOM_LAT_FRAMES] = g0.lat_frames; @@ -647,11 +836,16 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, const int64_t video_rows = rows - g0.n_text - audio_rows; *hptr(R_LANE) = j.lane; *hptr(R_FIRST) = j.step == 0; - int32_t* seg = hptr(R_SEG); - seg[0] = 0; - seg[1] = g0.n_text; - seg[2] = (int32_t)(g0.n_text + audio_rows); - seg[3] = (int32_t)rows; + /* A step with references takes the plugin's segments and modulation groups; every other pass + * the plain sequence's segments, which are its modulation groups as well. */ + const std::vector plain = { 0, g0.n_text, (int32_t)(g0.n_text + audio_rows), + (int32_t)rows }; + const std::vector& seg = pack ? pack->seg : plain; + const std::vector& mod = pack ? pack->mod : plain; + std::memcpy(hptr(R_SEG), seg.data(), seg.size() * 4); + std::memcpy(hptr(R_MOD), mod.data(), mod.size() * 4); + reg_[R_SEG].used = (int64_t)seg.size() * 4; + reg_[R_MOD].used = (int64_t)mod.size() * 4; int32_t* lat = hptr(R_LAT); lat[0] = 0; lat[1] = (int32_t)video_rows; @@ -661,7 +855,6 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, reg_[R_GUIDE].used = sizeof j.guidance; reg_[R_LANE].used = 4; reg_[R_FIRST].used = 4; - reg_[R_SEG].used = 4 * 4; reg_[R_LAT].used = 4 * 4; } @@ -688,11 +881,13 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to V.lane_d = dptr(ri, R_LANE); V.first_d = dptr(ri, R_FIRST); V.seg_cu = dptr(ri, R_SEG); + V.mod_cu = dptr(ri, R_MOD); V.lat_cu = dptr(ri, R_LAT); V.n_steps = j.sched.steps; V.t_video = dptr(ri, R_TV); V.t_audio = dptr(ri, R_TA); V.step = j.step; + V.sampler = j.req->sampler; V.sched = dptr(ri, R_SCHED); V.pos = dptr(ri, R_ROPE); V.seed = dptr(ri, R_SEED); @@ -701,6 +896,7 @@ 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.ref_tab = j.ref_tab.empty() ? nullptr : j.ref_tab.data(); V.guidance_h = j.guidance; V.guidance = dptr(ri, R_GUIDE); V.has_image = !j.req->image.empty(); @@ -735,12 +931,18 @@ const RadBatch* VideoDriver::next(int step) { if (!j.audio_done) return build_audio(j, step); if (j.chunk < j.n_chunks) return build_chunk(j, step); } - /* 2. A prompt. */ + /* 2. The encodes of an admitted request's media, before its prompt. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed || j.cond_done) continue; + if (j.enc_next < j.enc_q.size()) return build_encode(j, step); + } + /* 3. A prompt. */ for (auto& jp : jobs_) { Job& j = *jp; if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step); } - /* 3. The oldest lane's next step, or its upscale once its small steps are done. */ + /* 4. The oldest lane's next step, or its upscale once its small steps are done. */ for (auto& jp : jobs_) { Job& j = *jp; if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue; @@ -794,8 +996,45 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { 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); + + /* The prompt's pictures for the vision tower, and its M-RoPE in R_ROPE. */ + StagedMedia sm; + if (j.req->media) { + const mm::PromptMedia& pm = *j.req->media; + int32_t* rope = hptr(R_ROPE); + for (int64_t i = 0; i < T; ++i) { + int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i }; + pm.rope.at(i, p3); + rope[i] = p3[0]; + rope[T + i] = p3[1]; + rope[2 * T + i] = p3[2]; + } + reg_[R_ROPE].used = 3 * T * 4; + sm = stage_media(pm, patch_dim_, hptr(R_ENCPIX), hptr(R_ENCCRD), + hptr(R_ENCCU), hptr(R_MMROW)); + reg_[R_ENCPIX].used = sm.n_patch * patch_dim_ * 2; + reg_[R_ENCCRD].used = 4 * sm.n_patch * 4; + reg_[R_ENCCU].used = (sm.n_seg + 1) * 4; + reg_[R_MMROW].used = sm.n_rows * 4; + } if (upload() < 0) return nullptr; base_batches(j, g, T + N, step); + if (j.req->media) + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + const int ri = (int)r; + B.rope_pos = dptr(ri, R_ROPE); + B.rope_mixed = 1; + B.n_mm_rows = sm.n_rows; + B.mm_rows = sm.n_rows ? dptr(ri, R_MMROW) : nullptr; + B.enc = 0; + B.enc_n_patch = sm.n_patch; + B.enc_pixels = sm.n_patch ? dptr(ri, R_ENCPIX) : nullptr; + B.enc_coord = sm.n_patch ? dptr(ri, R_ENCCRD) : nullptr; + B.enc_n_seg = sm.n_seg; + B.enc_cu = sm.n_seg ? dptr(ri, R_ENCCU) : nullptr; + B.enc_max_seg = sm.max_seg; + } for (size_t r = 0; r < out_.size(); ++r) { RadBatch& B = out_[r]; B.gen = RAD_GEN_PASS_VCOND; @@ -811,8 +1050,15 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { return &out_[0]; } -/* Step i's timesteps and sigmas, the video's then the soundtrack's (RadVideoGenBatch::sched); - * with `to_clean` the next sigmas are 0, so the step lands on its clean estimate. */ +/* Step i's timesteps, sigmas and res_multistep scalars (RadVideoGenBatch::sched). With + * `to_clean` the next sigmas are 0, so the step lands on its clean estimate. res_multistep is + * k-diffusion's at eta 0 (DPM-Solver++ 2M): with h = log(sigma / sigma_next) and + * rs = log(sigma_prev / sigma) / h, + * + * hb1 = (1 - r) (1 + 1 / (2 rs)), hb2 = -(1 - r) / (2 rs), order 2, + * + * and order 1 (Euler) on a step with no last estimate on its grid: the first, the first after an + * upscale (i == split) and one to sigma 0. */ void VideoDriver::stage_sched(const Job& j, int32_t i, bool to_clean) { float* s = hptr(R_SCHED); s[0] = 1.0f - j.sched.sig_v[(size_t)i]; @@ -821,7 +1067,30 @@ void VideoDriver::stage_sched(const Job& j, int32_t i, bool to_clean) { s[3] = 1.0f - j.sched.sig_a[(size_t)i]; s[4] = j.sched.sig_a[(size_t)i]; s[5] = to_clean ? 0.0f : j.sched.sig_a[(size_t)i + 1]; - reg_[R_SCHED].used = 6 * 4; + /* A stream's five: sigma, r, hb1, hb2, order. */ + auto coeffs = [&](const std::vector& sig, float* out) { + const float sg = sig[(size_t)i]; + const float sgn = to_clean ? 0.0f : sig[(size_t)i + 1]; + const float r = sg > 0.0f ? sgn / sg : 0.0f; + float hb1 = 1.0f - r, hb2 = 0.0f, order = 1.0f; + const bool two = sgn > 0.0f && i > 0 && !(j.split > 0 && i == j.split); + if (two) { + const float h = std::log(sg / sgn); + const float h_last = std::log(sig[(size_t)i - 1] / sg); + const float rs = h_last / h; + hb1 = (1.0f - r) * (1.0f + 1.0f / (2.0f * rs)); + hb2 = -(1.0f - r) / (2.0f * rs); + order = 2.0f; + } + out[0] = sg; + out[1] = r; + out[2] = hb1; + out[3] = hb2; + out[4] = order; + }; + coeffs(j.sched.sig_v, s + 6); + coeffs(j.sched.sig_a, s + 11); + reg_[R_SCHED].used = 16 * 4; } /* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped, so @@ -840,8 +1109,11 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; const bool small = small_now(j); const RadVideoGeom& g = small ? j.geom_small : j.geom; - const int64_t rows = small ? j.rows_small : j.rows; - const std::vector& pos = small ? j.pos_small : j.pos; + /* With references the step is the plugin's packed sequence at this size. */ + const Pack* pack = small ? &j.pack_small : &j.pack; + if (pack->rows == 0) pack = nullptr; + const int64_t plain = small ? j.rows_small : j.rows, rows = pack ? pack->rows : plain; + const std::vector& pos = pack ? pack->pos : small ? j.pos_small : j.pos; stage_sched(j, j.step, small && j.step == j.split - 1); std::memcpy(hptr(R_ROPE), pos.data(), pos.size() * 4); reg_[R_ROPE].used = (int64_t)pos.size() * 4; @@ -851,7 +1123,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { cu[0] = 0; cu[1] = (int32_t)rows; reg_[R_CU].used = 2 * 4; - stage_geom(j, g, rows, 0); + stage_geom(j, g, plain, 0, pack); if (upload() < 0) return nullptr; base_batches(j, g, rows, step); for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; @@ -910,6 +1182,73 @@ const RadBatch* VideoDriver::build_chunk(Job& j, int step) { return &out_[0]; } +/* The job's next media through its encoder: its frames padded to whole clips by repeating the + * last, or its samples padded with zeros to the hop, as the plugin's geometry says. */ +const RadBatch* VideoDriver::build_encode(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const Job::EncItem& it = j.enc_q[j.enc_next]; + const VideoRefMedia& m = j.req->refs[(size_t)it.ref]; + const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO; + int32_t* gd = hptr(R_ENCG); + const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : m.enc_h, + audio ? 0 : m.enc_w, audio ? m.enc_channels : 3 }; + const int64_t ng = enc_geom_(audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE, in, gd, + kEncGeomCap); + int64_t stage_frames = 0, stage_samples = 0; + if (audio) { + const int64_t n = m.enc_n, ch = m.enc_channels; + stage_samples = ng > 0 ? gd[0] : 0; + if (stage_samples < n || stage_samples * ch * 4 > reg_[R_ENCSM].bytes) { + fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass"); + return nullptr; + } + float* sm = hptr(R_ENCSM); + std::memset(sm, 0, (size_t)(stage_samples * ch) * 4); + for (int64_t c = 0; c < ch; ++c) + std::memcpy(sm + c * stage_samples, m.enc_samples.data() + c * n, (size_t)n * 4); + reg_[R_ENCSM].used = stage_samples * ch * 4; + } else { + const int64_t nf = m.enc_frames, area = (int64_t)m.enc_h * m.enc_w * 3; + stage_frames = ng > 23 ? gd[23] : 0; + if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) { + fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass"); + return nullptr; + } + float* px = hptr(R_ENCPX); + std::memcpy(px, m.enc_pixels.data(), (size_t)(nf * area) * 4); + for (int64_t f = nf; f < stage_frames; ++f) + std::memcpy(px + f * area, px + (nf - 1) * area, (size_t)area * 4); + reg_[R_ENCPX].used = stage_frames * area * 4; + } + reg_[R_ENCG].used = ng * 4; + stage_seed(j); /* the condition noise draws from the request's seed */ + stage_geom(j, j.geom, j.rows, 0); + if (upload() < 0) return nullptr; + base_batches(j, j.geom, 0, step); + for (size_t r = 0; r < ranks_.size(); ++r) { + const int ri = (int)r; + RadVideoGenBatch& V = vout_[(size_t)r]; + V.enc_geom_d = dptr(ri, R_ENCG); + V.enc_kind = it.kind; + V.enc_slot = it.slot; + if (audio) { + V.enc_samples = dptr(ri, R_ENCSM); + V.enc_n_samples = stage_samples; + V.enc_channels = m.enc_channels; + } else { + V.enc_pixels = dptr(ri, R_ENCPX); + V.enc_frames = (int32_t)stage_frames; + V.enc_height = m.enc_h; + V.enc_width = m.enc_w; + } + } + const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE; + for (auto& B : out_) B.gen = kind; + pass_.kind = kind; + pass_.job = j.id; + return &out_[0]; +} + int VideoDriver::done() { std::lock_guard lk(mu_); const int64_t now = (int64_t)rad_mono_ns(); @@ -939,6 +1278,10 @@ int VideoDriver::done() { j->req->ticket->push(std::move(e)); } break; + case RAD_GEN_PASS_VENCODE: + case RAD_GEN_PASS_AENCODE: + ++j->enc_next; + break; case RAD_GEN_PASS_VSTEP: { ++j->step; VideoEvent e; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index d61b7a55..cc486689 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -13,8 +13,10 @@ * * 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish * a request and free its lane. - * 2. VCOND of an admitted request, so its steps can follow the current request's without a gap. - * 3. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done. + * 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the + * video and audio VAE latents are in the lane's slots before its prompt runs. + * 3. VCOND of an admitted request, so its steps can follow the current request's without a gap. + * 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done. * Requests are denoised one after another, not in turns: a pass is one request's whole * sequence, so taking turns would only delay the first. */ @@ -35,9 +37,14 @@ public: RadStream stream = nullptr; }; using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); + using PackFn = int64_t (*)(const RadVideoGeom*, const int32_t*, int32_t*, int32_t*, int32_t*, + int32_t*, float*, int64_t); + using EncodeGeomFn = int64_t (*)(int32_t, const int64_t*, int32_t*, int64_t); - /* `positions` is the plugin's rad_arch_video_positions. */ - int init(const Program& prog, PositionsFn positions, const std::vector& ranks); + /* The plugin's rad_arch_video_positions, and its rad_arch_video_pack and rad_arch_encode_geom + * (null without reference conditioning, which then refuses every reference). */ + int init(const Program& prog, PositionsFn positions, const std::vector& ranks, + PackFn pack = nullptr, EncodeGeomFn enc_geom = nullptr); void fini(); ~VideoDriver() override { fini(); } @@ -61,6 +68,13 @@ public: int64_t running() const override; private: + /* A step's packed sequence with references in (rad_arch_video_pack). */ + struct Pack { + int64_t rows = 0; + std::vector seg; /* segment boundaries */ + std::vector mod; /* modulation-group boundaries, then a cell a group */ + std::vector pos; /* [3, rows] */ + }; struct Job { uint64_t id = 0; std::unique_ptr req; @@ -70,6 +84,14 @@ private: int64_t n_samples = 0; /* the soundtrack's samples a channel */ VideoSchedule sched; std::vector pos; /* [3, rows] */ + /* References and keyframes: their table (RadVideoGenBatch::ref_tab), the step's packed + * sequence at the full size and at an upscale's small one (rows 0 without references), + * and the encode passes, one a media in order, `enc_next` the next to run. */ + std::vector ref_tab; + Pack pack, pack_small; + struct EncItem { int32_t kind, slot, ref; }; /* RAD_ENC_*, its number, its req->refs */ + std::vector enc_q; + size_t enc_next = 0; /* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and * positions, the factor the network is told, and whether the upscale has run. */ int32_t split = 0; @@ -105,8 +127,12 @@ private: /* Staging regions: their offsets in the host span and every rank's slab. */ struct Region { int64_t off = 0, bytes = 0, used = 0; }; + /* R_MMROW .. R_ENCCU are the prompt's pictures for the vision tower, as the image driver + * stages them (driver.cpp), and R_ROPE then their M-RoPE; R_ENCPX .. R_ENCG an encode pass's + * media and geometry. */ 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_IMG, R_GUIDE, R_N }; + R_SEG, R_MOD, R_LAT, R_UP, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_ENCPX, R_ENCSM, + R_ENCG, 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 { @@ -116,9 +142,13 @@ private: /* 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); + int plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::string* why) const; + int lay_out(const RadVideoGeom& g, const std::vector& tab, Pack* out, + std::string* why) const; 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_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk, + const Pack* pack = nullptr); void stage_sched(const Job& j, int32_t i, bool to_clean); void stage_seed(const Job& j); @@ -132,6 +162,7 @@ private: const RadBatch* build_upscale(Job& j, int step); const RadBatch* build_audio(Job& j, int step); const RadBatch* build_chunk(Job& j, int step); + const RadBatch* build_encode(Job& j, int step); RadVideoGenDecl decl_{}; std::vector rungs_; /* decl_.rungs points here */ @@ -141,7 +172,11 @@ private: std::vector decoder_area_; /* each one's largest frame */ std::string name_; PositionsFn positions_ = nullptr; + PackFn pack_ = nullptr; + EncodeGeomFn enc_geom_ = nullptr; int64_t max_tok_ = 0; + /* The vision tower's patch width and the patches a pass carries; 0 without a tower. */ + int64_t patch_dim_ = 0, max_enc_ = 0; std::vector ranks_; char* host_ = nullptr; /* pinned, same layout as each slab */ diff --git a/core/kvstream/bind.cpp b/core/kvstream/bind.cpp new file mode 100644 index 00000000..52cbf2f2 --- /dev/null +++ b/core/kvstream/bind.cpp @@ -0,0 +1,84 @@ +/* bind.cpp -- see bind.h. */ +#include "kvstream/bind.h" + +#include "kvstream/plan.h" + +namespace rad { + +void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b) { + if (!b || !p.paged()) return; + b->base = p.base; + + b->ring.layer_stride = p.layer_stride(); + b->ring.bytes = kv_ring_bytes(p, p.pool_blocks()); + b->ring.depth = 0; + b->ring.shape0 = p.pool_blocks(); + + b->has_stage = p.depth == 1; + if (b->has_stage) { + b->stage.layer_stride = p.n_blocks * p.layer_bytes_per_block(); + b->stage.bytes = b->stage.layer_stride; + b->stage.depth = 1; + b->stage.shape0 = p.n_blocks; + } + + kv_binding_enter(*b, KVView::Ring); +} + +int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer) { + return b.depth == 1 ? 0 : layer * b.layer_stride; +} + +KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec) { + /* The serial drafter's history pass is labelled decode but runs over a prefill chunk's tokens, + * whose union no ring bound covers, so it stages. */ + if (phase != RAD_PHASE_DECODE) return KVView::Stage; + const int64_t rows = (int64_t)n_seq * (1 + (n_spec > 0 ? n_spec : 0)); + return n_tok > rows ? KVView::Stage : KVView::Ring; +} + +void kv_binding_enter(KVPoolBinding& b, KVView view) { + const KVViewState& v = (view == KVView::Stage && b.has_stage) ? b.stage : b.ring; + b.layer_stride = v.layer_stride; + b.bytes = v.bytes; + b.depth = v.depth; + b.shape[0] = v.shape0; +} + +namespace { +template +T* on_rank(const void* base_r, const void* base_0, T* p0) { + return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr; +} +} /* namespace */ + +uint64_t kvstream_view_key(const RadKVStream* v) { + if (!v) return 0; + uint64_t h = 0x9e3779b97f4a7c15ull; + auto mix = [&](uint64_t x) { + h ^= x + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2); + h *= 0xbf58476d1ce4e5b9ull; + }; + auto p = [&](const void* q) { mix((uint64_t)(uintptr_t)q); }; + p(v->host); p(v->res); p(v->slot_block); p(v->slot_state); + p(v->ctl); + mix((uint64_t)v->block_bytes); mix((uint64_t)v->host_layer_stride); + mix((uint64_t)v->slots); mix((uint64_t)v->host_bytes); + return h | 1; +} + +const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank, + const void* kv0, const void* kvr) { + if (!src) return nullptr; + *out = *src; + /* Rebase a follower's maps into its own pool by the offset its arena buffers take. */ + if (!per_rank && kv0 && kvr) { + out->res = on_rank(kvr, kv0, src->res); + out->slot_block = on_rank(kvr, kv0, src->slot_block); + out->slot_state = on_rank(kvr, kv0, src->slot_state); + out->ctl = on_rank(kvr, kv0, src->ctl); + } + return out; +} + +} /* namespace rad */ diff --git a/core/kvstream/bind.h b/core/kvstream/bind.h new file mode 100644 index 00000000..0dd01148 --- /dev/null +++ b/core/kvstream/bind.h @@ -0,0 +1,49 @@ +/* bind.h -- the two views of a streamed group's one pool allocation. + * + * The stage view aliases every layer to offset 0 by reporting depth 1; `layer_slot` keeps each + * layer's group-local position, because that is also its row in the host mirror + * (docs/KV-STREAMING.md §3.5.1). + * + * A pass takes a view from its phase and row shape, before it is recorded or replayed. A decode + * pass of at most 1 + n_spec rows a sequence takes the ring: its selection is rewritten to ring + * slots and misses are copied in. Every other pass (prefill, mixed, and a decode-classified pass + * with more rows a sequence, such as the serial drafter's history pass) takes the stage, the + * group's context at block-id addressing, where no selection can overflow. `phase`, `n_tok`, + * `n_seq` and `n_spec` are in the pass key, so a recorded pass replays against its view. + */ +#pragma once +#include "mem/kv.h" +#include "runtime/ctx.h" + +namespace rad { + +enum class KVView { Ring, Stage }; + +/* Fill both views from the carved plan and make the ring active. A non-paged group is left + * untouched. */ +void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b); + +/* A layer's offset in the active view: 0 at depth 1. The `off + layer_stride <= bytes` bound in + * issue.cpp holds for both views. */ +int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer); + +/* The view a pass with this phase and row shape takes (see the header). */ +KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec); + +/* Make `view` active; the stage falls back to the ring when the group has none. */ +void kv_binding_enter(KVPoolBinding& b, KVView view); + +/* One rank's step view of a group's ring and mirror, copied into `out`; null when the group does + * not stream. With `per_rank`, `src` is that rank's own manager's view: its maps live in that + * rank's KV pool and its mirror is that rank's pinned allocation. Without (tests), `src` is rank + * 0's and its map pointers are rebased from rank 0's pool (`kv0`) into this rank's (`kvr`). The + * addresses are fixed at bring-up. */ +const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank, + const void* kv0, const void* kvr); + +/* A step view's identity for Ctx::pass_key: the memory a kernel reads, never the struct's address. + * The batch copies the view into one of the builder's rotating Out slots, so keying on its address + * would make every streamed decode step a new pass that never replays. */ +uint64_t kvstream_view_key(const RadKVStream* v); + +} /* namespace rad */ diff --git a/core/kvstream/bringup.cpp b/core/kvstream/bringup.cpp new file mode 100644 index 00000000..1f212780 --- /dev/null +++ b/core/kvstream/bringup.cpp @@ -0,0 +1,183 @@ +/* bringup.cpp -- see bringup.h. */ +#include "kvstream/bringup.h" + +#include "device/device.h" +#include "engine_hostmem.h" +#include "kvstream/plan.h" + +#include +#include + +namespace rad { + +/* The ops whose only job is the host mirror or the ring. `kv_store` and the fused + * `qk_norm_rope_gate_kv_store` serve resident groups too. */ +static const char* const kStreamOnlyOps[] = { + "kv_store_streamed", + "qk_norm_rope_gate_kv_store_streamed", + "kv_resolve", +}; + +bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op) { + if (!op) return false; + if (ctx.kv_stream_ok != 0 && ctx.kv_resident_blocks > 0) return false; /* a ring is carved */ + for (const char* s : kStreamOnlyOps) + if (std::strcmp(s, op) == 0) return true; + return false; +} + +int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector& groups, + const Program& prog, KVStreamSetup* out) { + *out = KVStreamSetup{}; + if (cfg.kv_resident <= 0) return RAD_OK; + /* On Flash-Next the group is `kv_attn`. The indexer's `kv_qsa_bkey` is full too, but qsa_score + * reads it over the whole history every step, so it is dense-read and stays resident + * (docs/KV-STREAMING.md §2). A model with only windowed groups has nothing to stream. */ + int32_t g = kv_stream_group(groups, &prog); + /* With no streamed path anywhere, the widest full group is still chosen, so the warning below + * can name it and the op it lacks. */ + if (g < 0) g = kv_stream_group(groups); + if (g < 0) return RAD_OK; + const KVGroupInfo& gi = groups[(size_t)g]; + const int64_t bs = gi.block_size > 0 ? gi.block_size : 1; + /* A ring that covers the context is not a refusal: the group stays a resident pool. */ + const KVStreamRing shape = kvstream_ring_shape(cfg, ctx, bs); + out->asked_tokens = cfg.kv_resident; + out->context_tokens = ctx * cfg.max_seqs; + out->group_name = gi.name; + out->ring_blocks = shape.ring_blocks; + out->ring_tokens = shape.ring_blocks * bs; + out->block_size = bs; + out->ctx_blocks = shape.ctx_blocks; + if (!shape.streams()) return RAD_OK; + /* Before anything is allocated: the group needs the ops its streamed path issues (KVStreamOps). + * The gated fp8 attention (rad_block_attn_gated_fp8.h) and GLM-5.3's MLA block + * (rad_block_glm_mla.h) declare both. Without them the flag is ignored and the configuration is + * exactly the one without it. */ + const KVStreamOps ops = kvstream_ops(prog, &gi); + if (!ops.streams()) { + /* A packed cache (fp8_v4, k6_v4) is declared to the core as plain E4M3, so the dtype check + * below cannot see it; its architecture declares the resolve but no store row. The + * operator's answer is then the cache layout, not the model. */ + if ((cfg.kv_cache_dtype == "fp8_v4" || cfg.kv_cache_dtype == "k6_v4") && ops.resolve && + !ops.store && !ops.folded) + RAD_WARN("--kv-resident %lld ignored: group '%s' has a %s cache, and the streamed store " + "has no writer for that layout (E4M3 and bf16 only); the group stays " + "resident", + (long long)cfg.kv_resident, gi.name.c_str(), cfg.kv_cache_dtype.c_str()); + else + RAD_WARN("--kv-resident %lld ignored: architecture '%s' declares no %s for group '%s', " + "so the group stays resident", + (long long)cfg.kv_resident, + prog.meta.arch_id && *prog.meta.arch_id ? prog.meta.arch_id : "(unnamed)", + ops.missing(), gi.name.c_str()); + *out = KVStreamSetup{}; + return RAD_OK; + } + /* The streamed store has E4M3 and bf16 rows only. Packed layouts were ignored above; this + * refuses a core dtype no architecture ships a full group in (f32, f16). */ + if (gi.decl.dtype != RAD_F8E4M3 && gi.decl.dtype != RAD_BF16) { + RAD_ERR("--kv-resident %lld: group '%s' has a %s cache, and the streamed store has E4M3 " + "and bf16 rows only (--kv-cache-dtype fp8 or bf16); leave --kv-resident off", + (long long)cfg.kv_resident, out->group_name.c_str(), + rad_dtype_name(gi.decl.dtype)); + return RAD_E_INVAL; + } + KVStreamRing ring; + kvstream_ring(cfg, ctx, bs, ops.sel_pitch, &ring); + if (ring.raised_blocks > 0) { + /* The line names the floor that bound: one decode step's selection (a correctness bound) or + * kStreamFloorTokens (a cost bound). */ + const int64_t asked_blocks = (out->asked_tokens + bs - 1) / bs; + const int64_t step = kvstream_ceiling_blocks(cfg, ops.sel_pitch); + if (ring.by_union && step > asked_blocks) { + RAD_WARN("--kv-resident %lld raised to %lld tokens: one decode step can select %lld " + "blocks of %lld tokens (--max-num-seqs %lld x %lld rows x %lld), and the ring " + "must hold them", + (long long)out->asked_tokens, (long long)(ring.ring_blocks * bs), + (long long)step, (long long)bs, + (long long)(cfg.max_seqs > 0 ? cfg.max_seqs : 1), + (long long)(1 + (cfg.n_spec > 0 ? cfg.n_spec : 0)), + (long long)ops.sel_pitch); + } else { + RAD_WARN("--kv-resident %lld raised to %lld tokens: a ring under %lld tokens (%lld " + "blocks of %lld) misses more than it saves", + (long long)out->asked_tokens, (long long)(ring.ring_blocks * bs), + (long long)kStreamFloorTokens, (long long)ring.raised_blocks, (long long)bs); + } + } + /* The raised ring may cover the whole context, which does not stream. */ + out->ring_blocks = ring.ring_blocks; + out->ring_tokens = ring.ring_blocks * bs; + out->raised_tokens = ring.raised_blocks > 0 ? ring.ring_blocks * bs : 0; + out->raised_by_union = ring.raised_blocks > 0 && ring.by_union; + out->group = ring.streams() ? g : -1; + /* Prefill takes the stage and never resolves: above `qsa_exact_to` a launch selects a chunk's + * union, which no ring could hold. The stage is the group's context one layer deep, addressed + * by block id (kvstream/bind.h says which passes take it). */ + out->stage_blocks = ring.streams() ? ring.ctx_blocks : 0; + return RAD_OK; +} + +void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv) { + const KVStreamCost c = kv.stream_cost(); + use->sum.groups += c.groups; + use->sum.host_bytes += c.host_bytes; + use->sum.map_bytes += c.map_bytes; + use->max_rank_bytes = std::max(use->max_rank_bytes, c.host_bytes); +} + +int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom) { + if (use.sum.host_bytes <= 0) return RAD_OK; + std::string why; + if (lockable_room(use.sum.host_bytes, still, headroom, false, &why)) return RAD_OK; + RAD_ERR("kv streaming: the host mirror for %lld streamed KV group(s) needs up to %s of " + "pinned host memory a rank (%s over %d ranks), and %s. It holds one full context a " + "sequence: lower --max-model-len or --max-num-seqs, or set --kv-resident 0 " + "(--host-pool-mib sizes the experts' tier, not this one)", + (long long)use.sum.groups, humanb(use.max_rank_bytes).c_str(), + humanb(use.sum.host_bytes).c_str(), n_ranks, why.c_str()); + return RAD_E_NOMEM; +} + +int kvstream_fill(KVManager& kv) { + /* After the carve, which backs an elastic pool's range; drained before the first pass reads the + * maps. */ + RadStream st = nullptr; + int rc = rad_stream_create(&st, 0); + if (rc == RAD_OK) rc = kv.init_stream(st); + if (rc == RAD_OK) rc = rad_stream_sync(st); + rad_stream_destroy(st); + return rc; +} + +void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks) { + const int64_t flag = s.raised_tokens > 0 ? s.raised_tokens : s.asked_tokens; + if (s.raised_tokens > 0 && s.block_size > 0) + RAD_INFO("kv streaming: --kv-resident %lld became %lld tokens (%lld -> %lld blocks of " + "%lld tokens), %s", + (long long)s.asked_tokens, (long long)s.raised_tokens, + (long long)((s.asked_tokens + s.block_size - 1) / s.block_size), + (long long)(s.raised_tokens / s.block_size), (long long)s.block_size, + s.raised_by_union ? "the blocks one decode step can select" + : "the floor below which misses cost more than the ring saves"); + if (host.sum.groups > 0) + RAD_INFO("kv streaming: %lld group(s) stream (%s): up to %s of pinned host mirror a " + "rank (%s over %d), %s of ring maps in the KV pools", + (long long)host.sum.groups, s.group_name.c_str(), + humanb(host.max_rank_bytes).c_str(), humanb(host.sum.host_bytes).c_str(), n_ranks, + humanb(host.sum.map_bytes).c_str()); + if (s.stage_blocks > 0) + RAD_INFO("kv streaming: prefill staging, group '%s' ring %lld blocks, one-layer stage %lld " + "blocks (one layer of its %lld-block context); decode passes use the ring", + s.group_name.c_str(), (long long)s.ring_blocks, + (long long)s.stage_blocks, (long long)s.ctx_blocks); + if (s.group < 0 && s.asked_tokens > 0 && s.ctx_blocks > 0) + RAD_INFO("kv streaming: nothing streams: --kv-resident %lld covers group '%s''s " + "%lld-token context (%lld blocks), so the group stays resident; below %lld " + "tokens it would stream", + (long long)flag, s.group_name.c_str(), (long long)s.context_tokens, + (long long)s.ctx_blocks, (long long)s.context_tokens); +} + +} /* namespace rad */ diff --git a/core/kvstream/bringup.h b/core/kvstream/bringup.h new file mode 100644 index 00000000..9d544cba --- /dev/null +++ b/core/kvstream/bringup.h @@ -0,0 +1,78 @@ +/* bringup.h -- the engine side of a streamed group's bring-up (docs/KV-STREAMING.md §4.1). + * + * `--kv-resident N` is the only switch: absent or 0 nothing streams, and a ring that covers the + * group's context streams nothing either, so the group keeps the resident path at no cost. This + * module chooses the group, refuses what cannot stream, applies the ring's floors, gates the host + * mirrors against host RAM, fills the maps and reports, so core/engine_bringup.cpp makes one call + * at each seam. + */ +#pragma once +#include "mem/kv.h" + +#include +#include + +namespace rad { + +struct Config; + +/* What --kv-resident resolved to. `group` is -1 when nothing streams; the other fields then say + * what was asked and why, for the report. */ +struct KVStreamSetup { + int32_t group = -1; /* the group that streams; -1 when none does */ + std::string group_name; /* the group that would have */ + int64_t asked_tokens = 0; /* --kv-resident as given */ + int64_t raised_tokens = 0; /* the ring a floor raised it to; 0 when not raised */ + bool raised_by_union = false; /* raised to the decode-step bound, not the floor */ + int64_t context_tokens = 0; /* --max-model-len x --max-num-seqs */ + int64_t ring_tokens = 0; /* the carved ring, in tokens */ + int64_t ring_blocks = 0; /* the carved ring, in blocks */ + int64_t block_size = 0; /* the group's page, in tokens */ + int64_t ctx_blocks = 0; /* the group's id space, in blocks */ + int64_t stage_blocks = 0; /* the stage view's depth in blocks; 0 when none */ +}; + +/* The host mirrors summed over the ranks; `max_rank_bytes` is the largest one rank pins (an uneven + * tensor-parallel split gives ranks different shards). */ +struct KVStreamHostUse { + KVStreamCost sum; + int64_t max_rank_bytes = 0; +}; + +/* Whether `op` must not be declared: the streamed-only ops (kv_store_streamed, its folded form, + * kv_resolve) exist only for a carved ring, so a run that carves none must not have them in its + * graph. False when the architecture streams (RadBuildCtx::kv_stream_ok) and --kv-resident asks + * for a ring. Every architecture's rad_op_declared check then falls through to its resident path. */ +bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op); + +/* Read --kv-resident against rank 0's declarations and fill `out`; RAD_OK with group -1 when + * nothing streams. + * + * - The group is kv_stream_group's. A ring that covers its context streams nothing. + * - An architecture with no streamed path for the group (kvstream_ops: no kv_resolve, or no + * streamed store, as for a packed fp8_v4 / k6_v4 cache) ignores the flag with one warning + * naming the missing op or the layout; `out` is then exactly the no-flag configuration. + * - A core dtype other than E4M3 or bf16 is refused: the streamed store has rows for those only. + * - A ring below the decode-step bound or kStreamFloorTokens is raised, with one warning. + * --kv-resident itself is left as given; `out` holds both numbers for the report. */ +int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector& groups, + const Program& prog, KVStreamSetup* out); + +/* Add one rank's stream_cost() to `use`. */ +void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv); + +/* The host-RAM gate for the mirrors, checked once before any rank pins one. A mirror is one full + * context of the group per sequence per rank, the largest host allocation after the experts' + * pool, so it is checked against everything still to be pinned after it (`still`). A refusal + * names --max-model-len and --max-num-seqs, which size it; --host-pool-mib sizes the experts' pool + * and cannot make room here. */ +int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom); + +/* After the carve: fill the maps on a bring-up stream and drain it. */ +int kvstream_fill(KVManager& kv); + +/* The startup lines: the raised ring, which group streams and what it took on both tiers, the + * stage, or which context a ring given by the flag covers. */ +void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks); + +} /* namespace rad */ diff --git a/core/kvstream/carve.cpp b/core/kvstream/carve.cpp new file mode 100644 index 00000000..0764c8a4 --- /dev/null +++ b/core/kvstream/carve.cpp @@ -0,0 +1,141 @@ +/* carve.cpp -- see carve.h. */ +#include "kvstream/carve.h" + +#include "kvstream/mirror.h" +#include "kvstream/plan.h" +#include "mem/kv.h" + +namespace rad { + +int64_t kvstream_maps_charged(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs) { + return st.cost(plans, max_ctx, max_seqs).map_bytes; +} + +bool kvstream_dense(const KVGroupPlan& p, const std::vector& plans, + const KVStreamStore& st) { + if (!p.paged() || p.zero || p.kind != RAD_KV_FULL || !p.dense_read) return false; + for (const auto& q : plans) + if (!q.zero && q.paged() && st.windowed(q.index)) return true; + return false; +} + +int64_t kvstream_dense_charged(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs) { + int64_t bytes = 0; + for (const auto& p : plans) { + if (!kvstream_dense(p, plans, st)) continue; + bytes += align_up(kv_context_blocks(p.block_size, max_ctx, max_seqs) * p.bytes_per_block, + RAD_ALIGN_UNIT); + } + return bytes; +} + +void kvstream_split_windows(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs, int64_t* remaining, + std::vector* out) { + for (const auto& p : plans) { + if (!p.paged() || p.zero || !st.windowed(p.index)) continue; + const int64_t slots = st.resident_blocks(p); + *remaining -= kv_pool_bytes(p, slots, st.context_blocks(p, max_ctx, max_seqs)); + (*out)[p.index] = slots; + } + /* The maps, which the probe cannot reserve yet, or the pool it sizes falls short by them. */ + *remaining -= kvstream_maps_charged(plans, st, max_ctx, max_seqs); + /* A dense-read group's floor is every sequence's context, fixed by the configuration. */ + for (const auto& p : plans) { + if (!kvstream_dense(p, plans, st)) continue; + const int64_t blocks = kv_context_blocks(p.block_size, max_ctx, max_seqs); + *remaining -= align_up(blocks * p.bytes_per_block, RAD_ALIGN_UNIT); + (*out)[p.index] = blocks; + } +} + +int kvstream_window_fit(const std::vector& plans, const KVStreamStore& st, + int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs) { + int64_t window_bytes = 0; + int64_t window_groups = 0; + for (const auto& p : plans) { + if (!p.paged() || p.zero || !st.windowed(p.index)) continue; + if (p.kind != RAD_KV_FULL) { + RAD_ERR("KV group '%s' is a %s group and streaming is set for it: only a full " + "attention group streams (a window's block ids are its window's, not its " + "context's)", + p.name.c_str(), kv_kind_name(p.kind)); + return RAD_E_INVAL; + } + window_bytes += kv_pool_bytes(p, st.resident_blocks(p), + st.context_blocks(p, max_ctx, max_seqs)); + ++window_groups; + } + const int64_t map_bytes = kvstream_maps_charged(plans, st, max_ctx, max_seqs); + const int64_t dense_bytes = kvstream_dense_charged(plans, st, max_ctx, max_seqs); + int64_t dense_groups = 0; + for (const auto& p : plans) if (kvstream_dense(p, plans, st)) ++dense_groups; + if (fixed + window_bytes + map_bytes + dense_bytes > budget) { + RAD_ERR("the resident KV windows and dense-read groups do not fit vram_kv:\n" + " resident windows %10s (%lld group(s) streaming)\n" + " ring maps %10s (the streamed groups' residency maps)\n" + " dense-read groups %10s (%lld group(s) at %lld sequences x %lld tokens)\n" + " linear/conv state %10s (%lld sequences)\n" + " vram_kv %10s\n" + " short by %10s\n" + "Lower --kv-resident (the ring) or --max-model-len / --max-num-seqs (the one-layer " + "stage and the dense-read floor), or give the cache more of the card: a smaller " + "--gpu-headroom-mib or a larger --host-pool-mib.", + humanb(window_bytes).c_str(), (long long)window_groups, + humanb(map_bytes).c_str(), humanb(dense_bytes).c_str(), (long long)dense_groups, + (long long)max_seqs, (long long)max_ctx, humanb(fixed).c_str(), + (long long)max_seqs, humanb(budget).c_str(), + humanb(fixed + window_bytes + map_bytes + dense_bytes - budget).c_str()); + return RAD_E_NOMEM; + } + return RAD_OK; +} + +int kvstream_apply(std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs) { + for (auto& p : plans) { + if (!p.paged()) continue; + if (st.windowed(p.index) && !p.zero) { + /* The split gave a streamed group its window; its ids run over its context. */ + p.n_blocks = st.context_blocks(p, max_ctx, max_seqs); + p.n_slots = st.resident_blocks(p); + /* A ring that covers the context never reaches here (kvstream_ring), so the group has a + * stage. */ + p.depth = p.streamed() ? 1 : 0; + } else { + p.n_slots = p.n_blocks; + } + if (p.n_slots > p.n_blocks) p.n_slots = p.n_blocks; + /* A streamed group has no tier entry (its mirror is its tier), so replication, which + * describes the tier slot, does not apply. */ + if (p.streamed()) p.replicated = false; + /* An unbacked block id would be written past the layer stride: fluent wrong output, so + * refuse here. RAD_E_INVAL, since RAD_E_STATE reads as "called in the wrong phase". */ + if (p.streamed()) { + const KVStreamStore::Map* m = st.map(p.index); + const int64_t need = p.n_blocks * p.bytes_per_block; + if (!m || !m->host || !m->res || m->host_bytes < need) { + RAD_ERR("KV group '%s' streams (%lld of its %lld blocks resident) but has no host " + "mirror of %s and residency map to hold the rest: an engine bug", + p.name.c_str(), (long long)p.n_slots, (long long)p.n_blocks, + humanb(need).c_str()); + return RAD_E_INVAL; + } + } + } + return RAD_OK; +} + +std::string kvstream_report_line(const KVGroupPlan& p) { + return fmt(" %-14s %-6s streaming: %7lld blocks resident in vram_kv at " + "+%lld = %9s, %7lld blocks = %9s mirrored in pinned host memory, " + "maps %s\n", "", "", (long long)p.pool_blocks(), + (long long)p.pool_offset, humanb(p.pool_bytes).c_str(), + (long long)p.n_blocks, + humanb(p.n_blocks * p.bytes_per_block).c_str(), + humanb(kvstream_map_bytes(p.n_blocks, p.pool_blocks(), p.n_layers)).c_str()); +} + +} /* namespace rad */ diff --git a/core/kvstream/carve.h b/core/kvstream/carve.h new file mode 100644 index 00000000..b8d574c7 --- /dev/null +++ b/core/kvstream/carve.h @@ -0,0 +1,58 @@ +/* carve.h -- the streamed groups' part of KVManager::carve() (docs/KV-STREAMING.md §4.1, §4.2): + * the resident windows and dense-read floors leave the budget before the other groups split the + * rest; after the split each paged group's n_slots (and a streamed group's context and depth) is + * written, refusing a streamed group with nothing to back its other blocks; and the pool report + * gains a line naming both tiers. Arithmetic on the plans only. + */ +#pragma once +#include +#include +#include + +namespace rad { + +struct KVGroupPlan; +class KVStreamStore; + +/* Bytes the streamed groups' maps take from the KV pool (KVStreamStore::cost). They are reserved + * before carve(), so the budget probe, which cannot reserve them, charges them in paged_split() + * and the carve adds them back to its budget: both then see the same bytes. */ +int64_t kvstream_maps_charged(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs); + +/* Whether `p` is a dense-read group (rad_kv_group_dense_read: an indexer's block keys, read over + * the whole history every step) while a sibling streams. Its pool must then hold every sequence's + * context, since the sibling's mirror is sized for max_seqs. False when nothing streams: the cache + * is then sized for one full-length sequence. */ +bool kvstream_dense(const KVGroupPlan& p, const std::vector& plans, + const KVStreamStore& st); + +/* The dense-read groups' full contexts in bytes, rounded as reserve() rounds them. */ +int64_t kvstream_dense_charged(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs); + +/* Take the streamed groups' windows, their maps and the dense-read groups' full contexts out of + * the split before the other groups share the rest: `remaining` loses their bytes and + * `out[group]` becomes the window's depth (or the dense-read context) in blocks. A streamed + * group's context lives in host memory, so it does not compete for the pool. */ +void kvstream_split_windows(const std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs, int64_t* remaining, + std::vector* out); + +/* Refuse windows and dense-read floors that do not fit `budget`, before anything is split. + * Otherwise the other groups would be left zero blocks and refused for a small pool, pointing the + * operator at the wrong flag. The fixed costs were checked by the caller. A window group cannot + * stream: its ids are its window's, not its context's. */ +int kvstream_window_fit(const std::vector& plans, const KVStreamStore& st, + int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs); + +/* After the split: write every paged group's n_slots (its carve unless it streams) and, for a + * streamed group, its context as n_blocks and its depth. Refuses a streamed group whose host + * mirror or residency map is missing. */ +int kvstream_apply(std::vector& plans, const KVStreamStore& st, + int64_t max_ctx, int64_t max_seqs); + +/* The pool report's extra line for a streamed group, whose pool is smaller than its context. */ +std::string kvstream_report_line(const KVGroupPlan& p); + +} /* namespace rad */ diff --git a/core/kvstream/mirror.cpp b/core/kvstream/mirror.cpp new file mode 100644 index 00000000..c3b5e21e --- /dev/null +++ b/core/kvstream/mirror.cpp @@ -0,0 +1,196 @@ +/* mirror.cpp -- see mirror.h. */ +#include "kvstream/mirror.h" + +#include + +#include "kvstream/plan.h" + +#include +#include +#include + +namespace rad { + +namespace { +int64_t ceil_div(int64_t a, int64_t b) { return b > 0 ? (a + b - 1) / b : 0; } + +/* Each array starts 8-byte aligned: `ctl`'s counters are read as u64 pairs, and an odd block + * count or ring depth would misalign the next array. The pool base is RAD_ALIGN_UNIT aligned. */ +int64_t align8(int64_t n) { return (n + 7) & ~(int64_t)7; } + +/* The maps' one layout, shared by alloc(), init() and kvstream_map_bytes(). */ +struct MapLayout { + int64_t res_bytes = 0, slot_block_bytes = 0, slot_state_bytes = 0, ctl_bytes = 0; + int64_t res = 0, slot_block = 0, slot_state = 0, ctl = 0; + int64_t bytes = 0; /* the whole reservation */ +}; + +MapLayout map_layout(int64_t blocks, int64_t slots, int64_t layers) { + if (layers < 1) layers = 1; + MapLayout l; + l.res_bytes = layers * blocks * (int64_t)sizeof(int32_t); + l.slot_block_bytes = layers * slots * (int64_t)sizeof(int32_t); + l.slot_state_bytes = layers * slots * 2 * (int64_t)sizeof(int32_t); + l.ctl_bytes = 16 * (int64_t)sizeof(int32_t); + l.res = 0; /* res, block -> slot, one map a layer */ + l.slot_block = l.res + align8(l.res_bytes); /* slot_block, slot -> block */ + l.slot_state = l.slot_block + align8(l.slot_block_bytes);/* slot_state: epoch, heat */ + l.ctl = l.slot_state + align8(l.slot_state_bytes);/* ctl, shared by the layers */ + l.bytes = l.ctl + align8(l.ctl_bytes); + return l; +} +} /* namespace */ + +int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers) { + return map_layout(blocks, slots, layers).bytes; +} + +void KVStreamStore::cap(int32_t group, int64_t tokens) { + if (group < 0) return; + if ((size_t)group >= resident_tokens_.size()) resident_tokens_.resize((size_t)group + 1, 0); + resident_tokens_[(size_t)group] = tokens > 0 ? tokens : 0; +} + +bool KVStreamStore::windowed(int32_t group) const { + return group >= 0 && (size_t)group < resident_tokens_.size() && + resident_tokens_[(size_t)group] > 0; +} + +int64_t KVStreamStore::resident_blocks(const KVGroupPlan& p) const { + const size_t g = (size_t)p.index; + if (g >= resident_tokens_.size() || resident_tokens_[g] <= 0 || p.block_size <= 0) return 0; + return ceil_div(resident_tokens_[g], p.block_size); +} + +int64_t KVStreamStore::context_blocks(const KVGroupPlan& p, int64_t max_ctx, + int64_t max_seqs) const { + return kv_context_blocks(p.block_size, max_ctx, max_seqs); +} + +void KVStreamStore::set_map(int32_t group, const Map& m) { + if (group < 0) return; + if ((size_t)group >= maps_.size()) maps_.resize((size_t)group + 1); + maps_[(size_t)group] = m; +} + +const KVStreamStore::Map* KVStreamStore::map(int32_t group) const { + if (group < 0 || (size_t)group >= maps_.size()) return nullptr; + return &maps_[(size_t)group]; +} + +const RadKVStream* KVStreamStore::view(const KVGroupPlan* p, int32_t group) const { + /* A ring that covers the context is never capped, so such a group gets null here. */ + if (!p || !p->streamed() || !windowed(group)) return nullptr; + const Map* m = map(group); + return m && m->host && m->res ? m : nullptr; +} + +KVStreamCost KVStreamStore::cost(const std::vector& plans, int64_t max_ctx, + int64_t max_seqs) const { + KVStreamCost c; + for (const auto& p : plans) { + if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue; + const int64_t blocks = context_blocks(p, max_ctx, max_seqs); + const int64_t slots = std::min(resident_blocks(p), blocks); + if (blocks <= 0 || slots <= 0) continue; + c.host_bytes += blocks * p.bytes_per_block; + c.map_bytes += kvstream_map_bytes(blocks, slots, p.n_layers); + ++c.groups; + } + return c; +} + +int KVStreamStore::alloc(const std::vector& plans, int64_t max_ctx, int64_t max_seqs, + MemAllocator& host_alloc, Pool& kv_pool) { + for (const auto& p : plans) { + if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue; + const int64_t blocks = context_blocks(p, max_ctx, max_seqs); + const int64_t slots = std::min(resident_blocks(p), blocks); + if (blocks <= 0 || slots <= 0) continue; + + Map m; + m.slots = slots; + m.block_bytes = p.layer_bytes_per_block(); + m.host_layer_stride = blocks * m.block_bytes; + m.host_bytes = blocks * p.bytes_per_block; + m.host = static_cast(host_alloc.alloc(m.host_bytes, RAD_MEM_HOST_MAPPED)); + if (!m.host) { + RAD_ERR("KV group '%s': the host mirror of %s (%lld blocks of %s) could not be " + "allocated", p.name.c_str(), humanb(m.host_bytes).c_str(), (long long)blocks, + humanb(p.bytes_per_block).c_str()); + release(host_alloc); + return RAD_E_NOMEM; + } + /* A block nothing has written is still copied in on a miss, so its bytes must be defined. */ + std::memset(m.host, 0, (size_t)m.host_bytes); + + /* One reservation for all of the group's maps, from the KV pool so its report names them. */ + const int64_t layers = p.n_layers > 0 ? p.n_layers : 1; + const MapLayout lay = map_layout(blocks, slots, layers); + const int64_t map_bytes = lay.bytes; + std::string what = "kv_stream_maps:" + p.name; + char* at = static_cast(kv_pool.reserve(what, map_bytes, RAD_ALIGN_UNIT, nullptr)); + if (!at) { + RAD_ERR("KV group '%s': its residency map and ring bookkeeping (%s) did not fit the " + "KV pool", p.name.c_str(), humanb(map_bytes).c_str()); + host_alloc.free(m.host, RAD_MEM_HOST_MAPPED); + release(host_alloc); + return RAD_E_NOMEM; + } + /* Residency is per layer, because the resolve copies one layer's block: a group-wide map + * would call a block resident in a layer whose bytes were never copied. The control + * block is the group's. */ + m.res = reinterpret_cast(at + lay.res); + m.slot_block = reinterpret_cast(at + lay.slot_block); + m.slot_state = reinterpret_cast(at + lay.slot_state); + m.ctl = reinterpret_cast(at + lay.ctl); + set_map(p.index, m); + } + return RAD_OK; +} + +int KVStreamStore::init(const std::vector& plans, RadStream s) { + if (!s) { + RAD_ERR("kv streaming: the maps must be filled on a stream, and none was given"); + return RAD_E_INVAL; + } + for (const auto& p : plans) { + const Map* m = map(p.index); + if (!m || !m->host || !m->res) continue; + /* The state a resolve expects (libref/ref_kvstream.cpp): both maps -1, slot state and + * control block 0. Every block starts absent. */ + const MapLayout lay = map_layout((int64_t)p.n_blocks, m->slots, + p.n_layers > 0 ? p.n_layers : 1); + int rc = RAD_OK; + rc = rad_memset_async(m->res, 0xff, lay.res_bytes, s); + if (rc == RAD_OK) rc = rad_memset_async(m->slot_block, 0xff, lay.slot_block_bytes, s); + if (rc == RAD_OK) rc = rad_memset_async(m->slot_state, 0, lay.slot_state_bytes, s); + if (rc == RAD_OK) rc = rad_memset_async(m->ctl, 0, lay.ctl_bytes, s); + if (rc != RAD_OK) { + RAD_ERR("KV group '%s': the residency map could not be initialised: %s", + p.name.c_str(), rad_dev_last_error()); + return rc; + } + } + return RAD_OK; +} + +void KVStreamStore::release(MemAllocator& host_alloc) { + for (auto& m : maps_) { + if (!m.host) continue; + host_alloc.free(m.host, RAD_MEM_HOST_MAPPED); + /* Cleared, so a second call is a no-op. */ + m = Map{}; + } +} + +KVStreamStats KVStreamStore::stats(const std::vector& plans) const { + KVStreamStats st; + st.misses = misses_; + st.bytes_in = bytes_in_; + for (const auto& p : plans) + if (p.streamed()) st.resident_blocks += p.pool_blocks(); + return st; +} + +} /* namespace rad */ diff --git a/core/kvstream/mirror.h b/core/kvstream/mirror.h new file mode 100644 index 00000000..23773fca --- /dev/null +++ b/core/kvstream/mirror.h @@ -0,0 +1,101 @@ +/* mirror.h -- a streamed group's host mirror and residency maps (docs/KV-STREAMING.md §4.1). + * + * A streamed group's device pool backs a resident window, not its context. Every block lives in a + * pinned host mirror laid out layer-major and block-indexed like the pool, and a device residency + * map gives each block's ring slot (-1 when absent). KVStreamStore owns the window caps, the + * mirrors, the maps and their sizing, so mem/kv.{h,cpp} keeps one member and one call per method. + * Only init() touches a device: it fills the maps on the stream it is given. + */ +#pragma once +#include "mem/pools.h" + +#include +#include + +namespace rad { + +struct KVGroupPlan; + +/* What the streamed groups need, before anything is taken: `host_bytes` of pinned mirror (each rank + * its own shard) and `map_bytes` of residency map, reverse map, slot state and control block, all + * taken from the KV pool itself and budgeted with it. Valid between plan_groups() and carve(). */ +struct KVStreamCost { + int64_t groups = 0; + int64_t host_bytes = 0; + int64_t map_bytes = 0; +}; + +/* The resolve's counters for the metrics; zeros on a server that does not stream. */ +struct KVStreamStats { + int64_t resident_blocks = 0; + uint64_t misses = 0; /* blocks placed in the ring by resolve launches */ + uint64_t bytes_in = 0; /* bytes those placements copied from the host mirror */ +}; + +/* Bytes of one streamed group's maps: the residency map (one entry a block, per layer), the + * ring's reverse map and slot state (per layer), and the shared control block. */ +int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers); + +/* The streamed groups' state by group handle: window caps, mirrors, maps and the resolve's + * counters. A group's Map is the ABI's RadKVStream, so the run phase reads the fields alloc() + * fills. Empty on a manager that does not stream. */ +class KVStreamStore { +public: + using Map = RadKVStream; + + /* The tokens of `group`'s context its device pool backs; 0 (the default) is all of it. Only the + * named group: its neighbours (an indexer's block keys, read over the whole history) stay + * resident. */ + void cap(int32_t group, int64_t tokens); + + /* Whether cap() narrowed `group` to a window: its block ids run over the context and only + * `n_slots` of them are in device memory. */ + bool windowed(int32_t group) const; + + /* The window in whole blocks; at least one, since a pool that holds nothing cannot run. */ + int64_t resident_blocks(const KVGroupPlan& p) const; + + /* Blocks the group's context addresses (kv_context_blocks). The block table is already pitched + * for them, whether the pool backs them or not. */ + int64_t context_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs) const; + + void set_map(int32_t group, const Map& m); + const Map* map(int32_t group) const; + + /* The ABI view of a streamed group, or null for a resident one. Its addresses are fixed from + * bring-up, which lets a recorded pass that reads it replay. */ + const RadKVStream* view(const KVGroupPlan* p, int32_t group) const; + + KVStreamCost cost(const std::vector& plans, int64_t max_ctx, int64_t max_seqs) const; + + /* Take the mirror and the maps for every streamed group. Call after plan_groups() and before + * carve(), which refuses a streamed group with no map and whose paged split must see the maps' + * bytes gone. The mirror is zeroed: a block nothing has written yet is still read on a miss. + * The maps are filled by init() after the carve backs the pool. On failure the mirrors taken + * so far are released. */ + int alloc(const std::vector& plans, int64_t max_ctx, int64_t max_seqs, + MemAllocator& host_alloc, Pool& kv_pool); + + /* Fill the maps as a resolve expects them: `res` and `slot_block` -1, `slot_state` and `ctl` + * zero. Call after carve(), then sync `s` before the first pass. */ + int init(const std::vector& plans, RadStream s); + + /* Free the mirrors; the maps go with the KV pool. Safe twice and after a failed bring-up. */ + void release(MemAllocator& host_alloc); + + KVStreamStats stats(const std::vector& plans) const; + + /* Charged by the engine, which reads the resolve's counters where a step has drained. */ + void note_traffic(int64_t misses, int64_t bytes) { + if (misses > 0) misses_ += (uint64_t)misses; + if (bytes > 0) bytes_in_ += (uint64_t)bytes; + } + +private: + std::vector resident_tokens_; /* by group handle: its pool's depth in tokens */ + std::vector maps_; /* set_map(), by group handle */ + uint64_t misses_ = 0; /* note_traffic() */ + uint64_t bytes_in_ = 0; +}; + +} /* namespace rad */ diff --git a/core/kvstream/plan.cpp b/core/kvstream/plan.cpp new file mode 100644 index 00000000..a49f1a1f --- /dev/null +++ b/core/kvstream/plan.cpp @@ -0,0 +1,186 @@ +/* plan.cpp -- see plan.h. */ +#include "kvstream/plan.h" + +#include + +namespace rad { + +int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks) { + if (!p.paged()) return p.n_states * p.bytes_per_state; + const int64_t ring = kv_ring_bytes(p, slots); + if (slots <= 0 || slots >= context_blocks) return ring; + return std::max(ring, context_blocks * p.layer_bytes_per_block()); +} + +int64_t kv_pool_bytes(const KVGroupPlan& p) { + return kv_pool_bytes(p, p.pool_blocks(), p.n_blocks); +} + +int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots) { + if (!p.paged() || p.block_size <= 0) return 0; + if (slots <= 0 || slots >= blocks) return blocks * p.bytes_per_block; + return kv_pool_bytes(p, slots, blocks); +} + +namespace { +/* Both overloads' rule: from group 1 on, the widest full group that owns bytes, is neither zero + * nor dense-read, and passes the caller's test. */ +bool kv_stream_candidate(int32_t kind, bool zero, bool dense_read, int64_t bytes_per_block) { + return kind == RAD_KV_FULL && !zero && !dense_read && bytes_per_block > 0; +} + +template +int32_t kv_stream_widest(size_t n, const Candidate& candidate) { + int32_t best = -1; + int64_t widest = 0; + for (size_t g = 1; g < n; ++g) { + int64_t bytes = 0; + if (!candidate(g, &bytes)) continue; + if (bytes > widest) { + widest = bytes; + best = (int32_t)g; + } + } + return best; +} +} /* namespace */ + +int32_t kv_stream_group(const KVManager& kv, const Program* prog) { + const std::vector& ps = kv.plans(); + return kv_stream_widest(ps.size(), [&](size_t g, int64_t* bytes) { + const KVGroupPlan& p = ps[g]; + if (!kv_stream_candidate(p.kind, p.zero, p.dense_read, p.bytes_per_block)) return false; + const KVGroupInfo* gi = g < prog->kv_groups.size() ? &prog->kv_groups[g] : nullptr; + if (!kvstream_ops(*prog, gi).streams()) return false; + *bytes = p.bytes_per_block; + return true; + }); +} + +int32_t kv_stream_group(const std::vector& gs, const Program* prog) { + return kv_stream_widest(gs.size(), [&](size_t g, int64_t* bytes) { + const KVGroupInfo& gi = gs[g]; + if (!kv_stream_candidate(gi.decl.kind, gi.zero, gi.dense_read, gi.bytes_per_block)) + return false; + if (prog && !kvstream_ops(*prog, &gi).streams()) return false; + *bytes = gi.bytes_per_block; + return true; + }); +} + +int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch) { + if (sel_pitch <= 0 || cfg.max_seqs <= 0) return 0; + /* One selection per row; a verify step is 1 + n_spec rows a sequence. */ + const int64_t rows = cfg.max_seqs * (1 + (cfg.n_spec > 0 ? cfg.n_spec : 0)); + return rows * sel_pitch; +} + +KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group) { + KVStreamOps ops; + /* Whether a declaration has a kernel in some domain: an op no row matched keeps a placeholder band + * with both domains null (Builder::op_resolved asks the same). */ + const auto resolved = [](const OpInfo& o) { + for (const Band& b : o.bands) + for (int d = 0; d < RAD_N_DOMAINS; ++d) + if (b.dom[d]) return true; + return false; + }; + /* The group's per-layer block pitch, which kv_resolve states as `block_bytes`. */ + const int64_t n_bound = group && !group->layers.empty() ? (int64_t)group->layers.size() : 1; + const int64_t layer_bytes = + group && group->bytes_per_block > 0 ? group->bytes_per_block / n_bound : 0; + for (const OpInfo& op : prog.ops) { + /* A declaration with no kernel issues nothing (a packed cache layout has no streamed store + * row); counting it would stream a group whose mirror is never written. */ + if (!resolved(op)) continue; + const bool is_resolve = op.op == "kv_resolve"; + const bool is_store = op.op == "kv_store_streamed" || + op.op == "qk_norm_rope_gate_kv_store_streamed"; + if (!is_resolve && !is_store) continue; + /* A declaration stating another group's geometry does not stream this one; one stating + * none is taken at its word. */ + long long stated = 0; + if (is_resolve && layer_bytes > 0 && op.base.get_i("block_bytes", &stated) && + stated != layer_bytes) + continue; + if (is_store && group && group->block_size > 0 && + op.base.get_i("block_size", &stated) && stated != group->block_size) + continue; + if (is_resolve) { + long long pitch = 0; + if (!op.base.get_i("sel_pitch", &pitch) || pitch <= 0) continue; + /* Every layer of the group declares the same pitch; the first wins. */ + if (!ops.resolve) ops.sel_pitch = (int64_t)pitch; + ops.resolve = true; + } else if (op.op == "kv_store_streamed") { + ops.store = true; + } else { + ops.folded = true; + } + } + return ops; +} + +KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size) { + KVStreamRing out; + const int64_t bs = block_size > 0 ? block_size : 1; + out.ctx_blocks = kv_context_blocks(bs, ctx, cfg.max_seqs); + out.ring_blocks = cfg.kv_resident > 0 ? (cfg.kv_resident + bs - 1) / bs : 0; + /* The floor, at most the context: a context under it streams nothing. */ + if (out.ring_blocks > 0) { + out.floor_blocks = (kStreamFloorTokens + bs - 1) / bs; + if (out.floor_blocks > out.ctx_blocks) out.floor_blocks = out.ctx_blocks; + if (out.ring_blocks < out.floor_blocks) { + out.ring_blocks = out.floor_blocks; + out.raised_blocks = out.floor_blocks; + } + } + if (out.ring_blocks > out.ctx_blocks) out.ring_blocks = out.ctx_blocks; + return out; +} + +void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch, + KVStreamRing* out) { + *out = kvstream_ring_shape(cfg, ctx, block_size); + if (!out->streams()) return; /* absent, 0, or a ring that covers the context */ + + /* The decode-step bound is always positive here: a group reaches this only when kvstream_ops + * found a kv_resolve with a sel_pitch, and --max-num-seqs is at least 1. Silent, because this + * runs on every rank's probe and again in bring-up; kvstream_configure prints the one line. */ + const int64_t ceiling = kvstream_ceiling_blocks(cfg, sel_pitch); + if (out->ring_blocks < ceiling) { + out->ring_blocks = ceiling < out->ctx_blocks ? ceiling : out->ctx_blocks; + out->raised_blocks = out->ring_blocks; + out->by_union = true; + } +} + +/* `cfg.kv_streams` is set by kvstream_cap_probe only when a group really streams. */ +int64_t kvstream_prefix_host_off(Config& cfg) { + if (!cfg.kv_streams || cfg.prefix_cache_mib <= 0) return 0; + const int64_t was = cfg.prefix_cache_mib; + cfg.prefix_cache_mib = 0; + return was; +} + +int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx) { + cfg.kv_streams = false; + if (cfg.kv_resident <= 0) return RAD_OK; + const int32_t g = kv_stream_group(probe, &prog); + if (g < 0) return RAD_OK; + const KVGroupPlan* p = probe.plan(g); + if (!p || p->block_size <= 0) return RAD_OK; + /* No streamed path: priced as without the flag. kvstream_configure warns, once. */ + const KVStreamOps ops = + kvstream_ops(prog, g < (int32_t)prog.kv_groups.size() ? &prog.kv_groups[(size_t)g] : nullptr); + if (!ops.streams()) return RAD_OK; + KVStreamRing ring; + /* The raised ring, so the budget and the carve take the same depth. */ + kvstream_ring(cfg, ctx, p->block_size, ops.sel_pitch, &ring); + if (!ring.streams()) return RAD_OK; + cfg.kv_streams = true; + probe.cap_resident_tokens(g, ring.ring_blocks * p->block_size); + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/kvstream/plan.h b/core/kvstream/plan.h new file mode 100644 index 00000000..879a6d25 --- /dev/null +++ b/core/kvstream/plan.h @@ -0,0 +1,120 @@ +/* plan.h -- the KV streaming policy, as arithmetic on a KVGroupPlan. Nothing here touches a device. + * + * A streamed group has two device views over one allocation (docs/KV-STREAMING.md §4.1): + * + * ring n_slots blocks deep, `n_layers` layer stripes, addressed through the residency map; + * stage n_blocks blocks deep, one layer stripe, addressed by block id. + * + * The allocation is max(ring, stage), never the sum. The plan's `depth` is the staged view's stripe + * count (1); the ring keeps the group's `n_layers` stripes. + * + * The VRAM budget is resolved from the plan's ceiling before cap_resident_tokens() runs, so + * kvstream_cap_probe() must teach the budget probe the streamed plan first; otherwise the pool is + * sized for the whole cache and streaming frees nothing. + */ +#pragma once +#include "mem/kv.h" + +namespace rad { + +/* Bytes of the ring view: `slots` blocks, every layer. Inline so that a caller that only lays out a + * view (kvstream/bind.cpp, linked by tests with weak device fakes) need not link KVManager. */ +inline int64_t kv_ring_bytes(const KVGroupPlan& p, int64_t slots) { + return slots > 0 ? slots * p.bytes_per_block : 0; +} + +/* Blocks the group's context addresses: `max_seqs` sequences of `max_ctx` tokens, each rounded up + * to whole blocks. The one definition of the id space, for the mirror's size and the ring decision + * alike. */ +inline int64_t kv_context_blocks(int64_t block_size, int64_t max_ctx, int64_t max_seqs) { + if (block_size <= 0) return 0; + const int64_t seqs = max_seqs > 0 ? max_seqs : 1; + const int64_t ctx = max_ctx > 0 ? max_ctx : 0; + return seqs * ((ctx + block_size - 1) / block_size); +} + +/* The group's one allocation: max(ring, stage) for `slots` resident blocks of `context_blocks`. + * `slots >= context_blocks` is a group that does not stream: `slots` blocks of every layer. The + * one-argument form is the carved plan's. A stateful group is its states. */ +int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks); +int64_t kv_pool_bytes(const KVGroupPlan& p); + +/* The pool cost ceiling() sums for `blocks` blocks of context and `slots` resident blocks: + * blocks * bytes_per_block unless the group streams. */ +int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots); + +/* The group --kv-resident streams: the widest paged full group, not dense-read (a step reads those + * over the whole history), for which the program declares a streamed path (kvstream_ops). -1 when + * there is none. */ +int32_t kv_stream_group(const KVManager& kv, const Program* prog); + +/* The same choice from a rank's declarations, before the plans exist. With no program the + * declared-path test is skipped. */ +int32_t kv_stream_group(const std::vector& groups, const Program* prog = nullptr); + +/* What --kv-resident makes of one group. */ +struct KVStreamRing { + int64_t ring_blocks = 0; /* the ring: the flag in whole blocks, raised to the floors */ + int64_t raised_blocks = 0; /* the depth a floor raised the flag to; 0 when not raised */ + int64_t floor_blocks = 0; /* kStreamFloorTokens in blocks, at most the context */ + bool by_union = false; /* the raise was the decode-step bound, not kStreamFloorTokens */ + int64_t ctx_blocks = 0; /* max_seqs x ceil(ctx / block_size): the group's context */ + /* A ring that covers the context does not stream: the group keeps the resident path, with no + * mirror, maps, stage or resolve, and a null RadKVStream. */ + bool streams() const { return ring_blocks > 0 && ring_blocks < ctx_blocks; } +}; + +/* The blocks one decode step's selections can name, which the ring must hold: `max_seqs x + * (1 + n_spec)` rows of at most `sel_pitch` distinct blocks each. A decode-classified pass with + * more rows a sequence than that (the serial drafter's history pass) takes the stage and is not + * counted. 0 when the program declares no kv_resolve. */ +int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch); + +/* The streamed ops the program declares for `group` (null: any group). A streamed group needs + * `kv_resolve`, which rewrites `sel` from block ids to ring slots, and a store that writes the host + * mirror (`kv_store_streamed`, or its fold into the prologue). Without the resolve the attention + * reads block ids as ring slots, past the ring; without the store a miss copies zeros. A + * declaration whose stated geometry (`block_bytes` on the resolve, `block_size` on the store) + * belongs to another group does not count, nor does one that resolved to no kernel (a packed cache + * layout has no streamed store row). */ +struct KVStreamOps { + bool resolve = false; /* kv_resolve with this group's layer bytes and a sel_pitch */ + bool store = false; /* kv_store_streamed */ + bool folded = false; /* qk_norm_rope_gate_kv_store_streamed */ + int64_t sel_pitch = 0; /* the blocks one selection row can name */ + bool streams() const { return resolve && (store || folded); } + /* The first op missing, for the startup line; null when streams(). */ + const char* missing() const { + if (!resolve) return "kv_resolve"; + if (!store && !folded) return "kv_store_streamed"; + return nullptr; + } +}; +KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group); + +/* The depth a ring is never carved below, in tokens (at most the group's context): below it the + * misses of a decode step cost more than the VRAM the ring gives back (docs/KV-STREAMING.md §3.9). + * A floor, not a default: --kv-resident 0 is still off. */ +constexpr int64_t kStreamFloorTokens = 32768; + +/* The ring and the id space from the flag and kStreamFloorTokens alone, so a caller can tell a + * model with no streamed path from a ring below the decode-step bound. */ +KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size); + +/* kvstream_ring_shape, then raised to kvstream_ceiling_blocks: a ring below what one decode step + * can select would serve a selection table that no longer addresses the pool. Never refuses; the + * caller prints the one warning. `block_size` is the group's page (1 when unknown). */ +void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch, + KVStreamRing* out); + +/* Turn the prefix cache's host tier off when a group streams: no entry holding a streamed group + * can be demoted to it. Returns the MiB turned off, 0 when nothing changed. Call after + * kvstream_cap_probe, before anything is sized from --prefix-cache-mib. */ +int64_t kvstream_prefix_host_off(Config& cfg); + +/* Teach the budget probe the streamed plan (the ring from --kv-resident, the stage from the + * context) before probe.ceiling(ctx), and set `cfg.kv_streams` when a group streams. A model with + * no streamed path is left exactly as without the flag. */ +int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx); + +} /* namespace rad */ diff --git a/core/kvstream/stage.cpp b/core/kvstream/stage.cpp new file mode 100644 index 00000000..7ccdc6df --- /dev/null +++ b/core/kvstream/stage.cpp @@ -0,0 +1,361 @@ +/* stage.cpp -- see stage.h, which states the ordering rule. */ +#include "kvstream/stage.h" + +#include "device/device.h" +#include "kvstream/bind.h" +#include "runtime/wtab.h" + +#include +#include + +namespace rad { + +namespace { +/* The layer staged most recently on this rank thread; reset at every pass. */ +thread_local int g_last_layer = -1; +/* What the pass staged, reported at the next pass's start. */ +struct PassStage { + uint64_t layers = 0, bytes = 0; + int64_t tokens = 0, ctx = 0, live_row = 0; /* live_row: the history one layer reads */ + int64_t bound_blocks = 0; /* the manager's bound the copy was clamped to */ + int phase = -1; +}; +thread_local PassStage g_pass; +/* Waits out a stage list still in flight (defined beside g_pipe). */ +static void stage_pipe_drain(Ctx* c); + +bool trace_stage() { + static const bool on = std::getenv("RADIANCE_KV_STAGE_TRACE") != nullptr; + return on; +} + +/* Under RADIANCE_KV_STAGE_TRACE, one line per pass that staged: the bytes it moved against the + * bytes of history it could read. */ +void report_pass() { + if (!g_pass.layers || !trace_stage()) return; + const double live = (double)g_pass.live_row * (double)g_pass.layers; + RAD_INFO("kv streaming: stage pass phase=%d tokens=%lld ctx=%lld: %llu layers, %.1f MiB moved, " + "%.1f MiB of live history (%.1fx), bound %lld blocks", + g_pass.phase, (long long)g_pass.tokens, (long long)g_pass.ctx, + (unsigned long long)g_pass.layers, (double)g_pass.bytes / (1024.0 * 1024.0), + live / (1024.0 * 1024.0), live > 0.0 ? (double)g_pass.bytes / live : 0.0, + (long long)g_pass.bound_blocks); +} +} /* namespace */ + +/* A pass visits its layers in order and may ask for one layer once per attention launch, so a + * layer is staged once and a consecutive repeat is already done. */ +static void kvstage_begin_pass() { + report_pass(); + g_last_layer = -1; + g_pass = PassStage(); +} + +void kvstream_enter(Ctx* c, const RadBatch* b) { + kvstage_begin_pass(); + if (!c || !b) return; + g_pass.tokens = b->n_tok; + g_pass.ctx = b->max_ctx_len; + g_pass.phase = b->phase; + for (int i = 0; i < b->n_kv_groups; ++i) { + if (!b->kv[i].stream) continue; + KVPoolBinding* kb = c->kv_binding(b->kv[i].group); + if (!kb || !kb->has_stage) continue; + const bool was_stage = kb->depth == 1; + kv_binding_enter(*kb, kv_pass_view(b->phase, b->n_tok, b->n_seq, b->n_spec)); + /* Back on the ring after a staged pass, the residency maps describe bytes the stage has + * overwritten. A staged pass copies whole layers to the pool at block-id identity (block b + * at base + b * block_bytes), which overlaps the ring's slots of other layers, and the + * copy leaves the maps alone: a decode that trusts them reads another layer's, or another + * request's, KV without a fault. The maps are reset, so the first ring pass resolves every + * live block from the mirror as a request's first pass does. `slots < blocks` holds for + * every stream with a stage: bringup gives a stream whose ring covers its context no + * mirror, no resolve and no stage. */ + if (was_stage && kb->depth == 0) { + const RadKVStream* st = b->kv[i].stream; + const int64_t bb = st->block_bytes; + const int64_t blocks = bb > 0 ? st->host_layer_stride / bb : 0; + const int64_t layers = st->host_layer_stride > 0 + ? st->host_bytes / st->host_layer_stride : 0; + if (blocks > 0 && layers > 0 && st->slots > 0 && st->slots < blocks) { + /* A list of the pass that just ended lands before the refill, not after it. */ + stage_pipe_drain(c); + (void)rad_memset_async(st->res, 0xff, + layers * blocks * (int64_t)sizeof(int32_t), c->stream()); + (void)rad_memset_async(st->slot_block, 0xff, + layers * st->slots * (int64_t)sizeof(int32_t), + c->stream()); + (void)rad_memset_async(st->slot_state, 0, + layers * st->slots * 2 * (int64_t)sizeof(int32_t), + c->stream()); + } + } + /* The history one layer can read, up to the longest sequence's end, for the report. */ + if (kb->stage.bytes > 0 && b->kv[i].block_size > 0 && b->kv[i].stream->block_bytes > 0) { + const int64_t reach = b->max_ctx_len + b->max_q_len; + const int64_t live_blocks = (reach + b->kv[i].block_size - 1) / b->kv[i].block_size; + const int64_t row = std::min(live_blocks * b->kv[i].stream->block_bytes, kb->stage.bytes); + if (row > g_pass.live_row) g_pass.live_row = row; + if (kb->stage_live_bytes > 0) { + const int64_t bound = kb->stage_live_bytes / b->kv[i].stream->block_bytes; + if (bound > g_pass.bound_blocks) g_pass.bound_blocks = bound; + } + } + } +} + +/* The allocator's high-water mark in bytes of one layer (stage.h, "Volume"). */ +void kvstream_bound_live(Ctx* c, const KVManager& kv) { + if (!c) return; + for (int g = 0; g < kv.n_groups(); ++g) { + KVPoolBinding* b = c->kv_binding(g); + if (!b || !b->has_stage) continue; + const RadKVStream* st = kv.stream_view(g); + if (!st || st->block_bytes <= 0) continue; + const int64_t blocks = kv.held_top_blocks(g); + b->stage_live_bytes = blocks > 0 ? blocks * st->block_bytes : 0; + } +} + +namespace { + +/* A staged layer's copy: from its mirror row (by group-local position, not model layer) to the + * pool base, where both views start. */ +struct StageSrc { + void* dst = nullptr; + const uint8_t* src = nullptr; + int64_t bytes = 0; +}; + +bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, StageSrc* o) { + const KVPoolBinding* b = ctx->kv_binding(group); + const RadKVStream* st = kvb ? kvb->stream : nullptr; + if (!b || !st) return false; + const int64_t li = ctx->kv_layer_index(group, layer); + if (!st->host || st->block_bytes <= 0 || st->host_layer_stride <= 0 || li < 0) return false; + o->dst = b->base; + o->src = st->host + li * st->host_layer_stride; + o->bytes = b->bytes; + /* Only up to the held bound (stage.h, "Volume"). */ + if (b->stage_live_bytes > 0 && b->stage_live_bytes < o->bytes) o->bytes = b->stage_live_bytes; + if (o->bytes <= 0 || o->bytes > st->host_layer_stride) o->bytes = st->host_layer_stride; + return o->bytes > 0; +} + +/* Whether the card has the DMA queue the pipelined path needs. */ +bool dma_stage(Ctx* c) { + static const bool on = rad_xp_supported(c->device()) != 0; + return on; +} + +/* The one list in flight per rank thread: the layer it fills and the ride it waits on. */ +struct StagePipe { + RadEvent done = nullptr; + int inflight = -1; /* the layer the outstanding list fills */ + int group = -1; + void* mark = nullptr; + int64_t bytes = 0; /* what that list was told to move, for the pass's counter */ +}; +thread_local StagePipe g_pipe; +thread_local bool g_warned_ride = false; + +/* A list handed over by arm_and_submit() is normally waited for by the next kvstage_wait or + * consumed by kvstage_next, but a pass can end with one in flight. On the transition back to the + * ring such a list, still writing base + 0, would land on the ring's layer-0 slots after the + * refill the map reset causes, and `res` would call another layer's bytes resident. */ +static void stage_pipe_drain(Ctx* c) { + if (g_pipe.inflight < 0) return; + (void)rad_event_wait(c->stream(), g_pipe.done); + g_pipe.inflight = -1; + g_pipe.group = -1; + g_pipe.bytes = 0; + rad_ride_release(g_pipe.mark, nullptr, 0); + g_pipe.mark = nullptr; +} + +/* Arm the completion word in stream order and hand the list over. The arm (a 1 written by the + * weight table's patch dispatch, runtime/wtab.h) is also what completes the list's ride, so the + * list cannot write its 0 before the 1 the wait looks for. */ +bool arm_and_submit(Ctx* c, int group, int layer, const StageSrc& s, void* mark) { + uint32_t* word = nullptr; + if (!g_pipe.done || rad_event_dma(g_pipe.done, c->stream(), &word) < 0) return false; + WtabPatch arm; + arm.n = 1; + arm.dst[0] = (void**)(void*)word; + arm.val[0] = (void*)(uintptr_t)1; + if (wtab_patch(arm, c->stream()) < 0) return false; + const uint64_t src = (uint64_t)(uintptr_t)s.src, dst = (uint64_t)(uintptr_t)s.dst; + const uint64_t bytes = (uint64_t)s.bytes; + /* No yield: the compute stream waits on this copy, so yielding the link to a hold whose release + * is behind that wait would deadlock (docs/KV-STREAMING.md §6.1). */ + if (rad_xp_list(c->device(), mark, 1, &src, &dst, &bytes, word, 0, RAD_XP_NO_YIELD) != RAD_OK) + return false; + g_pipe.inflight = layer; + g_pipe.group = group; + g_pipe.mark = mark; + g_pipe.bytes = s.bytes; + if (trace_stage()) + RAD_INFO("kv streaming: handed over layer %d (%lld bytes), behind %lld", layer, + (long long)s.bytes, (long long)rad_xp_behind(c->device())); + return true; +} + +/* The copy on the compute stream: for a backend with no DMA queue, and when no ride is spare. */ +int serial_stage(Ctx* c, const StageSrc& s) { + RadStream st = c->stream(); + const int rc = (s.bytes & 15) == 0 + ? rad_memcpy_ranges_async(s.dst, s.src, s.bytes, nullptr, 0, st) + : rad_memcpy_async(s.dst, s.src, s.bytes, st); + return rc; +} + +void count_stage(Ctx* c, int layer, int64_t bytes) { + g_last_layer = layer; + g_pass.layers += 1; + g_pass.bytes += (uint64_t)bytes; + if (trace_stage() && c->rank() == 0) + RAD_INFO("kv streaming: stage layer %d (%lld bytes)", layer, (long long)bytes); +} + +/* While recording, a host tape step that re-runs the arm and the submit at every play. */ +int stage_issue_host(Ctx* c, int group, int layer, bool after) { + if (c->recording()) + return c->tape_kv_stage(after, group, layer); + return kvstage_run(c, group, layer, after); +} + +} /* namespace */ + +/* Before the layer's store: wait for the pipelined copy, or copy now. 1 when staged, 0 when the + * group has no stage view. A failure fails the step and returns 1, so the caller stops rather + * than read an unstaged layer. */ +static int kvstage_wait(Ctx* c, int group, const RadKVGroupBatch* kvb, int layer) { + if (!c || !kvb || !kvb->stream) return 0; + const KVPoolBinding* b = c->kv_binding(group); + if (!b || !b->has_stage || b->depth != 1) return 0; + if (layer == g_last_layer) return 1; + return stage_issue_host(c, group, layer, false); +} + +/* After every attention launch of `layer`: start the copy of the group's next layer, riding the + * next dispatch on the compute stream. Nothing reads the stage again before the next layer's + * wait. */ +static int kvstage_next(Ctx* c, int group, int layer) { + if (!c) return 0; + const KVPoolBinding* b = c->kv_binding(group); + if (!b || !b->has_stage || b->depth != 1) return 0; + return stage_issue_host(c, group, layer, true); +} + +int kvstage_run(Ctx* c, int group, int layer, bool after) { + if (!c) return 0; + const RadBatch* b = c->batch(); + const RadKVGroupBatch* kvb = nullptr; + if (b) + for (int i = 0; i < b->n_kv_groups; ++i) + if ((int)b->kv[i].group == group) { kvb = &b->kv[i]; break; } + if (!kvb || !kvb->stream) return 0; + const KVPoolBinding* kb = c->kv_binding(group); + if (!kb || !kb->has_stage || kb->depth != 1) return 0; + + if (!after) { + /* Make `layer`'s row whole. A pipelined list was handed over at the layer before; its + * wait is a barrier on the compute stream. */ + if (g_pipe.inflight >= 0 && (g_pipe.inflight != layer || g_pipe.group != group)) { + /* A list for a layer this pass does not read (one an earlier pass started): it must + * land before anything rewrites the buffer. */ + (void)rad_event_wait(c->stream(), g_pipe.done); + g_pipe.inflight = -1; + g_pipe.bytes = 0; + rad_ride_release(g_pipe.mark, nullptr, 0); + g_pipe.mark = nullptr; + } + if (g_pipe.inflight == layer && g_pipe.group == group) { + if (rad_event_wait(c->stream(), g_pipe.done) < 0) { + rad_step_fail(c, "kv streaming: the compute stream could not wait for the stage copy " + "the DMA engine is filling; the layer's attention would read the " + "previous layer's bytes"); + return 1; + } + const int64_t moved = g_pipe.bytes; + g_pipe.inflight = -1; + g_pipe.bytes = 0; + rad_ride_release(g_pipe.mark, nullptr, 0); + g_pipe.mark = nullptr; + count_stage(c, layer, moved); + return 1; + } + StageSrc s; + if (!stage_src(c, group, kvb, layer, &s)) { + rad_step_fail(c, "kv streaming: a layer needs its prefill stage but the group has no host " + "mirror row for it, so the attention would read an unstaged layer"); + return 1; + } + /* Nothing pipelined (the pass's first layer): copy now and wait, in the layer's prologue. */ + if (dma_stage(c)) { + if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr; + void* mark = nullptr; + if (g_pipe.done && rad_ride(c->stream(), &mark) == RAD_OK) { + if (arm_and_submit(c, group, layer, s, mark)) { + const bool ok = rad_event_wait(c->stream(), g_pipe.done) >= 0; + g_pipe.inflight = -1; + rad_ride_release(mark, nullptr, 0); + if (ok) { + count_stage(c, layer, s.bytes); + return 1; + } + } else { + rad_ride_release(mark, nullptr, 0); + } + } + } + if (serial_stage(c, s) < 0) { + rad_step_fail(c, "kv streaming: the prefill stage copy failed; the layer's attention " + "would read the previous layer's bytes"); + return 1; + } + count_stage(c, layer, s.bytes); + return 1; + } + + /* The group's next bound layer, if any. */ + int next = -1; + const auto& ls = kb->layer_slot; + for (int l = layer + 1; l < (int)ls.size(); ++l) + if (c->kv_layer_index(group, l) >= 0) { next = l; break; } + if (next < 0 || !dma_stage(c)) return 0; + if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr; + if (!g_pipe.done) return 0; + StageSrc s; + if (!stage_src(c, group, kvb, next, &s)) return 0; + /* No spare ride: the next layer's wait copies it on the compute stream. */ + void* mark = nullptr; + if (rad_ride(c->stream(), &mark) != RAD_OK) { + if (!g_warned_ride) { + g_warned_ride = true; + RAD_INFO("rank %d: kv streaming: no spare ride for the stage's DMA list, so its layer " + "copies serially", c->rank()); + } + return 0; + } + if (!arm_and_submit(c, group, next, s, mark)) { + rad_ride_release(mark, nullptr, 0); + return 0; + } + return 0; +} + +} /* namespace rad */ + +extern "C" int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, + int layer) { + using namespace rad; + if (!c || !kvb || !kvb->stream) return 0; + return kvstage_wait(static_cast(c), group, kvb, layer); +} + +extern "C" int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) { + using namespace rad; + if (!c) return 0; + return kvstage_next(static_cast(c), group, layer); +} diff --git a/core/kvstream/stage.h b/core/kvstream/stage.h new file mode 100644 index 00000000..af89a0d3 --- /dev/null +++ b/core/kvstream/stage.h @@ -0,0 +1,80 @@ +/* stage.h -- the one-layer prefill stage: per pass and layer, copy the live part of the layer's + * mirror row into the group's stage view, on the card's DMA engine, one layer ahead. + * + * Ordering rule. Every layer aliases offset 0 of the stage, which is safe only because for each + * layer L these happen in order: + * + * 1. the stage copy of L has landed; + * 2. L's store writes this chunk's tokens into the stage (the copy reads the mirror, which does + * not hold them yet, so a copy landing later would put older bytes back over them); + * 3. L's attention reads the stage; + * 4. the copy of L+1 starts. + * + * The copy is a DMA list, which holds no CU slot, so the order cannot rest on one stream's issue + * order: + * + * - 1 before 2: the compute stream waits on an event the list itself completes (rad_event_dma + * hands the list the event's completion word as its `done`), issued immediately before L's + * store. The wait is a barrier packet, so nothing between it and the store can pass it. + * - 4 after 3: the list polls a ride (rad_ride) taken on the compute stream after every + * attention launch of L (rad_kv_stage_next), so it starts when L's reads are done and crosses + * the link under L's MLP and L+1's projections. + * + * What breaks it: + * + * - taking the ride before all of L's attention launches (a prefill layer's attention is issued + * in `qsa_gq_rows`-wide chunks, so the seam is after the loop, not in the resolve); + * - waiting for the copy after the layer's store instead of before it; + * - arming the completion word from the host instead of in stream order: an older 0 would then + * release this layer's wait early, or a fresh 1 cut the previous wait short; + * - the copy on lane 1, or on a second stream with no recorded event pair (docs/KV-STREAMING.md + * §3.5.1); + * - replaying a recorded pass without re-running the arm and the submit: the list is not a + * queue packet, so Ctx::tape_kv_stage re-runs them with the tape paused, as xprefetch.cpp does. + * + * The hazard pass sees the same byte range for every aliased layer, and it never sees the DMA + * copy at all, so the barriers above are the copy's whole ordering (core/runtime/issue.cpp, + * haz_mark). + * + * Volume. The copy moves the mirror row up to the highest block id the pass can read, not the + * whole row (`n_blocks * block_bytes` is the context allocation). The bound is + * KVManager::held_top_blocks, one past the highest held block (kvstream_bound_live, per step), and + * it must never be low: the attention would read whatever the previous layer left there, which is + * fluent wrong text, not a fault. It is an upper bound because + * + * - every id a block table holds is held, and the held histogram counts sequence and + * cache-retained blocks alike; + * - the stage is identity-addressed from block 0, so copying [0, bound) covers every id below + * it, dense or not; + * - it is re-read every step, after the step's blocks are ensured, so a block a chunk appends or + * a speculative token's block is inside it; a partial block is copied whole and its unwritten + * tail is the mirror's zeros. + * + * Allocation is not assumed ascending: a retained or restored block can sit above a free one. The + * bound counts every held block, so a server with a long cached conversation stages more than one + * request reads; 0 (nothing held) stages the whole row. + * + * A backend with no DMA queue (the host backend, a test) copies on the compute stream, in the same + * order. + */ +#pragma once +#include "mem/kv.h" +#include "runtime/ctx.h" + +namespace rad { + +/* Select the view of every streamed group the pass names and reset the stage's per-pass state. + * Called before each pass (core/runtime/ctx.cpp). Not in bind.h, so a caller that only builds a + * step's view (core/sched/batch.cpp) does not link the driver. */ +void kvstream_enter(Ctx* c, const RadBatch* b); + +/* Set every streamed group's stage bound from `kv` (rank 0's manager, which hands out the ids) for + * the step about to run. Called for every rank from Engine::prepare_release, with the ranks parked + * and the step's blocks ensured. */ +void kvstream_bound_live(Ctx* c, const KVManager& kv); + +/* The driver, also re-run by a recorded pass (Ctx::tape_kv_stage). `after` is the call after the + * layer's attention (rad_kv_stage_next) rather than before its store. */ +int kvstage_run(Ctx* c, int group, int layer, bool after); + +} /* namespace rad */ diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 821dea16..c1a3eb7a 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -1,6 +1,9 @@ /* kv.cpp -- see kv.h. */ #include "mem/kv.h" +#include "kvstream/carve.h" +#include "kvstream/plan.h" + #include #include #include @@ -71,7 +74,7 @@ std::string BundleComparison::report() const { /* ------------------------------------------------------------------ configure */ -static const char* kv_kind_name(int k) { +const char* kv_kind_name(int k) { switch (k) { case RAD_KV_FULL: return "full"; case RAD_KV_WINDOW: return "window"; @@ -133,6 +136,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config& * other plan-path code has to know the kind. */ p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind; p.n_layers = (int64_t)g.layers.size(); + p.dense_read = g.dense_read; if (p.n_layers <= 0) { RAD_ERR("KV group '%s': no layers are bound to it, so its page size is unknown " @@ -309,8 +313,10 @@ int64_t KVManager::ceiling(int64_t ctx) const { int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size); if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0) blocks = std::min(blocks, window_pool_cap(p)); - need += blocks * p.bytes_per_block; + need += kv_ceiling_bytes(p, blocks, stream_.resident_blocks(p)); } + /* The streamed groups' maps come out of this pool too (kvstream/carve.h). */ + need += kvstream_maps_charged(plans_, stream_, ctx, max_seqs_); return need; } @@ -415,9 +421,15 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block /* Zero groups take no part in the split; they get the shared table's block count, which is * what the costed groups settle on here or, under the cap, on the ranks holding the cache. */ std::vector open, zeros; - for (const auto& p : plans_) - if (p.paged()) (p.zero ? zeros : open).push_back(p.index); - /* Every paged group zero: this rank limits nothing, so take the cap, or report unbounded. */ + bool dense = false; + for (const auto& p : plans_) { + if (!p.paged()) continue; + if (p.zero) zeros.push_back(p.index); + else if (kvstream_dense(p, plans_, stream_)) dense = true; /* its carve is a floor */ + else if (!stream_.windowed(p.index)) open.push_back(p.index); + } + kvstream_split_windows(plans_, stream_, max_ctx_, max_seqs_, &remaining, &out); + /* Every paged group is zero: this rank limits nothing, so take the cap, or report unbounded. */ if (open.empty() && !zeros.empty()) { const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens; if (blocks) { @@ -453,6 +465,9 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block } for (int32_t i : open) out[i] = remaining > 0 ? tokens / plans_[i].block_size : 0; for (int32_t i : zeros) out[i] = remaining > 0 ? zero_blocks(plans_[i], tokens) : 0; + /* A dense-read group's floor is already charged; with no other open group the pool still pages + * one full-length sequence, which is what the report and the admission cap see. */ + if (dense && open.empty() && remaining > 0) tokens = max_ctx_; if (blocks) *blocks = std::move(out); return tokens; } @@ -486,8 +501,11 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const { } int KVManager::carve_into(Pool& kv_pool) { - /* The pool size is the resolver's; this only splits it between the groups. */ - const int64_t budget_bytes = kv_pool.avail(); + /* The pool size is the resolver's; this only splits it between the groups. The streamed + * groups' maps were reserved from it before the carve and paged_split() charges them, so they + * are added back here rather than charged twice. */ + const int64_t budget_bytes = kv_pool.avail() + + kvstream_maps_charged(plans_, stream_, max_ctx_, max_seqs_); const int64_t fixed = fixed_; pool_base_ = kv_pool.base(); pool_ = &kv_pool; @@ -505,11 +523,19 @@ int KVManager::carve_into(Pool& kv_pool) { return RAD_E_NOMEM; } + /* ---- the resident windows, before anything is split (kvstream/carve.h) ---- */ + RAD_TRY(kvstream_window_fit(plans_, stream_, fixed, budget_bytes, max_ctx_, max_seqs_)); + /* ---- the paged split; under a cap, the least rank's ---- */ std::vector blocks; (void)paged_split(budget_bytes, &blocks); for (auto& p : plans_) if (p.paged()) p.n_blocks = blocks[p.index]; + /* How much of that the pool backs, and the refusal of an unbacked streamed plan. */ + RAD_TRY(kvstream_apply(plans_, stream_, max_ctx_, max_seqs_)); + + /* A streamed group's `n_blocks` is its context, so this asks whether it can address anything, + * not whether its window is large enough. */ for (auto& p : plans_) { if (!p.paged()) continue; if (p.n_blocks <= 0 && p.zero) { @@ -531,7 +557,7 @@ int KVManager::carve_into(Pool& kv_pool) { /* ---- carve. Every reservation comes from the KV pool only; the mover works inside the * weight slab and cannot reach it (spec §6). ---- */ for (auto& p : plans_) { - int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block + int64_t bytes = p.paged() ? kv_pool_bytes(p) : p.n_states * p.bytes_per_state; if (p.zero) { p.base = nullptr; @@ -625,14 +651,16 @@ int KVManager::carve_into(Pool& kv_pool) { return p.runtime_win ? "ring" : kv_kind_name(p.kind); }; for (const auto& p : plans_) { - if (p.paged()) + if (p.paged()) { report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s " "%7lld blocks = %9s (%lld tokens)\n", p.name.c_str(), kind_of(p), (long long)p.n_layers, (long long)p.block_size, humanb(p.bytes_per_block).c_str(), (long long)p.n_blocks, humanb(p.pool_bytes).c_str(), (long long)(p.n_blocks * p.block_size)); - else + if (p.streamed()) + report_ += kvstream_report_line(p); + } else report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n", p.name.c_str(), kind_of(p), (long long)p.n_layers, humanb(p.bytes_per_state).c_str(), @@ -758,6 +786,9 @@ int64_t KVManager::total_blocks(int32_t g) const { int64_t KVManager::live_blocks(int32_t g) const { return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0; } +int64_t KVManager::held_top_blocks(int32_t g) const { + return (g >= 0 && g < (int32_t)plans_.size()) ? held_top((size_t)g) : 0; +} /* The larger of one prefill chunk and the recent shortfall peak (see buffer_bytes in kv.h). */ int64_t KVManager::buf_blocks(size_t i) const { @@ -786,8 +817,10 @@ int64_t KVManager::available_blocks(int32_t g) const { bool KVManager::lendable(int32_t g) const { const KVGroupPlan* p = plan(g); + /* A streamed group never lends: its pool is the ring, and a lent block would leave fewer + * slots than one launch's selection needs. */ return p && p->kind == RAD_KV_FULL && p->n_blocks > 0 && p->block_size > 0 && - p->bytes_per_block > 0; + p->bytes_per_block > 0 && !p->streamed(); } int64_t KVManager::lent_blocks(size_t i, int64_t tokens) const { @@ -905,7 +938,7 @@ int64_t KVManager::pool_bytes(int32_t g) const { int64_t KVManager::pool_bytes_carved(int32_t g) const { const KVGroupPlan* p = plan(g); if (!p) return 0; - if (p->paged()) return p->n_blocks * p->bytes_per_block; + if (p->paged()) return kv_pool_bytes(*p); if (p->stateful()) return p->n_states * p->bytes_per_state; return 0; } diff --git a/core/mem/kv.h b/core/mem/kv.h index f2240e1d..7786569f 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -20,6 +20,7 @@ * request by the other. */ #pragma once +#include "kvstream/mirror.h" #include "mem/hostarena.h" #include "mem/pools.h" #include "rad_core.h" @@ -54,6 +55,9 @@ struct BundleComparison { }; BundleComparison compare_bundling(const std::vector& bundles); +/* A RAD_KV_* kind's name, for reports and refusals. */ +const char* kv_kind_name(int kind); + /* ------------------------------------------------------------------ the runtime window */ /* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the * "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image @@ -123,11 +127,25 @@ struct KVGroupPlan { * snapshot would be read. */ bool win_snap = false; - int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */ + int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */ + /* Paged groups: blocks the device pool backs, fewer than `n_blocks` when the group streams + * (docs/KV-STREAMING.md). Block ids stay dense over `n_blocks`: the allocator, refcounts, block + * table, prefix cache and every `id < n_blocks` guard count the context. Only addressing uses + * this: the pool and its layer stride are `n_slots` blocks deep, and the residency map turns a + * block into a slot. Equal to `n_blocks` otherwise. */ + int64_t n_slots = 0; + /* Layer stripes the staged view presents: 0 means `n_layers` (the ring, and every group that + * does not stream), 1 means one stripe that every layer aliases. A depth rather than a + * rewritten `layer_slot`, which is also the host mirror's row (docs/KV-STREAMING.md §3.5.1). Set + * by carve() when the ring is smaller than the context. */ + int64_t depth = 0; /* rad_kv_group_zero: this rank keeps no cache for the group. The plan keeps its position and * block count (one block table serves every rank); its costs are zero and nothing is carved. * No op on this rank names it (issue refuses a group with no pool bound). */ bool zero = false; + /* rad_kv_group_dense_read: read over the whole history every step, so it cannot stream; while a + * sibling streams its carve is a floor of max_seqs full contexts (kvstream/carve.h). */ + bool dense_read = false; /* rad_kv_group_replicated: every rank holds the same bytes, so a tier slot carries this * group once, in a window at its front that rank 0 writes and every rank reads * (TierExec::slot_layout). The pool is carved as for any group. */ @@ -147,13 +165,19 @@ struct KVGroupPlan { bool paged() const { return kind == RAD_KV_FULL || kind == RAD_KV_WINDOW; } bool stateful() const { return kind == RAD_KV_LINEAR || kind == RAD_KV_CONV; } + /* Blocks of device pool this group owns: `n_slots`, which is `n_blocks` unless the group + * streams. Every carve and stride goes through here; every allocation and guard uses + * `n_blocks`. */ + int64_t pool_blocks() const { return n_slots > 0 ? n_slots : n_blocks; } + /* The pool holds fewer blocks than the group addresses; a residency map says which. */ + bool streamed() const { return paged() && n_slots > 0 && n_slots < n_blocks; } /* The pool is layer-major, as the ABI requires: a RAD_OPK_KV operand carries the layer as its * offset and resolves to `base + layer * layer_stride` (RadOperand in rad_runtime.h, * KVPoolBinding in core/runtime/ctx.h), so a kernel gets one base pointer per layer and * indexes it with the block table and slot mapping. * - * Layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of + * Layer i owns [base + i*layer_stride, + layer_stride): pool_blocks() blocks of * `bytes_per_block / n_layers` for a paged group, n_states states of * `bytes_per_state / n_layers` for a stateful one. */ int64_t layer_bytes_per_block() const { @@ -163,7 +187,8 @@ struct KVGroupPlan { return n_layers > 0 ? bytes_per_state / n_layers : bytes_per_state; } int64_t layer_stride() const { - return paged() ? n_blocks * layer_bytes_per_block() : n_states * layer_bytes_per_state(); + return paged() ? pool_blocks() * layer_bytes_per_block() + : n_states * layer_bytes_per_state(); } }; @@ -224,6 +249,28 @@ public: * because paged_split is monotone in the budget. */ int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const; void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; } + + /* ---- KV streaming: KVStreamStore's state and lifecycle under the manager's names, so callers + * need not include kvstream/mirror.h, which documents each. */ + using StreamMap = RadKVStream; /* the ABI's view: the mirror and the ring's maps */ + using StreamCost = KVStreamCost; + using StreamStats = KVStreamStats; + void cap_resident_tokens(int32_t group, int64_t tokens) { stream_.cap(group, tokens); } + void set_stream_map(int32_t group, const StreamMap& m) { stream_.set_map(group, m); } + const StreamMap* stream_map(int32_t group) const { return stream_.map(group); } + const RadKVStream* stream_view(int32_t group) const { + return stream_.view(plan(group), group); + } + StreamCost stream_cost() const { return stream_.cost(plans_, max_ctx_, max_seqs_); } + int alloc_stream(MemAllocator& host_alloc, Pool& kv_pool) { + return stream_.alloc(plans_, max_ctx_, max_seqs_, host_alloc, kv_pool); + } + int init_stream(RadStream s) { return stream_.init(plans_, s); } + void free_stream(MemAllocator& host_alloc) { stream_.release(host_alloc); } + StreamStats stream_stats() const { return stream_.stats(plans_); } + void note_stream_traffic(int64_t misses, int64_t bytes) { + stream_.note_traffic(misses, bytes); + } int carve(Pool& kv_pool); const std::vector& plans() const { return plans_; } @@ -368,6 +415,10 @@ public: /* The carve: the range every block id is addressed against. live_blocks() is what the cache * keeps unlent. */ int64_t total_blocks(int32_t group) const; + /* One past the highest held block, rounded up to a `held_hist_` bucket (0 when nothing is held): + * an upper bound on every id a block table can name, which a streamed group's stage copies up + * to (kvstream/stage.h). It counts blocks the prefix cache and other sequences hold too. */ + int64_t held_top_blocks(int32_t group) const; int64_t free_states(int32_t group) const; /* Pool size in bytes, the only unit in which groups can be summed: paged and stateful groups @@ -622,6 +673,9 @@ private: int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */ int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */ int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */ + /* KV streaming's state by group handle (kvstream/mirror.h); empty when nothing streams. */ + KVStreamStore stream_; + /* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its * start: it is a declaration about the program, not about a plan. */ std::unordered_map runtime_decl_; diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index d90f6fe1..a4a450e7 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -186,6 +186,15 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ p.name.c_str(), (long long)p.block_size, (long long)block_size_); } + /* An entry can be demoted only when the host tier can hold every group in it. A streamed + * group's rows are its pinned mirror, addressed by the block id the sequence used, so an entry + * holding one stays in VRAM and is evicted whole (docs/KV-STREAMING.md §4.1). */ + demotable_ = true; + for (int32_t g : groups_) { + const KVGroupPlan* p = kv->plan(g); + if (p && p->streamed()) demotable_ = false; + } + interval_ = checkpoint_interval; /* A window snapshot is state too: a hit is reusable only at a checkpoint, whose slot carries * the window behind it (KVManager::has_window_snapshot). */ @@ -217,6 +226,11 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ (long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(), policy_->name()); report_ += skipped; + if (!demotable_) { + /* Stated whether or not a host tier is configured. */ + report_ += " a streamed group is cached, so no entry can be demoted to the host tier: a " + "streamed group's rows are its pinned mirror, addressed by block id\n"; + } return RAD_OK; } @@ -431,14 +445,15 @@ int PrefixCache::insert(uint64_t session, * The ids come from the map, not from `blocks`. For an entry that already existed the loop * above kept the cache's blocks, and `blocks` belongs to a sequence about to be freed; the * tiers would copy from blocks reassigned to another sequence. */ - if (tiers_) { + if (tiers_ && demotable_) { for (int64_t b = 0; b < n_full; ++b) { auto it = map_.find(hs[(size_t)b]); if (it == map_.end()) continue; tiers_->note_used(hs[(size_t)b], it->second.blocks, now, b); } - tiers_->note_session(session, hs, n_tokens, now, label); } + /* The session index names no blocks, so it is kept with or without a host copy. */ + if (tiers_) tiers_->note_session(session, hs, n_tokens, now, label); take_over(session, hs, n_full * block_size_); return RAD_OK; @@ -635,11 +650,12 @@ int64_t PrefixCache::trim_sparing(int64_t n_blocks, it = next; continue; } - if (keep && !tiers_->droppable(h)) { ++it; continue; } + /* Skip an entry whose copy is still in flight; one the tier cannot hold never gets a copy. */ + if (keep && demotable_ && !tiers_->droppable(h)) { ++it; continue; } it = lru_.erase(it); e.in_lru = false; release_blocks(e); - if (keep) { + if (keep && demotable_) { tiers_->drop_commit(h); ++stats_.drops; } else { diff --git a/core/mem/prefix.h b/core/mem/prefix.h index b60eec9e..c3301bfc 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -205,6 +205,10 @@ public: int64_t block_size() const { return block_size_; } int64_t checkpoint_interval() const { return interval_; } const std::vector& cached_groups() const { return groups_; } + /* Whether the host tier can hold this cache's entries. False when a cached group streams: its + * rows are addressed by the sequence's block ids, so entries stay in VRAM and are evicted + * whole (docs/KV-STREAMING.md §4.1). */ + bool demotable() const { return demotable_; } std::string report() const; /* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies, @@ -461,6 +465,7 @@ private: int64_t block_size_ = 0; int64_t interval_ = 0; std::vector groups_; /* paged groups this cache indexes */ + bool demotable_ = false; /* the host tier can hold every group in an entry */ bool has_linear_ = false; mutable std::unordered_map map_; diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 75932168..eb02b667 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -239,6 +239,12 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg cfg.vram_weights_mib = to_mib_up(b.weights); const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights; cfg.vram_kv_mib = to_mib(std::max(b.kv - w_over, 0)); + /* A streamed plan's maps are charged in kv_one but reserved outside the paged split, so the MiB + * truncation would leave the pool short of the one conversation kv_one was sized for. Under + * streaming kv_one is a requirement, so it is rounded up. */ + if (cfg.kv_streams && kv_one > 0 && + b.kv >= kv_one && cfg.vram_kv_mib * kMiB < kv_one) + cfg.vram_kv_mib = to_mib_up(kv_one); /* A cache given its whole ceiling is rounded up to cover it, out of the headroom as the * weights' MiB is: truncated, a ceiling under a MiB would be an empty pool and one just over a * whole MiB a pool short of its own context. */ diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp index fb8e2943..33e1ec0c 100644 --- a/core/mm/imaging.cpp +++ b/core/mm/imaging.cpp @@ -173,6 +173,25 @@ static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinea } } +void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* out) { + /* At alpha 255 the premultiply and the divide back are the identity. */ + FrameRGBA pre; + pre.w = src.w; + pre.h = src.h; + pre.rgba.resize((size_t)src.w * src.h * 4); + for (size_t i = 0; i < (size_t)src.w * src.h; ++i) { + for (int c = 0; c < 3; ++c) pre.rgba[i * 4 + c] = src.rgb[i * 3 + c]; + pre.rgba[i * 4 + 3] = 255; + } + FrameRGBA post; + resize_lanczos_rgba(pre, w, h, &post); + out->w = post.w; + out->h = post.h; + out->rgb.resize((size_t)post.w * post.h * 3); + for (size_t i = 0; i < (size_t)post.w * post.h; ++i) + for (int c = 0; c < 3; ++c) out->rgb[i * 3 + c] = post.rgba[i * 4 + c]; +} + void composite_white(const FrameRGBA& src, Frame* out) { out->w = src.w; out->h = src.h; diff --git a/core/mm/imaging.h b/core/mm/imaging.h index 5457ace6..66639b11 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 for RGB: PIL's LANCZOS on the RGB image, which is the RGBA one at alpha 255. */ +void resize_lanczos_rgb(const Frame& src, int32_t w, int32_t h, Frame* 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. */ diff --git a/core/mm/item.cpp b/core/mm/item.cpp index d263ab3e..30a1f226 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -3,6 +3,8 @@ * metadata reader, the real device layer. */ #include "mm/processor.h" +#include + namespace rad { namespace mm { @@ -50,5 +52,37 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { } } +/* The rotary layout of one prompt: a run a segment, the text in front of a run counting up and a + * grid advancing the rotary by its longer side. Here, beside the accessors, so that code without + * the processor has it. */ +void PromptMedia::layout() { + rope.runs.clear(); + int64_t pos = 0, tok = 0; + for (size_t pi = 0; pi < items.size(); ++pi) { + const Placed& p = items[pi]; + const Item& it = *p.item; + const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1; + for (int32_t s = 0; s < it.n_seg; ++s) { + const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; + pos += run_tok - tok; /* the text in front of the run counts up */ + const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m; + const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m; + RopeLayout::Run r; + r.tok = (int32_t)run_tok; + r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s)); + r.w = rw; + r.base = (int32_t)pos; + r.flat = it.rope_1d; + /* A grid advances the rotary by its longer side; a 1-D run by its length. */ + pos += it.rope_1d ? r.n : std::max(rh, rw); + tok = run_tok + r.n; + r.shift = (int32_t)(pos - tok); + r.item = (int32_t)pi; + r.row0 = (int32_t)it.row_at(s); + rope.runs.push_back(r); + } + } +} + } /* namespace mm */ } /* namespace rad */ diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 4960668f..58643f79 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -1,5 +1,6 @@ /* processor.cpp -- see processor.h. */ #include "mm/processor.h" +#include "mm/imaging.h" #include "rad_internal.h" #include "rad_plugin.h" @@ -1809,6 +1810,126 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, return image_from(f, out, why, mode); } +namespace { +/* A picture's sides for a video encoder: the longer one scaled to at most `max_side`, aspect + * kept, then each floored to a multiple of `ratio`, at least one multiple. */ +void encoder_sides(int32_t fw, int32_t fh, int32_t ratio, int32_t max_side, int32_t* w, + int32_t* h) { + const int32_t longest = std::max(fw, fh); + const double scale = longest > max_side ? (double)max_side / (double)longest : 1.0; + auto snap = [&](int32_t s) { + const int64_t v = (int64_t)std::floor(s * scale) / ratio * ratio; + return (int32_t)std::min(std::max(v, ratio), max_side / ratio * ratio); + }; + *w = snap(fw); + *h = snap(fh); +} +} /* namespace */ + +int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + Frame* out, std::string* why) const { + if (ratio < 1 || max_side < ratio) { + if (why) *why = "the encoder's side ratio and maximum are not usable"; + return RAD_E_INVAL; + } + /* image()'s decode guard. The encoder runs a picture whole, not in ComfyUI's 256-pixel tiles, + * so a larger one is shrunk to its bound. */ + Frame f; + RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + int32_t w = 0, h = 0; + encoder_sides(f.w, f.h, ratio, max_side, &w, &h); + if (w == f.w && h == f.h) { + *out = std::move(f); + return RAD_OK; + } + resize_lanczos_rgb(f, w, h, out); + return RAD_OK; +} + +int Processor::encoder_image_canvas(const uint8_t* bytes, size_t n, int32_t w, int32_t h, + bool cover, Frame* out, std::string* why) const { + if (w < 1 || h < 1) { + if (why) *why = "the keyframe canvas is empty"; + return RAD_E_INVAL; + } + /* image()'s decode guard. */ + Frame f; + RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + if (!cover) { + /* A stretch, ComfyUI's first-frame resize. */ + if (w == f.w && h == f.h) { *out = std::move(f); return RAD_OK; } + resize_lanczos_rgb(f, w, h, out); + return RAD_OK; + } + /* Scaled to cover the canvas, aspect kept, then cropped at the centre: ComfyUI's last-frame + * resize. */ + const double s = std::max((double)w / (double)f.w, (double)h / (double)f.h); + int32_t cw = (int32_t)std::llround((double)f.w * s); + int32_t ch = (int32_t)std::llround((double)f.h * s); + if (cw < w) cw = w; + if (ch < h) ch = h; + Frame big; + resize_lanczos_rgb(f, cw, ch, &big); + const int32_t x0 = (cw - w) / 2, y0 = (ch - h) / 2; + out->w = w; + out->h = h; + out->rgb.resize((size_t)w * h * 3); + for (int32_t y = 0; y < h; ++y) + for (int32_t x = 0; x < w * 3; ++x) + out->rgb[(size_t)y * w * 3 + x] = + big.rgb[(size_t)(y0 + y) * cw * 3 + (size_t)(x0 * 3 + x)]; + return RAD_OK; +} + +namespace { +/* The frames a reference video keeps, spread over the stream: the most, within the stream and + * `max_frames`, that is 5 modulo 17, ComfyUI's trim; a shorter stream keeps what it has. */ +struct VaeSampleArgs { int32_t max_frames; }; +std::vector vae_sample_cb(const VideoInfo& info, const void* user) { + const VaeSampleArgs* a = static_cast(user); + const int64_t avail = info.n_frames > 0 ? info.n_frames : 1; + const int64_t cap = a->max_frames > 0 ? std::min(a->max_frames, avail) : avail; + int64_t want = cap - (((cap - 5) % 17) + 17) % 17; /* the largest v <= cap, v % 17 == 5 */ + if (want < 5) want = std::min(cap, 5); + const int64_t take = std::max(1, std::min(want, avail)); + std::vector idx((size_t)take); + for (int64_t i = 0; i < take; ++i) + idx[(size_t)i] = take > 1 ? (i * (avail - 1)) / (take - 1) : 0; + return idx; +} +} /* namespace */ + +int Processor::encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + int32_t max_frames, std::vector* out, std::string* why) const { + if (ratio < 1 || max_side < ratio) { + if (why) *why = "the encoder's side ratio and maximum are not usable"; + return RAD_E_INVAL; + } + /* image()'s decode guard. */ + Video v; + const VaeSampleArgs a{ max_frames }; + RAD_TRY(decode_video(bytes, n, vae_sample_cb, &a, cfg_.max_source_pixels, &v, why)); + if (v.frames.empty()) { + if (why) *why = "the video holds no frames"; + return RAD_E_INVAL; + } + int32_t w = 0, h = 0; + encoder_sides(v.frames.front().w, v.frames.front().h, ratio, max_side, &w, &h); + out->clear(); + out->reserve(v.frames.size()); + for (const Frame& f : v.frames) { + Frame r; + resize_lanczos_rgb(f, w, h, &r); + out->push_back(std::move(r)); + } + return RAD_OK; +} + +int Processor::encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why) const { + return decode_audio(bytes, n, rate, max_samples, out, why); +} + namespace { struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; }; std::vector sample_cb(const VideoInfo& info, const void* user) { @@ -2338,36 +2459,5 @@ int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr* out, return audio_from(s, out, why); } -/* ================================================================== rotary layout */ - -void PromptMedia::layout() { - rope.runs.clear(); - int64_t pos = 0, tok = 0; - for (size_t pi = 0; pi < items.size(); ++pi) { - const Placed& p = items[pi]; - const Item& it = *p.item; - const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1; - for (int32_t s = 0; s < it.n_seg; ++s) { - const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; - pos += run_tok - tok; /* the text in front of the run counts up */ - const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m; - const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m; - RopeLayout::Run r; - r.tok = (int32_t)run_tok; - r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s)); - r.w = rw; - r.base = (int32_t)pos; - r.flat = it.rope_1d; - /* A grid advances the rotary by its longer side; a 1-D run by its length. */ - pos += it.rope_1d ? r.n : std::max(rh, rw); - tok = run_tok + r.n; - r.shift = (int32_t)(pos - tok); - r.item = (int32_t)pi; - r.row0 = (int32_t)it.row_at(s); - rope.runs.push_back(r); - } - } -} - } /* namespace mm */ } /* namespace rad */ diff --git a/core/mm/processor.h b/core/mm/processor.h index b2659a64..eed2c4c3 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -368,11 +368,32 @@ public: std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const; int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; - /* From an already-decoded picture or frame list; for tests. */ + /* image() from a decoded frame: a keyframe's canvas frame (IMultimodal::prepare_frame), or a + * test's synthetic one. */ int image_from(const Frame& f, std::shared_ptr* out, std::string* why, const ImageMode& mode = ImageMode{}) const; int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; + /* Media for a video generator's VAE encoders (RadVideoGenDecl), decoded under `image`'s guard. + * A reference picture, scaled with its aspect kept to sides that are multiples of `ratio`, the + * longer at most `max_side`. */ + int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, Frame* out, + std::string* why) const; + + /* A keyframe, at the video's w x h: stretched, or with `cover` scaled to cover it and cropped + * at the centre. */ + int encoder_image_canvas(const uint8_t* bytes, size_t n, int32_t w, int32_t h, bool cover, + Frame* out, std::string* why) const; + + /* A reference video: frames spread over the stream, at most `max_frames` and 5 modulo 17 + * (ComfyUI's trim), each at encoder_image's sides. */ + int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + int32_t max_frames, std::vector* out, std::string* why) const; + + /* A soundtrack: its first stream, mono at `rate` Hz, at most `max_samples`. */ + int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why) const; + /* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the * encoder's. */ int init_audio(const AudioConfig& cfg, std::string* why = nullptr); diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 1c864985..9e4085b0 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -228,6 +228,12 @@ int Registry::commit_(Staged& s, int order) { /* A video generator's rotary positions; the driver refuses to start without it. */ p.arch_video_positions = dl_fn( s.handle, "rad_arch_video_positions"); + /* Its reference conditioning, which the video driver refuses to serve without. */ + p.arch_video_pack = dl_fn( + s.handle, "rad_arch_video_pack"); + p.arch_encode_geom = dl_fn( + s.handle, "rad_arch_encode_geom"); /* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim * the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16 diff --git a/core/plugin/registry.h b/core/plugin/registry.h index 65fea419..fdced875 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -97,6 +97,10 @@ struct Plugin { /* Optional (rad_builder.h, rad_arch_serves_imports); absent is true. False keeps the plugin * out of the pick for an imported checkpoint (startup.h). */ bool arch_serves_imports = true; + /* A video generator's reference conditioning (rad_builder.h); null for one without. */ + int64_t (*arch_video_pack)(const RadVideoGeom*, const int32_t*, int32_t*, int32_t*, int32_t*, + int32_t*, float*, int64_t) = nullptr; + int64_t (*arch_encode_geom)(int32_t, const int64_t*, int32_t*, int64_t) = nullptr; RadPluginCloseFn close = nullptr; }; diff --git a/core/rad_core.h b/core/rad_core.h index dd5fb92c..67911b80 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -289,6 +289,9 @@ struct KVGroupInfo { int64_t bytes_per_state = 0; /* linear/conv: per sequence */ std::vector layers; bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */ + /* rad_kv_group_dense_read: read over the whole history every step (an indexer's block keys), so + * it cannot stream and must hold every sequence's context while a sibling streams. */ + bool dense_read = false; bool replicated = false; /* rad_kv_group_replicated: the same bytes on every rank */ /* Bound only at meta.n_layers and above: the drafter's own cache, which no trunk layer reads. * Set at declare (Builder::finish_kv_groups). */ @@ -504,12 +507,10 @@ public: Geometry geom; std::string geom_key; const RadKernelInfo* info = nullptr; - /* The instance init() produced for this instantiation, null for a kernel with no init. - * A collective's launch cannot be formed without it: the peer bundle -- the scratch, the - * flags and the sequence counters, published to every rank and made peer-accessible at - * init -- is what makes the exchange addressable, and RadArgs carries no other route to - * it. The instance belongs to the rank this Program was declared for (Program::ctx), and - * the Registry that made it must outlive the launch (spec §1, §15). */ + /* The instance init() made for this instantiation, null for a kernel with no init. A + * collective's launch reaches its peer bundle (scratch, flags, sequence counters) only + * through it. It belongs to the rank this Program was declared for, and the Registry that + * made it must outlive the launch (spec §1, §15). */ void* instance = nullptr; }; std::vector tune_requests; @@ -775,6 +776,10 @@ struct Config { /* --tp-attn-split heads|rows: 1 runs a prefill-sized step's attention by rows over the ranks * (RadBuildCtx::tp_attn_rows). Not bit-identical to the head split, so heads is the default. */ int tp_attn_rows = 0; + /* --weight-prefetch on|off: off declares none of the plugin's weight reads beside the + * collectives (RadBuildCtx::weight_prefetch_off), for an engine that shares its cards with + * another server, where the second lane's read costs a queue switch every decode step. */ + bool weight_prefetch = true; /* Smallest all-reduce message, in KiB, that the lossy wire compresses; smaller ones are sent * exact. Compression pays only when the transfer is bandwidth-bound: a decode step's handful * of residual rows costs more to rotate than it saves, while a prefill chunk is far larger. @@ -826,6 +831,13 @@ struct Config { * accepted in e4m3 (RadBuildCtx::attn_prefill_fp8). Lossy, so off is the default. * attn_prefill_fp8_name() spells it as the flag does. */ int attn_prefill_fp8 = 0; + /* --kv-resident N: tokens of the sparse attention group's context its VRAM ring holds + * (docs/KV-STREAMING.md). 0 is off; a ring that covers `max_seqs x max_ctx` streams nothing; a + * ring below kStreamFloorTokens or one decode step's selection is raised to it. */ + int64_t kv_resident = 0; + /* Derived: whether a group streams, set by kvstream_cap_probe before the pool is sized (a + * streamed group's ceiling is its ring and stage, not its cache); the KV MiB rounding reads it. */ + bool kv_streams = false; int64_t host_pool_mib = 0; int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */ /* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 2db02d28..ff0f746c 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -329,6 +329,14 @@ int Ctx::bind_ops() { p.n_bands = (int32_t)oi.bands.size(); p.plan_off = (int32_t)issue_table_.size(); p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1; + p.n_opd_required = -1; + if (oi.schema) { + /* One past the last required operand: an issue may leave out the optional ones after + * it. */ + for (int o = 0; o < oi.schema->n_operands; ++o) + if (!oi.schema->operands[o].optional) p.n_opd_required = o + 1; + if (p.n_opd_required < 0) p.n_opd_required = 0; + } /* Matched by name once here, not on the issue path; see OpPlan::billed. */ p.billed = (oi.op == "all_reduce"); p.collective = p.billed; @@ -959,10 +967,7 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table); mix((uint64_t)k.block_table_pitch); ptr(k.seqused); ptr(k.state_index); mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks); - /* Null on a fully resident group, a fixed set of addresses on a streamed one. Two groups - * that differ here hand a kernel different memory, so they are different passes -- and the - * view's *address* must not enter the key: the builder's Out slot rotates every step, which - * would make every streamed pass a new one (kvstream/bind.h, kvstream_view_key). */ + /* A streamed group's view by the memory it names, never its address (kvstream_view_key). */ mix(kvstream_view_key(k.stream)); } mix((uint64_t)level_); @@ -1267,8 +1272,7 @@ int Ctx::run_pass(const RadBatch* b) { /* A pass the stager armed for is issued live: see runtime/stager.h. */ if (!tape_on_ || staging_) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } const uint64_t key = pass_key(b); - if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); - return RAD_OK; } + if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } if (std::find(tape_refused_.begin(), tape_refused_.end(), key) != tape_refused_.end()) { bump(pc_refused_); arch_step_(this, b); diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 3a52cddf..db6bf847 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -75,9 +75,11 @@ struct OpPlan { int32_t band_off = 0; /* into Ctx::band_table_ */ int32_t n_bands = 0; int32_t plan_off = 0; /* into Ctx::issue_table_, band * RAD_N_DOMAINS + domain */ - /* The schema's operand count, cached so the arity check avoids a cold OpInfo. -1 when the op - * has no schema. */ - int32_t n_opd_schema = -1; + /* The schema's operand count, cached so the arity check avoids a cold OpInfo, -1 when the op + * has no schema; and the count without its trailing optional operands, which an issue may + * leave out. */ + int32_t n_opd_schema = -1; + int32_t n_opd_required = -1; bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */ /* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows * (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share @@ -141,11 +143,9 @@ struct RouteSlot { * LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]] * CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time */ -/* One of the two views a streamed group's allocation is addressed through. `depth` is the number - * of layer stripes the view presents: the ring keeps the group's `n_layers`, the stage presents - * one and every layer aliases offset 0. The field is a depth and NOT a rewritten `layer_slot`: - * that table is also the host mirror's row (rad_kv_layer_index), so collapsing it would write all - * layers into one mirror row (docs/KV-STREAMING.md §3.5.1). */ +/* One of a streamed group's two views of its allocation (kvstream/bind.h). `depth` is the stripe + * count it presents: 0 for the ring's `n_layers`, 1 for the stage, where every layer aliases + * offset 0. */ struct KVViewState { int64_t layer_stride = 0; int64_t bytes = 0; @@ -164,24 +164,19 @@ struct KVPoolBinding { std::vector layer_slot; uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */ int64_t shape[RAD_MAX_RANK] = {0}; - /* The active view's stripe count: 0 is n_layers, 1 is the one-layer prefill stage. */ + /* The active view's stripe count, as KVViewState::depth. */ int64_t depth = 0; - /* Both fixed views over the group's one allocation. The ring is always present; the stage only - * for a group whose plan depth is 1 (its ring is smaller than its context). The active fields - * above are set from one of these before each pass (kvstream_enter), so a recorded pass that - * used a view replays against it: the pass key already carries the phase, which selects it. */ + /* Both views of a streamed group's allocation; the stage only when the plan's depth is 1. The + * active fields above are set from one of them before each pass (kvstream_enter). */ KVViewState ring; KVViewState stage; bool has_stage = false; - /* Bytes of one layer's mirror row a staged pass must copy, from the block manager's highest - * held block (kvstream/stage.h). 0 copies the whole row, which is always correct and is what a - * caller with no manager (a test, a harness) leaves it at. Set once per step, before the pass, - * because the bound grows as a prefill appends blocks. */ + /* Bytes of a layer's mirror row a staged pass copies, from the held bound (kvstream/stage.h, + * "Volume"), set each step. 0 copies the whole row. */ int64_t stage_live_bytes = 0; }; -/* The KV stage's driver, run again where a recorded pass made it (kvstream/stage.cpp). `after` is - * the call the architecture makes after a layer's attention instead of before it. */ +/* The KV stage's driver (kvstream/stage.cpp), declared here for Ctx::tape_kv_stage. */ int kvstage_run(Ctx* c, int group, int layer, bool after); struct CtxDesc { @@ -243,19 +238,18 @@ public: 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_; } - /* Whether the pass being issued is being recorded. Work a tape cannot record -- a DMA - * submission -- must be re-run where the pass made it instead (tape_kv_stage). */ + /* Whether the pass being issued is being recorded. */ bool recording() const { return rec_ != nullptr; } - /* While recording: a KV stage call becomes a host step that re-runs at every play, because the - * DMA list it hands the engine and the stream wait on the list's completion word are neither of - * them queue packets (kvstream/stage.cpp; xprefetch.cpp does the same for the prefetch). */ + /* A KV stage call while recording: a host step that re-runs at every play, because its DMA + * list is not a queue packet (kvstream/stage.cpp; xprefetch.cpp does the same). */ int tape_kv_stage(bool after, int group, int layer) { TapeStep st; st.kind = (uint8_t)(after ? kTapeKvStageAfter : kTapeKvStage); st.a = group; st.b = layer; return tape_host(st, [&] { return kvstage_run(this, group, layer, after); }); - } /* This rank's device ordinal, for the calls that name a card rather than a stream. */ + } + /* This rank's device ordinal, for the calls that name a card rather than a stream. */ int device() const { return device_; } int world_size() const { return world_size_; } RadStream stream() const { return stream_; } @@ -274,11 +268,10 @@ public: void* weight_ptr(rad_weight w); void* buf_ptr(rad_buf b); - /* The group-local position of absolute model layer `layer` in the binding's layer_slot, or -1. - * rad_kv_layer_index (rad_runtime.h) exposes it to a plugin, which needs it for the host - * mirror: that is laid out by the group's layers, not by model layer numbers. */ + /* The group-local position of model layer `layer` in the binding's layer_slot, or -1: the + * index of its host mirror row (rad_kv_layer_index). */ int64_t kv_layer_index(rad_kvgroup g, int layer) const; - /* The group's pool binding, for the view switch and the stage copy. */ + /* The group's pool binding, for the view switch and the stage. */ const KVPoolBinding* kv_binding(rad_kvgroup g) const { return g < kv_.size() ? &kv_[(size_t)g] : nullptr; } diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 154f12b3..3ffbfef0 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -596,8 +596,8 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { /* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across * it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside * it, on either side: a transient of such an op may share bytes with a concurrent buffer. An op - * that names no buffer (a weight read into the cache, prefetch_beside) touches nothing the window - * keeps live and has no transient: it runs on lane 1 anywhere and leaves no window work to join. */ + * that names no buffer (prefetch_beside's weight read) touches nothing the window keeps live, + * so it may run on lane 1 anywhere. */ bool names_buf = false; for (int i = 0; i < n_opd && !names_buf; ++i) names_buf = opd[i].kind == RAD_OPK_BUF; if (program_ && program_->lane1_w1 >= 0 && names_buf) { @@ -627,13 +627,23 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { return abort_step_msg(h, RAD_E_INVAL, fmt("issued with %d operands; the runtime carries at most %d", n_opd, MAX_OPERANDS)); - if (p.n_opd_schema >= 0 && n_opd != p.n_opd_schema) + /* A count below the schema is legal only when every dropped slot is a *trailing optional* + * operand (rad_abi.h: "an absent optional operand is a null RadTensor.data" -- the shims + * branch on exactly that: r4d_opt(), rad_args_have(), libref's finish()). A count below the + * required floor shifts positions or drops a required operand, and operands are positional, + * so a miscount is silent numerical garbage. */ + if (p.n_opd_schema >= 0 && (n_opd > p.n_opd_schema || n_opd < p.n_opd_required)) return abort_step_msg(h, RAD_E_SCHEMA, - fmt("issued with %d operands; the op's schema declares %d. Operands " - "are positional, so a miscount is silent numerical garbage", - n_opd, (int)p.n_opd_schema)); + fmt("issued with %d operands; the op's schema declares %d " + "(%d required, only trailing optional operands may be omitted). " + "Operands are positional, so a miscount is silent numerical " + "garbage", + n_opd, (int)p.n_opd_schema, (int)p.n_opd_required)); RadTensor* t = tbuf_; + /* The schema slots the issue stopped short of: absent operands, null tensors rather than + * stale ones, since args.n_t covers every schema slot (rad_plugin.h). */ + for (int i = n_opd; i < p.n_opd_schema; ++i) t[i] = RadTensor{}; bool touches_host = false; /* a host-domain buffer among the operands; see host_touch_ev_ */ for (int i = 0; i < n_opd; ++i) { @@ -841,8 +851,9 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { } } - /* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. */ - ip.args.n_t = n_opd; + /* The rest of RadArgs was filled in at prepare; args.t already points at tbuf_. There is one + * entry per schema operand, the trailing optional ones the issue left out null. */ + ip.args.n_t = std::max(n_opd, (int)p.n_opd_schema); p.issued = true; ++n_issues_; @@ -857,7 +868,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { /* The oracle snapshots every operand before the launch, so the host kernel sees the same * input bytes even for an in-place op. */ - const IssuePlan* horacle = oracle_ ? oracle_before(h, b, n_opd) : nullptr; + const IssuePlan* horacle = oracle_ ? oracle_before(h, b, ip.args.n_t) : nullptr; /* ============================== a host launch is a join ============================== * @@ -1049,7 +1060,6 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { g_iss_lau_p = g_iss_lau; } } else { - /* The launch alone, split from the band scan and operand resolution `own` covers above. */ s = ip.launch(la, cur_stream()); } if (hold) { @@ -1075,7 +1085,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { if (er < 0) return abort_step(h, b, dom, ip, n, er); host_touch_pending_[l] = true; } - if (horacle) oracle_after(h, *horacle, ip, n_opd); + if (horacle) oracle_after(h, *horacle, ip, ip.args.n_t); return RAD_OK; } diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp index bb734863..46ae1330 100644 --- a/core/runtime/kvbind.cpp +++ b/core/runtime/kvbind.cpp @@ -13,8 +13,7 @@ void bind_kv_pools(const Program& p, const std::functionbase; b.layer_stride = gp->layer_stride(); b.bytes = gp->pool_bytes; @@ -37,14 +36,11 @@ void bind_kv_pools(const Program& p, const std::functionpool_blocks(); b.shape[1] = d.n_head_kv; b.shape[2] = gp->block_size; b.shape[3] = 2 * d.head_dim; - /* Both fixed views over the group's one allocation, with the ring active. */ kv_bind_views(*gp, &b); break; case RAD_KV_LINEAR: diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 075407c3..12a38194 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -1,7 +1,6 @@ #include "runtime/tierexec.h" #include "rad_internal.h" -#include "kvstream/plan.h" #include #include @@ -32,17 +31,13 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, for (int32_t g : groups) { const KVGroupPlan* p = kv->plan(g); if (!p || !p->paged()) continue; - /* A streamed group's pool is one layer of its context, so a gather of layer L would copy - * the last staged layer n_layers times. Its mirror is the tier and the residency map - * restores a block on the next resolve (docs/KV-STREAMING.md §4.1). */ - if (!kv_tier_cached(*p)) continue; + /* A streamed group's host mirror is its tier (docs/KV-STREAMING.md §4.1). */ + if (p->streamed()) continue; GroupInfo gi; gi.g = g; gi.n_layers = p->n_layers; gi.frag = p->layer_bytes_per_block(); gi.layer_stride = p->layer_stride(); - /* The pool's depth: a streamed group backs fewer blocks than it addresses, and the tier - * gathers fragments of the blocks that are here (docs/KV-STREAMING.md §3.1). */ gi.n_blocks = p->pool_blocks(); gi.base = p->base; gi.replicated = p->replicated; @@ -116,12 +111,8 @@ int TierExec::slot_layout(const std::vector& ranks, for (int32_t g : groups) { const KVGroupPlan* p0 = ranks[0]->plan(g); if (!p0 || !p0->paged()) continue; - /* A streamed group is not part of a tier entry: its pool is one layer deep, so a gather - * of layer L would copy the last staged layer n_layers times, and its host mirror is the - * tier (docs/KV-STREAMING.md §4.1). TierExec::stage skips the same groups, so this - * arithmetic and its gather offsets agree. A streamed group is never replicated, so - * leaving it out of the replicated window too is the safe rule. */ - if (!kv_tier_cached(*p0)) continue; + /* Skipped as in configure(), so the slot layout and the gather offsets agree. */ + if (p0->streamed()) continue; bool replicated = false; for (size_t i = 0; i < ranks.size(); ++i) { const KVGroupPlan* p = ranks[i]->plan(g); diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index 7b8ae007..a173f7d0 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -168,14 +168,11 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { ctx[i] = base; /* The context ends at the last committed position, not at the run's end. Attention places * row j of a q_len-row run at seqused - q_len + j and reads keys up to there (attn_paged's - * contract, libref/ref_attn.cpp). The rows past `last` sit at the last committed position - * but are counted as if at base + j, so with the run's whole length the last row -- round - * 1, the one row whose output goes on -- would also read the n_spec - acc positions after - * it, which the head has not written for this sequence: last step's speculative rounds, or - * whatever the block held before it was handed out (another request's K and V, or bytes - * the expert slab left on a recalled loan). Ending it there puts the last row where it - * is; earlier rows count lower than their positions, but nothing reads their output, and - * every row's K and V still store at the slot of its own position. */ + * contract). With the run's whole length the last row, the only one whose output is used, + * would also read the n_spec - acc positions after it, which the head has not written for + * this sequence (stale rounds, or another request's K and V). Earlier rows then count + * lower than their positions, but nothing reads their output, and every row's K and V + * still store at its own position's slot. */ adv_groups(a, i, k, base, n, last + 1); return; } diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index d21ab81a..bd2907bc 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -4,6 +4,7 @@ #include "mm/processor.h" #include "derive.h" #include "device/device.h" +#include "kvstream/bind.h" #include #include @@ -12,11 +13,9 @@ namespace rad { -/* How many steps of the following prompt the PLE read-ahead queue stages (RadBatch::n_ahead): - * the arch's reader thread drains the queue at disk speed, off the step path, so a prefill - * chunk's table rows are already cached when its gather runs. Keep in step with rad_block_ple.h - * (kAheadChunks), which clamps to the buffer it declared; a mismatch degrades to a smaller queue, - * never an overflow. */ +/* Steps of the following prompt a prefill batch carries for the PLE read-ahead queue + * (RadBatch::n_ahead), whose rows the arch's reader thread prefetches off the step path. Keep in + * step with rad_block_ple.h's kAheadChunks, which clamps to the buffer it declared. */ static constexpr int64_t k_ahead_chunks = 8; /* Alignment of each staging array carved from a set's slab. One slab per set means a couple of @@ -104,9 +103,7 @@ void BatchBuilder::carve(Set& s, char* h) { *ph = ::rad::carve(h, oh, n); *pd = ::rad::carve(d, od, n); }; - /* The step's tokens, then the PLE read-ahead queue -- k_ahead_chunks steps of the following - * prompt (RadBatch::n_ahead), which the arch's reader thread prefetches off the step path - * (rad_block_ple.h, which clamps to the same count). */ + /* The step's tokens, then k_ahead_chunks steps of the following prompt (RadBatch::n_ahead). */ pair(&s.h_tok, &s.d_tok, (1 + k_ahead_chunks) * T); pair(&s.h_pos, &s.d_pos, T); pair(&s.h_parent, &s.d_parent, T); @@ -241,6 +238,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector& groups) { for (Out& o : out_) { o.kv.assign(ranks_.size(), std::vector(s.groups.size())); + o.stream.assign(ranks_.size(), std::vector(s.groups.size())); o.batch.assign(ranks_.size(), RadBatch{}); } pitch_.assign(s.groups.size(), 1); @@ -829,6 +827,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& a.tlen_off = (const char*)s.d_tlen - d0; } + /* Each rank's own view of the group's ring and mirror (kvstream_step_view). */ + const RadKVStream* sv = kv.stream_view((int32_t)gi); for (size_t r = 0; r < ranks_.size(); ++r) { void* base = s.dev[r]; RadKVGroupBatch& b = o.kv[r][gi]; @@ -841,6 +841,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& b.state_index_pitch = g.sidx_pitch; b.block_size = L.block_size; b.max_blocks = pitch; + b.stream = kvstream_step_view(&o.stream[r][gi], + ranks_[r].kv_streams ? ranks_[r].kv_streams[gi] : sv, + ranks_[r].kv_streams != nullptr, + ranks_[0].kv_base, ranks_[r].kv_base); /* The group's arrays are uploaded with the rest of the slab in build(). */ } @@ -1052,10 +1056,10 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, } } - /* Up to the read-ahead queue's worth of the last sequence's following tokens, after this - * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, - * bounded by the tokens the request has; like token_at, a re-prefill after preemption - * continues into its own output. The arch clamps to the rows it declared. */ + /* Up to k_ahead_chunks steps of the last sequence's following tokens, after this step's own + * (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by the + * tokens the request has; like token_at, a re-prefill after preemption continues into its own + * output. The arch clamps to the rows it declared. */ int64_t n_ahead = 0; if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) { const StepEntry& e = plan.e[(size_t)(n_seq - 1)]; diff --git a/core/sched/batch.h b/core/sched/batch.h index f2ec88f5..524778cd 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -105,6 +105,13 @@ public: int device = 0; RadStream stream = nullptr; Program* prog = nullptr; + /* This rank's KV pool base, for rebasing rank 0's map pointers when no per-rank views are + * given (kvstream_step_view). */ + void* kv_base = nullptr; + /* Per group, this rank's stream view or null, owned by the engine. Each rank's view names its + * own maps and its own mirror. Pointers rather than the manager, so a test that drives the + * builder without a device does not link the manager. */ + const RadKVStream* const* kv_streams = nullptr; }; /* `prog` is non-const because derived buffers are written into its arena, whose pointer lands @@ -242,6 +249,8 @@ private: static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4; struct Out { std::vector> kv; + /* Per rank and group, the RadKVStream a batch names: each rank's own copy, outside the slab. */ + std::vector> stream; std::vector batch; }; diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 94871128..e7e329a2 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -94,6 +94,8 @@ struct IKVManager { /* Blocks held by anything, as opposed to free_blocks (what can be handed out now). On an * elastic pool they differ by what the cache released (KVManager::held_blocks). */ virtual int64_t held_blocks(int32_t group) const = 0; + /* KVManager::held_top_blocks; a manager that cannot answer says the whole row. */ + virtual int64_t held_top_blocks(int32_t group) const { (void)group; return INT64_MAX; } /* The pool in bytes, the only unit that sums across groups. Asked of the manager because its * plan knows whether a group counts blocks or states. */ @@ -102,6 +104,15 @@ struct IKVManager { /* What the carve gave the group; an elastic pool may have released part of it. */ virtual int64_t pool_bytes_carved(int32_t group) const = 0; + /* A streamed group's RadKVStream for the step batch, or null for a resident group; its addresses + * are fixed from bring-up. */ + virtual const RadKVStream* stream_view(int32_t group) const { (void)group; return nullptr; } + /* The resolve's cumulative traffic and the rings' depth, for the metrics; zero without + * streaming. */ + virtual int64_t stream_misses() const { return 0; } + virtual int64_t stream_bytes_in() const { return 0; } + virtual int64_t stream_resident_blocks() const { return 0; } + /* Tokens one block covers, or 0 for a stateful group. */ virtual int64_t block_tokens(int32_t group) const = 0; /* A checkpoint slot carries this group's window (KVGroupPlan::win_snap): a prefix hit, which @@ -329,9 +340,16 @@ struct KVBinding final : IKVManager { int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); } int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); } int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); } + int64_t held_top_blocks(int32_t g) const override { return m->held_top_blocks(g); } int64_t pool_bytes(int32_t g) const override { return m->pool_bytes(g); } int64_t pool_bytes_used(int32_t g) const override { return m->pool_bytes_used(g); } int64_t pool_bytes_carved(int32_t g) const override { return m->pool_bytes_carved(g); } + const RadKVStream* stream_view(int32_t g) const override { return m->stream_view(g); } + int64_t stream_misses() const override { return (int64_t)m->stream_stats().misses; } + int64_t stream_bytes_in() const override { return (int64_t)m->stream_stats().bytes_in; } + int64_t stream_resident_blocks() const override { + return m->stream_stats().resident_blocks; + } int64_t block_tokens(int32_t g) const override { const KVGroupPlan* p = m->plan(g); return p && p->paged() ? p->block_size : 0; diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 1ed81a9f..20889e24 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -77,6 +77,11 @@ struct SchedMetrics { * difference is the VRAM the elastic pool released behind unheld blocks. */ int64_t bytes_carved = 0; } kv[RAD_SCHED_MAX_KV_GROUPS]; + /* KV streaming: the rings' depth over every streamed group, and the resolve's cumulative misses + * and bytes copied in from the host mirrors. Zero when nothing streams. */ + int64_t kv_resident_blocks = 0; + int64_t kv_stream_misses = 0; + int64_t kv_stream_bytes_in = 0; /* Prefix caching (§7.3). Attention and linear are reported separately because they hit at * different granularities. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index fe6e4b4f..9f6507c9 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -483,6 +483,7 @@ void Scheduler::trim_prefix_cache() { void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free, bool publish, int status, const char* why) { + ++step_finished_; /* Publish before freeing: this is the only moment the whole prefix is both computed and still * owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled * and failed requests are published too; their prompts were computed, and a client that hangs @@ -563,6 +564,44 @@ void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_ ++m_.checkpoints_written; } +int Scheduler::fail_prefilling(const char* why) { + std::lock_guard lk(mu_); + /* The sink keeps this pointer past the call (Sink::why_). */ + stream_why_ = why ? why : "kv streaming overflow"; + why = stream_why_.c_str(); + int n = 0; + /* The prompts the step just committed completed; when it produced no row (a middle prefill + * chunk), every request still prefilling, whose next chunk would read the failed table. */ + const bool by_step = !last_prefill_ids_.empty(); + auto fail = [&](SchedReq& s) { + if (s.req->state != ReqState::Running && s.req->state != ReqState::Preempted && + s.req->state != ReqState::Waiting) + return; + /* The next step may already be issued, so blocks it names stay until its commit, as for + * cancel(). */ + const bool in_flight = in_step(s) || block_holds(s.req->id); + /* RAD_E_FULL: the ring ran out (RAD_E_STATE would read "called in the wrong phase"). */ + close_request(s, ReqState::Failed, "kv_stream_overflow", in_flight, + /*publish=*/false, RAD_E_FULL, why); + ++n; + }; + if (by_step) { + for (uint64_t id : last_prefill_ids_) { + auto it = by_id_.find(id); + if (it != by_id_.end()) fail(*reqs_[(size_t)it->second]); + } + } else { + std::vector live(running_); + live.insert(live.end(), waiting_.begin(), waiting_.end()); + for (int32_t slot : live) { + if (slot < 0 || (size_t)slot >= reqs_.size() || !reqs_[(size_t)slot]) continue; + SchedReq& s = *reqs_[(size_t)slot]; + if ((int64_t)s.req->n_computed < (int64_t)s.req->prompt.size()) fail(s); + } + } + return n; +} + int Scheduler::cancel(uint64_t id) { std::lock_guard lk(mu_); auto it = by_id_.find(id); @@ -1843,15 +1882,12 @@ bool Scheduler::is_eog(int32_t id) const { return std::binary_search(eog_.begin(), eog_.end(), id); } -/* Whether the step just issued ends every request it carries: when it can bring each to its - * max_tokens -- certainly with the token it emits, possibly with the drafts it verifies, since it - * commits that token and every draft it accepts -- or, most likely, when those drafts hold an - * end-of-generation id (not for an ignore_eos request). A step issued ahead behind it would verify - * nothing, its rows' requests finished by the commit in between, yet the card runs its whole - * forward pass and the drafter's passes behind it, and a request that arrives once the last token - * is out (a client's next turn, sent as this one ends) queues behind them: a decode step of TTFT - * (#225). A guess that misses (a drafted end the verify rejects, or too few drafts accepted to - * reach max_tokens) costs one step built after the commit instead of before it. */ +/* Whether the step just issued likely ends every request it carries: its token and accepted drafts + * can reach each request's max_tokens, or its drafts hold an end-of-generation id (unless + * ignore_eos). A step issued ahead behind it would verify nothing, yet the card would run its + * forward pass and drafter passes, and a request arriving as the reply ends (a client's next turn) + * would wait behind them, about a decode step of TTFT. A wrong guess costs one step built after + * the commit instead of before it. */ bool Scheduler::ends_every_request() const { for (const StepEntry& e : plan_.e) { if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) return false; @@ -1875,8 +1911,7 @@ const RadBatch* Scheduler::step_next_locked() { /* Once the hold is spent, the held chunk goes into the next full step rather than waiting * behind decode steps issued ahead. */ if (held_prefill_ > 0 && interleave_left_ == 0) return nullptr; - /* Nothing behind a step that ends every request it carries (ends_every_request). Before the - * loop below, which reserves the next step's KV. */ + /* Before the loop below, which reserves the next step's KV. */ if (ends_every_request()) return nullptr; plan_next_.reset(); @@ -1975,14 +2010,16 @@ void Scheduler::promote_next() { } /* ------------------------------------------------------------------ commit */ -/* With early ids (Engine::collect_step waits on tok_end_, not step_end_), this runs while the card - * may still be running the drafter's passes behind the step. So it issues no device work and - * allocates nothing: what it releases (KV blocks, StepSlot cards, prefix-cache publications) may - * still be read by those passes, and is reused only by work the engine issues after its wait for - * step_end_. Device work or an allocation added here must move behind that wait. */ -int Scheduler::commit(const StepResult& res) { +/* This may run while the card still runs the drafter's passes behind the step (Engine::StepOut:: + * early). It therefore issues no device work and allocates nothing: what it releases (KV blocks, + * StepSlot cards, prefix-cache publications) may still be read by those passes, and is reused only + * by work the engine issues after waiting for step_end_. */ +int Scheduler::commit(StepResult& res) { std::lock_guard lk(mu_); if (!step_open_) return RAD_E_STATE; + /* StepResult's counts describe this step only. */ + step_finished_ = 0; + last_prefill_ids_.clear(); if (res.n_seq != (int)plan_.e.size()) { RAD_ERR("commit of %d sequences against a step of %d", res.n_seq, (int)plan_.e.size()); return RAD_E_INVAL; @@ -2045,8 +2082,12 @@ int Scheduler::commit(const StepResult& res) { r.n_cached); /* Once, when the prompt is fully placed: the usage block's admission accounting. * `n_cached` is what the prefix cache supplied. */ - if (r.n_computed >= (int64_t)r.prompt.size()) + if (r.n_computed >= (int64_t)r.prompt.size()) { server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached); + /* From here a decode step reads the ring, and the engine checks the resolve's + * overflow. */ + last_prefill_ids_.push_back(r.id); + } if (e.produces_token && res.token && r.embed) { /* The answer is the pooled vector the engine already put in the sink; there is * no token to emit, and `eos` ends the request below. */ @@ -2172,8 +2213,8 @@ int Scheduler::commit(const StepResult& res) { } else if (eos) { close_request(s, ReqState::Finished, "stop", carried); } - /* -v: a step issued ahead behind a request this commit ended verifies nothing; why the - * rule in step_next_locked let it through (ends_every_request). */ + /* -v: a request ended with a step issued ahead behind it, which ends_every_request did not + * predict. */ if (carried && r.state != ReqState::Running && (int)log_level() >= (int)Log::Debug) { const int32_t acc = res.n_accepted ? res.n_accepted[i] : 0; bool drafted_end = false; @@ -2195,10 +2236,11 @@ int Scheduler::commit(const StepResult& res) { /* Every entry is retired, so anything deferred on this step, or on a drafter snapshot that * block_end() / serial_end() has since cleared, can be released: every pass naming them was - * issued before this step's readback. That readback may return while the drafter's passes - * behind it still run (Engine::StepOut::early), and the engine then waits for them before it - * issues anything else, so nothing reuses what is released here before they end. */ + * issued before this step's readback, and the engine waits for the drafter's passes behind it + * before issuing anything that could reuse what is released here. */ sweep_deferred(); + res.n_prefill_done = (int)last_prefill_ids_.size(); + res.n_finished = step_finished_; return RAD_OK; } @@ -2413,6 +2455,9 @@ const RadBatch* Scheduler::serial_batch(int round, int step) { serial_plan_.reset(); serial_plan_.phase = RAD_PHASE_DECODE; + /* The deployment's window, though no draft-pass entry verifies: the pass's KV view is chosen + * from its row shape against 1 + n_spec (kv_pass_view). */ + serial_plan_.n_spec = cfg_.n_spec > 0 ? cfg_.n_spec : 0; /* Negative is the history pass; positive is draft round r. The sign is what the plugin reads * to decide whether the pass ends in the lm_head (rad_runtime.h). */ serial_plan_.draft_pass = round == 0 ? -1 : round; @@ -2847,6 +2892,10 @@ SchedMetrics Scheduler::metrics_locked() const { m.kv[i].bytes_used = kv_->pool_bytes_used(i); m.kv[i].bytes_carved = kv_->pool_bytes_carved(i); } + /* Zero on a server whose groups are all resident. */ + m.kv_resident_blocks = kv_->stream_resident_blocks(); + m.kv_stream_misses = kv_->stream_misses(); + m.kv_stream_bytes_in = kv_->stream_bytes_in(); if (pc_) { m.prefix_evictions = pc_->evictions(); m.prefix_ckpt_evictions = pc_->ckpt_evictions(); diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 421c13a3..d30eafc3 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -127,12 +127,15 @@ struct SchedReq { class Scheduler { public: /* What the sampler hands back after a step: per sequence, how many drafts survived, the token - * sampled at the accepted position, and whether the sequence ended. No logits. */ + * sampled at the accepted position, and whether the sequence ended. No logits. commit() fills + * in the two counts. */ struct StepResult { int n_seq = 0; const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */ const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */ const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */ + int n_prefill_done = 0; /* prompts this step fully placed */ + int n_finished = 0; /* requests that ended during this step */ /* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its * accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */ const TokenLogprobs* lp = nullptr; @@ -176,6 +179,10 @@ public: * under exactly the load that cancels. */ int cancel(uint64_t id); Request* find(uint64_t id); + /* Fail every request prefilling in the step just committed, with `why` for the client: a streamed + * group's resolve latched overflow, so their selection tables no longer address the pool + * (docs/KV-STREAMING.md §3.4). */ + int fail_prefilling(const char* why); /* Whether the request is still admitted and Running, read under the lock. */ bool running(uint64_t id) const; /* What the step just committed left for `seq`, copied by commit under the lock. False when @@ -274,9 +281,8 @@ public: * cache. Takes the step lock because the step path inserts into the map (live sequences hold * their own block references). See IScheduler::reset_prefix_cache. */ int64_t reset_prefix_cache(); - /* The vocabulary's end-of-generation ids, the ones the card's acceptance reads: step_next() - * issues no step ahead behind one whose drafts end every request it carries. Set once at - * start; none (the default) leaves only the max_tokens half of that rule. */ + /* The end-of-generation ids the card's acceptance reads, for ends_every_request. Set once at + * start; without them only max_tokens ends are predicted. */ void set_eog(std::vector ids); /* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens` * (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that @@ -311,12 +317,14 @@ public: void expect_draft(uint64_t id, int n); const RadBatch* step_next(); const RadBatch* step_next_locked(); - /* Whether the step just issued ends every request it carries (step_next_locked). */ + /* Whether the step just issued likely ends every request it carries; step_next_locked then + * issues nothing behind it. */ bool ends_every_request() const; void promote_next(); /* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire - * finished requests, feed the draft controller. */ - int commit(const StepResult& r); + * finished requests, feed the draft controller, and fill `r`'s report counts + * (n_prefill_done, n_finished). */ + int commit(StepResult& r); /* Ends the step for timing; call once per loop iteration that ran a step, after the drafter, * so the draft rounds are charged to the step (see the definition). Without it the counters * stay correct but there is no timing. */ @@ -564,6 +572,10 @@ private: std::vector running_; std::vector waiting_; std::vector completed_; + /* StepResult's counts for the step being committed: the ids whose prompt it completed, and the + * requests it ended. Reset at every commit. */ + std::vector last_prefill_ids_; + int step_finished_ = 0; /* Requests whose release waits on something that still refers to them (a deferred reap or a * deferred free). A count, so the sweeps cost nothing on the steps where there are none. */ @@ -588,6 +600,8 @@ private: * lives here). See add_locked. */ int64_t pool_tokens_ = -1; std::string pool_refusal_; + /* fail_prefilling()'s message; a sink keeps the pointer until the HTTP thread writes it. */ + std::string stream_why_; /* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so * an admission does not reach the allocator. */ diff --git a/core/server/adapters.h b/core/server/adapters.h index fc492cbb..32911b13 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -87,6 +87,11 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t; } + /* KV streaming's totals are not per group, so they pass through. */ + o.kv_resident_blocks = m.kv_resident_blocks; + o.kv_stream_misses = m.kv_stream_misses; + o.kv_stream_bytes_in = m.kv_stream_bytes_in; + /* vLLM's gpu_prefix_cache_hit_rate means attention caching. The linear-checkpoint hit * rate has a different granularity (spec §7.3) and is reported separately, not averaged * in. */ @@ -746,6 +751,53 @@ public: return rc; } + /* A decoded frame (a keyframe on the output canvas) through the processor's resize and + * patching, as a prepared file's would go. */ + int prepare_frame(const mm::Frame& f, std::shared_ptr* out, + std::string* why) override { + if (!accepts(MediaKind::Image)) { + if (why) *why = "this model's vision tower serves no pictures"; + return RAD_E_UNSUPPORTED; + } + return p_->image_from(f, out, why); + } + + int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + mm::Frame* out, std::string* why) override { + if (!p_ || !mm::decoder_available()) { + if (why) *why = "no picture decoder is available"; + return RAD_E_UNSUPPORTED; + } + return p_->encoder_image(bytes, n, ratio, max_side, out, why); + } + + int encoder_image_canvas(const uint8_t* bytes, size_t n, int32_t w, int32_t h, bool cover, + mm::Frame* out, std::string* why) override { + if (!p_ || !mm::decoder_available()) { + if (why) *why = "no picture decoder is available"; + return RAD_E_UNSUPPORTED; + } + return p_->encoder_image_canvas(bytes, n, w, h, cover, out, why); + } + + int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + int32_t max_frames, std::vector* out, std::string* why) override { + if (!p_ || !mm::decoder_available()) { + if (why) *why = "no video decoder is available"; + return RAD_E_UNSUPPORTED; + } + return p_->encoder_video(bytes, n, ratio, max_side, max_frames, out, why); + } + + int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why) override { + if (!p_ || !mm::decoder_available()) { + if (why) *why = "no audio decoder is available"; + return RAD_E_UNSUPPORTED; + } + return p_->encoder_audio(bytes, n, rate, max_samples, out, why); + } + int32_t audio_rate() const override { return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0; } diff --git a/core/server/admin.cpp b/core/server/admin.cpp index ee6e450a..85ad6ce1 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -399,6 +399,8 @@ json Server::capabilities() const { caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; caps["audio_generation"] = deps_.audio != nullptr; caps["video_generation"] = deps_.videos != nullptr; + /* What a video request may carry. */ + if (deps_.videos) video_caps(caps, deps_.videos); /* The efforts a chat request may send, probed from the template at startup; null when it * takes any word. "none" and "minimal" are this server's and turn thinking off. */ if (lim_.reasoning_efforts.empty()) { diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index e0d11802..9993c082 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -273,6 +273,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) { } } o["uptime_s"] = unix_now() - started_at_; + /* The process's start, unix seconds: with a request id, a key unique across restarts. */ + o["started_at"] = started_at_; /* 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); @@ -666,7 +668,7 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; } * narrow screens let the scroll chain to the document. `.body .hold` rather than `.hold`: the * base .hold rule comes later in this sheet and would win at equal specificity. */ .body .panel > .pbody, .body .hold { overscroll-behavior:auto; } - /* The history table is the card's scroller now, and it is the same trap on a phone. */ + /* The history table is the card's scroller, and the same trap on a phone. */ #hist .hlist { overscroll-behavior:auto; } } @@ -704,11 +706,8 @@ th + th, td + td { padding-left:14px; } .hold { scrollbar-width:thin; scrollbar-color:var(--edge) transparent; } -/* HISTORY UNDER THE LIVE TABLE. The requests card holds two tables: what is running now and what - has already finished. The live one is short by nature and stays put; only history scrolls, so - the card has one scrollbar, and the card is half again the stock height to buy history rows. - The age column is the only cell that changes on a poll, and it is rewritten in place rather - than redrawing the table -- see histRender. */ +/* The requests card: the live table, which stays put, over the history, which scrolls. The card + is half again the stock height to make room for history rows. */ #reqpanel { height:459px; } #reqpanel > .pbody { overflow:hidden; } #reqpanel .hold { flex:0 0 auto; height:auto; overflow:visible; } @@ -1996,28 +1995,17 @@ function renderRequests(list, poolTokens) { /* ---------------------------------------------------------------- history * - * A REQUEST LIVES IN /STATS ONLY WHILE IT EXISTS. Its finished row is gone from the payload within - * roughly 20 ms (a one-token reply) to half a second, so a reader looking at the card after the - * fact finds the number they wanted — the average tok/s and the time to first token of that - * request — nowhere on the page. This keeps every finished request the poll managed to see, per - * browser, and draws the last two hundred under the live table. + * A request is in /stats only while it exists: its finished row leaves the payload within about + * 20 ms (a one-token reply) to half a second. The history keeps every finished request a poll + * saw, per browser in localStorage, and shows the last HMAX under the live table. * - * CAPTURE IS BY SIGHTING: a request is recorded the moment its state is "done", or, for the usual - * case where the engine drops it before a poll lands on "done", at its last sighting once it is - * gone from the payload. What was never seen is COUNTED, not invented: the grey row says how many - * requests began and ended between two polls. - * - * AN ID HERE IS NOT THE ENGINE'S ID. The engine renumbers 1..N and starts over at 1 on every - * restart, so rows carry a unique key (k) — the engine id plus a running offset persisted in - * storage — and a separate history id (id) that starts at 0 and counts up. Clear sets that counter - * back to 0, which is the point of the button: a cleared table begins again at #0. - * - * Rows are per browser, in localStorage, shared by every dashboard tab: a save UNIONS with what is - * stored (two tabs each saw different requests), a row is deduplicated by k, and a clear is a - * timestamp every tab honours. */ -const HK = "radiance.history.v2"; /* rows */ + * A request is recorded when a poll sees it "done", or, usually, from its last sighting once it + * has left the payload. Requests that began and ended between two polls are counted in a grey + * row. Rows are keyed by the engine's start and request id, so every tab and reload keys a + * request alike; a save unions with what is stored, and a clear is a timestamp every tab + * honours. The history id shown starts at 0 again after a clear. */ +const HK = "radiance.history.v3"; /* rows */ const HKN = HK + ".next"; /* next history id: 0 after a clear */ -const HKO = HK + ".off"; /* engine-id offset, raised across engine restarts */ const HKC = HK + ".clear"; /* clear marker: rows older than this stay deleted */ const HMAX = 200; @@ -2026,7 +2014,6 @@ function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) {} } let hRows = []; /* oldest first, unique by k */ let hNext = 0; /* next history id; the clear button writes 0 here */ -let hOff = 0; /* engine id -> unique key offset */ let hTracked = new Map(); /* engine id -> { last, fin } */ let hSeen = new Set(), hBase = null, hBaseSeen = 0; let hDrawn = null; @@ -2038,48 +2025,37 @@ function histStored() { } function histMerge(lists) { const cleared = +lsGet(HKC) || 0, by = new Map(); - for (const rows of lists) for (const r of rows) - if (r && r.k != null && (r.at || 0) > cleared) { - const p = by.get(r.k); - if (!p || (r.at || 0) > (p.at || 0)) by.set(r.k, r); + for (const rows of lists) for (const h of rows) + if (h && h.k != null && (h.at || 0) > cleared) { + const p = by.get(h.k); + if (!p || (h.at || 0) > (p.at || 0)) by.set(h.k, h); } - return [...by.values()].sort((a, b) => a.k - b.k).slice(-HMAX); + return [...by.values()].sort((a, b) => a.at - b.at).slice(-HMAX); } /* The whole table, on load and on every poll: another tab's rows join this one's. */ function histLoad() { hRows = histMerge([histStored(), hRows]); let n = 0; - for (const r of hRows) n = Math.max(n, (r.id || 0) + 1); + for (const h of hRows) n = Math.max(n, (h.id || 0) + 1); hNext = Math.max(n, +lsGet(HKN) || 0); - hOff = Math.max(hOff, +lsGet(HKO) || 0); - for (const r of hRows) hOff = Math.max(hOff, r.k); } function histSave() { hRows = histMerge([hRows]); lsSet(HK, JSON.stringify(hRows)); lsSet(HKN, String(hNext)); - lsSet(HKO, String(hOff)); -} -/* A restart renumbers the engine's ids from 1. The offset keeps new rows from overwriting old - * ones with the same key. It is not reset by a clear: the clear renumbers HISTORY ids, not the - * engine's. */ -function histBump() { - for (const r of hRows) hOff = Math.max(hOff, r.k); - lsSet(HKO, String(hOff)); } -/* Prefill rate: the prompt tokens this request actually computed (the rest came out of the - * prefix cache) over its time to first token. A fully cached prompt did no prefill work: no - * number, rather than 0. */ +/* Prefill rate: the prompt tokens computed (not from the prefix cache) over the time to first + * token; none for a fully cached prompt. */ function histPrefill(r) { if (!finite(r.prompt) || !finite(r.ttft_s) || r.ttft_s <= 0) return null; const fresh = r.prompt - (r.cached || 0); return fresh > 0 ? fresh / r.ttft_s : null; } -function histFinish(r) { +function histFinish(r, run) { if (!r || !r.id) return; hRows.push({ - k: hOff + r.id, /* unique for the life of this browser */ + k: run + ":" + r.id, id: hNext++, /* 0 after a clear, then 1, 2, … */ prompt: finite(r.prompt) ? r.prompt : null, out: finite(r.output) ? r.output : null, @@ -2095,9 +2071,10 @@ function histFinish(r) { /* Returns the requests that finished unseen between two polls, for the grey row. */ function histIngest(s) { const total = s.total_requests || 0; + const run = s.started_at || 0; if (hBase === null) { hBase = total; hBaseSeen = hSeen.size; } else if (total < hBase) { /* a new engine run: its ids restart at 1 */ - hBase = total; hBaseSeen = 0; hSeen.clear(); hTracked.clear(); histBump(); + hBase = total; hBaseSeen = 0; hSeen.clear(); hTracked.clear(); } histLoad(); const live = new Set(); @@ -2107,23 +2084,23 @@ function histIngest(s) { let t = hTracked.get(r.id); if (!t) { t = {}; hTracked.set(r.id, t); } t.last = r; - if (r.state === "done" && !t.fin) { t.fin = true; histFinish(r); } + if (r.state === "done" && !t.fin) { t.fin = true; histFinish(r, run); } } /* Gone without a "done" sighting: finalise it from its last sighting, then forget it. */ for (const [id, t] of [...hTracked]) - if (!live.has(id)) { if (!t.fin) histFinish(t.last); hTracked.delete(id); } + if (!live.has(id)) { if (!t.fin) histFinish(t.last, run); hTracked.delete(id); } return Math.max(0, total - hBase - (hSeen.size - hBaseSeen)); } const HCOLS = [ - { h: "id", f: (r) => "#" + r.id }, - { h: "prompt", f: (r) => cnt3(r.prompt) }, - { h: "out", f: (r) => cnt3(r.out) }, - { h: "ctx", f: (r) => cnt3(r.ctx) }, - { h: "ttft", f: (r) => dur(r.ttft) }, - { h: "prefill tok/s", f: (r) => cnt3(r.pf) }, - { h: "tok/s", f: (r) => tps(r.tps) }, + { h: "id", f: (h) => "#" + h.id }, + { h: "prompt", f: (h) => cnt3(h.prompt) }, + { h: "out", f: (h) => cnt3(h.out) }, + { h: "ctx", f: (h) => cnt3(h.ctx) }, + { h: "ttft", f: (h) => dur(h.ttft) }, + { h: "prefill tok/s", f: (h) => cnt3(h.pf) }, + { h: "tok/s", f: (h) => tps(h.tps) }, { h: "age", f: null }, /* rewritten in place every poll */ ]; for (const c of HCOLS) $("hhead").appendChild(el("th", null, c.h)); @@ -2137,29 +2114,28 @@ function histRender(missed) { return label + " avg " + fmt(all) + (a20 != null ? " (20: " + fmt(a20) + ", 5: " + fmt(a5) + ")" : ""); }; - const tpsV = hRows.map((r) => r.tps).filter((v) => v != null); - const pfV = hRows.map((r) => r.pf).filter((v) => v != null); - const tfs = hRows.map((r) => r.ttft).filter((v) => v != null).sort((a, b) => a - b); + const tpsV = hRows.map((h) => h.tps).filter((v) => v != null); + const pfV = hRows.map((h) => h.pf).filter((v) => v != null); + const tfs = hRows.map((h) => h.ttft).filter((v) => v != null).sort((a, b) => a - b); const parts = [hRows.length + " done"]; if (tpsV.length) parts.push(group(tpsV, tps, "tok/s")); if (pfV.length) parts.push(group(pfV, cnt3, "prefill")); if (tfs.length) parts.push("ttft " + dur(tfs[Math.floor(tfs.length / 2)])); $("hsum").textContent = parts.join(" · "); - /* Newest first, and the DOM is rebuilt only when the SET of rows changes: a long request - * finishing late never shifts the rows being read, and the per-poll age update is a text write. */ + /* Newest first. The rows are rebuilt only when the set changes; a poll only rewrites the ages. */ const body = $("hbody"); - const shape = hRows.length + ":" + (hRows.length ? hRows[hRows.length - 1].k : 0) + ":" + missed; + const shape = hRows.length + ":" + (hRows.length ? hRows[hRows.length - 1].k : "") + ":" + missed; if (shape !== hDrawn) { hDrawn = shape; body.textContent = ""; const frag = document.createDocumentFragment(); for (let i = hRows.length - 1; i >= 0; i--) { - const r = hRows[i], tr = el("tr"); + const h = hRows[i], tr = el("tr"); for (const c of HCOLS) { const td = tr.appendChild(el("td", c.f === null ? "dim" : null)); - if (c.f) td.textContent = c.f(r); - else td.dataset.at = r.at; + if (c.f) td.textContent = c.f(h); + else td.dataset.at = h.at; } frag.appendChild(tr); } @@ -3601,9 +3577,8 @@ $("cvbox").addEventListener("change", async (e) => { } }); -/* THE POLL SPEEDS UP WHILE SOMETHING IS RUNNING, for the history: a finished request leaves - * /stats within a fraction of a second of its last token, so the idle 500 ms poll would miss most - * of them. 100 ms costs the server one small JSON read and buys the finished row. */ +/* The poll runs every 100 ms while a request is in flight, so the history sees most finished + * requests before they leave /stats, and every 500 ms otherwise. */ let pollTimer = null; function schedulePoll(ms) { clearTimeout(pollTimer); pollTimer = setTimeout(poll, ms); } async function poll() { diff --git a/core/server/iface.h b/core/server/iface.h index ca9cdd16..5e661b0b 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -60,6 +60,11 @@ struct SchedMetrics { * expert slab (`kv_bytes_carved` in bytes). The smallest over the paged groups, which share * one token axis; windowed groups are excluded, since their carve bounds lookback, not fit. */ int64_t kv_tokens_max = 0; + /* KV streaming: the rings' depth over every streamed group, and the resolve's cumulative misses + * and bytes copied in from the host mirrors. Zero when nothing streams. */ + int64_t kv_resident_blocks = 0; + int64_t kv_stream_misses = 0; + int64_t kv_stream_bytes_in = 0; double prefix_hit_rate = 0.0; /* 0..1 */ /* Cumulative prefix-cache evictions. They rise as reusable prefixes are dropped, while @@ -568,6 +573,46 @@ public: virtual int prepare(MediaKind k, const std::vector& bytes, const MediaOpts& opts, std::shared_ptr* out, std::string* why) = 0; + /* A frame the caller decoded, for the vision tower: a keyframe resized to the output canvas, + * so the tower sees the same pixels the video VAE is handed. Unsupported where the tower cannot + * read host-built frames. */ + virtual int prepare_frame(const mm::Frame& f, std::shared_ptr* out, + std::string* why) { + (void)f; (void)out; + if (why) *why = "this server cannot show a pre-decoded frame to the vision tower"; + return RAD_E_UNSUPPORTED; + } + + /* Media for a video generator's VAE encoders, as mm::Processor::encoder_image and the rest + * make them; unsupported without a processor. */ + virtual int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + mm::Frame* out, std::string* why) { + (void)bytes; (void)n; (void)ratio; (void)max_side; (void)out; + if (why) *why = "this server prepares no reference media for a video encoder"; + return RAD_E_UNSUPPORTED; + } + + virtual int encoder_image_canvas(const uint8_t* bytes, size_t n, int32_t w, int32_t h, + bool cover, mm::Frame* out, std::string* why) { + (void)bytes; (void)n; (void)w; (void)h; (void)cover; (void)out; + if (why) *why = "this server prepares no reference media for a video encoder"; + return RAD_E_UNSUPPORTED; + } + + virtual int encoder_video(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, + int32_t max_frames, std::vector* out, std::string* why) { + (void)bytes; (void)n; (void)ratio; (void)max_side; (void)max_frames; (void)out; + if (why) *why = "this server prepares no reference media for a video encoder"; + return RAD_E_UNSUPPORTED; + } + + virtual int encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why) { + (void)bytes; (void)n; (void)rate; (void)max_samples; (void)out; + if (why) *why = "this server prepares no reference media for an audio encoder"; + return RAD_E_UNSUPPORTED; + } + /* Audio in two halves, for a route that cuts a long recording into clips itself * (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most * `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most @@ -722,9 +767,16 @@ struct VideoGenInfo { int64_t sample_rate = 0, channels = 0; int64_t default_steps = 0, max_steps = 0, max_lanes = 1; bool fixed_steps = false; /* a trained schedule: max_steps grid points and no other */ + /* The schedule shifts a request that names none runs (RadVideoGenDecl). */ + double shift_video = 0.0, shift_audio = 0.0; /* 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; + /* Reference conditioning (RadVideoGenDecl): the reference pictures, videos and soundtracks a + * request may carry (a video's own soundtrack counts with the video), and the encoders' bounds + * the server fits media to; `max_enc_side` 0 means no video encoder, so no keyframes either. */ + int64_t max_ref_images = 0, max_ref_videos = 0, max_ref_audios = 0; + int64_t max_enc_frames = 0, max_enc_side = 0, max_enc_samples = 0, enc_ratio = 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 diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 0b000e62..8fc3226b 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -136,6 +136,7 @@ void Metrics::sample(const SchedMetrics& m) { g_kv_util_.set(m.kv_util); g_kv_max_tokens_.set((double)m.kv_tokens_max); g_kv_max_bytes_.set((double)m.kv_bytes_carved); + g_kv_resident_blocks_.set((double)m.kv_resident_blocks); g_prefix_hit_.set(m.prefix_hit_rate); g_prefill_tps_.set(m.prefill_tps); g_decode_tps_.set(m.decode_tps); @@ -200,6 +201,8 @@ void Metrics::sample(const SchedMetrics& m) { c_cut_resumed_below_.advance_to(m.hit_cut_resumed_below); c_restore_cuts_.advance_to(m.prefix_restore_cuts); c_cut_tokens_.advance_to(m.hit_cut_tokens); + c_kv_stream_misses_.advance_to((double)m.kv_stream_misses); + c_kv_stream_bytes_.advance_to((double)m.kv_stream_bytes_in); g_linear_hit_.set(m.linear_hit_rate); } @@ -281,6 +284,20 @@ std::string Metrics::render() const { w.gauge("radiance:kv_cache_max_bytes", "VRAM the KV cache holds with every block it lends the experts taken back, one card.", L, g_kv_max_bytes_.get()); + w.gauge("radiance:kv_resident_blocks", + "Blocks of every streamed KV group the device ring holds; 0 when no group streams.", + L, g_kv_resident_blocks_.get()); + w.counter("radiance:kv_stream_misses_total", + "Blocks copied into a streamed KV group's ring from the host mirror.", + L, c_kv_stream_misses_.get()); + /* Labelled by direction; the resolve only copies in. */ + w.help("radiance:kv_stream_bytes_total", + "Bytes a streamed KV group's resolve moved, by direction.", "counter"); + w.out += "radiance:kv_stream_bytes_total"; + w.out += L.substr(0, L.size() - 1); + w.out += ",dir=\"in\"} "; + w.out += num(c_kv_stream_bytes_.get()); + w.out += '\n'; w.gauge("vllm:gpu_prefix_cache_hit_rate", "GPU prefix cache block hit rate.", L, g_prefix_hit_.get()); diff --git a/core/server/metrics.h b/core/server/metrics.h index 5b6d11e0..f2dabcfd 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -111,7 +111,9 @@ private: std::string labels_; /* {model_name="...",engine="0"} */ Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_; - Gauge g_kv_max_tokens_, g_kv_max_bytes_; + Gauge g_kv_max_tokens_, g_kv_max_bytes_, g_kv_resident_blocks_; + /* KV streaming: blocks and bytes copied into the rings, cumulative. */ + Counter c_kv_stream_misses_, c_kv_stream_bytes_; Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_; /* The decode floor in seconds: the fastest and the most recent single-sequence window. 0 * until a window completes, and render() omits a 0. */ diff --git a/core/server/server.h b/core/server/server.h index aebb7dad..cccc7804 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -318,6 +318,8 @@ private: /* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning * efforts), shared by /server_info's `capabilities` and the model entry so they agree. */ json capabilities() const; + /* A video model's capabilities (videos.cpp). */ + static void video_caps(json& caps, const IVideoGen* gen); HttpResponse handle_reset_prefix_cache(const HttpRequest& req); /* ------------------------------------------------------------------ dashboard.cpp */ diff --git a/core/server/videos.cpp b/core/server/videos.cpp index e33182f2..76e090c6 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -15,6 +15,11 @@ * (`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. +* A model with the VAEs' encoders also takes keyframes, form file parts `first_frame` and + * `last_frame` (tasks i2va, l2va, fl2va), or reference media (task ref2va): `ref_image_N` (at + * most 9), `ref_video_N` (3) with a soundtrack `ref_video_audio_N` and `ref_audio_N` (3), N from 1 + * without gaps within each kind. The parts carry the bytes: `input_reference` (but for i2va on a + * model that starts from a picture) 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 @@ -53,10 +58,12 @@ #include #include #include +#include #include #include #include #include +#include namespace rad { namespace server { @@ -65,16 +72,25 @@ struct Server::VideoJob { std::string id, model, prompt, seconds, size; int64_t created_at = 0; uint64_t seed = 0; + int32_t sampler = 0; /* the request's RAD_SAMPLER_* */ + double shift_video = 0, shift_audio = 0; /* 0: the model's */ std::shared_ptr ticket; std::thread worker; /* Under Server::videos_m_ from here on. */ std::string status = "queued"; int progress = 0; + /* The steps done of the total (0 before the first), and the first one's steady-clock time in + * ns, which the per-step log line measures its rate from. */ + int steps_done = 0, steps_total = 0; + int64_t step_ns0 = 0; int64_t completed_at = 0, expires_at = 0; bool failed = false; std::string err_code, err_message; std::string mp4; std::vector first; /* the first frame, RGB, for the thumbnail */ + /* A job with reference media or keyframes: its task and its parts in conditioning order. */ + std::string task; + std::vector refs; /* Latent upscaling, as the generator resolved it: the factor, the evaluations after it and the * small size; refine 0 when the video is not upscaled. */ double upscale = 0.0; @@ -144,8 +160,110 @@ void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int6 *h = std::max(mult, (int64_t)std::nearbyint(H / mult) * mult); } +/* The most reference media of each kind a request carries, ComfyUI's ref2va workflow's; a model + * may take fewer. */ +constexpr int32_t kMaxRefImages = 9, kMaxRefVideos = 3, kMaxRefAudios = 3; + +/* A reference part's kind and number from its name; false for any other name. `ref_video_audio_` + * is tried before `ref_video_`, which it starts with. */ +bool parse_ref_name(const std::string& name, gen::VideoRefMedia::Kind* kind, int32_t* index) { + static const struct { const char* pfx; gen::VideoRefMedia::Kind kind; } kKinds[] = { + { "ref_image_", gen::VideoRefMedia::IMAGE }, + { "ref_video_audio_", gen::VideoRefMedia::VIDEO_AUDIO }, + { "ref_video_", gen::VideoRefMedia::VIDEO }, + { "ref_audio_", gen::VideoRefMedia::AUDIO }, + }; + for (const auto& k : kKinds) { + const size_t n = std::strlen(k.pfx); + if (name.compare(0, n, k.pfx) != 0 || name.size() == n) continue; + char* e = nullptr; + const long v = std::strtol(name.c_str() + n, &e, 10); + if (*e == '\0' && v >= 1 && v <= 99) { *kind = k.kind; *index = (int32_t)v; return true; } + } + return false; +} + +/* A ref2va request's parts, refused naming the part when one is empty, over its kind's count, + * numbered with a gap or twice, or a soundtrack with no video of its number. On return `refs` is + * sorted by (kind, number), the order of the conditioning. */ +int validate_refs(std::vector& refs, const VideoGenInfo& info, ApiError* err) { + if (refs.empty()) { + *err = err_bad("task", "ref2va takes at least one reference part: ref_image_N, " + "ref_video_N, ref_video_audio_N or ref_audio_N"); + return -1; + } + const struct { + const char* pfx; + gen::VideoRefMedia::Kind kind; + int32_t cap; + } kinds[] = { + { "ref_image", gen::VideoRefMedia::IMAGE, + std::min(kMaxRefImages, (int32_t)info.max_ref_images) }, + { "ref_video", gen::VideoRefMedia::VIDEO, + std::min(kMaxRefVideos, (int32_t)info.max_ref_videos) }, + { "ref_video_audio", gen::VideoRefMedia::VIDEO_AUDIO, + std::min(kMaxRefVideos, (int32_t)info.max_ref_videos) }, + { "ref_audio", gen::VideoRefMedia::AUDIO, + std::min(kMaxRefAudios, (int32_t)info.max_ref_audios) }, + }; + for (const auto& k : kinds) { + std::vector got(k.cap + 1, false); + int n = 0; + for (const gen::VideoRefMedia& m : refs) { + if (m.kind != k.kind) continue; + ++n; + if (m.data.empty()) + return *err = err_bad(m.name, "'" + m.name + "' carries an empty file"), -1; + if (m.index > k.cap) + return *err = err_bad(m.name, k.cap == 0 + ? "this model takes no parts named " + + std::string(k.pfx) + "_N" + : "this model takes at most " + + std::to_string(k.cap) + " parts named " + + std::string(k.pfx) + "_N"), -1; + if (got[m.index]) + return *err = err_bad(m.name, "two parts are numbered " + std::string(k.pfx) + + "_" + std::to_string(m.index)), -1; + got[m.index] = true; + } + for (int i = 1; i <= n; ++i) + if (!got[i]) + return *err = err_bad(std::string(k.pfx) + "_" + std::to_string(i), + "the " + std::string(k.pfx) + "_N parts must be numbered 1 " + "to " + std::to_string(n) + " without gaps or repeats"), -1; + } + for (const gen::VideoRefMedia& m : refs) { + if (m.kind != gen::VideoRefMedia::VIDEO_AUDIO) continue; + bool paired = false; + for (const gen::VideoRefMedia& v : refs) + paired = paired || (v.kind == gen::VideoRefMedia::VIDEO && v.index == m.index); + if (!paired) + return *err = err_bad(m.name, "'" + m.name + "' is the soundtrack of a reference " + "video; give ref_video_" + std::to_string(m.index) + + " with it"), -1; + } + std::stable_sort(refs.begin(), refs.end(), + [](const gen::VideoRefMedia& a, const gen::VideoRefMedia& b) { + return a.kind != b.kind ? a.kind < b.kind : a.index < b.index; + }); + return 0; +} + } /* namespace */ +/* A video model's capabilities on /v1/models and /server_info: the counts validate_refs applies, + * the samplers and the model's shifts. */ +void Server::video_caps(json& caps, const IVideoGen* gen) { + const VideoGenInfo& info = gen->info(); + caps["video_max_text"] = info.max_text; + caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images); + caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos); + caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios); + caps["video_samplers"] = json::array({ "euler", "res_multistep" }); + caps["video_shift"] = info.shift_video; + caps["video_audio_shift"] = info.shift_audio; +} + HttpResponse Server::handle_video_create(const HttpRequest& req) { if (!deps_.videos || !deps_.tok) return error_response(err_not_implemented( @@ -153,8 +271,14 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { req.peer); const VideoGenInfo& info = deps_.videos->info(); + const bool takes_refs = info.max_ref_images > 0 || info.max_ref_videos > 0 || + info.max_ref_audios > 0; /* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form, - * since it may carry a file). */ + * since it may carry a file). Reference media and keyframes are file parts, collected here and + * checked once the task is known. */ + std::vector refs; + /* The keyframes, `first_frame` and `last_frame`. */ + std::vector keys; json body = json::object(); std::vector ref_bytes; bool has_ref = false; @@ -165,9 +289,32 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { has_ref = true; continue; } - if (!p.filename.empty()) - return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"), - req.peer); + if (p.name == "first_frame" || p.name == "last_frame") { + if (p.filename.empty()) + return error_response(err_bad(p.name, "'" + p.name + "' must carry an image " + "file"), req.peer); + gen::VideoRefMedia m; + m.kind = p.name == "first_frame" ? gen::VideoRefMedia::FIRST_FRAME + : gen::VideoRefMedia::LAST_FRAME; + m.name = p.name; + m.filename = p.filename; + m.content_type = p.content_type; + m.data = p.data; + keys.push_back(std::move(m)); + continue; + } + if (!p.filename.empty()) { + gen::VideoRefMedia m; + if (!parse_ref_name(p.name, &m.kind, &m.index)) + return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a " + "file"), req.peer); + m.name = p.name; + m.filename = p.filename; + m.content_type = p.content_type; + m.data = p.data; + refs.push_back(std::move(m)); + continue; + } json v = p.data; if (p.name == "target" || p.name == "conditions" || ((p.name == "loras" || p.name == "lora") && !p.data.empty() && @@ -186,6 +333,7 @@ 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", + "sampler", "shift", "audio_shift", "first_frame_mode", "negative_prompt", "decoder", "loras", "lora", /* RadVideoGenBatch::guidance_h's order */ "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", @@ -243,19 +391,104 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { 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); - 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(err_unsupported("input_reference", takes_refs + ? "this server reads reference media as ref_image_N " + "file parts" + : "this model makes video from text only"), req.peer); + /* With `input_reference` the task is i2va. */ + if (has_ref && has(body, "task") && (!body["task"].is_string() || + body["task"].get() != "i2va")) { + ApiError e = err_unsupported("task", "a video from a picture is i2va"); + e.supported = { "i2va" }; return error_response(e, req.peer); } + /* Otherwise t2va, or what the model takes: ref2va with reference media, the keyframe tasks + * with a video encoder. */ + bool ref2va = false; + std::string kf_task; /* a keyframe task named */ + if (!has_ref && has(body, "task")) { + const std::string task = body["task"].is_string() ? body["task"].get() : ""; + if (task == "ref2va" && takes_refs) ref2va = true; + /* The parts say which frames there are; a named task is checked against them below. */ + else if (info.max_enc_side > 0 && (task == "i2va" || task == "l2va" || task == "fl2va")) + kf_task = task; + else if (task != "t2va") { + std::string what = "this server makes video from text"; + std::vector sup{ "t2va" }; + if (info.image_cond) { what += ", from a picture"; sup.push_back("i2va"); } + if (info.max_enc_side > 0) { + what += ", or between keyframes"; + for (const char* k : { "i2va", "l2va", "fl2va" }) + if (std::find(sup.begin(), sup.end(), std::string(k)) == sup.end()) + sup.push_back(k); + } + if (takes_refs) { what += ", from reference media"; sup.push_back("ref2va"); } + what += ": "; + for (size_t i = 0; i < sup.size(); ++i) what += (i ? ", " : "") + sup[i]; + ApiError e = err_unsupported("task", what); + e.supported = sup; + return error_response(e, req.peer); + } + } if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) - return error_response(err_unsupported("conditions", "this server makes video from text " - "only; conditions must be empty"), req.peer); + return error_response(err_unsupported("conditions", takes_refs + ? "reference media arrive as ref_* file parts; " + "conditions must be empty" + : "this server makes video from text only; " + "conditions must be empty"), req.peer); + /* Reference parts without task ref2va are a mistake about the task. */ + if (!refs.empty() && !ref2va) + return bad("task", "reference files are given: send them with task ref2va, or send " + "none"); + if (ref2va) { + ApiError e; + if (validate_refs(refs, info, &e) < 0) return error_response(e, req.peer); + } + /* At most one keyframe of each, not with reference media, and only with a video encoder. */ + { + int n_first = 0, n_last = 0; + for (const gen::VideoRefMedia& m : keys) + if (m.kind == gen::VideoRefMedia::FIRST_FRAME) ++n_first; else ++n_last; + if (n_first > 1) return bad("first_frame", "at most one first_frame part"); + if (n_last > 1) return bad("last_frame", "at most one last_frame part"); + /* A keyframe's counts the pictures present, as ComfyUI numbers them: a last + * frame alone is . */ + for (gen::VideoRefMedia& m : keys) + m.index = m.kind == gen::VideoRefMedia::LAST_FRAME && n_first ? 2 : 1; + if (!keys.empty()) { + if (info.max_enc_side <= 0) + return bad("first_frame", "this model has no video encoder, so it cannot pin a " + "keyframe"); + if (!refs.empty()) + return bad("first_frame", "a keyframe completion conditions on its pinned frames, " + "not on reference media: give first_frame/last_frame or " + "the ref_* parts, not both"); + } + /* A named keyframe task carries its frames. */ + if (!kf_task.empty()) { + if ((kf_task == "i2va" || kf_task == "fl2va") && n_first < 1) + return bad("first_frame", "task '" + kf_task + "' pins a first frame: give a " + "first_frame part"); + if ((kf_task == "l2va" || kf_task == "fl2va") && n_last < 1) + return bad("last_frame", "task '" + kf_task + "' pins a last frame: give a " + "last_frame part"); + } + } + /* How the first frame is fitted to the video: stretched, as ComfyUI does, or `center`, scaled + * to cover it and cropped. The last frame is always cropped, as ComfyUI does. */ + bool first_center = false; + if (has(body, "first_frame_mode")) { + const std::string fm = body["first_frame_mode"].is_string() + ? body["first_frame_mode"].get() : ""; + if (fm.empty() || fm == "stretch") + ; + else if (fm == "center") + first_center = true; + else + return bad("first_frame_mode", "expected \"stretch\" (the reference's own resize) " + "or \"center\" (keep the anchor's aspect, crop the " + "canvas)"); + } json target = json::object(); if (has(body, "target")) { if (!body["target"].is_object()) return bad("target", "expected an object"); @@ -384,6 +617,34 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { (unit + 1) + ")"); r->steps = (int32_t)v; } + if (has(body, "sampler")) { + const std::string sm = body["sampler"].is_string() ? body["sampler"].get() : ""; + if (sm.empty() || sm == "euler") r->sampler = RAD_SAMPLER_EULER; + else if (sm == "res_multistep") r->sampler = RAD_SAMPLER_RES_MULTISTEP; + else { + ApiError e = err_unsupported("sampler", "the sampler is euler (first order) or " + "res_multistep (second order on the clean " + "estimate)"); + e.supported = { "euler", "res_multistep" }; + return error_response(e, req.peer); + } + } + /* Each stream's schedule shift; any positive shift is safe, and (0, 100] refuses typos. */ + if (has(body, "shift")) { + double v = 0; + if (!number(body["shift"], &v) || !(v > 0.0) || v > 100.0) + return bad("shift", "the video schedule shift: a number in (0, 100], or omit it to run " + "the model's trained shift " + rad::fmt("%g", info.shift_video)); + r->shift_video = v; + } + if (has(body, "audio_shift")) { + double v = 0; + if (!number(body["audio_shift"], &v) || !(v > 0.0) || v > 100.0) + return bad("audio_shift", "the soundtrack schedule shift: a number in (0, 100], or " + "omit it to run the model's trained shift " + + rad::fmt("%g", info.shift_audio)); + r->shift_audio = v; + } /* ---- guidance */ static const char* kGuide[8] = { "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", @@ -442,25 +703,139 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { std::random_device rd; r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); } + r->refs = std::move(refs); + /* The keyframes after the references, the first before the last. */ + std::stable_sort(keys.begin(), keys.end(), [](const gen::VideoRefMedia& a, + const gen::VideoRefMedia& b) { + return a.kind < b.kind; + }); + r->refs.insert(r->refs.end(), keys.begin(), keys.end()); + const bool has_keys = !keys.empty(); - /* ---- the prompt: the template's text with special tokens, the prompt without */ + /* Pixels as the VAE encoders take them: RGB in 0..255, frame after frame. */ + auto pixels = [](gen::VideoRefMedia& m, const std::vector& fr) { + m.enc_frames = (int32_t)fr.size(); + m.enc_h = fr.front().h; + m.enc_w = fr.front().w; + m.enc_pixels.clear(); + for (const mm::Frame& f : fr) m.enc_pixels.insert(m.enc_pixels.end(), f.rgb.begin(), + f.rgb.end()); + }; + + /* A keyframe is decoded once, onto the output canvas, and that frame serves both the VAE pin + * and the vision tower, as in ComfyUI: the tower sees the pixels that are pinned, not the file + * at its own size. The first frame is stretched unless first_frame_mode=center, the last is + * centre-cropped. `canvas` parallels r->refs. */ + std::vector canvas; + if (has_keys && deps_.mm) { + canvas.resize(r->refs.size()); + for (size_t i = 0; i < r->refs.size(); ++i) { + gen::VideoRefMedia& m = r->refs[i]; + if (m.kind != gen::VideoRefMedia::FIRST_FRAME && + m.kind != gen::VideoRefMedia::LAST_FRAME) + continue; + std::string why; + if (deps_.mm->encoder_image_canvas((const uint8_t*)m.data.data(), m.data.size(), + (int32_t)W, (int32_t)H, + m.kind == gen::VideoRefMedia::LAST_FRAME || + first_center, + &canvas[i], &why) < 0) + return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why); + pixels(m, { canvas[i] }); + } + } + + /* ---- the prompt: the template's text with special tokens, the media in ComfyUI's order, the + * prompt without. A picture is its `: ` label, encoded on its own, then its + * tokens; a video its soundtrack's `