diff --git a/CMakeLists.txt b/CMakeLists.txt index 8b76ba4e..1eb31cdb 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.7.0 LANGUAGES C CXX) +project(radiance VERSION 1.8.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/Dockerfile b/Dockerfile index 5dc11a17..151fd6ba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,15 +51,17 @@ ARG JOBS= RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \ - libwebp-dev \ + libwebp-dev libopenh264-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /tmp # Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still # images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4, # AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name # (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image -# (png, jpeg as mjpeg, webp through libwebp). No protocols: media.cpp reads from memory through its -# own I/O context. +# (png, jpeg as mjpeg, webp through libwebp), and a generated video's MP4 (core/mm/mp4.cpp): H.264 +# through libopenh264 (BSD-licensed, so the build stays LGPL) and FFmpeg's own AAC, in the mp4 +# muxer. No protocols: media.cpp and mp4.cpp read and write memory through their own I/O +# contexts. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \ && echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \ @@ -70,7 +72,7 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ --enable-zlib --enable-libdav1d --enable-libwebp \ --enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \ --enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \ - --enable-encoder=png,mjpeg,libwebp \ + --enable-encoder=png,mjpeg,libwebp,libopenh264,aac --enable-muxer=mp4 --enable-libopenh264 \ --enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \ && make -j"${JOBS:-$(nproc)}" \ && make install \ @@ -136,11 +138,11 @@ ARG JOBS= # g++-14 rather than the default 13: hipcc compiles device-side translation units against its # libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which -# mawk lacks. libdav1d7 and libwebp7 are the runtime libraries of the ffmpeg stage's AV1 decoder -# and WebP encoder; busybox-static goes into the runtime image. +# mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's +# AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ - cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 busybox-static \ + cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg @@ -207,10 +209,11 @@ ARG JOBS= # ctest --test-dir /build -L gpu --output-on-failure # Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT # machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a -# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build sandbox forbids io_uring, so avx_check skips its -# file-backed gather case. The `oot` suite (every shipped plugin rebuilt against the installed -# package) repeats this stage's whole compile, so it runs from the development tree instead -# (tests/oot_plugins.sh). +# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build +# sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so +# the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The +# `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's +# whole compile, so it runs from the development tree instead (tests/oot_plugins.sh). RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ && ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \ diff --git a/NOTICE b/NOTICE index 7658c1db..0d450ed3 100644 --- a/NOTICE +++ b/NOTICE @@ -22,8 +22,8 @@ Written by Deadcode, with contributions from: request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl, - jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, and - --prefill-interleave + jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave, + and runtime LoRA adapters served beside the base model and picked per request - hazyumps: static YaRN for the Qwen rotary paths - malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit diff --git a/README.md b/README.md index f9853aeb..8f6744c5 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # radiance -An LLM and image-generation inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks -OpenAI's chat, completions, Responses and images APIs, Anthropic's Messages API and llama-server's -native one, so their clients and SDKs work unchanged. Model architectures, kernel libraries and -quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third -party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). +An inference server for AMD GPUs, in C++ and HIP: language models, and image, video, speech and +music generation. Its HTTP API speaks OpenAI's chat, completions, Responses, images, audio and video +APIs, Anthropic's Messages API and llama-server's native one, so their clients and SDKs work +unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this +tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). The bundled device kernels (`libr4d`) target AMD RDNA4 (`gfx1200`, `gfx1201`). The serve flags below are for two 32 GB cards (Radeon AI PRO R9700). The engine starts on any AMD GPU family; @@ -28,6 +28,10 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | +| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` | +| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` | +| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | +| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | @@ -63,6 +67,19 @@ On two R9700s a 2048x2048 picture takes 61 s at the base model's 40 steps and 13 12 s with `--tp-wire wht6`); 1024x1024 takes 6 s and 2.6 s. Qwen-Image 2.1 is under Qwen's research license, which is non-commercial. +The MiniMax-H3 containers serve OpenAI's video jobs (`/v1/videos`): a video with its stereo +soundtrack from a prompt, 5 to 14 s, up to 1344x768. On two R9700s a 5.17 s clip at 1344x768 takes +about 68 s with FastH3 and 8.8 minutes at MiniMax-H3's 50 steps; both read about 39 GiB of pinned +host memory. MiniMax-H3's license, which FastH3 carries, does not cover the EU, the UK, the Republic +of Korea or the USA. + +MiniMax-Music3 and Breeze-TTS-2 answer `/v1/audio/speech`, whole or streamed as they are made: a song +from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays on two cards; and +speech in a voice the request describes, made in 0.6 of its playing time on one card, its first +streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written, +over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use +only. + ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The @@ -141,6 +158,9 @@ four-rank rows have no compose file. The other models' flags are in their compos | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | | Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` | | Qwen-Image 2.1 and 2.1 Turbo | `--tp 2 --tp-wire wht6` | +| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` | +| MiniMax-Music3 | `--tp 2` | +| Breeze-TTS-2 | `--tp 1` | Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference) and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of @@ -204,15 +224,20 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.ra build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \ --draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2 +build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \ + --recipe data/recipes/q38-27b-w4a16.recipe ``` With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In the image the recipes are in `/opt/radiance/share/radiance/recipes/`. A checkpoint served at its own precision needs no container: `radiance --model /srv/models/hf/Qwen/Qwen3.8-27B-FP8`. A release someone else quantised is read as it ships when the engine serves its form (block-scaled FP8, -Quark's MXFP4) and converted from its exact dequantisation when it does not: compressed-tensors' -NVFP4 to the MXFP4 kernels, AutoRound and GPTQ int4 to int8. [docs/GUIDE.md](docs/GUIDE.md) names -the recipes of record with their `rad-convert` commands. +Quark's MXFP4), written at its own numbers when the kernels read them in another spelling (an int4 +W4A16 release, compressed-tensors' AWQ and GPTQ or AutoRound's, on the 4-bit GEMMs with +`data/recipes/q38-27b-w4a16.recipe`), and converted from its exact dequantisation when no kernel +reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels, an AutoRound +Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record +with their `rad-convert` commands. ## Test diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 6e966fc0..115f52c7 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 18u +#define RAD_ABI_VERSION 21u /* ================================================================== 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 2b1477af..a57fe122 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -395,7 +395,8 @@ int rad_op_declared(RadBuilder* b, const char* op); /* The plugin owns the map from checkpoint tensor names to declared weight names, including * convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component * that knows both sides, and rad-convert reads the map from it (spec §2.4). */ -enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1 }; +enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3, + RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5 }; typedef struct RadNameMap { const char* declared; /* the name given to rad_decl_weight */ @@ -409,12 +410,37 @@ typedef struct RadNameMap { * declared weight per expert; this carries the expert index so rad-convert need not parse it * out of the declared name. */ int src_index[8]; + + /* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or + * higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. */ + int64_t src_rows[8]; } RadNameMap; /* RAD_MAP_COPY with n_src > 1: the first source present in the container wins. This expresses a * tied lm_head (output.weight if present, else token_embd.weight), so one plugin covers family * members that differ only in tying. RAD_MAP_CONCAT with n_src > 1 concatenates all sources along - * concat_dim and requires every one. */ + * concat_dim and requires every one. + * + * RAD_MAP_WNORM folds a weight-normalised tensor (torch.nn.utils.weight_norm) into the plain + * weight it stands for: src[0] is the magnitude `weight_g` ([d0, 1, ...]), src[1] the direction + * `weight_v` ([d0, ...]), and the result is g * v / ||v||, the norm taken over every dimension but + * the first. Folded in f32 and stored as the recipe says. A model that applies the + * parametrisation at every forward computes the same weight each time; doing it once at convert + * leaves the plugin an ordinary weight. + * + * RAD_MAP_ROWS keeps only row ranges of its sources (see src_rows), joined: a head read over a + * fraction of a vocabulary (an audio model's codes, a few rows of a text model's 200K) stores that + * fraction rather than the whole table. + * + * RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to + * [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in). + * + * RAD_MAP_EMA is an exponential-moving-average codebook as EnCodec-style quantisers keep it: src[0] + * the embedding sums [bins, ...], src[1] the cluster usage [bins], and the codebook is each row + * divided by max(usage, 1e-5), in f32. Successive EMA maps for one name stack their codebooks + * along dim 0, as CONCAT maps extend (a residual quantiser's codebooks as one table). + * + * TRANSPOSE and EMA are computed at convert in f32, like WNORM, and stored as the recipe says. */ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); @@ -580,7 +606,7 @@ int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d); * against its conditioning's KV. * RAD_GEN_PASS_DECODE one image's latent to pixels, in `image_out`, which the core reads back. * - * A program declares exactly one of this, logits or pooled vectors. + * A program declares exactly one of this, the other generators, logits or pooled vectors. * * The fields are the model's contract with a client: the prompt it was trained on, the sizes it * makes, its sampler's schedule. The core turns a request into passes from them without naming @@ -662,6 +688,202 @@ typedef struct RadGeneratorDecl { int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d); +/* ================================================================== the audio generator */ +/* A program that makes audio from text: an autoregressive language model writes the piece frame by + * frame, with classifier-free guidance (each request runs a conditional and an unconditional + * branch in step), and either a denoiser turns the frames' hidden states into audio latents window + * by window, which a vocoder turns into samples, or (`voc_chunk` > 0) a vocoder plays the frames + * themselves a few at a time as they are made. The core drives the passes (RadBatch::gen, + * RadAudioGenBatch): + * + * RAD_GEN_PASS_PROMPT the prompt of one or more requests, both branches, as an ordinary causal + * prefill into the KV group: two sequences a request, the conditional one + * first. A long prompt takes several passes, each a chunk of both branches, + * unless the declaration asks for whole prompts (`prompt_whole`). The pass + * that ends a prompt leaves the branches' last hidden states in the + * request's lane. + * RAD_GEN_PASS_FRAME one frame of every request in its autoregressive stage: the plugin samples + * the frame from the lane's last hidden states, keeps what the denoiser + * conditions on, and runs the language model over the frame's embedding + * (one row a branch, appended to that branch's KV). It writes `status` for + * each lane: >= 0 a frame was made, -1 the model ended the piece instead. + * RAD_GEN_PASS_WINDOW one denoising step of one or more windows, each a run of a request's frames + * (two entries a window with guidance, conditional and unconditional). + * RAD_GEN_PASS_VOCODE one finished window's latents to samples, in `audio_out`, which the core + * reads back; with `voc_chunk`, the frames [voc_frame0, voc_frame0 + + * voc_latents) of one lane, of which the first `voc_left` are context and + * only the rest are played. + * + * Windows overlap: window k covers frames [k win_hop, k win_hop + win_frames) and is stepped once + * the language model has made all of them, or ended. A window joins its predecessor through the + * latents they share, so a request's windows run in order, and window k + 1 does not start before + * window k is vocoded. The last window ends at the last frame; there is a window k >= 1 only while + * frames remain past k win_hop + (win_frames - win_hop), so no window is all overlap. + * + * A program declares exactly one of this, the other generators, logits or pooled vectors. */ +enum { RAD_GEN_PASS_PROMPT = 4, RAD_GEN_PASS_FRAME = 5, RAD_GEN_PASS_WINDOW = 6, + RAD_GEN_PASS_VOCODE = 7 }; + +typedef struct RadAudioGenDecl { + const char* name; /* "minimax-music3" -- the served model id and messages */ + + /* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's + * instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the + * words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports + * one. Special tokens are spelled as text. */ + const char* tmpl; + /* The unconditional branch is the conditional prompt with every token but the first + * `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches + * are the same length and step together. */ + int32_t neg_token; + int32_t neg_keep_head, neg_keep_tail; + /* The longest prompt in tokens, and the most frames a request makes. */ + int64_t max_prompt; + int64_t max_frames; + /* frame_rate_num / frame_rate_den frames a second. */ + int64_t frame_rate_num, frame_rate_den; + + /* Windows: `win_frames` frames, a new one every `win_hop`. A window of n frames has + * floor(n * lat_num / lat_den) latents of `latent_channels`, and each latent is + * `samples_per_latent` samples of `channels` channels at `sample_rate`. Where two windows meet, + * the earlier one's last `win_crop_right` latents and the later one's first `win_crop_left` are + * not played; the first window keeps its start and the last its end. */ + int64_t win_frames, win_hop; + /* Rows the denoiser puts ahead of a window's latents in each entry of a WINDOW pass (a + * timestep token); the core counts them into the pass's rows. */ + int64_t win_lead; + int64_t lat_num, lat_den; + int64_t latent_channels; + int64_t win_crop_left, win_crop_right; + int64_t samples_per_latent; + int64_t sample_rate; + int64_t channels; + + /* The denoiser's sampler: `default_steps` Euler steps of flow matching from t = 0 (noise) to + * t = 1 (data), t_i = i / steps; guidance `default_cfg` (1 is off), v = u + cfg (c - u). */ + int64_t default_steps; + double default_cfg; + + /* `max_lanes` requests may be in flight at once, each in a lane of the plugin's state. + * `status` is [>= max_lanes] i32 on the device, indexed by lane (see FRAME above); `audio_out` + * is [>= the samples of the longest window, channels] f32 on the device, interleaved, in + * [-1, 1]: what a VOCODE pass plays, its crops already applied. */ + int64_t max_lanes; + rad_buf status; + rad_buf audio_out; + + /* The prompt of a request without instructions, `{input}` its only slot; NULL makes the + * instructions required. */ + const char* tmpl_plain; + /* The unconditional branch's own template, rendered from the request's texts as `tmpl` is; + * NULL derives it from the conditional prompt by `neg_token` as above. With it the branches + * may differ in length, and a request whose guidance is 1 runs the conditional prompt in both + * (the guided logits are then the conditional ones). */ + const char* neg_tmpl; + /* Nonzero: a prompt is never split across PROMPT passes (an encoder that reads it at once); + * the pass rows must hold both branches of the longest. Required with `neg_tmpl`. */ + int32_t prompt_whole; + /* The first frame a request keeps: frames before it only move the model past the prompt. */ + int32_t first_frame; + /* Nonzero: no denoiser and no windows. The vocoder plays the kept frames as they are made, at + * most `voc_chunk` a VOCODE pass, reading `voc_context` frames before them again (and not + * playing them) so that a causal vocoder needs no state between passes. A frame is then one + * latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */ + int64_t voc_chunk; + int64_t voc_context; +} RadAudioGenDecl; + +int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); + +/* ================================================================== the video generator */ +/* A program that makes a video and its soundtrack from text: a text encoder reads the prompt, one + * denoiser steps a packed sequence holding the prompt's rows, the soundtrack's latents and the + * video's latents together (flow matching, one forward a step, no guidance), and two decoders turn + * the latents into frames and samples. The core drives the passes (RadBatch::gen, + * RadVideoGenBatch), one request a pass: + * + * RAD_GEN_PASS_VCOND the request's prompt, an ordinary non-paged pass over its tokens: the + * text encoder, and what the denoiser reads of the prompt at every step, + * into the request's lane. It carries the request's whole schedule, so + * what depends only on a step's timesteps can be computed once here. + * RAD_GEN_PASS_VSTEP one denoising step of one lane over the packed sequence + * [text | audio | video]: the prompt's rows, then the soundtrack's + * `audio_channels` blocks of latents (channel-major, one row a latent), + * then the video's patches (frame-major, then row-major). The first step + * draws the lane's noise. + * RAD_GEN_PASS_ADECODE the lane's soundtrack to samples in `audio_out`, which the core reads + * back. Runs once, after the last step. + * RAD_GEN_PASS_VDECODE one chunk of the lane's video latents to frames in `frames_out`, which + * the core reads back. Chunks run in order after the soundtrack; each joins + * its predecessor through state the plugin keeps in the lane. + * + * Geometry. A video of n chunks has `frames_per_chunk n + frames_tail` frames at + * `fps_num / fps_den` a second and `latents_per_chunk n + latents_tail` latent frames, each of + * (height / latent_scale) x (width / latent_scale) latents of `latent_channels`; the denoiser + * reads them in `patch` x `patch` patches. Chunk c of n is `frames_per_chunk` frames, the last + * `frames_per_chunk + frames_tail`. A side is a multiple of `size_multiple` pixels, at least + * `min_side`, the area at most `max_area`, and the long side over the short at most `max_aspect`. + * The soundtrack has round(frames / fps * audio_rate) latents a channel, each + * `sample_rate / audio_rate` samples. + * + * The rotary positions of a pass's rows are the plugin's (rad_arch_video_positions), which a video + * generator must export. + * + * The sampler: a request's `steps` are sigma grid points, the terminal 0 included, as diffusers' + * MiniMax-H3 counts them: sigma_i = shift s / (1 + (shift - 1) s) over s = linspace(1, 0, steps) + * in f32 (consecutive duplicates dropped), and a model evaluation at each timestep + * t_i = 1 - sigma_i but the last; one schedule for the video (`shift_video`) and one for the + * soundtrack (`shift_audio`), stepped together. A few-step (distilled) checkpoint instead declares + * the base times it was trained on (`rungs`, below): s = rungs then 0, each taken to f32, the same + * shifts applied, and the step count fixed at n_rungs + 1. + * + * A program declares exactly one of this, the other generators, logits or pooled vectors. */ +enum { RAD_GEN_PASS_VCOND = 8, RAD_GEN_PASS_VSTEP = 9, RAD_GEN_PASS_ADECODE = 10, + RAD_GEN_PASS_VDECODE = 11 }; + +typedef struct RadVideoGenDecl { + const char* name; /* "minimax-h3" -- the served model id and messages */ + + /* The prompt as text the core tokenises, `{prompt}` replaced by the request's; special tokens + * are spelled as text. No beginning-of-sequence token is added. */ + const char* tmpl; + int64_t max_text; /* the longest prompt, in tokens */ + + /* Geometry (above). */ + int64_t fps_num, fps_den; + int64_t frames_per_chunk, frames_tail; + int64_t latents_per_chunk, latents_tail, dec_latents; + int64_t min_chunks, max_chunks; + int64_t latent_scale, latent_channels, patch; + int64_t size_multiple, min_side, max_area, max_aspect; + /* The size and length a request that names none is made at. */ + int64_t default_width, default_height, default_chunks; + + /* The soundtrack. */ + int64_t sample_rate, audio_rate, audio_channels, audio_latent_channels; + + /* The sampler (above). */ + int64_t default_steps, max_steps; + double shift_video, shift_audio; + + /* `max_lanes` requests may hold state at once. `frames_out` is [>= the frames of the largest + * chunk, height, width, 3] u8 on the device, the frames a VDECODE pass made, row-major RGB; + * `audio_out` is [>= the samples of the longest soundtrack, audio_channels] f32, interleaved, + * what an ADECODE pass made. */ + int64_t max_lanes; + rad_buf frames_out; + rad_buf audio_out; + + /* A trained schedule when `n_rungs` > 0: base times strictly decreasing in (0, 1] (a + * trainer's timesteps over its 1000-step clock), each modality's sigmas their shifts as above. + * `default_steps` and `max_steps` are then both n_rungs + 1 and a request may not name another + * count. 0 is the linspace schedule. */ + int32_t n_rungs; + const double* rungs; +} RadVideoGenDecl; + +int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); + /* ================================================================== diagnostics */ /* A plugin may annotate the graph dump. Free-form, printed under --debug-graph. */ void rad_note(RadBuilder* b, const char* fmt, ...); @@ -721,15 +943,26 @@ typedef struct RadArchProbe { * the engine sizes the audio pass with it (RadBuildCtx::max_audio_frames). 0 is no audio. */ int64_t audio_frames; - /* Nonzero for an image generator (rad_declare_generator): the rows its largest pass carries. - * The engine sizes the step for it before declare (a denoise pass carries all of an image's - * latent rows at once, twice with guidance) and turns off what a generator does not use. 0 is - * a program that generates text or embeds. */ + /* Nonzero for a generator (rad_declare_generator, rad_declare_audio_generator): the rows its + * largest pass carries. The engine sizes the step for it before declare (an image's denoise + * pass carries all of its latent rows at once, twice with guidance; an audio window's step all + * of the window's) and turns off what a generator does not use. 0 is a program that + * generates text or embeds. */ int64_t gen_rows; /* The most patches the generator's conditioning pass encodes: every reference picture a * request may carry, at the model's resize target. This is the encoder's pass size * (max_enc_patches). */ int64_t gen_patches; + /* Nonzero for an audio generator, which the engine sizes before declare as it does an image + * generator, with these differences: two sequences a request (its branches), and `gen_ctx` + * the longest a sequence grows (the whole prompt and every frame), which is the context the + * KV group is sized for. */ + int32_t gen_audio; + int64_t gen_ctx; + /* Nonzero for a video generator, which the engine sizes as it does an image generator from + * `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It + * keeps no KV. */ + int32_t gen_video; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); @@ -900,6 +1133,35 @@ typedef struct RadAudioFormat { /* Return the format, or NULL when this model serves no speech route. Called once at startup. */ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta); +/* A request's free text rewritten into the form the model was trained on, before it goes into the + * audio generator's prompt template (RadAudioGenDecl::tmpl). Optional: absent, the text goes in + * as given. Training data has conventions a client does not know -- section tags on lines of + * their own and lower case, no markdown in a description -- and only the plugin knows them. + * + * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included, + * and returns the length the whole result needs without its NUL (call again with more room when + * it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so + * it keeps no state. */ +enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 }; +int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap); + +/* The layout of a video generator's passes (rad_declare_video_generator), which only the model + * knows. `which` names the pass: RAD_VPOS_STEP, the packed sequence of every VSTEP pass of a + * request of geometry `g` -- its rows, and their rotary positions written to `pos` (f32 [3, rows] + * component-major) when it is non-null and `cap` rows hold them; RAD_VPOS_DECODE, the rows of one + * of its VDECODE passes, whose positions the plugin makes itself (`pos` is not written). Returns + * the rows, or a negative status for a geometry the model cannot take. Called on any thread, so it + * keeps no state. Required of a video generator. */ +typedef struct RadVideoGeom { + int32_t n_text; /* the prompt's tokens */ + int32_t frames; /* the video's frames */ + int32_t lat_frames; /* its latent frames */ + int32_t lat_h, lat_w; /* latents a frame, down and across */ + int32_t n_audio; /* the soundtrack's latents a channel */ +} RadVideoGeom; +enum { RAD_VPOS_STEP = 1, RAD_VPOS_DECODE = 2 }; +int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap); + int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx); /* Forward declaration; the signature is in rad_runtime.h. */ struct RadCtx; diff --git a/abi/rad_philox.h b/abi/rad_philox.h index 57808ab7..eb8a92f0 100644 --- a/abi/rad_philox.h +++ b/abi/rad_philox.h @@ -46,4 +46,30 @@ RAD_PHILOX_HD float rad_philox_normal(uint64_t seed, uint64_t e) { return (j & 1) ? r * sinf(t) : r * cosf(t); } +/* Element `e` of the standard-normal stream (seed, stream): the counter's upper half is `stream`, + * so stream 0 is rad_philox_normal and each other value an independent stream of the same seed + * (an audio window's noise is stream 1 + its index). */ +RAD_PHILOX_HD float rad_philox_normal_s(uint64_t seed, uint64_t stream, uint64_t e) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + const int j = (int)(e & 3u); + const uint32_t wa = c[(j >> 1) * 2], wb = c[(j >> 1) * 2 + 1]; + const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float r = sqrtf(-2.0f * logf(ua)); + const float t = 6.28318530717958647692f * ub; + return (j & 1) ? r * sinf(t) : r * cosf(t); +} + +/* Element `e` of the uniform stream (seed, stream), in (0, 1): word e % 4 of the counter + * (e / 4, stream) made uniform as the normal stream's words are. A sampler draws its pick from + * it. */ +RAD_PHILOX_HD float rad_philox_uniform_s(uint64_t seed, uint64_t stream, uint64_t e) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, (uint32_t)(stream >> 32) }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + return ((float)(c[e & 3u] >> 8) + 0.5f) * (1.0f / 16777216.0f); +} + #endif /* RAD_PHILOX_H */ diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index cea5e989..ff3c20d8 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -55,10 +55,11 @@ typedef struct RadBatch { * row of a sequence carries its request's slot, fixed when the request was admitted, so a step * that mixes adapters and the base needs nothing else. * - * Null when the engine serves no adapters (no --lora and no --max-loras). The core issues the - * adapter ops itself and reads it there; a block with an adapter epilogue of its own reads it - * too. Like every array above it sits at one address per rank for the engine's life and is - * rewritten every step, so a recorded pass replays it. */ + * Null on a step with no adapter row, so always when the engine serves no adapters (no --lora + * and no --max-loras). The core issues the adapter ops itself, only when this is set; a block + * with an adapter epilogue of its own reads it too. Like every array above it sits at one + * address per rank for the engine's life and is rewritten every step, so a recorded pass + * replays it. */ const int32_t* lora_slot; /* The tokens the sampler wants logits for: indices into this step's tokens, [n_out]. @@ -230,6 +231,18 @@ typedef struct RadBatch { * every step of a program that declared no generator. */ int32_t gen; const struct RadGenBatch* gen_b; + + /* ================================================ audio generation */ + + /* An audio generator's pass (rad_declare_audio_generator; `gen` is one of its + * RAD_GEN_PASS_*): its payload. Null on every other step. */ + const struct RadAudioGenBatch* agen_b; + + /* ================================================ video generation */ + + /* A video generator's pass (rad_declare_video_generator; `gen` is one of its + * RAD_GEN_PASS_*): its payload. Null on every other step. */ + const struct RadVideoGenBatch* vgen_b; } RadBatch; /* What a generator pass carries beside the step batch's own fields, which keep their meanings: @@ -312,6 +325,155 @@ enum { RAD_GEN_F_PREVIEW = 4 /* write the step's estimate of the clean latent to the lane's preview */ }; +/* What an audio generator's pass carries beside the step batch's own fields (rad_builder.h, + * RadAudioGenDecl, describes the passes): + * + * PROMPT an ordinary causal prefill: `token_ids`, `positions`, `cu_seqlens` and the KV group's + * slot mapping, block table and seqused, two sequences a lane (2i conditional, 2i + 1 + * unconditional). A chunk of a longer prompt is the same with positions that start + * past zero. + * FRAME one row a sequence, two sequences a lane, ordered as PROMPT's: the frame's embedding + * is the plugin's (it samples the frame first), so `token_ids` are zero; `positions`, + * the slot mapping and seqused place the row after its sequence's earlier ones. + * WINDOW one entry per (window, branch): `cu_seqlens` bounds each entry's rows, `win_lead` + * rows of the plugin's own (RadAudioGenDecl::win_lead) and then the window's latent + * rows; positions count from 0 in each entry. + * VOCODE one window, no rows. + * + * Every pointer is device memory unless the name ends in _h. */ +typedef struct RadAudioGenBatch { + /* ---- PROMPT and FRAME: the lanes of the pass's requests, in entry order */ + int64_t n_lane; + const int32_t* lane; /* [n_lane] */ + const int32_t* lane_h; + /* PROMPT: 1 where this pass holds the end of the lane's prompt, so the last rows' hidden + * states are the ones the first frame is sampled from. [n_lane] */ + const int32_t* last; + const int32_t* last_h; + /* FRAME: the frame each lane makes, from 0; frames before RadAudioGenDecl::first_frame only + * move the model past the prompt. [n_lane] */ + const int32_t* frame; + const int32_t* frame_h; + /* PROMPT, FRAME and WINDOW: each lane's (WINDOW: each entry's) request seed, [n, 2] low word + * first. */ + const uint32_t* seed; + /* PROMPT and FRAME, one value per entry ([n_seq]): the entry's row in a state of two rows a + * lane, 2 lane + branch, and the entry's last row in the pass (a prompt chunk's, or a frame's + * one row). */ + const int32_t* slot; + const int32_t* last_row; + /* PROMPT: each entry's rows already in the KV before this pass ([n_seq]), the prefix a chunk's + * rows attend to beside their own. */ + const int32_t* prefix; + + /* ---- WINDOW, one value per entry ([n_seq]) */ + const float* t; /* where the entry's latent is, in [0, 1) */ + const float* t_next; /* where this step takes it */ + const float* cfg; /* v = u + cfg (c - u); 1 without a pair. FRAME: each lane's + * guidance, [n_lane] */ + /* The entry holding this window's unconditional branch, or -1 for none; -2 marks an entry + * that is one, whose rows serve another entry's step and which does not move its lane. */ + const int32_t* pair; + const int32_t* win_lane; /* the lane the window's request runs in */ + const int32_t* win_lane_h; + /* RAD_AGEN_F_*, device and host. */ + const int32_t* flags; + const int32_t* flags_h; + /* The window: its index in the request, its first frame and its frames, host and device. */ + const int32_t* win_index; + const int32_t* win_index_h; + const int32_t* win_frame0; + const int32_t* win_frame0_h; + const int32_t* win_frames; + const int32_t* win_frames_h; + /* The latent rows apart from the lead rows: [n_seq + 1] offsets over them, and for each the + * row of the pass it is (`lat_rows` of them). */ + int64_t lat_rows; + const int32_t* lat_cu; + const int32_t* lat_cu_h; + const int32_t* lat_src; + + /* ---- VOCODE */ + int32_t voc_lane; + int32_t voc_window; + int32_t voc_latents; /* the window's latents */ + int32_t voc_left; /* latents at its start not played */ + int32_t voc_right; /* latents at its end not played */ + + /* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted + * from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */ + int64_t voc_frame0; +} RadAudioGenBatch; + +/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear + * of RAD_GEN_F_*'s, so one flags array serves the image generator's sampler ops as well. */ +enum { + RAD_AGEN_F_FIRST = 1, /* the window's first step: its latent is the noise its seed draws and + * its conditioning is built from the request's frames */ + RAD_AGEN_F_LAST = 8, /* the window's last step: after it the latent is final */ + RAD_AGEN_F_JOIN = 16 /* the window has a predecessor whose end it overlaps */ +}; + +/* What a video generator's pass carries beside the step batch's own fields (rad_builder.h, + * RadVideoGenDecl, describes the passes). Every pass is one request's, in lane `lane`: + * + * VCOND `token_ids`, `positions` and `cu_seqlens` are the prompt, one sequence of `n_tok` + * rows, attended causally, nothing paged. + * VSTEP `n_tok` rows: the packed sequence, n_text + audio_channels n_audio + the video's + * patches. No token ids. + * ADECODE no rows of the pass's own. + * VDECODE `dec_rows` rows of the decoder's own (rad_arch_video_positions, RAD_VPOS_DECODE). + * + * Every pointer is device memory unless the name ends in _h. */ +typedef struct RadVideoGenBatch { + int32_t lane; + RadVideoGeom geom; /* the request's geometry */ + /* The geometry again for ops that read it from an operand, i32 [RAD_VGEOM_N] (below). */ + const int32_t* geom_d; + /* The same lane, i32 [1], and 1 on a request's first step (0 otherwise), i32 [1]. */ + const int32_t* lane_d; + const int32_t* first_d; + /* i32 [4]: the packed sequence's segments, {0, n_text, n_text + audio rows, n_tok} -- text, + * soundtrack, video -- and i32 [4] {0, video rows, 0, audio rows}, the bounds of the lane's two + * latents counted from each one's first row. */ + const int32_t* seg_cu; + const int32_t* lat_cu; + + /* ---- VCOND: every step the request takes, the video's timestep and the soundtrack's */ + int32_t n_steps; + const float* t_video; /* [n_steps] */ + const float* t_audio; /* [n_steps] */ + + /* ---- VSTEP */ + int32_t step; /* from 0; the first draws the lane's noise */ + /* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */ + const float* sched; + const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */ + /* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first. */ + const uint32_t* seed; + + /* ---- VDECODE */ + int32_t chunk; /* from 0, of n_chunks */ + int32_t n_chunks; + int64_t dec_rows; /* RAD_VPOS_DECODE */ + int32_t n_frames_out; /* frames the pass writes to frames_out */ + + /* ---- ADECODE */ + int64_t n_samples; /* samples a channel the pass writes to audio_out */ +} RadVideoGenBatch; + +/* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent + * frames it reads (from latent frame `chunk_lat0`), its latent grid again so that (frames, h, w, + * first, last) is one run, and the same chunk in patches. */ +enum { + RAD_VGEOM_LAT_FRAMES = 0, RAD_VGEOM_LAT_H = 1, RAD_VGEOM_LAT_W = 2, RAD_VGEOM_N_TEXT = 3, + RAD_VGEOM_N_AUDIO = 4, RAD_VGEOM_CHUNK_LAT0 = 5, + RAD_VGEOM_CHUNK_FRAMES = 6, RAD_VGEOM_CHUNK_H = 7, RAD_VGEOM_CHUNK_W = 8, + RAD_VGEOM_CHUNK_FIRST = 9, RAD_VGEOM_CHUNK_LAST = 10, + RAD_VGEOM_PATCH_FRAMES = 11, RAD_VGEOM_PATCH_H = 12, RAD_VGEOM_PATCH_W = 13, + RAD_VGEOM_N = 16 +}; + /* ================================================================== operands */ /* RAD_OPK_KV names a KV group's pool rather than a buffer: attention and kv_store take the cache * as an operand, and RadKVGroupBatch carries the slot mapping and block table but not the pool diff --git a/abi/rad_yarn.h b/abi/rad_yarn.h index a0c69ae5..925a06e1 100644 --- a/abi/rad_yarn.h +++ b/abi/rad_yarn.h @@ -51,6 +51,41 @@ inline bool rad_yarn_valid(const RadYarn& y) { y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f)); } +/* Llama 3's frequency scaling (transformers' rope_type "llama3"), the other static scaling a + * checkpoint may name: a frequency whose wavelength 2 pi / inv is shorter than orig / high is + * kept, one longer than orig / low is divided by `factor`, and those between are blended, + * s = (orig / wavelength - low) / (high - low), (1 - s) inv / factor + s inv. f32 throughout, as + * transformers computes it. `factor` zero is off. */ +struct RadLlama3 { + float factor = 0.0f; + float low = 0.0f; /* low_freq_factor */ + float high = 0.0f; /* high_freq_factor */ + float orig = 0.0f; /* original_max_position_embeddings */ + + RAD_YARN_HD float frequency(float inv) const { + if (factor == 0.0f) return inv; + const float wavelen = 6.28318530717958647692f / inv; + if (wavelen < orig / high) return inv; + if (wavelen > orig / low) return inv / factor; + const float sm = (orig / wavelen - low) / (high - low); + return (1.0f - sm) * inv / factor + sm * inv; + } +}; + +inline RadLlama3 rad_llama3_args(const RadArgs* a) { + const float factor = (float)rad_args_getf_or(a, "llama3_factor", 0.0); + if (factor == 0.0f) return {}; + return { factor, (float)rad_args_getf_or(a, "llama3_low", 0.0), + (float)rad_args_getf_or(a, "llama3_high", 0.0), + (float)rad_args_getf_or(a, "llama3_orig", 0.0) }; +} + +inline bool rad_llama3_valid(const RadLlama3& l) { + return std::isfinite(l.factor) && + (l.factor == 0.0f || (l.factor >= 1.0f && l.low > 0.0f && l.high > l.low && + std::isfinite(l.high) && l.orig > 0.0f && std::isfinite(l.orig))); +} + #undef RAD_YARN_HD #else /* C */ @@ -82,6 +117,23 @@ static inline RadYarn rad_yarn_args(const RadArgs* a) { return y; } +typedef struct RadLlama3 { + float factor; /* zero: off */ + float low; + float high; + float orig; +} RadLlama3; + +static inline float rad_llama3_frequency(const RadLlama3* l, float inv) { + float wavelen, sm; + if (l->factor == 0.0f) return inv; + wavelen = 6.28318530717958647692f / inv; + if (wavelen < l->orig / l->high) return inv; + if (wavelen > l->orig / l->low) return inv / l->factor; + sm = (l->orig / wavelen - l->low) / (l->high - l->low); + return (1.0f - sm) * inv / l->factor + sm * inv; +} + static inline int rad_yarn_valid(const RadYarn* y) { return isfinite(y->factor) && (y->factor == 0.0f || (y->factor >= 1.0f && isfinite(y->low) && isfinite(y->high) && y->high >= y->low && diff --git a/arch/breeze/CMakeLists.txt b/arch/breeze/CMakeLists.txt new file mode 100644 index 00000000..c8a4ff71 --- /dev/null +++ b/arch/breeze/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/breeze -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(breeze LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(breeze architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/breeze.cpp) diff --git a/arch/breeze/breeze.cpp b/arch/breeze/breeze.cpp new file mode 100644 index 00000000..3cefe06f --- /dev/null +++ b/arch/breeze/breeze.cpp @@ -0,0 +1,1527 @@ +/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono. + * + * ============================== THE MODEL ============================== + * + * Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer): + * + * Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads + * over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read + * bidirectionally over the whole prompt: sliding layers see 255 keys behind and 256 ahead, every + * sixth layer sees all of it. Its output, projected 1152 -> 2048, is the backbone's prompt: the + * backbone never embeds a text token. + * + * Backbone: Qwen3 (28 layers of 2048, 16 query heads over 8 KV heads of 128, q and k RMS-normed, + * theta 1e6). From its last hidden state a head of 2052 writes each frame's first code: one of + * 2048, or the end of the speech (2051). A frame's sixteen codes, embedded from one shared table + * and summed, are its next input. + * + * Depth decoder: 12 layers of 1024 (8 query heads over 2 KV heads of 128, Llama 3's rotary + * scaling, no q/k norms) writes the frame's other fifteen codes one at a time from the backbone's + * hidden state and the codes before them, each from its own head. Sampling everywhere: guidance + * u + g (c - u) when the request asks for it (an unconditional prompt without the voice + * description), temperature 0.9, top 50; the backbone's pick also takes a repetition penalty of + * 1.1 over the piece's earlier first codes. + * + * Codec: the Qwen3-TTS 12 Hz tokenizer's decoder: the codes dequantised through two residual + * quantisers (the first code, the other fifteen), a causal 3-tap conv, an 8-layer transformer of + * 512 (causal, 72 frames of attention), two 2x upsamplings with ConvNeXt blocks, then four + * transposed convolutions (8, 5, 4, 3) with snake-beta residual units: 1920 samples a frame. + * + * The passes are the core's audio generator in its chunked form (abi/rad_builder.h, + * rad_declare_audio_generator with voc_chunk; core/gen/audio_driver.h): PROMPT runs the encoder + * and the backbone over both branches' whole prompts, FRAME samples one frame of every speech in + * flight and runs the backbone over its embedding, VOCODE plays a few frames of one lane as soon as + * they are made. Every layer of the codec is causal, so a chunk is decoded exactly by running the + * codec again over the frames its outputs reach back to (kVocContext) and keeping only its own + * samples; no state is carried between chunks. + * + * ============================== STATE ============================== + * + * A request is a lane: its branches' last hidden states, its first codes so far (the penalty's + * history), and every frame's sixteen codes, which the vocoder reads back. The depth decoder's + * sequence is rebuilt every frame and recomputed whole at each of its fifteen steps (causal + * attention keeps the positions not yet written out of every result it reads). + * + * One card: the model is 3.6B parameters, and a speech in flight is bound by the step's latency, + * which tensor parallelism would only lengthen. + */ +#include + +#include +#include +#include +#include +#include +#include + +namespace breeze { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +constexpr int64_t kMaxLanes = 4; +/* The longest prompt and speech: the reference runs at most 1500 frames (120 s) in a 2048-row + * context. */ +constexpr int64_t kMaxPrompt = 512, kMaxFrames = 1500; +/* The frame's codes: 16 codebooks of 2048, rows of 2051 in the shared table (2048..2050 are never + * sampled); the backbone's head has a 2052nd row, the end of the speech. */ +constexpr int64_t kCodes = 16, kVocab = 2051, kHeadRows = 2052, kEnd = 2051; +constexpr int64_t kSupLo = 2048, kSupHi = 2051, kTopK = 50; +static const double kTemp = 0.9; +static const double kPenalty = 1.1; + +/* The text encoder: a sliding layer sees 255 keys behind and 256 ahead (transformers' sliding mask + * at 512); full layers see the whole prompt, with linear rotary scaling. */ +constexpr int64_t kEncWin = 256, kEncWinRight = 257; +static const double kEncThetaSliding = 10000.0, kEncThetaFull = 1000000.0, kEncFullScale = 8.0; +/* bf16(sqrt(1152)), as the reference holds it. */ +static const double kEncEmbedScale = 34.0; + +/* The codec: 12.5 frames a second of 1920 samples. A chunk is at most kVocChunk frames; its + * outputs reach back kConvCtx frames through the convolutions after the transformer, whose rows + * reach back kAttnWin - 1 frames, whose inputs reach back 2 through the first conv. */ +constexpr int64_t kSamplesPerFrame = 1920, kSampleRate = 24000; +constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72; +constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx; +constexpr int64_t kConvFrames = kConvCtx + kVocChunk; +constexpr int64_t kCbBins = 2048, kCbDim = 256; +/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames, + * the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */ +constexpr int kRates = 8; +static const int64_t kRate[kRates] = { 1, 1, 2, 4, 32, 160, 640, 1920 }; + +/* The prompt (the reference's tts_instruction and tts_plain templates, speaker S0). */ +static const char* kTemplate = "[S0]{instructions}{input}"; +static const char* kPlain = "[S0]{input}"; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpEnc = 0, /* the text encoder's layers: 0.. */ + kGrpLm = 100, + kGrpDepth = 200, + kGrpCodec = 300, +}; + +/* ================================================================== the networks */ +/* A Gemma 3 encoder layer: fused q|k|v, per-head (1 + w) norms and rotary, bidirectional + * attention, sandwich norms around attention and the gelu-tanh GLU. */ +struct EncLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_n3 = 0, w_n4 = 0, w_qn = 0, w_kn = 0; + rad_weight w_qkv = 0, w_o = 0, w_gu = 0, w_down = 0; + rad_op op_n1 = 0, op_qkv = 0, op_qknr = 0, op_attn = 0, op_o = 0, op_n2 = 0, op_add1 = 0; + rad_op op_n3 = 0, op_gu = 0, op_act = 0, op_down = 0, op_n4 = 0, op_add2 = 0; +}; + +/* A Qwen3 layer (the backbone, over the paged cache) or a Llama layer (the depth decoder, dense, + * no q/k norms): separate q, k, v (paged attention reads a contiguous query), rotary, SwiGLU. */ +struct LmLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + rad_weight w_q = 0, w_k = 0, w_v = 0, w_o = 0, w_gu = 0, w_down = 0; + rad_op op_n1 = 0, op_q = 0, op_k = 0, op_v = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0; + rad_op op_kv = 0, op_attn = 0, op_attn_p = 0, op_o = 0, op_add1 = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_add2 = 0; +}; + +/* The codec transformer's layer: fused q|k|v with rotary at the frames' positions, causal + * attention over a 72-frame window, layer scales on both residual branches. */ +struct CodecLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qkv = 0, w_o = 0, w_gu = 0, w_down = 0, w_ls1 = 0, w_ls2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_o = 0, op_ls1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_ls2 = 0, op_add2 = 0; +}; + +/* A ConvNeXt block after a 2x upsampling. */ +struct Upsample { + rad_weight w_t = 0, b_t = 0, w_dw = 0, b_dw = 0, w_ln = 0, b_ln = 0, w_p1 = 0, b_p1 = 0; + rad_weight w_p2 = 0, b_p2 = 0, w_g = 0; + rad_op op_t = 0, op_dw = 0, op_ln = 0, op_p1 = 0, op_gelu = 0, op_p2 = 0, op_g = 0; + rad_op op_add = 0; +}; + +/* A causal conv with its bias. */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct VRes { + rad_weight a1 = 0, b1 = 0, a2 = 0, b2 = 0; + rad_op op_s1 = 0, op_s2 = 0; + VConv c1{}, c2{}; +}; +struct VBlock { + rad_weight a = 0, b = 0, wt = 0, bt = 0; + rad_op op_s = 0, op_t = 0; + int64_t cin = 0, cout = 0, stride = 1; + VRes res[3]; +}; + +/* The depth decoder's rotary scaling (rope_scaling, rope_type "llama3"). */ +struct Llama3 { + double factor = 0, low = 0, high = 0, orig = 0; +}; + +struct Model { + Names nm{""}; + Llama3 l3{}; + Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */ + int64_t lanes = 0; + int64_t S = 0; /* a FRAME pass's rows at most: two a lane */ + rad_kvgroup kv = 0; + + /* ---- the text encoder (PROMPT) */ + rad_weight w_etok = 0, w_enorm = 0, w_eproj = 0; + rad_op op_eembed = 0, op_enorm = 0, op_eproj = 0; + rad_buf b_ex = 0, b_eh = 0, b_eqkv = 0, b_eattn = 0, b_eo = 0, b_egu = 0, b_eff = 0; + std::vector enc; + + /* ---- the backbone */ + rad_weight w_norm = 0, w_head = 0; + rad_op op_norm = 0; + rad_buf b_x = 0, b_h = 0, b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_h2 = 0, b_gu = 0, b_ff = 0; + rad_buf b_last = 0; + std::vector lm; + + /* ---- the frame */ + rad_buf b_hid = 0; /* [2 lanes, 2048] PERSIST: row 2 lane + branch */ + rad_buf b_status = 0; /* [lanes] i32 PERSIST */ + rad_buf b_hist = 0; /* [lanes, 2052] i32 PERSIST: the first codes picked so far */ + rad_buf b_codes_all = 0; /* [lanes * 16, kMaxFrames] i32 PERSIST: each lane's codes */ + rad_buf b_plane = 0; /* [S, 2048] the lanes' hidden states */ + rad_buf b_slog = 0; /* [S, 2052] f32 */ + rad_buf b_codes = 0; /* [16, S] i32: code-major, each code twice (both branches) */ + rad_op op_hsel = 0, op_head = 0, op_samp0 = 0, op_status = 0, op_store = 0, op_fb = 0; + rad_op op_plast = 0, op_pnorm = 0, op_pstore = 0; + rad_weight w_cb = 0; /* [16 * 2051, 2048] the shared codebook table */ + + /* ---- the depth decoder */ + rad_weight w_din = 0, w_dnorm = 0, w_dheads = 0; + rad_op op_din[16] = {}, op_demb[16] = {}, op_dscat = 0, op_dgather = 0; + rad_op op_dnorm = 0, op_dhead = 0, op_dsamp[16] = {}, op_iota[16] = {}; + rad_op op_dpos = 0, op_dcu = 0, op_dzero = 0; + rad_buf b_dseq = 0, b_dx = 0, b_dh = 0, b_dq = 0, b_dk = 0, b_dv = 0, b_dattn = 0, b_dh2 = 0; + rad_buf b_dgu = 0, b_dff = 0, b_didx = 0, b_dpos = 0, b_dcu = 0, b_demb = 0, b_drow = 0; + rad_buf b_dsel = 0, b_dplane = 0, b_dlog = 0; + std::vector dep; + + /* ---- the codec (VOCODE) */ + rad_weight w_cb0 = 0, w_cbr = 0, w_qo0 = 0, w_qor = 0; + rad_op op_rq0 = 0, op_rqr = 0, op_qp0 = 0, op_qpr = 0, op_qadd = 0; + VConv pre{}; + rad_weight w_ip = 0, b_ip = 0, w_cn = 0, w_op = 0, b_op = 0; + rad_op op_ip = 0, op_cn = 0, op_op = 0; + std::vector ct; + Upsample up[2]; + VConv dec0{}; + VBlock vb[4]; + int64_t v_ups[4] = { 8, 5, 4, 3 }; + rad_weight w_fa = 0, w_fb = 0; + rad_op op_fs = 0, op_fcast = 0, op_cnst = 0, op_ccu[8] = {}; + VConv fin{}; + rad_buf b_rq0 = 0, b_rqr = 0, b_qz = 0, b_qt = 0, b_pre = 0, b_cx = 0, b_ch = 0, b_cqkv = 0; + rad_buf b_cattn = 0, b_co = 0, b_cgu = 0, b_cff = 0, b_cn = 0, b_cy = 0; + rad_buf b_cconst = 0, b_ccu[8] = {}; + rad_buf b_ux[3] = {}, b_ua = 0, b_ub = 0, b_uh = 0, b_ug = 0; + rad_buf b_vs[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {}; + rad_buf b_vout = 0, b_audio = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== declare helpers */ +static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y, double wadd = 0.0) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", wadd)), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { x }, { y }); +} + +static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n, + std::initializer_list in, std::initializer_list out) { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + in, out); +} + +static rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); +} + +static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) { + return rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", mult)), + RAD_NOWEIGHTS), + { len }, { y }); +} + +/* A plain weight copied from the checkpoint, declared at `dtype`. */ +static rad_weight wcopy(RadBuilder* b, Names& nm, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int group) { + (void)nm; + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); +} + +/* Two or three checkpoint tensors stacked along dim 0 into one declared weight. */ +static rad_weight wcat(RadBuilder* b, const char* dn, std::initializer_list src, + std::initializer_list shape, int group) { + if (map_concat(b, dn, src) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); +} + +/* ================================================================== the text encoder */ +static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.ge; + Names& nm = m.nm; + const char* tc = "text_encoder_config"; + g.n_layer = rad_meta_geti(meta, nm.f("%s.num_hidden_layers", tc), 26); + g.n_embd = rad_meta_geti(meta, nm.f("%s.hidden_size", tc), 1152); + g.n_head = rad_meta_geti(meta, nm.f("%s.num_attention_heads", tc), 4); + g.n_head_kv = rad_meta_geti(meta, nm.f("%s.num_key_value_heads", tc), 1); + g.head_dim = rad_meta_geti(meta, nm.f("%s.head_dim", tc), 256); + g.n_ff = rad_meta_geti(meta, nm.f("%s.intermediate_size", tc), 6912); + const int64_t V = rad_meta_geti(meta, nm.f("%s.vocab_size", tc), 262158); + const int64_t qpas = rad_meta_geti(meta, nm.f("%s.query_pre_attn_scalar", tc), 256); + const char* lt = rad_meta_gets(meta, nm.f("%s.layer_types", tc), ""); + if (g.n_embd != 1152 || g.head_dim != 256 || g.n_head != 4 || g.n_head_kv != 1 || + rad_meta_geti(meta, nm.f("%s.sliding_window", tc), 512) != 512 || !lt || !*lt) { + fprintf(stderr, "radiance: breeze: the text encoder is not the released one (width %lld, " + "%lld x %lld heads over %lld)\n", (long long)g.n_embd, + (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head_kv); + return RAD_E_UNSUPPORTED; + } + /* Which layers see the whole prompt, from layer_types. */ + std::vector full; + { + std::string s(lt); + size_t at = 0; + while (at < s.size()) { + size_t e = s.find(' ', at); + if (e == std::string::npos) e = s.size(); + const std::string w = s.substr(at, e - at); + if (!w.empty()) full.push_back(w == "full_attention"); + at = e + 1; + } + } + if ((int64_t)full.size() != g.n_layer) { + fprintf(stderr, "radiance: breeze: layer_types names %zu layers for %lld\n", full.size(), + (long long)g.n_layer); + return RAD_E_UNSUPPORTED; + } + const int64_t T = g.max_tok, D = g.n_embd, hd = g.head_dim; + const int64_t qd = g.n_head * hd, kd = g.n_head_kv * hd, Wq = qd + 2 * kd; + const double eps = 1e-6; + + m.b_ex = decl_b(b, nm.f("enc.x"), RAD_BF16, { T, D }); + m.b_eh = decl_b(b, nm.f("enc.h"), RAD_BF16, { T, D }); + m.b_eqkv = decl_b(b, nm.f("enc.qkv"), RAD_BF16, { T, Wq }); + m.b_eattn = decl_b(b, nm.f("enc.attn"), RAD_BF16, { T, qd }); + m.b_eo = decl_b(b, nm.f("enc.o"), RAD_BF16, { T, D }); + m.b_egu = decl_b(b, nm.f("enc.gu"), RAD_BF16, { T, 2 * g.n_ff }); + m.b_eff = decl_b(b, nm.f("enc.ff"), RAD_BF16, { T, g.n_ff }); + + m.w_etok = wcopy(b, nm, nm.f("enc.tok.weight"), "text_encoder.embed_tokens.weight", RAD_BF16, + { V, D }, kGrpEnc); + m.op_eembed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_vocab", V), RAD_STR("dtype", "bf16"), + RAD_F64("mult", kEncEmbedScale)), + RAD_WEIGHTS(m.w_etok)), + {}, { m.b_ex }); + + m.enc.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + EncLayer& L = m.enc[(size_t)l]; + const int li = (int)l, grp = kGrpEnc + 1 + li; + auto src = [&](const char* s) { return nm.ckpt("text_encoder.layers.%d.%s", li, s); }; + auto gain = [&](const char* dn, const char* s, int64_t n) { + return wcopy(b, nm, nm.f("enc.%d.%s", li, dn), src(s), RAD_F32, { n }, grp); + }; + L.w_n1 = gain("n1.weight", "pre_self_attn_layernorm.weight", D); + L.w_n2 = gain("n2.weight", "post_self_attn_layernorm.weight", D); + L.w_n3 = gain("n3.weight", "pre_feedforward_layernorm.weight", D); + L.w_n4 = gain("n4.weight", "post_feedforward_layernorm.weight", D); + L.w_qn = gain("q_norm.weight", "self_attn.q_norm.weight", hd); + L.w_kn = gain("k_norm.weight", "self_attn.k_norm.weight", hd); + L.w_qkv = wcat(b, nm.f("enc.%d.qkv.weight", li), + { src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"), + src("self_attn.v_proj.weight") }, { Wq, D }, grp); + L.w_o = wcopy(b, nm, nm.f("enc.%d.o.weight", li), src("self_attn.o_proj.weight"), RAD_BF16, + { D, qd }, grp); + L.w_gu = wcat(b, nm.f("enc.%d.gate_up.weight", li), + { src("mlp.gate_proj.weight"), src("mlp.up_proj.weight") }, + { 2 * g.n_ff, D }, grp); + L.w_down = wcopy(b, nm, nm.f("enc.%d.down.weight", li), src("mlp.down_proj.weight"), + RAD_BF16, { D, g.n_ff }, grp); + L.op_n1 = norm_op(b, T, D, eps, L.w_n1, m.b_ex, m.b_eh, 1.0); + L.op_qkv = gemm_op(b, T, Wq, D, L.w_qkv, m.b_eh, m.b_eqkv); + const bool fl = full[(size_t)l]; + L.op_qknr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", fl ? kEncThetaFull : kEncThetaSliding), + RAD_F64("eps", eps), + RAD_F64("scale", fl ? kEncFullScale : 1.0), + RAD_STR("mode", "neox"), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_eqkv }, { m.b_eqkv }); + const double scale = 1.0 / std::sqrt((double)qpas); + L.op_attn = fl ? rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.n_head / g.n_head_kv), + RAD_INT("causal", 0), RAD_STR("dtype", "bf16"), + RAD_F64("scale", scale), + RAD_INT("max_seqlen", kMaxPrompt)), + RAD_NOWEIGHTS), + { m.b_eqkv }, { m.b_eattn }) + : rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.n_head / g.n_head_kv), + RAD_INT("causal", 0), RAD_STR("dtype", "bf16"), + RAD_F64("scale", scale), + RAD_INT("max_seqlen", kMaxPrompt), + RAD_INT("window", kEncWin), + RAD_INT("window_right", kEncWinRight)), + RAD_NOWEIGHTS), + { m.b_eqkv }, { m.b_eattn }); + L.op_o = gemm_op(b, T, D, qd, L.w_o, m.b_eattn, m.b_eo); + L.op_n2 = norm_op(b, T, D, eps, L.w_n2, m.b_eo, m.b_eh, 1.0); + L.op_add1 = add_op(b, T, D, m.b_ex, m.b_eh, m.b_ex); + L.op_n3 = norm_op(b, T, D, eps, L.w_n3, m.b_ex, m.b_eh, 1.0); + L.op_gu = gemm_op(b, T, 2 * g.n_ff, D, L.w_gu, m.b_eh, m.b_egu); + L.op_act = rows_op(b, "gelu_mul", T, g.n_ff, { m.b_egu }, { m.b_eff }); + L.op_down = gemm_op(b, T, D, g.n_ff, L.w_down, m.b_eff, m.b_eo); + L.op_n4 = norm_op(b, T, D, eps, L.w_n4, m.b_eo, m.b_eh, 1.0); + L.op_add2 = add_op(b, T, D, m.b_ex, m.b_eh, m.b_ex); + if (!L.w_n1 || !L.w_n2 || !L.w_n3 || !L.w_n4 || !L.w_qn || !L.w_kn || !L.w_qkv || !L.w_o || + !L.w_gu || !L.w_down || !L.op_qknr || !L.op_attn || !L.op_act) + return RAD_E_INVAL; + } + m.w_enorm = wcopy(b, nm, nm.f("enc.norm.weight"), "text_encoder.norm.weight", RAD_F32, { D }, + kGrpEnc); + m.op_enorm = norm_op(b, T, D, eps, m.w_enorm, m.b_ex, m.b_eh, 1.0); + m.w_eproj = wcopy(b, nm, nm.f("enc.proj.weight"), "text_encoder_proj.weight", RAD_BF16, + { m.gl.n_embd, D }, kGrpEnc); + m.op_eproj = gemm_op(b, T, m.gl.n_embd, D, m.w_eproj, m.b_eh, m.b_x); + return m.w_etok && m.w_enorm && m.w_eproj && m.op_eembed ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the backbone, the depth */ +/* A layer's weights and ops over `rows` rows. The backbone's (paged) has q/k norms and NeoX rotary + * at theta; the depth decoder's (dense) has Llama 3's rotary and no norms. */ +static int declare_layer(RadBuilder* b, Names& nm, const Geom& g, const Llama3& l3, LmLayer& L, + int li, const char* dn, const char* pre, int group, int64_t rows, + bool paged, rad_kvgroup kv, rad_buf x, rad_buf h, rad_buf bq, rad_buf bk, + rad_buf bv, rad_buf attn, rad_buf h2, rad_buf gu, rad_buf ff, + rad_buf x_in, rad_buf pos = 0) { + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.n_head * hd, kd = g.n_head_kv * hd; + auto src = [&](const char* s) { return nm.ckpt("%s.%d.%s", pre, li, s); }; + L.w_n1 = wcopy(b, nm, nm.f("%s.%d.attn_norm.weight", dn, li), src("input_layernorm.weight"), + RAD_F32, { D }, group); + L.w_n2 = wcopy(b, nm, nm.f("%s.%d.ffn_norm.weight", dn, li), + src("post_attention_layernorm.weight"), RAD_F32, { D }, group); + L.w_q = wcopy(b, nm, nm.f("%s.%d.q.weight", dn, li), src("self_attn.q_proj.weight"), RAD_BF16, + { qd, D }, group); + L.w_k = wcopy(b, nm, nm.f("%s.%d.k.weight", dn, li), src("self_attn.k_proj.weight"), RAD_BF16, + { kd, D }, group); + L.w_v = wcopy(b, nm, nm.f("%s.%d.v.weight", dn, li), src("self_attn.v_proj.weight"), RAD_BF16, + { kd, D }, group); + L.w_o = wcopy(b, nm, nm.f("%s.%d.o.weight", dn, li), src("self_attn.o_proj.weight"), RAD_BF16, + { D, qd }, group); + L.w_gu = wcat(b, nm.f("%s.%d.gate_up.weight", dn, li), + { src("mlp.gate_proj.weight"), src("mlp.up_proj.weight") }, { 2 * g.n_ff, D }, + group); + L.w_down = wcopy(b, nm, nm.f("%s.%d.down.weight", dn, li), src("mlp.down_proj.weight"), + RAD_BF16, { D, g.n_ff }, group); + if (!L.w_n1 || !L.w_n2 || !L.w_q || !L.w_k || !L.w_v || !L.w_o || !L.w_gu || !L.w_down) + return RAD_E_INVAL; + /* Layer 0 of the depth stack reads its input from the rebuilt sequence, which must survive the + * stack; every other layer reads and writes the residual. */ + L.op_n1 = norm_op(b, rows, D, g.eps, L.w_n1, x_in, h); + L.op_q = gemm_op(b, rows, qd, D, L.w_q, h, bq); + L.op_k = gemm_op(b, rows, kd, D, L.w_k, h, bk); + L.op_v = gemm_op(b, rows, kd, D, L.w_v, h, bv); + auto rope = [&](int64_t heads, rad_buf t) { + if (paged) + return rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + { t }, { t }); + return rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), + RAD_F64("llama3_factor", l3.factor), + RAD_F64("llama3_low", l3.low), + RAD_F64("llama3_high", l3.high), + RAD_F64("llama3_orig", l3.orig)), + RAD_NOWEIGHTS), + { t, pos }, { t }); + }; + if (paged) { + L.w_qn = wcopy(b, nm, nm.f("%s.%d.q_norm.weight", dn, li), src("self_attn.q_norm.weight"), + RAD_F32, { hd }, group); + L.w_kn = wcopy(b, nm, nm.f("%s.%d.k_norm.weight", dn, li), src("self_attn.k_norm.weight"), + RAD_F32, { hd }, group); + if (!L.w_qn || !L.w_kn) return RAD_E_INVAL; + /* Each norm in place: a row's scale is computed before the row is written. */ + L.op_qn = norm_op(b, rows * g.n_head, hd, g.eps, L.w_qn, bq, bq); + L.op_kn = norm_op(b, rows * g.n_head_kv, hd, g.eps, L.w_kn, bk, bk); + } + L.op_rq = rope(g.n_head, bq); + L.op_rk = rope(g.n_head_kv, bk); + if (paged) { + /* A frame is one row a sequence, decode's band; a prompt attends to its own rows. */ + L.op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, 1), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.n_head / g.n_head_kv), RAD_INT("causal", 1), + RAD_INT("window", 0), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), + RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + { bq }, { attn }); + L.op_attn_p = rw(b, RAD_OP(b, "attn_prefix_self", + RAD_PARAMS(RAD_INT("q_len", rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.n_head / g.n_head_kv), + RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("causal", 1), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_ctx", g.max_ctx), RAD_INT("n_head", g.n_head), + RAD_INT("max_seqs", g.max_seqs), RAD_STR("qk", "bf16")), + RAD_NOWEIGHTS), + { bq, bk, bv }, { attn }); + L.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + 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), + { bk, bv }, {}); + } else { + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.n_head / g.n_head_kv), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_seqlen", kCodes)), + RAD_NOWEIGHTS), + { bq, bk, bv }, { attn }); + } + L.op_o = gemm_op(b, rows, D, qd, L.w_o, attn, h2); + L.op_add1 = add_op(b, rows, D, x_in, h2, x); + L.op_n2 = norm_op(b, rows, D, g.eps, L.w_n2, x, h); + L.op_gu = gemm_op(b, rows, 2 * g.n_ff, D, L.w_gu, h, gu); + L.op_act = rows_op(b, "silu_mul", rows, g.n_ff, { gu }, { ff }); + L.op_down = gemm_op(b, rows, D, g.n_ff, L.w_down, ff, h2); + L.op_add2 = add_op(b, rows, D, x, h2, x); + return L.op_rq && L.op_rk && L.op_attn && L.op_act ? RAD_OK : RAD_E_INVAL; +} + +static void step_layer(RadCtx* c, const Model& m, const Geom& g, const LmLayer& L, + const RadBatch* batch, int64_t T, rad_buf x, rad_buf x_in, rad_buf h, + rad_buf bq, rad_buf bk, rad_buf bv, rad_buf attn, rad_buf h2, rad_buf gu, + rad_buf ff, const RadOperand& pos, const RadOperand& cu, int layer) { + RAD_ISSUE(c, L.op_n1, brows(x_in, T), RAD_W(L.w_n1), brows(h, T)); + RAD_ISSUE(c, L.op_q, brows(h, T), RAD_W(L.w_q), brows(bq, T)); + RAD_ISSUE(c, L.op_k, brows(h, T), RAD_W(L.w_k), brows(bk, T)); + RAD_ISSUE(c, L.op_v, brows(h, T), RAD_W(L.w_v), brows(bv, T)); + if (L.op_qn) { + RAD_ISSUE_N(c, L.op_qn, T * g.n_head, brows(bq, T), RAD_W(L.w_qn), brows(bq, T)); + RAD_ISSUE_N(c, L.op_kn, T * g.n_head_kv, brows(bk, T), RAD_W(L.w_kn), brows(bk, T)); + } + RAD_ISSUE(c, L.op_rq, brows(bq, T), pos); + RAD_ISSUE(c, L.op_rk, brows(bk, T), pos); + if (L.op_kv) { + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv); + const RadOperand bt = + praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + const RadOperand bcu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + if (batch->gen == RAD_GEN_PASS_PROMPT) { + /* The prefix first, read from the cache before this pass's rows go in. */ + RAD_ISSUE(c, L.op_attn_p, brows(bq, T), brows(bk, T), brows(bv, T), + kv_cache(m.kv, layer), bt, + praw(batch->agen_b->prefix, RAD_I32, batch->n_seq), bcu, RAD_NONE, RAD_NONE, + RAD_NONE, RAD_NONE, brows(attn, T), RAD_NONE); + RAD_ISSUE(c, L.op_kv, brows(bk, T), brows(bv, T), praw(kvb->slot_mapping, RAD_I32, T), + kv_cache(m.kv, layer)); + } else { + RAD_ISSUE(c, L.op_kv, brows(bk, T), brows(bv, T), praw(kvb->slot_mapping, RAD_I32, T), + kv_cache(m.kv, layer)); + RAD_ISSUE_N(c, L.op_attn, batch->max_q_len, brows(bq, T), kv_cache(m.kv, layer), bt, + praw(kvb->seqused, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, bcu, + brows(attn, T)); + } + } else { + RAD_ISSUE_N(c, L.op_attn, T, brows(bq, T), brows(bk, T), brows(bv, T), cu, brows(attn, T)); + } + RAD_ISSUE(c, L.op_o, brows(attn, T), RAD_W(L.w_o), brows(h2, T)); + RAD_ISSUE(c, L.op_add1, brows(x_in, T), brows(h2, T), brows(x, T)); + RAD_ISSUE(c, L.op_n2, brows(x, T), RAD_W(L.w_n2), brows(h, T)); + RAD_ISSUE(c, L.op_gu, brows(h, T), RAD_W(L.w_gu), brows(gu, T)); + RAD_ISSUE(c, L.op_act, brows(gu, T), brows(ff, T)); + RAD_ISSUE(c, L.op_down, brows(ff, T), RAD_W(L.w_down), brows(h2, T)); + RAD_ISSUE(c, L.op_add2, brows(x, T), brows(h2, T), brows(x, T)); +} + +static int declare_backbone(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m) { + Geom& g = m.gl; + Names& nm = m.nm; + const int64_t T = g.max_tok, D = g.n_embd; + (void)meta; + { + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + kd.n_head_kv = g.n_head_kv; + kd.head_dim = g.head_dim; + m.kv = rad_decl_kv_group(b, nm.f("kv_lm"), &kd); + if (!m.kv) return RAD_E_INVAL; + for (int64_t l = 0; l < g.n_layer; ++l) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv)); + g.kv_dtype = rad_dtype_name(kd.dtype); + } + m.b_x = decl_b(b, nm.f("lm.x"), RAD_BF16, { T, D }); + m.b_h = decl_b(b, nm.f("lm.h"), RAD_BF16, { T, D }); + m.b_q = decl_b(b, nm.f("lm.q"), RAD_BF16, { T, g.n_head * g.head_dim }); + m.b_k = decl_b(b, nm.f("lm.k"), RAD_BF16, { T, g.n_head_kv * g.head_dim }); + m.b_v = decl_b(b, nm.f("lm.v"), RAD_BF16, { T, g.n_head_kv * g.head_dim }); + m.b_attn = decl_b(b, nm.f("lm.attn"), RAD_BF16, { T, g.n_head * g.head_dim }); + m.b_h2 = decl_b(b, nm.f("lm.h2"), RAD_BF16, { T, D }); + m.b_gu = decl_b(b, nm.f("lm.gu"), RAD_BF16, { T, 2 * g.n_ff }); + m.b_ff = decl_b(b, nm.f("lm.ff"), RAD_BF16, { T, g.n_ff }); + m.b_last = decl_b(b, nm.f("lm.last"), RAD_BF16, { m.S, D }); + m.lm.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) + RAD_ARCH_TRY(declare_layer(b, nm, g, m.l3, m.lm[(size_t)l], (int)l, "lm", + "backbone_model.layers", + kGrpLm + (int)l, T, true, m.kv, m.b_x, m.b_h, m.b_q, m.b_k, + m.b_v, m.b_attn, m.b_h2, m.b_gu, m.b_ff, m.b_x)); + m.w_norm = wcopy(b, nm, nm.f("lm.norm.weight"), "backbone_model.norm.weight", RAD_F32, { D }, + kGrpLm); + m.w_head = wcopy(b, nm, nm.f("lm.head.weight"), "lm_head.weight", RAD_BF16, { kHeadRows, D }, + kGrpLm); + return m.w_norm && m.w_head ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the frame */ +static int declare_frame(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& gd = m.gd; + Names& nm = m.nm; + const int64_t S = m.S, D = m.gl.n_embd, lanes = m.lanes, R = (int64_t)kCodes * S; + m.b_hid = decl_b(b, nm.f("frame.hid"), RAD_BF16, { 2 * lanes, D }, RAD_BUF_PERSIST); + m.b_status = decl_b(b, nm.f("frame.status"), RAD_I32, { lanes }, RAD_BUF_PERSIST); + m.b_hist = decl_b(b, nm.f("frame.hist"), RAD_I32, { lanes, kHeadRows }, RAD_BUF_PERSIST); + m.b_codes_all = decl_b(b, nm.f("frame.history"), RAD_I32, { lanes * kCodes, kMaxFrames }, + RAD_BUF_PERSIST); + m.b_plane = decl_b(b, nm.f("frame.plane"), RAD_BF16, { S, D }); + m.b_slog = decl_b(b, nm.f("frame.slog"), RAD_F32, { S, kHeadRows }); + m.b_codes = decl_b(b, nm.f("frame.codes"), RAD_I32, { kCodes, S }); + + /* The shared codebook table: the backbone embeds a frame from it, the depth decoder each + * code. */ + m.w_cb = wcopy(b, nm, nm.f("frame.codebooks.weight"), "depth_decoder.model.embed_tokens.weight", + RAD_BF16, { (int64_t)kCodes * kVocab, D }, kGrpDepth); + + m.op_hsel = rows_op(b, "gather_rows", S, D, { m.b_hid }, { m.b_plane }); + m.op_head = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kHeadRows), + RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_head)), + { m.b_plane }, { m.b_slog }); + m.op_samp0 = rw(b, RAD_OP(b, "cfg_topk_sample", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kHeadRows), + RAD_INT("k", kTopK), RAD_INT("rep", 2), + RAD_F64("cfg", 1.0), + RAD_F64("temp", kTemp), RAD_INT("stream", 0), + RAD_STR("dtype", "f32"), RAD_INT("sup_lo", kSupLo), + RAD_INT("sup_hi", kSupHi), RAD_F64("penalty", kPenalty)), + RAD_NOWEIGHTS), + { m.b_slog, m.b_hist }, { m.b_codes, m.b_hist }); + m.op_status = rw(b, RAD_OP(b, "end_status", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("end", kEnd), + RAD_INT("rep", 2)), + RAD_NOWEIGHTS), + { m.b_codes }, { m.b_status }); + + /* ---- the depth decoder */ + gd = m.gl; + const char* dc = "depth_decoder_config"; + gd.n_layer = rad_meta_geti(meta, nm.f("%s.num_hidden_layers", dc), 12); + gd.n_embd = rad_meta_geti(meta, nm.f("%s.hidden_size", dc), 1024); + gd.n_head = rad_meta_geti(meta, nm.f("%s.num_attention_heads", dc), 8); + gd.n_head_kv = rad_meta_geti(meta, nm.f("%s.num_key_value_heads", dc), 2); + gd.head_dim = rad_meta_geti(meta, nm.f("%s.head_dim", dc), 128); + gd.n_ff = rad_meta_geti(meta, nm.f("%s.intermediate_size", dc), 8192); + gd.eps = (float)rad_meta_getf(meta, nm.f("%s.rms_norm_eps", dc), 1e-5); + gd.theta = (float)rad_meta_getf(meta, nm.f("%s.rope_theta", dc), 500000.0); + m.l3.factor = rad_meta_getf(meta, nm.f("%s.rope_scaling.factor", dc), 32.0); + m.l3.low = rad_meta_getf(meta, nm.f("%s.rope_scaling.low_freq_factor", dc), 0.001953125); + m.l3.high = rad_meta_getf(meta, nm.f("%s.rope_scaling.high_freq_factor", dc), 0.0078125); + m.l3.orig = rad_meta_getf(meta, nm.f("%s.rope_scaling.original_max_position_embeddings", dc), + 16.0); + gd.max_tok = R; + const int64_t Dd = gd.n_embd; + if (Dd != 1024 || gd.head_dim != 128 || + std::strcmp(rad_meta_gets(meta, nm.f("%s.rope_scaling.rope_type", dc), "llama3"), + "llama3") != 0 || + rad_meta_geti(meta, nm.f("%s.num_codebooks", dc), kCodes) != kCodes || + rad_meta_geti(meta, nm.f("%s.vocab_size", dc), kVocab) != kVocab) { + fprintf(stderr, "radiance: breeze: the depth decoder is not the released one (width %lld, " + "head %lld)\n", (long long)Dd, (long long)gd.head_dim); + return RAD_E_UNSUPPORTED; + } + m.w_din = wcopy(b, nm, nm.f("dep.in.weight"), + "depth_decoder.model.inputs_embeds_projector.weight", RAD_BF16, { Dd, D }, + kGrpDepth); + m.w_dnorm = wcopy(b, nm, nm.f("dep.norm.weight"), "depth_decoder.model.norm.weight", RAD_F32, + { Dd }, kGrpDepth); + /* The fifteen heads, stored (in, out) [15, 1024, 2051]: read transposed, one [2051, 1024] + * each. */ + RAD_ARCH_TRY(map_transpose(b, nm.f("dep.heads.weight"), "depth_decoder.codebooks_head.weight")); + m.w_dheads = decl_w(b, nm.f("dep.heads.weight"), RAD_BF16, { (kCodes - 1) * kVocab, Dd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpDepth)); + + m.b_dseq = decl_b(b, nm.f("dep.seq"), RAD_BF16, { R, Dd }); + m.b_dx = decl_b(b, nm.f("dep.x"), RAD_BF16, { R, Dd }); + m.b_dh = decl_b(b, nm.f("dep.h"), RAD_BF16, { R, Dd }); + m.b_dq = decl_b(b, nm.f("dep.q"), RAD_BF16, { R, gd.n_head * gd.head_dim }); + m.b_dk = decl_b(b, nm.f("dep.k"), RAD_BF16, { R, gd.n_head_kv * gd.head_dim }); + m.b_dv = decl_b(b, nm.f("dep.v"), RAD_BF16, { R, gd.n_head_kv * gd.head_dim }); + m.b_dattn = decl_b(b, nm.f("dep.attn"), RAD_BF16, { R, gd.n_head * gd.head_dim }); + m.b_dh2 = decl_b(b, nm.f("dep.h2"), RAD_BF16, { R, Dd }); + m.b_dgu = decl_b(b, nm.f("dep.gu"), RAD_BF16, { R, 2 * gd.n_ff }); + m.b_dff = decl_b(b, nm.f("dep.ff"), RAD_BF16, { R, gd.n_ff }); + m.b_didx = decl_b(b, nm.f("dep.idx"), RAD_I32, { kCodes, S }); + m.b_dpos = decl_b(b, nm.f("dep.pos"), RAD_I32, { R }); + m.b_dcu = decl_b(b, nm.f("dep.cu"), RAD_I32, { S + 1 }); + m.b_demb = decl_b(b, nm.f("dep.emb"), RAD_BF16, { S, D }); + m.b_drow = decl_b(b, nm.f("dep.row"), RAD_BF16, { S, Dd }); + m.b_dsel = decl_b(b, nm.f("dep.sel"), RAD_BF16, { S, Dd }); + m.b_dplane = decl_b(b, nm.f("dep.plane"), RAD_BF16, { S, Dd }); + m.b_dlog = decl_b(b, nm.f("dep.log"), RAD_F32, { S, kVocab }); + + /* Declared in the order a frame issues them, so each buffer's live range is its use: the + * sequence's indices, positions and bounds, and the inputs of positions 0 and p; then the + * stack; then the read-out. The stack runs fifteen times, and what the read-out writes must + * not land on what the next run reads (see the reads added at the end). */ + m.op_dcu = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, S + 1), RAD_INT("mult", kCodes)), + RAD_NOWEIGHTS), + {}, { m.b_dcu }); + for (int p = 0; p < kCodes; ++p) m.op_iota[p] = iota_op(b, S, p, kCodes, m.b_didx); + /* Every sequence's rows at positions 0..15. */ + m.op_dpos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("start", 0), + RAD_INT("step", 1), RAD_INT("period", kCodes)), + RAD_NOWEIGHTS), + {}, { m.b_dpos }); + /* The sequences start each frame as zeros: causal attention never reads a row past the step's + * position, and zeros keep it finite as well (a buffer's first contents are arbitrary). */ + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", Dd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_dseq }); + for (int p = 1; p < kCodes; ++p) + /* Code p - 1's embedding (position p's input): codebook p - 1's rows of the table. */ + m.op_demb[p] = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", 1), RAD_INT("vocab", kVocab), + RAD_INT("off0", (int64_t)(p - 1) * kVocab), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_codes }, { m.b_demb }); + for (int p = 0; p < kCodes; ++p) + m.op_din[p] = gemm_op(b, S, Dd, D, m.w_din, p == 0 ? m.b_plane : m.b_demb, m.b_drow); + m.op_dscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", Dd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_drow, m.b_didx }, { m.b_dseq }); + + m.dep.resize((size_t)gd.n_layer); + for (int64_t l = 0; l < gd.n_layer; ++l) + RAD_ARCH_TRY(declare_layer(b, nm, gd, m.l3, m.dep[(size_t)l], (int)l, "dep", + "depth_decoder.model.layers", kGrpDepth + 1 + (int)l, R, false, + 0, m.b_dx, m.b_dh, m.b_dq, m.b_dk, m.b_dv, m.b_dattn, m.b_dh2, + m.b_dgu, m.b_dff, l == 0 ? m.b_dseq : m.b_dx, m.b_dpos)); + /* Each layer's attention also reads the frame's sequence offsets. */ + for (const LmLayer& L : m.dep) RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_dcu, 1)); + + m.op_dgather = rows_op(b, "gather_rows", S, Dd, { m.b_dx, m.b_didx }, { m.b_dsel }); + m.op_dnorm = norm_op(b, S, Dd, gd.eps, m.w_dnorm, m.b_dsel, m.b_dplane); + m.op_dhead = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kVocab), + RAD_INT("n_embd", Dd), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_dheads)), + { m.b_dplane }, { m.b_dlog }); + for (int p = 1; p < kCodes; ++p) + m.op_dsamp[p] = rw(b, RAD_OP(b, "cfg_topk_sample", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kVocab), + RAD_INT("k", kTopK), RAD_INT("rep", 2), + RAD_F64("cfg", 1.0), RAD_F64("temp", kTemp), + RAD_INT("stream", p), RAD_STR("dtype", "f32"), + RAD_INT("sup_lo", kSupLo), + RAD_INT("sup_hi", kSupHi)), + RAD_NOWEIGHTS), + { m.b_dlog }, { m.b_codes }); + /* The buffers the next run of the stack reads stay live through this one's read-out. */ + { + const rad_buf carried[] = { m.b_dseq, m.b_dpos, m.b_dcu, m.b_didx }; + RAD_ARCH_TRY(rad_op_reads(b, m.op_dsamp[kCodes - 1], carried, 4)); + } + + /* ---- the frame's codes into the lane's history; the next input of the backbone */ + m.op_store = rw(b, RAD_OP(b, "frame_store", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("n_codes", kCodes), + RAD_INT("stride", kMaxFrames), RAD_INT("rep", 2), + RAD_INT("skip", 0)), + RAD_NOWEIGHTS), + { m.b_codes, m.b_status }, { m.b_codes_all }); + m.op_fb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_codes }, { m.b_x }); + /* The backbone's last rows: normed (a prompt's last row a branch, or a frame's row) and into + * the lane's state. */ + m.op_plast = rows_op(b, "gather_rows", S, D, { m.b_x }, { m.b_plane }); + m.op_pnorm = norm_op(b, S, D, m.gl.eps, m.w_norm, m.b_plane, m.b_last); + m.op_pstore = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_last }, { m.b_hid }); + return m.w_cb && m.w_din && m.w_dnorm && m.w_dheads && m.op_samp0 && m.op_store && m.op_fb + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the codec */ +static int vconv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, int64_t rows, rad_buf x, rad_buf res, + rad_buf y, rad_buf cu) { + v.w = wcopy(b, nm, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { cout, cin, k }, + kGrpCodec); + v.b = wcopy(b, nm, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpCodec); + if (!v.w || !v.b) return RAD_E_INVAL; + const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout), + RAD_INT("k", k), RAD_INT("dil", dil), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16"), RAD_INT("causal", 1) }; + const rad_weight ws[] = { v.w, v.b }; + v.op = res ? rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu, res }, { y }) + : rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu }, { y }); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +/* A snake-beta activation's two log-scale vectors. */ +static int snake_beta(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t n, + rad_weight* a, rad_weight* be) { + *a = wcopy(b, nm, nm.f("%s.alpha", dn), nm.ckpt("%s.alpha", src), RAD_F32, { n }, kGrpCodec); + *be = wcopy(b, nm, nm.f("%s.beta", dn), nm.ckpt("%s.beta", src), RAD_F32, { n }, kGrpCodec); + return *a && *be ? RAD_OK : RAD_E_INVAL; +} + +static rad_op snake_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight a, rad_weight be, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16"), RAD_INT("log", 1)), + RAD_WEIGHTS(a, be)), + { x }, { y }); +} + +static int declare_codec(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const char* pc = "audio_tokenizer.decoder_config"; + const int64_t Hc = rad_meta_geti(meta, nm.f("%s.hidden_size", pc), 512); + const int64_t Lat = rad_meta_geti(meta, nm.f("%s.latent_dim", pc), 1024); + const int64_t Dec = rad_meta_geti(meta, nm.f("%s.decoder_dim", pc), 1536); + const int64_t Cd = rad_meta_geti(meta, nm.f("%s.codebook_dim", pc), 512); + const int64_t nq = rad_meta_geti(meta, nm.f("%s.num_quantizers", pc), kCodes); + const int64_t nl_c = rad_meta_geti(meta, nm.f("%s.num_hidden_layers", pc), 8); + const int64_t heads = rad_meta_geti(meta, nm.f("%s.num_attention_heads", pc), 16); + const int64_t hd = rad_meta_geti(meta, nm.f("%s.head_dim", pc), 64); + const int64_t ffc = rad_meta_geti(meta, nm.f("%s.intermediate_size", pc), 1024); + if (std::strcmp(rad_meta_gets(meta, "audio_tokenizer.model_type", ""), + "qwen3_tts_tokenizer_12hz") != 0 || + Hc != 512 || Lat != 1024 || Dec != 1536 || Cd != 512 || nq != kCodes || hd != 64 || + rad_meta_geti(meta, nm.f("%s.sliding_window", pc), kAttnWin) != kAttnWin || + rad_meta_geti(meta, "audio_tokenizer.output_sample_rate", kSampleRate) != kSampleRate) { + fprintf(stderr, "radiance: breeze: the checkpoint has no audio_tokenizer/ folder holding " + "the released Qwen3-TTS 12 Hz codec\n"); + return RAD_E_UNSUPPORTED; + } + const int64_t NL = kVocContext + kVocChunk; /* frames through the transformer */ + const int64_t NC = kConvFrames; /* frames through the convolutions */ + const int64_t qd = heads * hd; + const char* q = "audio_tokenizer.decoder.quantizer"; + + /* ---- the dequantiser: two residual quantisers, each projected 256 -> 512 */ + RAD_ARCH_TRY(map_ema(b, nm.f("codec.cb0.weight"), + nm.ckpt("%s.rvq_first.vq.layers.0._codebook.embedding_sum", q), + nm.ckpt("%s.rvq_first.vq.layers.0._codebook.cluster_usage", q))); + m.w_cb0 = decl_w(b, nm.f("codec.cb0.weight"), RAD_BF16, { kCbBins, kCbDim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); + for (int j = 0; j < kCodes - 1; ++j) + RAD_ARCH_TRY(map_ema(b, nm.f("codec.cbr.weight"), + nm.ckpt("%s.rvq_rest.vq.layers.%d._codebook.embedding_sum", q, j), + nm.ckpt("%s.rvq_rest.vq.layers.%d._codebook.cluster_usage", q, j))); + m.w_cbr = decl_w(b, nm.f("codec.cbr.weight"), RAD_BF16, { (kCodes - 1) * kCbBins, kCbDim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); + m.w_qo0 = wcopy(b, nm, nm.f("codec.q0.weight"), nm.ckpt("%s.rvq_first.output_proj.weight", q), + RAD_BF16, { Cd, kCbDim }, kGrpCodec); + m.w_qor = wcopy(b, nm, nm.f("codec.qr.weight"), nm.ckpt("%s.rvq_rest.output_proj.weight", q), + RAD_BF16, { Cd, kCbDim }, kGrpCodec); + m.b_rq0 = decl_b(b, nm.f("codec.rq0"), RAD_BF16, { NL, kCbDim }); + m.b_rqr = decl_b(b, nm.f("codec.rqr"), RAD_BF16, { NL, kCbDim }); + m.b_qz = decl_b(b, nm.f("codec.qz"), RAD_BF16, { NL, Cd }); + m.b_qt = decl_b(b, nm.f("codec.qt"), RAD_BF16, { NL, Cd }); + auto rvq = [&](rad_weight t0, rad_weight t1, int64_t K, rad_buf y) { + return rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("n_embd", kCbDim), + RAD_INT("n_codes", K), RAD_INT("vocab", kCbBins), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(t0, t1)), + { m.b_codes_all }, { y }); + }; + m.op_rq0 = rvq(m.w_cb0, m.w_cb0, 1, m.b_rq0); + m.op_rqr = rvq(m.w_cbr, m.w_cbr, kCodes - 1, m.b_rqr); + m.op_qp0 = gemm_op(b, NL, Cd, kCbDim, m.w_qo0, m.b_rq0, m.b_qz); + m.op_qpr = gemm_op(b, NL, Cd, kCbDim, m.w_qor, m.b_rqr, m.b_qt); + m.op_qadd = add_op(b, NL, Cd, m.b_qz, m.b_qt, m.b_qz); + + /* ---- the sequence bounds, one sequence at each rate: the transformer's frames (the pass's + * own), then the convolutions' (the last kConvFrames of them, or all when fewer) at the frame + * rate, 2x, 4x, and after each of the decoder's four blocks */ + m.b_cconst = decl_b(b, nm.f("codec.nconv"), RAD_I32, { 1 }); + m.op_cnst = iota_op(b, 1, NC, 0, m.b_cconst); + for (int s2 = 0; s2 < kRates; ++s2) { + m.b_ccu[s2] = decl_b(b, nm.f("codec.cu%d", s2), RAD_I32, { 2 }); + m.op_ccu[s2] = s2 == 0 ? cu_op(b, 1, 0, m.b_ccu[0]) + : cu_op(b, kRate[s2], m.b_cconst, m.b_ccu[s2]); + } + + /* ---- the causal 3-tap conv and the transformer */ + m.b_pre = decl_b(b, nm.f("codec.pre"), RAD_BF16, { NL, Lat }); + RAD_ARCH_TRY(vconv(b, nm, m.pre, "codec.pre", "audio_tokenizer.decoder.pre_conv.conv", Cd, Lat, + 3, 1, NL, m.b_qz, 0, m.b_pre, m.b_ccu[0])); + const char* pt = "audio_tokenizer.decoder.pre_transformer"; + m.w_ip = wcopy(b, nm, nm.f("codec.in.weight"), nm.ckpt("%s.input_proj.weight", pt), RAD_BF16, + { Hc, Lat }, kGrpCodec); + m.b_ip = wcopy(b, nm, nm.f("codec.in.bias"), nm.ckpt("%s.input_proj.bias", pt), RAD_BF16, + { Hc }, kGrpCodec); + m.b_cx = decl_b(b, nm.f("codec.x"), RAD_BF16, { NL, Hc }); + m.b_ch = decl_b(b, nm.f("codec.h"), RAD_BF16, { NL, Hc }); + m.b_cqkv = decl_b(b, nm.f("codec.qkv"), RAD_BF16, { NL, 3 * qd }); + m.b_cattn = decl_b(b, nm.f("codec.attn"), RAD_BF16, { NL, qd }); + m.b_co = decl_b(b, nm.f("codec.o"), RAD_BF16, { NL, Hc }); + m.b_cgu = decl_b(b, nm.f("codec.gu"), RAD_BF16, { NL, 2 * ffc }); + m.b_cff = decl_b(b, nm.f("codec.ff"), RAD_BF16, { NL, ffc }); + m.op_ip = gemm_bias_op(b, NL, Hc, Lat, m.w_ip, m.b_ip, m.b_pre, m.b_cx); + m.ct.resize((size_t)nl_c); + for (int64_t l = 0; l < nl_c; ++l) { + CodecLayer& L = m.ct[(size_t)l]; + const int li = (int)l; + auto src = [&](const char* s) { return nm.ckpt("%s.layers.%d.%s", pt, li, s); }; + L.w_n1 = wcopy(b, nm, nm.f("codec.%d.n1.weight", li), src("input_layernorm.weight"), + RAD_F32, { Hc }, kGrpCodec); + L.w_n2 = wcopy(b, nm, nm.f("codec.%d.n2.weight", li), + src("post_attention_layernorm.weight"), RAD_F32, { Hc }, kGrpCodec); + L.w_ls1 = wcopy(b, nm, nm.f("codec.%d.ls1.weight", li), src("self_attn_layer_scale.scale"), + RAD_F32, { Hc }, kGrpCodec); + L.w_ls2 = wcopy(b, nm, nm.f("codec.%d.ls2.weight", li), src("mlp_layer_scale.scale"), + RAD_F32, { Hc }, kGrpCodec); + L.w_qkv = wcat(b, nm.f("codec.%d.qkv.weight", li), + { src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"), + src("self_attn.v_proj.weight") }, { 3 * qd, Hc }, kGrpCodec); + L.w_o = wcopy(b, nm, nm.f("codec.%d.o.weight", li), src("self_attn.o_proj.weight"), + RAD_BF16, { Hc, qd }, kGrpCodec); + L.w_gu = wcat(b, nm.f("codec.%d.gate_up.weight", li), + { src("mlp.gate_proj.weight"), src("mlp.up_proj.weight") }, { 2 * ffc, Hc }, + kGrpCodec); + L.w_down = wcopy(b, nm, nm.f("codec.%d.down.weight", li), src("mlp.down_proj.weight"), + RAD_BF16, { Hc, ffc }, kGrpCodec); + L.op_n1 = norm_op(b, NL, Hc, 1e-5, L.w_n1, m.b_cx, m.b_ch); + L.op_qkv = gemm_op(b, NL, 3 * qd, Hc, L.w_qkv, m.b_ch, m.b_cqkv); + L.op_rope = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", + rad_meta_getf(meta, nm.f("%s.rope_theta", pc), + 10000.0)), + RAD_F64("scale", 1.0), RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + { m.b_cqkv }, { m.b_cqkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, NL), 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", NL), RAD_INT("window", kAttnWin)), + RAD_NOWEIGHTS), + { m.b_cqkv }, { m.b_cattn }); + L.op_o = gemm_op(b, NL, Hc, qd, L.w_o, m.b_cattn, m.b_co); + L.op_ls1 = mulw_op(b, NL, Hc, L.w_ls1, m.b_co, m.b_co); + L.op_add1 = add_op(b, NL, Hc, m.b_cx, m.b_co, m.b_cx); + L.op_n2 = norm_op(b, NL, Hc, 1e-5, L.w_n2, m.b_cx, m.b_ch); + L.op_gu = gemm_op(b, NL, 2 * ffc, Hc, L.w_gu, m.b_ch, m.b_cgu); + L.op_act = rows_op(b, "silu_mul", NL, ffc, { m.b_cgu }, { m.b_cff }); + L.op_down = gemm_op(b, NL, Hc, ffc, L.w_down, m.b_cff, m.b_co); + L.op_ls2 = mulw_op(b, NL, Hc, L.w_ls2, m.b_co, m.b_co); + L.op_add2 = add_op(b, NL, Hc, m.b_cx, m.b_co, m.b_cx); + if (!L.w_n1 || !L.w_n2 || !L.w_ls1 || !L.w_ls2 || !L.w_qkv || !L.w_o || !L.w_gu || + !L.w_down || !L.op_rope || !L.op_attn || !L.op_ls1 || !L.op_ls2) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_ccu[0], 1)); + } + m.w_cn = wcopy(b, nm, nm.f("codec.norm.weight"), nm.ckpt("%s.norm.weight", pt), RAD_F32, { Hc }, + kGrpCodec); + m.op_cn = norm_op(b, NL, Hc, 1e-5, m.w_cn, m.b_cx, m.b_ch); + m.w_op = wcopy(b, nm, nm.f("codec.out.weight"), nm.ckpt("%s.output_proj.weight", pt), RAD_BF16, + { Lat, Hc }, kGrpCodec); + m.b_op = wcopy(b, nm, nm.f("codec.out.bias"), nm.ckpt("%s.output_proj.bias", pt), RAD_BF16, + { Lat }, kGrpCodec); + m.b_cy = decl_b(b, nm.f("codec.y"), RAD_BF16, { NL, Lat }); + m.op_op = gemm_bias_op(b, NL, Lat, Hc, m.w_op, m.b_op, m.b_ch, m.b_cy); + + /* ---- two 2x upsamplings, each a transposed conv of kernel 2 and a ConvNeXt block */ + m.b_ua = decl_b(b, nm.f("codec.ua"), RAD_BF16, { 4 * NC, Lat }); + m.b_ub = decl_b(b, nm.f("codec.ub"), RAD_BF16, { 4 * NC, Lat }); + m.b_uh = decl_b(b, nm.f("codec.uh"), RAD_BF16, { 4 * NC, 4 * Lat }); + m.b_ug = decl_b(b, nm.f("codec.ug"), RAD_BF16, { 4 * NC, 4 * Lat }); + m.b_ux[0] = m.b_cy; + for (int i = 0; i < 2; ++i) { + Upsample& U = m.up[i]; + const int64_t rin = NC << i, rout = NC << (i + 1); + const char* us = nm.ckpt("audio_tokenizer.decoder.upsample.%d", i); + auto w = [&](const char* dn, const char* s, uint32_t dt, + std::initializer_list sh) { + return wcopy(b, nm, nm.f("codec.up%d.%s", i, dn), nm.ckpt("%s.%s", us, s), dt, sh, + kGrpCodec); + }; + U.w_t = w("t.weight", "0.conv.weight", RAD_BF16, { Lat, Lat, 2 }); + U.b_t = w("t.bias", "0.conv.bias", RAD_BF16, { Lat }); + U.w_dw = w("dw.weight", "1.dwconv.conv.weight", RAD_BF16, { Lat, 1, 7 }); + U.b_dw = w("dw.bias", "1.dwconv.conv.bias", RAD_BF16, { Lat }); + U.w_ln = w("ln.weight", "1.norm.weight", RAD_F32, { Lat }); + U.b_ln = w("ln.bias", "1.norm.bias", RAD_F32, { Lat }); + U.w_p1 = w("p1.weight", "1.pwconv1.weight", RAD_BF16, { 4 * Lat, Lat }); + U.b_p1 = w("p1.bias", "1.pwconv1.bias", RAD_BF16, { 4 * Lat }); + U.w_p2 = w("p2.weight", "1.pwconv2.weight", RAD_BF16, { Lat, 4 * Lat }); + U.b_p2 = w("p2.bias", "1.pwconv2.bias", RAD_BF16, { Lat }); + U.w_g = w("gamma", "1.gamma", RAD_F32, { Lat }); + m.b_ux[i + 1] = decl_b(b, nm.f("codec.ux%d", i + 1), RAD_BF16, { rout, Lat }); + U.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rin), RAD_INT("cin", Lat), + RAD_INT("cout", Lat), RAD_INT("stride", 2), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2)), + RAD_WEIGHTS(U.w_t, U.b_t)), + { m.b_ux[i], m.b_ccu[1 + i] }, { m.b_ux[i + 1] }); + U.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", Lat), + RAD_INT("k", 7), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_dw, U.b_dw)), + { m.b_ux[i + 1], m.b_ccu[2 + i] }, { m.b_ua }); + U.op_ln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", Lat), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_ln, U.b_ln)), + { m.b_ua }, { m.b_ub }); + U.op_p1 = gemm_bias_op(b, rout, 4 * Lat, Lat, U.w_p1, U.b_p1, m.b_ub, m.b_uh); + U.op_gelu = rows_op(b, "gelu", rout, 4 * Lat, { m.b_uh }, { m.b_ug }); + U.op_p2 = gemm_bias_op(b, rout, Lat, 4 * Lat, U.w_p2, U.b_p2, m.b_ug, m.b_ua); + U.op_g = mulw_op(b, rout, Lat, U.w_g, m.b_ua, m.b_ua); + U.op_add = add_op(b, rout, Lat, m.b_ux[i + 1], m.b_ua, m.b_ux[i + 1]); + if (!U.w_t || !U.b_t || !U.w_dw || !U.b_dw || !U.w_ln || !U.b_ln || !U.w_p1 || !U.b_p1 || + !U.w_p2 || !U.b_p2 || !U.w_g || !U.op_t || !U.op_dw || !U.op_ln || !U.op_gelu) + return RAD_E_INVAL; + } + + /* ---- the decoder: a conv into 1536 channels, four upsampling blocks, the output conv */ + const int64_t R0 = 4 * NC; /* rows at the 50 Hz latent rate */ + int64_t rows[5], ch[5]; + rows[0] = R0; + ch[0] = Dec; + for (int i = 0; i < 4; ++i) { + rows[i + 1] = rows[i] * m.v_ups[i]; + ch[i + 1] = Dec >> (i + 1); + } + for (int s = 0; s < 5; ++s) { + m.b_vs[s] = decl_b(b, nm.f("codec.s%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vt[s] = decl_b(b, nm.f("codec.t%d", s), RAD_BF16, { rows[s], ch[s] }); + if (s > 0) { + m.b_va[s] = decl_b(b, nm.f("codec.a%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vb[s] = decl_b(b, nm.f("codec.b%d", s), RAD_BF16, { rows[s], ch[s] }); + } + } + const char* dd = "audio_tokenizer.decoder.decoder"; + RAD_ARCH_TRY(vconv(b, nm, m.dec0, "codec.dec0", nm.ckpt("%s.0.conv", dd), Lat, Dec, 7, 1, R0, + m.b_ux[2], 0, m.b_vs[0], m.b_ccu[3])); + static const int64_t kDil[3] = { 1, 3, 9 }; + for (int i = 0; i < 4; ++i) { + VBlock& B = m.vb[i]; + const int64_t ci = ch[i], co = ch[i + 1], s = m.v_ups[i]; + B.cin = ci; B.cout = co; B.stride = s; + const char* bn = nm.f("codec.b%d", i); + const char* bs = nm.ckpt("%s.%d.block", dd, i + 1); + RAD_ARCH_TRY(snake_beta(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.0", bs), ci, &B.a, &B.b)); + B.op_s = snake_op(b, rows[i], ci, B.a, B.b, m.b_vs[i], m.b_vt[i]); + B.wt = wcopy(b, nm, nm.f("%s.t.weight", bn), nm.ckpt("%s.1.conv.weight", bs), RAD_BF16, + { ci, co, 2 * s }, kGrpCodec); + B.bt = wcopy(b, nm, nm.f("%s.t.bias", bn), nm.ckpt("%s.1.conv.bias", bs), RAD_BF16, { co }, + kGrpCodec); + B.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[i]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", s), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2 * s)), + RAD_WEIGHTS(B.wt, B.bt)), + { m.b_vt[i], m.b_ccu[3 + i] }, { m.b_vs[i + 1] }); + if (!B.wt || !B.bt || !B.op_t || !B.op_s) return RAD_E_INVAL; + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* us = nm.ckpt("%s.%d", bs, r + 2); + const int64_t R = rows[i + 1]; + RAD_ARCH_TRY(snake_beta(b, nm, nm.f("%s.act1", un), nm.ckpt("%s.act1", us), co, &U.a1, + &U.b1)); + RAD_ARCH_TRY(snake_beta(b, nm, nm.f("%s.act2", un), nm.ckpt("%s.act2", us), co, &U.a2, + &U.b2)); + U.op_s1 = snake_op(b, R, co, U.a1, U.b1, m.b_vs[i + 1], m.b_vt[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.conv1.conv", us), co, + co, 7, kDil[r], R, m.b_vt[i + 1], 0, m.b_va[i + 1], m.b_ccu[4 + i])); + U.op_s2 = snake_op(b, R, co, U.a2, U.b2, m.b_va[i + 1], m.b_vb[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.conv2.conv", us), co, + co, 1, 1, R, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], + m.b_ccu[4 + i])); + if (!U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + } + RAD_ARCH_TRY(snake_beta(b, nm, "codec.snake_out", nm.ckpt("%s.5", dd), ch[4], &m.w_fa, + &m.w_fb)); + m.op_fs = snake_op(b, rows[4], ch[4], m.w_fa, m.w_fb, m.b_vs[4], m.b_vt[4]); + m.b_vout = decl_b(b, nm.f("codec.out"), RAD_BF16, { rows[4], 1 }); + RAD_ARCH_TRY(vconv(b, nm, m.fin, "codec.conv_out", nm.ckpt("%s.6.conv", dd), ch[4], 1, 7, 1, + rows[4], m.b_vt[4], 0, m.b_vout, m.b_ccu[7])); + m.b_audio = decl_b(b, nm.f("codec.audio"), RAD_F32, { kVocChunk * kSamplesPerFrame, 1 }, + RAD_BUF_PERSIST); + m.op_fcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kVocChunk * kSamplesPerFrame), + RAD_INT("n", 1), RAD_STR("from", "bf16"), + RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_vout }, { m.b_audio }); + return m.w_cb0 && m.w_cbr && m.w_qo0 && m.w_qor && m.w_ip && m.b_ip && m.w_cn && m.w_op && + m.b_op && m.op_fs && m.op_fcast && m.op_cnst + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + if (std::strcmp(rad_meta_gets(meta, "backbone_model_type", ""), "qwen3") != 0 || + rad_meta_geti(meta, "num_codebooks", 0) != kCodes || + rad_meta_geti(meta, "vocab_size", 0) != kVocab || + rad_meta_geti(meta, "audio_token_id", 0) != 262144) { + fprintf(stderr, "radiance: breeze: not the released Breeze-TTS-2 layout (a Qwen3 backbone " + "over 16 codebooks of 2051)\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: breeze: Breeze-TTS-2 is served on one card (--tp 1): a speech's " + "pace is the step's latency, which tensor parallelism only lengthens\n"); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(geom_from(m.gl, meta, ctx, "bf16", RAD_BF16)); + /* The backbone's own configuration: the top level's rotary and eps are the depth decoder's + * family's, not the Qwen3 backbone's. */ + m.gl.eps = (float)rad_meta_getf(meta, "backbone_config.rms_norm_eps", 1e-6); + m.gl.theta = (float)rad_meta_getf(meta, "backbone_config.rope_theta", 1000000.0); + m.lanes = std::min(kMaxLanes, std::max(1, ctx->max_seqs / 2)); + m.S = 2 * m.lanes; + m.ge = m.gl; + if (m.gl.max_tok < 2 * (int64_t)kMaxPrompt || m.gl.max_tok < kVocContext + kVocChunk) { + fprintf(stderr, "radiance: breeze: a pass carries %lld rows; a prompt pass needs %lld\n", + (long long)m.gl.max_tok, (long long)(2 * kMaxPrompt)); + return RAD_E_INVAL; + } + + RAD_ARCH_TRY(declare_backbone(b, meta, ctx, m)); + RAD_ARCH_TRY(declare_encoder(b, meta, m)); + RAD_ARCH_TRY(declare_frame(b, meta, m)); + RAD_ARCH_TRY(declare_codec(b, meta, m)); + + if (!ctx->shape_probe) { + RadAudioGenDecl d{}; + d.name = "breeze-tts-2"; + d.tmpl = kTemplate; + d.tmpl_plain = kPlain; + d.neg_tmpl = kPlain; + d.prompt_whole = 1; + d.first_frame = 0; + d.max_prompt = kMaxPrompt; + d.max_frames = kMaxFrames; + d.frame_rate_num = 25; + d.frame_rate_den = 2; + d.lat_num = 1; + d.lat_den = 1; + d.samples_per_latent = kSamplesPerFrame; + d.sample_rate = kSampleRate; + d.channels = 1; + d.default_cfg = 1.0; + d.max_lanes = m.lanes; + d.status = m.b_status; + d.audio_out = m.b_audio; + d.voc_chunk = kVocChunk; + d.voc_context = kVocContext; + RAD_ARCH_TRY(rad_declare_audio_generator(b, &d)); + } + rad_note(b, "Breeze-TTS-2 -- text encoder %lld layers, backbone %lld layers (%lld heads over " + "%lld KV), depth decoder %lld layers, codec transformer %zu layers, %lld lanes", + (long long)m.ge.n_layer, (long long)m.gl.n_layer, (long long)m.gl.n_head, + (long long)m.gl.n_head_kv, (long long)m.gd.n_layer, m.ct.size(), (long long)m.lanes); + return RAD_OK; +} + +/* ================================================================== step */ +static void store_hidden(RadCtx* c, const Model& m, const RadAudioGenBatch* A, int64_t S, + const int32_t* last_rows, int64_t T) { + RAD_ISSUE_N(c, m.op_plast, S, brows(m.b_x, T), praw(last_rows, RAD_I32, S), + brows(m.b_plane, S)); + RAD_ISSUE_N(c, m.op_pnorm, S, brows(m.b_plane, S), RAD_W(m.w_norm), brows(m.b_last, S)); + RAD_ISSUE_N(c, m.op_pstore, S, brows(m.b_last, S), praw(A->slot, RAD_I32, S), + brows(m.b_hid, 2 * m.lanes)); +} + +static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) { + const int64_t T = batch->n_tok; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + const RadOperand pos = praw(batch->positions, RAD_I32, T); + int layer = 0; + for (const LmLayer& L : m.lm) + step_layer(c, m, m.gl, L, batch, T, m.b_x, m.b_x, m.b_h, m.b_q, m.b_k, m.b_v, m.b_attn, + m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++); +} + +static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t T = batch->n_tok; + const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + const RadOperand pos = praw(batch->positions, RAD_I32, T); + /* The encoder over each branch's prompt, bidirectional within it; its projection is the + * backbone's input. */ + RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok), + brows(m.b_ex, T)); + for (const EncLayer& L : m.enc) { + RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T)); + RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T)); + RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T), + bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T)); + RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T)); + RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T)); + RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); + RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T)); + RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T)); + RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T)); + RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T)); + RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T)); + RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); + } + RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T)); + RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T)); + step_backbone(c, batch, m); + bool any_last = false; + for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i]; + if (any_last) store_hidden(c, m, A, batch->n_seq, A->last_row, T); +} + +static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t n = A->n_lane, S = 2 * n, R = (int64_t)kCodes * S, D = m.gl.n_embd; + const int64_t Dd = m.gd.n_embd, Sx = m.S; /* Sx: the codes' and indices' row pitch */ + const RadOperand seed = praw(A->seed, RAD_U32, 2 * n), frame = praw(A->frame, RAD_I32, n); + const RadOperand lanes = praw(A->lane, RAD_I32, n), slot = praw(A->slot, RAD_I32, S); + const RadOperand cfg = praw(A->cfg, RAD_F32, n); + /* Row p of a code-major [16, Sx] plane, narrowed to this pass's S entries. */ + auto row_of = [&](rad_buf h, int p) { + RadOperand o = brow_slice(h, p, 1, Sx); + o.cols = S; + return o; + }; + auto codes = [&](int p) { return row_of(m.b_codes, p); }; + auto idx = [&](int p) { return row_of(m.b_didx, p); }; + + /* 1. the first code, from the lanes' hidden states */ + RAD_ISSUE_N(c, m.op_hsel, S, brows(m.b_hid, 2 * m.lanes), slot, brows(m.b_plane, S)); + RAD_ISSUE_N(c, m.op_head, S, brows(m.b_plane, S), RAD_W(m.w_head), brows(m.b_slog, S)); + RAD_ISSUE_N(c, m.op_samp0, S, brows(m.b_slog, S), seed, frame, codes(0), cfg, lanes, + brows(m.b_hist, m.lanes)); + RAD_ISSUE_N(c, m.op_status, n, codes(0), lanes, brows(m.b_status, m.lanes)); + + /* 2. the depth decoder's sequences: 16 rows each, the hidden state's projection at position 0 + * and each code's from position 1 */ + for (int p = 0; p < kCodes; ++p) RAD_ISSUE_N(c, m.op_iota[p], S, idx(p)); + RAD_ISSUE_N(c, m.op_dpos, R, brows(m.b_dpos, R)); + RAD_ISSUE_N(c, m.op_dzero, R, brows(m.b_dseq, R)); + RAD_ISSUE_N(c, m.op_dcu, S + 1, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_dcu, S + 1)); + RAD_ISSUE_N(c, m.op_din[0], S, brows(m.b_plane, S), RAD_W(m.w_din), brows(m.b_drow, S)); + RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx(0), brows(m.b_dseq, R)); + const RadOperand dpos_r = brows(m.b_dpos, R); + const RadOperand dcu = brows(m.b_dcu, S + 1); + for (int p = 1; p < kCodes; ++p) { + /* Code p - 1 into position p. */ + RAD_ISSUE_N(c, m.op_demb[p], S, codes(p - 1), RAD_W(m.w_cb), RAD_W(m.w_cb), + brows(m.b_demb, S)); + RAD_ISSUE_N(c, m.op_din[p], S, brows(m.b_demb, S), RAD_W(m.w_din), brows(m.b_drow, S)); + RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx(p), brows(m.b_dseq, R)); + int layer = 0; + for (const LmLayer& L : m.dep) + step_layer(c, m, m.gd, L, batch, R, m.b_dx, &L == &m.dep[0] ? m.b_dseq : m.b_dx, m.b_dh, + m.b_dq, m.b_dk, m.b_dv, m.b_dattn, m.b_dh2, m.b_dgu, m.b_dff, dpos_r, dcu, + layer++); + RAD_ISSUE_N(c, m.op_dgather, S, brows(m.b_dx, R), idx(p), brows(m.b_dsel, S)); + RAD_ISSUE_N(c, m.op_dnorm, S, brows(m.b_dsel, S), RAD_W(m.w_dnorm), brows(m.b_dplane, S)); + RadOperand head = RAD_W(m.w_dheads); + head.offset = (int64_t)(p - 1) * kVocab * Dd; + head.rows = kVocab; + RAD_ISSUE_N(c, m.op_dhead, S, brows(m.b_dplane, S), head, brows(m.b_dlog, S)); + RAD_ISSUE_N(c, m.op_dsamp[p], S, brows(m.b_dlog, S), seed, frame, codes(p), cfg, RAD_NONE, + RAD_NONE); + } + + /* 3. the frame into its lane's history, and the backbone over the frame's embedding */ + RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame, + brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes)); + RadOperand t1 = RAD_W(m.w_cb); + t1.offset = (int64_t)kVocab * D; + t1.rows = (int64_t)(kCodes - 1) * kVocab; + RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S)); + step_backbone(c, batch, m); + store_hidden(c, m, A, S, A->last_row, S); +} + +static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t nl = A->voc_latents, n = nl - A->voc_left, L = A->voc_lane; + const int64_t Hc = 512, qd = 1024; + /* The convolutions run over the last kConvFrames frames, or all of them when fewer. */ + const int64_t nc = std::min(nl, kConvFrames), c0 = nl - nc; + const RadOperand nlen = praw(batch->cu_seqlens + 1, RAD_I32, 1); + const RadOperand clen = nc == nl ? nlen : brows(m.b_cconst, 1); + + /* 1. the codes, dequantised: the lane's frames [voc_frame0, + nl) of each codebook */ + RadOperand codes = bcol_at(m.b_codes_all, L * kCodes, kMaxFrames, A->voc_frame0, nl, kCodes); + RadOperand rest = bcol_at(m.b_codes_all, L * kCodes + 1, kMaxFrames, A->voc_frame0, nl, + kCodes - 1); + RadOperand t1 = RAD_W(m.w_cbr); + t1.offset = (int64_t)kCbBins * kCbDim; + t1.rows = (int64_t)(kCodes - 2) * kCbBins; + RAD_ISSUE_N(c, m.op_rq0, nl, codes, RAD_W(m.w_cb0), RAD_W(m.w_cb0), brows(m.b_rq0, nl)); + RAD_ISSUE_N(c, m.op_rqr, nl, rest, RAD_W(m.w_cbr), t1, brows(m.b_rqr, nl)); + RAD_ISSUE_N(c, m.op_qp0, nl, brows(m.b_rq0, nl), RAD_W(m.w_qo0), brows(m.b_qz, nl)); + RAD_ISSUE_N(c, m.op_qpr, nl, brows(m.b_rqr, nl), RAD_W(m.w_qor), brows(m.b_qt, nl)); + RAD_ISSUE_N(c, m.op_qadd, nl, brows(m.b_qz, nl), brows(m.b_qt, nl), brows(m.b_qz, nl)); + + /* 2. the causal conv and the transformer over every frame of the pass */ + /* In declaration order: the constant, then the bounds that read it. */ + if (nc != nl) RAD_ISSUE_N(c, m.op_cnst, 1, brows(m.b_cconst, 1)); + RAD_ISSUE_N(c, m.op_ccu[0], 2, nlen, brows(m.b_ccu[0], 2)); + for (int s2 = 1; s2 < kRates; ++s2) + RAD_ISSUE_N(c, m.op_ccu[s2], 2, clen, brows(m.b_ccu[s2], 2)); + RAD_ISSUE_N(c, m.pre.op, nl, brows(m.b_qz, nl), RAD_W(m.pre.w), brows(m.b_ccu[0], 2), RAD_NONE, + brows(m.b_pre, nl), RAD_W(m.pre.b)); + RAD_ISSUE_N(c, m.op_ip, nl, brows(m.b_pre, nl), RAD_W(m.w_ip), RAD_W(m.b_ip), RAD_NONE, + brows(m.b_cx, nl)); + const RadOperand pos = praw(batch->positions, RAD_I32, nl); + const RadOperand cu = brows(m.b_ccu[0], 2); + for (const CodecLayer& Ly : m.ct) { + RAD_ISSUE_N(c, Ly.op_n1, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n1), brows(m.b_ch, nl)); + RAD_ISSUE_N(c, Ly.op_qkv, nl, brows(m.b_ch, nl), RAD_W(Ly.w_qkv), brows(m.b_cqkv, nl)); + RAD_ISSUE_N(c, Ly.op_rope, nl, brows(m.b_cqkv, nl), pos); + RAD_ISSUE_N(c, Ly.op_attn, nl, bcol(m.b_cqkv, 0, qd, nl), bcol(m.b_cqkv, qd, qd, nl), + bcol(m.b_cqkv, 2 * qd, qd, nl), cu, brows(m.b_cattn, nl)); + RAD_ISSUE_N(c, Ly.op_o, nl, brows(m.b_cattn, nl), RAD_W(Ly.w_o), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_ls1, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls1), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_add1, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); + RAD_ISSUE_N(c, Ly.op_n2, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n2), brows(m.b_ch, nl)); + RAD_ISSUE_N(c, Ly.op_gu, nl, brows(m.b_ch, nl), RAD_W(Ly.w_gu), brows(m.b_cgu, nl)); + RAD_ISSUE_N(c, Ly.op_act, nl, brows(m.b_cgu, nl), brows(m.b_cff, nl)); + RAD_ISSUE_N(c, Ly.op_down, nl, brows(m.b_cff, nl), RAD_W(Ly.w_down), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_ls2, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls2), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_add2, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); + } + RAD_ISSUE_N(c, m.op_cn, nl, brows(m.b_cx, nl), RAD_W(m.w_cn), brows(m.b_ch, nl)); + /* Only the frames the convolutions read: the last nc. */ + RAD_ISSUE_N(c, m.op_op, nc, brow_slice(m.b_ch, c0, nc, Hc), RAD_W(m.w_op), RAD_W(m.b_op), + RAD_NONE, brows(m.b_cy, nc)); + + /* 3. the upsamplings, at 25 and 50 rows a second */ + for (int i = 0; i < 2; ++i) { + const Upsample& U = m.up[i]; + const int64_t rin = nc << i, rout = nc << (i + 1); + RAD_ISSUE_N(c, U.op_t, rin, brows(m.b_ux[i], rin), RAD_W(U.w_t), RAD_W(U.b_t), + brows(m.b_ccu[1 + i], 2), brows(m.b_ux[i + 1], rout)); + RAD_ISSUE_N(c, U.op_dw, rout, brows(m.b_ux[i + 1], rout), RAD_W(U.w_dw), + brows(m.b_ccu[2 + i], 2), brows(m.b_ua, rout), RAD_W(U.b_dw)); + RAD_ISSUE_N(c, U.op_ln, rout, brows(m.b_ua, rout), RAD_W(U.w_ln), RAD_W(U.b_ln), + brows(m.b_ub, rout)); + RAD_ISSUE_N(c, U.op_p1, rout, brows(m.b_ub, rout), RAD_W(U.w_p1), RAD_W(U.b_p1), RAD_NONE, + brows(m.b_uh, rout)); + RAD_ISSUE_N(c, U.op_gelu, rout, brows(m.b_uh, rout), brows(m.b_ug, rout)); + RAD_ISSUE_N(c, U.op_p2, rout, brows(m.b_ug, rout), RAD_W(U.w_p2), RAD_W(U.b_p2), RAD_NONE, + brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_g, rout, brows(m.b_ua, rout), RAD_W(U.w_g), brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_add, rout, brows(m.b_ux[i + 1], rout), brows(m.b_ua, rout), + brows(m.b_ux[i + 1], rout)); + } + + /* 4. the decoder */ + int64_t rows[5]; + rows[0] = 4 * nc; + for (int i = 0; i < 4; ++i) rows[i + 1] = rows[i] * m.v_ups[i]; + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cub) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), brows(cub, 2), + res ? brows(res, R) : RAD_NONE, brows(y, R), RAD_W(v.b)); + }; + conv(m.dec0, m.b_ux[2], 0, m.b_vs[0], rows[0], m.b_ccu[3]); + for (int i = 0; i < 4; ++i) { + const VBlock& B = m.vb[i]; + const int64_t r0 = rows[i], r1 = rows[i + 1]; + RAD_ISSUE_N(c, B.op_s, r0, brows(m.b_vs[i], r0), RAD_W(B.a), brows(m.b_vt[i], r0), + RAD_W(B.b)); + RAD_ISSUE_N(c, B.op_t, r0, brows(m.b_vt[i], r0), RAD_W(B.wt), RAD_W(B.bt), + brows(m.b_ccu[3 + i], 2), brows(m.b_vs[i + 1], r1)); + for (int r = 0; r < 3; ++r) { + const VRes& U = B.res[r]; + RAD_ISSUE_N(c, U.op_s1, r1, brows(m.b_vs[i + 1], r1), RAD_W(U.a1), + brows(m.b_vt[i + 1], r1), RAD_W(U.b1)); + conv(U.c1, m.b_vt[i + 1], 0, m.b_va[i + 1], r1, m.b_ccu[4 + i]); + RAD_ISSUE_N(c, U.op_s2, r1, brows(m.b_va[i + 1], r1), RAD_W(U.a2), + brows(m.b_vb[i + 1], r1), RAD_W(U.b2)); + conv(U.c2, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], r1, m.b_ccu[4 + i]); + } + } + RAD_ISSUE_N(c, m.op_fs, rows[4], brows(m.b_vs[4], rows[4]), RAD_W(m.w_fa), + brows(m.b_vt[4], rows[4]), RAD_W(m.w_fb)); + conv(m.fin, m.b_vt[4], 0, m.b_vout, rows[4], m.b_ccu[7]); + /* 5. the chunk's own samples: its last n frames */ + const int64_t ns = n * kSamplesPerFrame; + RAD_ISSUE_N(c, m.op_fcast, ns, brow_slice(m.b_vout, rows[4] - ns, ns, 1), brows(m.b_audio, ns)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->agen_b) { + rad_step_fail(c, "breeze is an audio generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_PROMPT: step_prompt(c, batch, m); return; + case RAD_GEN_PASS_FRAME: step_frame(c, batch, m); return; + case RAD_GEN_PASS_VOCODE: step_vocode(c, batch, m); return; + default: + rad_step_fail(c, "breeze: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * kMaxPrompt; + out->gen_audio = 1; + out->gen_ctx = (int64_t)kMaxPrompt + kMaxFrames + 1; + return RAD_OK; +} + +/* ================================================================== the request's texts */ +/* The reference strips the instructions; the text goes in as written. */ +static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { + if (!in) return RAD_E_INVAL; + std::string r = in; + if (field == RAD_TEXT_INSTRUCTIONS) { + const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n"); + r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1); + } + if ((int64_t)r.size() < cap) { + std::memcpy(out, r.data(), r.size()); + out[r.size()] = 0; + } + return (int64_t)r.size(); +} + +} /* namespace breeze */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(breeze) +extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) { + return breeze::text_prepare(field, in, out, cap); +} +RAD_ARCH_PLUGIN(breeze, "breeze", "", "0.1.0", + "Breeze-TTS-2: a T5Gemma 2 text encoder over a Qwen3 backbone with a 16-codebook " + "depth decoder and the Qwen3-TTS 12 Hz codec; 24 kHz mono speech") +#endif diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index c7b80d42..a160909e 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -417,6 +417,48 @@ inline RadNameMap map_base(const char* declared, int mode) { return m; } +/* Row ranges of checkpoint tensors joined along dim 0 (RAD_MAP_ROWS): each piece is (source, + * first row, rows). */ +struct RowPiece { const char* src; int first; int64_t rows; }; +inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list pieces) { + RadNameMap m = map_base(declared, RAD_MAP_ROWS); + for (const RowPiece& p : pieces) { + if (m.n_src >= 8) return RAD_E_INVAL; + m.src[m.n_src] = p.src; + m.src_index[m.n_src] = p.first; + m.src_rows[m.n_src] = p.rows; + ++m.n_src; + } + return rad_decl_name_map(b, &m); +} + +/* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */ +inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) { + RadNameMap m = map_base(declared, RAD_MAP_WNORM); + m.n_src = 2; + m.src[0] = g; + m.src[1] = v; + return rad_decl_name_map(b, &m); +} + +/* A linear the checkpoint keeps as (in, out), read as (out, in): src's last two dimensions + * swapped (RAD_MAP_TRANSPOSE). */ +inline int map_transpose(RadBuilder* b, const char* declared, const char* src) { + RadNameMap m = map_base(declared, RAD_MAP_TRANSPOSE); + m.n_src = 1; + m.src[0] = src; + return rad_decl_name_map(b, &m); +} + +/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */ +inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) { + RadNameMap m = map_base(declared, RAD_MAP_EMA); + m.n_src = 2; + m.src[0] = sums; + m.src[1] = usage; + return rad_decl_name_map(b, &m); +} + /* A checkpoint tensor copied through unchanged. */ inline int map_copy(RadBuilder* b, const char* declared, const char* src) { RadNameMap m = map_base(declared, RAD_MAP_COPY); diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index 6a9e8261..18485a41 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -98,9 +98,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down })); RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x)); - /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4 and rotated 5-bit gate_up weights - * take the pair. */ - if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5) + /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit and 4-bit gate_up + * weights take the pair. */ + if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4) op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, { w.h.q, w.h.s }, gq_ffn.want_x diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index e5a4012a..fe5058a2 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -631,6 +631,14 @@ struct LinearFP8 { /* The 5-bit sibling: the same rotation to f16 (`rot_q` is the f16 plane, no `rot_s`), then * gemm_nt_q at w5a16 over u5 codes with an f16 scale and a zero point. */ bool paro5 = false; + /* A 4-bit weight with a zero point and no rotation (linear_is_w4): the int4 W4A16 releases. + * At or below `w4_split` rows `op_a16` casts the input's bf16 plane to f16 (`a16`) for the + * w4a16_asym GEMM `op`; above it `op_q` quantises it to int8 with a scale per (row, 128) + * (`a8q`, `a8s`) for the w4a8i8_asym GEMM `op2`. */ + bool w4 = false; + int64_t w4_split = 0; + rad_buf a16 = 0, a8q = 0, a8s = 0; + rad_op op_a16 = 0; /* Prefill band for z-lab's int4 and the int5: above `rot_split` rows the f16 skinny kernel is * bound by the slow f16 matrix instruction, so a second chain runs: the same rotation to int8 * with a scale per (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM (`w4a8i8_asym` / @@ -650,6 +658,10 @@ struct LinearFP8 { * this is set; otherwise the linear reads unwritten arena bytes. */ bool reads_x = false; bool mapped = false; /* probe() made the name map; declare() does not make it again */ + /* The weight's access class (rad_builder.h): read every pass by default; a linear run once a + * request (an encoder's) says so, which lets placement keep it off the card. Set before + * declare(). */ + int access = RAD_ACCESS_PER_TOKEN; /* Declares the name map and reads the weight's format (reads_x, probed_i8). `base` and `src` * are the same as for declare(). */ @@ -778,6 +790,19 @@ inline bool linear_is_paro_mxfp4(const RadEncoding& e) { sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP; } +/* A 4-bit weight with a zero point and no transform: u4 codes, an f16 scale and a u4 or u8 zero + * point per 128 of K (libquant `codes=u4 zero=u4 group=128 scale=f16`, or rad-convert's import rule + * over an int4 release). Read by gemm_nt_q at w4a16_asym over an f16 activation, or w4a8i8_asym + * over an int8 one, the rotated int4's GEMMs with no rotation. */ +inline bool linear_is_w4(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || e.n_planes != 3 || e.transform[0]) return false; + const RadEncPlane *sc = rad_enc_plane(&e, "scale"), *zp = rad_enc_plane(&e, "zero"); + return e.plane[0].dtype == RAD_U4 && e.plane[0].block[1] == 1 && sc && zp && + sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK && + (zp->dtype == RAD_U4 || zp->dtype == RAD_U8) && zp->block[0] == 1 && + zp->block[1] == RAD_FP8_BLOCK; +} + /* A rotated weight with ParoQuant int5 (u5) or z-lab int4 (u4) asymmetric codes: an f16 scale and * u8 zero point per 128 of K. Read by gemm_nt_q at w5a16 / w4a16_asym over an f16 activation, or * w5a8i8 / w4a8i8_asym over an int8 one. */ @@ -799,9 +824,10 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; probed_i8 = known && linear_is_w8(enc); - /* A rotated weight rotates and quantises the bf16 plane itself. */ + /* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or + * quantises it. */ const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); - reads_x = g.w_bf16 || plain || probed_i8 || rotated; + reads_x = g.w_bf16 || plain || probed_i8 || rotated || (known && linear_is_w4(enc)); return RAD_OK; } @@ -941,7 +967,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } RowParts rp; RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows")); - w = decl_w_n(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, rp.w, rp.n); + w = decl_w_n(b, wn, RAD_BF16, { N, K }, access, shard, grp, 0, rp.w, rp.n); if (!w) return RAD_E_INVAL; if (span_hi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); op = rw(b, RAD_OP(b, "gemm_nt", @@ -973,9 +999,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha RowParts rp; RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows")); const char* sn = nm.f("%s.scale", base); - w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, rp.w, rp.n); - ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, + ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, access, shard, grp, rp.w, rp.n); if (!w || !ws) return RAD_E_INVAL; if (span_hi > 0) { @@ -1042,10 +1068,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha if (!rot_q) return RAD_E_INVAL; op_rot = decl_rot_op(b, g, a, 1, f16_hi, { rot_q }); if (!op_rot) return RAD_E_INVAL; - w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, + w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, access, shard, grp); ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, - RAD_ACCESS_PER_TOKEN, shard, grp); + access, shard, grp); if (!w || !ws) return RAD_E_INVAL; op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, bits5 ? "w5a16" : "w4a16_asym", pb1, pb2, { w, ws }, { rot_q }, y); @@ -1067,6 +1093,71 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha return RAD_OK; } + /* ---- 4-bit weight with a zero point and no rotation: the rotated int4's two GEMMs over this + * linear's own copies of the input's bf16 plane. At or below kSplit rows (the skinny f16 + * kernel's ceiling) the plane is cast to f16 for w4a16_asym; above it, where that kernel is + * bound by the f16 matrix instruction, it is quantised to int8 with an f32 scale per + * (row, 128) for w4a8i8_asym. Two views: codes, and (scale, zero) as `b_scale`, both at the + * logical extents, so row parts and spans apply to both as they are; a column slice must be + * whole 128s, the scale group. */ + w4 = known && linear_is_w4(enc); + if (w4) { + if (!a.x) { + fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, " + "and its input has none\n", wn); + return RAD_E_DTYPE; + } + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a 4-bit weight takes rows in " + "16s and K in whole %d-column groups\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + RowParts rp; + RAD_ARCH_TRY(rp.set(row_parts, 1, 1, base, "rows")); + w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, access, shard, grp, rp.w, rp.n); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, access, + shard, grp, rp.w, rp.n); + if (!w || !ws) return RAD_E_INVAL; + if (span_hi > 0) { + if (shard == RAD_SHARD_COL && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a " + "%d-column scale group\n", base, (long long)span_lo, + (long long)span_hi, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi)); + RAD_ARCH_TRY(rad_weight_shard_span(b, ws, span_lo, span_hi)); + } + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; + const int64_t kSplit = 64; + const int64_t f16_hi = hi > kSplit ? kSplit : hi; + a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { f16_hi, K }); + if (!a16) return RAD_E_INVAL; + op_a16 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, f16_hi), RAD_INT("n", K), + RAD_STR("from", g.dtype), RAD_STR("to", "f16")), + RAD_NOWEIGHTS), + { a.x }, { a16 }); + op = decl_gemm_q(b, 1, f16_hi, RAD_FP8_BLOCK, "w4a16_asym", 0, 0, { w, ws }, { a16 }, y); + if (!op_a16 || !op) return RAD_E_INVAL; + if (hi > kSplit) { + w4_split = kSplit; + a8q = decl_b(b, nm.f("%s.a8q", base), RAD_I8, { hi, K }); + a8s = decl_b(b, nm.f("%s.a8s", base), RAD_F32, { hi, K / RAD_FP8_BLOCK }); + if (!a8q || !a8s) return RAD_E_INVAL; + op_q = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { a.x }, { a8q, a8s }); + op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, "w4a8i8_asym", 0, 0, { w, ws }, + { a8q, a8s }, y); + if (!op_q || !op2) return RAD_E_INVAL; + } + return RAD_OK; + } + /* The remaining formats read the E4M3 pair, which an int8-fed input lacks (a trunk mixing * formats that the model's probe did not detect). */ if (a.q8_fed) { @@ -1125,12 +1216,12 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } const char* sn = nm.f("%s.scale", base); const char* rn = nm.f("%s.ref", base); - w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN, + w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, rp.w, rp.n); ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, - RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n); + access, shard, grp, rp.w, rp.n); wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, - RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n); + access, shard, grp, rp.w, rp.n); if (!w || !ws || !wref) return RAD_E_INVAL; if (span_hi > 0) { const bool col = shard == RAD_SHARD_COL; @@ -1152,6 +1243,23 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha return op ? RAD_OK : RAD_E_INVAL; } + /* Block fp8 is the last form; any other encoding is refused by name with the ones read. */ + if (known) { + const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); + if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] || + enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 || + sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) { + char en[256]; + rad_enc_format(&enc, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they " + "read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], " + "fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the " + "ParoQuant forms. A recipe rule stores the weight in one of them " + "(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en); + return RAD_E_DTYPE; + } + } + /* Block fp8: per-rank extents must be whole scale blocks, checked here to name the weight (this * also catches a tensor-parallel width that cuts a block). */ if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) { @@ -1173,10 +1281,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in * the checkpoint or made so by rad-convert's recipe. */ w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, - RAD_ACCESS_PER_TOKEN, shard, grp, rp.w, rp.n); + access, shard, grp, rp.w, rp.n); ws_row_div = RAD_FP8_BLOCK; ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, - RAD_ACCESS_PER_TOKEN, shard, grp, rp.s, rp.n); + access, shard, grp, rp.s, rp.n); if (!w || !ws) return RAD_E_INVAL; /* An uneven slice; the scale plane takes the same slice in blocks. */ if (span_hi > 0) { @@ -1222,6 +1330,22 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); return; } + /* The 4-bit weight's copies of the input start at their buffers' first row: they live only + * between the two ops issued here. */ + if (w4 && w4_split && rows > w4_split) { + RAD_ISSUE_N(c, op_q, rows, brow_slice(a.x, r0, rows, K), brow_slice(a8q, 0, rows, K), + brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK)); + RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K), + brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws), + brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } + if (w4) { + RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K)); + RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws), + brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } if (paro5 && rot_split && rows > rot_split) { RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense), RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), @@ -1275,6 +1399,8 @@ struct DenseFP8 { * works against the same E4M3 activation pair. */ rad_weight ref = 0; bool mx = false; + /* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */ + bool mapped = false; int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, int shard, RadWeightGroup grp, @@ -1309,7 +1435,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t * only whole 16-row tiles; K takes whole 128s for the activation's per-(row, 128) scale. */ { const char* wn = nm.f("%s.weight", base); - RAD_ARCH_TRY(map_linear(b, wn, src)); + if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); RadEncoding enc{}; mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc); if (mx) { diff --git a/arch/embgemma2/embgemma2.cpp b/arch/embgemma2/embgemma2.cpp index 6dd04f00..c76b5a67 100644 --- a/arch/embgemma2/embgemma2.cpp +++ b/arch/embgemma2/embgemma2.cpp @@ -443,11 +443,12 @@ struct Audio { bcol(out, 0, n_out, Rn)); }; - RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2)); + RAD_ISSUE_N(c, op_c0, Pn, frames, RAD_W(w_c0), cu, valid, brows(b_s0, Pn / 2), RAD_NONE); RAD_ISSUE_N(c, op_n0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), RAD_W(w_n0), RAD_NONE, brows(b_s0, Pn / 2)); RAD_ISSUE_N(c, op_r0, Pn / 2 * (nmel / 2), brows(b_s0, Pn / 2), brows(b_s0, Pn / 2)); - RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn)); + RAD_ISSUE_N(c, op_c1, Pn / 2, brows(b_s0, Pn / 2), RAD_W(w_c1), cu, valid, brows(b_s1, Rn), + RAD_NONE); RAD_ISSUE_N(c, op_n1, Rn * (nmel / 4), brows(b_s1, Rn), RAD_W(w_n1), RAD_NONE, brows(b_s1, Rn)); RAD_ISSUE_N(c, op_r1, Rn * (nmel / 4), brows(b_s1, Rn), brows(b_s1, Rn)); @@ -477,7 +478,8 @@ struct Audio { RAD_ISSUE_N(c, l.op_lc_pre, Rn, brows(b_x, Rn), RAD_W(l.lc_pre), brows(b_h, Rn)); clipped(l.lc_start, b_h, H, b_hc, b_g, 2 * H); RAD_ISSUE_N(c, l.op_glu, Rn, bcol(b_g, H, H, Rn), bcol(b_g, 0, H, Rn), brows(b_u, Rn)); - RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn)); + RAD_ISSUE_N(c, l.op_dw, Rn, brows(b_u, Rn), RAD_W(l.lc_dw), cu, brows(b_o, Rn), + RAD_NONE); RAD_ISSUE_N(c, l.op_lc_norm, Rn, brows(b_o, Rn), RAD_W(l.lc_norm), brows(b_o, Rn)); RAD_ISSUE_N(c, l.op_lc_act, Rn, brows(b_o, Rn), brows(b_o, Rn)); clipped(l.lc_end, b_o, H, b_hc, b_u, H); diff --git a/arch/minimaxh3/CMakeLists.txt b/arch/minimaxh3/CMakeLists.txt new file mode 100644 index 00000000..6ad47f4d --- /dev/null +++ b/arch/minimaxh3/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/minimaxh3 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(minimaxh3 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(minimaxh3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxh3.cpp) diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp new file mode 100644 index 00000000..3f8d9e52 --- /dev/null +++ b/arch/minimaxh3/minimaxh3.cpp @@ -0,0 +1,2097 @@ +/* minimaxh3 -- MiniMax-H3: a video and its stereo soundtrack from text. + * + * ============================== THE MODEL ============================== + * + * Four networks behind one prompt (diffusers' MiniMaxH3ModularPipeline, workflow t2va): + * + * Text encoder: Qwen3-VL-32B's language model over the prompt's tokens (no template, no special + * tokens). The conditioning is the hidden state after its 50th layer, before any norm, so only + * the first 50 layers exist here. + * + * Denoiser: a 33B single-stream diffusion transformer over ONE packed sequence + * [text | soundtrack | video] -- the conditioning through `context_embedder` and a two-block + * token refiner, the soundtrack's latents (40 a second, two channels one after the other, 32 + * values each) through `audio_proj_in`, the video's latents in 1 x 2 x 2 patches through + * `proj_in` -- with full attention and a 3-axis rotary over (time, row, column). 50 blocks of + * `h += gate * attn(rms(h) w1 (1 + scale) + shift); h += gate' * mlp(...)`, each block's six + * modulation vectors chosen per row by its modality (video, text, audio) at its timestep. It is + * guidance-distilled: one forward a step. The video and the soundtrack step down their own + * schedules together. + * + * Video decoder: a 36-layer ViT over the latents, decoded in 16 x 16-latent tiles of 7 latent + * frames (a 256-pixel tile, 28 pixel frames), blended where tiles and chunks overlap; frames + * come out at 24 a second. + * + * Audio decoder: a BigVGAN with anti-aliased SnakeBeta activations, 800 samples a latent at + * 32 kHz, each stereo channel a sequence of its own. + * + * 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). + * + * ============================== A DISTILLED RELEASE ============================== + * + * FastVideo's FastH3 is the same denoiser distilled to eight evaluations on fixed timesteps with + * video sparse attention, and says so in its inference settings (fastvideo_inference.json): the + * timesteps on a 1000-step clock, the shifts (10 for the video), the attention and its sparsity. + * Its attention cuts the packed sequence into tiles -- the prompt's and the soundtrack's rows in + * 64-row chunks, the video's patches in 4 x 4 x 4 boxes of (time, row, column) -- and a video + * query tile attends to every chunk and to the video tiles of best mean-query . mean-key score, + * (1 - sparsity) of them; a chunk's queries attend to everything. A fourth projection beside q, k + * and v (`to_gate_compress`) gates in an attention over the tiles' means. Everything else is the + * base model's. + * + * ============================== ONCE A REQUEST ============================== + * + * The conditioning pass runs the text encoder and the refiner, and also every step's modulation: + * a block's six vectors depend only on the step's timesteps, which the request's schedule fixes, + * so the 13B parameters of the modulation projections are read once a request rather than once a + * step. They are a table in the lane, [step][block][modality][this rank's share], gathered across + * ranks one step at a time. Both the text encoder and the modulation projections are therefore + * read once a request (RAD_ACCESS_PER_REQUEST), which lets placement keep them in host memory + * (--vision-tower-placement ram). + * + * ============================== 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 + * 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 + * score half at twice the rate. The video decoder's linears are bf16 with f32 norms and layer + * scales; the audio decoder is f32 throughout. + * + * ============================== TENSOR PARALLEL ============================== + * + * The text encoder, the refiner and the DiT's blocks split by heads and feed-forward width, an + * all-reduce after each output projection. A modulation projection splits by its output rows + * (6 / world of the six vectors a rank) and the table is gathered a step at a time. The video + * decoder splits its tiles between ranks with whole weights on each, and gathers the decoded + * tiles; the audio decoder runs whole on every rank. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace minimaxh3 { + +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 }; +/* 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 + * terminal 0 included, so one more than the evaluations). */ +enum { kMaxSteps = 64, kDefSteps = 50 }; +/* Time: 24 frames a second; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, + * and a decode pass reads 7 latent frames from 5 c. 5 to 15 seconds: 7 to 20 chunks. */ +enum { kFps = 24, kFpc = 17, kFtail = 5, kLpc = 5, kLtail = 2, kDecLat = 7 }; +enum { kMinChunks = 7, kMaxChunks = 20, kDefChunks = 7 }; +/* Space: 16 pixels a latent, 2 x 2 latents a patch; sides multiples of 32 from 256, at most the + * 1344 x 768 canvas's area, 4:1 at most. */ +enum { kScale = 16, kPatch = 2, kMult = 32, kMinSide = 256, kMaxAspect = 4 }; +enum { kDefW = 1344, kDefH = 768, kMaxArea = kDefW * kDefH }; +/* The soundtrack. */ +enum { kRate = 32000, kAudioRate = 40, kAudioCh = 2, kAudioC = 32 }; +/* The video decoder's tiles, in latents: 16 square, 4 apart at least, 4 register tokens and one + * zero token after a tile's 7 x 16 x 16. */ +enum { kTile = 16, kOverlap = 4, kRegs = 4, kTileTok = kDecLat * kTile * kTile, + kPeriod = kTileTok + kRegs + 1 }; +/* Rows the DiT's heads run a part at a time: the f32 copy of the normed rows they read. */ +enum { kHeadRows = 16384 }; +/* Rows a DiT all-reduce carries. The library's peer scratch is sized by the largest message an + * all-reduce declares, two slots of it and outside the VRAM budget, so a step's whole 106K x 5376 + * residual would hold over 4 GiB a card; 16K rows is 176 MB a message, past where the link + * saturates. */ +enum { kArRows = 16384 }; + +/* The latent channels and the patch's values. */ +enum { kC = 24, kPatchVals = kC * kPatch * kPatch }; + +/* Video sparse attention's tiles, in patches (time, row, column), for a checkpoint distilled with + * it: 64 rows a tile, the dense segments cut into 64-row chunks of their own. */ +enum { kVsaT = 4, kVsaH = 4, kVsaW = 4, kVsaRows = kVsaT * kVsaH * kVsaW }; + +/* ImageNet's normalisation, which the video decoder's pixels are in. */ +static const char* kPixMean = "0.485 0.456 0.406"; +static const char* kPixStd = "0.229 0.224 0.225"; + +/* The packed sequence's segments, in order, and each one's modulation table row: text rows take + * the video's timestep with modality 1, the soundtrack its own with 2, the video its own with 0. */ +enum { kSegText = 0, kSegAudio = 1, kSegVideo = 2, kSegs = 3 }; +static const int kSegMod[kSegs] = { 1, 2, 0 }; + +/* ================================================================== 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, + * a latent at a time. A side no longer than a tile is one tile (min_side keeps it exactly one). */ +static std::vector tile_starts(int64_t L) { + std::vector st{ 0 }; + if (kTile >= L) return st; + int64_t n = (L + kTile - 1) / kTile; + while (kTile * n - kOverlap * (n - 1) - L < 0) ++n; + std::vector ov((size_t)(n - 1), kOverlap); + const int64_t rem = kTile * n - kOverlap * (n - 1) - L; + for (int64_t i = 0; i < rem; ++i) ov[(size_t)(i % (n - 1))] += 1; + for (int64_t i = 0; i + 1 < n; ++i) st.push_back(st.back() + kTile - ov[(size_t)i]); + return st; +} + +static int64_t tiles_of(int64_t lat_h, int64_t lat_w) { + return (int64_t)tile_starts(lat_h).size() * (int64_t)tile_starts(lat_w).size(); +} + +/* Whether a frame of w x h pixels is one this model makes. */ +static bool size_ok(int64_t w, int64_t h) { + return w % kMult == 0 && h % kMult == 0 && w >= kMinSide && h >= kMinSide && + w * h <= kMaxArea && std::max(w, h) <= kMaxAspect * std::min(w, h); +} + +/* The most tiles a decode pass carries, over every size. */ +static int64_t max_tiles() { + int64_t best = 0; + for (int64_t w = kMinSide; w <= (int64_t)kMaxArea / kMinSide; w += kMult) + for (int64_t h = kMinSide; h * w <= kMaxArea; h += kMult) + if (size_ok(w, h)) best = std::max(best, tiles_of(h / kScale, w / kScale)); + return best; +} + +static int64_t max_lat_frames() { return (int64_t)kLpc * kMaxChunks + kLtail; } +static int64_t max_patches() { return (int64_t)kMaxArea / (kScale * kPatch * kScale * kPatch); } +static int64_t max_video_rows() { return max_lat_frames() * max_patches(); } +static int64_t max_audio() { + const int64_t frames = (int64_t)kFpc * kMaxChunks + kFtail; + return (frames * kAudioRate + kFps / 2) / kFps + 1; +} +static int64_t max_step_rows() { return kMaxText + kAudioCh * max_audio() + max_video_rows(); } + +/* Video sparse attention's video tiles over a grid of F x ph x pw patches, and the ones a video + * query keeps at `sparsity`: ceil((1 - sparsity) V) in f64, at least one. */ +static int64_t vsa_video_tiles(int64_t F, int64_t ph, int64_t pw) { + return ((F + kVsaT - 1) / kVsaT) * ((ph + kVsaH - 1) / kVsaH) * ((pw + kVsaW - 1) / kVsaW); +} +static int64_t vsa_keep(double sparsity, int64_t V) { + const double keep = std::ceil((1.0 - sparsity) * (double)V); + return std::max(1, std::min((int64_t)keep, V)); +} +/* The most tiles a step has (the prompt's and the soundtrack's chunks, then the video's boxes) and + * the most a video query keeps, over every size at the longest length. */ +static void vsa_bounds(double sparsity, int64_t* tiles, int64_t* keep) { + int64_t best = 0; + for (int64_t w = kMinSide; w <= (int64_t)kMaxArea / kMinSide; w += kMult) + for (int64_t h = kMinSide; h * w <= kMaxArea; h += kMult) + if (size_ok(w, h)) + best = std::max(best, vsa_video_tiles(max_lat_frames(), h / (kScale * kPatch), + w / (kScale * kPatch))); + const int64_t prefix = ((int64_t)kMaxText + kVsaRows - 1) / kVsaRows + + (kAudioCh * max_audio() + kVsaRows - 1) / kVsaRows; + *tiles = prefix + best; + *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. */ +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; +} + +/* A decode pass's rows: every tile of the frame, each kPeriod rows. */ +static int64_t decode_rows(const RadVideoGeom* g) { + if (!g || g->lat_h < kTile || g->lat_w < kTile) return RAD_E_INVAL; + return tiles_of(g->lat_h, g->lat_w) * kPeriod; +} + +/* ================================================================== the model's parts */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +/* A token refiner block: a plain pre-norm transformer block, no rotary, no modulation. */ +struct RefBlock { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkn = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +/* A DiT block. Its two modulated norms carry the gated residual in front of them: the first the + * previous block's MLP branch (none for block 0), the second this block's attention branch. */ +struct DitBlock { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_attn{}; + GateQuantFP8 gq{}; + rad_op op_mq1 = 0, op_mq2 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_ar2 = 0; + 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. */ + DenseFP8 ada[3]; + rad_weight ada_b[3] = {}; + rad_op op_ada[3] = {}; +}; + +/* A video decoder block. */ +struct VitBlock { + rad_weight w_n1 = 0, w_n2 = 0, w_qkv = 0, b_qkv = 0, w_o = 0, b_o = 0; + rad_weight w_up = 0, b_up = 0, w_down = 0, b_down = 0, s1 = 0, s2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_qkr = 0, op_attn = 0, op_o = 0, op_s1 = 0, op_r1 = 0; + rad_op op_n2 = 0, op_up = 0, op_act = 0, op_down = 0, op_s2 = 0, op_r2 = 0; +}; + +/* An audio decoder convolution (weight-normalised in the checkpoint, folded at convert). */ +struct AConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +/* An anti-aliased SnakeBeta. */ +struct AAct { + rad_weight alpha = 0, beta = 0, up = 0, down = 0; + rad_op op = 0; +}; +/* One dilation of an AMP block: act, dilated conv, act, conv with the residual. */ +struct AmpUnit { + AAct a1{}, a2{}; + AConv c1{}, c2{}; +}; +struct AmpBlock { + AmpUnit u[3]; +}; +struct AStage { + AConv up{}; + rad_op op_cu = 0; + AmpBlock amp[3]; + rad_op op_sum = 0, op_avg = 0; + int64_t ch = 0, rate = 0, k = 0; +}; + +/* Weight groups (movement units) by network: the text encoder's layers 0.., the refiner, the + * timestep MLP with norm_out's projection, the DiT's model-level weights and its blocks after + * them, each block's modulation projections, the decoders. A unit takes the strongest access class + * of its weights, so what is read once a request (the modulation, the timestep MLP) is never + * grouped with what a step reads: that would keep it off the tower placement. */ +enum : int { + kGrpRefiner = 1000, + kGrpTemb = 1010, + kGrpDit = 2000, + kGrpAda = 2200, + kGrpVae = 3000, + kGrpAudio = 3100, +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}, gr{}; /* text encoder, DiT (step rows), refiner (prompt rows) */ + int64_t D = 0, S = kMaxSteps; + int64_t W = 1, Ws = 0; /* ranks, and a rank's share of a modality's six vectors */ + int64_t maxV = 0, maxA = 0; /* a lane's video and soundtrack latent rows */ + int64_t tiles = 0, tpr = 0; /* the most tiles a decode carries, and a rank's share of them */ + + /* ---- the text encoder */ + rad_weight w_tok = 0; + rad_op op_embed = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- 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; + rad_buf b_rh = 0, b_rqkv = 0, b_rao = 0, b_rgu = 0; + 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; + QuantFP8 q_temb{}; + rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0; + ActFP8 a_temb{}; + + /* ---- the lanes (PERSIST) */ + rad_buf b_text = 0; /* [lanes * kMaxText, D] bf16: the refined prompt */ + rad_buf b_ada = 0; /* [lanes * S, 150 * Ws] bf16: the modulation table */ + 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_prev = 0; /* [lanes * 5 * area, 3] bf16: the decoder's frames across chunks */ + + /* ---- the DiT */ + rad_op op_rnd_v = 0, op_rnd_a = 0, op_modg = 0, op_text = 0, op_ain = 0, op_vin = 0; + rad_weight w_ain = 0, b_ain = 0, w_vin = 0, b_vin = 0; + rad_buf b_modg = 0; /* [W * 150, Ws] bf16: this step's table, every rank's share */ + /* Video sparse attention (a checkpoint distilled with it): the dropped share of a video + * query's video tiles, the most tiles a step has and the most a query keeps, and the per-layer + * selection and pooled-tile attention, [heads, tiles, k] i32 and [heads, tiles, head_dim]. */ + bool vsa = false; + double vsa_sparsity = 0.0; + int64_t vsa_tiles = 0, vsa_k = 0; + rad_buf b_sel = 0, b_coarse = 0; + rad_buf b_k8 = 0, b_ks = 0; /* the attention's keys at int8 codes and their scales */ + 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; + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + 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; + + /* ---- the audio decoder */ + std::string a_mean, a_std; + rad_op op_adenorm = 0, op_acu0 = 0, op_vmix = 0; + AConv a_in{}, a_pre{}, a_post{}; + AAct a_actpost{}; + AStage ast[7]; + int64_t a_rows[8] = {}; + rad_buf b_aden = 0, b_ain0 = 0, b_acu[8] = {}, b_ah[8] = {}, b_aavg[8] = {}, b_aamp[3][8] = {}; + rad_buf b_at1[8] = {}, b_at2[8] = {}, b_aout0 = 0, b_audio = 0; + + /* ---- the video decoder */ + std::string v_mean, v_std; + rad_op op_unfold = 0, op_pqc = 0, op_vpin = 0, op_tiles = 0, op_dpos = 0, op_dcu = 0; + rad_op op_vnorm = 0, op_vproj = 0, op_vgather = 0, op_stitch = 0; + rad_weight w_pqc = 0, b_pqc = 0, w_vpin2 = 0, b_vpin2 = 0, w_reg = 0; + rad_weight w_vno = 0, b_vno = 0, w_vpo = 0, b_vpo = 0; + rad_buf b_vox = 0, b_vox2 = 0, b_vpin = 0, b_vx = 0, b_dpos = 0, b_dcu = 0, b_vn = 0; + rad_buf b_vqkv = 0, b_vattn = 0, b_vo = 0, b_vt = 0, b_vup = 0, b_vact = 0; + rad_buf b_vpix = 0, b_vpix_all = 0, b_frames = 0; + std::vector vit; +}; + +static Model g_model[MAX_RANKS]; + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static std::string join_list(const std::vector& v) { + std::string s; + for (size_t i = 0; i < v.size(); ++i) { + char t[40]; + std::snprintf(t, sizeof t, "%s%.9g", i ? " " : "", v[i]); + s += t; + } + return s; +} + +/* A weight copied as the checkpoint holds it, under `group`, read whole on every rank. */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A linear with a bias, `gemm_nt_bias` at `dtype` (bf16 or f32), read whole on every rank. */ +static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* src, uint32_t wdt, + const char* dtype, int64_t N, int64_t K, int64_t rows, rad_buf in, + rad_buf out, rad_weight* w, rad_weight* bias, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), wdt, { N, K }, access, group); + *bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), wdt, { N }, access, group); + if (!*w || !*bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", dtype)), + RAD_WEIGHTS(*w, *bias)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, const char* dtype, + rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, const char* dtype, rad_buf a, rad_buf c, + rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +/* (a + b) / div, each step rounded to y's dtype. */ +static rad_op add_div_op(RadBuilder* b, int64_t rows, int64_t n, const char* dtype, rad_buf a, + rad_buf c, rad_buf y, double div) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", dtype), + RAD_F64("div", div)), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op rmsnorm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +/* `overlap`: issued on the second lane beside compute, which picks a narrow launch. */ +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows, int64_t n, + const char* dtype = "bf16", bool overlap = false) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n), + RAD_STR("dtype", dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes), + RAD_INT("overlap", overlap ? 1 : 0)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* cls = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strcmp(cls, "MiniMaxH3ModularPipeline") != 0 && + std::strcmp(cls, "MiniMaxH3Pipeline") != 0) { + fprintf(stderr, "radiance: minimaxh3: the container's pipeline is '%s', not " + "MiniMaxH3ModularPipeline\n", cls); + return RAD_E_UNSUPPORTED; + } + const int64_t ps[3] = { rad_meta_geti(meta, "transformer.patch_size.0", 1), + rad_meta_geti(meta, "transformer.patch_size.1", 2), + rad_meta_geti(meta, "transformer.patch_size.2", 2) }; + const std::vector pl = meta_list(meta, "transformer.patch_size"); + const double pp = (double)kPatch; + const bool patch_ok = pl.size() == 3 ? pl[0] == 1.0 && pl[1] == pp && pl[2] == pp + : ps[0] == 1 && ps[1] == kPatch && ps[2] == kPatch; + if (!patch_ok || rad_meta_geti(meta, "transformer.in_channels", 0) != kC || + rad_meta_geti(meta, "transformer.audio_in_channels", 0) != kAudioC || + rad_meta_geti(meta, "transformer.rope_freq_dim", 0) != 16 || + rad_meta_geti(meta, "vae.latent_channels", 0) != kC || + rad_meta_geti(meta, "vae.clip_length", 0) != kFpc || + rad_meta_geti(meta, "vae.token_drop", 0) != 3 || + rad_meta_geti(meta, "audio_vae.latent_channels", 0) != kAudioC || + rad_meta_geti(meta, "audio_vae.sampling_rate", 0) != kRate) { + fprintf(stderr, "radiance: minimaxh3: the transformer, video VAE or audio VAE is not the " + "released geometry (patch 1x2x2, 24 + 32 latent channels, 17-frame " + "chunks, 32 kHz)\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== the text encoder */ +/* Qwen3-VL's language model, its first kTextLayers layers: plain RMSNorm gains, q/k head norms, + * SwiGLU. Its interleaved M-RoPE turns each frequency by one of three position components; a text + * token's three are one position, which makes it NeoX's rotary over the whole head, declared as + * such. Read once a request. */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = g.max_tok; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int acc = RAD_ACCESS_PER_REQUEST; + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens.weight"))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff)); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + + m.te.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + TeLayer& L = m.te[(size_t)l]; + const int li = (int)l; + const char* pre = "model.language_model.layers"; + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", li), + nm.ckpt("%s.%d.input_layernorm.weight", pre, li), RAD_F32, { g.n_embd }, acc, li); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", li), + nm.ckpt("%s.%d.post_attention_layernorm.weight", pre, li), RAD_F32, + { g.n_embd }, acc, li); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", li), + nm.ckpt("%s.%d.self_attn.q_norm.weight", pre, li), RAD_BF16, { g.head_dim }, + acc, li); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", li), + nm.ckpt("%s.%d.self_attn.k_norm.weight", pre, li), RAD_BF16, { g.head_dim }, + acc, li); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rmsnorm_op(b, T, g.n_embd, g.eps, L.w_n1, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + L.qkv.access = acc; + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", li), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_ROW, grp_layer(li), + { nm.ckpt("%s.%d.self_attn.q_proj.weight", pre, li), + nm.ckpt("%s.%d.self_attn.k_proj.weight", pre, li), + nm.ckpt("%s.%d.self_attn.v_proj.weight", pre, li) }, + m.a_th, m.b_tkv, 0, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "neox"), + RAD_INT("rotary_dim", g.head_dim)), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + L.o.access = acc; + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", li), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(li), + { nm.ckpt("%s.%d.self_attn.o_proj.weight", pre, li) }, + m.a_tattn, m.b_th2)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T, g.n_embd); + L.op_add1 = add_op(b, T, g.n_embd, "bf16", m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rmsnorm_op(b, T, g.n_embd, g.eps, L.w_n2, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + L.gate_up.access = acc; + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", li), 2 * g.n_ff, + g.n_embd, RAD_SHARD_ROW, grp_layer(li), + { nm.ckpt("%s.%d.mlp.gate_proj.weight", pre, li), + nm.ckpt("%s.%d.mlp.up_proj.weight", pre, li) }, + m.a_th, m.b_tgu, 0, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", 0, true)); + L.down.access = acc; + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", li), g.n_embd, g.n_ff, + RAD_SHARD_COL, grp_layer(li), + { nm.ckpt("%s.%d.mlp.down_proj.weight", pre, li) }, + m.a_tffn, m.b_th2)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T, g.n_embd); + L.op_add2 = add_op(b, T, g.n_embd, "bf16", m.b_tx, m.b_th2, m.b_tx); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2) + return RAD_E_INVAL; + } + return m.op_embed ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the token refiner */ +/* `context_embedder` (5120 -> 5376, bf16, replicated), two plain blocks with full attention over + * the prompt and no rotary, and the final RMSNorm into the lane's prompt rows. The feed-forward is + * diffusers' SwiGLU, `value * silu(gate)` with the value first in the checkpoint; the gate half is + * moved first at convert, which is the order `silu_mul` reads. */ +static int declare_refiner(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gr; + Names& nm = m.nm; + const int64_t T = g.max_tok, D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const int acc = RAD_ACCESS_PER_REQUEST; + const int gx = kGrpRefiner; + const double eps = rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + const double qk_eps = rad_meta_getf(meta, "transformer.qk_norm_eps", 1e-5); + const int64_t tdim = rad_meta_geti(meta, "transformer.text_dim", 5120); + if (tdim != m.gt.n_embd) { + fprintf(stderr, "radiance: minimaxh3: the DiT reads %lld-wide conditioning and the text " + "encoder writes %lld\n", (long long)tdim, (long long)m.gt.n_embd); + return RAD_E_INVAL; + } + + m.b_rh = decl_b(b, nm.f("ref.h"), RAD_BF16, { T, D }); + m.op_ce = dense_bias(b, nm, "ref.ctx", "transformer.context_embedder", RAD_BF16, "bf16", D, + tdim, T, m.b_tx, m.b_rh, &m.w_ce, &m.b_ce, acc, gx); + m.a_rh.x = decl_b(b, nm.f("ref.hn"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_rh.declare_qs(b, nm, g, "ref.hn", D)); + m.b_rqkv = decl_b(b, nm.f("ref.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_rattn.x = decl_b(b, nm.f("ref.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_rattn.declare_qs(b, nm, g, "ref.attn", qd)); + m.b_rao = decl_b(b, nm.f("ref.ao"), RAD_BF16, { T, D }); + m.b_rgu = decl_b(b, nm.f("ref.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_rffn.x = decl_b(b, nm.f("ref.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_rffn.declare_qs(b, nm, g, "ref.ffn", g.n_ff)); + const int64_t ff_all = g.n_ff_all; + + for (int l = 0; l < 2; ++l) { + RefBlock& R = m.rb[l]; + const char* pre = nm.ckpt("transformer.token_refiner.refiner_blocks.%d", l); + const char* dn = nm.f("ref.blk.%d", l); + R.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_BF16, + { D }, acc, gx); + R.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_BF16, + { D }, acc, gx); + R.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), + RAD_BF16, { hd }, acc, gx); + R.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), + RAD_BF16, { hd }, acc, gx); + if (!R.w_n1 || !R.w_n2 || !R.w_qn || !R.w_kn) return RAD_E_INVAL; + R.op_n1 = rmsnorm_op(b, T, D, eps, R.w_n1, m.b_rh, m.a_rh.x); + RAD_ARCH_TRY(R.q_h.declare(b, g, m.a_rh, D)); + R.qkv.access = acc; + RAD_ARCH_TRY(R.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(gx), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_rh, m.b_rqkv, 0, { qd, qd, qd })); + R.op_qkn = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", 10000.0), RAD_F64("eps", qk_eps), + RAD_INT("rotary_dim", 0)), + RAD_WEIGHTS(R.w_qn, R.w_kn)), + { m.b_rqkv }, { m.b_rqkv }); + R.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", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_rqkv }, { m.a_rattn.x }); + RAD_ARCH_TRY(R.q_attn.declare(b, g, m.a_rattn, qd)); + R.o.access = acc; + RAD_ARCH_TRY(R.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(gx), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_rattn, m.b_rao)); + R.op_ar1 = all_reduce(b, g, m.b_rao, T, D); + R.op_add1 = add_op(b, T, D, "bf16", m.b_rh, m.b_rao, m.b_rh); + R.op_n2 = rmsnorm_op(b, T, D, eps, R.w_n2, m.b_rh, m.a_rh.x); + RAD_ARCH_TRY(R.q_h2.declare(b, g, m.a_rh, D)); + const char* fw = nm.f("%s.ffn_gate_up.weight", dn); + const char* fsrc = nm.ckpt("%s.ff.net.0.proj.weight", pre); + RAD_ARCH_TRY(map_rows(b, fw, { { fsrc, (int)ff_all, ff_all }, { fsrc, 0, ff_all } })); + R.gate_up.mapped = true; + R.gate_up.access = acc; + RAD_ARCH_TRY(R.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D, + RAD_SHARD_ROW, grp_layer(gx), { fsrc }, m.a_rh, m.b_rgu, 0, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(R.gq.declare(b, g, m.b_rgu, m.a_rffn, g.n_ff, "silu", 0, true)); + R.down.access = acc; + RAD_ARCH_TRY(R.down.declare(b, nm, g, nm.f("%s.ffn_down", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(gx), { nm.ckpt("%s.ff.net.2.weight", pre) }, + m.a_rffn, m.b_rao)); + R.op_ar2 = all_reduce(b, g, m.b_rao, T, D); + R.op_add2 = add_op(b, T, D, "bf16", m.b_rh, m.b_rao, m.b_rh); + if (!R.op_n1 || !R.op_qkn || !R.op_attn || !R.op_add1 || !R.op_n2 || !R.op_add2) + return RAD_E_INVAL; + } + m.w_fn = wcopy(b, nm.f("ref.final_norm.weight"), + nm.ckpt("transformer.token_refiner.final_norm.weight"), RAD_BF16, { D }, acc, gx); + if (!m.w_fn) return RAD_E_INVAL; + m.op_fn = rmsnorm_op(b, T, D, rad_meta_getf(meta, "transformer.final_norm_eps", 1e-5), m.w_fn, + m.b_rh, m.b_text); + return m.op_ce && m.op_fn ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the per-step tables */ +/* The timestep embedding of every step's two timesteps -- rows [0, S) the video's, [S, 2S) the + * soundtrack's -- through the f32 timestep MLP, then silu, rounded to bf16 as the bf16 projections + * read it, and quantised for the modulation projections. Each block's modulation for segment e is + * its modality's projection of its timestep's row, into the lane's table at column block + * (l, e); norm_out's shift and scale are the same of norm_out's own projection, by timestep. */ +static int declare_tables(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const Geom& g = m.gd; + const int64_t S = m.S, D = m.D, L = g.n_layer; + 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 int acc = RAD_ACCESS_PER_REQUEST; + const int gx = kGrpTemb; + if (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; + + /* The lane's tables. */ + m.b_ada = decl_b(b, nm.f("lane.ada"), RAD_BF16, { (int64_t)kMaxLanes * S, L * kSegs * m.Ws }, + RAD_BUF_PERSIST); + m.b_nout = decl_b(b, nm.f("lane.nout"), RAD_BF16, { (int64_t)kMaxLanes * S, kSegs * 2 * D }, + RAD_BUF_PERSIST); + const int64_t ada_rows = 6 * D; /* one modality's six vectors */ + m.dit.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + DitBlock& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpAda + li; + const char* src_w = nm.ckpt("transformer.transformer_blocks.%d.adaln_proj.linear.weight", li); + const char* src_b = nm.ckpt("transformer.transformer_blocks.%d.adaln_proj.linear.bias", li); + for (int md = 0; md < 3; ++md) { + const char* base = nm.f("dit.blk.%d.ada%d", li, md); + const char* wn = nm.f("%s.weight", base); + 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 } })); + B.ada[md].mapped = true; + RAD_ARCH_TRY(B.ada[md].declare(b, nm, base, m.Ws, td, acc, RAD_SHARD_ROW, + grp_layer(grp), { src_w })); + 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 (!B.op_ada[md]) return RAD_E_INVAL; + } + } + m.op_no = dense_bias(b, nm, "dit.nout.lin", "transformer.norm_out.linear", RAD_BF16, "bf16", + 2 * D, td, S, m.a_temb.x, m.b_nout, &m.w_no, &m.b_no, acc, gx); + return m.op_no ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the DiT */ +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok, D = g.n_embd, qd = g.q_dim(), hd = g.head_dim, L = g.n_layer; + const double eps = rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + const double qk_eps = rad_meta_getf(meta, "transformer.qk_norm_eps", 1e-5); + const double theta = rad_meta_getf(meta, "transformer.rope_theta", 10000.0); + const int64_t rf = rad_meta_geti(meta, "transformer.rope_freq_dim", 16); + const int gx = kGrpDit; + const int64_t La = (int64_t)kMaxLanes; + + /* ---- 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.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")), + RAD_NOWEIGHTS), + { m.b_vstate }, { m.b_vstate }); + m.op_rnd_a = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxA), RAD_INT("n", kAudioC), + RAD_INT("stride", m.maxA), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { 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 }); + if (g.world > 1) + m.op_modg = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 1, row), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ada }, { m.b_modg }); + else + m.op_modg = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", row), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_ada }, { m.b_modg }); + + /* ---- 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 }); + 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), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_text }, { m.b_h }); + m.op_ain = dense_bias(b, nm, "dit.audio_in", "transformer.audio_proj_in", RAD_F32, "f32", D, + kAudioC, m.maxA, m.b_astate, m.b_h, &m.w_ain, &m.b_ain, + RAD_ACCESS_PER_TOKEN, gx); + m.op_vin = dense_bias(b, nm, "dit.video_in", "transformer.proj_in", RAD_F32, "f32", D, + kPatchVals, m.maxV, m.b_vstate, m.b_h, &m.w_vin, &m.b_vin, + RAD_ACCESS_PER_TOKEN, gx); + if (!m.op_rnd_v || !m.op_rnd_a || !m.op_modg || !m.op_text || !m.op_ain || !m.op_vin) + return RAD_E_INVAL; + + /* ---- the blocks */ + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + /* 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; + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, nparts * qd }); + if (m.vsa) { + m.b_sel = decl_b(b, nm.f("dit.vsa_sel"), RAD_I32, { g.n_head, m.vsa_tiles, m.vsa_k }); + m.b_coarse = decl_b(b, nm.f("dit.vsa_coarse"), RAD_BF16, { g.n_head, m.vsa_tiles, hd }); + } + m.b_k8 = decl_b(b, nm.f("dit.k8"), RAD_I8, { T, qd }); + m.b_ks = decl_b(b, nm.f("dit.ks"), RAD_F32, { T, qd / hd }); + 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)); + 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)); + 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; + + auto mod_q = [&](rad_weight w, bool gated) { + rad_op op = RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("gated", gated ? 1 : 0), + RAD_STR("dtype", "bf16")), + RAD_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_op_writes(b, op, wr, 3); + return op; + }; + + for (int64_t l = 0; l < L; ++l) { + DitBlock& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpDit + 1 + li; + const char* pre = nm.ckpt("transformer.transformer_blocks.%d", li); + const char* dn = nm.f("dit.blk.%d", li); + const int acc = RAD_ACCESS_PER_TOKEN; + B.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_BF16, + { D }, acc, grp); + B.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_BF16, + { D }, acc, grp); + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), + RAD_BF16, { hd }, acc, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), + RAD_BF16, { hd }, acc, grp); + if (!B.w_n1 || !B.w_n2 || !B.w_qn || !B.w_kn) return RAD_E_INVAL; + B.op_mq1 = mod_q(B.w_n1, l > 0); + if (m.vsa) + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 4 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre), + nm.ckpt("%s.attn.to_gate_compress.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, qd, qd, qd })); + else + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, qd, qd })); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", theta), RAD_F64("eps", qk_eps), + RAD_STR("mode", "axial"), RAD_INT("rotary_dim", 6 * rf), + RAD_STR("sections", sections)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + /* The keys to int8 codes and scales per (row, head) for the attention's scores. */ + B.op_kq = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", qd), + RAD_INT("group", hd), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.b_k8, m.b_ks }); + /* The values to E4M3 with a scale per column (one dimension of one head), for P.V on + * the fp8 matrix instruction. */ + B.op_vq = rw(b, RAD_OP(b, "quant_cols_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", qd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.b_v8, m.b_vs }); + if (m.vsa) { + /* Tiles of the packed sequence: each query tile's best video tiles by pooled score + * and the softmax over every tile's pooled keys, then attention over the kept tiles + * with that pooled term gated in. */ + B.op_sel = rw(b, RAD_OP(b, "vsa_select", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("tile_t", kVsaT), RAD_INT("tile_h", kVsaH), + RAD_INT("tile_w", kVsaW), RAD_INT("patch", kPatch), + RAD_F64("sparsity", m.vsa_sparsity), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.b_sel, m.b_coarse }); + /* The kept tiles' scores in int8, as the dense form below takes them. */ + B.op_attn = rw(b, RAD_OP(b, "attn_vsa", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("tile_t", kVsaT), RAD_INT("tile_h", kVsaH), + RAD_INT("tile_w", kVsaW), RAD_INT("patch", kPatch), + RAD_F64("sparsity", m.vsa_sparsity), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_STR("qk", "i8"), RAD_STR("pv", "fp8")), + RAD_NOWEIGHTS), + { m.b_qkv, m.b_sel, m.b_coarse, m.b_k8, m.b_ks, m.b_v8, m.b_vs }, + { m.a_attn.x }); + if (!B.op_sel) return RAD_E_INVAL; + } else { + /* Dense attention with int8 scores: the keys quantised per (row, head) by + * quant_act_i8g, the query inside the op, the score an exact integer product times + * both scales, P.V in bf16. The prefix-free form of attn_prefix_self, the op that + * carries the int8 form. */ + B.op_attn = rw(b, RAD_OP(b, "attn_prefix_self", + RAD_PARAMS(RAD_INT("q_len", T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("block_size", 16), + RAD_INT("causal", 0), RAD_STR("q_dtype", "bf16"), + RAD_STR("kv_dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_ctx", 0), RAD_INT("n_head", g.n_head), + RAD_INT("max_seqs", 1), RAD_STR("qk", "i8"), + RAD_STR("pv", "fp8")), + RAD_NOWEIGHTS), + { m.b_qkv, m.b_k8, m.b_ks, m.b_v8, m.b_vs }, { m.a_attn.x }); + } + if (!B.op_kq || !B.op_vq) return RAD_E_INVAL; + RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_attn, m.b_ao)); + B.op_ar1 = all_reduce(b, g, m.b_ao, std::min(T, kArRows), D, "bf16", true); + 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); + 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 })); + 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) }, + m.a_ffn, m.b_ao)); + B.op_ar2 = all_reduce(b, g, m.b_ao, std::min(T, kArRows), D, "bf16", true); + if (!B.op_mq1 || !B.op_mq2 || !B.op_qkr || !B.op_attn) return RAD_E_INVAL; + } + + /* ---- the output: norm_out's modulated norm (the last block's branch gated in), the heads in + * f32 over parts of the rows, and the two Euler steps into the lane */ + m.b_hn = decl_b(b, nm.f("dit.hn"), RAD_BF16, { T, D }); + m.w_no_n = wcopy(b, nm.f("dit.nout.norm.weight"), nm.ckpt("transformer.norm_out.norm.weight"), + RAD_BF16, { D }, RAD_ACCESS_PER_TOKEN, gx); + if (!m.w_no_n) return RAD_E_INVAL; + { + rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_F64("eps", rad_meta_getf(meta, "transformer.final_norm_eps", + 1e-5)), + RAD_INT("gated", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_no_n)); + if (!op) return RAD_E_INVAL; + rad_buf rd[4] = { m.b_ao, m.b_modg, m.b_nout, m.b_h }; + rad_buf wr[2] = { m.b_hn, m.b_h }; + rad_op_reads(b, op, rd, 4); + rad_op_writes(b, op, wr, 2); + m.op_nout = op; + } + m.b_hf = decl_b(b, nm.f("dit.hf"), RAD_F32, { (int64_t)kHeadRows, D }); + m.op_hcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kHeadRows), RAD_INT("n", D), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_hn }, { m.b_hf }); + m.b_vel = decl_b(b, nm.f("dit.vel"), RAD_F32, { m.maxV, kPatchVals }); + m.b_avel = decl_b(b, nm.f("dit.avel"), RAD_F32, { m.maxA, kAudioC }); + m.op_vout = dense_bias(b, nm, "dit.video_out", "transformer.proj_out", RAD_F32, "f32", + kPatchVals, D, kHeadRows, m.b_hf, m.b_vel, &m.w_vout, &m.b_vout, + RAD_ACCESS_PER_TOKEN, gx); + m.op_aout = dense_bias(b, nm, "dit.audio_out", "transformer.audio_proj_out", RAD_F32, "f32", + kAudioC, D, kHeadRows, m.b_hf, m.b_avel, &m.w_aout, &m.b_aout, + RAD_ACCESS_PER_TOKEN, gx); + /* The cast and the two heads are issued in a loop over parts of the rows, the cast again after + * a head has run, so the normed rows outlive both heads: declared as read by them, their + * storage is never the velocities'. */ + if (m.op_vout && m.op_aout) { + RAD_ARCH_TRY(rad_op_reads(b, m.op_vout, &m.b_hn, 1)); + RAD_ARCH_TRY(rad_op_reads(b, m.op_aout, &m.b_hn, 1)); + } + m.op_ev = rw(b, RAD_OP(b, "flow_x0_step", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxV), RAD_INT("n", kPatchVals), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_vel, m.b_vstate }, { m.b_vstate }); + m.op_ea = rw(b, RAD_OP(b, "flow_x0_step", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxA), RAD_INT("n", kAudioC), + 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; +} + +/* ================================================================== the audio decoder */ +/* A weight-normalised convolution's folded weight and its bias (none for conv_post). */ +static int aconv(RadBuilder* b, Names& nm, AConv& c, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, bool wnorm, bool bias, int64_t rows, rad_buf x, + rad_buf cu, rad_buf res, rad_buf y, const char* act) { + const char* wn = nm.f("%s.weight", dn); + if (wnorm) RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.weight_g", src), nm.ckpt("%s.weight_v", src))); + else RAD_ARCH_TRY(map_copy(b, wn, nm.ckpt("%s.weight", src))); + c.w = decl_w(b, wn, RAD_F32, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpAudio)); + if (bias) + c.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_F32, { cout }, + RAD_ACCESS_PER_TOKEN, kGrpAudio); + if (!c.w || (bias && !c.b)) return RAD_E_INVAL; + rad_op op = bias ? RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("dil", dil), + RAD_STR("act", act), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(c.w, c.b)) + : RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("dil", dil), + RAD_STR("act", act), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(c.w)); + c.op = res ? rw(b, op, { x, cu, res }, { y }) : rw(b, op, { x, cu }, { y }); + return c.op ? RAD_OK : RAD_E_INVAL; +} + +/* An anti-aliased SnakeBeta: its log-space alpha and beta, and the two Kaiser filters. */ +static int aact(RadBuilder* b, Names& nm, AAct& a, const char* dn, const char* src, int64_t ch, + int64_t rows, rad_buf x, rad_buf cu, rad_buf y) { + a.alpha = wcopy(b, nm.f("%s.alpha", dn), nm.ckpt("%s.act.alpha", src), RAD_F32, { ch }, + RAD_ACCESS_PER_TOKEN, kGrpAudio); + a.beta = wcopy(b, nm.f("%s.beta", dn), nm.ckpt("%s.act.beta", src), RAD_F32, { ch }, + RAD_ACCESS_PER_TOKEN, kGrpAudio); + a.up = wcopy(b, nm.f("%s.up", dn), nm.ckpt("%s.upsample.filter", src), RAD_F32, { 1, 1, 12 }, + RAD_ACCESS_PER_TOKEN, kGrpAudio); + a.down = wcopy(b, nm.f("%s.down", dn), nm.ckpt("%s.downsample.lowpass.filter", src), RAD_F32, + { 1, 1, 12 }, RAD_ACCESS_PER_TOKEN, kGrpAudio); + if (!a.alpha || !a.beta || !a.up || !a.down) return RAD_E_INVAL; + a.op = rw(b, RAD_OP(b, "snake_aa", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", ch), RAD_INT("ratio", 2), + RAD_INT("k", 12), RAD_INT("log", 1), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(a.alpha, a.beta, a.up, a.down)), + { x, cu }, { y }); + return a.op ? RAD_OK : RAD_E_INVAL; +} + +static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf y) { + return rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_INT("mult", mult)), + RAD_NOWEIGHTS), + {}, { y }); +} + +/* dec_in_proj and BigVGAN over the soundtrack's two channels, each a sequence (`cu`); every stage + * an upsampling transposed convolution and the mean of three AMP blocks (kernel 3, 7 and 11), each + * three dilations of act, dilated conv, act, conv and the residual. */ +static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const std::vector rates = meta_list(meta, "audio_vae.decoder_rates"); + const std::vector ks = meta_list(meta, "audio_vae.decoder_kernel_sizes"); + const std::vector rk = meta_list(meta, "audio_vae.resblock_kernel_sizes"); + const int64_t dd = rad_meta_geti(meta, "audio_vae.decoder_dim", 1024); + 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"); + int64_t hop = 1; + for (double r : rates) hop *= (int64_t)r; + if (rates.size() != 7 || ks.size() != 7 || rk.size() != 3 || hop != kRate / kAudioRate || + (int64_t)mean.size() != kAudioC || (int64_t)sd.size() != kAudioC) { + fprintf(stderr, "radiance: minimaxh3: the audio VAE is not the released BigVGAN (7 stages " + "to 800 samples a latent, three AMP kernels)\n"); + return RAD_E_UNSUPPORTED; + } + static const int64_t kDil[3] = { 1, 3, 5 }; + m.a_mean = join_list(mean); + m.a_std = join_list(sd); + m.a_rows[0] = m.maxA; + for (int s = 0; s < 7; ++s) m.a_rows[s + 1] = m.a_rows[s] * (int64_t)rates[(size_t)s]; + + m.b_aden = decl_b(b, nm.f("aud.den"), RAD_F32, { m.maxA, kAudioC }); + m.op_adenorm = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxA), RAD_INT("n", kAudioC), + RAD_STR("mul", m.a_std.c_str()), + RAD_STR("add", m.a_mean.c_str()), RAD_STR("mode", "fma"), + RAD_INT("round", 0), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_astate }, { m.b_aden }); + for (int s = 0; s < 8; ++s) m.b_acu[s] = decl_b(b, nm.f("aud.cu%d", s), RAD_I32, { 3 }); + m.op_acu0 = cu_op(b, 1, m.b_acu[0]); + m.b_ain0 = decl_b(b, nm.f("aud.in"), RAD_F32, { m.maxA, ld }); + RAD_ARCH_TRY(aconv(b, nm, m.a_in, "aud.in_proj", "audio_vae.dec_in_proj", kAudioC, ld, 1, 1, + false, true, m.maxA, m.b_aden, m.b_acu[0], 0, m.b_ain0, "none")); + m.b_aavg[0] = decl_b(b, nm.f("aud.h0"), RAD_F32, { m.maxA, dd }); + RAD_ARCH_TRY(aconv(b, nm, m.a_pre, "aud.conv_pre", "audio_vae.decoder.conv_pre", ld, dd, 7, 1, + true, true, m.maxA, m.b_ain0, m.b_acu[0], 0, m.b_aavg[0], "none")); + int64_t mult = 1; + for (int s = 0; s < 7; ++s) { + AStage& St = m.ast[s]; + const int64_t ci = dd >> s, co = dd >> (s + 1), R = m.a_rows[s + 1]; + St.ch = co; + St.rate = (int64_t)rates[(size_t)s]; + St.k = (int64_t)ks[(size_t)s]; + mult *= St.rate; + St.op_cu = cu_op(b, mult, m.b_acu[s + 1]); + m.b_ah[s + 1] = decl_b(b, nm.f("aud.s%d.in", s), RAD_F32, { R, co }); + const char* wn = nm.f("aud.s%d.up.weight", s); + const char* src = nm.ckpt("audio_vae.decoder.ups.%d.0", s); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.weight_g", src), nm.ckpt("%s.weight_v", src))); + St.up.w = decl_w(b, wn, RAD_F32, { ci, co, St.k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpAudio)); + St.up.b = wcopy(b, nm.f("aud.s%d.up.bias", s), nm.ckpt("%s.bias", src), RAD_F32, { co }, + RAD_ACCESS_PER_TOKEN, kGrpAudio); + if (!St.up.w || !St.up.b) return RAD_E_INVAL; + St.up.op = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, m.a_rows[s]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", St.rate), + RAD_INT("k", St.k), RAD_INT("pad", (St.k - St.rate) / 2), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(St.up.w, St.up.b)), + { m.b_aavg[s], m.b_acu[s] }, { m.b_ah[s + 1] }); + if (!St.up.op || !St.op_cu) return RAD_E_INVAL; + m.b_at1[s + 1] = decl_b(b, nm.f("aud.s%d.t1", s), RAD_F32, { R, co }); + m.b_at2[s + 1] = decl_b(b, nm.f("aud.s%d.t2", s), RAD_F32, { R, co }); + for (int j = 0; j < 3; ++j) m.b_aamp[j][s + 1] = decl_b(b, nm.f("aud.s%d.amp%d", s, j), RAD_F32, + { R, co }); + for (int j = 0; j < 3; ++j) { + AmpBlock& A = St.amp[j]; + const int64_t k = (int64_t)rk[(size_t)j]; + const int ri = s * 3 + j; + for (int d = 0; d < 3; ++d) { + AmpUnit& U = A.u[d]; + const char* bn = nm.f("aud.s%d.amp%d.d%d", s, j, d); + const char* bs = nm.ckpt("audio_vae.decoder.resblocks.%d", ri); + /* The unit reads the stage's input on its first dilation, its own running sum + * after. */ + const rad_buf x = d == 0 ? m.b_ah[s + 1] : m.b_aamp[j][s + 1]; + RAD_ARCH_TRY(aact(b, nm, U.a1, nm.f("%s.act1", bn), + nm.ckpt("%s.activations.%d", bs, 2 * d), co, R, x, m.b_acu[s + 1], + m.b_at1[s + 1])); + RAD_ARCH_TRY(aconv(b, nm, U.c1, nm.f("%s.conv1", bn), + nm.ckpt("%s.convs1.%d", bs, d), co, co, k, kDil[d], true, true, R, + m.b_at1[s + 1], m.b_acu[s + 1], 0, m.b_at2[s + 1], "none")); + RAD_ARCH_TRY(aact(b, nm, U.a2, nm.f("%s.act2", bn), + nm.ckpt("%s.activations.%d", bs, 2 * d + 1), co, R, m.b_at2[s + 1], + m.b_acu[s + 1], m.b_at1[s + 1])); + RAD_ARCH_TRY(aconv(b, nm, U.c2, nm.f("%s.conv2", bn), + nm.ckpt("%s.convs2.%d", bs, d), co, co, k, 1, true, true, R, + m.b_at1[s + 1], m.b_acu[s + 1], x, m.b_aamp[j][s + 1], "none")); + } + } + m.b_aavg[s + 1] = decl_b(b, nm.f("aud.s%d.out", s), RAD_F32, { R, co }); + St.op_sum = add_op(b, R, co, "f32", m.b_aamp[0][s + 1], m.b_aamp[1][s + 1], m.b_aavg[s + 1]); + St.op_avg = add_div_op(b, R, co, "f32", m.b_aavg[s + 1], m.b_aamp[2][s + 1], m.b_aavg[s + 1], + 3.0); + if (!St.op_sum || !St.op_avg) return RAD_E_INVAL; + } + const int64_t R7 = m.a_rows[7], c7 = dd >> 7; + RAD_ARCH_TRY(aact(b, nm, m.a_actpost, "aud.act_post", nm.ckpt("audio_vae.decoder.activation_post"), + c7, R7, m.b_aavg[7], m.b_acu[7], m.b_at1[7])); + m.b_aout0 = decl_b(b, nm.f("aud.mono"), RAD_F32, { R7, 1 }); + RAD_ARCH_TRY(aconv(b, nm, m.a_post, "aud.conv_post", "audio_vae.decoder.conv_post", c7, 1, 7, 1, + true, false, R7, m.b_at1[7], m.b_acu[7], 0, m.b_aout0, "clamp")); + m.b_audio = decl_b(b, nm.f("audio_out"), RAD_F32, { R7 / kAudioCh + 1, kAudioCh }, + RAD_BUF_PERSIST); + m.op_vmix = rw(b, RAD_OP(b, "interleave2", + RAD_PARAMS(RAD_RANGE("M", 1, R7 / kAudioCh), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_aout0 }, { m.b_audio }); + return m.op_adenorm && m.op_acu0 && m.op_vmix ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the video decoder */ +/* A decode pass is one chunk: latent frames [5 c, 5 c + 7) unpatchified out of the lane and + * denormalised, post_quant_conv and proj_in (f32) over every latent, then this rank's share of the + * tiles (7 x 16 x 16 latents, its registers and a zero token) through the ViT, its pixels gathered + * across ranks, and the tiles stitched into the chunk's frames. */ +static int declare_video(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int64_t dim = rad_meta_geti(meta, "vae.decoder_num_attention_heads", 32) * + rad_meta_geti(meta, "vae.decoder_attention_head_dim", 64); + const int64_t hd = rad_meta_geti(meta, "vae.decoder_attention_head_dim", 64); + const int64_t nl = rad_meta_geti(meta, "vae.decoder_num_layers", 36); + const int64_t ff = dim * rad_meta_geti(meta, "vae.decoder_ffn_mult", 4); + const double eps = rad_meta_getf(meta, "vae.decoder_norm_eps", 1e-5); + const double theta = rad_meta_getf(meta, "vae.decoder_rope_theta", 100.0); + const double ratio = rad_meta_getf(meta, "vae.decoder_rope_dim_ratio", 0.75); + const std::vector mean = meta_list(meta, "vae.latents_mean"); + const std::vector sd = meta_list(meta, "vae.latents_std"); + const int64_t rot = (int64_t)(hd * ratio); + const int64_t px = 3 * 4 * kScale * kScale; /* a token's pixels: 3 colours x 4 frames x 16^2 */ + if ((int64_t)mean.size() != kC || (int64_t)sd.size() != kC || rot % 6 || + rad_meta_geti(meta, "vae.decoder_num_register_tokens", 0) != kRegs) { + fprintf(stderr, "radiance: minimaxh3: the video VAE decoder is not the released ViT\n"); + return RAD_E_UNSUPPORTED; + } + m.v_mean = join_list(mean); + m.v_std = join_list(sd); + const int64_t maxhw = (int64_t)kMaxArea / (kScale * kScale); + const int64_t vox = (int64_t)kDecLat * maxhw; + const int64_t R = m.tpr * kPeriod; /* this rank's tile rows */ + const int64_t RA = (int64_t)m.W * R; /* every rank's, gathered */ + const int gv = kGrpVae; + const int acc = RAD_ACCESS_PER_TOKEN; + + m.b_vox = decl_b(b, nm.f("vae.vox"), RAD_F32, { vox, kC }); + m.op_unfold = rw(b, RAD_OP(b, "patch_unfold", + RAD_PARAMS(RAD_RANGE("M", 1, vox), RAD_INT("C", kC), RAD_INT("pt", 1), + RAD_INT("ph", kPatch), RAD_INT("pw", kPatch), + RAD_STR("mul", m.v_std.c_str()), + RAD_STR("add", m.v_mean.c_str()), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_vstate }, { m.b_vox }); + m.b_vox2 = decl_b(b, nm.f("vae.vox2"), RAD_F32, { vox, kC }); + { + RAD_ARCH_TRY(map_copy(b, nm.f("vae.pqc.weight"), nm.ckpt("vae.post_quant_conv.weight"))); + m.w_pqc = decl_w(b, nm.f("vae.pqc.weight"), RAD_F32, { kC, kC, 1, 1, 1 }, acc, + RAD_SHARD_NONE, grp_layer(gv)); + m.b_pqc = wcopy(b, nm.f("vae.pqc.bias"), nm.ckpt("vae.post_quant_conv.bias"), RAD_F32, + { kC }, acc, gv); + if (!m.w_pqc || !m.b_pqc) return RAD_E_INVAL; + m.op_pqc = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, vox), RAD_INT("N", kC), RAD_INT("K", kC), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.w_pqc, m.b_pqc)), + { m.b_vox }, { m.b_vox2 }); + } + m.b_vpin = decl_b(b, nm.f("vae.pin"), RAD_F32, { vox, dim }); + m.op_vpin = dense_bias(b, nm, "vae.proj_in", "vae.decoder.proj_in", RAD_F32, "f32", dim, kC, vox, + m.b_vox2, m.b_vpin, &m.w_vpin2, &m.b_vpin2, acc, gv); + m.b_vx = decl_b(b, nm.f("vae.x"), RAD_F32, { (int64_t)m.tiles * kPeriod, dim }); + m.w_reg = wcopy(b, nm.f("vae.registers"), nm.ckpt("vae.decoder.register_tokens"), RAD_F32, + { 1, kRegs, dim }, acc, gv); + if (!m.w_reg || !m.op_vpin || !m.op_pqc) return RAD_E_INVAL; + m.op_tiles = rw(b, RAD_OP(b, "vtile_gather", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)m.tiles * kPeriod), + RAD_INT("n", dim), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), RAD_INT("frames", kDecLat), + RAD_INT("period", kPeriod), RAD_INT("n_reg", kRegs), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.w_reg)), + { m.b_vpin }, { m.b_vx }); + m.b_dpos = decl_b(b, nm.f("vae.pos"), RAD_F32, { 3, R }); + m.op_dpos = rw(b, RAD_OP(b, "grid_pos3", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("T", kDecLat), + RAD_INT("H", kTile), RAD_INT("W", kTile), + RAD_INT("period", kPeriod), RAD_F64("scale", 2.0 * M_PI)), + RAD_NOWEIGHTS), + {}, { m.b_dpos }); + m.b_dcu = decl_b(b, nm.f("vae.cu"), RAD_I32, { m.tpr + 1 }); + m.op_dcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, m.tpr + 1), RAD_INT("start", 0), + RAD_INT("step", kPeriod)), + RAD_NOWEIGHTS), + {}, { m.b_dcu }); + if (!m.op_tiles || !m.op_dpos || !m.op_dcu) return RAD_E_INVAL; + + m.b_vn = decl_b(b, nm.f("vae.hn"), RAD_BF16, { R, dim }); + m.b_vqkv = decl_b(b, nm.f("vae.qkv"), RAD_BF16, { R, 3 * dim }); + m.b_vattn = decl_b(b, nm.f("vae.attn"), RAD_BF16, { R, dim }); + m.b_vo = decl_b(b, nm.f("vae.o"), RAD_BF16, { R, dim }); + m.b_vt = decl_b(b, nm.f("vae.t"), RAD_F32, { R, dim }); + m.b_vup = decl_b(b, nm.f("vae.up"), RAD_BF16, { R, 2 * ff }); + m.b_vact = decl_b(b, nm.f("vae.act"), RAD_BF16, { R, ff }); + const char* sections = nm.f("%lld %lld %lld", (long long)(rot / 6), (long long)(rot / 6), + (long long)(rot / 6)); + m.vit.resize((size_t)nl); + for (int64_t l = 0; l < nl; ++l) { + VitBlock& V = m.vit[(size_t)l]; + const int li = (int)l; + const char* pre = nm.ckpt("vae.decoder.transformer_blocks.%d", li); + const char* dn = nm.f("vae.blk.%d", li); + V.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_F32, + { dim }, acc, gv); + V.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_F32, + { dim }, acc, gv); + V.s1 = wcopy(b, nm.f("%s.scale1", dn), nm.ckpt("%s.scale1", pre), RAD_F32, { dim }, acc, gv); + V.s2 = wcopy(b, nm.f("%s.scale2", dn), nm.ckpt("%s.scale2", pre), RAD_F32, { dim }, acc, gv); + const char* qn = nm.f("%s.attn_qkv.weight", dn); + const char* qb = nm.f("%s.attn_qkv.bias", dn); + RAD_ARCH_TRY(map_concat(b, qn, { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) })); + RAD_ARCH_TRY(map_concat(b, qb, { nm.ckpt("%s.attn.to_q.bias", pre), + nm.ckpt("%s.attn.to_k.bias", pre), + nm.ckpt("%s.attn.to_v.bias", pre) })); + V.w_qkv = decl_w(b, qn, RAD_BF16, { 3 * dim, dim }, acc, RAD_SHARD_NONE, grp_layer(gv)); + V.b_qkv = decl_w(b, qb, RAD_F32, { 3 * dim }, acc, RAD_SHARD_NONE, grp_layer(gv)); + V.w_o = wcopy(b, nm.f("%s.attn_out.weight", dn), nm.ckpt("%s.attn.to_out.0.weight", pre), + RAD_BF16, { dim, dim }, acc, gv); + V.b_o = wcopy(b, nm.f("%s.attn_out.bias", dn), nm.ckpt("%s.attn.to_out.0.bias", pre), + RAD_F32, { dim }, acc, gv); + const char* un = nm.f("%s.ffn_up.weight", dn); + const char* ub = nm.f("%s.ffn_up.bias", dn); + const char* usrc = nm.ckpt("%s.ff.net.0.proj.weight", pre); + const char* ubsrc = nm.ckpt("%s.ff.net.0.proj.bias", pre); + RAD_ARCH_TRY(map_rows(b, un, { { usrc, (int)ff, ff }, { usrc, 0, ff } })); + RAD_ARCH_TRY(map_rows(b, ub, { { ubsrc, (int)ff, ff }, { ubsrc, 0, ff } })); + V.w_up = decl_w(b, un, RAD_BF16, { 2 * ff, dim }, acc, RAD_SHARD_NONE, grp_layer(gv)); + V.b_up = decl_w(b, ub, RAD_F32, { 2 * ff }, acc, RAD_SHARD_NONE, grp_layer(gv)); + V.w_down = wcopy(b, nm.f("%s.ffn_down.weight", dn), nm.ckpt("%s.ff.net.2.weight", pre), + RAD_BF16, { dim, ff }, acc, gv); + V.b_down = wcopy(b, nm.f("%s.ffn_down.bias", dn), nm.ckpt("%s.ff.net.2.bias", pre), RAD_F32, + { dim }, acc, gv); + if (!V.w_n1 || !V.w_n2 || !V.s1 || !V.s2 || !V.w_qkv || !V.b_qkv || !V.w_o || !V.b_o || + !V.w_up || !V.b_up || !V.w_down || !V.b_down) + return RAD_E_INVAL; + auto gemm = [&](rad_weight w, rad_weight bias, int64_t N, int64_t K, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { x }, { y }); + }; + V.op_n1 = rmsnorm_op(b, R, dim, eps, V.w_n1, m.b_vx, m.b_vn); + V.op_qkv = gemm(V.w_qkv, V.b_qkv, 3 * dim, dim, m.b_vn, m.b_vqkv); + V.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("n_head", dim / hd), RAD_INT("n_head_kv", dim / hd), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "axial"), RAD_INT("rotary_dim", rot), + RAD_STR("sections", sections)), + RAD_NOWEIGHTS), + { m.b_vqkv, m.b_dpos }, { m.b_vqkv }); + V.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd)), + RAD_INT("max_seqlen", kPeriod)), + RAD_NOWEIGHTS), + { m.b_vqkv, m.b_dcu }, { m.b_vattn }); + V.op_o = gemm(V.w_o, V.b_o, dim, dim, m.b_vattn, m.b_vo); + V.op_s1 = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", dim), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(V.s1)), + { m.b_vo }, { m.b_vt }); + V.op_r1 = add_op(b, R, dim, "f32", m.b_vx, m.b_vt, m.b_vx); + V.op_n2 = rmsnorm_op(b, R, dim, eps, V.w_n2, m.b_vx, m.b_vn); + V.op_up = gemm(V.w_up, V.b_up, 2 * ff, dim, m.b_vn, m.b_vup); + V.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vup }, { m.b_vact }); + V.op_down = gemm(V.w_down, V.b_down, dim, ff, m.b_vact, m.b_vo); + V.op_s2 = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", dim), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(V.s2)), + { m.b_vo }, { m.b_vt }); + V.op_r2 = add_op(b, R, dim, "f32", m.b_vx, m.b_vt, m.b_vx); + if (!V.op_n1 || !V.op_qkv || !V.op_qkr || !V.op_attn || !V.op_o || !V.op_s1 || !V.op_r1 || + !V.op_n2 || !V.op_up || !V.op_act || !V.op_down || !V.op_s2 || !V.op_r2) + return RAD_E_INVAL; + } + m.w_vno = wcopy(b, nm.f("vae.norm_out.weight"), nm.ckpt("vae.decoder.norm_out.weight"), RAD_F32, + { dim }, acc, gv); + m.b_vno = wcopy(b, nm.f("vae.norm_out.bias"), nm.ckpt("vae.decoder.norm_out.bias"), RAD_F32, + { dim }, acc, gv); + if (!m.w_vno || !m.b_vno) return RAD_E_INVAL; + m.op_vnorm = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", dim), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_vno, m.b_vno)), + { m.b_vx }, { m.b_vn }); + m.b_vpix = decl_b(b, nm.f("vae.pix"), RAD_BF16, { R, px }); + m.op_vproj = dense_bias(b, nm, "vae.proj_out", "vae.decoder.proj_out", RAD_BF16, "bf16", px, dim, + R, m.b_vn, m.b_vpix, &m.w_vpo, &m.b_vpo, acc, gv); + if (!m.op_vnorm || !m.op_vproj) return RAD_E_INVAL; + if (m.W > 1) { + m.b_vpix_all = decl_b(b, nm.f("vae.pix_all"), RAD_BF16, { RA, px }); + m.op_vgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", m.W), + RAD_RANGE("numel", 1, R * px), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vpix }, { m.b_vpix_all }); + if (!m.op_vgather) return RAD_E_INVAL; + } + const int64_t fmax = (int64_t)kFpc + kFtail; + m.b_prev = decl_b(b, nm.f("lane.prev"), RAD_BF16, { (int64_t)kMaxLanes * kFtail * kMaxArea, 3 }, + RAD_BUF_PERSIST); + m.b_frames = decl_b(b, nm.f("frames_out"), RAD_U8, { fmax * kMaxArea, 3 }, RAD_BUF_PERSIST); + m.op_stitch = rw(b, RAD_OP(b, "vtile_stitch", + RAD_PARAMS(RAD_RANGE("M", 1, fmax * kMaxArea), RAD_INT("tile", kTile), + RAD_INT("overlap", kOverlap), RAD_INT("scale", kScale), + RAD_INT("pt", 4), RAD_INT("skip", 3), RAD_INT("keep", kFpc), + RAD_INT("blend", kFtail), RAD_INT("period", kPeriod), + RAD_STR("mean", kPixMean), RAD_STR("std", kPixStd)), + RAD_NOWEIGHTS), + { m.W > 1 ? m.b_vpix_all : m.b_vpix, m.b_prev }, { m.b_prev, m.b_frames }); + return m.op_stitch ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== declare */ +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + if (m.gt.n_layer <= kTextLayers) { + fprintf(stderr, "radiance: minimaxh3: the conditioning is the text encoder's state after " + "layer %d, and it has %lld layers\n", kTextLayers, (long long)m.gt.n_layer); + return RAD_E_INVAL; + } + m.gt.n_layer = kTextLayers; + m.gt.max_tok = kMaxText; + m.W = m.gt.world; + + /* ---- the DiT's geometry, off the transformer's own config */ + Geom& gd = m.gd; + gd = m.gt; + gd.max_tok = ctx->max_tok; + gd.n_layer = rad_meta_geti(meta, "transformer.num_layers", 50); + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 56); + gd.n_head_kv_all = gd.n_head_all; + gd.n_embd = rad_meta_geti(meta, "transformer.hidden_size", 5376); + gd.n_ff_all = rad_meta_geti(meta, "transformer.ffn_dim", 14336); + gd.eps = (float)rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + gd.rope_mc = false; + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + gd.n_head_kv = gd.n_head; + gd.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + m.D = gd.n_embd; + /* A rank holds 6 / world of a modality's six vectors, which keeps each [shift | scale] pair and + * its gate on one rank. */ + if (6 % m.W || (6 * m.D / m.W) % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: minimaxh3: %d ranks do not split the six modulation vectors " + "into whole fp8 blocks; use 1 or 2\n", (int)m.W); + return RAD_E_UNSUPPORTED; + } + m.Ws = 6 * m.D / m.W; + + /* A checkpoint distilled for few steps with video sparse attention says so in its inference + * settings (fastvideo_inference.json): the attention, its sparsity and tile, the timesteps it + * was trained on (a 1000-step clock) and the shifts it was trained with. */ + const char* backend = rad_meta_gets(meta, "fastvideo_inference.attention_backend", ""); + if (!std::strcmp(backend, "VIDEO_SPARSE_ATTN_H3")) { + m.vsa = true; + m.vsa_sparsity = rad_meta_getf(meta, "fastvideo_inference.vsa_sparsity", -1.0); + const long long tile = rad_meta_geti(meta, "fastvideo_inference.vsa_tile_size", 0); + if (tile != kVsaRows || !(m.vsa_sparsity >= 0.0 && m.vsa_sparsity < 1.0)) { + fprintf(stderr, "radiance: minimaxh3: video sparse attention at %lld-row tiles and " + "sparsity %g; this plugin runs %d-row (4 x 4 x 4) tiles at a sparsity " + "in [0, 1)\n", tile, m.vsa_sparsity, (int)kVsaRows); + return RAD_E_UNSUPPORTED; + } + vsa_bounds(m.vsa_sparsity, &m.vsa_tiles, &m.vsa_k); + } else if (*backend && std::strcmp(backend, "FLASH_ATTN")) { + fprintf(stderr, "radiance: minimaxh3: the checkpoint was made for the attention '%s'; this " + "plugin runs dense attention and VIDEO_SPARSE_ATTN_H3\n", backend); + return RAD_E_UNSUPPORTED; + } + for (double t : meta_list(meta, "fastvideo_inference.dmd_denoising_steps")) + m.rungs.push_back(t / 1000.0); + if (!m.rungs.empty()) { + const long long fw = rad_meta_geti(meta, "fastvideo_inference.transformer_forwards", + (long long)m.rungs.size()); + if (fw != (long long)m.rungs.size() || (int64_t)m.rungs.size() > kMaxSteps) { + fprintf(stderr, "radiance: minimaxh3: a trained schedule of %zu timesteps for %lld " + "evaluations; at most %d, one a timestep\n", m.rungs.size(), fw, + (int)kMaxSteps); + return RAD_E_UNSUPPORTED; + } + m.S = (int64_t)m.rungs.size(); + } + for (const char* k : { "video", "audio" }) { + const double want = rad_meta_getf(meta, m.nm.f("fastvideo_inference.%s_scheduler_shift", k), + 0.0); + const double have = rad_meta_getf(meta, !std::strcmp(k, "video") ? "scheduler.shift" + : "audio_scheduler.shift", + !std::strcmp(k, "video") ? 12.0 : 3.0); + if (want > 0.0 && want != have) { + fprintf(stderr, "radiance: minimaxh3: the checkpoint was trained with a %s shift of %g " + "and its scheduler says %g\n", k, want, have); + return RAD_E_INVAL; + } + } + m.gr = gd; + m.gr.max_tok = kMaxText; + m.maxV = max_video_rows(); + m.maxA = kAudioCh * max_audio(); + m.tiles = max_tiles(); + m.tpr = (m.tiles + m.W - 1) / m.W; + if (gd.n_layer >= kGrpAda - kGrpDit - 1 || gd.n_layer > kGrpVae - kGrpAda || + m.gt.n_layer >= kGrpRefiner) { + fprintf(stderr, "radiance: minimaxh3: the networks are too deep for the weight groups\n"); + return RAD_E_UNSUPPORTED; + } + if (ctx->max_tok < max_step_rows() || ctx->max_tok < m.tpr * kPeriod) { + fprintf(stderr, "radiance: minimaxh3: a pass carries %lld rows; the longest video's step " + "needs %lld and its decode %lld\n", (long long)ctx->max_tok, + (long long)max_step_rows(), (long long)(m.tpr * kPeriod)); + return RAD_E_INVAL; + } + + /* ---- 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); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_refiner(b, meta, m)); + RAD_ARCH_TRY(declare_tables(b, meta, m)); + 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"); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(declare_audio(b, meta, m)); + RAD_ARCH_TRY(declare_video(b, meta, m)); + + if (!ctx->shape_probe) { + RadVideoGenDecl d{}; + /* A distilled release is served under its own id's last part, lower case. */ + std::string name = "minimax-h3"; + if (const char* id = rad_meta_gets(meta, "fastvideo_inference.model_id", nullptr)) { + const char* last = std::strrchr(id, '/'); + name = last ? last + 1 : id; + for (char& ch : name) ch = (char)std::tolower((unsigned char)ch); + } + d.name = name.c_str(); + d.tmpl = "{prompt}"; + d.max_text = kMaxText; + d.fps_num = kFps; + d.fps_den = 1; + d.frames_per_chunk = kFpc; + d.frames_tail = kFtail; + d.latents_per_chunk = kLpc; + d.latents_tail = kLtail; + d.dec_latents = kDecLat; + d.min_chunks = kMinChunks; + d.max_chunks = kMaxChunks; + d.latent_scale = kScale; + d.latent_channels = kC; + d.patch = kPatch; + d.size_multiple = kMult; + d.min_side = kMinSide; + d.max_area = kMaxArea; + d.max_aspect = kMaxAspect; + d.default_width = kDefW; + d.default_height = kDefH; + d.default_chunks = kDefChunks; + d.sample_rate = kRate; + d.audio_rate = kAudioRate; + d.audio_channels = kAudioCh; + d.audio_latent_channels = kAudioC; + d.default_steps = kDefSteps; + d.max_steps = kMaxSteps + 1; + if (!m.rungs.empty()) { + d.n_rungs = (int32_t)m.rungs.size(); + d.rungs = m.rungs.data(); + d.default_steps = d.max_steps = d.n_rungs + 1; + } + d.shift_video = rad_meta_getf(meta, "scheduler.shift", 12.0); + d.shift_audio = rad_meta_getf(meta, "audio_scheduler.shift", 3.0); + d.max_lanes = kMaxLanes; + d.frames_out = m.b_frames; + d.audio_out = m.b_audio; + RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); + } + + rad_note(b, "rank %d/%d: MiniMax-H3 t2va -- text encoder %lld layers (%lld heads a rank), " + "refiner 2 and DiT %lld blocks (%lld heads, ff %lld a rank), modulation %lld of " + "6 x %lld a rank, video decoder %lld tiles at most (%lld a rank)", + m.gt.rank, m.gt.world, (long long)m.gt.n_layer, (long long)m.gt.n_head, + (long long)gd.n_layer, (long long)gd.n_head, (long long)gd.n_ff, (long long)m.Ws, + (long long)m.D, (long long)m.tiles, (long long)m.tpr); + return RAD_OK; +} + +/* ================================================================== step */ +/* 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) { + const RadVideoGenBatch* V = batch->vgen_b; + 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(); + 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); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + for (const TeLayer& L : m.te) { + 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_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add1, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE(c, L.op_n2, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add2, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + } + + const Geom& r = m.gr; + const int64_t D = m.D, qd = r.q_dim(); + RAD_ISSUE_N(c, m.op_ce, T, brows(m.b_tx, T), RAD_W(m.w_ce), RAD_W(m.b_ce), RAD_NONE, + brows(m.b_rh, T)); + for (const RefBlock& R : m.rb) { + RAD_ISSUE_N(c, R.op_n1, T, brows(m.b_rh, T), RAD_W(R.w_n1), brows(m.a_rh.x, T)); + R.q_h.step(c, T); + R.qkv.step(c, m.a_rh, m.b_rqkv, T); + RAD_ISSUE_N(c, R.op_qkn, T, brows(m.b_rqkv, T), RAD_NONE, RAD_W(R.w_qn), RAD_W(R.w_kn)); + RAD_ISSUE_N(c, R.op_attn, T, bcol(m.b_rqkv, 0, qd, T), bcol(m.b_rqkv, qd, qd, T), + bcol(m.b_rqkv, 2 * qd, qd, T), cu, brows(m.a_rattn.x, T)); + R.q_attn.step(c, T); + R.o.step(c, m.a_rattn, m.b_rao, T); + if (R.op_ar1) RAD_ISSUE_N(c, R.op_ar1, T * D, brows(m.b_rao, T), RAD_NONE); + RAD_ISSUE_N(c, R.op_add1, T, brows(m.b_rh, T), brows(m.b_rao, T), brows(m.b_rh, T)); + RAD_ISSUE_N(c, R.op_n2, T, brows(m.b_rh, T), RAD_W(R.w_n2), brows(m.a_rh.x, T)); + R.q_h2.step(c, T); + R.gate_up.step(c, m.a_rh, m.b_rgu, T); + R.gq.step(c, m.b_rgu, T); + R.down.step(c, m.a_rffn, m.b_rao, T); + if (R.op_ar2) RAD_ISSUE_N(c, R.op_ar2, T * D, brows(m.b_rao, T), RAD_NONE); + RAD_ISSUE_N(c, R.op_add2, T, brows(m.b_rh, T), brows(m.b_rao, T), brows(m.b_rh, T)); + } + 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)); + m.q_temb.step(c, S2); + + /* ---- 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; + 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 (int e = 0; e < kSegs; ++e) { + const int64_t r0 = e == kSegAudio ? S : 0; + 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)); + } +} + +/* One denoising step of the lane: the packed sequence, the blocks, the heads and both Euler + * steps. */ +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 D = m.D, qd = g.q_dim(), L = g.n_layer, La = kMaxLanes; + const RadOperand lane_d = praw(V->lane_d, RAD_I32, 1); + + 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)); + RAD_ISSUE_N(c, m.op_rnd_a, arows, praw(V->first_d, RAD_I32, 1), + praw(V->seed + 2, RAD_U32, 2), lane_d, praw(V->lat_cu + 2, RAD_I32, 2), + brows(m.b_astate, La * m.maxA)); + } + const int64_t row = L * kSegs * 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)); + 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)); + 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_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)); + + const RadOperand segs = praw(V->seg_cu, RAD_I32, 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. */ + 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); + }; + /* 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). */ + const bool split = g.world > 1; + const int64_t cut = split ? nt + arows + 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 }; + 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, + chunks * D, 1); + }; + /* A half's partial sums across the ranks, kArRows rows a message, on lane 1 when split. */ + auto all_reduce_half = [&](rad_op op, int64_t r0, int64_t n) { + if (!op) return; + if (split) { + rad_lane_join(c, 0, 1); + rad_lane(c, 1); + } + for (int64_t q0 = 0; q0 < n; q0 += kArRows) { + const int64_t k = std::min(kArRows, n - q0); + RAD_ISSUE_N(c, op, k * D, brow_slice(m.b_ao, r0 + q0, k, D), RAD_NONE); + } + if (split) rad_lane(c, 0); + }; + auto wait_ar = [&]() { if (split) rad_lane_join(c, 1, 0); }; + for (int64_t l = 0; l < L; ++l) { + const DitBlock& B = m.dit[(size_t)l]; + /* The first half's norm reads the all-reduce the previous block waited for last; the + * second half's waits here, so its reduction ran under the first half's norm and qkv. */ + for (int h = 0; h < nh; ++h) { + 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); + 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), + RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_kq, R, bcol(m.b_qkv, qd, qd, R), brows(m.b_k8, R), brows(m.b_ks, R)); + RAD_ISSUE_N(c, B.op_vq, R, bcol(m.b_qkv, 2 * qd, qd, R), brows(m.b_v8, R), RAD_B(m.b_vs)); + if (m.vsa) { + RAD_ISSUE_N(c, B.op_sel, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + bcol(m.b_qkv, 2 * qd, qd, R), segs, geom, RAD_B(m.b_sel), + RAD_B(m.b_coarse)); + RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + brows(m.b_v8, R), segs, geom, RAD_B(m.b_sel), RAD_B(m.b_coarse), + bcol(m.b_qkv, 3 * qd, qd, R), brows(m.a_attn.x, R), brows(m.b_k8, R), + brows(m.b_ks, R), RAD_B(m.b_vs)); + } else { + RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + brows(m.b_v8, R), RAD_NONE, RAD_NONE, RAD_NONE, cu, RAD_NONE, RAD_NONE, + brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R), RAD_B(m.b_vs)); + } + /* Each wait below is for the all-reduce lane 1 holds last, which is the one lane 0 reads + * next: the second half's projection runs under the first half's reduction, the first + * half's feed-forward under the second's, and so on. */ + for (int h = 0; h < nh; ++h) { + B.q_attn.step(c, R, hr0[h], hn[h]); + B.o.step(c, m.a_attn, m.b_ao, R, hr0[h], hn[h]); + if (h > 0) wait_ar(); + all_reduce_half(B.op_ar1, hr0[h], hn[h]); + } + for (int h = 0; h < nh; ++h) { + 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); + 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); + wait_ar(); + all_reduce_half(B.op_ar2, r0, n); + } + } + wait_ar(); + 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); + 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)); + + /* 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, + rad_buf y) { + for (int64_t r0 = 0; r0 < n; r0 += kHeadRows) { + const int64_t k = std::min(kHeadRows, n - r0); + RAD_ISSUE_N(c, m.op_hcast, k, brow_slice(m.b_hn, first + r0, k, D), brows(m.b_hf, k)); + RAD_ISSUE_N(c, op, k, brows(m.b_hf, k), RAD_W(w), RAD_W(bias), RAD_NONE, + 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)); +} + +/* The soundtrack: both channels, each a sequence, through the audio decoder, then interleaved. */ +static void step_audio(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t lane = V->lane, na = V->geom.n_audio, r0 = kAudioCh * na; + const RadOperand nlen = praw(V->geom_d + RAD_VGEOM_N_AUDIO, RAD_I32, 1); + auto conv = [&](const AConv& k, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, k.op, R, brows(x, R), RAD_W(k.w), brows(cu, 3), res ? brows(res, R) : RAD_NONE, + brows(y, R), k.b ? RAD_W(k.b) : RAD_NONE); + }; + auto act = [&](const AAct& a, rad_buf x, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, a.op, R, brows(x, R), RAD_W(a.alpha), RAD_W(a.beta), RAD_W(a.up), + RAD_W(a.down), brows(cu, 3), brows(y, R)); + }; + RAD_ISSUE_N(c, m.op_adenorm, r0, brow_slice(m.b_astate, lane * m.maxA, r0, kAudioC), + brows(m.b_aden, r0)); + RAD_ISSUE_N(c, m.op_acu0, 3, nlen, brows(m.b_acu[0], 3)); + conv(m.a_in, m.b_aden, 0, m.b_ain0, r0, m.b_acu[0]); + conv(m.a_pre, m.b_ain0, 0, m.b_aavg[0], r0, m.b_acu[0]); + int64_t rows = r0; + for (int s = 0; s < 7; ++s) { + const AStage& St = m.ast[s]; + const int64_t R = rows * St.rate; + RAD_ISSUE_N(c, St.op_cu, 3, nlen, brows(m.b_acu[s + 1], 3)); + RAD_ISSUE_N(c, St.up.op, rows, brows(m.b_aavg[s], rows), RAD_W(St.up.w), RAD_W(St.up.b), + brows(m.b_acu[s], 3), brows(m.b_ah[s + 1], R)); + for (int j = 0; j < 3; ++j) + for (int d = 0; d < 3; ++d) { + const AmpUnit& U = St.amp[j].u[d]; + const rad_buf x = d == 0 ? m.b_ah[s + 1] : m.b_aamp[j][s + 1]; + act(U.a1, x, m.b_at1[s + 1], R, m.b_acu[s + 1]); + conv(U.c1, m.b_at1[s + 1], 0, m.b_at2[s + 1], R, m.b_acu[s + 1]); + act(U.a2, m.b_at2[s + 1], m.b_at1[s + 1], R, m.b_acu[s + 1]); + conv(U.c2, m.b_at1[s + 1], x, m.b_aamp[j][s + 1], R, m.b_acu[s + 1]); + } + RAD_ISSUE_N(c, St.op_sum, R, brows(m.b_aamp[0][s + 1], R), brows(m.b_aamp[1][s + 1], R), + brows(m.b_aavg[s + 1], R)); + RAD_ISSUE_N(c, St.op_avg, R, brows(m.b_aavg[s + 1], R), brows(m.b_aamp[2][s + 1], R), + brows(m.b_aavg[s + 1], R)); + rows = R; + } + act(m.a_actpost, m.b_aavg[7], m.b_at1[7], rows, m.b_acu[7]); + conv(m.a_post, m.b_at1[7], 0, m.b_aout0, rows, m.b_acu[7]); + const int64_t n = rows / kAudioCh; + RAD_ISSUE_N(c, m.op_vmix, n, brow_slice(m.b_aout0, 0, n, 1), brow_slice(m.b_aout0, n, n, 1), + brows(m.b_audio, n)); +} + +/* One chunk of frames: the latents, this rank's tiles through the ViT, every rank's gathered, and + * the stitch into the chunk's frames. */ +static void step_video(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t lane = V->lane, lh = V->geom.lat_h, lw = V->geom.lat_w; + const int64_t ppf = (lh / kPatch) * (lw / kPatch), vox = (int64_t)kDecLat * lh * lw; + const int64_t dim = 2048, px = 3 * 4 * kScale * kScale; + const int64_t nt = tiles_of(lh, lw), tpr = (nt + m.W - 1) / m.W; + const int64_t t0 = (int64_t)m.gt.rank * tpr; + const int64_t mine = std::max(0, std::min(tpr, nt - t0)); + const int64_t R = mine * kPeriod, a = t0 * kPeriod; + + RAD_ISSUE_N(c, m.op_unfold, vox, + brow_slice(m.b_vstate, lane * m.maxV + (int64_t)V->chunk * kLpc * ppf, + (int64_t)kDecLat * ppf, kPatchVals), + praw(V->geom_d + RAD_VGEOM_PATCH_FRAMES, RAD_I32, 3), brows(m.b_vox, vox)); + RAD_ISSUE_N(c, m.op_pqc, vox, brows(m.b_vox, vox), RAD_W(m.w_pqc), RAD_W(m.b_pqc), RAD_NONE, + brows(m.b_vox2, vox)); + RAD_ISSUE_N(c, m.op_vpin, vox, brows(m.b_vox2, vox), RAD_W(m.w_vpin2), RAD_W(m.b_vpin2), + RAD_NONE, brows(m.b_vpin, vox)); + RAD_ISSUE_N(c, m.op_tiles, nt * kPeriod, brows(m.b_vpin, vox), RAD_W(m.w_reg), + praw(V->geom_d + RAD_VGEOM_CHUNK_FRAMES, RAD_I32, 3), + brows(m.b_vx, nt * kPeriod)); + if (mine > 0) { + const RadOperand x = brow_slice(m.b_vx, a, R, dim); + const RadOperand pos = bcol(m.b_dpos, 0, R, 3); + RAD_ISSUE_N(c, m.op_dpos, R, pos); + RAD_ISSUE_N(c, m.op_dcu, mine + 1, brows(m.b_dcu, mine + 1)); + for (const VitBlock& B : m.vit) { + RAD_ISSUE_N(c, B.op_n1, R, x, RAD_W(B.w_n1), brows(m.b_vn, R)); + RAD_ISSUE_N(c, B.op_qkv, R, brows(m.b_vn, R), RAD_W(B.w_qkv), RAD_W(B.b_qkv), RAD_NONE, + brows(m.b_vqkv, R)); + RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_vqkv, R), pos, RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_vqkv, 0, dim, R), bcol(m.b_vqkv, dim, dim, R), + bcol(m.b_vqkv, 2 * dim, dim, R), brows(m.b_dcu, mine + 1), + brows(m.b_vattn, R)); + RAD_ISSUE_N(c, B.op_o, R, brows(m.b_vattn, R), RAD_W(B.w_o), RAD_W(B.b_o), RAD_NONE, + brows(m.b_vo, R)); + RAD_ISSUE_N(c, B.op_s1, R, brows(m.b_vo, R), RAD_W(B.s1), brows(m.b_vt, R)); + RAD_ISSUE_N(c, B.op_r1, R, x, brows(m.b_vt, R), x); + RAD_ISSUE_N(c, B.op_n2, R, x, RAD_W(B.w_n2), brows(m.b_vn, R)); + RAD_ISSUE_N(c, B.op_up, R, brows(m.b_vn, R), RAD_W(B.w_up), RAD_W(B.b_up), RAD_NONE, + brows(m.b_vup, R)); + RAD_ISSUE_N(c, B.op_act, R, brows(m.b_vup, R), brows(m.b_vact, R)); + RAD_ISSUE_N(c, B.op_down, R, brows(m.b_vact, R), RAD_W(B.w_down), RAD_W(B.b_down), + RAD_NONE, brows(m.b_vo, R)); + RAD_ISSUE_N(c, B.op_s2, R, brows(m.b_vo, R), RAD_W(B.s2), brows(m.b_vt, R)); + RAD_ISSUE_N(c, B.op_r2, R, x, brows(m.b_vt, R), x); + } + RAD_ISSUE_N(c, m.op_vnorm, R, x, RAD_W(m.w_vno), RAD_W(m.b_vno), brows(m.b_vn, R)); + RAD_ISSUE_N(c, m.op_vproj, R, brows(m.b_vn, R), RAD_W(m.w_vpo), RAD_W(m.b_vpo), RAD_NONE, + brows(m.b_vpix, R)); + } + rad_buf pix = m.b_vpix; + if (m.W > 1) { + RAD_ISSUE_N(c, m.op_vgather, tpr * kPeriod * px, brows(m.b_vpix, tpr * kPeriod), + brows(m.b_vpix_all, m.W * tpr * kPeriod)); + pix = m.b_vpix_all; + } + const int64_t hp = lh * kScale, wp = lw * kScale, n = (int64_t)V->n_frames_out * hp * wp; + RAD_ISSUE_N(c, m.op_stitch, n, brows(pix, nt * kPeriod), + praw(V->geom_d + RAD_VGEOM_CHUNK_FRAMES, RAD_I32, 5), + brow_slice(m.b_prev, lane * kFtail * (int64_t)kMaxArea, (int64_t)kFtail * hp * wp, 3), + brows(m.b_frames, n)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->vgen_b) { + rad_step_fail(c, "minimaxh3 is a video generator and runs its generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_VCOND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_VSTEP: step_dit(c, batch, m); return; + case RAD_GEN_PASS_ADECODE: step_audio(c, batch, m); return; + case RAD_GEN_PASS_VDECODE: step_video(c, batch, m); return; + default: + rad_step_fail(c, "minimaxh3: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows of the largest pass: a step of the longest video at the largest size, or a decode of + * the most tiles. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = std::max(max_step_rows(), max_tiles() * kPeriod); + out->gen_video = 1; + return RAD_OK; +} + +} /* namespace minimaxh3 */ + +#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") + +extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, + int64_t cap) { + if (!g || g->n_text < 1 || g->n_text > minimaxh3::kMaxText) return RAD_E_INVAL; + if (which == RAD_VPOS_STEP) return minimaxh3::positions(g, pos, cap); + if (which == RAD_VPOS_DECODE) return minimaxh3::decode_rows(g); + return RAD_E_INVAL; +} +#endif diff --git a/arch/minimaxmusic3/CMakeLists.txt b/arch/minimaxmusic3/CMakeLists.txt new file mode 100644 index 00000000..9898969f --- /dev/null +++ b/arch/minimaxmusic3/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/minimaxmusic3 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(minimaxmusic3 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(minimaxmusic3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimaxmusic3.cpp) diff --git a/arch/minimaxmusic3/minimaxmusic3.cpp b/arch/minimaxmusic3/minimaxmusic3.cpp new file mode 100644 index 00000000..70647ec0 --- /dev/null +++ b/arch/minimaxmusic3/minimaxmusic3.cpp @@ -0,0 +1,1582 @@ +/* minimaxmusic3 -- MiniMax-Music3: a song from a description and lyrics, as 44.1 kHz stereo. + * + * ============================== THE MODEL ============================== + * + * Four networks behind one prompt (diffusers' MiniMaxMusic3ModularPipeline): + * + * Global language model: Qwen3-8B with its embedding and head adapted to music codes. It reads + * the prompt (description and lyrics in the model's tags) and writes the song one frame at a + * time, 25 a second: each frame's first residual code (one of 16384 semantic codes, or the end + * of the song), sampled from guided logits, u + 1.5 (c - u), between a conditional branch and an + * unconditional one whose prompt keeps only its first and last two tokens. Top 50 of the + * conditional logits are the candidates, top 50 of the guided ones drawn. + * + * Depth decoder (0.6B): four layers that write the frame's other seven codes, one at a time, + * from the language model's hidden state and the codes before them, each with the same + * guidance. The frame's eight codes, embedded and summed, are the language model's next input. + * + * Condition encoder and denoiser: each frame's nine hidden states (the language model's and the + * depth decoder's seven -- the eighth plane is the language model's own) are mixed with learned + * weights into one conditioning row. A window of 200 frames is projected (a 3-tap conv to 2048 + * channels), resampled to the vocoder's latent rate (441/128 latents a frame) and denoised by a + * 2.4B flow-matching transformer over 128-channel latents, 30 Euler steps with guidance 1.7 + * against an all-zero conditioning. Windows overlap by half; each binds its first 172 latents to + * its predecessor's. + * + * Vocoder: a DAC decoder, the latent's two 64-channel halves decoded as two streams (left and + * right) through four transposed convolutions (8, 8, 4, 2) and dilated residual units with snake + * activations, 512 samples a latent. + * + * The passes are the core's audio generator (abi/rad_builder.h, rad_declare_audio_generator; + * core/gen/audio_driver.h): PROMPT runs the language model over prompt chunks, FRAME samples one + * frame of every song in flight and runs the language model over its embedding, WINDOW steps the + * denoiser, VOCODE plays a finished window. + * + * ============================== STATE ============================== + * + * A song is a lane. Each lane keeps its two branches' last hidden states, every frame's + * conditioning row (9000 frames at most), its window's latent and conditioning, and what the next + * window binds to: the previous window's latents and conditioning over the overlap, and its own + * noise there. The depth decoder's sequence is rebuilt every frame and recomputed whole at each of + * its seven steps (causal attention keeps the positions not yet written out of every result it + * reads), which costs nothing at a frame's handful of rows since every pass reads the same + * weights. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model, the depth decoder and the denoiser's blocks are split by heads and by + * feed-forward width, an all-reduce after each output projection. The heads, the sampler, the + * condition encoder, the denoiser's input and output layers and the vocoder are replicated: every + * rank draws the same codes from the same logits and seeds, and plays the same samples. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace minimaxmusic3 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* Songs at once: lanes. */ +enum { kMaxLanes = 4 }; +/* The longest prompt and song (diffusers' _MAX_PROMPT_TOKENS, _MAX_AUDIO_FRAMES). */ +enum { kMaxPrompt = 5000, kMaxFrames = 9000 }; +/* The frame's codes: the semantic one and seven residual ones of 1024. */ +enum { kCodes = 8, kSemCodes = 16384, kResCodes = 1024 }; +/* Token ids: the first semantic code, the end of the song, the unconditional branch's filler. */ +enum { kCodeOffset = 151675, kEndToken = 151670, kCfgToken = 151654 }; +/* Windows: 200 frames a new one every 100; latents per frame 44100/24000 * 960/512 = 441/128. */ +enum { kWinFrames = 200, kWinHop = 100, kLatNum = 441, kLatDen = 128 }; +enum { kWinLat = kWinFrames * kLatNum / kLatDen }; /* 689 */ +/* The overlap a window binds (diffusers' _OVERLAP_LATENT_LENGTH) and the crops at a join. */ +enum { kOverlap = 172, kCropLeft = 86, kCropRight = 344 - 86 }; +enum { kSamplesPerLatent = 512, kSampleRate = 44100 }; + +static const double kArCfg = 1.5; +static const int kTopK = 50; +static const int kDitSteps = 30; +static const double kDitCfg = 1.7; + +/* The prompt, in the model's own tags (diffusers' MiniMaxMusic3TokenizeStep). */ +static const char* kTemplate = + "<|im_start|><|caption_start|>{instructions}<|caption_end|><|lyrics_start|>{input}" + "<|lyrics_end|><|im_end|><|audio_start|>"; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpLm = 0, /* the language model's layers: 0.. */ + kGrpDepth = 100, + kGrpCond = 150, + kGrpDit = 200, /* the denoiser's model-level weights; its blocks 201.. */ + kGrpVoc = 300, +}; + +/* ================================================================== the networks */ +/* A Qwen3 layer over a paged cache: q, k and v as three projections (paged attention reads a + * contiguous query), per-head RMS norms, NeoX rotary, an output projection and a SwiGLU. Every + * linear is a LinearFP8, which reads bf16 or block fp8 as the container holds it. The depth + * decoder's layers are the same without the norms on q and k, the rotary or the cache. */ +struct LmLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 q{}, k{}, v{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_kv = 0, op_attn = 0; + rad_op op_attn_p = 0; /* a prompt chunk: its own rows causally, its earlier ones cached */ + rad_op op_ar1 = 0, op_add1 = 0, op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +/* The denoiser's block: layer norms with gain and bias, attention over fused q|k|v with a partial + * rotary, a SwiGLU whose value half comes first (`gate_states, gate = chunk(2)`), biases on the + * feed-forward. */ +struct DitLayer { + rad_weight w_n1 = 0, w_b1 = 0, w_n2 = 0, w_b2 = 0, w_fi = 0, w_fib = 0, w_fo = 0, w_fob = 0; + LinearFP8 qkv{}, o{}; + QuantFP8 q_h{}, q_attn{}; + rad_op op_ln1 = 0, op_rope = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_ln2 = 0, op_fi = 0, op_act = 0, op_fo = 0, op_ar2 = 0, op_add2 = 0; +}; + +/* One vocoder convolution: its weight, bias and the op. */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; + int64_t cin = 0, cout = 0, k = 1, dil = 1; +}; +struct VRes { + rad_weight a1 = 0, a2 = 0; + rad_op op_s1 = 0, op_s2 = 0; + VConv c1{}, c2{}; +}; +struct VBlock { + rad_weight a = 0; + rad_op op_s = 0; + rad_weight wt = 0, bt = 0; + rad_op op_t = 0; + int64_t cin = 0, cout = 0, stride = 1; + VRes res[3]; + rad_op op_cu = 0; /* the stage's cu_seqlens: the window's two streams at this rate */ +}; + +struct Model { + Names nm{""}; + Geom gl{}, gd{}, gt{}; /* the language model's, the depth decoder's and the DiT's */ + int64_t lanes = 0; /* lanes declared (kMaxLanes, or what max_seqs leaves) */ + int64_t S = 0; /* a FRAME pass's rows at most: two a lane */ + rad_kvgroup kv = 0; + + /* ---- the language model */ + rad_weight w_tok = 0, w_norm = 0, w_head = 0; + rad_op op_embed = 0, op_norm = 0, op_head = 0; + rad_buf b_x = 0, b_q = 0, b_k = 0, b_v = 0, b_h2 = 0, b_gu = 0, b_last = 0; + ActFP8 a_h{}, a_attn{}, a_ffn{}; + std::vector lm; + + /* ---- the frame: the lanes' last hidden states, the logits, the codes, the depth decoder */ + rad_buf b_hid = 0; /* [2 lanes, n_embd] PERSIST: row 2 lane + branch */ + rad_buf b_status = 0; /* [lanes] i32 PERSIST: what the FRAME pass reports */ + rad_buf b_slog = 0; /* [S, 16385] the semantic codes' logits, the end's last */ + rad_buf b_codes = 0; /* [8, S] i32: code-major, each code twice (both branches) */ + rad_buf b_idx = 0; /* [8, S] i32: depth row e * 8 + p for each position p */ + rad_buf b_planes = 0; /* [8 * S, n_embd]: the frame's eight conditioning planes */ + rad_op op_hsel = 0, op_sem = 0, op_status = 0, op_iota[kCodes] = {}; + rad_op op_mix = 0, op_fb = 0, op_store = 0, op_plast = 0, op_pnorm = 0, op_pstore = 0; + rad_weight w_dproj = 0, w_dpos = 0, w_dnorm = 0, w_dheads = 0, w_demb = 0; + rad_op op_dpos0 = 0, op_de1 = 0, op_dproj[kCodes] = {}, op_dscat = 0, op_dgather = 0; + rad_op op_dnorm = 0, op_dhead = 0, op_dsamp[kCodes] = {}, op_demb[kCodes] = {}; + rad_buf b_dseq = 0, b_dx = 0, b_dq = 0, b_dk = 0, b_dv = 0, b_dh2 = 0, b_dgu = 0; + rad_buf b_dsel = 0, b_drow = 0, b_dlog = 0, b_demb = 0, b_dcu = 0; + rad_op op_dcu = 0; + ActFP8 a_dh{}, a_dattn{}, a_dffn{}; + std::vector dep; + rad_buf b_mix = 0; /* [lanes * kMaxFrames, n_embd] PERSIST */ + rad_weight w_mixl = 0, w_mixs = 0; + + /* ---- the window: condition encoder, denoiser */ + rad_weight w_cconv = 0, w_cbias = 0; + rad_op op_ccu = 0, op_cconv = 0, op_cres = 0, op_cjoin = 0; + rad_buf b_ccu = 0, b_cc = 0; + rad_buf b_lat = 0, b_wcond = 0, b_prev = 0, b_pcond = 0, b_noise = 0; /* PERSIST, lanes */ + rad_op op_prep = 0, op_win_in = 0, op_pre = 0, op_pin = 0, op_finish = 0, op_euler = 0; + rad_weight w_pre = 0, w_pin = 0, w_tw = 0, w_t1 = 0, w_t1b = 0, w_t2 = 0, w_t2b = 0; + rad_weight w_pout = 0, w_post = 0; + rad_op op_four = 0, op_t1 = 0, op_tsilu = 0, op_t2 = 0, op_hscat = 0, op_tscat = 0; + rad_op op_hgather = 0, op_pout = 0, op_post = 0; + rad_buf b_din = 0, b_dpre = 0, b_hl = 0, b_tf = 0, b_te1 = 0, b_te1s = 0, b_temb = 0; + rad_buf b_h = 0, b_qkv = 0, b_ao = 0, b_th2 = 0, b_ff = 0, b_ffa = 0, b_ho = 0, b_po = 0; + rad_buf b_vel = 0; + ActFP8 a_th{}, a_tattn{}; + std::vector dit; + int64_t C = 128, Dc = 2048; + + /* ---- the vocoder */ + VConv v_in{}, v_conv{}, v_out{}; + rad_weight v_aout = 0; + rad_op op_vsplit = 0, op_vsout = 0, op_vcu0 = 0, op_vcu_out = 0, op_vmix = 0; + VBlock vb[4]; + int64_t v_ups[4] = { 8, 8, 4, 2 }; + rad_buf b_vx = 0, b_vin = 0, b_vout = 0; + rad_buf b_vcu[5] = {}, b_vstage[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {}; + rad_buf b_audio = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== declare helpers */ +static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op ar_op(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +static rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { x }, { y }); +} + +static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n, + std::initializer_list in, std::initializer_list out) { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + in, out); +} + +/* A plain weight copied from the checkpoint, declared at `dtype`. */ +static rad_weight wcopy(RadBuilder* b, Names& nm, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int group, int shard = RAD_SHARD_NONE, + std::initializer_list row_parts = {}) { + if (map_copy(b, dn, src) < 0) return 0; + (void)nm; + return decl_w(b, dn, dtype, shape, RAD_ACCESS_PER_TOKEN, shard, grp_layer(group), 0, row_parts); +} + +/* ================================================================== the language model */ +/* One Qwen3 layer's weights and ops over `rows` rows, `pre` the checkpoint's prefix. */ +static int declare_qwen3_layer(RadBuilder* b, Names& nm, const Geom& g, LmLayer& L, int li, + const char* dn, const char* pre, int group, int64_t rows, + bool qk_norm, bool paged, rad_kvgroup kv, rad_buf x, ActFP8& ah, + rad_buf bq, rad_buf bk, rad_buf bv, ActFP8& aattn, rad_buf h2, + rad_buf gu, ActFP8& affn, const char* n1, const char* n2, + const char* qn, const char* kn, const char* qs, const char* ks, + const char* vs, const char* os, const char* gs, const char* us, + const char* ds, rad_buf x_in) { + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ARCH_TRY(map_copy(b, nm.f("%s.%d.attn_norm.weight", dn, li), nm.ckpt("%s.%d.%s", pre, li, n1))); + L.w_n1 = decl_w(b, nm.f("%s.%d.attn_norm.weight", dn, li), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); + RAD_ARCH_TRY(map_copy(b, nm.f("%s.%d.ffn_norm.weight", dn, li), nm.ckpt("%s.%d.%s", pre, li, n2))); + L.w_n2 = decl_w(b, nm.f("%s.%d.ffn_norm.weight", dn, li), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); + /* Layer 0 of a stack may read its input from another buffer than its residual: the depth + * decoder's sequence is rebuilt a row at a time and must survive the stack, so its first layer + * reads it and writes the residual. */ + L.op_n1 = norm_op(b, rows, g.n_embd, g.eps, L.w_n1, x_in, ah.x); + RAD_ARCH_TRY(L.q_h.declare(b, g, ah, g.n_embd)); + RAD_ARCH_TRY(L.q.declare(b, nm, g, nm.f("%s.%d.attn_q", dn, li), q_dim, g.n_embd, RAD_SHARD_ROW, + grp_layer(group), { nm.ckpt("%s.%d.%s", pre, li, qs) }, ah, bq, rows)); + RAD_ARCH_TRY(L.k.declare(b, nm, g, nm.f("%s.%d.attn_k", dn, li), kv_dim, g.n_embd, RAD_SHARD_ROW, + grp_layer(group), { nm.ckpt("%s.%d.%s", pre, li, ks) }, ah, bk, rows)); + RAD_ARCH_TRY(L.v.declare(b, nm, g, nm.f("%s.%d.attn_v", dn, li), kv_dim, g.n_embd, RAD_SHARD_ROW, + grp_layer(group), { nm.ckpt("%s.%d.%s", pre, li, vs) }, ah, bv, rows)); + if (qk_norm) { + RAD_ARCH_TRY(map_copy(b, nm.f("%s.%d.q_norm.weight", dn, li), nm.ckpt("%s.%d.%s", pre, li, qn))); + L.w_qn = decl_w(b, nm.f("%s.%d.q_norm.weight", dn, li), RAD_F32, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); + RAD_ARCH_TRY(map_copy(b, nm.f("%s.%d.k_norm.weight", dn, li), nm.ckpt("%s.%d.%s", pre, li, kn))); + L.w_kn = decl_w(b, nm.f("%s.%d.k_norm.weight", dn, li), RAD_F32, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); + /* Each norm in place: a row's scale is computed before the row is written. */ + L.op_qn = norm_op(b, rows * g.n_head, g.head_dim, g.eps, L.w_qn, bq, bq); + L.op_kn = norm_op(b, rows * g.n_head_kv, g.head_dim, g.eps, L.w_kn, bk, bk); + L.op_rq = rw(b, decl_rope(b, g, rows, g.head_dim, g.n_head, 0, g.head_dim, "neox"), { bq }, { bq }); + L.op_rk = rw(b, decl_rope(b, g, rows, g.head_dim, g.n_head_kv, 0, g.head_dim, "neox"), { bk }, { bk }); + } + if (paged) { + /* A frame is one row a sequence, decode's band; a prompt chunk attends to its cached + * prefix and its own rows (attn_prefix_self), which serves every chunk length at this + * head geometry. */ + L.op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, 1), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", 0), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + { bq }, { aattn.x }); + L.op_attn_p = rw(b, RAD_OP(b, "attn_prefix_self", + RAD_PARAMS(RAD_INT("q_len", rows), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("causal", 1), RAD_STR("q_dtype", "bf16"), + RAD_STR("kv_dtype", g.kv_dtype), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_ctx", g.max_ctx), RAD_INT("n_head", g.n_head), + RAD_INT("max_seqs", g.max_seqs), RAD_STR("qk", "bf16")), + RAD_NOWEIGHTS), + { bq, bk, bv }, { aattn.x }); + L.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, rows), 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), + { bk, bv }, {}); + } else { + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", kCodes)), + RAD_NOWEIGHTS), + { bq, bk, bv }, { aattn.x }); + } + RAD_ARCH_TRY(L.q_attn.declare(b, g, aattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("%s.%d.attn_output", dn, li), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(group), { nm.ckpt("%s.%d.%s", pre, li, os) }, + aattn, h2, rows)); + L.op_ar1 = ar_op(b, g, h2, rows); + L.op_add1 = add_op(b, rows, g.n_embd, x_in, h2, x); + L.op_n2 = norm_op(b, rows, g.n_embd, g.eps, L.w_n2, x, ah.x); + RAD_ARCH_TRY(L.q_h2.declare(b, g, ah, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("%s.%d.ffn_gate_up", dn, li), 2 * g.n_ff, + g.n_embd, RAD_SHARD_ROW, grp_layer(group), + { nm.ckpt("%s.%d.%s", pre, li, gs), nm.ckpt("%s.%d.%s", pre, li, us) }, + ah, gu, rows, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, gu, affn, g.n_ff, "silu", rows, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("%s.%d.ffn_down", dn, li), g.n_embd, g.n_ff, + RAD_SHARD_COL, grp_layer(group), { nm.ckpt("%s.%d.%s", pre, li, ds) }, + affn, h2, rows)); + L.op_ar2 = ar_op(b, g, h2, rows); + L.op_add2 = add_op(b, rows, g.n_embd, x, h2, x); + return RAD_OK; +} + +static void step_qwen3_layer(RadCtx* c, const Model& m, const Geom& g, const LmLayer& L, + const RadBatch* batch, int64_t T, rad_buf x, rad_buf x_in, + const ActFP8& ah, rad_buf bq, rad_buf bk, rad_buf bv, + const ActFP8& aattn, rad_buf h2, rad_buf gu, const ActFP8& affn, + const RadOperand& cu, int64_t n_seq) { + const int layer = (int)(&L - (L.op_kv ? m.lm.data() : m.dep.data())); + RAD_ISSUE(c, L.op_n1, brows(x_in, T), RAD_W(L.w_n1), brows(ah.x, T)); + L.q_h.step(c, T); + L.q.step(c, ah, bq, T); + L.k.step(c, ah, bk, T); + L.v.step(c, ah, bv, T); + if (L.op_qn) { + const RadOperand pos = praw(batch->positions, RAD_I32, T); + RAD_ISSUE_N(c, L.op_qn, T * g.n_head, brows(bq, T), RAD_W(L.w_qn), brows(bq, T)); + RAD_ISSUE_N(c, L.op_kn, T * g.n_head_kv, brows(bk, T), RAD_W(L.w_kn), brows(bk, T)); + RAD_ISSUE(c, L.op_rq, brows(bq, T), pos); + RAD_ISSUE(c, L.op_rk, brows(bk, T), pos); + } + if (L.op_kv) { + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv); + const RadOperand bt = praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + const RadOperand bcu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + if (batch->gen == RAD_GEN_PASS_PROMPT) { + /* The prefix first, read from the cache before this chunk's rows go in. */ + RAD_ISSUE(c, L.op_attn_p, brows(bq, T), brows(bk, T), brows(bv, T), kv_cache(m.kv, layer), + bt, praw(batch->agen_b->prefix, RAD_I32, batch->n_seq), bcu, RAD_NONE, + RAD_NONE, RAD_NONE, RAD_NONE, brows(aattn.x, T), RAD_NONE); + RAD_ISSUE(c, L.op_kv, brows(bk, T), brows(bv, T), praw(kvb->slot_mapping, RAD_I32, T), + kv_cache(m.kv, layer)); + } else { + RAD_ISSUE(c, L.op_kv, brows(bk, T), brows(bv, T), praw(kvb->slot_mapping, RAD_I32, T), + kv_cache(m.kv, layer)); + RAD_ISSUE_N(c, L.op_attn, batch->max_q_len, brows(bq, T), kv_cache(m.kv, layer), bt, + praw(kvb->seqused, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, bcu, + brows(aattn.x, T)); + } + } else { + RAD_ISSUE_N(c, L.op_attn, T, brows(bq, T), brows(bk, T), brows(bv, T), cu, brows(aattn.x, T)); + } + (void)n_seq; + L.q_attn.step(c, T); + L.o.step(c, aattn, h2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * g.n_embd, brows(h2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add1, brows(x_in, T), brows(h2, T), brows(x, T)); + RAD_ISSUE(c, L.op_n2, brows(x, T), RAD_W(L.w_n2), brows(ah.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, ah, gu, T); + L.gq.step(c, gu, T); + L.down.step(c, affn, h2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(h2, T), RAD_NONE); + RAD_ISSUE(c, L.op_add2, brows(x, T), brows(h2, T), brows(x, T)); +} + +static int declare_lm(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Model& m) { + Geom& g = m.gl; + Names& nm = m.nm; + const int64_t T = g.max_tok; + (void)meta; + /* bf16 or block fp8, as the container holds the first projection: every linear of the three + * transformers follows it (rad_fp8.h, Geom::w_bf16). */ + m.lm.resize((size_t)g.n_layer); + RAD_ARCH_TRY(m.lm[0].q.probe(b, nm, g, "lm.0.attn_q", { "model.layers.0.self_attn.q_proj.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("lm.0.attn_q.weight"), &e) && rad_enc_is(&e, "plain"); + g.w_bf16 = m.gd.w_bf16 = m.gt.w_bf16 = plain; + + { + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + kd.n_head_kv = g.n_head_kv; + kd.head_dim = g.head_dim; + m.kv = rad_decl_kv_group(b, nm.f("kv_lm"), &kd); + if (!m.kv) return RAD_E_INVAL; + for (int64_t l = 0; l < g.n_layer; ++l) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv)); + g.kv_dtype = rad_dtype_name(kd.dtype); + } + + m.b_x = decl_b(b, nm.f("lm.x"), RAD_BF16, { T, g.n_embd }); + m.a_h.x = decl_b(b, nm.f("lm.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "lm.h", g.n_embd)); + m.b_q = decl_b(b, nm.f("lm.q"), RAD_BF16, { T, g.q_dim() }); + m.b_k = decl_b(b, nm.f("lm.k"), RAD_BF16, { T, g.kv_dim() }); + m.b_v = decl_b(b, nm.f("lm.v"), RAD_BF16, { T, g.kv_dim() }); + m.a_attn.x = decl_b(b, nm.f("lm.attn"), RAD_BF16, { T, g.q_dim() }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "lm.attn", g.q_dim())); + m.b_h2 = decl_b(b, nm.f("lm.h2"), RAD_BF16, { T, g.n_embd }); + m.b_gu = decl_b(b, nm.f("lm.gu"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("lm.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "lm.ffn", g.n_ff)); + m.b_last = decl_b(b, nm.f("lm.last"), RAD_BF16, { T, g.n_embd }); + + m.w_tok = wcopy(b, nm, nm.f("lm.tok.weight"), "model.embed_tokens.weight", RAD_BF16, + { g.n_vocab_all, g.n_embd }, -1); + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_x }); + + for (int64_t l = 0; l < g.n_layer; ++l) + RAD_ARCH_TRY(declare_qwen3_layer( + b, nm, g, m.lm[(size_t)l], (int)l, "lm", "model.layers", kGrpLm + (int)l, T, true, true, + m.kv, m.b_x, m.a_h, m.b_q, m.b_k, m.b_v, m.a_attn, m.b_h2, m.b_gu, m.a_ffn, + "input_layernorm.weight", "post_attention_layernorm.weight", "self_attn.q_norm.weight", + "self_attn.k_norm.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", + "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.gate_proj.weight", + "mlp.up_proj.weight", "mlp.down_proj.weight", m.b_x)); + + RAD_ARCH_TRY(map_copy(b, nm.f("lm.norm.weight"), "model.norm.weight")); + m.w_norm = decl_w(b, nm.f("lm.norm.weight"), RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + m.op_norm = norm_op(b, T, g.n_embd, g.eps, m.w_norm, m.b_x, m.b_last); + + /* The head over the rows a frame can be: the semantic codes, then the end of the song. */ + RAD_ARCH_TRY(map_rows(b, nm.f("lm.head.weight"), + { { "lm_head.weight", kCodeOffset, kSemCodes }, + { "lm_head.weight", kEndToken, 1 } })); + m.w_head = decl_w(b, nm.f("lm.head.weight"), RAD_BF16, { kSemCodes + 1, g.n_embd }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + return m.w_tok && m.w_norm && m.w_head && m.op_embed ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the frame */ +static int declare_frame(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& gd = m.gd; + Names& nm = m.nm; + const int64_t S = m.S, D = m.gl.n_embd, R = (int64_t)kCodes * S; + const int64_t lanes = m.lanes; + + m.b_hid = decl_b(b, nm.f("frame.hid"), RAD_BF16, { 2 * lanes, D }, RAD_BUF_PERSIST); + m.b_status = decl_b(b, nm.f("frame.status"), RAD_I32, { lanes }, RAD_BUF_PERSIST); + m.b_slog = decl_b(b, nm.f("frame.slog"), RAD_BF16, { S, kSemCodes + 1 }); + m.b_codes = decl_b(b, nm.f("frame.codes"), RAD_I32, { kCodes, S }); + m.b_idx = decl_b(b, nm.f("frame.idx"), RAD_I32, { kCodes, S }); + m.b_planes = decl_b(b, nm.f("frame.planes"), RAD_BF16, { (int64_t)kCodes * S, D }); + m.b_mix = decl_b(b, nm.f("frame.mix"), RAD_BF16, { lanes * kMaxFrames, D }, RAD_BUF_PERSIST); + + /* The lanes' hidden states into the pass's rows, plane 0 of the frame's conditioning. */ + m.op_hsel = rows_op(b, "gather_rows", S, D, { m.b_hid }, { m.b_planes }); + m.op_sem = gemm_op(b, S, kSemCodes + 1, D, m.w_head, m.b_planes, m.b_slog); + auto sampler = [&](int64_t V, int stream, int cond_k, rad_buf lg) { + return rw(b, RAD_OP(b, "cfg_topk_sample", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", V), RAD_INT("k", kTopK), + RAD_INT("rep", 2), RAD_INT("cond_k", cond_k), + RAD_F64("cfg", kArCfg), RAD_F64("temp", 1.0), + RAD_INT("stream", stream), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { lg }, { m.b_codes }); + }; + m.op_dsamp[0] = sampler(kSemCodes + 1, 0, kTopK, m.b_slog); + m.op_status = rw(b, RAD_OP(b, "end_status", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("end", kSemCodes), + RAD_INT("rep", 2)), + RAD_NOWEIGHTS), + { m.b_codes }, { m.b_status }); + for (int p = 0; p < kCodes; ++p) + m.op_iota[p] = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("start", p), + RAD_INT("step", kCodes)), + RAD_NOWEIGHTS), + {}, { m.b_idx }); + + /* ---- the depth decoder */ + gd = m.gl; + gd.n_layer = rad_meta_geti(meta, "rvq_depth_decoder.num_layers", 4); + gd.n_embd = rad_meta_geti(meta, "rvq_depth_decoder.hidden_size", 4096); + gd.n_head_all = rad_meta_geti(meta, "rvq_depth_decoder.num_attention_heads", 16); + gd.n_head_kv_all = gd.n_head_all; + gd.head_dim = gd.n_embd / gd.n_head_all; + gd.n_ff_all = rad_meta_geti(meta, "rvq_depth_decoder.intermediate_size", 6144); + gd.eps = 1e-6f; + gd.max_tok = R; + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "the depth decoder's heads", &gd.n_head)); + gd.n_head_kv = gd.n_head; + gd.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the depth decoder's feed-forward", &gd.n_ff)); + if (gd.n_embd != D || gd.head_dim != 256 || + rad_meta_geti(meta, "rvq_depth_decoder.num_codebooks", kCodes) != kCodes || + rad_meta_geti(meta, "rvq_depth_decoder.audio_vocab_size", kResCodes) != kResCodes) { + fprintf(stderr, "radiance: minimaxmusic3: the depth decoder is not the released one (width " + "%lld, head %lld)\n", (long long)gd.n_embd, (long long)gd.head_dim); + return RAD_E_UNSUPPORTED; + } + const char* dp = "rvq_depth_decoder"; + m.w_dproj = wcopy(b, nm, nm.f("dep.proj.weight"), nm.ckpt("%s.projection.weight", dp), RAD_BF16, + { D, D }, kGrpDepth); + m.w_dpos = wcopy(b, nm, nm.f("dep.pos.weight"), nm.ckpt("%s.pos_embedding.weight", dp), RAD_BF16, + { 16, D }, kGrpDepth); + RAD_ARCH_TRY(map_copy(b, nm.f("dep.norm.weight"), nm.ckpt("%s.norm.weight", dp))); + m.w_dnorm = decl_w(b, nm.f("dep.norm.weight"), RAD_F32, { D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpDepth)); + RAD_ARCH_TRY(map_concat(b, nm.f("dep.heads.weight"), + { nm.ckpt("%s.audio_heads.0.weight", dp), nm.ckpt("%s.audio_heads.1.weight", dp), + nm.ckpt("%s.audio_heads.2.weight", dp), nm.ckpt("%s.audio_heads.3.weight", dp), + nm.ckpt("%s.audio_heads.4.weight", dp), nm.ckpt("%s.audio_heads.5.weight", dp), + nm.ckpt("%s.audio_heads.6.weight", dp) })); + m.w_dheads = decl_w(b, nm.f("dep.heads.weight"), RAD_BF16, { (kCodes - 1) * kResCodes, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpDepth)); + m.w_demb = wcopy(b, nm, nm.f("dep.emb.weight"), nm.ckpt("%s.audio_embeddings.weight", dp), + RAD_BF16, { (kCodes - 1) * kResCodes, D }, kGrpDepth); + + m.b_dseq = decl_b(b, nm.f("dep.seq"), RAD_BF16, { R, D }); + m.b_dx = decl_b(b, nm.f("dep.x"), RAD_BF16, { R, D }); + m.a_dh.x = decl_b(b, nm.f("dep.h"), RAD_BF16, { R, D }); + RAD_ARCH_TRY(m.a_dh.declare_qs(b, nm, gd, "dep.h", D, R)); + m.b_dq = decl_b(b, nm.f("dep.q"), RAD_BF16, { R, gd.q_dim() }); + m.b_dk = decl_b(b, nm.f("dep.k"), RAD_BF16, { R, gd.kv_dim() }); + m.b_dv = decl_b(b, nm.f("dep.v"), RAD_BF16, { R, gd.kv_dim() }); + m.a_dattn.x = decl_b(b, nm.f("dep.attn"), RAD_BF16, { R, gd.q_dim() }); + RAD_ARCH_TRY(m.a_dattn.declare_qs(b, nm, gd, "dep.attn", gd.q_dim(), R)); + m.b_dh2 = decl_b(b, nm.f("dep.h2"), RAD_BF16, { R, D }); + m.b_dgu = decl_b(b, nm.f("dep.gu"), RAD_BF16, { R, 2 * gd.n_ff }); + m.a_dffn.x = decl_b(b, nm.f("dep.ffn"), RAD_BF16, { R, gd.n_ff }); + RAD_ARCH_TRY(m.a_dffn.declare_qs(b, nm, gd, "dep.ffn", gd.n_ff, R)); + m.b_dcu = decl_b(b, nm.f("dep.cu"), RAD_I32, { S + 1 }); + m.op_dcu = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, S + 1), RAD_INT("mult", kCodes)), + RAD_NOWEIGHTS), + {}, { m.b_dcu }); + m.b_dsel = decl_b(b, nm.f("dep.sel"), RAD_BF16, { S, D }); + m.b_drow = decl_b(b, nm.f("dep.row"), RAD_BF16, { S, D }); + m.b_dlog = decl_b(b, nm.f("dep.log"), RAD_BF16, { S, kResCodes }); + m.b_demb = decl_b(b, nm.f("dep.emb"), RAD_BF16, { S, D }); + + m.dep.resize((size_t)gd.n_layer); + for (int64_t l = 0; l < gd.n_layer; ++l) + RAD_ARCH_TRY(declare_qwen3_layer( + b, nm, gd, m.dep[(size_t)l], (int)l, "dep", "rvq_depth_decoder.layers", + kGrpDepth + 1 + (int)l, R, false, false, 0, m.b_dx, m.a_dh, m.b_dq, m.b_dk, m.b_dv, + m.a_dattn, m.b_dh2, m.b_dgu, m.a_dffn, "input_layernorm.weight", + "post_attention_layernorm.weight", nullptr, nullptr, "attn.to_q.weight", + "attn.to_k.weight", "attn.to_v.weight", "attn.to_out.weight", "gate_proj.weight", + "up_proj.weight", "down_proj.weight", l == 0 ? m.b_dseq : m.b_dx)); + /* Each layer's attention also reads the frame's sequence offsets. */ + for (const LmLayer& L : m.dep) RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_dcu, 1)); + + /* A depth position's input row: projection plus the position's embedding (one bias row of the + * table), scattered to the position in every sequence. */ + for (int p = 0; p < kCodes; ++p) + m.op_dproj[p] = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", D), RAD_INT("K", D), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_dproj, m.w_dpos)), + { m.b_demb }, { m.b_drow }); + m.op_dscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_drow, m.b_idx }, { m.b_dseq }); + m.op_dgather = rows_op(b, "gather_rows", S, D, { m.b_dx, m.b_idx }, { m.b_dsel }); + m.op_dnorm = norm_op(b, S, D, gd.eps, m.w_dnorm, m.b_dsel, m.b_planes); + m.op_dhead = gemm_op(b, S, kResCodes, D, m.w_dheads, m.b_planes, m.b_dlog); + for (int p = 1; p < kCodes; ++p) m.op_dsamp[p] = sampler(kResCodes, p, 0, m.b_dlog); + /* A code's embedding: position 1 reads the language model's table at the semantic code, + * position p > 1 the residual table at code p - 1's block. */ + auto embed1 = [&](rad_weight t, int64_t off) { + return rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), RAD_INT("n_codes", 1), + RAD_INT("vocab", kResCodes), RAD_INT("off0", off), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(t, m.w_demb)), + { m.b_codes }, { m.b_demb }); + }; + m.op_demb[1] = embed1(m.w_tok, kCodeOffset); + for (int p = 2; p < kCodes; ++p) m.op_demb[p] = embed1(m.w_demb, (int64_t)(p - 2) * kResCodes); + + /* ---- the frame's conditioning row, and the next input of the language model */ + m.w_mixl = wcopy(b, nm, nm.f("cond.mix.logits"), "condition_encoder.layer_weight_logits", RAD_F32, + { kCodes }, kGrpCond); + m.w_mixs = wcopy(b, nm, nm.f("cond.mix.scale"), "condition_encoder.layer_scale", RAD_F32, { 1 }, + kGrpCond); + m.op_mix = rw(b, RAD_OP(b, "frame_mix_store", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("n_embd", D), + RAD_INT("L", kCodes), RAD_INT("stride", kMaxFrames), + RAD_INT("rep", 2), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_mixl, m.w_mixs)), + { m.b_planes, m.b_status }, { m.b_mix }); + m.op_fb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes), RAD_INT("vocab", kResCodes), + RAD_INT("off0", kCodeOffset), + RAD_F64("scale", 1.0 / std::sqrt((double)kCodes)), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_tok, m.w_demb)), + { m.b_codes }, { m.b_x }); + /* The language model's last rows: normed (a prompt's last row a branch, or a frame's row) and + * into the lane's state. */ + m.op_plast = rows_op(b, "gather_rows", S, D, { m.b_x }, { m.b_dsel }); + m.op_pnorm = norm_op(b, S, D, m.gl.eps, m.w_norm, m.b_dsel, m.b_last); + m.op_store = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_last }, { m.b_hid }); + return m.w_dproj && m.w_dpos && m.w_dheads && m.w_demb && m.w_mixl && m.w_mixs ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the window */ +static int declare_window(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& gt = m.gt; + Names& nm = m.nm; + const int64_t lanes = m.lanes, D = m.gl.n_embd; + const int64_t C = rad_meta_geti(meta, "transformer.in_channels", 128); + const int64_t Dc = rad_meta_geti(meta, "transformer.condition_dim", 2048); + m.C = C; + m.Dc = Dc; + const int64_t T = gt.max_tok; + + gt = m.gl; + gt.n_layer = rad_meta_geti(meta, "transformer.num_layers", 36); + gt.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 64); + gt.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 32); + gt.n_head_kv_all = gt.n_head_all; + gt.n_embd = gt.head_dim * gt.n_head_all; + gt.n_ff_all = rad_meta_geti(meta, "transformer.ff_inner_dim", 8192); + gt.eps = 1e-5f; + gt.theta = 10000.0f; + gt.rope_mc = false; + gt.max_tok = m.gl.max_tok; + RAD_ARCH_TRY(divide_or_fail(gt.n_head_all, gt.world, "the DiT's heads", >.n_head)); + gt.n_head_kv = gt.n_head; + gt.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gt.n_ff_all, gt.world, "the DiT's feed-forward", >.n_ff)); + const int64_t H = gt.n_embd, rot = rad_meta_geti(meta, "transformer.rotary_dim", 32); + const int64_t F = rad_meta_geti(meta, "transformer.fourier_embedding_dim", 256); + const int64_t Wd = 2 * C + Dc; /* [lat | zeros | cond] */ + if (gt.head_dim != 64 || C != 128 || Dc != 2048 || F != 256) { + fprintf(stderr, "radiance: minimaxmusic3: the DiT is not the released one (head %lld, %lld " + "latent channels, %lld conditioning)\n", (long long)gt.head_dim, + (long long)C, (long long)Dc); + return RAD_E_UNSUPPORTED; + } + + /* ---- the window states, a lane a song */ + m.b_lat = decl_b(b, nm.f("win.lat"), RAD_BF16, { lanes * kWinLat, C }, RAD_BUF_PERSIST); + m.b_wcond = decl_b(b, nm.f("win.cond"), RAD_BF16, { lanes * kWinLat, Dc }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("win.prev"), RAD_BF16, { lanes * kOverlap, C }, RAD_BUF_PERSIST); + m.b_pcond = decl_b(b, nm.f("win.pcond"), RAD_BF16, { lanes * kOverlap, Dc }, RAD_BUF_PERSIST); + m.b_noise = decl_b(b, nm.f("win.noise"), RAD_BF16, { lanes * kOverlap, C }, RAD_BUF_PERSIST); + + /* ---- the condition encoder: a 3-tap conv over the window's frames, resampled */ + m.b_ccu = decl_b(b, nm.f("win.ccu"), RAD_I32, { 2 }); + m.b_cc = decl_b(b, nm.f("win.cc"), RAD_BF16, { (int64_t)kWinFrames, Dc }); + m.op_ccu = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 1)), + RAD_NOWEIGHTS), + {}, { m.b_ccu }); + m.w_cconv = wcopy(b, nm, nm.f("cond.conv.weight"), "condition_encoder.proj.weight", RAD_BF16, + { Dc, D, 3 }, kGrpCond); + m.w_cbias = wcopy(b, nm, nm.f("cond.conv.bias"), "condition_encoder.proj.bias", RAD_BF16, { Dc }, + kGrpCond); + m.op_cconv = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, kWinFrames), RAD_INT("cin", D), + RAD_INT("cout", Dc), RAD_INT("k", 3), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cconv, m.w_cbias)), + { m.b_mix, m.b_ccu }, { m.b_cc }); + m.op_cres = rows_op(b, "resample_nearest", kWinLat, Dc, { m.b_cc }, { m.b_wcond }); + m.op_cjoin = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kOverlap), RAD_INT("n", Dc), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_pcond }, { m.b_wcond }); + + /* ---- the window step's front: noise and overlap, the input rows, the projections */ + m.op_prep = rw(b, RAD_OP(b, "win_prep", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_INT("stride", kWinLat), RAD_INT("ov", kOverlap), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_prev, m.b_noise, m.b_lat }, { m.b_noise, m.b_lat }); + m.b_din = decl_b(b, nm.f("dit.in"), RAD_BF16, { T, Wd }); + m.b_dpre = decl_b(b, nm.f("dit.pre"), RAD_BF16, { T, Wd }); + m.b_hl = decl_b(b, nm.f("dit.hl"), RAD_BF16, { T, H }); + m.op_win_in = rw(b, RAD_OP(b, "win_input", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_lat", C), RAD_INT("n_zero", C), + RAD_INT("n_cond", Dc), RAD_INT("stride", kWinLat), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_lat, m.b_wcond }, { m.b_din }); + /* preprocess_conv is a 1x1 conv with no bias, then the residual: x = W x + x. */ + m.w_pre = wcopy(b, nm, nm.f("dit.pre.weight"), "transformer.preprocess_conv.weight", RAD_BF16, + { Wd, Wd, 1 }, kGrpDit); + m.op_pre = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", Wd), RAD_INT("cout", Wd), + RAD_INT("k", 1), RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_pre)), + { m.b_din }, { m.b_dpre }); + m.w_pin = wcopy(b, nm, nm.f("dit.proj_in.weight"), "transformer.proj_in.weight", RAD_BF16, + { H, Wd }, kGrpDit); + m.op_pin = gemm_op(b, T, H, Wd, m.w_pin, m.b_dpre, m.b_hl); + + /* ---- the timestep token: Fourier features, a two-linear MLP */ + m.b_tf = decl_b(b, nm.f("dit.tf"), RAD_BF16, { 64, F }); + m.b_te1 = decl_b(b, nm.f("dit.te1"), RAD_BF16, { 64, H }); + m.b_te1s = decl_b(b, nm.f("dit.te1s"), RAD_BF16, { 64, H }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { 64, H }); + m.w_tw = wcopy(b, nm, nm.f("dit.t.fourier"), "transformer.time_proj.weight", RAD_F32, + { F / 2, 1 }, kGrpDit); + m.op_four = rw(b, RAD_OP(b, "fourier_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 64), RAD_INT("n", F), RAD_INT("round", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_tw)), + {}, { m.b_tf }); + m.w_t1 = wcopy(b, nm, nm.f("dit.t.l1.weight"), "transformer.time_embed.linear_1.weight", RAD_BF16, + { H, F }, kGrpDit); + m.w_t1b = wcopy(b, nm, nm.f("dit.t.l1.bias"), "transformer.time_embed.linear_1.bias", RAD_BF16, + { H }, kGrpDit); + m.w_t2 = wcopy(b, nm, nm.f("dit.t.l2.weight"), "transformer.time_embed.linear_2.weight", RAD_BF16, + { H, H }, kGrpDit); + m.w_t2b = wcopy(b, nm, nm.f("dit.t.l2.bias"), "transformer.time_embed.linear_2.bias", RAD_BF16, + { H }, kGrpDit); + m.op_t1 = gemm_bias_op(b, 64, H, F, m.w_t1, m.w_t1b, m.b_tf, m.b_te1); + m.op_tsilu = rows_op(b, "silu", 64, H, { m.b_te1 }, { m.b_te1s }); + m.op_t2 = gemm_bias_op(b, 64, H, H, m.w_t2, m.w_t2b, m.b_te1s, m.b_temb); + + /* ---- the denoiser's rows: each entry's timestep token, then its latents */ + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, H }); + m.op_hscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", H), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_hl }, { m.b_h }); + m.op_tscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, 64), RAD_INT("n", H), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_temb }, { m.b_h }); + + m.a_th.x = decl_b(b, nm.f("dit.hn"), RAD_BF16, { T, H }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, gt, "dit.hn", H)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * gt.q_dim() }); + m.a_tattn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, gt.q_dim() }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, gt, "dit.attn", gt.q_dim())); + m.b_th2 = decl_b(b, nm.f("dit.h2"), RAD_BF16, { T, H }); + m.b_ff = decl_b(b, nm.f("dit.ff"), RAD_BF16, { T, 2 * gt.n_ff }); + m.b_ffa = decl_b(b, nm.f("dit.ffa"), RAD_BF16, { T, gt.n_ff }); + + const int64_t q_dim = gt.q_dim(); + m.dit.resize((size_t)gt.n_layer); + for (int64_t l = 0; l < gt.n_layer; ++l) { + DitLayer& L = m.dit[(size_t)l]; + const int li = (int)l, grp = kGrpDit + 1 + li; + const char* pre = "transformer.transformer_blocks"; + auto ln = [&](const char* dn, const char* src, rad_weight* w) { + *w = wcopy(b, nm, nm.f("dit.%d.%s", li, dn), nm.ckpt("%s.%d.%s", pre, li, src), RAD_F32, + { H }, grp); + return *w ? RAD_OK : RAD_E_INVAL; + }; + RAD_ARCH_TRY(ln("ln1.weight", "norm1.weight", &L.w_n1)); + RAD_ARCH_TRY(ln("ln1.bias", "norm1.bias", &L.w_b1)); + RAD_ARCH_TRY(ln("ln2.weight", "norm2.weight", &L.w_n2)); + RAD_ARCH_TRY(ln("ln2.bias", "norm2.bias", &L.w_b2)); + auto layernorm = [&](rad_weight w, rad_weight bias) { + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", H), + RAD_F64("eps", gt.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { m.b_h }, { m.a_th.x }); + }; + L.op_ln1 = layernorm(L.w_n1, L.w_b1); + RAD_ARCH_TRY(L.q_h.declare(b, gt, m.a_th, H)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, gt, nm.f("dit.%d.attn_qkv", li), 3 * q_dim, H, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.%d.attn.to_q.weight", pre, li), + nm.ckpt("%s.%d.attn.to_k.weight", pre, li), + nm.ckpt("%s.%d.attn.to_v.weight", pre, li) }, + m.a_th, m.b_qkv, 0, { q_dim, q_dim, q_dim })); + L.op_rope = rw(b, decl_rope(b, gt, T, gt.head_dim, gt.n_head, gt.n_head, rot, "neox"), + { m.b_qkv }, { m.b_qkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", gt.head_dim), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)gt.head_dim)), + RAD_INT("max_seqlen", 1 + kWinLat)), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, gt, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, gt, nm.f("dit.%d.attn_output", li), H, q_dim, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.%d.attn.to_out.0.weight", pre, li) }, + m.a_tattn, m.b_th2)); + L.op_ar1 = ar_op(b, gt, m.b_th2, T); + L.op_add1 = add_op(b, T, H, m.b_h, m.b_th2, m.b_h); + L.op_ln2 = layernorm(L.w_n2, L.w_b2); + /* The feed-forward's halves are [value | gate], each row-sharded as its own part, and its + * output projection column-sharded with the bias on rank 0 alone (added once, before the + * all-reduce sums the ranks). */ + L.w_fi = wcopy(b, nm, nm.f("dit.%d.ffn_in.weight", li), nm.ckpt("%s.%d.ff_in.weight", pre, li), + RAD_BF16, { 2 * gt.n_ff, H }, grp, RAD_SHARD_ROW, { gt.n_ff, gt.n_ff }); + L.w_fib = wcopy(b, nm, nm.f("dit.%d.ffn_in.bias", li), nm.ckpt("%s.%d.ff_in.bias", pre, li), + RAD_BF16, { 2 * gt.n_ff }, grp, RAD_SHARD_ROW, { gt.n_ff, gt.n_ff }); + L.w_fo = wcopy(b, nm, nm.f("dit.%d.ffn_out.weight", li), nm.ckpt("%s.%d.ff_out.weight", pre, li), + RAD_BF16, { H, gt.n_ff }, grp, RAD_SHARD_COL); + L.w_fob = wcopy(b, nm, nm.f("dit.%d.ffn_out.bias", li), nm.ckpt("%s.%d.ff_out.bias", pre, li), + RAD_BF16, { H }, grp); + L.op_fi = gemm_bias_op(b, T, 2 * gt.n_ff, H, L.w_fi, L.w_fib, m.a_th.x, m.b_ff); + L.op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", gt.n_ff), + RAD_STR("act", "silu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ff }, { m.b_ffa }); + L.op_fo = gt.rank == 0 ? gemm_bias_op(b, T, H, gt.n_ff, L.w_fo, L.w_fob, m.b_ffa, m.b_th2) + : gemm_op(b, T, H, gt.n_ff, L.w_fo, m.b_ffa, m.b_th2); + L.op_ar2 = ar_op(b, gt, m.b_th2, T); + L.op_add2 = add_op(b, T, H, m.b_h, m.b_th2, m.b_h); + if (!L.op_ln1 || !L.op_rope || !L.op_attn || !L.op_ln2 || !L.op_fi || !L.op_act || !L.op_fo) + return RAD_E_INVAL; + } + + /* ---- the output: the latent rows, proj_out, postprocess_conv's residual, the Euler step */ + m.b_ho = decl_b(b, nm.f("dit.ho"), RAD_BF16, { T, H }); + m.b_po = decl_b(b, nm.f("dit.po"), RAD_BF16, { T, C }); + m.b_vel = decl_b(b, nm.f("dit.v"), RAD_BF16, { T, C }); + m.op_hgather = rows_op(b, "gather_rows", T, H, { m.b_h }, { m.b_ho }); + m.w_pout = wcopy(b, nm, nm.f("dit.proj_out.weight"), "transformer.proj_out.weight", RAD_BF16, + { C, H }, kGrpDit); + m.op_pout = gemm_op(b, T, C, H, m.w_pout, m.b_ho, m.b_po); + m.w_post = wcopy(b, nm, nm.f("dit.post.weight"), "transformer.postprocess_conv.weight", RAD_BF16, + { C, C, 1 }, kGrpDit); + m.op_post = rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("cin", C), RAD_INT("cout", C), + RAD_INT("k", 1), RAD_INT("dil", 1), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_post)), + { m.b_po }, { m.b_vel }); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_INT("stride", kWinLat), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vel, m.b_lat }, { m.b_lat }); + m.op_finish = rw(b, RAD_OP(b, "win_finish", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), RAD_INT("n_cond", Dc), + RAD_INT("stride", kWinLat), RAD_INT("ov", kOverlap), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_wcond, m.b_lat, m.b_prev, m.b_pcond }, { m.b_lat, m.b_prev, m.b_pcond }); + return m.op_cconv && m.op_pre && m.op_pin && m.op_four && m.op_t1 && m.op_t2 && m.op_pout && + m.op_post && m.op_euler && m.op_finish && m.op_prep && m.op_win_in + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the vocoder */ +/* A weight-normalised conv's weight (folded at convert) and bias. */ +static int vconv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, bool wnorm, int64_t rows, rad_buf x, + rad_buf res, rad_buf y, const char* act, rad_buf cu) { + v.cin = cin; v.cout = cout; v.k = k; v.dil = dil; + const char* wn = nm.f("%s.weight", dn); + if (wnorm) RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.weight_g", src), nm.ckpt("%s.weight_v", src))); + else RAD_ARCH_TRY(map_copy(b, wn, nm.ckpt("%s.weight", src))); + v.w = decl_w(b, wn, RAD_BF16, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpVoc)); + v.b = wcopy(b, nm, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpVoc); + if (!v.w || !v.b) return RAD_E_INVAL; + v.op = res ? rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("dil", dil), + RAD_STR("act", act), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(v.w, v.b)), + { x, cu, res }, { y }) + : rw(b, RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", k), RAD_INT("dil", dil), + RAD_STR("act", act), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(v.w, v.b)), + { x, cu }, { y }); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +static rad_weight valpha(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t n) { + return wcopy(b, nm, nm.f("%s.alpha", dn), nm.ckpt("%s.alpha", src), RAD_F32, { 1, n, 1 }, kGrpVoc); +} + +static rad_op snake_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight a, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(a)), + { x }, { y }); +} + +static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf y) { + return rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_INT("mult", mult)), + RAD_NOWEIGHTS), + {}, { y }); +} + +static int declare_vocoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int64_t lat = rad_meta_geti(meta, "vocoder.latent_channels", 128); + const int64_t din = rad_meta_geti(meta, "vocoder.decoder_input_dim", 1024); + const int64_t dh = rad_meta_geti(meta, "vocoder.decoder_hidden_dim", 1536); + if (lat != m.C || rad_meta_geti(meta, "vocoder.sampling_rate", kSampleRate) != kSampleRate) { + fprintf(stderr, "radiance: minimaxmusic3: the vocoder is not the released one\n"); + return RAD_E_UNSUPPORTED; + } + /* Rows at each stage: the window's two streams, stage 0 at the latent rate. */ + const int64_t half = lat / 2; + int64_t rows[5]; + rows[0] = 2 * (int64_t)kWinLat; + for (int i = 0; i < 4; ++i) rows[i + 1] = rows[i] * m.v_ups[i]; + int64_t ch[5]; + ch[0] = dh; + for (int i = 0; i < 4; ++i) ch[i + 1] = dh >> (i + 1); + + m.b_vx = decl_b(b, nm.f("voc.x"), RAD_BF16, { rows[0], half }); + m.op_vsplit = rw(b, RAD_OP(b, "chan_split", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kWinLat), RAD_INT("n", half), + RAD_INT("parts", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_lat }, { m.b_vx }); + for (int s = 0; s < 5; ++s) { + int64_t mult = 1; + for (int i = 0; i < s; ++i) mult *= m.v_ups[i]; + m.b_vcu[s] = decl_b(b, nm.f("voc.cu%d", s), RAD_I32, { 3 }); + if (s == 0) m.op_vcu0 = cu_op(b, 1, m.b_vcu[0]); + else m.vb[s - 1].op_cu = cu_op(b, mult, m.b_vcu[s]); + m.b_vstage[s] = decl_b(b, nm.f("voc.s%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vt[s] = decl_b(b, nm.f("voc.t%d", s), RAD_BF16, { rows[s], ch[s] }); + /* The residual units' two scratch planes; stage 0 has no residual units. */ + if (s > 0) { + m.b_va[s] = decl_b(b, nm.f("voc.a%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vb[s] = decl_b(b, nm.f("voc.b%d", s), RAD_BF16, { rows[s], ch[s] }); + } + } + /* dec_in_proj (1x1, plain weight) into the input width, conv_in to the hidden width. */ + m.b_vin = decl_b(b, nm.f("voc.in"), RAD_BF16, { rows[0], din }); + RAD_ARCH_TRY(vconv(b, nm, m.v_in, "voc.in_proj", "vocoder.dec_in_proj", half, din, 1, 1, false, + rows[0], m.b_vx, 0, m.b_vin, "none", m.b_vcu[0])); + RAD_ARCH_TRY(vconv(b, nm, m.v_conv, "voc.conv_in", "vocoder.conv_in", din, dh, 7, 1, true, rows[0], + m.b_vin, 0, m.b_vstage[0], "none", m.b_vcu[0])); + for (int i = 0; i < 4; ++i) { + VBlock& B = m.vb[i]; + const int64_t ci = ch[i], co = ch[i + 1], s = m.v_ups[i]; + B.cin = ci; B.cout = co; B.stride = s; + const char* bn = nm.f("voc.b%d", i); + const char* bs = nm.ckpt("vocoder.blocks.%d", i); + B.a = valpha(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.snake1", bs), ci); + B.op_s = snake_op(b, rows[i], ci, B.a, m.b_vstage[i], m.b_vt[i]); + const char* wn = nm.f("%s.conv_t.weight", bn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.conv_t1.weight_g", bs), nm.ckpt("%s.conv_t1.weight_v", bs))); + B.wt = decl_w(b, wn, RAD_BF16, { ci, co, 2 * s }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpVoc)); + B.bt = wcopy(b, nm, nm.f("%s.conv_t.bias", bn), nm.ckpt("%s.conv_t1.bias", bs), RAD_BF16, + { co }, kGrpVoc); + B.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[i]), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("stride", s), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.wt, B.bt)), + { m.b_vt[i], m.b_vcu[i] }, { m.b_vstage[i + 1] }); + if (!B.wt || !B.bt || !B.op_t || !B.op_s) return RAD_E_INVAL; + /* Three residual units (dilations 1, 3, 9): x + conv2(snake2(conv1(snake1(x)))), x the + * stage buffer, written back in place by conv2's residual. */ + static const int64_t kDil[3] = { 1, 3, 9 }; + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* us = nm.ckpt("%s.res_unit%d", bs, r + 1); + U.a1 = valpha(b, nm, nm.f("%s.snake1", un), nm.ckpt("%s.snake1", us), co); + U.a2 = valpha(b, nm, nm.f("%s.snake2", un), nm.ckpt("%s.snake2", us), co); + const int64_t R = rows[i + 1]; + U.op_s1 = snake_op(b, R, co, U.a1, m.b_vstage[i + 1], m.b_vt[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.conv1", us), co, co, 7, + kDil[r], true, R, m.b_vt[i + 1], 0, m.b_va[i + 1], "none", + m.b_vcu[i + 1])); + U.op_s2 = snake_op(b, R, co, U.a2, m.b_va[i + 1], m.b_vb[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.conv2", us), co, co, 1, 1, + true, R, m.b_vb[i + 1], m.b_vstage[i + 1], m.b_vstage[i + 1], "none", + m.b_vcu[i + 1])); + if (!U.a1 || !U.a2 || !U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + } + /* snake_out, conv_out to one channel with tanh, and the two streams interleaved. */ + m.v_aout = valpha(b, nm, nm.f("voc.snake_out"), nm.ckpt("vocoder.snake_out"), ch[4]); + m.op_vsout = snake_op(b, rows[4], ch[4], m.v_aout, m.b_vstage[4], m.b_vt[4]); + m.b_vout = decl_b(b, nm.f("voc.out"), RAD_BF16, { rows[4], 1 }); + RAD_ARCH_TRY(vconv(b, nm, m.v_out, "voc.conv_out", "vocoder.conv_out", ch[4], 1, 7, 1, true, + rows[4], m.b_vt[4], 0, m.b_vout, "tanh", m.b_vcu[4])); + m.b_audio = decl_b(b, nm.f("voc.audio"), RAD_F32, { rows[4] / 2, 2 }, RAD_BUF_PERSIST); + m.op_vmix = rw(b, RAD_OP(b, "interleave2", + RAD_PARAMS(RAD_RANGE("M", 1, rows[4] / 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vout }, { m.b_audio }); + return m.v_aout && m.op_vsout && m.op_vmix && m.op_vsplit ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* cls = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strcmp(cls, "MiniMaxMusic3ModularPipeline") != 0) { + fprintf(stderr, "radiance: minimaxmusic3: the container's pipeline is '%s', not " + "MiniMaxMusic3ModularPipeline\n", cls); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "n_vocab", 0) != 200000 && + rad_meta_geti(meta, "vocab_size", 0) != 200000) { + fprintf(stderr, "radiance: minimaxmusic3: the language model's vocabulary is not the " + "released 200000-entry one\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gl, meta, ctx, "bf16", RAD_BF16)); + m.lanes = std::min(kMaxLanes, std::max(1, ctx->max_seqs / 2)); + m.S = 2 * m.lanes; + m.gt.max_tok = m.gl.max_tok; + if (m.gl.max_tok < 2 * (1 + (int64_t)kWinLat)) { + fprintf(stderr, "radiance: minimaxmusic3: a pass carries %lld rows; a window's step needs " + "%lld\n", (long long)m.gl.max_tok, (long long)(2 * (1 + kWinLat))); + return RAD_E_INVAL; + } + + RAD_ARCH_TRY(declare_lm(b, meta, ctx, m)); + RAD_ARCH_TRY(declare_frame(b, meta, m)); + RAD_ARCH_TRY(declare_window(b, meta, m)); + RAD_ARCH_TRY(declare_vocoder(b, meta, m)); + + if (!ctx->shape_probe) { + RadAudioGenDecl d{}; + d.name = "minimax-music3"; + d.tmpl = kTemplate; + d.neg_token = kCfgToken; + d.neg_keep_head = 1; + d.neg_keep_tail = 2; + d.max_prompt = kMaxPrompt; + d.max_frames = kMaxFrames; + d.frame_rate_num = 25; + d.frame_rate_den = 1; + d.win_frames = kWinFrames; + d.win_hop = kWinHop; + d.win_lead = 1; + d.lat_num = kLatNum; + d.lat_den = kLatDen; + d.latent_channels = m.C; + d.win_crop_left = kCropLeft; + d.win_crop_right = kCropRight; + d.samples_per_latent = kSamplesPerLatent; + d.sample_rate = kSampleRate; + d.channels = 2; + d.default_steps = kDitSteps; + d.default_cfg = kDitCfg; + d.max_lanes = m.lanes; + d.status = m.b_status; + d.audio_out = m.b_audio; + d.first_frame = 1; + RAD_ARCH_TRY(rad_declare_audio_generator(b, &d)); + } + rad_note(b, "rank %d/%d: MiniMax-Music3 -- language model %lld layers (%lld heads, %lld KV " + "a rank), depth decoder %lld layers, DiT %lld blocks (%lld heads a rank), %s " + "linears, %lld lanes", + m.gl.rank, m.gl.world, (long long)m.gl.n_layer, (long long)m.gl.n_head, + (long long)m.gl.n_head_kv, (long long)m.gd.n_layer, (long long)m.gt.n_layer, + (long long)m.gt.n_head, m.gl.w_bf16 ? "bf16" : "block-fp8", (long long)m.lanes); + return RAD_OK; +} + +/* ================================================================== step */ +/* The language model over the pass's rows in `b_x`, then the final norm and the store of the + * lanes' hidden states from the rows `last` names (a prompt's last row a branch, or every row of a + * frame). */ +static void step_lm(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gl; + const int64_t T = batch->n_tok; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + for (const LmLayer& L : m.lm) + step_qwen3_layer(c, m, g, L, batch, T, m.b_x, m.b_x, m.a_h, m.b_q, m.b_k, m.b_v, m.a_attn, + m.b_h2, m.b_gu, m.a_ffn, cu, batch->n_seq); +} + +static void store_hidden(RadCtx* c, const Model& m, const RadAudioGenBatch* A, int64_t S, + const int32_t* last_rows, int64_t T) { + const int64_t D = m.gl.n_embd; + RAD_ISSUE_N(c, m.op_plast, S, brows(m.b_x, T), praw(last_rows, RAD_I32, S), brows(m.b_dsel, S)); + RAD_ISSUE_N(c, m.op_pnorm, S, brows(m.b_dsel, S), RAD_W(m.w_norm), brows(m.b_last, S)); + RAD_ISSUE_N(c, m.op_store, S, brows(m.b_last, S), praw(A->slot, RAD_I32, S), + brows(m.b_hid, 2 * m.lanes)); + (void)D; +} + +static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t T = batch->n_tok; + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + step_lm(c, batch, m); + bool any_last = false; + for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i]; + if (any_last) store_hidden(c, m, A, batch->n_seq, A->last_row, T); +} + +static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t n = A->n_lane, S = 2 * n, D = m.gl.n_embd, R = (int64_t)kCodes * S; + const int64_t Sx = m.S; /* the codes' and indices' row pitch */ + const RadOperand seed = praw(A->seed, RAD_U32, 2 * n), frame = praw(A->frame, RAD_I32, n); + const RadOperand lanes = praw(A->lane, RAD_I32, n), slot = praw(A->slot, RAD_I32, S); + auto codes = [&](int p) { return brow_slice(m.b_codes, p, 1, Sx); }; + auto idx = [&](int p) { return brow_slice(m.b_idx, p, 1, Sx); }; + auto plane = [&](int p) { return brow_slice(m.b_planes, (int64_t)p * Sx, S, D); }; + /* The positions' row indices into the depth sequence (constant, cheap to remake). */ + for (int p = 0; p < kCodes; ++p) { + RadOperand o = idx(p); + o.cols = S; + RAD_ISSUE_N(c, m.op_iota[p], S, o); + } + auto idx_s = [&](int p) { RadOperand o = idx(p); o.cols = S; return o; }; + auto codes_s = [&](int p) { RadOperand o = codes(p); o.cols = S; return o; }; + + /* 1. the semantic code, from the lanes' hidden states (plane 0) */ + RAD_ISSUE_N(c, m.op_hsel, S, brows(m.b_hid, 2 * m.lanes), slot, plane(0)); + RAD_ISSUE_N(c, m.op_sem, S, plane(0), RAD_W(m.w_head), brows(m.b_slog, S)); + RAD_ISSUE_N(c, m.op_dsamp[0], S, brows(m.b_slog, S), seed, frame, codes_s(0), RAD_NONE, + RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, m.op_status, n, codes_s(0), lanes, brows(m.b_status, m.lanes)); + + /* 2. the depth decoder's sequence: the hidden state at position 0, the semantic code's + * embedding at 1, then a code a step. */ + auto pos_row = [&](int p) { RadOperand o = RAD_W(m.w_dpos); o.offset = (int64_t)p * D; o.rows = 1; return o; }; + RAD_ISSUE_N(c, m.op_dproj[0], S, plane(0), RAD_W(m.w_dproj), pos_row(0), RAD_NONE, + brows(m.b_drow, S)); + RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx_s(0), brows(m.b_dseq, R)); + RAD_ISSUE_N(c, m.op_demb[1], S, codes(0), RAD_W(m.w_tok), RAD_W(m.w_demb), brows(m.b_demb, S)); + RAD_ISSUE_N(c, m.op_dproj[1], S, brows(m.b_demb, S), RAD_W(m.w_dproj), pos_row(1), RAD_NONE, + brows(m.b_drow, S)); + RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx_s(1), brows(m.b_dseq, R)); + /* The depth sequences' bounds: 8 rows each, from the frame's one row a sequence. */ + RAD_ISSUE_N(c, m.op_dcu, S + 1, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_dcu, S + 1)); + for (int p = 1; p < kCodes; ++p) { + /* The depth stack over every sequence's eight rows; causal attention keeps the rows past + * position p out of the rows it reads. The sequences are 8 rows each: the batch's + * cu_seqlens over 2n frame rows times 8, made by the window op's sibling below. */ + const RadOperand cu8 = brows(m.b_dcu, S + 1); + for (const LmLayer& L : m.dep) + step_qwen3_layer(c, m, m.gd, L, batch, R, m.b_dx, &L == &m.dep[0] ? m.b_dseq : m.b_dx, + m.a_dh, m.b_dq, m.b_dk, m.b_dv, m.a_dattn, m.b_dh2, m.b_dgu, m.a_dffn, + cu8, S); + RAD_ISSUE_N(c, m.op_dgather, S, brows(m.b_dx, R), idx_s(p), brows(m.b_dsel, S)); + RAD_ISSUE_N(c, m.op_dnorm, S, brows(m.b_dsel, S), RAD_W(m.w_dnorm), plane(p)); + RadOperand head = RAD_W(m.w_dheads); + head.offset = (int64_t)(p - 1) * kResCodes * D; + head.rows = kResCodes; + RAD_ISSUE_N(c, m.op_dhead, S, plane(p), head, brows(m.b_dlog, S)); + RAD_ISSUE_N(c, m.op_dsamp[p], S, brows(m.b_dlog, S), seed, frame, codes_s(p), RAD_NONE, + RAD_NONE, RAD_NONE); + if (p + 1 < kCodes) { + RAD_ISSUE_N(c, m.op_demb[p + 1], S, codes(p), RAD_W(m.w_demb), RAD_W(m.w_demb), + brows(m.b_demb, S)); + RAD_ISSUE_N(c, m.op_dproj[p + 1], S, brows(m.b_demb, S), RAD_W(m.w_dproj), + pos_row(p + 1), RAD_NONE, brows(m.b_drow, S)); + RAD_ISSUE_N(c, m.op_dscat, S, brows(m.b_drow, S), idx_s(p + 1), brows(m.b_dseq, R)); + } + } + + /* 3. the frame's conditioning row, and the language model over the frame's embedding */ + RAD_ISSUE_N(c, m.op_mix, n, brows(m.b_planes, (int64_t)kCodes * Sx), RAD_W(m.w_mixl), + RAD_W(m.w_mixs), lanes, frame, brows(m.b_status, m.lanes), + brows(m.b_mix, m.lanes * kMaxFrames)); + RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_tok), RAD_W(m.w_demb), + brows(m.b_x, S)); + step_lm(c, batch, m); + store_hidden(c, m, A, S, A->last_row, S); +} + +static void step_window(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t S = batch->n_seq, R = batch->n_tok, NL = A->lat_rows; + const int64_t C = m.C, Dc = m.Dc, D = m.gl.n_embd, H = m.gt.n_embd; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand lcu = praw(A->lat_cu, RAD_I32, S + 1); + const RadOperand wl = praw(A->win_lane, RAD_I32, S), pair = praw(A->pair, RAD_I32, S); + const RadOperand fl = praw(A->flags, RAD_I32, S); + const int64_t LS = m.lanes * kWinLat, LO = m.lanes * kOverlap; + + /* 0. a window's first step: its conditioning from the frames (each window on its own) */ + for (int64_t e = 0; e < S; ++e) { + if (!(A->flags_h[e] & RAD_AGEN_F_FIRST) || (e > 0 && A->win_lane_h[e] == A->win_lane_h[e - 1])) + continue; + const int64_t L = A->win_lane_h[e], f0 = A->win_frame0_h[e], nf = A->win_frames_h[e]; + const int64_t nl = A->lat_cu_h[e + 1] - A->lat_cu_h[e]; + RAD_ISSUE_N(c, m.op_ccu, 2, praw(A->win_frames + e, RAD_I32, 1), brows(m.b_ccu, 2)); + RAD_ISSUE_N(c, m.op_cconv, nf, brow_slice(m.b_mix, L * kMaxFrames + f0, nf, D), + RAD_W(m.w_cconv), brows(m.b_ccu, 2), RAD_NONE, brows(m.b_cc, nf), + RAD_W(m.w_cbias)); + RAD_ISSUE_N(c, m.op_cres, nl, brows(m.b_cc, nf), brow_slice(m.b_wcond, L * kWinLat, nl, Dc)); + if (A->flags_h[e] & RAD_AGEN_F_JOIN) { + const int64_t ov = std::min(kOverlap, nl); + RAD_ISSUE_N(c, m.op_cjoin, ov, brow_slice(m.b_pcond, L * kOverlap, ov, Dc), + brow_slice(m.b_wcond, L * kWinLat, ov, Dc)); + } + } + /* 1. noise and the overlap's binding, the input rows, preprocess_conv, proj_in */ + RAD_ISSUE_N(c, m.op_prep, NL, fl, praw(A->t, RAD_F32, S), praw(A->seed, RAD_U32, 2 * S), + praw(A->win_index, RAD_I32, S), wl, pair, lcu, brows(m.b_prev, LO), + brows(m.b_noise, LO), brows(m.b_lat, LS)); + RAD_ISSUE_N(c, m.op_win_in, NL, brows(m.b_lat, LS), brows(m.b_wcond, LS), lcu, wl, pair, + brows(m.b_din, NL)); + RAD_ISSUE_N(c, m.op_pre, NL, brows(m.b_din, NL), RAD_W(m.w_pre), lcu, brows(m.b_din, NL), + brows(m.b_dpre, NL), RAD_NONE); + RAD_ISSUE_N(c, m.op_pin, NL, brows(m.b_dpre, NL), RAD_W(m.w_pin), brows(m.b_hl, NL)); + /* 2. the timestep tokens, and every row in its place */ + RAD_ISSUE_N(c, m.op_four, S, praw(A->t, RAD_F32, S), RAD_W(m.w_tw), brows(m.b_tf, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tf, S), RAD_W(m.w_t1), RAD_W(m.w_t1b), RAD_NONE, + brows(m.b_te1, S)); + RAD_ISSUE_N(c, m.op_tsilu, S, brows(m.b_te1, S), brows(m.b_te1s, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_te1s, S), RAD_W(m.w_t2), RAD_W(m.w_t2b), RAD_NONE, + brows(m.b_temb, S)); + RAD_ISSUE_N(c, m.op_hscat, NL, brows(m.b_hl, NL), praw(A->lat_src, RAD_I32, NL), brows(m.b_h, R)); + RAD_ISSUE_N(c, m.op_tscat, S, brows(m.b_temb, S), praw(batch->cu_seqlens, RAD_I32, S), + brows(m.b_h, R)); + /* 3. the blocks */ + const int64_t qd = m.gt.q_dim(); + const RadOperand pos = praw(batch->positions, RAD_I32, R); + for (const DitLayer& L : m.dit) { + RAD_ISSUE(c, L.op_ln1, brows(m.b_h, R), RAD_W(L.w_n1), RAD_W(L.w_b1), brows(m.a_th.x, R)); + L.q_h.step(c, R); + L.qkv.step(c, m.a_th, m.b_qkv, R); + RAD_ISSUE(c, L.op_rope, brows(m.b_qkv, R), pos); + RAD_ISSUE_N(c, L.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + bcol(m.b_qkv, 2 * qd, qd, R), cu, brows(m.a_tattn.x, R)); + L.q_attn.step(c, R); + L.o.step(c, m.a_tattn, m.b_th2, R); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, R * H, brows(m.b_th2, R), RAD_NONE); + RAD_ISSUE(c, L.op_add1, brows(m.b_h, R), brows(m.b_th2, R), brows(m.b_h, R)); + RAD_ISSUE(c, L.op_ln2, brows(m.b_h, R), RAD_W(L.w_n2), RAD_W(L.w_b2), brows(m.a_th.x, R)); + RAD_ISSUE(c, L.op_fi, brows(m.a_th.x, R), RAD_W(L.w_fi), RAD_W(L.w_fib), RAD_NONE, + brows(m.b_ff, R)); + const int64_t f = m.gt.n_ff; + RAD_ISSUE(c, L.op_act, bcol(m.b_ff, f, f, R), bcol(m.b_ff, 0, f, R), brows(m.b_ffa, R)); + if (m.gt.rank == 0) + RAD_ISSUE(c, L.op_fo, brows(m.b_ffa, R), RAD_W(L.w_fo), RAD_W(L.w_fob), RAD_NONE, + brows(m.b_th2, R)); + else + RAD_ISSUE(c, L.op_fo, brows(m.b_ffa, R), RAD_W(L.w_fo), brows(m.b_th2, R)); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, R * H, brows(m.b_th2, R), RAD_NONE); + RAD_ISSUE(c, L.op_add2, brows(m.b_h, R), brows(m.b_th2, R), brows(m.b_h, R)); + } + /* 4. the latent rows out, the velocity, the step, the window's end */ + RAD_ISSUE_N(c, m.op_hgather, NL, brows(m.b_h, R), praw(A->lat_src, RAD_I32, NL), brows(m.b_ho, NL)); + RAD_ISSUE_N(c, m.op_pout, NL, brows(m.b_ho, NL), RAD_W(m.w_pout), brows(m.b_po, NL)); + RAD_ISSUE_N(c, m.op_post, NL, brows(m.b_po, NL), RAD_W(m.w_post), lcu, brows(m.b_po, NL), + brows(m.b_vel, NL), RAD_NONE); + RAD_ISSUE_N(c, m.op_euler, NL, brows(m.b_vel, NL), praw(A->t, RAD_F32, S), + praw(A->t_next, RAD_F32, S), praw(A->cfg, RAD_F32, S), pair, wl, fl, + praw(A->seed, RAD_U32, 2 * S), lcu, RAD_NONE, RAD_NONE, brows(m.b_lat, LS), RAD_NONE); + RAD_ISSUE_N(c, m.op_finish, NL, fl, pair, wl, lcu, brows(m.b_wcond, LS), brows(m.b_lat, LS), + brows(m.b_prev, LO), brows(m.b_pcond, LO)); + (void)C; +} + +static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t nl = A->voc_latents, half = m.C / 2; + int64_t rows[5]; + rows[0] = 2 * nl; + for (int i = 0; i < 4; ++i) rows[i + 1] = rows[i] * m.v_ups[i]; + const RadOperand nlen = praw(batch->cu_seqlens + 1, RAD_I32, 1); + RAD_ISSUE_N(c, m.op_vsplit, nl, brow_slice(m.b_lat, (int64_t)A->voc_lane * kWinLat, nl, m.C), + brows(m.b_vx, 2 * nl)); + RAD_ISSUE_N(c, m.op_vcu0, 3, nlen, brows(m.b_vcu[0], 3)); + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), brows(cu, 3), + res ? brows(res, R) : RAD_NONE, brows(y, R), RAD_W(v.b)); + }; + conv(m.v_in, m.b_vx, 0, m.b_vin, rows[0], m.b_vcu[0]); + conv(m.v_conv, m.b_vin, 0, m.b_vstage[0], rows[0], m.b_vcu[0]); + for (int i = 0; i < 4; ++i) { + const VBlock& B = m.vb[i]; + const int64_t r0 = rows[i], r1 = rows[i + 1]; + RAD_ISSUE_N(c, B.op_cu, 3, nlen, brows(m.b_vcu[i + 1], 3)); + RAD_ISSUE_N(c, B.op_s, r0, brows(m.b_vstage[i], r0), RAD_W(B.a), brows(m.b_vt[i], r0), + RAD_NONE); + RAD_ISSUE_N(c, B.op_t, r0, brows(m.b_vt[i], r0), RAD_W(B.wt), RAD_W(B.bt), + brows(m.b_vcu[i], 3), brows(m.b_vstage[i + 1], r1)); + for (int r = 0; r < 3; ++r) { + const VRes& U = B.res[r]; + RAD_ISSUE_N(c, U.op_s1, r1, brows(m.b_vstage[i + 1], r1), RAD_W(U.a1), + brows(m.b_vt[i + 1], r1), RAD_NONE); + conv(U.c1, m.b_vt[i + 1], 0, m.b_va[i + 1], r1, m.b_vcu[i + 1]); + RAD_ISSUE_N(c, U.op_s2, r1, brows(m.b_va[i + 1], r1), RAD_W(U.a2), + brows(m.b_vb[i + 1], r1), RAD_NONE); + conv(U.c2, m.b_vb[i + 1], m.b_vstage[i + 1], m.b_vstage[i + 1], r1, m.b_vcu[i + 1]); + } + } + RAD_ISSUE_N(c, m.op_vsout, rows[4], brows(m.b_vstage[4], rows[4]), RAD_W(m.v_aout), + brows(m.b_vt[4], rows[4]), RAD_NONE); + conv(m.v_out, m.b_vt[4], 0, m.b_vout, rows[4], m.b_vcu[4]); + /* The two streams, cropped, interleaved into what the core reads back. */ + const int64_t L5 = rows[4] / 2; + const int64_t off = (int64_t)A->voc_left * kSamplesPerLatent; + const int64_t n = (int64_t)(A->voc_latents - A->voc_left - A->voc_right) * kSamplesPerLatent; + RAD_ISSUE_N(c, m.op_vmix, n, brow_slice(m.b_vout, off, n, 1), brow_slice(m.b_vout, L5 + off, n, 1), + brows(m.b_audio, n)); + (void)half; +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->agen_b) { + rad_step_fail(c, "minimaxmusic3 is an audio generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_PROMPT: step_prompt(c, batch, m); return; + case RAD_GEN_PASS_FRAME: step_frame(c, batch, m); return; + case RAD_GEN_PASS_WINDOW: step_window(c, batch, m); return; + case RAD_GEN_PASS_VOCODE: step_vocode(c, batch, m); return; + default: + rad_step_fail(c, "minimaxmusic3: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: a window's step with guidance (two entries of a timestep row and the + * window's latents), and the longest sequence a branch holds. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2048; + out->gen_audio = 1; + out->gen_ctx = (int64_t)kMaxPrompt + kMaxFrames + 1; + return RAD_OK; +} + +/* ================================================================== the request's texts */ +/* diffusers' _clean_caption: <|tag inner|> becomes "tag is inner", markdown heads, bullets, + * emphasis and rules are dropped, and runs of blank lines collapse. */ +static std::string clean_caption(const std::string& in) { + std::string t; + for (size_t i = 0; i < in.size();) { + if (in.compare(i, 2, "<|") == 0) { + const size_t e = in.find("|>", i + 2); + if (e != std::string::npos) { + std::string inner = in.substr(i + 2, e - i - 2); + size_t a = inner.find_first_not_of(" \t"), z = inner.find_last_not_of(" \t"); + inner = a == std::string::npos ? std::string() : inner.substr(a, z - a + 1); + const size_t sp = inner.find_first_of(" \t\n"); + if (sp != std::string::npos) { + const size_t r = inner.find_first_not_of(" \t\n", sp); + t += inner.substr(0, sp) + " is " + (r == std::string::npos ? "" : inner.substr(r)); + } else { + t += inner; + } + i = e + 2; + continue; + } + } + t += in[i++]; + } + std::string out; + size_t pos = 0; + bool first = true; + while (pos <= t.size()) { + size_t nl = t.find('\n', pos); + std::string line = t.substr(pos, nl == std::string::npos ? std::string::npos : nl - pos); + /* a markdown heading: up to three spaces, 1-6 #, a space */ + { + size_t k = 0; + while (k < line.size() && k < 3 && line[k] == ' ') ++k; + size_t h = k; + while (h < line.size() && line[h] == '#' && h - k < 6) ++h; + if (h > k && h < line.size() && (line[h] == ' ' || line[h] == '\t')) { + while (h < line.size() && (line[h] == ' ' || line[h] == '\t')) ++h; + line = line.substr(h); + } + } + /* a bullet: whitespace, one of * + -, whitespace */ + { + size_t k = 0; + while (k < line.size() && (line[k] == ' ' || line[k] == '\t')) ++k; + if (k + 1 < line.size() && (line[k] == '*' || line[k] == '+' || line[k] == '-') && + (line[k + 1] == ' ' || line[k + 1] == '\t')) { + size_t h = k + 1; + while (h < line.size() && (line[h] == ' ' || line[h] == '\t')) ++h; + line = line.substr(h); + } + } + /* **bold** then *italic* */ + for (;;) { + const size_t a = line.find("**"); + if (a == std::string::npos) break; + const size_t z = line.find("**", a + 2); + if (z == std::string::npos || z == a + 2) break; + if (line.substr(a + 2, z - a - 2).find('*') != std::string::npos) break; + line = line.substr(0, a) + line.substr(a + 2, z - a - 2) + line.substr(z + 2); + } + for (size_t a = 0; (a = line.find('*', a)) != std::string::npos;) { + if ((a > 0 && line[a - 1] == '*') || (a + 1 < line.size() && line[a + 1] == '*')) { ++a; continue; } + const size_t z = line.find('*', a + 1); + if (z == std::string::npos || z == a + 1 || line.substr(a + 1, z - a - 1).find('\n') != std::string::npos || + (z + 1 < line.size() && line[z + 1] == '*')) + break; + line = line.substr(0, a) + line.substr(a + 1, z - a - 1) + line.substr(z + 1); + a = z - 1; + } + while (!line.empty() && (line.back() == ' ' || line.back() == '\t' || line.back() == '\r')) + line.pop_back(); + /* a horizontal rule */ + { + std::string s2; + for (char ch : line) if (ch != ' ' && ch != '\t') s2 += ch; + bool rule = s2.size() >= 3; + for (char ch : s2) rule = rule && (ch == '-' || ch == '*' || ch == '_'); + if (rule && (s2.find_first_not_of(s2[0]) == std::string::npos || true)) { + bool same = true; + for (char ch : s2) same = same && (ch == '-' || ch == '*' || ch == '_'); + if (same) line.clear(); + } + } + if (!first) out += '\n'; + out += line; + first = false; + if (nl == std::string::npos) break; + pos = nl + 1; + } + /* "• " and four-space runs go; runs of newlines become one. */ + std::string r; + for (size_t i = 0; i < out.size();) { + if (out.compare(i, 4, "\xE2\x80\xA2 ") == 0) { i += 4; continue; } + if (out.compare(i, 4, " ") == 0) { i += 4; continue; } + if (out[i] == '\n' && !r.empty() && r.back() == '\n') { ++i; continue; } + r += out[i++]; + } + return r; +} + +/* diffusers' _normalize_lyrics: a line that starts with section tags keeps only them; "] " and + * " [" break lines, " ^ " too; tags are lower case; the lyrics start with "[start]". */ +static std::string normalize_lyrics(const std::string& in) { + std::string t; + size_t pos = 0; + bool first = true; + while (pos <= in.size()) { + const size_t nl = in.find('\n', pos); + std::string line = in.substr(pos, nl == std::string::npos ? std::string::npos : nl - pos); + size_t k = 0; + while (k < line.size() && (line[k] == ' ' || line[k] == '\t')) ++k; + size_t e = k; + bool any = false; + while (e < line.size() && line[e] == '[') { + const size_t z = line.find(']', e + 1); + if (z == std::string::npos || z == e + 1) break; + e = z + 1; + any = true; + while (e < line.size() && (line[e] == ' ' || line[e] == '\t')) ++e; + } + if (any) { + std::string tags = line.substr(k, e - k); + while (!tags.empty() && (tags.back() == ' ' || tags.back() == '\t')) tags.pop_back(); + line = tags; + } + if (!first) t += '\n'; + t += line; + first = false; + if (nl == std::string::npos) break; + pos = nl + 1; + } + auto replace = [](std::string s, const std::string& a, const std::string& b) { + for (size_t p = s.find(a); p != std::string::npos; p = s.find(a, p + b.size())) s.replace(p, a.size(), b); + return s; + }; + t = replace(t, "] ", "]\n"); + t = replace(t, " [", "\n["); + t = replace(t, " ^ ", "\n"); + for (size_t a = t.find('['); a != std::string::npos; a = t.find('[', a + 1)) { + const size_t z = t.find(']', a + 1); + if (z == std::string::npos) break; + for (size_t i = a + 1; i < z; ++i) t[i] = (char)std::tolower((unsigned char)t[i]); + } + return "[start]\n" + t; +} + +static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { + if (!in) return RAD_E_INVAL; + std::string r; + if (field == RAD_TEXT_INSTRUCTIONS) r = clean_caption(in); + else if (field == RAD_TEXT_INPUT) r = normalize_lyrics(in); + else r = in; + if ((int64_t)r.size() < cap) { + std::memcpy(out, r.data(), r.size()); + out[r.size()] = 0; + } + return (int64_t)r.size(); +} + +} /* namespace minimaxmusic3 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(minimaxmusic3) +extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) { + return minimaxmusic3::text_prepare(field, in, out, cap); +} +RAD_ARCH_PLUGIN(minimaxmusic3, "minimaxmusic3", "", "0.1.0", + "MiniMax-Music3: a Qwen3-8B music language model with a residual-code depth " + "decoder, a 2.4B flow-matching transformer over windows of frames, and a DAC " + "vocoder; 44.1 kHz stereo") +#endif diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp index b8e1ec7e..ebce7b1b 100644 --- a/arch/qwenimage21/qwenimage21.cpp +++ b/arch/qwenimage21/qwenimage21.cpp @@ -1399,12 +1399,13 @@ static void step_blocks(RadCtx* c, const Model& m, int64_t R, int64_t S, const R brows(m.b_ks, R)); RAD_ISSUE(c, L.op_attn_q, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), bcol(m.b_qkv, 2 * qd, qd, R), kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE, - RAD_NONE, brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R)); + RAD_NONE, brows(m.b_k8, R), brows(m.b_ks, R), brows(m.a_attn.x, R), + RAD_NONE); } else { RAD_ISSUE(c, causal ? L.op_attn_c : L.op_attn_b, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), bcol(m.b_qkv, 2 * qd, qd, R), kv_cache(m.kv, (int)l), bt, used, cu, RAD_NONE, RAD_NONE, RAD_NONE, RAD_NONE, - brows(m.a_attn.x, R)); + brows(m.a_attn.x, R), RAD_NONE); } /* Each wait below is for the all-reduce lane 1 holds last, which is the one lane 0 reads * next: the second half's projection runs under the first half's reduction, the first diff --git a/core/build/rad_build.h b/core/build/rad_build.h index a630785a..6559f969 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -127,6 +127,8 @@ public: int drafter_shared_kv(int pos_offset); int declare_encoder(const RadEncoderDecl* d); int declare_generator(const RadGeneratorDecl* d); + int declare_audio_generator(const RadAudioGenDecl* d); + int declare_video_generator(const RadVideoGenDecl* d); void note_v (const char* f, va_list ap); /* An op's buffer operands (rad_op_reads/rad_op_writes in rad_builder.h), which give the @@ -159,13 +161,13 @@ public: * an io_uring ring, which must not stop a sandboxed conversion. */ void set_instances(bool on) { instances_ = on; } - /* RUNTIME LoRA (core/lora/): the HF module leaves an adapter may target. Set before the - * plugin declares, so a FUSED GEMM over a targeted weight -- a GEMM no adapter delta can ride - * on, the gated gate_up fold -- is declined as it is declared and the plugin emits the unfused - * chain it already has for a library without the fused kernel. Null: nothing is declined. */ + /* Runtime LoRA (core/lora/): the HF module leaves an adapter may target. Set before the plugin + * declares, so a fused GEMM over a targeted weight (the gated gate_up fold), which leaves no + * output for the delta, is declined as it is declared and the plugin emits the unfused chain it + * has for a library without the fused kernel. Null: nothing is declined. */ void set_lora_targets(const std::set* t) { lora_targets_ = t; } - /* The read and write sets an op declared (rad_op_reads / rad_op_writes), for the LoRA declare, - * which needs the dtypes of the activation and the output a targeted GEMM was declared over. */ + /* The read and write sets an op declared (rad_op_reads / rad_op_writes): the LoRA declare reads + * the dtypes of a targeted GEMM's activation and output from them. */ const std::vector& op_read_set (rad_op h) const { return op_bufs_[h].reads; } const std::vector& op_write_set(rad_op h) const { return op_bufs_[h].writes; } diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index abb0144e..e7c877f2 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -703,12 +703,12 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, } } - /* RUNTIME LoRA: A FUSED GEMM OVER A TARGETED WEIGHT IS DECLINED. Every `gemm_*` op other than - * the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue -- - * the gated fold quantises the SiLU product in place -- so the delta has no y to land in. The - * op is recorded resolved to nothing, exactly as a library without the kernel would leave it, - * and the plugin falls back to the unfused chain it emits for that library. The decision reads - * only the weight's own declaration and name map, so the sizing declare makes the same one. */ + /* Runtime LoRA: a fused GEMM over a targeted weight is declined. Every `gemm_*` op other than + * the four an adapter delta can follow (lora::op_is_site) fuses something into its epilogue + * (the gated fold quantises the SiLU product in place), so the delta has no y to land in. The + * op is recorded unresolved, as a library without the kernel would leave it, and the plugin + * runs its unfused chain. The decision reads only the weight's own declaration and name map, + * so the sizing declare makes the same one. */ bool lora_declined = false; if (lora_targets_ && n_w > 0 && oi.op.rfind("gemm_", 0) == 0 && oi.op != "gemm_nt" && oi.op != "gemm_nt_bias" && oi.op != "gemm_nt_q" && oi.op != "gemm_nt_q_bias") { @@ -726,10 +726,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, "output for the adapter's delta (the plugin runs the unfused chain)"; oi.bands.assign(1, none); oi.lora_declined = true; - /* AND IT OWNS NO WEIGHT. The planner, the layout pass and the weight-use bookkeeping all - * read an op's weights, and an op with no kernel anywhere would tell the planner the weight - * cannot be read on the card -- moving the gate_up the unfused chain multiplies on the card - * off it. The op stays in the list, by name, so the sizing declare lines up. */ + /* It owns no weight: the planner reads an op's weights, and an op with no kernel anywhere + * would tell it the weight cannot be read on the card, moving the gate_up the unfused + * chain multiplies off the card. The op stays in the list by name so the sizing declare + * lines up. */ oi.weights.clear(); oi.weight_opd.clear(); prog_.ops.push_back(std::move(oi)); @@ -939,10 +939,23 @@ int Builder::decl_name_map(const RadNameMap* m) { err(RAD_E_INVAL, "name map for '%s': %d source tensors, 1..8 allowed", m->declared, m->n_src); return RAD_E_INVAL; } - if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT) { + if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM && + m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) { err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode); return RAD_E_INVAL; } + if ((m->mode == RAD_MAP_WNORM || m->mode == RAD_MAP_EMA) && m->n_src != 2) { + err(RAD_E_INVAL, "name map for '%s': a %s map names two sources (%s), not %d", + m->declared, m->mode == RAD_MAP_EMA ? "codebook" : "weight-norm", + m->mode == RAD_MAP_EMA ? "the embedding sums and the cluster usage" + : "the magnitude and the direction", m->n_src); + return RAD_E_INVAL; + } + if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) { + err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d", + m->declared, m->n_src); + return RAD_E_INVAL; + } RadNameMap c{}; c.declared = intern(scoped(m->declared)); @@ -961,6 +974,14 @@ int Builder::decl_name_map(const RadNameMap* m) { * also map_base() in arch/common/rad_arch.h), so every map would ask for slice 0. */ for (int i = 0; i < m->n_src; ++i) c.src_index[i] = m->src_index[i]; for (int i = m->n_src; i < 8; ++i) c.src_index[i] = -1; + for (int i = 0; i < 8; ++i) c.src_rows[i] = i < m->n_src ? m->src_rows[i] : 0; + if (m->mode == RAD_MAP_ROWS) + for (int i = 0; i < m->n_src; ++i) + if (m->src_index[i] < 0 || m->src_rows[i] <= 0) { + err(RAD_E_INVAL, "name map for '%s': row piece %d starts at %d and holds %lld rows", + m->declared, i, m->src_index[i], (long long)m->src_rows[i]); + return RAD_E_INVAL; + } /* A CONCAT map may be declared in pieces; any other repeat is an error. * @@ -975,10 +996,12 @@ int Builder::decl_name_map(const RadNameMap* m) { auto seen = name_map_first_.find(c.declared); if (seen != name_map_first_.end()) { const RadNameMap& first = prog_.name_map[seen->second]; - if (c.mode != RAD_MAP_CONCAT || first.mode != RAD_MAP_CONCAT) { - err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT map may be " - "extended -- a repeated COPY map means two sources for one weight, and " - "which one wins is not something a declaration can express", + const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) || + (c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA); + if (!joins) { + err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may " + "be extended -- a repeated COPY map means two sources for one weight, " + "and which one wins is not something a declaration can express", c.declared); return RAD_E_INVAL; } @@ -1022,6 +1045,16 @@ int Builder::declare_logits(rad_buf b) { prog_.gen_str.name.c_str()); return RAD_E_STATE; } + if (prog_.is_audio_generator()) { + err(RAD_E_STATE, "declare_logits: this program already declared the audio generator '%s'", + prog_.agen_str.name.c_str()); + return RAD_E_STATE; + } + if (prog_.is_video_generator()) { + err(RAD_E_STATE, "declare_logits: this program already declared the video generator '%s'", + prog_.vgen_str.name.c_str()); + return RAD_E_STATE; + } prog_.logits_buf = b; return RAD_OK; } @@ -1052,6 +1085,16 @@ int Builder::declare_pooled(rad_buf b) { prog_.gen_str.name.c_str()); return RAD_E_STATE; } + if (prog_.is_audio_generator()) { + err(RAD_E_STATE, "declare_pooled: this program already declared the audio generator '%s'", + prog_.agen_str.name.c_str()); + return RAD_E_STATE; + } + if (prog_.is_video_generator()) { + err(RAD_E_STATE, "declare_pooled: this program already declared the video generator '%s'", + prog_.vgen_str.name.c_str()); + return RAD_E_STATE; + } const RadBufDecl& d = prog_.buffers[b].decl; if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 || d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) { @@ -1140,10 +1183,13 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { prog_.gen_str.name.c_str(), nm); return RAD_E_STATE; } - if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE) { + if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || + prog_.is_audio_generator() || prog_.is_video_generator()) { err(RAD_E_STATE, "declare_generator '%s': this program already declared %s; a program " - "generates text, embeds or makes images -- one of the three", nm, - prog_.logits_buf != RAD_NULL_HANDLE ? "logits" : "a pooled output"); + "generates text, embeds, makes images, audio or video -- one of the five", + nm, prog_.logits_buf != RAD_NULL_HANDLE ? "logits" + : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" + : prog_.is_audio_generator() ? "an audio generator" : "a video generator"); return RAD_E_STATE; } if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) { @@ -1224,6 +1270,258 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { return RAD_OK; } +/* Validated at declare for the reason the image generator is: a buffer too small for the longest + * window, or a window that never ends, would otherwise show at the first request. */ +int Builder::declare_audio_generator(const RadAudioGenDecl* d) { + if (finished_) { + err(RAD_E_STATE, "declare_audio_generator after declare finished"); + return RAD_E_STATE; + } + if (!d) { err(RAD_E_INVAL, "declare_audio_generator: null declaration"); return RAD_E_INVAL; } + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (prog_.is_audio_generator()) { + err(RAD_E_STATE, "declare_audio_generator: '%s' was already declared; '%s' is a second one", + prog_.agen_str.name.c_str(), nm); + return RAD_E_STATE; + } + if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || + prog_.generator.layout != 0 || prog_.is_video_generator()) { + err(RAD_E_STATE, "declare_audio_generator '%s': this program already declared %s; a " + "program generates text, embeds, makes images, audio or video -- one of " + "the five", nm, + prog_.logits_buf != RAD_NULL_HANDLE ? "logits" + : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" + : prog_.generator.layout != 0 ? "an image generator" : "a video generator"); + return RAD_E_STATE; + } + if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) { + err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm); + return RAD_E_INVAL; + } + if (d->tmpl_plain && + (!std::strstr(d->tmpl_plain, "{input}") || std::strstr(d->tmpl_plain, "{instructions}"))) { + err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_plain is the prompt without " + "instructions and needs {input} alone", nm); + return RAD_E_INVAL; + } + if (d->neg_tmpl && !d->prompt_whole) { + err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches " + "of different lengths, which step together only as whole prompts; set " + "prompt_whole", nm); + return RAD_E_INVAL; + } + if (d->max_prompt <= 0 || d->first_frame < 0 || + (!d->neg_tmpl && (d->neg_keep_head < 0 || d->neg_keep_tail < 0 || d->neg_token < 0 || + d->neg_keep_head + d->neg_keep_tail >= d->max_prompt))) { + err(RAD_E_INVAL, "declare_audio_generator '%s': the prompt is out of range (at most %lld " + "tokens, unconditional branch token %d keeping %d + %d)", nm, + (long long)d->max_prompt, (int)d->neg_token, (int)d->neg_keep_head, + (int)d->neg_keep_tail); + return RAD_E_INVAL; + } + const bool chunked = d->voc_chunk > 0; + if (chunked && (d->voc_context < 0 || d->lat_num != 1 || d->lat_den != 1)) { + err(RAD_E_INVAL, "declare_audio_generator '%s': a vocoder that plays frames as they are " + "made reads a frame as one latent (lat_num = lat_den = 1) and a context " + "of >= 0 frames; got %lld/%lld and %lld", nm, (long long)d->lat_num, + (long long)d->lat_den, (long long)d->voc_context); + return RAD_E_INVAL; + } + if (d->max_frames <= 0 || d->frame_rate_num <= 0 || d->frame_rate_den <= 0 || + (!chunked && (d->win_frames <= 0 || d->win_hop <= 0 || d->win_hop > d->win_frames || + d->win_lead < 0 || d->latent_channels <= 0 || d->win_crop_left < 0 || + d->win_crop_right < 0)) || + d->lat_num <= 0 || d->lat_den <= 0 || d->samples_per_latent <= 0 || d->sample_rate <= 0 || + d->channels <= 0 || d->max_lanes <= 0) { + err(RAD_E_INVAL, "declare_audio_generator '%s': a geometry field is out of range (%lld " + "frames at %lld/%lld a second, windows of %lld every %lld, %lld lead " + "rows, %lld/%lld latents a frame of %lld channels, crops %lld + %lld, " + "%lld samples a latent at %lld Hz x %lld, %lld lanes)", nm, + (long long)d->max_frames, (long long)d->frame_rate_num, (long long)d->frame_rate_den, + (long long)d->win_frames, (long long)d->win_hop, (long long)d->win_lead, + (long long)d->lat_num, (long long)d->lat_den, (long long)d->latent_channels, + (long long)d->win_crop_left, (long long)d->win_crop_right, + (long long)d->samples_per_latent, (long long)d->sample_rate, (long long)d->channels, + (long long)d->max_lanes); + return RAD_E_INVAL; + } + /* A middle window plays what is left after both crops, so they must leave some of it. */ + if (!chunked && + d->win_crop_left + d->win_crop_right >= d->win_frames * d->lat_num / d->lat_den) { + err(RAD_E_INVAL, "declare_audio_generator '%s': the crops (%lld + %lld latents) leave a " + "window of %lld latents nothing to play", nm, (long long)d->win_crop_left, + (long long)d->win_crop_right, (long long)(d->win_frames * d->lat_num / d->lat_den)); + return RAD_E_INVAL; + } + if ((!chunked && d->default_steps <= 0) || !(d->default_cfg >= 1.0)) { + err(RAD_E_INVAL, "declare_audio_generator '%s': the sampler is incomplete (%lld default " + "steps, guidance %g)", nm, (long long)d->default_steps, d->default_cfg); + return RAD_E_INVAL; + } + auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) { + if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_audio_generator '%s': %s %u is not a declared buffer", nm, + what, (unsigned)h); + return false; + } + const RadBufDecl& ob = prog_.buffers[h].decl; + if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE || + decl_numel(ob.rank, ob.shape) < numel) { + err(RAD_E_INVAL, "declare_audio_generator '%s': %s '%s' must be a device %s buffer of " + "at least %lld elements", nm, what, prog_.buffers[h].name.c_str(), + dtype == RAD_I32 ? "i32" : "f32", (long long)numel); + return false; + } + return true; + }; + /* audio_out holds what one VOCODE pass plays: a window, or a chunk of frames. */ + const int64_t win_samples = (chunked ? d->voc_chunk : d->win_frames * d->lat_num / d->lat_den) * + d->samples_per_latent; + if (!buf_ok(d->status, RAD_I32, d->max_lanes, "status") || + !buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out")) + return RAD_E_INVAL; + prog_.agen_str.name = nm; + prog_.agen_str.tmpl = d->tmpl; + prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : ""; + prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : ""; + prog_.audio_gen = *d; + /* As for the image generator: the Program is moved after declare; strings live in agen_str. */ + prog_.audio_gen.name = nullptr; + prog_.audio_gen.tmpl = nullptr; + prog_.audio_gen.tmpl_plain = nullptr; + prog_.audio_gen.neg_tmpl = nullptr; + return RAD_OK; +} + +/* Validated at declare for the reasons the other generators are: an output buffer too small for + * the largest chunk or the longest soundtrack, or a geometry whose frame count does not follow + * from its chunks, would otherwise show at the first request. */ +int Builder::declare_video_generator(const RadVideoGenDecl* d) { + if (finished_) { + err(RAD_E_STATE, "declare_video_generator after declare finished"); + return RAD_E_STATE; + } + if (!d) { err(RAD_E_INVAL, "declare_video_generator: null declaration"); return RAD_E_INVAL; } + const char* nm = d->name && *d->name ? d->name : "(unnamed)"; + if (prog_.is_video_generator()) { + err(RAD_E_STATE, "declare_video_generator: '%s' was already declared; '%s' is a second one", + prog_.vgen_str.name.c_str(), nm); + return RAD_E_STATE; + } + if (prog_.logits_buf != RAD_NULL_HANDLE || prog_.pooled_buf != RAD_NULL_HANDLE || + prog_.generator.layout != 0 || prog_.is_audio_generator()) { + err(RAD_E_STATE, "declare_video_generator '%s': this program already declared %s; a " + "program generates text, embeds, makes images, audio or video -- one of " + "the five", nm, + prog_.logits_buf != RAD_NULL_HANDLE ? "logits" + : prog_.pooled_buf != RAD_NULL_HANDLE ? "a pooled output" + : prog_.generator.layout != 0 ? "an image generator" : "an audio generator"); + return RAD_E_STATE; + } + if (!d->tmpl || !std::strstr(d->tmpl, "{prompt}") || d->max_text <= 0) { + err(RAD_E_INVAL, "declare_video_generator '%s': tmpl needs {prompt} and max_text a " + "length (%lld)", nm, (long long)d->max_text); + return RAD_E_INVAL; + } + if (d->fps_num <= 0 || d->fps_den <= 0 || d->frames_per_chunk <= 0 || d->frames_tail < 0 || + d->latents_per_chunk <= 0 || d->latents_tail < 0 || d->dec_latents < d->latents_per_chunk || + d->min_chunks <= 0 || d->max_chunks < d->min_chunks || d->default_chunks < d->min_chunks || + d->default_chunks > d->max_chunks || + d->latents_per_chunk * (d->max_chunks - 1) + d->dec_latents > + d->latents_per_chunk * d->max_chunks + d->latents_tail) { + err(RAD_E_INVAL, "declare_video_generator '%s': the temporal geometry is out of range " + "(%lld/%lld fps, %lld n + %lld frames over %lld n + %lld latents, chunks of " + "%lld latents, %lld..%lld chunks, %lld by default)", nm, + (long long)d->fps_num, (long long)d->fps_den, (long long)d->frames_per_chunk, + (long long)d->frames_tail, (long long)d->latents_per_chunk, (long long)d->latents_tail, + (long long)d->dec_latents, (long long)d->min_chunks, (long long)d->max_chunks, + (long long)d->default_chunks); + return RAD_E_INVAL; + } + const int64_t unit = d->latent_scale * d->patch; + if (d->latent_scale <= 0 || d->latent_channels <= 0 || d->patch <= 0 || + d->size_multiple <= 0 || d->size_multiple % unit != 0 || d->min_side < d->size_multiple || + d->max_area < d->min_side * d->min_side || d->max_aspect < 1 || + d->default_width % d->size_multiple != 0 || d->default_height % d->size_multiple != 0 || + d->default_width < d->min_side || d->default_height < d->min_side || + d->default_width * d->default_height > d->max_area) { + err(RAD_E_INVAL, "declare_video_generator '%s': the spatial geometry is out of range " + "(latents of %lld px in %lld x %lld patches, sides multiples of %lld from " + "%lld, area to %lld, aspect to %lld, %lld x %lld by default)", nm, + (long long)d->latent_scale, (long long)d->patch, (long long)d->patch, + (long long)d->size_multiple, (long long)d->min_side, (long long)d->max_area, + (long long)d->max_aspect, (long long)d->default_width, (long long)d->default_height); + return RAD_E_INVAL; + } + if (d->sample_rate <= 0 || d->audio_rate <= 0 || d->sample_rate % d->audio_rate != 0 || + d->audio_channels <= 0 || d->audio_latent_channels <= 0) { + err(RAD_E_INVAL, "declare_video_generator '%s': the soundtrack is out of range (%lld Hz " + "at %lld latents a second, %lld channels of %lld)", nm, + (long long)d->sample_rate, (long long)d->audio_rate, (long long)d->audio_channels, + (long long)d->audio_latent_channels); + return RAD_E_INVAL; + } + if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) || + !(d->shift_audio > 0.0) || d->max_lanes <= 0) { + err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by " + "default, %lld at most, shifts %g and %g, %lld lanes)", nm, + (long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio, + (long long)d->max_lanes); + return RAD_E_INVAL; + } + if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) || + (d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) { + err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid " + "points, which default_steps and max_steps must both be (%lld, %lld)", nm, + (int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps, + (long long)d->max_steps); + return RAD_E_INVAL; + } + for (int i = 0; i < d->n_rungs; ++i) + if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) || + (i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) { + err(RAD_E_INVAL, "declare_video_generator '%s': rung %d (%g) is outside (0, 1] or not " + "below the one before it", nm, i, d->rungs[i]); + return RAD_E_INVAL; + } + auto buf_ok = [&](rad_buf h, uint32_t dtype, int64_t numel, const char* what) { + if (h == RAD_NULL_HANDLE || (size_t)h >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_video_generator '%s': %s %u is not a declared buffer", nm, + what, (unsigned)h); + return false; + } + const RadBufDecl& ob = prog_.buffers[h].decl; + if (ob.dtype != dtype || ob.domain != RAD_DOMAIN_DEVICE || + decl_numel(ob.rank, ob.shape) < numel) { + err(RAD_E_INVAL, "declare_video_generator '%s': %s '%s' must be a device %s buffer of " + "at least %lld elements", nm, what, prog_.buffers[h].name.c_str(), + dtype == RAD_U8 ? "u8" : "f32", (long long)numel); + return false; + } + return true; + }; + /* frames_out holds the last chunk, the largest, at the largest area; audio_out the longest + * soundtrack. */ + const int64_t chunk_px = (d->frames_per_chunk + d->frames_tail) * d->max_area * 3; + const int64_t max_frames = d->frames_per_chunk * d->max_chunks + d->frames_tail; + const int64_t max_lat = (max_frames * d->fps_den * d->audio_rate * 2 + d->fps_num) / + (2 * d->fps_num) + 1; + const int64_t max_samples = max_lat * (d->sample_rate / d->audio_rate); + if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") || + !buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out")) + return RAD_E_INVAL; + prog_.vgen_str.name = nm; + prog_.vgen_str.tmpl = d->tmpl; + prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs); + prog_.video_gen = *d; + /* As for the other generators: the Program is moved after declare; strings and the rungs live + * in vgen_str. */ + prog_.video_gen.name = nullptr; + prog_.video_gen.tmpl = nullptr; + prog_.video_gen.rungs = nullptr; + return RAD_OK; +} + /* Validates the draft head at declare rather than at the first draft pass, where a bad decl would * only show as zero acceptance. `depth` must equal RadBuildCtx::max_spec, which the plugin sized * its buffers with. */ @@ -1524,10 +1822,12 @@ void Builder::finish_layouts() { for (size_t h = 1; h < prog_.weights.size(); ++h) { const WeightInfo& w = prog_.weights[h]; if (w.n_sel <= 1 || !w.identity || !claimant[h].empty()) continue; + char en[256]; + rad_enc_format(&w.enc, en, sizeof en); if (unjoined[h].empty()) - err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight and no op reads it, so " - "nothing says how they are stored", w.name.c_str(), w.n_sel, - w.source.c_str()); + err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' (%s) as one weight and no op reads it, " + "so nothing says how they are stored", w.name.c_str(), w.n_sel, + w.source.c_str(), en); else err(RAD_E_SHAPE, "'%s' takes %d planes of '%s' as one weight, and the host kernels " "reading it (%s) have no layout that joins them (abi/rad_planes.h)", @@ -1814,6 +2114,16 @@ int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { return B(b)->declare_generator(d); } +int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_audio_generator(d); +} + +int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_video_generator(d); +} + void rad_note(RadBuilder* b, const char* f, ...) { if (!b) return; va_list ap; diff --git a/core/build/startup.cpp b/core/build/startup.cpp index 63ef7a10..a901400d 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -258,6 +258,32 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& lp, const RadMod return ap->arch_chat_format(&meta); } +int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string& in, + std::string* out) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + if (!ap || !ap->arch_text_prepare) { + *out = in; + return RAD_OK; + } + std::string buf(in.size() * 2 + 64, '\0'); + for (int tries = 0; tries < 2; ++tries) { + const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size()); + if (n < 0) return (int)n; + if (n < (int64_t)buf.size()) { + buf.resize((size_t)n); + *out = std::move(buf); + return RAD_OK; + } + buf.assign((size_t)n + 1, '\0'); + } + return RAD_E_STATE; +} + +VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& lp) { + const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); + return ap ? ap->arch_video_positions : nullptr; +} + const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& lp, const RadModelMeta& meta) { const Plugin* ap = rad_tools_registry().plugin(lp.arch_plugin); if (!ap || !ap->arch_audio_format) return nullptr; @@ -368,8 +394,8 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R return s; } - /* RUNTIME LoRA, after the plugin and before the sampler: the sites read the plugin's finished - * graph, and the appended ops go through the same resolution as everything else. */ + /* Runtime LoRA, after the plugin and before the sampler: the sites read the plugin's finished + * graph, and the appended ops go through the same resolution as every other op. */ if (with_lora) { b.set_lora_targets(nullptr); s = lora_declare(b, *lora); @@ -381,9 +407,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R /* The sampler declares into the same builder before finish(). An unresolved sampler op is not * a declare failure (a deployment that never sends `typical_p` needs no typical kernel), so a - * negative return here is structural. Skipped for embedding programs and image generators, - * which sample no token. */ - if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_generator()) { + * negative return here is structural. Skipped for embedding programs and generators, which + * sample through no token sampler (an audio generator samples its frames itself). */ + if (also && b.program().pooled_buf == RAD_NULL_HANDLE && !b.program().is_pass_driven()) { /* This rank's vocabulary width, taken from the declared logits buffer rather than * re-derived from n_vocab and world_size, which would break when a plugin does not split * the vocabulary (arch/common/rad_arch.h does not). A wrong width does not crash; it diff --git a/core/build/startup.h b/core/build/startup.h index 3a35199d..46eee91c 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -88,6 +88,17 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R * small to hold a field reads that field as null. */ const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const RadModelMeta& meta); +/* A request's text rewritten by the architecture plugin for the audio generator's prompt + * (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin + * states no rewrite), or the plugin's negative status. */ +int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in, + std::string* out); + +/* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports + * none. */ +using VideoPositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); +VideoPositionsFn rad_tools_video_positions(const LoadedPlugins& plugins); + /* Run declare. * * `also` declares into the same builder after the architecture plugin, which is how the sampler diff --git a/core/config.cpp b/core/config.cpp index 475f94b8..f9fd92cf 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -14,12 +14,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include namespace rad { @@ -104,9 +106,9 @@ static const Flag g_flags[] = { " --lora). Each slot holds one adapter's A/B on the card"}, { "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n" " adapter is zero-padded, a larger one refused"}, - { "--lora-target-modules", "LIST", "comma-separated HF module names adapters may target\n" - " (q_proj,k_proj,...). Default: what the --lora adapters\n" - " target. Needed with --max-loras and no --lora"}, + { "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n" + " target (q_proj,k_proj,...). Default: what the --lora\n" + " adapters target. Needed with --max-loras and no --lora"}, { "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" }, { "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n" @@ -122,12 +124,12 @@ static const Flag g_flags[] = { " intervals, and the checkpoints inside a span are not\n" " written" }, /* A total, not per sequence: the snapshot store is one pool of N slots - * (KVManager::set_checkpoint_store). The default 8 gives one per sequence at 8 sequences, - * enough for append-only chat, where the next turn hits at the end of the last. */ - { "--checkpoint-slots", "N", "linear-state or sliding-window snapshots " - "retained IN TOTAL (not " - "per sequence), in pinned host memory; compare " - "against --max-num-seqs" }, + * (KVManager::set_checkpoint_store). */ + { "--checkpoint-slots", "N", "linear-state or sliding-window snapshots the server holds in\n" + " total, in pinned host memory. Default `auto`: what\n" + " --checkpoint-policy keeps for a --max-model-len session, plus\n" + " one, for each of --max-num-seqs, within an eighth of host\n" + " memory. N fixes the total; 0 keeps none" }, { "--no-prefix-cache", nullptr, "disable prefix caching" }, { "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff " "(default), tip-only, keep-all" }, @@ -515,20 +517,29 @@ int config_parse(int argc, char** argv, Config* c) { else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; } else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; } else if (S("--lora-target-modules")) { + /* Module leaf names, as PEFT's target_modules lists them: a dotted path or a pattern + * would match no leaf and target nothing without a word. */ if (!(v = need(i))) return RAD_E_INVAL; - c->lora.targets.clear(); + std::set leaves; std::string cur; for (const char* q = v;; ++q) { if (*q == ',' || !*q) { - if (!cur.empty()) c->lora.targets.insert(cur); + if (!cur.empty()) leaves.insert(cur); cur.clear(); if (!*q) break; - } else if (*q != ' ') cur += *q; + } else if (std::isalnum((unsigned char)*q) || *q == '_') { + cur += *q; + } else if (*q != ' ') { + RAD_ERR("--lora-target-modules takes module leaf names (q_proj,k_proj,...); " + "'%s' holds '%c'", v, *q); + return RAD_E_INVAL; + } } - if (c->lora.targets.empty()) { + if (leaves.empty()) { RAD_ERR("--lora-target-modules names no module"); return RAD_E_INVAL; } + c->lora.targets.assign(leaves.begin(), leaves.end()); } /* The prefix cache has no disk tier; the removed flags name their replacements. */ else if (S("--prefix-cache-host-mib")) { @@ -555,7 +566,17 @@ int config_parse(int argc, char** argv, Config* c) { else if (S("--deterministic")) c->deterministic = true; else if (S("--checkpoint-interval")) { if (!num(0, INT64_MAX, &c->checkpoint_interval)) return RAD_E_INVAL; } else if (S("--prefill-span")) { if (!num(1, INT32_MAX, &c->prefill_span)) return RAD_E_INVAL; } - else if (S("--checkpoint-slots")) { if (!num(0, INT64_MAX, &c->checkpoint_slots)) return RAD_E_INVAL; } + else if (S("--checkpoint-slots")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "auto")) { + c->checkpoint_slots = -1; + } else if (!*v || std::strspn(v, "0123456789") != std::strlen(v)) { + RAD_ERR("--checkpoint-slots takes auto or a whole number, not '%s'", v); + return RAD_E_INVAL; + } else if (!parse_int(a.c_str(), v, 0, INT64_MAX, &c->checkpoint_slots)) { + return RAD_E_INVAL; + } + } else if (S("--no-prefix-cache")) c->prefix_cache = false; else if (S("--checkpoint-policy")) { if (!(v = need(i))) return RAD_E_INVAL; @@ -844,6 +865,48 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } + /* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's + * adapter is one of them. */ + { + const LoraConfig& L = c->lora; + std::set names; + for (const auto& [name, path] : L.adapters) + if (!names.insert(name).second) { + RAD_ERR("--lora names the adapter '%s' twice", name.c_str()); + return RAD_E_INVAL; + } + if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) { + RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names", + L.max_loras, L.adapters.size()); + return RAD_E_INVAL; + } + const bool rank_given = c->given.count("--max-lora-rank") != 0; + if (!L.enabled() && (rank_given || !L.targets.empty())) { + RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras", + rank_given ? "--max-lora-rank" : "--lora-target-modules"); + return RAD_E_INVAL; + } + if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) { + RAD_ERR("--max-loras with no --lora names no module an adapter may target; give " + "--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)"); + return RAD_E_INVAL; + } + if (!c->kld_lora.empty() && !c->kld()) { + RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or " + "--kld-ref"); + return RAD_E_INVAL; + } + if (!c->kld_lora.empty() && !names.count(c->kld_lora)) { + RAD_ERR("--kld-lora '%s' is not one of the adapters --lora names", c->kld_lora.c_str()); + return RAD_E_INVAL; + } + if (!c->kld_lora_sources.empty() && c->kld_lora.empty()) { + RAD_ERR("--kld-lora-sources picks the documents that run through --kld-lora's adapter; " + "give --kld-lora"); + return RAD_E_INVAL; + } + } + /* --reasoning-effort is a template variable ("none" also sets enable_thinking false), so * either key in --chat-template-kwargs as well would give two defaults for one setting. */ if (!c->reasoning_effort.empty() && @@ -960,7 +1023,8 @@ const ShowRow kShow[] = { { "--deterministic", [](const Config& c) { return onoff(c.deterministic); } }, { "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } }, { "--prefill-span", [](const Config& c) { return num(c.prefill_span); } }, - { "--checkpoint-slots", [](const Config& c) { return num(c.checkpoint_slots); } }, + { "--checkpoint-slots", [](const Config& c) { + return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } }, { "--no-prefix-cache", [](const Config& c) { return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } }, { "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } }, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 02d49ebf..c8f252ae 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -618,6 +618,9 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) { * nothing will decrement, or a kernel that faulted silently); the packet at the read index says * which. */ /* Sum of every queue's read index. It only grows, so an unchanged sum means no queue moved. */ +/* How long a host wait may see no queue advance before it reports the queues; see dump_queues. */ +constexpr uint32_t kStallMs = 5000; + uint64_t read_progress() { std::lock_guard lk(G().streams_mu); uint64_t n = 0; @@ -630,7 +633,7 @@ void (*g_dump_lanes)() = nullptr; void dump_queues(const char* where) { std::lock_guard lk(G().streams_mu); - RAD_ERR("device: %s has waited 5 s; the queues:", where); + RAD_ERR("device: %s has seen no queue advance for %u s; the queues:", where, kStallMs / 1000); for (Stream* s : G().streams) { const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q); const uint64_t wr = hsa_queue_load_write_index_scacquire(s->q); @@ -829,45 +832,44 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) { "exiting so a restart can bring the server back", card); } -/* How long a host wait goes before it reports the queues; see dump_queues. */ -constexpr uint32_t kStallMs = 5000; - /* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand * times a second at most. * - * The dump alone cannot tell slow from stuck: a long prefill at deep context can hold one wait - * past 5 s while the queue drains, and a hung kernel holds it with the read index frozen. So the - * read indices are sampled with the dump and again one stall period later: advanced means a long - * wait, unchanged means the GPU is not running the queue. */ + * A long wait is not a fault: a long prefill at deep context holds one wait for seconds, and a + * video generator's denoising pass for tens of them. So the queues' read indices are sampled once + * every stall period and only a period in which none advanced reports, with the packet each queue + * is on: a hung kernel, or a queue the driver evicted and could not restore. A wait that keeps + * moving says nothing. */ struct Stall { const char* where; uint32_t n = 0; - int told = 0; /* 0 nothing said, 1 the dump, 2 the verdict */ + bool told = false; + bool sampled = false; uint64_t progress = 0; - std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point next = + std::chrono::steady_clock::now() + std::chrono::milliseconds(kStallMs); explicit Stall(const char* w) : where(w) {} void tick() { - if (told == 2 || (++n & 0xffff)) return; + if (told || (++n & 0xffff)) return; check(); } /* Checks on every call, for a loop that sleeps between calls. */ void check() { - if (told == 2) return; - const auto waited = std::chrono::steady_clock::now() - t0; - if (told == 0 && waited > std::chrono::milliseconds(kStallMs)) { - told = 1; - progress = read_progress(); + if (told) return; + const auto now = std::chrono::steady_clock::now(); + if (now < next) return; + next = now + std::chrono::milliseconds(kStallMs); + const uint64_t p = read_progress(); + if (sampled && p == progress) { + told = true; dump_queues(where); - } else if (told == 1 && waited > std::chrono::milliseconds(2 * kStallMs)) { - told = 2; - if (read_progress() != progress) - RAD_WARN("device: the queues advanced in the %u s since; %s is long, not stuck", - kStallMs / 1000, where); - else - RAD_ERR("device: no queue has advanced in the %u s since: the GPU is not running " - "the packet named above -- a hung kernel, or a queue the driver evicted and " - "could not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000); + RAD_ERR("device: no queue has advanced in the %u s since: the GPU is not running the " + "packet named above -- a hung kernel, or a queue the driver evicted and could " + "not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000); + return; } + sampled = true; + progress = p; } }; diff --git a/core/engine.cpp b/core/engine.cpp index efafc468..9a2eee65 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -4,6 +4,8 @@ */ #include "engine_priv.h" #include "gen/driver.h" +#include "gen/audio_driver.h" +#include "gen/video_driver.h" #include "kld.h" #include "mm/processor.h" @@ -1343,28 +1345,39 @@ int Engine::serve(std::unique_ptr watch) { return RAD_E_STATE; } embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE; - const bool generator = ranks_[0]->program.is_generator(); + const bool audio_gen = ranks_[0]->program.is_audio_generator(); + const bool video_gen = ranks_[0]->program.is_video_generator(); + const bool generator = ranks_[0]->program.is_pass_driven(); if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_ && !generator) { RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), no pooled output " - "(rad_declare_pooled) and no image generator (rad_declare_generator), so a step " - "produces nothing anyone can read. An encoder-only plugin cannot serve.", + "(rad_declare_pooled) and no generator (rad_declare_generator, " + "rad_declare_audio_generator, rad_declare_video_generator), so a step produces " + "nothing anyone can read. An encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str()); return RAD_E_UNSUPPORTED; } if (generator) { + const char* const what = audio_gen ? "audio" : video_gen ? "video" : "images"; if (cfg_.kld() || cfg_.n_spec > 0) { - RAD_ERR("the '%s' plugin makes images: --kld and speculative decoding have no tokens to " - "work on", plugins_.arch_plugin.c_str()); + RAD_ERR("the '%s' plugin makes %s: --kld and speculative decoding have no tokens to " + "work on", plugins_.arch_plugin.c_str(), what); return RAD_E_UNSUPPORTED; } for (size_t i = 1; i < ranks_.size(); ++i) - if (!ranks_[i]->program.is_generator()) { - RAD_ERR("rank %zu declared no image generator and rank 0 did", i); + if (ranks_[i]->program.is_audio_generator() != audio_gen || + ranks_[i]->program.is_video_generator() != video_gen || + !ranks_[i]->program.is_pass_driven()) { + RAD_ERR("rank %zu declared a different generator from rank 0's", i); return RAD_E_STATE; } cfg_.prefix_cache = false; - prefix_off_why_ = "an image generator: a conditioning is read by its own request's images " - "and by nothing after them"; + prefix_off_why_ = audio_gen + ? "an audio generator: a prompt is read by its own request's frames and by nothing " + "after them" + : video_gen + ? "a video generator: a prompt is read by its own request's steps and keeps no KV" + : "an image generator: a conditioning is read by its own request's images and by " + "nothing after them"; decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); } if (embedding_) { @@ -1498,13 +1511,33 @@ int Engine::serve(std::unique_ptr watch) { rio.reserve(ranks_.size()); for (auto& rk : ranks_) rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); - if (generator) { + if (video_gen) { + /* As for the image generator below; the plugin lays out each request's rows. */ + std::vector 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)); + vid_gen_ = d.get(); + gen_ = std::move(d); + RAD_TRY(rad_dev_set(ranks_[0]->device)); + } else if (audio_gen) { + /* As for the image generator below. */ + std::vector 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, kv_iface_.get(), gio)); + aud_gen_ = d.get(); + gen_ = std::move(d); + RAD_TRY(rad_dev_set(ranks_[0]->device)); + } else if (generator) { /* The generator's driver replaces the scheduler, which is never initialised, so its * token-step staging is never allocated. */ std::vector gio; for (auto& rk : ranks_) gio.push_back({ rk->device, rk->ctx.stream() }); - gen_ = std::make_unique(); - RAD_TRY(gen_->init(ranks_[0]->program, kv_iface_.get(), gio)); + auto d = std::make_unique(); + RAD_TRY(d->init(ranks_[0]->program, kv_iface_.get(), gio)); + img_gen_ = d.get(); + gen_ = std::move(d); RAD_TRY(rad_dev_set(ranks_[0]->device)); } else RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); @@ -2006,7 +2039,9 @@ int Engine::run_server() { server::ServerOptions o{}; o.embedding_model = embedding_; - o.image_model = gen_ != nullptr; + o.image_model = img_gen_ != nullptr; + o.audio_model = aud_gen_ != nullptr; + o.video_model = vid_gen_ != nullptr; o.decision_type = rad_meta_gets(&meta_, "decision.type", ""); o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name : meta_.name && *meta_.name ? meta_.name : "radiance"; @@ -2024,9 +2059,9 @@ int Engine::run_server() { o.default_reasoning_effort = cfg_.reasoning_effort; o.reasoning_effort_map = cfg_.reasoning_effort_map; o.default_thinking_budget = cfg_.thinking_token_budget; - { + if (!gen_) { /* The four sampler defaults a file can state: the served value and, per field, its - * source. */ + * source. A generator samples by its own rules and serves no text requests. */ GenSampling stated; std::string src; o.default_sampling = @@ -2078,6 +2113,14 @@ int Engine::run_server() { /* Per request, from a reading at most a second old (Engine::diagnostics_json). */ o.diagnostics_json = [this] { return diagnostics_json(); }; if (cfg_.lora.enabled()) { + /* `model` picks the adapter, and the served model's own name picks the base. */ + for (const auto& [name, dir] : cfg_.lora.adapters) + if (name == o.model_id) { + RAD_ERR("lora: the adapter '%s' has the served model's own name, so a request " + "naming it would run the base; rename it or give --served-model-name", + name.c_str()); + return RAD_E_INVAL; + } o.lora_acquire = [this](const std::string& m, int32_t* slot, uint64_t* uid, std::shared_ptr* hold) { return lora_acquire(m, slot, uid, hold); @@ -2317,7 +2360,7 @@ int Engine::run_server() { int64_t queued() const override { return drv->queued(); } int64_t running() const override { return drv->running(); } } image_bridge; - if (gen_) { + if (img_gen_) { const Program& pg = ranks_[0]->program; const RadGeneratorDecl& gd = pg.generator; server::ImageGenInfo& in = image_bridge.inf; @@ -2339,11 +2382,11 @@ int Engine::run_server() { in.default_height = gd.default_height; in.default_steps = gd.default_steps; in.max_lanes = gd.max_lanes; - in.max_cond_tokens = gen_->max_cond_tokens(); + in.max_cond_tokens = img_gen_->max_cond_tokens(); in.fixed_schedule = !pg.gen_str.sigmas.empty(); in.fixed_steps = (int64_t)pg.gen_str.sigmas.size(); in.default_cfg = gd.default_cfg; - image_bridge.drv = gen_.get(); + image_bridge.drv = img_gen_; image_bridge.proc = mm_proc.get(); d.images = &image_bridge; /* The served model id is the generator's own name (qwen-image-2.1), not the container's @@ -2359,6 +2402,116 @@ int Engine::run_server() { : (std::to_string(in.default_steps) + " steps by default").c_str()); } + /* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the + * plugin's rewrite of a request's texts. */ + struct AudioBridge final : server::IAudioGen { + gen::AudioDriver* drv = nullptr; + const LoadedPlugins* plugins = nullptr; + server::AudioGenInfo inf; + const server::AudioGenInfo& info() const override { return inf; } + int prepare(int field, const std::string& in, std::string* out, + std::string* why) const override { + const int s = rad_tools_text_prepare(*plugins, field, in, out); + if (s < 0 && why) + *why = s == RAD_E_INVAL ? "the model cannot take this text" + : std::string(rad_strerror(s)); + return s; + } + int submit(std::unique_ptr r, std::string* why) override { + return drv->submit(std::move(r), why); + } + int64_t queued() const override { return drv->queued(); } + int64_t running() const override { return drv->running(); } + } audio_bridge; + if (aud_gen_) { + const Program& pg = ranks_[0]->program; + const RadAudioGenDecl& ad = pg.audio_gen; + server::AudioGenInfo& in = audio_bridge.inf; + in.name = pg.agen_str.name; + in.tmpl = pg.agen_str.tmpl; + in.tmpl_plain = pg.agen_str.tmpl_plain; + in.neg_tmpl = pg.agen_str.neg_tmpl; + in.max_prompt = ad.max_prompt; + in.max_frames = ad.max_frames; + in.frame_rate_num = ad.frame_rate_num; + in.frame_rate_den = ad.frame_rate_den; + in.sample_rate = ad.sample_rate; + in.channels = ad.channels; + in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps; + in.default_cfg = ad.default_cfg; + in.max_lanes = ad.max_lanes; + audio_bridge.drv = aud_gen_; + audio_bridge.plugins = &plugins_; + d.audio = &audio_bridge; + if (cfg_.served_model_name.empty() && !in.name.empty()) { + o.model_id = in.name; + decide("--served-model-name", o.model_id, "an audio generator: its own name"); + } + RAD_INFO("audio: '%s', %lld Hz x %lld, up to %lld frames (%lld s), %lld at once, %s", + in.name.c_str(), (long long)in.sample_rate, (long long)in.channels, + (long long)in.max_frames, + (long long)(in.max_frames * in.frame_rate_den / in.frame_rate_num), + (long long)in.max_lanes, + ad.voc_chunk > 0 + ? fmt("played %lld frames at a time as they are made", + (long long)ad.voc_chunk).c_str() + : fmt("%lld steps a window by default", (long long)in.default_steps).c_str()); + } + + /* A video generator's endpoints: the driver's queue and the declared prompt, sizes and + * lengths. */ + struct VideoBridge final : server::IVideoGen { + gen::VideoDriver* drv = nullptr; + server::VideoGenInfo inf; + const server::VideoGenInfo& info() const override { return inf; } + int submit(std::unique_ptr r, std::string* why) override { + return drv->submit(std::move(r), why); + } + int64_t queued() const override { return drv->queued(); } + int64_t running() const override { return drv->running(); } + } video_bridge; + if (vid_gen_) { + const Program& pg = ranks_[0]->program; + const RadVideoGenDecl& vd = pg.video_gen; + server::VideoGenInfo& in = video_bridge.inf; + in.name = pg.vgen_str.name; + in.tmpl = pg.vgen_str.tmpl; + in.max_text = vd.max_text; + in.fps_num = vd.fps_num; + in.fps_den = vd.fps_den; + in.frames_per_chunk = vd.frames_per_chunk; + in.frames_tail = vd.frames_tail; + in.min_chunks = vd.min_chunks; + in.max_chunks = vd.max_chunks; + in.size_multiple = vd.size_multiple; + in.min_side = vd.min_side; + in.max_area = vd.max_area; + in.max_aspect = vd.max_aspect; + in.default_width = vd.default_width; + in.default_height = vd.default_height; + in.default_chunks = vd.default_chunks; + in.sample_rate = vd.sample_rate; + in.channels = vd.audio_channels; + in.default_steps = vd.default_steps; + in.max_steps = vd.max_steps; + in.fixed_steps = vd.n_rungs > 0; + in.max_lanes = vd.max_lanes; + video_bridge.drv = vid_gen_; + d.videos = &video_bridge; + if (cfg_.served_model_name.empty() && !in.name.empty()) { + o.model_id = in.name; + decide("--served-model-name", o.model_id, "a video generator: its own name"); + } + const double fps = (double)in.fps_num / (double)in.fps_den; + RAD_INFO("video: '%s', %lldx%lld by default (up to %lld pixels), %.2f to %.2f s at %g fps " + "with %lld Hz x %lld sound, %lld steps by default", + in.name.c_str(), (long long)in.default_width, (long long)in.default_height, + (long long)in.max_area, + (double)(in.frames_per_chunk * in.min_chunks + in.frames_tail) / fps, + (double)(in.frames_per_chunk * in.max_chunks + in.frames_tail) / fps, fps, + (long long)in.sample_rate, (long long)in.channels, (long long)in.default_steps); + } + if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set()) RAD_WARN("media: the media flags do nothing here -- this model %s", cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)" @@ -2417,6 +2570,12 @@ int Engine::run_server() { if (embedding_) RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501%s)", o.host.c_str(), o.port, keyed); + else if (aud_gen_) + RAD_INFO("serving on http://%s:%d (/v1/audio/speech; completions and chat are 501%s)", + o.host.c_str(), o.port, keyed); + else if (vid_gen_) + RAD_INFO("serving on http://%s:%d (/v1/videos; completions and chat are 501%s)", + o.host.c_str(), o.port, keyed); else if (gen_) RAD_INFO("serving on http://%s:%d (/v1/images/generations%s; completions and chat are " "501%s)", o.host.c_str(), o.port, diff --git a/core/engine.h b/core/engine.h index abe16bb9..19c468a5 100644 --- a/core/engine.h +++ b/core/engine.h @@ -44,7 +44,7 @@ namespace rad { class Kld; class StallWatch; -namespace gen { class Driver; } +namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPassDriver; } struct TierPump; struct TierJob; struct StepSlot; @@ -136,21 +136,19 @@ private: int apply_rope_scaling(); int declare(); int plan(); - /* RUNTIME LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded + /* Runtime LoRA (core/engine_lora.cpp). Targets are fixed before declare; adapters are loaded * into slots after every rank's Ctx is bound, and a request's `model` names one. */ int lora_targets(); int lora_start(); public: int lora_load(const std::string& name, const std::string& dir, std::string* err); /* Unpublish an adapter (lora::SlotTable::unload). Idle, its slot is freed at once; in use, it - * DRAINS: *in_flight says how many requests still hold it, no new request may name it, and - * the last of them frees the slot. A freed slot is reused only once the step loop has gone - * round three times since, so no step still on the card can read bytes a later load is - * writing (the next step is issued before the last is read back). */ + * drains: *in_flight says how many requests still hold it, no new request may name it, and the + * last of them frees the slot, which cools before reuse (lora/slots.h). */ int lora_unload(const std::string& name, std::string* err, int* in_flight); - /* RAD_OK with the slot, the uid of its load and a HOLD -- the adapter is not freed while the - * hold lives (the server keeps it in the request's Generation, which outlives the request in - * the scheduler). RAD_E_NOTFOUND for a name no slot holds, or one that is draining. */ + /* RAD_OK with the slot, the uid of its load and a hold: the adapter is not freed while the + * hold lives (the server keeps it in the request's Generation). RAD_E_NOTFOUND for a name no + * slot holds, or one that is draining. */ int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, std::shared_ptr* hold); std::vector lora_names() const; @@ -186,6 +184,8 @@ private: std::vector> table_copy_of_; int load_weights(); int configure_kv(); + /* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */ + int size_checkpoint_store(int64_t slot, const char* what); /* Maps the step's logits rows back to the sequences that wanted them. Not the identity: a * mid-prompt prefill chunk produces no row, and a speculative verify produces 1 + n_spec. */ struct StepOut { @@ -310,10 +310,15 @@ private: float* pooled_host_ = nullptr; int collect_pooled_issue(const RadBatch* b, StepOut& so); int collect_pooled(const RadBatch* b, StepOut& so); - /* Image generator (rad_declare_generator): the driver that turns requests into passes and the - * loop that runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every - * other program. */ - std::unique_ptr gen_; + /* A generator (rad_declare_generator, rad_declare_audio_generator, + * rad_declare_video_generator): the driver that turns requests into passes and the loop that + * runs them, replacing the scheduler and step loop (engine_gen.cpp). Null for every other + * program. `img_gen_`, `aud_gen_` and `vid_gen_` are the same driver by its kind, for the + * endpoints; one of them is set when `gen_` is. */ + std::unique_ptr gen_; + gen::Driver* img_gen_ = nullptr; + gen::AudioDriver* aud_gen_ = nullptr; + gen::VideoDriver* vid_gen_ = nullptr; int gen_loop(); bool serial_drafting() const; int advance_all(int mode, int round, bool from_proposal, int rows = -1); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 291baae0..705ffaf3 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -7,6 +7,8 @@ #include "engine_priv.h" #include "engine_hostmem.h" #include "gen/driver.h" +#include "gen/audio_driver.h" +#include "gen/video_driver.h" #include "build/startup.h" #include "build/rad_build.h" @@ -205,12 +207,27 @@ static int64_t meminfo_bytes(const char* key) { return -1; } +/* The amdgpu driver's cap on the memory every process together pins: RAM less 1/64 and 1.5 GiB + * (half of RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it; + * ttm.pages_limit does not apply. -1 when lifted (`*lifted` set) or MemTotal is unreadable. */ +static int64_t amdgpu_pin_cap(bool* lifted) { + { + std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit"); + std::string v; + *lifted = (f >> v) && (v == "Y" || v == "1"); + } + const int64_t total = meminfo_bytes("MemTotal"); + if (*lifted || total <= 0) return -1; + const int64_t reserve = (int64_t)3 << 29; + const int64_t cap = total - (total >> 6); + return cap < 2 * reserve ? cap >> 1 : cap - reserve; +} + /* Explain a refused pool allocation from the machine's current state. * * A card pool refused after the budget was measured (once, before any rank allocates) usually - * lost the memory to another process. A host pool is pinned, once per rank. Pinned memory counts - * against amdgpu's system-wide cap: RAM less 1/64 and 1.5 GiB (half of RAM less 1/64 below - * 3 GiB), unless amdgpu.no_system_mem_limit lifts it; ttm.pages_limit does not apply. */ + * lost the memory to another process. A host pool is pinned, once per rank, and counts against + * amdgpu_pin_cap. */ static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) { bool card = false, host = false; for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true; @@ -226,19 +243,9 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const int64_t pinned = 0, mapped = 0; rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); - const int64_t total = meminfo_bytes("MemTotal"), avail = meminfo_bytes("MemAvailable"); + const int64_t avail = meminfo_bytes("MemAvailable"); bool lifted = false; - { - std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit"); - std::string v; - lifted = (f >> v) && (v == "Y" || v == "1"); - } - const int64_t reserve = (int64_t)3 << 29; - int64_t cap = -1; - if (total > 0 && !lifted) { - cap = total - (total >> 6); - cap = cap < 2 * reserve ? cap >> 1 : cap - reserve; - } + const int64_t cap = amdgpu_pin_cap(&lifted); /* With room under both limits the refusal is not about size; do not advise shrinking. */ const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024; std::string tables, advice = "Lower --host-pool-mib"; @@ -273,6 +280,34 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const * kernel reclaims the files the engine reads, then the OOM killer runs. */ static const int64_t kLockMargin = (int64_t)4 << 30; +/* Every level of every memory cgroup the process is in, leaf first: `visit(dir, room)` until it + * returns false (cgroup_levels). /proc/self/cgroup reads "0::/path" on v2 and "N:memory:/path" + * (or a comma list naming memory) on v1; each level up to the visible root is a limit of its + * own. */ +static void memory_cgroups(const std::function& visit) { + std::ifstream f("/proc/self/cgroup"); + std::string line; + bool go = true; + while (go && std::getline(f, line)) { + const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1); + if (b == std::string::npos) continue; + const std::string ctrl = line.substr(a + 1, b - a - 1); + std::string path = line.substr(b + 1); + const bool v2 = ctrl.empty(); + bool memory = v2; + for (size_t i = 0; !memory && i < ctrl.size();) { + const size_t j = std::min(ctrl.find(',', i), ctrl.size()); + memory = ctrl.compare(i, j - i, "memory") == 0; + i = j + 1; + } + if (!memory) continue; + const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory"; + cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) { + return go = visit(dir, room); + }); + } +} + /* Whether `need` more bytes fit in host memory after `still` more this process will allocate * first, or why not. Checks MemAvailable; every memory cgroup from the process's own up to the * visible root (Docker's --memory, enforced by the OOM killer); and, for an mlock()ed copy @@ -307,37 +342,39 @@ static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string* humanb(kLockMargin).c_str()); return false; } - /* /proc/self/cgroup: "0::/path" on v2, "N:memory:/path" (or a comma list naming memory) on v1. - * Each level up to the visible root is a separate limit. */ - std::ifstream f("/proc/self/cgroup"); - std::string line; - while (std::getline(f, line)) { - const size_t a = line.find(':'), b = a == std::string::npos ? a : line.find(':', a + 1); - if (b == std::string::npos) continue; - const std::string ctrl = line.substr(a + 1, b - a - 1); - std::string path = line.substr(b + 1); - const bool v2 = ctrl.empty(); - bool memory = v2; - for (size_t i = 0; !memory && i < ctrl.size();) { - const size_t j = std::min(ctrl.find(',', i), ctrl.size()); - memory = ctrl.compare(i, j - i, "memory") == 0; - i = j + 1; - } - if (!memory) continue; - const std::string root = v2 ? "/sys/fs/cgroup" : "/sys/fs/cgroup/memory"; - bool fits = true; - cgroup_levels(root, path, v2, [&](const std::string& dir, int64_t room) { - if (room - still - kLockMargin >= need) return true; - *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, " - "and this wants %s with %s to spare", dir.c_str(), - humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(), - humanb(kLockMargin).c_str()); - fits = false; - return false; - }); - if (!fits) return false; + bool fits = true; + memory_cgroups([&](const std::string& dir, int64_t room) { + if (room - still - kLockMargin >= need) return true; + *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, " + "and this wants %s with %s to spare", dir.c_str(), + humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(), + humanb(kLockMargin).c_str()); + fits = false; + return false; + }); + return fits; +} + +/* The most lockable_room(need, still, false) admits, and in `limit` the bound that decides it. + * INT64_MAX when no limit can be read. */ +static int64_t lockable_bytes(int64_t still, std::string* limit) { + int64_t most = INT64_MAX; + *limit = "no readable memory limit"; + if (const int64_t avail = meminfo_bytes("MemAvailable"); avail >= 0) { + most = avail - still - kLockMargin; + *limit = fmt("%s of memory available, less %s still to be allocated and %s to spare", + humanb(avail).c_str(), humanb(still).c_str(), humanb(kLockMargin).c_str()); } - return true; + memory_cgroups([&](const std::string& dir, int64_t room) { + if (room - still - kLockMargin < most) { + most = room - still - kLockMargin; + *limit = fmt("the memory cgroup at %s, which leaves %s, less %s still to be allocated " + "and %s to spare", dir.c_str(), humanb(room).c_str(), + humanb(still).c_str(), humanb(kLockMargin).c_str()); + } + return true; + }); + return std::max(most, 0); } /* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into @@ -878,7 +915,47 @@ int Engine::declare() { { RadArchProbe pb{}; (void)rad_tools_probe(plugins_, meta_, &pb); - if (pb.gen_rows > 0) { + if (pb.gen_rows > 0 && pb.gen_audio) { + if (!cfg_.given.count("--max-num-batched-tokens")) { + cfg_.max_tok = pb.gen_rows; + decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok), + "an audio generator: a window's denoising step, both branches, and a " + "prompt chunk of half as many rows a branch"); + } + if (!cfg_.given.count("--max-num-seqs")) { + cfg_.max_seqs = 8; + decide("--max-num-seqs", "8", "an audio generator: four requests at once, two " + "branches each"); + } + if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) { + cfg_.max_ctx = pb.gen_ctx > 0 ? pb.gen_ctx : pb.gen_rows; + decide("--max-model-len", std::to_string(cfg_.max_ctx), + "an audio generator: the longest prompt and every frame of the longest " + "piece"); + } + if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + if (cfg_.n_spec < 0) cfg_.n_spec = 0; + cfg_.prefix_cache = false; + } else if (pb.gen_rows > 0 && pb.gen_video) { + if (!cfg_.given.count("--max-num-batched-tokens")) { + cfg_.max_tok = pb.gen_rows; + decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok), + "a video generator: a denoising step carries the prompt, the soundtrack " + "and every patch of the largest, longest video"); + } + if (!cfg_.given.count("--max-num-seqs")) { + cfg_.max_seqs = 1; + decide("--max-num-seqs", "1", "a video generator: a pass is one request's"); + } + if (!cfg_.given.count("--max-model-len") && cfg_.max_ctx == 0) { + cfg_.max_ctx = pb.gen_rows; + decide("--max-model-len", std::to_string(cfg_.max_ctx), + "a video generator: a step's rows"); + } + if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + if (cfg_.n_spec < 0) cfg_.n_spec = 0; + cfg_.prefix_cache = false; + } else if (pb.gen_rows > 0) { if (!cfg_.given.count("--max-num-batched-tokens")) { cfg_.max_tok = pb.gen_rows; decide("--max-num-batched-tokens", std::to_string(cfg_.max_tok), @@ -1308,8 +1385,10 @@ int Engine::plan() { const int64_t w = probe.state_index_width((int32_t)i); if (w > 0) kg.g[i].sidx_width = w; } - f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program) - : BatchBuilder::device_bytes(r->program, cfg_, kg); + f.staging = r->program.is_generator() ? gen::Driver::device_bytes(r->program) + : r->program.is_audio_generator() ? gen::AudioDriver::device_bytes(r->program) + : r->program.is_video_generator() ? gen::VideoDriver::device_bytes(r->program) + : BatchBuilder::device_bytes(r->program, cfg_, kg); if (f.staging < 0) return RAD_E_INVAL; late_step_bytes_ = std::max(late_step_bytes_, f.staging); int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0; @@ -1343,8 +1422,12 @@ int Engine::plan() { facts[i].expert_floor = expert_vram_floor(wfs[i], std::max(room, 0)); } /* Capped well below overflow, so the sums it joins stay defined: a store that large is - * refused by name in configure_kv. */ - const int64_t ck_n = std::max(cfg_.checkpoint_slots, 0), ck_cap = INT64_MAX / 8; + * refused by name in configure_kv. Under --checkpoint-slots auto the store is sized in + * configure_kv from the memory the tables leave, and the tables leave room for the fewest + * slots auto resolves to. */ + const int64_t ck_n = + cfg_.checkpoint_slots < 0 ? kCheckpointSlotsFloor : cfg_.checkpoint_slots; + const int64_t ck_cap = INT64_MAX / 8; const int64_t ck_store = !cfg_.prefix_cache || ck_slot <= 0 ? 0 : ck_n > ck_cap / ck_slot ? ck_cap : ck_slot * ck_n; RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes, @@ -2658,6 +2741,79 @@ int Engine::load_weights() { * * Runs after load, since it takes what the weight pool left, and before Ctx::init, which would * otherwise resolve every RAD_OPK_KV operand to null. */ +/* --checkpoint-slots auto, resolved into cfg_.checkpoint_slots once a slot's size is known + * (checkpoint_slots_auto in core/mem/prefix.h). The store is pinned for the life of the process, + * so it takes at most an eighth of host memory, leaving the rest to the page cache a model's + * mapped tables read through and to the host's other work. It is pinned before the host + * activation arenas and the prefix cache's host tier, so their bytes count as still to come; + * on a card the amdgpu pin cap bounds it too. */ +int Engine::size_checkpoint_store(int64_t slot, const char* what) { + if (slot <= 0 || !cfg_.prefix_cache) { + cfg_.checkpoint_slots = 0; + decide("--checkpoint-slots", "0", + slot <= 0 ? "the model keeps no linear or sliding-window state to snapshot" + : "prefix caching is off (--no-prefix-cache)"); + return RAD_OK; + } + const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; + const int64_t interval = geo_.checkpoint_interval; + const std::unique_ptr pol = + make_checkpoint_policy(cfg_.checkpoint_policy, interval); + + int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20); + for (const auto& r : ranks_) still += arena_host_bytes(r->program); + std::string limit; + int64_t room = lockable_bytes(still, &limit); + if (!device_is_host()) { + bool lifted = false; + if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) { + int64_t pinned = 0, mapped = 0; + rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); + rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); + const int64_t left = std::max(cap - pinned - mapped - still, 0); + if (left < room) { + room = left; + limit = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s " + "and still pins %s", humanb(cap).c_str(), + humanb(pinned + mapped).c_str(), humanb(still).c_str()); + } + } + } + const int64_t total = meminfo_bytes("MemTotal"); + const int64_t share = total > 0 ? total / 8 : room; + const CheckpointSlots c = checkpoint_slots_auto(*pol, cfg_.max_seqs, ctx, interval, slot, + share, room); + cfg_.checkpoint_slots = c.slots; + + const std::string need = + fmt("%lld a sequence for --max-num-seqs %lld: %s keeps %lld for a %lld-token session at " + "a %lld-token interval, and one more for a running turn", (long long)c.per_seq, + (long long)cfg_.max_seqs, pol->name(), (long long)(c.per_seq - 1), (long long)ctx, + (long long)interval); + std::string bound; + if (c.bound == CheckpointSlots::Bound::Share) + bound = fmt("; %lld wanted, held to an eighth of host memory (%s); --checkpoint-slots N " + "sets more", (long long)c.want, humanb(share).c_str()); + else if (c.bound == CheckpointSlots::Bound::Room) + bound = fmt("; %lld wanted, held to what the host can pin: %s", (long long)c.want, + limit.c_str()); + decide("--checkpoint-slots", std::to_string(c.slots), need + bound); + if (c.slots == 0) { + RAD_WARN("checkpoint slots: auto finds no room for one %s snapshot of %s (%s), so every " + "prefix hit on this model prefills from the start. Free host memory, or lower " + "--host-pool-mib or --prefix-cache-mib", what, humanb(slot).c_str(), + limit.c_str()); + return RAD_OK; + } + const std::string line = + fmt("checkpoint slots: auto: %lld %s snapshot(s) of %s in pinned host memory (%s), none of " + "it on the card; %s%s", (long long)c.slots, what, humanb(slot).c_str(), + humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str()); + if (c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str()); + else RAD_INFO("%s", line.c_str()); + return RAD_OK; +} + int Engine::configure_kv() { /* Resolved once, for the cache below and Scheduler::init later (see Engine::geo_). */ RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_)); @@ -2726,9 +2882,11 @@ int Engine::configure_kv() { shard_off[i] = slot; slot += ranks_[i]->kv.checkpoint_bytes(); } - const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0; /* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */ const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state"; + const bool sized_auto = cfg_.checkpoint_slots < 0; + if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what)); + const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0; if (slot > 0 && n > 0 && cfg_.prefix_cache) { /* Pinned all at once and outside every pool. A store larger than the memory left would * push the process into reclaim, which stalls it without a word; one that cannot be had @@ -2736,13 +2894,14 @@ int Engine::configure_kv() { * makes visible. Either stops startup. */ const bool sized = n <= INT64_MAX / slot; auto refuse = [&](const std::string& reason) { - RAD_ERR("checkpoint slots: %lld %s snapshot(s) of %s are %s of pinned host memory, " - "which %s. Lower --checkpoint-slots (a larger --checkpoint-interval needs " - "fewer for the same context), or pass --checkpoint-slots 0 to serve with " - "no %s snapshot, every prefix hit on this model then prefilling from the " - "start", (long long)n, what, humanb(slot).c_str(), - sized ? humanb(slot * n).c_str() : "more than 8 EiB", reason.c_str(), - what); + RAD_ERR("checkpoint slots: %lld %s snapshot(s)%s of %s are %s of pinned host " + "memory, which %s. Lower --checkpoint-slots (a larger " + "--checkpoint-interval needs fewer for the same context), or pass " + "--checkpoint-slots 0 to serve with no %s snapshot, every prefix hit on " + "this model then prefilling from the start", (long long)n, what, + sized_auto ? " (auto)" : "", + humanb(slot).c_str(), sized ? humanb(slot * n).c_str() : "more than 8 EiB", + reason.c_str(), what); return RAD_E_NOMEM; }; if (!sized) return refuse("no host has"); @@ -2750,10 +2909,11 @@ int Engine::configure_kv() { if (!lockable_room(slot * n, 0, false, &why)) return refuse("does not fit: " + why); if (ck_store_.open(slot, slot * n) != RAD_OK) return refuse(std::string("the host did not pin: ") + rad_dev_last_error()); - RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), " - "none of it on the card", (long long)n, what, humanb(slot).c_str(), - humanb(ck_store_.cap_bytes()).c_str()); - } else if (slot > 0 && cfg_.prefix_cache) { + if (!sized_auto) + RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), " + "none of it on the card", (long long)n, what, humanb(slot).c_str(), + humanb(ck_store_.cap_bytes()).c_str()); + } else if (slot > 0 && cfg_.prefix_cache && !sized_auto) { RAD_INFO("checkpoint slots: --checkpoint-slots 0 keeps no %s snapshot, so every " "prefix hit on this model prefills from the start", what); } @@ -2911,6 +3071,14 @@ int Engine::configure_kv() { * * For an image generator the sequence is a conditioning, which its driver refuses at * admission; warn in those terms. */ + if (ranks_[0]->program.is_audio_generator()) { + RAD_WARN("kv group '%s' holds %lld rows: a request needs its prompt and every " + "frame it may make, both branches, up to %lld rows a branch, so a long " + "piece is refused at once rather than cut short. Ask for shorter " + "pieces, use --kv-cache-dtype fp8, or add ranks.", + p->name.c_str(), (long long)cap, (long long)want); + continue; + } if (ranks_[0]->program.is_generator()) { RAD_WARN("kv group '%s' holds %lld rows: a conditioning longer than that -- a " "prompt with its pictures, up to %lld rows -- is refused. A picture " @@ -3139,8 +3307,8 @@ int Engine::start() { } } - /* RUNTIME LoRA: the startup adapters, copied into their slots now that every rank's pools have - * an address and before any step can read them. */ + /* Runtime LoRA: the startup adapters, copied into their slots now that every rank's pools + * have an address and before any step can read them. */ RAD_TRY(lora_start()); /* ---- the loan: the cache's idle blocks, lent to the expert slab in place ----------------- diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index 4a372d19..1ac45b97 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -1,23 +1,41 @@ -/* engine_gen.cpp -- the image generator's loop: the driver's passes (core/gen/driver.h) run on - * the ranks like token steps, one at a time, each drained before the next. +/* engine_gen.cpp -- a generator's loop: the driver's passes (core/gen/pass.h; driver.h for + * images, audio_driver.h for audio, video_driver.h for video) run on the ranks like token steps, one at a time, each drained + * before the next. * * Draining is cheap: a pass is tens to thousands of milliseconds of device work, and the next * pass depends only on the driver's host bookkeeping, so the wait costs the microseconds of * building it. Issuing ahead would need a second staging region and a commit protocol. */ #include "engine_priv.h" -#include "gen/driver.h" +#include "gen/pass.h" #include #include namespace rad { +/* A generator pass's kind, for the buffer probe's lines. */ +static const char* pass_name(int gen) { + switch (gen) { + case RAD_GEN_PASS_COND: return "cond"; + case RAD_GEN_PASS_DENOISE: return "denoise"; + case RAD_GEN_PASS_DECODE: return "decode"; + case RAD_GEN_PASS_PROMPT: return "prompt"; + case RAD_GEN_PASS_FRAME: return "frame"; + case RAD_GEN_PASS_WINDOW: return "window"; + case RAD_GEN_PASS_VOCODE: return "vocode"; + case RAD_GEN_PASS_VCOND: return "vcond"; + case RAD_GEN_PASS_VSTEP: return "vstep"; + case RAD_GEN_PASS_ADECODE: return "adecode"; + case RAD_GEN_PASS_VDECODE: return "vdecode"; + default: return ""; + } +} + int Engine::gen_loop() { if (rad_dev_set(ranks_[0]->device) < 0) - RAD_ERR("image generator loop: could not bind rank 0's device"); + RAD_ERR("generator loop: could not bind rank 0's device"); int step = 0, idle = 0; - const rad_buf img = ranks_[0]->program.generator.image_out; /* An error ends the driver's requests, then the loop. */ auto stop = [&](int st) { gen_->shutdown("the engine stopped on an error and is not serving", st); @@ -43,15 +61,17 @@ int Engine::gen_loop() { rad_strerror(st)); return stop(st); } - /* A decode pass's image, copied behind it on rank 0's stream; every rank holds the same - * pixels. */ - if (const int64_t n = gen_->decode_bytes(); n > 0) { - const void* src = ranks_[0]->ctx.buf_ptr(img); + /* What the pass leaves for the host (an image, a window's samples, the frames' status), + * copied behind it on rank 0's stream; every rank holds the same values. */ + for (const gen::IPassDriver::Readback& r : gen_->readbacks()) { + if (st < 0 || r.bytes <= 0) continue; + const void* src = ranks_[0]->ctx.buf_ptr(r.buf); if (!src) { - RAD_ERR("the generator's image buffer was declared but never planned"); + RAD_ERR("the generator's output buffer '%s' was declared but never planned", + ranks_[0]->program.buffers[r.buf].name.c_str()); return stop(RAD_E_STATE); } - st = rad_memcpy_async(gen_->host_image(), src, n, ranks_[0]->ctx.stream()); + st = rad_memcpy_async(r.host, src, r.bytes, ranks_[0]->ctx.stream()); } for (auto& rk : ranks_) if (st >= 0) st = rad_stream_sync(rk->ctx.stream()); @@ -59,7 +79,7 @@ int Engine::gen_loop() { RAD_ERR("generator pass %d: the device failed: %s", step, rad_strerror(st)); return stop(st); } - dump_buffers(ranks_[0]->ctx, step); + dump_buffers(ranks_[0]->ctx, step, pass_name(b->gen)); gen_->done(); ++step; } diff --git a/core/engine_lora.cpp b/core/engine_lora.cpp index 977682b7..43b78c73 100644 --- a/core/engine_lora.cpp +++ b/core/engine_lora.cpp @@ -1,10 +1,10 @@ /* engine_lora.cpp -- runtime LoRA on the engine side: which modules adapters may target (fixed * before declare), and loading an adapter into a slot of every rank's pools. * - * A LOAD IS: pack the adapter for each rank (lora::load_adapter, host only), refuse a module no - * rank placed, copy each rank's bytes into the slot on a stream of its own, wait, and only then - * publish the name. A request can name the adapter only after the publish, so no step ever reads - * a slot while it is being written; a slot no published adapter holds is never referenced. */ + * A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank + * placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then + * publishes the name. A request can name the adapter only after the publish, so no step reads a + * slot while it is written. */ #include "engine_priv.h" #include "lora/lora.h" @@ -54,13 +54,8 @@ int read_targets(const std::string& dir, std::set* out, std::string int Engine::lora_targets() { if (!cfg_.lora.enabled()) return RAD_OK; - lora_targets_ = cfg_.lora.targets; + lora_targets_ = std::set(cfg_.lora.targets.begin(), cfg_.lora.targets.end()); if (lora_targets_.empty()) { - if (cfg_.lora.adapters.empty()) { - RAD_ERR("lora: --max-loras with no --lora names no module an adapter may target; give " - "them with --lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)"); - return RAD_E_INVAL; - } for (const auto& [name, dir] : cfg_.lora.adapters) { std::string err; const int s = read_targets(dir, &lora_targets_, &err); @@ -70,13 +65,6 @@ int Engine::lora_targets() { } } } - std::set seen; - for (const auto& [name, dir] : cfg_.lora.adapters) { - if (!seen.insert(name).second) { - RAD_ERR("lora: two adapters are named '%s'", name.c_str()); - return RAD_E_INVAL; - } - } lora_table_.reset(cfg_.lora.slots(), &lora_epoch_); return RAD_OK; } @@ -92,6 +80,35 @@ int Engine::lora_start() { t.c_str()); return RAD_E_UNSUPPORTED; } + /* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds + * only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */ + { + std::set carried; + for (const auto& r : ranks_) + for (const lora::Site& site : r->lora_sites) + for (const lora::SiteSource& src : site.sources) + if (src.targeted) carried.insert(src.module.substr(src.module.rfind('.') + 1)); + for (const std::string& x : lora_targets_) + if (!carried.count(x)) { + RAD_ERR("lora: the target module '%s' is no trunk linear of this model, so no " + "adapter could land on it; leave it out of --lora-target-modules (or of " + "the adapters' target_modules)", x.c_str()); + return RAD_E_UNSUPPORTED; + } + } + /* The adapter ops run in their GEMM's domain and read the pools on the card, so a targeted + * GEMM placed on the host could serve no adapter request. On the host backend every op and + * the pools are in host memory. */ + if (!device_is_host()) + for (const auto& r : ranks_) + for (const LoraIssueSite& site : r->program.lora_sites) + if (r->ctx.op_domain((rad_op)site.gemm) != RAD_DOMAIN_DEVICE) { + RAD_ERR("lora: rank %d: the GEMM over '%s' is placed on the host, and its " + "adapter ops read pools on the card; keep the targeted weights in " + "VRAM or leave the module out of --lora-target-modules", r->index, + r->program.lora_pools[(size_t)site.pool].weight.c_str()); + return RAD_E_UNSUPPORTED; + } { const Program& P = ranks_[0]->program; int64_t slot_bytes = 0; @@ -118,12 +135,10 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri std::lock_guard lk(lora_mu_); if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; } if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; } - /* A SLOT FREED A MOMENT AGO IS WAITED FOR HERE, not handed back as a retry. It is reusable once - * the step loop has gone round three times (a pass issued ahead may still read it), and the - * loop goes round idle or busy, so that is milliseconds -- an unload followed at once by a load - * (a hot swap) would otherwise fail almost every time under traffic. Only other loads wait on - * lora_mu_ meanwhile; requests and unloads go to the table, and the step loop's counter is an - * atomic. */ + /* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a + * retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap + * (unload, then load at once) would otherwise fail under traffic. Only other loads wait on + * lora_mu_ meanwhile; requests and unloads use the table alone. */ const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2); int slot = -1; for (;;) { @@ -174,8 +189,8 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri char* ds = (char*)P.buffers[lp.scale].ptr; if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; } da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb; - /* A pool this adapter does not touch is ZEROED, not left: the bytes are whatever the - * last adapter in the slot or the arena held, and a scale of 0 times a NaN is a NaN. */ + /* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what + * the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */ if (ps.empty) { if (rad_memset_async(da, 0, ab, st) < 0 || rad_memset_async(db, 0, bb, st) < 0 || rad_memset_async(ds, 0, sb, st) < 0) diff --git a/core/engine_priv.h b/core/engine_priv.h index f1a1dbe3..b762a3a3 100644 --- a/core/engine_priv.h +++ b/core/engine_priv.h @@ -34,7 +34,7 @@ struct Engine::Rank { int index = 0; int device = 0; Program program; /* declare runs once per rank: dimensions are already divided */ - /* RUNTIME LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's + /* Runtime LoRA: this rank's sites (core/lora/lora.h), the loader's map from an adapter's * modules to this rank's slot bytes. Empty with LoRA off. */ std::vector lora_sites; Plan plan; diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp index cff9ac53..bba87b21 100644 --- a/core/engine_probe.cpp +++ b/core/engine_probe.cpp @@ -7,6 +7,7 @@ #include "device/device.h" #include "rad_plugin.h" +#include #include #include #include @@ -21,7 +22,10 @@ namespace rad { * * RADIANCE_DUMP_BUF names declared buffers (comma separated); every step prints the first row of * each: mean, largest magnitude and first four elements. RADIANCE_DUMP_HEAD= adds the first n - * elements verbatim (integers included); RADIANCE_DUMP_TOPK= adds the k largest. + * elements verbatim (integers included); RADIANCE_DUMP_TOPK= adds the k largest. A name may + * carry a row count, `frame.mix:100`, to read that many rows as one (a code-major plane holds one + * code a row). RADIANCE_DUMP_DIR= also writes each read's raw bytes to + * /--.bin, for a comparison against another implementation's tensors. * * It shows tensors inside a step, which neither rad-kbench (one op at a time) nor --debug-graph * (what was declared) can. An environment variable at -vv only, because it adds a device-to-host @@ -70,6 +74,13 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty uint64_t h = 1469598103934665603ull; for (size_t i = 0; i < raw.size(); ++i) { h ^= raw[i]; h *= 1099511628211ull; } const int64_t good = cnt - bad; + if (const char* dir = std::getenv("RADIANCE_DUMP_DIR"); dir && *dir) { + const std::string path = fmt("%s/%d-%s-%s.bin", dir, step, phase, name); + if (FILE* f = std::fopen(path.c_str(), "wb")) { + std::fwrite(raw.data(), 1, raw.size(), f); + std::fclose(f); + } + } RAD_TRACE("step %d%-8s %-28s %-5s n=%lld hash %016llx mean %.6f amax %.5f " "nonfinite %lld%s [%.6f %.6f %.6f %.6f]", step, phase, name, rad_dtype_name(dtype), (long long)cnt, (unsigned long long)h, @@ -159,8 +170,13 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) { for (const char* s = names; *s; ) { const char* e = s; while (*e && *e != ',') ++e; - const std::string want(s, (size_t)(e - s)); + std::string want(s, (size_t)(e - s)); s = *e ? e + 1 : e; + int64_t rows = 1; + if (const size_t colon = want.find(':'); colon != std::string::npos) { + rows = std::max(1, std::strtoll(want.c_str() + colon + 1, nullptr, 10)); + want.resize(colon); + } if (want.empty()) continue; /* Weights match the same names, to check that the loader put the right checkpoint tensor @@ -188,7 +204,7 @@ void dump_buffers(Ctx& ctx, int step, const char* phase) { const int64_t row = b.decl.rank >= 1 ? b.bytes / (b.decl.shape[0] ? b.decl.shape[0] : 1) : b.bytes; done = dump_at(ctx, step, phase, b.name, b.decl.dtype, ptr, - std::min(row, dump_cap())); + row <= dump_cap() ? std::min(row * rows, b.bytes) : dump_cap()); } } } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 3af20b86..43d66fd1 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -467,6 +468,13 @@ static int meta_merge_json_file(const std::string& path, const std::string& pref static bool path_exists(const std::string& p) { std::ifstream f(p); return (bool)f; } +/* Whether an FP8 piece of `rows` rows has one scale for the whole tensor: a rank-0 scale + * (ModelOpt's) or a one-element [1] (compressed-tensors' tensor strategy). A [1, 1] scale is a + * block plane. */ +static bool per_tensor_scale(const SrcTensor& s, int64_t rows) { + return s.shape.empty() || (s.shape.size() == 1 && s.shape[0] == 1 && rows > 1); +} + /* "X.weight" -> "X"; false for a name with no such suffix. */ static bool weight_base(const std::string& name, std::string* base) { static const std::string suffix = ".weight"; @@ -477,34 +485,77 @@ static bool weight_base(const std::string& name, std::string* base) { return true; } -/* A diffusers pipeline: model_index.json at the top and one folder per component, each with its - * own config and weights, read as one checkpoint: +/* A diffusers pipeline: model_index.json (or a modular pipeline's modular_model_index.json) at the + * top and one folder per component, each with its own config and weights, read as one checkpoint: * - * text_encoder/ its config.json is the container's model config -- the typed dimensions and - * the bare keys -- and its tensors keep their names; - * transformer/ tensors under `transformer.`, config.json under `transformer.` keys; - * vae/ tensors under `vae.`, config.json under `vae.` keys; - * scheduler/ scheduler_config.json under `scheduler.` keys; - * processor/ (or tokenizer/) the tokenizer, the chat template and the preprocessor configs. + * text_encoder/ or language_model/ the transformers model: its config.json is the + * container's model config -- the typed dimensions and the bare keys -- and its + * tensors keep their names; + * every other folder holding a diffusers model (config.json beside + * diffusion_pytorch_model*.safetensors): tensors under `.`, config.json + * under `.` keys (transformer/, vae/; MiniMax-Music3's + * rvq_depth_decoder/, condition_encoder/, vocoder/); + * scheduler/ scheduler_config.json under `scheduler.` keys (any folder holding one, under + * its own name); + * processor/ (or tokenizer/) the tokenizer, the chat template and the preprocessor configs; + * .json any other JSON object beside the index under `.` keys (a distilled + * release's inference settings: its trained timesteps, its attention's sparsity). * - * model_index.json goes under `pipeline.` keys, and its `_class_name` names the architecture - * (`QwenImage21Pipeline` is `qwenimage21`). A component folder may link to another pipeline's (a - * distilled release sharing its base's text encoder). */ + * The index goes under `pipeline.` keys, and its `_class_name` names the architecture + * (`QwenImage21Pipeline` is `qwenimage21`, `MiniMaxMusic3ModularPipeline` is `minimaxmusic3`). A + * component folder may link to another pipeline's (a distilled release sharing its base's text + * encoder). */ int Checkpoint::open_diffusers() { kind_ = SafeT; - RAD_TRY(meta_merge_json_file(dir_ + "/model_index.json", "pipeline", false, &meta_)); - const std::string te = dir_ + "/text_encoder"; - if (path_exists(te + "/config.json")) { + const bool modular = !path_exists(dir_ + "/model_index.json"); + RAD_TRY(meta_merge_json_file(dir_ + (modular ? "/modular_model_index.json" : "/model_index.json"), + "pipeline", false, &meta_)); + { + std::vector tops; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_regular_file(ec) || de.path().extension() != ".json") continue; + const std::string nm = de.path().filename().string(); + if (nm == "model_index.json" || nm == "modular_model_index.json") continue; + tops.push_back(nm); + } + std::sort(tops.begin(), tops.end()); + for (const std::string& nm : tops) + RAD_TRY(meta_merge_json_file(dir_ + "/" + nm, nm.substr(0, nm.size() - 5), false, + &meta_)); + } + std::string lm_dir; + for (const char* sub : { "text_encoder", "language_model" }) + if (path_exists(dir_ + "/" + sub + "/config.json")) { + lm_dir = dir_ + "/" + sub; + break; + } + if (!lm_dir.empty()) { std::vector shards; std::unordered_map owner; - RAD_TRY(shard_list(te, te + "/model.safetensors.index.json", false, &shards, &owner)); + RAD_TRY(shard_list(lm_dir, lm_dir + "/model.safetensors.index.json", false, &shards, + &owner)); for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner)); - RAD_TRY(meta_from_config_json(te, &meta_)); - RAD_TRY(meta_merge_generation_config(te, &meta_)); + RAD_TRY(meta_from_config_json(lm_dir, &meta_)); + RAD_TRY(meta_merge_generation_config(lm_dir, &meta_)); } - for (const char* comp : { "transformer", "vae" }) { + /* The diffusers models, in name order so the namespace does not depend on the directory's. */ + std::vector comps; + { + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_directory(ec)) continue; + const std::string nm = de.path().filename().string(); + const std::string d = dir_ + "/" + nm; + if (d == lm_dir || !path_exists(d + "/config.json")) continue; + if (path_exists(d + "/diffusion_pytorch_model.safetensors") || + path_exists(d + "/diffusion_pytorch_model.safetensors.index.json")) + comps.push_back(nm); + } + std::sort(comps.begin(), comps.end()); + } + for (const std::string& comp : comps) { const std::string d = dir_ + "/" + comp; - if (!path_exists(d + "/config.json")) continue; const std::string idx = d + "/diffusion_pytorch_model.safetensors.index.json"; std::vector shards; std::unordered_map owner; @@ -514,11 +565,23 @@ int Checkpoint::open_diffusers() { shards.push_back(d + "/diffusion_pytorch_model.safetensors"); } for (const auto& sh : shards) - RAD_TRY(add_shard(sh, std::string(comp) + ".", owner.empty() ? nullptr : &owner)); + RAD_TRY(add_shard(sh, comp + ".", owner.empty() ? nullptr : &owner)); RAD_TRY(meta_merge_json_file(d + "/config.json", comp, false, &meta_)); } - RAD_TRY(meta_merge_json_file(dir_ + "/scheduler/scheduler_config.json", "scheduler", true, - &meta_)); + /* Every scheduler folder under its own name: scheduler/, and a second schedule's (MiniMax-H3's + * audio_scheduler/). */ + { + std::vector scheds; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) + if (de.is_directory(ec) && + path_exists(de.path().string() + "/scheduler_config.json")) + scheds.push_back(de.path().filename().string()); + std::sort(scheds.begin(), scheds.end()); + for (const std::string& sc : scheds) + RAD_TRY(meta_merge_json_file(dir_ + "/" + sc + "/scheduler_config.json", sc, true, + &meta_)); + } for (const char* sub : { "processor", "tokenizer" }) { const std::string d = dir_ + "/" + sub; if (!path_exists(d + "/tokenizer.json")) continue; @@ -526,12 +589,14 @@ int Checkpoint::open_diffusers() { RAD_TRY(meta_merge_preprocessor_configs(d, &meta_)); break; } - /* The architecture is the pipeline's, whatever the text encoder calls itself. */ + /* The architecture is the pipeline's, whatever the language model calls itself. */ if (const char* cn = meta_.get("pipeline._class_name")) { std::string a = cn; - const std::string suf = "Pipeline"; - if (a.size() > suf.size() && a.compare(a.size() - suf.size(), suf.size(), suf) == 0) - a.resize(a.size() - suf.size()); + for (const std::string suf : { "ModularPipeline", "Pipeline" }) + if (a.size() > suf.size() && a.compare(a.size() - suf.size(), suf.size(), suf) == 0) { + a.resize(a.size() - suf.size()); + break; + } for (char& ch : a) ch = (char)std::tolower((unsigned char)ch); meta_.arch = a; } @@ -551,8 +616,11 @@ int Checkpoint::open_safetensors(const std::string& path) { const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0; const bool is_file = path.size() > 12 && path.compare(path.size() - 12, 12, ".safetensors") == 0; - if (!is_file && !is_index && path_exists(dir_ + "/model_index.json") && - !path_exists(dir_ + "/config.json")) + /* A pipeline index at the top: a diffusers pipeline. A modular pipeline may also carry a + * config.json there (MiniMax-Music3's names its model class), which is not a model's. */ + if (!is_file && !is_index && + ((path_exists(dir_ + "/model_index.json") && !path_exists(dir_ + "/config.json")) || + path_exists(dir_ + "/modular_model_index.json"))) return open_diffusers(); if (is_file) { shards.push_back(path); @@ -565,6 +633,7 @@ int Checkpoint::open_safetensors(const std::string& path) { RAD_TRY(meta_from_config_json(dir_, &meta_)); RAD_TRY(meta_merge_generation_config(dir_, &meta_)); RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_)); + if (!is_file && !is_index) RAD_TRY(add_companions()); /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { long long r = 0, c = 0; @@ -578,6 +647,35 @@ int Checkpoint::open_safetensors(const std::string& path) { return RAD_OK; } +/* Companion models: a folder beside the model's own weights holding a model of its own (its + * config.json and safetensors), such as Breeze-TTS-2's audio_tokenizer/ (the codec its frames are + * played through). Each is read as part of the checkpoint, its tensors under `.` and its + * config under `.` keys, in name order so the namespace does not depend on the + * directory's; a plugin that has no use for one maps none of it. */ +int Checkpoint::add_companions() { + std::vector comps; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_directory(ec)) continue; + const std::string d = de.path().string(); + if (path_exists(d + "/config.json") && + (path_exists(d + "/model.safetensors") || + path_exists(d + "/model.safetensors.index.json"))) + comps.push_back(de.path().filename().string()); + } + std::sort(comps.begin(), comps.end()); + for (const std::string& c : comps) { + const std::string d = dir_ + "/" + c; + std::vector shards; + std::unordered_map owner; + RAD_TRY(shard_list(d, d + "/model.safetensors.index.json", false, &shards, &owner)); + for (const auto& sh : shards) + RAD_TRY(add_shard(sh, c + ".", owner.empty() ? nullptr : &owner)); + RAD_TRY(meta_merge_config_json(d, c, &meta_)); + } + return RAD_OK; +} + /* Which published quantisation this is, from quantization_config alone; import_piece checks the * tensors weight by weight, refusing a file at the first weight that disagrees. */ void Checkpoint::detect_import() { @@ -614,14 +712,20 @@ void Checkpoint::detect_import() { "throughout, which is the one this reads"; } else if (qm == "compressed-tensors") { /* compressed-tensors states each scheme as a config group with a format. Three are read: - * pack-quantized symmetric grouped int4 (e.g. Google's Gemma 4 QAT w4a16-ct); - * every group must be one, and a zero point, act-order, or a - * dynamic or activation scheme would change what a code means + * pack-quantized grouped int4, symmetric (e.g. Google's Gemma 4 QAT w4a16-ct) + * or asymmetric with an integer zero point per group (W4A16_ASYM, + * as llm-compressor's AWQ writes it); every group must be one, + * and one group-reordering act-order, or a dynamic or activation + * scheme, would change what a code means * nvfp4-pack-quantized NVFP4: e2m1 codes, an e4m3 scale per 16 of K, an f32 global * scale per tensor * float-quantized 8-bit float weights, read by the FP8 path - * NVFP4 and float groups may be mixed (a mixed-precision release ships NVFP4 MLPs beside - * FP8 linears); the tensors confirm each weight's form at import_piece and ckpt_resolve. */ + * Act-order `static` (an alias of `weight`) quantises the columns in activation order but + * keeps each group's columns contiguous, so the weight reads as one without act-order; + * `group` (alias `dynamic`) reorders the groups through X.weight_g_idx, which the int4 + * kernels do not follow. NVFP4 and float groups may be mixed (a mixed-precision release + * ships NVFP4 MLPs beside FP8 linears); the tensors confirm each weight's form at + * import_piece and ckpt_resolve. */ std::vector groups; const std::string cg = "quantization_config.config_groups."; for (const std::string& k : meta_.keys) @@ -631,7 +735,7 @@ void Checkpoint::detect_import() { } std::string why; int64_t group = 0; - int n_int4 = 0, n_nvfp4 = 0, n_fp8 = 0; + int n_int4 = 0, n_nvfp4 = 0, n_fp8 = 0, n_asym = 0; if (groups.empty()) why = "its quantization_config names no config group"; for (const std::string& g : groups) { if (!why.empty()) break; @@ -653,20 +757,27 @@ void Checkpoint::detect_import() { } else if (f == "pack-quantized") { const std::string gs = qc(w + "group_size"); const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str()); + const std::string ao = qc(w + "actorder"); if (qc("format") != "pack-quantized") why = "its format is '" + qc("format") + "', and an int4 group is read only " "in a pack-quantized config"; + else if (ao == "group" || ao == "dynamic") + why = "config group '" + g + "' has act-order '" + ao + "', which reorders " + "the columns' groups through weight_g_idx; the int4 GEMMs read groups " + "in column order, so only act-order 'static' or 'weight' (groups kept " + "contiguous) or none is read"; else if (qc(w + "num_bits") != "4" || qc(w + "type") != "int" || - qc(w + "symmetric") != "1" || qc(w + "strategy") != "group" || - qc(w + "dynamic") != "0" || gn <= 0 || !qc(w + "actorder").empty() || + (qc(w + "symmetric") != "1" && qc(w + "symmetric") != "0") || + qc(w + "strategy") != "group" || qc(w + "dynamic") != "0" || gn <= 0 || + (!ao.empty() && ao != "static" && ao != "weight") || any_under("config_groups." + g + ".input_activations.")) - why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, " - "packed, with no act-order and unquantised activations, which is the " - "one this reads"; + why = "config group '" + g + "' is not 4-bit int weights in groups, packed, " + "with unquantised activations, which is the one this reads"; else if (group && gn != group) why = "its config groups state different group sizes"; else group = gn; + if (qc(w + "symmetric") == "0") ++n_asym; ++n_int4; } else { why = "config group '" + g + "' is in the format '" + f + "'"; @@ -674,15 +785,58 @@ void Checkpoint::detect_import() { } if (why.empty() && n_int4 && (n_nvfp4 || n_fp8)) why = "it mixes pack-quantized int4 groups with float ones"; + if (why.empty() && n_asym && n_asym != n_int4) + why = "it mixes symmetric and asymmetric int4 groups"; if (!why.empty()) { import_why_ = "compressed-tensors: " + why + "; the formats read are pack-quantized " - "(symmetric int4), nvfp4-pack-quantized and float-quantized (8-bit float)"; + "(int4, symmetric or with a zero point), nvfp4-pack-quantized and " + "float-quantized (8-bit float)"; } else if (n_int4) { import_ = Import::CtInt4; ct_group_ = group; + ct_asym_ = n_asym > 0; } else { import_ = n_nvfp4 ? Import::Nvfp4 : Import::CtFp8; } + } else if (qm == "modelopt") { + /* NVIDIA ModelOpt's export, one algorithm (`quant_algo`) or one per layer + * (MIXED_PRECISION, `quantized_layers..quant_algo`). Two are read: + * NVFP4 `X.weight` U8 [N, K/2] e2m1 codes, `X.weight_scale` e4m3 [N, K/16] and + * `X.weight_scale_2` f32, one per tensor, a multiplier of the e4m3 scale + * FP8 `X.weight` E4M3 [N, K] and `X.weight_scale` f32, one per tensor + * `X.input_scale` (a static activation scale) is not read: activations are quantised + * from their own values (the GEMM's activation quantiser). Any other algorithm (an + * AWQ-scaled one ships a pre_quant_scale this does not apply) is refused by name. */ + std::vector algos; + const std::string ql = "quantization_config.quantized_layers."; + for (size_t i = 0; i < meta_.keys.size(); ++i) { + const std::string& k = meta_.keys[i]; + const std::string tail = ".quant_algo"; + if (k.rfind(ql, 0) == 0 && k.size() > ql.size() + tail.size() && + k.compare(k.size() - tail.size(), tail.size(), tail) == 0) + algos.push_back(meta_.vals[i]); + const std::string gtail = ".group_size"; + if (k.rfind(ql, 0) == 0 && k.size() > ql.size() + gtail.size() && + k.compare(k.size() - gtail.size(), gtail.size(), gtail) == 0 && + meta_.vals[i] != "16" && import_why_.empty()) + import_why_ = "ModelOpt's '" + k.substr(ql.size(), k.size() - ql.size() - + gtail.size()) + + "' has group_size " + meta_.vals[i] + "; NVFP4 is read in groups of 16"; + } + const std::string top = qc("quant_algo"); + if (top != "MIXED_PRECISION") algos.push_back(top); + if (top == "NVFP4" && !qc("group_size").empty() && qc("group_size") != "16" && + import_why_.empty()) + import_why_ = "ModelOpt's NVFP4 here has group_size " + qc("group_size") + + "; it is read in groups of 16"; + if (algos.empty() && import_why_.empty()) + import_why_ = "ModelOpt's quantization_config names no quant_algo"; + for (const std::string& a : algos) + if (a != "NVFP4" && a != "FP8" && import_why_.empty()) + import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4 " + "and FP8 (per tensor), alone or per layer, are"; + if (import_why_.empty()) import_ = Import::ModelOpt; + else import_why_ = "modelopt: " + import_why_; } else if (qm == "paroquant") { /* z-lab's ParoQuant at integer widths: "int5-bitplane" (AWQ nibbles for the low four bits * plus a fifth-bit plane) or AWQ-packed int4, group 128, asymmetric, with the learned @@ -793,20 +947,28 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, if (import_ == Import::CtInt4) { /* CT-INT4: `X.weight` ships as X.weight_packed (i32 [N, K/8], eight codes per word from the - * low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are already the - * [N, K] code matrix in row order; only the offset is left for the relayout. An ignored - * layer is an ordinary X.weight. */ + * low bits, each the signed code plus 8) and X.weight_scale ([N, K/group]), and when + * asymmetric X.weight_zero_point (see SrcTensor::ct_zero). compressed-tensors dequantises + * w = (q - zero_point) * scale + * with q and zero_point the signed values (zero_point 0 when symmetric). The words are + * already the [N, K] code matrix in row order: a symmetric code is the stored nibble less + * 8 (i4), an asymmetric one the stored nibble (u4) under the stored zero (zero_point + 8). + * An ignored layer is an ordinary X.weight. */ std::string base; if (!weight_base(name, &base)) return RAD_E_NOTFOUND; const SrcTensor* pk = find(name + "_packed"); if (!pk) return RAD_E_NOTFOUND; const SrcTensor* sc = find(name + "_scale"); + const SrcTensor* zp = find(name + "_zero_point"); const std::string what = "'" + pk->name + "'"; if (pk->rad_dtype != RAD_I32 || pk->shape.size() != 2) return refuse(RAD_E_FORMAT, what + " is not an int32 [N, K/8] matrix"); - if (find(name + "_zero_point")) - return refuse(RAD_E_UNSUPPORTED, what + " has a zero point beside it, which a symmetric " - "config does not; an asymmetric weight is not read"); + if (zp && !ct_asym_) + return refuse(RAD_E_FORMAT, what + " has a zero point beside it, which its symmetric " + "config does not state"); + if (!zp && ct_asym_) + return refuse(RAD_E_FORMAT, what + " has no '" + name + "_zero_point' beside it, " + "which its asymmetric config states"); const int64_t N = pk->shape[0], K = pk->shape[1] * 8; if (K % ct_group_) return refuse(RAD_E_SHAPE, what + " has " + std::to_string(K) + " columns, not whole " @@ -816,6 +978,23 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return refuse(RAD_E_FORMAT, what + " has no float [" + std::to_string(N) + ", " + std::to_string(K / ct_group_) + "] '" + name + "_scale' beside it"); + const int64_t G = K / ct_group_; + if (zp && (zp->rad_dtype != RAD_I32 || zp->shape.size() != 2 || + zp->shape[0] != (N + 7) / 8 || zp->shape[1] != G)) + return refuse(RAD_E_FORMAT, "'" + zp->name + "' is not the int32 [" + + std::to_string((N + 7) / 8) + ", " + std::to_string(G) + + "] zero points of " + what + ", packed along its rows"); + /* Act-order 'static' / 'weight' ships no group index; one that does must keep every + * column in its own group. */ + if (const SrcTensor* gi = find(name + "_g_idx")) { + if ((gi->rad_dtype != RAD_I32 && gi->rad_dtype != RAD_I64) || gi->numel() != K) + return refuse(RAD_E_FORMAT, "'" + gi->name + "' is not an integer [K] group index"); + for (int64_t k = 0; k < K; ++k) + if ((int64_t)rad_load_f32(gi->data, gi->rad_dtype, k) != k / ct_group_) + return refuse(RAD_E_UNSUPPORTED, "'" + gi->name + "' reorders the columns' " + "groups (act-order); only an in-order index " + "is read"); + } if (const SrcTensor* ws = find(name + "_shape")) { int64_t dims[2] = { 0, 0 }; for (int i = 0; i < 2 && i < (int)ws->numel(); ++i) @@ -826,9 +1005,10 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, "] its codes hold"); } SrcTensor c = *pk; - c.rad_dtype = RAD_I4; + c.rad_dtype = zp ? RAD_U4 : RAD_I4; c.shape = { N, K }; c.ct_group = ct_group_; + c.ct_zero = zp; sliced_.push_back(std::move(c)); *codes = &sliced_.back(); *scale = sc; @@ -836,6 +1016,62 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return RAD_OK; } + if (import_ == Import::ModelOpt) { + /* ModelOpt's NVFP4: `X.weight` U8 [N, K/2] (two e2m1 codes a byte, the even k in the low + * nibble), `X.weight_scale` e4m3 [N, K/16] and `X.weight_scale_2` f32, one per tensor. + * ModelOpt dequantises + * w = e2m1(code) * (float(weight_scale) * weight_scale_2) + * so the second level multiplies (compressed-tensors' global scale divides). The f32 scale + * plane is that product, one per 16 of K, owned here; the code times it is ModelOpt's f32 + * value. A weight whose `X.weight` is not U8 (an FP8 or bf16 linear) reads stock. */ + const SrcTensor* p = find(name); + if (!p || p->rad_dtype != RAD_U8) return RAD_E_NOTFOUND; + std::string base; + if (!weight_base(name, &base) || p->shape.size() != 2) + return refuse(RAD_E_FORMAT, "'" + name + "' is a U8 tensor and not the [N, K/2] codes " + "of a ModelOpt NVFP4 linear"); + const SrcTensor* s = find(base + ".weight_scale"); + const SrcTensor* s2 = find(base + ".weight_scale_2"); + const int64_t N = p->shape[0], K = p->shape[1] * 2; + if (!s || s->rad_dtype != RAD_F8E4M3 || s->shape.size() != 2 || s->shape[0] != N || + K % 16 || s->shape[1] != K / 16) + return refuse(RAD_E_FORMAT, "'" + name + "' has no e4m3 [" + std::to_string(N) + ", " + + std::to_string(K / 16) + "] weight_scale beside its " + "packed codes, which is ModelOpt's NVFP4"); + if (!s2 || s2->rad_dtype != RAD_F32 || s2->bytes != 4) + return refuse(RAD_E_FORMAT, "'" + name + "' has no single f32 weight_scale_2 beside " + "its packed codes, which is ModelOpt's NVFP4"); + float m; + std::memcpy(&m, s2->data, 4); + if (!(m > 0.0f) || !std::isfinite(m)) + return refuse(RAD_E_FORMAT, "'" + s2->name + "' is not a usable f32 multiplier: " + + std::to_string(m)); + const int64_t nsc = N * (K / 16); + auto raw = std::make_unique((size_t)nsc * 4); + float* tab = reinterpret_cast(raw.get()); + const uint8_t* sb = (const uint8_t*)s->data; + for (int64_t i = 0; i < nsc; ++i) { + tab[i] = rad_fp8e4m3_to_f32(sb[(size_t)i]) * m; + if (!std::isfinite(tab[i])) + return refuse(RAD_E_FORMAT, "'" + s->name + "' holds a scale that is not finite " + "at element " + std::to_string(i)); + } + owned_.push_back(std::move(raw)); + SrcTensor sv = *s; + sv.rad_dtype = RAD_F32; + sv.data = owned_.back().get(); + sv.bytes = nsc * 4; + SrcTensor pv = *p; + pv.rad_dtype = RAD_FP4E2M1; + pv.shape = { N, K }; + sliced_.push_back(std::move(pv)); + *codes = &sliced_.back(); + sliced_.push_back(std::move(sv)); + *scale = &sliced_.back(); + imported_[name] = { *codes, *scale }; + return RAD_OK; + } + if (import_ == Import::Nvfp4) { /* NVFP4 (compressed-tensors' nvfp4-pack-quantized): `X.weight_packed` U8 [N, K/2], two * e2m1 codes per byte with the even k in the low nibble; `X.weight_scale` e4m3 [N, K/16]; @@ -1053,6 +1289,32 @@ const SrcTensor* Checkpoint::slice(const SrcTensor& st, int index, const char* d return &sliced_.back(); } +const SrcTensor* Checkpoint::rows(const SrcTensor& st, int64_t r0, int64_t n, const char* declared) { + if (st.shape.empty() || st.rad_dtype == RAD_DT_INVALID || st.gptq_bits || st.ct_group || + st.pbits) { + RAD_ERR("'%s' asks for rows of '%s', which is not a plainly stored tensor of rows", + declared, st.name.c_str()); + return nullptr; + } + const int64_t total = st.shape[0]; + if (r0 < 0 || n <= 0 || r0 + n > total || !st.data || st.bytes % total != 0) { + RAD_ERR("'%s' asks for rows [%lld, %lld) of '%s', which holds %lld", declared, + (long long)r0, (long long)(r0 + n), st.name.c_str(), (long long)total); + return nullptr; + } + const int64_t rb = st.bytes / total; + SrcTensor v; + v.name = st.name + "[" + std::to_string(r0) + ":" + std::to_string(r0 + n) + "]"; + v.ggml = st.ggml; + v.rad_dtype = st.rad_dtype; + v.shape = st.shape; + v.shape[0] = n; + v.bytes = rb * n; + v.data = (const uint8_t*)st.data + (size_t)(r0 * rb); + sliced_.push_back(std::move(v)); + return &sliced_.back(); +} + /* ================================================================== logical weights */ namespace { @@ -1191,6 +1453,169 @@ int paro_attach(Checkpoint& ck, CkptWeight* out, std::string* why) { } /* namespace */ +namespace { +int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out); +} /* namespace */ + +/* RAD_MAP_WNORM: src[0] the magnitude g ([d0, 1, ...]), src[1] the direction v ([d0, ...]). The + * weight is v's shape, and each dim-0 slice's factor g_i / ||v_i|| is computed here, in double, + * from v as the checkpoint stores it. */ +static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, CkptWeight* out, + std::string* why) { + auto refuse = [&](int rc, std::string msg) { + if (why) *why = std::move(msg); + return rc; + }; + if (m.n_src != 2) + return refuse(RAD_E_INVAL, "a weight-norm map names its magnitude and its direction"); + const SrcTensor* g = ck.find(m.src[0]); + const SrcTensor* v = ck.find(m.src[1]); + if (!g || !v) { + if (optional && !g && !v) return refuse(RAD_E_NOTFOUND, "none of its tensors is there"); + return refuse(RAD_E_NOTFOUND, std::string("it needs checkpoint tensors '") + m.src[0] + + "' and '" + m.src[1] + "', which are not both in " + ck.path()); + } + if (v->shape.empty() || v->shape.size() > RAD_MAX_RANK || g->shape.empty() || + g->shape[0] != v->shape[0]) + return refuse(RAD_E_SHAPE, "'" + g->name + "' and '" + v->name + "' are not a weight " + "norm's magnitude and direction"); + int64_t gn = 1, vn = 1; + for (int64_t x : g->shape) gn *= x; + for (int64_t x : v->shape) vn *= x; + const int64_t d0 = v->shape[0]; + if (gn != d0 || vn % d0) + return refuse(RAD_E_SHAPE, "'" + g->name + "' holds " + std::to_string(gn) + " values for " + "the " + std::to_string(d0) + " slices of '" + v->name + "'"); + const int64_t per = vn / d0; + std::vector vf((size_t)vn), gf((size_t)d0); + if (piece_f32(*v, 0, vn, vf.data()) < 0 || piece_f32(*g, 0, d0, gf.data()) < 0) + return refuse(RAD_E_FORMAT, "'" + v->name + "' or '" + g->name + "' cannot be read as f32"); + out->wnorm_scale.assign((size_t)d0, 0.0f); + for (int64_t i = 0; i < d0; ++i) { + double ss = 0; + for (int64_t k = 0; k < per; ++k) { + const double x = vf[(size_t)(i * per + k)]; + ss += x * x; + } + out->wnorm_scale[(size_t)i] = ss > 0 ? (float)((double)gf[(size_t)i] / std::sqrt(ss)) : 0.0f; + } + out->wnorm = true; + out->pieces.assign(1, v); + out->scales.assign(1, nullptr); + out->concat_dim = 0; + out->rank = (uint32_t)v->shape.size(); + for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = v->shape[i]; + rad_enc_view(out->rank, out->shape, &out->rows, &out->cols); + out->trivial = false; + out->why = "it is weight-normalised ('" + g->name + "' times '" + v->name + "' over its norm), " + "folded at convert -- a recipe rule stores it"; + return RAD_OK; +} + +/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]) and RAD_MAP_EMA (src[0] the embedding + * sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), computed in + * f32 into `derived`. */ +static int resolve_derived(Checkpoint& ck, const std::vector& maps, + bool optional, CkptWeight* out, std::string* why) { + auto refuse = [&](int rc, std::string msg) { + if (why) *why = std::move(msg); + return rc; + }; + /* Stacked EMA codebooks: each map's rows in turn, every one the first's width. */ + if (maps.size() > 1) { + std::vector all; + int64_t rows = 0, per = -1; + std::string names; + for (const RadNameMap* pm : maps) { + CkptWeight one; + const std::vector single{ pm }; + const int rc = resolve_derived(ck, single, false, &one, why); + if (rc < 0) return rc; + const int64_t w = (int64_t)one.derived.size() / one.shape[0]; + if (per >= 0 && w != per) + return refuse(RAD_E_SHAPE, "the codebooks stacked as '" + out->name + "' differ " + "in width"); + per = w; + rows += one.shape[0]; + all.insert(all.end(), one.derived.begin(), one.derived.end()); + if (out->pieces.empty()) { + out->pieces = one.pieces; + out->rank = one.rank; + for (uint32_t i = 0; i < one.rank; ++i) out->shape[i] = one.shape[i]; + } + names += (names.empty() ? "'" : ", '") + std::string(pm->src[0]) + "'"; + } + out->shape[0] = rows; + out->derived = std::move(all); + out->scales.assign(1, nullptr); + out->concat_dim = 0; + rad_enc_view(out->rank, out->shape, &out->rows, &out->cols); + out->trivial = false; + out->why = "it is " + std::to_string(maps.size()) + " EMA codebooks stacked (" + names + + "), divided at convert -- a recipe rule stores it"; + return RAD_OK; + } + const RadNameMap& m = *maps.front(); + const bool ema = m.mode == RAD_MAP_EMA; + const SrcTensor* a = ck.find(m.src[0]); + const SrcTensor* u = ema ? ck.find(m.src[1]) : nullptr; + if (!a || (ema && !u)) { + if (optional && !a && !u) return refuse(RAD_E_NOTFOUND, "none of its tensors is there"); + return refuse(RAD_E_NOTFOUND, std::string("it needs checkpoint tensor") + + (ema ? "s '" + std::string(m.src[0]) + "' and '" + + m.src[1] + "'" : " '" + std::string(m.src[0]) + + "'") + + ", not all in " + ck.path()); + } + const size_t rank = a->shape.size(); + if (rank < 2 || rank > RAD_MAX_RANK) + return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) + + "; the map needs a matrix"); + int64_t n = 1; + for (int64_t x : a->shape) n *= x; + std::vector src((size_t)n); + if (piece_f32(*a, 0, n, src.data()) < 0) + return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32"); + out->rank = (uint32_t)rank; + for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i]; + if (ema) { + const int64_t bins = a->shape[0], per = n / bins; + int64_t un = 1; + for (int64_t x : u->shape) un *= x; + if (un != bins) + return refuse(RAD_E_SHAPE, "'" + u->name + "' holds " + std::to_string(un) + + " usage counts for the " + std::to_string(bins) + + " rows of '" + a->name + "'"); + std::vector uf((size_t)bins); + if (piece_f32(*u, 0, bins, uf.data()) < 0) + return refuse(RAD_E_FORMAT, "'" + u->name + "' cannot be read as f32"); + for (int64_t i = 0; i < bins; ++i) { + const float d = std::max(uf[(size_t)i], 1e-5f); + for (int64_t k = 0; k < per; ++k) src[(size_t)(i * per + k)] /= d; + } + out->derived = std::move(src); + out->why = "it is an EMA codebook ('" + a->name + "' over '" + u->name + "'), divided at " + "convert -- a recipe rule stores it"; + } else { + const int64_t ra = a->shape[rank - 2], cb = a->shape[rank - 1], per = ra * cb; + out->shape[rank - 2] = cb; + out->shape[rank - 1] = ra; + out->derived.assign((size_t)n, 0.0f); + for (int64_t s = 0; s < n / per; ++s) + for (int64_t i = 0; i < ra; ++i) + for (int64_t j = 0; j < cb; ++j) + out->derived[(size_t)(s * per + j * ra + i)] = + src[(size_t)(s * per + i * cb + j)]; + out->why = "it is '" + a->name + "' transposed, at convert -- a recipe rule stores it"; + } + out->pieces.assign(1, a); + out->scales.assign(1, nullptr); + out->concat_dim = 0; + rad_enc_view(out->rank, out->shape, &out->rows, &out->cols); + out->trivial = false; + return RAD_OK; +} + int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional, CkptWeight* out, std::string* why) { auto refuse = [&](int rc, std::string m) { @@ -1206,11 +1631,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b for (const auto& nm : prog.name_map) if (nm.declared && name == nm.declared) maps.push_back(&nm); if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it"); - struct Src1 { const char* name; int index; }; + if (maps.front()->mode == RAD_MAP_WNORM) + return resolve_wnorm(ck, *maps.front(), optional, out, why); + if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA) + return resolve_derived(ck, maps, optional, out, why); + struct Src1 { const char* name; int index; int64_t rows; }; std::vector srcs; + const bool row_pieces = maps.front()->mode == RAD_MAP_ROWS; for (const RadNameMap* pm : maps) - for (int k = 0; k < pm->n_src; ++k) srcs.push_back({ pm->src[k], pm->src_index[k] }); - out->concat_dim = maps.front()->concat_dim; + for (int k = 0; k < pm->n_src; ++k) + srcs.push_back({ pm->src[k], pm->src_index[k], row_pieces ? pm->src_rows[k] : 0 }); + out->concat_dim = row_pieces ? 0 : maps.front()->concat_dim; /* The mode decides what several sources mean: * @@ -1243,9 +1674,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b return refuse(ir, iw); } } + /* A row piece (RAD_MAP_ROWS) of a plain tensor; a scale plane has no rows to match. */ + if (st && row_pieces) { + if (sc) + return refuse(RAD_E_UNSUPPORTED, "it takes rows of '" + std::string(s1.name) + + "', which the checkpoint ships block-scaled"); + st = ck.rows(*st, s1.index, s1.rows, name.c_str()); + if (!st) return refuse(RAD_E_SHAPE, "the rows it names are not there"); + } /* A sub-tensor index is always applied (ignoring it would give every expert the whole * stack). Its scale plane is sliced at the same index. */ - if (st && s1.index >= 0) { + else if (st && s1.index >= 0) { st = ck.slice(*st, s1.index, name.c_str()); if (!st) return refuse(RAD_E_SHAPE, "a sub-tensor it names is not there"); if (sc && !(sc = ck.slice(*sc, s1.index, name.c_str()))) @@ -1349,11 +1788,13 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b "rad-convert imports with its scales rounded to bf16 -- serve the " "container it writes"; } - } else if (dt == RAD_FP4E2M1 && scaled && ck.imports() == Checkpoint::Import::Nvfp4) { - /* NVFP4 as import_piece reads it: e2m1 codes beside the f32 quotient e4m3 / global, one - * per 16 of K, each piece with its own global. Not trivial (the scale is derived), so the - * loader refuses it and rad-convert decodes it for a recipe. Joined only along rows: the - * planes and the f32 read follow the pieces row by row. */ + } else if (dt == RAD_FP4E2M1 && scaled && (ck.imports() == Checkpoint::Import::Nvfp4 || + ck.imports() == Checkpoint::Import::ModelOpt)) { + /* NVFP4 as import_piece reads it: e2m1 codes beside the f32 scale the e4m3 one and the + * second level make, one per 16 of K, each piece with its own second level. Not trivial + * (the scale is derived), so the loader refuses it and rad-convert decodes it for a + * recipe. Joined only along rows: the planes and the f32 read follow the pieces row by + * row. */ bool f32 = true; for (const SrcTensor* s : out->scales) f32 = f32 && s->rad_dtype == RAD_F32; if (!f32) { @@ -1386,19 +1827,21 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b } } } else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) { - /* FP8 codes with a scale plane of one dtype, in one of two shapes per piece: - * block [ceil(N/br), ceil(K/bc)], the checkpoint's block (128x128 unless stated): - * `fp8_e4m3*[brxbc]` - * per row [N] or [N, 1] (compressed-tensors' channel strategy, ParoQuant's heads): - * `fp8_e4m3*[1x*]` - * Both are byte for byte when joined along rows, and a block join only where each piece - * but the last fills its last row block. A row join that ends inside a block is still - * read piece by piece, so it keeps its encoding without being trivial. Mixed shapes and - * column joins state no encoding: ckpt_rows_f32 reads scales along rows only, so it + /* FP8 codes with a scale plane of one dtype, in one of three shapes per piece: + * block [ceil(N/br), ceil(K/bc)], the checkpoint's block (128x128 unless stated): + * `fp8_e4m3*[brxbc]` + * per row [N] or [N, 1] (compressed-tensors' channel strategy, ParoQuant's heads): + * `fp8_e4m3*[1x*]` + * per tensor one element (ModelOpt's FP8): read as per row, the scale once a row, so + * pieces with their own scales join; not byte for byte, so imported + * The first two are byte for byte when joined along rows, and a block join only where each + * piece but the last fills its last row block. A row join that ends inside a block is + * still read piece by piece, so it keeps its encoding without being trivial. Mixed shapes + * and column joins state no encoding: ckpt_rows_f32 reads scales along rows only, so it * refuses them with `why`. */ const int64_t br = ck.fp8_block_rows(), bc = ck.fp8_block_cols(); const uint32_t sdt = out->scales[0]->rad_dtype; - int n_row = 0, n_blk = 0; + int n_row = 0, n_blk = 0, n_one = 0; bool bad = false; for (size_t k = 0; k < out->pieces.size() && !bad; ++k) { const SrcTensor& pk = *out->pieces[k]; @@ -1408,13 +1851,18 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b const int64_t want_r = (r + br - 1) / br, want_c = (c + bc - 1) / bc; int64_t sr = 0, scl = 0; rad_enc_view((uint32_t)sk.shape.size(), sk.shape.data(), &sr, &scl); - /* A rank-1 plane is per row; a wider one is a block plane first, then [N, 1]. */ + /* A rank-1 plane is per row; a wider one is a block plane first, then [N, 1]. One + * element for a piece of several rows is the whole tensor's. */ + const bool one = per_tensor_scale(sk, r); const bool row1 = sk.shape.size() == 1 && sk.shape[0] == r; const bool blk = sk.shape.size() >= 2 && sr == want_r && scl == want_c; const bool row2 = sk.shape.size() >= 2 && sr == r && scl == 1; if (sk.rad_dtype != sdt) { bad = true; out->why = "its FP8 pieces' scale planes differ in dtype"; + } else if (one) { + ++n_row; + ++n_one; } else if (row1) { ++n_row; } else if (blk) { @@ -1442,7 +1890,15 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b out->why = "its FP8 pieces are joined along a column, across their scale planes"; } if (!bad) { - out->trivial = out->why.empty(); + out->trivial = out->why.empty() && n_one == 0; + /* A per-tensor scale is written once a row (ckpt_plane_rows). */ + if (n_one) { + out->imported = true; + if (out->why.empty()) + out->why = "it is FP8 with one scale per tensor, which no kernel reads as it " + "is; a recipe's import rule (block=128x128 scale=bf16) or a " + "quantiser stores it"; + } rad_enc_clear(&out->enc); rad_enc_copy_str(out->enc.scheme, "affine"); rad_enc_add_plane(&out->enc, "codes", dt, 1, 1); @@ -1450,14 +1906,16 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b else rad_enc_add_plane(&out->enc, "scale", sdt, br, bc); } } else if (p0.ct_group) { - /* CT-INT4: one group throughout, joined only along rows, as GPTQ. Codes become signed i4 - * (the offset removed at relayout) and the scale plane is as shipped, one per group of K. */ + /* CT-INT4: one group throughout, joined only along rows, as GPTQ. A symmetric weight's + * codes become signed i4 (the offset removed at relayout); an asymmetric one keeps its u4 + * codes and has a u4 zero plane, one per group of K. The scale plane is as shipped. */ out->imported = true; for (size_t k = 1; k < out->pieces.size() && out->imported; ++k) if (out->pieces[k]->ct_group != p0.ct_group || - out->scales[k]->rad_dtype != out->scales[0]->rad_dtype) { + out->scales[k]->rad_dtype != out->scales[0]->rad_dtype || + !out->pieces[k]->ct_zero != !p0.ct_zero) { out->imported = false; - out->why = "its CT-INT4 pieces differ in group or scale dtype"; + out->why = "its CT-INT4 pieces differ in group, scale dtype or zero point"; } if (out->imported && d != 0 && out->pieces.size() > 1) { out->imported = false; @@ -1466,8 +1924,9 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b if (out->imported) { rad_enc_clear(&out->enc); rad_enc_copy_str(out->enc.scheme, "affine"); - rad_enc_add_plane(&out->enc, "codes", RAD_I4, 1, 1); + rad_enc_add_plane(&out->enc, "codes", p0.ct_zero ? RAD_U4 : RAD_I4, 1, 1); rad_enc_add_plane(&out->enc, "scale", out->scales[0]->rad_dtype, 1, p0.ct_group); + if (p0.ct_zero) rad_enc_add_plane(&out->enc, "zero", RAD_U4, 1, p0.ct_group); out->why = "it is CT-INT4, which rad-convert imports -- serve the container it writes"; } } else if (!unscaled) { @@ -1578,17 +2037,34 @@ struct Joined { } }; +/* An unsigned integer code dtype (u1 .. u12, u8, u16). */ +bool unsigned_int_dt(uint32_t dt) { + int sgn = 0; + return dt == RAD_U8 || dt == RAD_U16 || (rad_dtype_packed_int(dt, &sgn) > 0 && !sgn); +} + +/* The stored zero point (the signed one plus 8) of row `n`, group `g` of an asymmetric CT-INT4 + * piece: nibble n % 8 of word [n / 8, g]. */ +int ct_zero_at(const SrcTensor& t, int64_t n, int64_t g) { + const SrcTensor& z = *t.ct_zero; + uint32_t w; + std::memcpy(&w, (const uint8_t*)z.data + ((n / 8) * z.shape[1] + g) * 4, 4); + return (int)((w >> ((n % 8) * 4)) & 0xFu); +} + /* `n` elements of a stored-dtype piece from element `e`, as f32. */ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) { if (t.ct_group) { - /* Element (row, k) of the logical [N, K] matrix is nibble k % 8 of word [row, k / 8], - * less 8. */ + /* Element (row, k) of the logical [N, K] matrix is nibble k % 8 of word [row, k / 8]: less + * 8 for a symmetric weight (the signed code), as stored for an asymmetric one (the zero + * point is subtracted with the scale, ckpt_rows_f32). */ const int64_t K = t.shape[1]; + const int off = t.ct_zero ? 0 : 8; for (int64_t i = 0; i < n; ++i) { const int64_t row = (e + i) / K, k = (e + i) % K; uint32_t w; std::memcpy(&w, (const uint8_t*)t.data + (row * (K / 8) + k / 8) * 4, 4); - out[i] = (float)((int)((w >> ((k % 8) * 4)) & 0xFu) - 8); + out[i] = (float)((int)((w >> ((k % 8) * 4)) & 0xFu) - off); } return RAD_OK; } @@ -1651,6 +2127,22 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: if (w.paro) return refuse(RAD_E_UNSUPPORTED, "'" + w.name + "' is a ParoQuant weight, stored rotated; " "it is kept as it is and has no f32 view here"); + if (!w.derived.empty()) { + std::memcpy(out, w.derived.data() + r0 * w.cols, (size_t)(nr * w.cols) * sizeof(float)); + return RAD_OK; + } + if (w.wnorm) { + const SrcTensor& v = *w.pieces[0]; + if (piece_f32(v, r0 * w.cols, nr * w.cols, out) < 0) + return refuse(RAD_E_FORMAT, "'" + v.name + "' cannot be read as f32"); + /* View rows per dim-0 slice: the dims between the first and the last. */ + const int64_t rps = w.rows / (int64_t)w.wnorm_scale.size(); + for (int64_t r = 0; r < nr; ++r) { + const float f = w.wnorm_scale[(size_t)((r0 + r) / rps)]; + for (int64_t c = 0; c < w.cols; ++c) out[r * w.cols + c] *= f; + } + return RAD_OK; + } Joined j; j.init(w.pieces, w.concat_dim); /* Runs arrive in order, so the cursor is the count already written. */ @@ -1669,8 +2161,10 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: : std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) + ")"); /* An imported code times its group's shipped scale: GPTQ's scales are [groups, N] (row r's are - * a column), CT-INT4's are [N, groups] (a row). An NVFP4 import has neither group and takes - * the scale-plane form below. */ + * a column), CT-INT4's are [N, groups] (a row), and an asymmetric CT-INT4 code has its + * group's zero point subtracted first, (q - zero) * scale. Both factors are small integers + * times one float, so the f32 value is exact. An NVFP4 import has neither group and takes the + * scale-plane form below. */ if (w.imported && (w.pieces[0]->gptq_group || w.pieces[0]->ct_group)) { int64_t base = 0; for (size_t k = 0; k < w.pieces.size(); ++k) { @@ -1678,11 +2172,14 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: const SrcTensor& sk = *w.scales[k]; const int64_t pr = pk.shape[0]; for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r) - for (int64_t c = 0; c < w.cols; ++c) - out[(r - r0) * w.cols + c] *= rad_load_f32( + for (int64_t c = 0; c < w.cols; ++c) { + float& v = out[(r - r0) * w.cols + c]; + if (pk.ct_zero) v -= (float)ct_zero_at(pk, r - base, c / pk.ct_group); + v *= rad_load_f32( sk.data, sk.rad_dtype, pk.ct_group ? (r - base) * (w.cols / pk.ct_group) + c / pk.ct_group : (c / pk.gptq_group) * pr + (r - base)); + } base += pr; } return RAD_OK; @@ -1708,16 +2205,172 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: rad_enc_view((uint32_t)pk.shape.size(), pk.shape.data(), &pr, &pc); const int64_t br = br0 > 0 ? br0 : pr, bc = bc0 > 0 ? bc0 : pc; const int64_t sc = (pc + bc - 1) / bc; + /* A piece's single scale (FP8 per tensor) covers every one of its rows. */ + const bool one = per_tensor_scale(sk, pr); for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r) for (int64_t c = 0; c < w.cols; ++c) out[(r - r0) * w.cols + c] *= - rad_load_f32(sk.data, sk.rad_dtype, ((r - base) / br) * sc + c / bc); + rad_load_f32(sk.data, sk.rad_dtype, + one ? 0 : ((r - base) / br) * sc + c / bc); base += pr; } } return RAD_OK; } +int ckpt_import_form_parse(const std::vector>& options, + ImportForm* f, std::string* why) { + auto refuse = [&](std::string m) { + if (why) *why = std::move(m); + return (int)RAD_E_INVAL; + }; + for (const auto& [k, v] : options) { + uint32_t* dt = k == "codes" ? &f->codes : k == "zero" ? &f->zero + : k == "scale" ? &f->scale : nullptr; + if (dt) { + *dt = rad_dtype_parse(v.c_str()); + if (*dt == RAD_DT_INVALID) return refuse("import's " + k + "=" + v + " is not a dtype"); + } else if (k == "block") { + long long a = 0, b = 0; + char x = 0, tail = 0; + if (std::sscanf(v.c_str(), "%lld%c%lld%c", &a, &x, &b, &tail) != 3 || x != 'x' || + a < 1 || b < 1) + return refuse("import's block=" + v + " is not ROWSxCOLS"); + f->block[0] = a; + f->block[1] = b; + } else { + return refuse("the import rule takes codes=, zero=, scale= and block=, not " + k); + } + } + return RAD_OK; +} + +int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) { + auto refuse = [&](int rc, std::string m) { + if (why) *why = std::move(m); + return rc; + }; + char en[160]; + rad_enc_format(&w->enc, en, sizeof en); + if (w->pieces.empty() || w->paro || w->wnorm || !w->derived.empty()) + return refuse(RAD_E_FORMAT, "'" + w->name + "' is " + en + ", which the import rule does " + "not re-express"); + if (rad_enc_is(&w->enc, "plain")) + return refuse(RAD_E_UNSUPPORTED, "'" + w->name + "' ships as plain " + en + + ", with nothing quantised to re-express"); + const SrcTensor& p0 = *w->pieces[0]; + const RadEncPlane* sp = rad_enc_plane(&w->enc, "scale"); + auto float_dt = [](uint32_t d) { return d == RAD_F16 || d == RAD_BF16 || d == RAD_F32; }; + if (f.scale != RAD_DT_INVALID && !float_dt(f.scale)) + return refuse(RAD_E_INVAL, std::string("the import rule's scale=") + + rad_dtype_name(f.scale) + " is not f16, bf16 or f32"); + const uint32_t sdt = f.scale != RAD_DT_INVALID ? f.scale + : sp ? sp->dtype : (uint32_t)RAD_DT_INVALID; + + /* Every shipped scale once, as f32, with whether `sdt` holds it. */ + auto count = [&](const SrcTensor& s) { + const int64_t n = s.shape.empty() ? 1 : s.numel(); + for (int64_t i = 0; i < n; ++i) { + const float v = rad_load_f32(s.data, s.rad_dtype, i); + uint8_t b[4]; + rad_store_f32(b, sdt, 0, v); + const float r = rad_load_f32(b, sdt, 0); + if (r != v) { + ++w->rounded; + if (v != 0.0f) w->max_rel = std::max(w->max_rel, (double)std::fabs((r - v) / v)); + } + } + }; + w->rounded = 0; + w->max_rel = 0; + RadEncoding e{}; + rad_enc_copy_str(e.scheme, "affine"); + + if (w->imported && (p0.gptq_group || p0.ct_group)) { + /* An integer grid: GPTQ's or CT-INT4's codes, a scale per group and, when asymmetric, a + * zero point. */ + const int bits = p0.ct_group ? 4 : p0.gptq_bits; + const bool asym = p0.ct_zero != nullptr; + if (f.block[0] || f.block[1]) + return refuse(RAD_E_INVAL, "'" + w->name + "' is an integer grid (" + en + "); the " + "import rule's block= re-grids an FP8 scale, not a group"); + int sgn = 0; + const bool unsign = asym || f.codes != RAD_DT_INVALID; + if (f.codes != RAD_DT_INVALID && + (rad_dtype_packed_int(f.codes, &sgn) != bits || sgn) && !(bits == 8 && f.codes == RAD_U8)) + return refuse(RAD_E_INVAL, std::string("the import rule's codes=") + + rad_dtype_name(f.codes) + " is not the unsigned " + + std::to_string(bits) + "-bit dtype of '" + w->name + "' (" + + en + ")"); + if (!unsign && f.zero != RAD_DT_INVALID) + return refuse(RAD_E_INVAL, "'" + w->name + "' is a symmetric grid (" + en + ") and has " + "no zero point for zero= to store; codes=u" + + std::to_string(bits) + " makes one"); + const uint32_t zdt = f.zero != RAD_DT_INVALID ? f.zero + : asym ? (uint32_t)RAD_U4 : (uint32_t)RAD_DT_INVALID; + if (unsign && zdt == RAD_DT_INVALID) + return refuse(RAD_E_INVAL, "the import rule's codes=" + std::string(rad_dtype_name(f.codes)) + + " makes '" + w->name + "' unsigned and needs zero= for the " + "zero point " + std::to_string(1 << (bits - 1))); + if (unsign && !(unsigned_int_dt(zdt) && rad_dtype_bits(zdt) >= bits)) + return refuse(RAD_E_INVAL, std::string("the import rule's zero=") + rad_dtype_name(zdt) + + " does not hold the " + std::to_string(bits) + + "-bit zero points of '" + w->name + "'"); + const int64_t gs = sp->block[1]; + const uint32_t cdt = unsign ? (uint32_t)(bits == 4 ? RAD_U4 : RAD_U8) : w->enc.plane[0].dtype; + rad_enc_add_plane(&e, "codes", cdt, 1, 1); + rad_enc_add_plane(&e, "scale", sdt, 1, gs); + if (unsign) rad_enc_add_plane(&e, "zero", zdt, 1, gs); + for (const SrcTensor* s : w->scales) count(*s); + } else if ((w->enc.plane[0].dtype == RAD_F8E4M3 || w->enc.plane[0].dtype == RAD_F8E5M2) && + sp && sp->block[0] == 1 && sp->block[1] == 0) { + /* FP8 with a scale per row or per tensor. */ + if (f.codes != RAD_DT_INVALID || f.zero != RAD_DT_INVALID) + return refuse(RAD_E_INVAL, "'" + w->name + "' is FP8 (" + en + "), with no integer " + "codes or zero point for codes= or zero="); + const int64_t br = f.block[0] ? f.block[0] : 1, bc = f.block[1]; + if (br < 1 || bc < 0) + return refuse(RAD_E_INVAL, "the import rule's block= is not rows x columns"); + /* Each block's rows must share one scale: a per-tensor piece's rows all do, and a block + * may not straddle two pieces; per-row scales must agree within a block. */ + int64_t base = 0; + for (size_t p = 0; p < w->pieces.size(); ++p) { + const SrcTensor& s = *w->scales[p]; + const int64_t pr = w->pieces[p]->shape[0]; + const bool one = per_tensor_scale(s, pr); + if (br > 1 && (base % br || (p + 1 < w->pieces.size() && (base + pr) % br))) + return refuse(RAD_E_SHAPE, "'" + w->pieces[p]->name + "' starts or ends inside a " + + std::to_string(br) + "-row block of '" + w->name + "'"); + if (!one) + for (int64_t r = 0; r < pr; ++r) + if (rad_load_f32(s.data, s.rad_dtype, r) != + rad_load_f32(s.data, s.rad_dtype, r - r % br)) + return refuse(RAD_E_FORMAT, "'" + s.name + "' gives rows " + + std::to_string(r - r % br) + " and " + + std::to_string(r) + " of one " + + std::to_string(br) + "-row block different " + "scales, which one block scale cannot hold"); + count(s); + base += pr; + } + rad_enc_add_plane(&e, "codes", w->enc.plane[0].dtype, 1, 1); + rad_enc_add_plane(&e, "scale", sdt, br, bc); + } else { + return refuse(RAD_E_FORMAT, "'" + w->name + "' is " + en + "; the import rule re-expresses " + "an integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale " + "per row or per tensor"); + } + if (!rad_enc_valid(&e)) + return refuse(RAD_E_FORMAT, "the import rule's form of '" + w->name + "' is malformed"); + w->enc = e; + w->form = f; + w->reform = true; + w->imported = true; + w->trivial = false; + w->why = "it is re-expressed by an import rule"; + return RAD_OK; +} + int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst, std::string* why) { auto refuse = [&](int rc, std::string m) { @@ -1842,50 +2495,54 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds return RAD_OK; } if (w.imported && !w.paro && (w.pieces[0]->gptq_group || w.pieces[0]->ct_group)) { - /* GPTQ-packed, re-laid: a row of codes is a column of the qweight, its words' bytes in order - * (int4: two codes per byte, low nibble first), made signed by flipping each field's top - * bit; a row of scales is a column of the scale tensor, one per 128 of K, rounded to - * bf16. */ + /* GPTQ-packed and CT-INT4, re-laid row by row. Both store each code plus 2^(bits-1) + * (GPTQ's symmetric zero point, CT's packing offset), so a signed code is the stored field + * with its top bit flipped and an unsigned one (CT's asymmetric codes, or an `import` + * rule's codes=uN) is the field as stored. + * codes GPTQ: a column of the qweight, its words' bytes in order (int4: two codes a + * byte, low nibble first); CT: a row of the packed words, already in that order + * scale GPTQ: a column of the scale tensor, one per 128 of K; CT: a row of the scale + * tensor, one per group. Stored in the plane's dtype, rounded to nearest (bf16 + * by default for GPTQ, as shipped for CT) + * zero CT's asymmetric zero point as stored, or 2^(bits-1) for a symmetric grid an + * `import` rule made unsigned */ + const std::string role = w.enc.plane[k].role; + const bool unsign = unsigned_int_dt(w.enc.plane[0].dtype); int64_t base = 0; for (size_t p = 0; p < w.pieces.size(); ++p) { const SrcTensor& c = *w.pieces[p]; const SrcTensor& s = *w.scales[p]; const int64_t N = c.shape[0], K = c.shape[1]; - if (c.ct_group) { - /* CT-INT4, re-laid: a row of codes is a row of the packed words (already two per - * byte, low nibble first), made signed by flipping each top bit; a row of scales is - * a row of the scale tensor, as shipped. */ - for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) { - const int64_t n = r - base; - if (k == 0) { - const uint8_t* q = (const uint8_t*)c.data + n * (K / 2); - for (int64_t i = 0; i < K / 2; ++i) *o++ = q[i] ^ 0x88; - } else { - const int64_t g = K / c.ct_group, sb = rad_dtype_bits(s.rad_dtype) / 8; - std::memcpy(o, (const uint8_t*)s.data + n * g * sb, (size_t)(g * sb)); - o += g * sb; - } - } - base += N; - continue; - } - const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80; + const int bits = c.ct_group ? 4 : c.gptq_bits; + const uint8_t flip = unsign ? 0 : bits == 4 ? 0x88 : 0x80; + /* Scales a row: one per CT group, or one per 128 of K for GPTQ. */ + const int64_t gs = c.ct_group ? c.ct_group : 128, G = K / gs; for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) { const int64_t n = r - base; - if (k == 0) { + if (role == "codes" && c.ct_group) { + const uint8_t* q = (const uint8_t*)c.data + n * (K / 2); + for (int64_t i = 0; i < K / 2; ++i) *o++ = q[i] ^ flip; + } else if (role == "codes") { const uint8_t* q = (const uint8_t*)c.data; for (int64_t wi = 0; wi < K * c.gptq_bits / 32; ++wi) { uint32_t v; std::memcpy(&v, q + (wi * N + n) * 4, 4); for (int b = 0; b < 4; ++b) *o++ = (uint8_t)(v >> (8 * b)) ^ flip; } + } else if (role == "scale") { + for (int64_t g = 0; g < G; ++g) + rad_store_f32(o, dt, g, rad_load_f32(s.data, s.rad_dtype, + c.ct_group ? n * G + g + : ((g * 128) / c.gptq_group) * N + n)); + o += G * eb; + } else if (role == "zero") { + const int64_t zb = rad_enc_row_bytes(dt, G); + std::memset(o, 0, (size_t)zb); + for (int64_t g = 0; g < G; ++g) + rad_store_code(o, dt, g, c.ct_zero ? ct_zero_at(c, n, g) : 1 << (bits - 1)); + o += zb; } else { - for (int64_t g = 0; g < K / 128; ++g) { - const uint16_t h = rad_f32_to_bf16( - rad_load_f32(s.data, s.rad_dtype, ((g * 128) / c.gptq_group) * N + n)); - std::memcpy(o, &h, 2); - o += 2; - } + return refuse(RAD_E_STATE, "plane '" + role + "' is not one of an integer grid"); } } base += N; @@ -1905,6 +2562,29 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds return (int)RAD_OK; }); } + /* An FP8 scale shipped once per row or per tensor and written per row (a per-tensor piece's + * scale repeated), or over the block grid an `import` rule asks for, rounded to the plane's + * dtype. ckpt_import_form checked that every block's rows share their scale. */ + bool any_one = false; + for (size_t p = 0; p < src.size() && k > 0; ++p) + any_one = any_one || per_tensor_scale(*src[p], w.pieces[p]->shape[0]); + if (w.imported && k > 0 && + (dt != src[0]->rad_dtype || w.enc.plane[k].block[0] != 1 || any_one)) { + const int64_t br = w.enc.plane[k].block[0] > 0 ? w.enc.plane[k].block[0] : w.rows; + for (int64_t i = r0; i < r0 + nr; ++i) { + /* Logical row i * br's piece, and its scale. */ + int64_t r = i * br, base = 0; + size_t p = 0; + while (p + 1 < w.pieces.size() && r >= base + w.pieces[p]->shape[0]) + base += w.pieces[p++]->shape[0]; + const SrcTensor& s = *src[p]; + const bool one = per_tensor_scale(s, w.pieces[p]->shape[0]); + const float v = rad_load_f32(s.data, s.rad_dtype, one ? 0 : r - base); + for (int64_t j = 0; j < pc; ++j) rad_store_f32(o, dt, j, v); + o += pc * eb; + } + return RAD_OK; + } /* A scale plane: the pieces' scale rows in sequence. */ int64_t base = 0; for (const SrcTensor* s : src) { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 029b52c5..72e20805 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -17,8 +17,8 @@ * convert time. * * An imported quantisation's descriptor (`auto-round`, `gptq`, `quark`, `compressed-tensors`, - * `paroquant`) names the tool, not a served form, so no plugin claims it; Checkpoint::imports() - * describes how the plugin is chosen. + * `paroquant`, `modelopt`) names the tool, not a served form, so no plugin claims it; + * Checkpoint::imports() describes how the plugin is chosen. */ #pragma once #include "../rad_internal.h" @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace rad { @@ -54,12 +55,16 @@ struct SrcTensor { * scale row covers. 0 for other tensors. */ int32_t gptq_bits = 0; int64_t gptq_group = 0; - /* CT-INT4 (compressed-tensors' symmetric pack-quantized int4): `data` is X.weight_packed's - * int32 words [N, K / 8], eight codes per word along K from the low bits up, unsigned with zero - * point 8. The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4; - * `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for other - * tensors. */ + /* CT-INT4 (compressed-tensors' pack-quantized int4): `data` is X.weight_packed's int32 words + * [N, K / 8], eight codes per word along K from the low bits up, each the signed code plus 8. + * The tensor described is the logical [N, K] code matrix, `rad_dtype` RAD_I4 (symmetric) or + * RAD_U4 (asymmetric, the stored nibbles); `ct_group` is the K columns one scale of + * X.weight_scale [N, K / group] covers. 0 for other tensors. */ int64_t ct_group = 0; + /* An asymmetric CT-INT4 weight's X.weight_zero_point: int32 [ceil(N / 8), G], eight zero + * points per word along N from the low bits up, each the signed zero point plus 8 + * (compressed-tensors packs it along dim 0). Null for a symmetric weight. */ + const SrcTensor* ct_zero = nullptr; /* ParoQuant's int5-bitplane (Import::ParoI5): `data` is the AWQ-packed low nibbles qweight * [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit * plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32]. @@ -131,6 +136,9 @@ public: /* Sub-tensor `index` along dim 0 of a stacked (rank >= 2) tensor, as a view owned here and * valid for the checkpoint's life. Null, with the reason logged, if there is no such slice. */ const SrcTensor* slice(const SrcTensor& st, int index, const char* declared); + /* Rows [r0, r0 + n) along dim 0 of a plainly stored tensor, as a view owned here (a + * RAD_MAP_ROWS piece). Null, with the reason logged, when the rows are not there. */ + const SrcTensor* rows(const SrcTensor& st, int64_t r0, int64_t n, const char* declared); /* FP8's block, from quantization_config.weight_block_size; 128x128 when it says nothing. */ int64_t fp8_block_rows() const { return fp8_br_; } @@ -141,21 +149,24 @@ public: * (zero point stored less one). QuarkMx: Quark's MXFP4 (fp4 weights, per_group 32, e8m0 * scales, no per-layer overrides). ParoMx: ParoQuant's `paroquant_mxfp4` (Quark's codes and * exponents in a rotated basis, rotations beside them). CtInt4, Nvfp4, CtFp8: - * compressed-tensors' pack-quantized int4, a release with an nvfp4-pack-quantized group, and - * one whose groups are all float-quantized FP8 (detect_import). In an Nvfp4 or CtFp8 release - * every weight without the NVFP4 tensors reads stock, so FP8 and bf16 linears beside the - * NVFP4 ones read by their own form. An unreadable form of these stays None, with the reason - * in import_refusal(). The quantization_config keys are then renamed - * `imported_quantization_config.*`, since they describe the tool, not a served format. */ - enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8 }; + * compressed-tensors' pack-quantized int4 (symmetric, or asymmetric with a zero point), a + * release with an nvfp4-pack-quantized group, and one whose groups are all float-quantized FP8 + * (detect_import). ModelOpt: NVIDIA ModelOpt's NVFP4, FP8, or both per layer + * (MIXED_PRECISION). In an Nvfp4, CtFp8 or ModelOpt release every weight without the NVFP4 + * tensors reads stock, so FP8 and bf16 linears beside the NVFP4 ones read by their own form. + * An unreadable form of these stays None, with the reason in import_refusal(). The + * quantization_config keys are then renamed `imported_quantization_config.*`, since they + * describe the tool, not a served format. */ + enum class Import { None, Gptq, QuarkMx, CtInt4, ParoMx, ParoI5, ParoI4, Nvfp4, CtFp8, + ModelOpt }; Import imports() const { return import_; } const std::string& import_refusal() const { return import_why_; } /* The pieces an imported `name` (a `.weight`) is read from, as views owned here: GPTQ-packed * codes and their scales, Quark's codes and exponents as RAD dtypes, or NVFP4's codes as fp4 - * beside an f32 scale plane derived from the e4m3 scales and the global scale. RAD_E_NOTFOUND - * when `name` is an ordinary tensor or absent; another error, with `why`, for an unreadable - * imported form. */ + * beside an f32 scale plane derived from the e4m3 scales and the second level (a divisor in + * compressed-tensors, a multiplier in ModelOpt). RAD_E_NOTFOUND when `name` is an ordinary + * tensor or absent; another error, with `why`, for an unreadable imported form. */ int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale, std::string* why); @@ -166,6 +177,7 @@ private: const std::unordered_map* owner = nullptr); int open_safetensors(const std::string& path); int open_diffusers(); + int add_companions(); int open_gguf(const std::string& path); void detect_import(); @@ -185,11 +197,27 @@ private: Import import_ = Import::None; std::string import_why_; int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */ + bool ct_asym_ = false; /* CtInt4: the config states asymmetric weights */ /* import_piece's answers by name, so a weight resolved twice reuses its views. */ std::unordered_map> imported_; }; /* ================================================================== logical weights */ +/* Another spelling of the numbers a weight ships, asked for by a recipe's `import` rule + * (ckpt_import_form). Each field left at its default keeps that part as the import writes it. + * + * codes an unsigned dtype of the shipped codes' width: a symmetric grid's signed codes c are + * written c + 2^(bits-1) under a zero point of 2^(bits-1), so (u - z) * s == c * s; + * zero the zero plane's dtype (a shipped or re-expressed zero point), which must hold it; + * scale the scale plane's dtype, each shipped scale rounded to nearest (counted when that + * changes it); + * block a scale shipped once per row or per tensor (FP8) repeated over this block grid, + * which every block's rows must share. */ +struct ImportForm { + uint32_t codes = RAD_DT_INVALID, zero = RAD_DT_INVALID, scale = RAD_DT_INVALID; + int64_t block[2] = { 0, 0 }; +}; + /* A declared weight's source, as the name map resolves it: pieces joined along `concat_dim`, and * for block-scaled FP8 each piece's scale plane beside it. */ struct CkptWeight { @@ -216,6 +244,22 @@ struct CkptWeight { * piece (a row part: gate and up, or q, k and v, each rotated separately). */ bool paro = false; std::vector pq_pairs, pq_theta, pq_scale; + /* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every + * element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial + * (the values change), so a recipe rule stores it. */ + bool wnorm = false; + std::vector wnorm_scale; + /* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32 + * values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule + * stores it. */ + std::vector derived; + /* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the + * shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative + * change, both found by ckpt_import_form. */ + bool reform = false; + ImportForm form{}; + int64_t rounded = 0; + double max_rel = 0; RadEncoding enc{}; std::string why; }; @@ -226,6 +270,24 @@ struct CkptWeight { int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional, CkptWeight* out, std::string* why); +/* The quantiser name of a recipe rule rad-convert handles itself through ckpt_import_form. */ +constexpr const char* kImportRule = "import"; + +/* An import rule's options (codes=DTYPE, zero=DTYPE, scale=DTYPE, block=RxC) as an ImportForm. + * RAD_E_INVAL, with the option named in `why`, for an option it does not take or a value it + * cannot read. */ +int ckpt_import_form_parse(const std::vector>& options, + ImportForm* f, std::string* why); + +/* Re-express a resolved `w` as `f` asks (a recipe's `import` rule): RAD_OK with `w->enc` the new + * encoding and the form recorded for ckpt_plane_rows. RAD_E_UNSUPPORTED, with `why`, when `w` is + * a plain float weight with nothing shipped to re-express (the rule declines it); any other error, + * with `why`, when its shipped form cannot take `f`: a form other than an integer grid (GPTQ, + * CT-INT4) or an FP8 weight with one scale per row or per tensor, a code or zero dtype that does + * not hold the shipped values, or a block whose rows carry different scales. Rounding a scale to + * `f.scale` is allowed and counted in `w->rounded`. */ +int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why); + /* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a * stacked tensor carries, so an expert reads the stack it was cut from. */ std::string ckpt_tensor_of(const SrcTensor& t); diff --git a/core/format/share.cpp b/core/format/share.cpp index 48851a7f..f038ba09 100644 --- a/core/format/share.cpp +++ b/core/format/share.cpp @@ -55,7 +55,42 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con "RAD_SHARD_NONE", w.decl.shard == RAD_SHARD_ROW ? "ROW" : "COL", rank)); const bool cols = w.decl.shard == RAD_SHARD_COL || rank == 1; - if (cols) { + const int np1 = rank == 1 && w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1; + if (cols && np1 > 1) { + /* A rank-1 weight of stacked parts (a fused projection's bias, [value | gate]) is cut + * as the matrix it goes with: this rank's slice of each part, never a contiguous + * slice of the stack. Per-part spans and declared parts read as the row cut's do. */ + if (w.n_part_spans > 0) { + if (w.n_part_spans != np1) + return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np1)); + int64_t sum = 0, soff = 0; + for (int g = 0; g < np1; ++g) sum += w.part_total[g]; + if (sum != VC) + return refuse(fmt("the %d stacked parts' stated elements sum to %lld and the " + "entry has %lld", np1, (long long)sum, (long long)VC)); + for (int g = 0; g < np1; ++g) { + view.push_back({ 0, VR, soff + w.part_lo[g], soff + w.part_hi[g] }); + soff += w.part_total[g]; + } + } else { + if (span) + return refuse("a single span over a rank-1 weight of stacked parts is not " + "defined; state one span a part"); + if (VC % world) return refuse(fmt("%lld elements do not divide by %d ranks", + (long long)VC, world)); + int64_t sum = 0, soff = 0; + for (int g = 0; g < np1; ++g) sum += w.decl.row_parts[g]; + if (sum != VC / world) + return refuse(fmt("%d declared parts sum to %lld, and the rank's share of %lld " + "elements at %d ranks is %lld", np1, (long long)sum, + (long long)VC, world, (long long)(VC / world))); + for (int g = 0; g < np1; ++g) { + const int64_t take = w.decl.row_parts[g]; + view.push_back({ 0, VR, soff + index * take, soff + (index + 1) * take }); + soff += take * world; + } + } + } else if (cols) { int64_t c0 = w.shard_lo, c1 = w.shard_hi; if (!span) { if (VC % world) return refuse(fmt("%lld columns do not divide by %d ranks", @@ -162,7 +197,11 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con s.rows += pq.rows; s.cols = pq.cols; } - if (s.rows != w.sel_rows[k] || s.cols != w.sel_cols[k]) + /* A vector's stacked parts come out as one piece a part, each a row of the share; laid + * end to end they are the declared vector, so only the element count has to agree. */ + const bool fits = rank == 1 ? s.rows * s.cols == w.sel_rows[k] * w.sel_cols[k] + : s.rows == w.sel_rows[k] && s.cols == w.sel_cols[k]; + if (!fits) return refuse(fmt("this rank's share of the '%s' plane is [%lld, %lld] and the " "declaration says [%lld, %lld]", p.role, (long long)s.rows, (long long)s.cols, (long long)w.sel_rows[k], diff --git a/core/gen/audio.h b/core/gen/audio.h new file mode 100644 index 00000000..b879a537 --- /dev/null +++ b/core/gen/audio.h @@ -0,0 +1,76 @@ +/* audio.h -- audio generation: the request and the channel its audio comes back on. + * + * An audio generator (abi/rad_builder.h, rad_declare_audio_generator) makes a piece in two stages, + * a language model writing it frame by frame and a denoiser turning runs of frames (windows) into + * audio, which a vocoder plays. core/gen/audio_driver.h turns a request into those passes; this is + * what a caller hands it and what it hands back: a window's samples as each is vocoded, then the + * end. + */ +#pragma once +#include "rad_core.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace gen { + +/* One window's playable samples, interleaved, in [-1, 1]. */ +struct AudioChunk { + int32_t window = 0; + std::vector samples; +}; + +/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */ +class AudioTicket { +public: + /* driver side */ + void push(AudioChunk&& c); + void finish(int status, const std::string& why = std::string()); + + /* caller side: the next chunk, or false once the request has ended and every chunk was + * taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */ + bool next(AudioChunk* out, int ms, bool* timed_out); + bool finished() const; + int status() const; + std::string why() const; + + std::atomic cancel{false}; + + /* Usage for the response, written by the driver before finish(): prompt tokens, frames made, + * windows played and per-phase times. */ + int64_t in_tokens = 0, frames = 0, windows = 0; + int64_t t_submit_ns = 0, t_prompt_ns = 0, t_frames_ns = 0, t_first_audio_ns = 0, + t_done_ns = 0; + /* Why the piece ended: the model ended it, or it reached the request's length. */ + bool model_ended = false; + +private: + mutable std::mutex mu_; + std::condition_variable cv_; + std::deque q_; + bool done_ = false; + int status_ = RAD_OK; + std::string why_; +}; + +struct AudioRequest { + /* The conditional prompt, and the unconditional one when the declaration renders it from a + * template of its own (RadAudioGenDecl::neg_tmpl); otherwise it is derived from the + * conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */ + std::vector tokens; + std::vector neg_tokens; + int64_t max_frames = 0; /* the most frames to make, >= 1 */ + int32_t steps = 0; /* 0: the model's default */ + float cfg = 0.0f; /* 0: the model's default */ + uint64_t seed = 0; + std::shared_ptr ticket; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp new file mode 100644 index 00000000..c40df146 --- /dev/null +++ b/core/gen/audio_driver.cpp @@ -0,0 +1,910 @@ +/* audio_driver.cpp -- the audio generator's pass driver (audio_driver.h), and the ticket a caller + * waits on (audio.h). */ +#include "audio_driver.h" +#include "sched/mem_iface.h" + +#include +#include +#include + +namespace rad { +namespace gen { + +/* ================================================================== the ticket */ +void AudioTicket::push(AudioChunk&& c) { + { + std::lock_guard lk(mu_); + q_.push_back(std::move(c)); + } + cv_.notify_all(); +} + +void AudioTicket::finish(int status, const std::string& why) { + { + std::lock_guard lk(mu_); + if (done_) return; + done_ = true; + status_ = status; + why_ = why; + } + cv_.notify_all(); +} + +bool AudioTicket::next(AudioChunk* out, int ms, bool* timed_out) { + std::unique_lock lk(mu_); + if (timed_out) *timed_out = false; + if (q_.empty() && !done_) + cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; }); + if (!q_.empty()) { + *out = std::move(q_.front()); + q_.pop_front(); + return true; + } + if (!done_ && timed_out) *timed_out = true; + return false; +} + +bool AudioTicket::finished() const { + std::lock_guard lk(mu_); + return done_ && q_.empty(); +} + +int AudioTicket::status() const { + std::lock_guard lk(mu_); + return status_; +} + +std::string AudioTicket::why() const { + std::lock_guard lk(mu_); + return why_; +} + +/* ================================================================== sizing */ +namespace { + +constexpr int64_t kAlign = 256; + +int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } + +struct Sizes { + int64_t T = 0, S = 0, L = 0, NB = 0; +}; + +Sizes sizes_of(const Program& prog, int64_t block_size) { + const RadAudioGenDecl& d = prog.audio_gen; + Sizes z; + z.T = prog.ctx.max_tok; + z.S = prog.ctx.max_seqs; + z.L = d.max_lanes; + z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0; + return z; +} + +/* Region offsets and sizes, in order, and the total; shared by the allocation and the VRAM budget. + * The order is the enum's in audio_driver.h. */ +int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { + const int64_t I = 4; + const int64_t SL = std::max(z.S, z.L); + const int64_t want[] = { + z.T * I, /* R_TOK */ + z.T * I, /* R_POS */ + (z.S + 1) * I, /* R_CU */ + z.T * I, /* R_SLOT */ + z.S * z.NB * I, /* R_BT */ + z.S * I, /* R_USED */ + z.L * I, /* R_LANE */ + z.L * I, /* R_LAST */ + z.L * I, /* R_FRAME */ + 2 * SL * I, /* R_SEED */ + z.S * 4, /* R_T */ + z.S * 4, /* R_TN */ + z.S * 4, /* R_CFG */ + z.S * I, /* R_PAIR */ + z.S * I, /* R_WLANE */ + z.S * I, /* R_FLAGS */ + z.S * I, /* R_WIDX */ + z.S * I, /* R_WF0 */ + z.S * I, /* R_WNF */ + (z.S + 1) * I, /* R_LCU */ + z.T * I, /* R_LSRC */ + z.S * I, /* R_ESLOT */ + z.S * I, /* R_LROW */ + z.S * I, /* R_PREFIX */ + }; + int64_t off = 0; + for (int r = 0; r < n; ++r) { + bytes[r][0] = off; + bytes[r][1] = want[r]; + off = align_up(off + want[r]); + } + return off; +} + +} /* namespace */ + +int64_t AudioDriver::device_bytes(const Program& prog) { + if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0; + const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size); + int64_t b[R_N][2]; + return carve(z, b, R_N); +} + +int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector& ranks) { + fini(); + if (!prog.is_audio_generator()) return RAD_E_STATE; + decl_ = prog.audio_gen; + name_ = prog.agen_str.name; + kv_ = kv; + ranks_ = ranks; + /* The language model's KV, both branches of every lane: one paged full-attention group. */ + if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL || + prog.kv_groups[1].block_size <= 0) { + RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages exactly " + "one full-attention group, the language model's", prog.kv_groups.size() - 1); + return RAD_E_UNSUPPORTED; + } + kv_group_ = 1; + block_size_ = prog.kv_groups[1].block_size; + const Sizes z = sizes_of(prog, block_size_); + max_tok_ = z.T; + max_seqs_ = z.S; + max_blocks_ = z.NB; + neg_own_ = !prog.agen_str.neg_tmpl.empty(); + /* A FRAME pass carries both branches of every lane; a window's step at least one window, a + * chunk's vocode its frames and their context, and a whole prompt both its branches. */ + const int64_t step_rows = chunked() ? decl_.voc_context + decl_.voc_chunk + : 2 * (decl_.win_lead + win_latents(decl_.win_frames)); + const int64_t prompt_rows = decl_.prompt_whole ? 2 * decl_.max_prompt : 2; + if (max_seqs_ < 2 * decl_.max_lanes || max_tok_ < 2 * decl_.max_lanes || + max_tok_ < step_rows || max_tok_ < prompt_rows) { + RAD_ERR("audio generator: a pass carries %lld rows of %lld sequences; '%s' needs %lld " + "sequences for its %lld lanes, %lld rows for a %s and %lld for a whole prompt", + (long long)max_tok_, (long long)max_seqs_, name_.c_str(), + (long long)(2 * decl_.max_lanes), (long long)decl_.max_lanes, + (long long)step_rows, chunked() ? "chunk's vocode" : "window's step", + (long long)prompt_rows); + return RAD_E_UNSUPPORTED; + } + int64_t b[R_N][2]; + bytes_ = carve(z, b, R_N); + for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; } + + host_ = static_cast(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); + status_host_ = static_cast(rad_dev_alloc(decl_.max_lanes * 4, RAD_MEM_HOST_PINNED)); + audio_bytes_ = (chunked() ? decl_.voc_chunk : win_latents(decl_.win_frames)) * + decl_.samples_per_latent * decl_.channels * 4; + audio_host_ = static_cast(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED)); + if (!host_ || !status_host_ || !audio_host_) { + RAD_ERR("audio generator: no pinned host memory for the pass staging (%lld + %lld bytes)", + (long long)bytes_, (long long)audio_bytes_); + return RAD_E_NOMEM; + } + std::memset(host_, 0, (size_t)bytes_); + dev_.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE); + if (!dev_[r]) { + RAD_ERR("audio generator: rank %zu has no room for the pass staging (%lld bytes)", r, + (long long)bytes_); + return RAD_E_NOMEM; + } + } + if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device)); + out_.assign(ranks_.size(), RadBatch{}); + aout_.assign(ranks_.size(), RadAudioGenBatch{}); + kout_.assign(ranks_.size(), RadKVGroupBatch{}); + free_lanes_.clear(); + for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i); + return RAD_OK; +} + +void AudioDriver::fini() { + for (size_t r = 0; r < dev_.size(); ++r) + if (dev_[r]) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + rad_dev_free(dev_[r], RAD_MEM_DEVICE); + } + dev_.clear(); + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED); + if (status_host_) rad_dev_free(status_host_, RAD_MEM_HOST_PINNED); + if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED); + host_ = nullptr; + status_host_ = nullptr; + audio_host_ = nullptr; +} + +/* ================================================================== requests */ +int AudioDriver::submit(std::unique_ptr r, std::string* why) { + if (!r || !r->ticket) return RAD_E_INVAL; + const RadAudioGenDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size(); + if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail) + return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own " + "markers"); + if (T < 1 || std::max(T, Tn) > d.max_prompt) + return no("the prompt is " + std::to_string(std::max(T, Tn)) + " tokens; this model takes " + "1.." + std::to_string(d.max_prompt)); + if (r->max_frames < 1 || r->max_frames > d.max_frames) + return no("the length must be 1.." + std::to_string(d.max_frames) + " frames (" + + std::to_string(d.max_frames * d.frame_rate_den / d.frame_rate_num) + + " seconds)"); + if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000"); + if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1"); + if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1)) + return no("a piece of " + std::to_string(r->max_frames) + " frames after a " + + std::to_string(T) + "-token prompt does not fit the KV cache even when it is " + "empty; ask for a shorter piece"); + r->ticket->t_submit_ns = (int64_t)rad_mono_ns(); + std::lock_guard lk(mu_); + if (closed_) { + if (why) *why = closed_why_; + return closed_status_; + } + auto j = std::make_unique(); + j->id = next_id_++; + j->T = T; + j->req = std::move(r); + jobs_.push_back(std::move(j)); + return RAD_OK; +} + +void AudioDriver::shutdown(const char* why, int status) { + std::lock_guard lk(mu_); + closed_ = true; + closed_why_ = why ? why : "the engine stopped"; + closed_status_ = status; + for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_); +} + +int64_t AudioDriver::queued() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (!j->admitted) ++n; + return n; +} + +int64_t AudioDriver::running() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (j->admitted) ++n; + return n; +} + +AudioDriver::Job* AudioDriver::job_locked(uint64_t id) { + for (auto& j : jobs_) if (j->id == id) return j.get(); + return nullptr; +} + +void AudioDriver::release_locked(Job& j) { + for (int b = 0; b < 2; ++b) + if (j.seq[b]) { + kv_->free_sequence(j.seq[b]); + j.seq[b] = 0; + } + j.have_kv = false; + if (j.lane >= 0) { + free_lanes_.push_back(j.lane); + j.lane = -1; + } +} + +void AudioDriver::fail_locked(Job& j, int status, const std::string& why) { + j.failed = true; + j.req->ticket->finish(status, why); +} + +/* In arrival order; a request that does not fit stops the ones behind it. */ +int AudioDriver::admit_locked() { + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted || j.failed) continue; + if (free_lanes_.empty()) break; + const AudioRequest& r = *j.req; + const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg; + /* The unconditional prompt: the request's own (the conditional one at guidance 1, which + * makes the guided logits the conditional ones), or derived from the conditional one. */ + std::vector neg = r.tokens; + if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) { + neg = r.neg_tokens; + } else if (!neg_own_) { + for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i) + neg[(size_t)i] = decl_.neg_token; + } + /* Both branches for the whole piece, so nothing in flight ever waits for KV. */ + bool ok = true; + for (int b = 0; b < 2 && ok; ++b) { + const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1; + j.seq[b] = ((uint64_t)1 << 61) | next_seq_++; + if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false; + } + if (!ok) { + for (int b = 0; b < 2; ++b) + if (j.seq[b]) { + if (kv_->has_sequence(j.seq[b])) kv_->free_sequence(j.seq[b]); + j.seq[b] = 0; + } + break; + } + j.have_kv = true; + j.lane = free_lanes_.back(); + free_lanes_.pop_back(); + j.neg = std::move(neg); + j.Tn = (int64_t)j.neg.size(); + j.steps = r.steps > 0 ? r.steps : (int32_t)decl_.default_steps; + j.cfg = cfg; + j.req->ticket->in_tokens = j.T; + j.admitted = true; + } + return RAD_OK; +} + +/* ================================================================== windows */ +/* Window k is frames [k hop, k hop + win_frames), cut short at the piece's end. Window 0 always + * exists; window k >= 1 exists while frames remain past its overlap with window k - 1. */ +int64_t AudioDriver::window_frames(const Job& j, int32_t k) const { + const int64_t f0 = win_frame0(k); + return j.ar_done ? std::min(decl_.win_frames, j.kept - f0) : decl_.win_frames; +} + +bool AudioDriver::window_ready(const Job& j) const { + if (j.voc_due >= 0) return false; + if (j.win_step > 0) return true; + const int64_t k = j.win; + if (j.ar_done) + return k == 0 ? j.kept >= 1 + : j.kept > k * decl_.win_hop + (decl_.win_frames - decl_.win_hop); + return j.kept >= k * decl_.win_hop + decl_.win_frames; +} + +bool AudioDriver::chunk_due(const Job& j) const { + const int64_t ready = j.kept - j.played; + return !j.finished && (ready >= decl_.voc_chunk || (j.ar_done && ready > 0)); +} + +int AudioDriver::window_last(const Job& j, int32_t k) const { + const bool next_exists = + j.kept > (int64_t)(k + 1) * decl_.win_hop + (decl_.win_frames - decl_.win_hop); + if (next_exists) return 0; + return j.ar_done ? 1 : -1; +} + +/* ================================================================== staging */ +int AudioDriver::upload() { + for (size_t r = 0; r < ranks_.size(); ++r) + for (int g = 0; g < R_N; ++g) { + if (reg_[g].used <= 0) continue; + RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off, + reg_[g].used, ranks_[r].stream)); + } + return RAD_OK; +} + +void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, + int step, bool kv, int64_t bt_pitch) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + RadAudioGenBatch& A = aout_[r]; + RadKVGroupBatch& K = kout_[r]; + const int ri = (int)r; + B = RadBatch{}; + B.step = step; + B.phase = RAD_PHASE_PREFILL; + B.n_tok = n_tok; + B.n_seq = n_seq; + B.max_q_len = max_q; + B.max_ctx_len = max_ctx; + B.max_q_len_prefill = max_q; + B.token_ids = dptr(ri, R_TOK); + B.positions = dptr(ri, R_POS); + B.cu_seqlens = dptr(ri, R_CU); + if (kv) { + K = RadKVGroupBatch{}; + K.group = (rad_kvgroup)kv_group_; + K.slot_mapping = dptr(ri, R_SLOT); + K.block_table = dptr(ri, R_BT); + K.block_table_pitch = bt_pitch; + K.seqused = dptr(ri, R_USED); + K.block_size = block_size_; + K.max_blocks = max_blocks_; + B.n_kv_groups = 1; + B.kv = &K; + } + A = RadAudioGenBatch{}; + A.lane = dptr(ri, R_LANE); + A.last = dptr(ri, R_LAST); + A.frame = dptr(ri, R_FRAME); + A.seed = dptr(ri, R_SEED); + A.t = dptr(ri, R_T); + A.t_next = dptr(ri, R_TN); + A.cfg = dptr(ri, R_CFG); + A.pair = dptr(ri, R_PAIR); + A.win_lane = dptr(ri, R_WLANE); + A.flags = dptr(ri, R_FLAGS); + A.win_index = dptr(ri, R_WIDX); + A.win_frame0 = dptr(ri, R_WF0); + A.win_frames = dptr(ri, R_WNF); + A.lat_cu = dptr(ri, R_LCU); + A.lat_src = dptr(ri, R_LSRC); + A.slot = dptr(ri, R_ESLOT); + A.last_row = dptr(ri, R_LROW); + A.prefix = dptr(ri, R_PREFIX); + B.agen_b = &A; + } +} + +/* The KV slot of position `p` in a sequence with this block table. */ +static int32_t slot_of(const std::vector& bt, int64_t p, int64_t bs) { + const int64_t bi = p / bs; + return bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * bs + p % bs) : -1; +} + +/* ================================================================== the passes */ +const RadBatch* AudioDriver::next(int step) { + std::lock_guard lk(mu_); + pass_ = Pass{}; + rb_.clear(); + if (closed_) return nullptr; + /* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting. + * Safe because next() runs between passes, with nothing in flight. */ + for (auto it = jobs_.begin(); it != jobs_.end();) { + Job& j = **it; + const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire); + if (!(j.failed || cancelled || j.finished)) { ++it; continue; } + if (cancelled && !j.failed && !j.finished) + j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled"); + release_locked(j); + it = jobs_.erase(it); + } + admit_locked(); + + /* 1. A vocode: a chunk of frames that is ready, or a finished window, once it is known + * whether a window follows it. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed) continue; + if (chunked()) { + if (chunk_due(j)) return build_chunk(j, step); + continue; + } + if (j.voc_due >= 0 && window_last(j, j.voc_due) >= 0) return build_vocode(j, step); + } + /* 2. A prompt chunk. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted && !j.failed && j.prompt_done < j.T) return build_prompt(j, step); + } + /* 3. A frame of every lane in its autoregressive stage, or a step of the ready windows. */ + std::vector fr, win; + int64_t win_rows = 0, win_ent = 0; + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed || j.prompt_done < j.T) continue; + if (!j.ar_done) fr.push_back(&j); + if (!chunked() && window_ready(j)) { + const int64_t nb = j.cfg > 1.0f ? 2 : 1; + const int64_t rows = + nb * (decl_.win_lead + win_latents(window_frames(j, j.win))); + if (win_rows + rows <= max_tok_ && win_ent + nb <= max_seqs_) { + win_rows += rows; + win_ent += nb; + win.push_back(&j); + } + } + } + if (!fr.empty() && (win.empty() || frame_turn_)) { + frame_turn_ = false; + return build_frame(fr, step); + } + if (!win.empty()) { + frame_turn_ = true; + return build_window(win, step); + } + return nullptr; +} + +const RadBatch* AudioDriver::batch_for(int rank) const { + if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr; + return &out_[(size_t)rank]; +} + +const RadBatch* AudioDriver::build_prompt(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + /* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */ + const int64_t p0 = j.prompt_done; + int64_t cb[2]; + if (decl_.prompt_whole) { + cb[0] = j.T; + cb[1] = j.Tn; + } else { + cb[0] = cb[1] = std::min(j.T - j.prompt_done, max_tok_ / 2); + } + const int64_t cmax = std::max(cb[0], cb[1]); + int32_t* tok = hptr(R_TOK); + int32_t* pos = hptr(R_POS); + int32_t* slot = hptr(R_SLOT); + int32_t* cu = hptr(R_CU); + int64_t pitch = 1; + for (int b = 0; b < 2; ++b) + pitch = std::max(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size()); + int32_t* btab = hptr(R_BT); + int32_t* used = hptr(R_USED); + cu[0] = 0; + for (int b = 0; b < 2; ++b) { + const std::vector& src = b ? j.neg : j.req->tokens; + const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); + for (int64_t i = 0; i < cb[b]; ++i) { + const int64_t e = cu[b] + i; + tok[e] = src[(size_t)(p0 + i)]; + pos[e] = (int32_t)(p0 + i); + slot[e] = slot_of(bt, p0 + i, block_size_); + } + cu[b + 1] = (int32_t)(cu[b] + cb[b]); + for (int64_t k = 0; k < pitch; ++k) + btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; + used[b] = (int32_t)(p0 + cb[b]); + } + const int64_t rows = cu[2]; + const bool last = p0 + cb[0] == j.T; + for (int b = 0; b < 2; ++b) { + hptr(R_ESLOT)[b] = 2 * j.lane + b; + hptr(R_LROW)[b] = cu[b + 1] - 1; + hptr(R_PREFIX)[b] = (int32_t)p0; + } + reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4; + hptr(R_LANE)[0] = j.lane; + hptr(R_LAST)[0] = last ? 1 : 0; + hptr(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu); + hptr(R_SEED)[1] = (uint32_t)(j.req->seed >> 32); + reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4; + reg_[R_CU].used = 3 * 4; + reg_[R_BT].used = 2 * pitch * 4; + reg_[R_USED].used = 2 * 4; + reg_[R_LANE].used = reg_[R_LAST].used = 4; + reg_[R_SEED].used = 8; + if (upload() < 0) return nullptr; + base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); + h_lane_.assign(1, j.lane); + h_last_.assign(1, last ? 1 : 0); + for (size_t r = 0; r < ranks_.size(); ++r) { + out_[r].gen = RAD_GEN_PASS_PROMPT; + RadAudioGenBatch& A = aout_[r]; + A.n_lane = 1; + A.lane_h = h_lane_.data(); + A.last_h = h_last_.data(); + } + pass_.kind = RAD_GEN_PASS_PROMPT; + pass_.jobs.assign(1, j.id); + pass_.rows.assign(1, cb[0]); + return &out_[0]; +} + +const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int64_t L = (int64_t)js.size(), S = 2 * L; + int32_t* tok = hptr(R_TOK); + int32_t* pos = hptr(R_POS); + int32_t* slot = hptr(R_SLOT); + int32_t* cu = hptr(R_CU); + int32_t* btab = hptr(R_BT); + int32_t* used = hptr(R_USED); + int32_t* lane = hptr(R_LANE); + int32_t* frame = hptr(R_FRAME); + uint32_t* seed = hptr(R_SEED); + int64_t pitch = 1; + int32_t max_ctx = 0; + for (const Job* j : js) + for (int b = 0; b < 2; ++b) + pitch = std::max(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size()); + h_lane_.assign((size_t)L, 0); + h_frame_.assign((size_t)L, 0); + pass_.jobs.clear(); + for (int64_t i = 0; i < L; ++i) { + const Job& j = *js[(size_t)i]; + for (int b = 0; b < 2; ++b) { + /* The frame's row follows the branch's prompt and its earlier frames. */ + const int64_t p = (b ? j.Tn : j.T) + j.frame; + const int64_t e = 2 * i + b; + const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); + tok[e] = 0; + pos[e] = (int32_t)p; + slot[e] = slot_of(bt, p, block_size_); + cu[e] = (int32_t)e; + for (int64_t k = 0; k < pitch; ++k) + btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; + used[e] = (int32_t)(p + 1); + hptr(R_ESLOT)[e] = 2 * j.lane + b; + hptr(R_LROW)[e] = (int32_t)e; + max_ctx = std::max(max_ctx, (int32_t)(p + 1)); + } + hptr(R_CFG)[i] = j.cfg; + lane[i] = h_lane_[(size_t)i] = j.lane; + frame[i] = h_frame_[(size_t)i] = j.frame; + seed[2 * i] = (uint32_t)(j.req->seed & 0xffffffffu); + seed[2 * i + 1] = (uint32_t)(j.req->seed >> 32); + pass_.jobs.push_back(j.id); + } + cu[S] = (int32_t)S; + reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4; + reg_[R_CU].used = (S + 1) * 4; + reg_[R_BT].used = S * pitch * 4; + reg_[R_USED].used = S * 4; + reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4; + reg_[R_SEED].used = 2 * L * 4; + reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4; + if (upload() < 0) return nullptr; + base_batches(S, S, 1, max_ctx, step, true, pitch); + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + B.gen = RAD_GEN_PASS_FRAME; + B.phase = RAD_PHASE_DECODE; + B.n_seq_decode = S; + B.n_tok_decode = S; + B.max_q_len_decode = 1; + B.max_q_len_prefill = 0; + RadAudioGenBatch& A = aout_[r]; + A.n_lane = L; + A.lane_h = h_lane_.data(); + A.frame_h = h_frame_.data(); + } + rb_.assign(1, Readback{ decl_.status, decl_.max_lanes * 4, status_host_ }); + pass_.kind = RAD_GEN_PASS_FRAME; + return &out_[0]; +} + +const RadBatch* AudioDriver::build_window(const std::vector& js, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + int32_t* tok = hptr(R_TOK); + int32_t* pos = hptr(R_POS); + int32_t* cu = hptr(R_CU); + float* t = hptr(R_T); + float* tn = hptr(R_TN); + float* cfg = hptr(R_CFG); + int32_t* pair = hptr(R_PAIR); + int32_t* wlane = hptr(R_WLANE); + int32_t* flags = hptr(R_FLAGS); + int32_t* widx = hptr(R_WIDX); + int32_t* wf0 = hptr(R_WF0); + int32_t* wnf = hptr(R_WNF); + int32_t* lcu = hptr(R_LCU); + int32_t* lsrc = hptr(R_LSRC); + uint32_t* seed = hptr(R_SEED); + h_wlane_.clear(); + h_flags_.clear(); + h_widx_.clear(); + h_wf0_.clear(); + h_wnf_.clear(); + h_lcu_.assign(1, 0); + pass_.jobs.clear(); + int64_t S = 0, row = 0, lrow = 0; + int32_t max_q = 0; + cu[0] = 0; + lcu[0] = 0; + for (Job* jp : js) { + Job& j = *jp; + const int64_t nf = window_frames(j, j.win); + const int64_t nl = win_latents(nf); + const int64_t len = decl_.win_lead + nl; + const int nb = j.cfg > 1.0f ? 2 : 1; + int32_t f = 0; + if (j.win_step == 0) f |= RAD_AGEN_F_FIRST; + if (j.win_step + 1 == j.steps) f |= RAD_AGEN_F_LAST; + if (j.win > 0) f |= RAD_AGEN_F_JOIN; + for (int b = 0; b < nb; ++b) { + const int64_t e = S++; + for (int64_t k = 0; k < len; ++k) { + tok[row + k] = 0; + pos[row + k] = (int32_t)k; + } + for (int64_t k = 0; k < nl; ++k) lsrc[lrow + k] = (int32_t)(row + decl_.win_lead + k); + row += len; + lrow += nl; + cu[e + 1] = (int32_t)row; + lcu[e + 1] = (int32_t)lrow; + t[e] = (float)j.win_step / (float)j.steps; + tn[e] = (float)(j.win_step + 1) / (float)j.steps; + cfg[e] = b ? 0.0f : (nb > 1 ? j.cfg : 1.0f); + pair[e] = b ? -2 : (nb > 1 ? (int32_t)(e + 1) : -1); + wlane[e] = j.lane; + flags[e] = f; + widx[e] = j.win; + wf0[e] = (int32_t)win_frame0(j.win); + wnf[e] = (int32_t)nf; + seed[2 * e] = (uint32_t)(j.req->seed & 0xffffffffu); + seed[2 * e + 1] = (uint32_t)(j.req->seed >> 32); + h_wlane_.push_back(j.lane); + h_flags_.push_back(f); + h_widx_.push_back(j.win); + h_wf0_.push_back(wf0[e]); + h_wnf_.push_back((int32_t)nf); + h_lcu_.push_back((int32_t)lrow); + max_q = std::max(max_q, (int32_t)len); + } + pass_.jobs.push_back(j.id); + } + reg_[R_TOK].used = reg_[R_POS].used = row * 4; + reg_[R_CU].used = reg_[R_LCU].used = (S + 1) * 4; + reg_[R_T].used = reg_[R_TN].used = reg_[R_CFG].used = S * 4; + reg_[R_PAIR].used = reg_[R_WLANE].used = reg_[R_FLAGS].used = S * 4; + reg_[R_WIDX].used = reg_[R_WF0].used = reg_[R_WNF].used = S * 4; + reg_[R_SEED].used = 2 * S * 4; + reg_[R_LSRC].used = lrow * 4; + if (upload() < 0) return nullptr; + base_batches(row, S, max_q, 0, step, false, 0); + for (size_t r = 0; r < ranks_.size(); ++r) { + out_[r].gen = RAD_GEN_PASS_WINDOW; + RadAudioGenBatch& A = aout_[r]; + A.win_lane_h = h_wlane_.data(); + A.flags_h = h_flags_.data(); + A.win_index_h = h_widx_.data(); + A.win_frame0_h = h_wf0_.data(); + A.win_frames_h = h_wnf_.data(); + A.lat_rows = lrow; + A.lat_cu_h = h_lcu_.data(); + } + pass_.kind = RAD_GEN_PASS_WINDOW; + return &out_[0]; +} + +const RadBatch* AudioDriver::build_vocode(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int32_t k = j.voc_due; + const int64_t nl = win_latents(window_frames(j, k)); + int64_t left = k > 0 ? decl_.win_crop_left : 0; + int64_t right = window_last(j, k) == 1 ? 0 : decl_.win_crop_right; + left = std::min(left, nl); + right = std::min(right, nl - left); + int32_t* cu = hptr(R_CU); + cu[0] = 0; + cu[1] = (int32_t)nl; + reg_[R_CU].used = 2 * 4; + if (upload() < 0) return nullptr; + base_batches(nl, 1, (int32_t)nl, 0, step, false, 0); + for (size_t r = 0; r < ranks_.size(); ++r) { + out_[r].gen = RAD_GEN_PASS_VOCODE; + RadAudioGenBatch& A = aout_[r]; + A.voc_lane = j.lane; + A.voc_window = k; + A.voc_latents = (int32_t)nl; + A.voc_left = (int32_t)left; + A.voc_right = (int32_t)right; + } + const int64_t samples = (nl - left - right) * decl_.samples_per_latent; + rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ }); + pass_.kind = RAD_GEN_PASS_VOCODE; + pass_.voc_job = j.id; + pass_.voc_window = k; + pass_.voc_samples = samples; + return &out_[0]; +} + +/* A chunk of a lane's kept frames, after the frames it reads again for context. Its rows are + * the frames, at their positions in the piece. */ +const RadBatch* AudioDriver::build_chunk(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int64_t n = std::min(decl_.voc_chunk, j.kept - j.played); + const int64_t ctx = std::min(decl_.voc_context, j.played); + const int64_t f0 = j.played - ctx, nl = ctx + n; + int32_t* cu = hptr(R_CU); + int32_t* pos = hptr(R_POS); + cu[0] = 0; + cu[1] = (int32_t)nl; + for (int64_t i = 0; i < nl; ++i) pos[i] = (int32_t)(f0 + i); + reg_[R_CU].used = 2 * 4; + reg_[R_POS].used = nl * 4; + if (upload() < 0) return nullptr; + base_batches(nl, 1, (int32_t)nl, 0, step, false, 0); + for (size_t r = 0; r < ranks_.size(); ++r) { + out_[r].gen = RAD_GEN_PASS_VOCODE; + RadAudioGenBatch& A = aout_[r]; + A.voc_lane = j.lane; + A.voc_window = j.windows_played; + A.voc_latents = (int32_t)nl; + A.voc_left = (int32_t)ctx; + A.voc_right = 0; + A.voc_frame0 = f0; + } + const int64_t samples = n * decl_.samples_per_latent; + rb_.assign(1, Readback{ decl_.audio_out, samples * decl_.channels * 4, audio_host_ }); + pass_.kind = RAD_GEN_PASS_VOCODE; + pass_.voc_job = j.id; + pass_.voc_window = j.windows_played; + pass_.voc_samples = samples; + pass_.voc_frames = n; + return &out_[0]; +} + +int AudioDriver::done() { + std::lock_guard lk(mu_); + const int64_t now = (int64_t)rad_mono_ns(); + switch (pass_.kind) { + case RAD_GEN_PASS_PROMPT: + for (size_t i = 0; i < pass_.jobs.size(); ++i) { + Job* j = job_locked(pass_.jobs[i]); + if (!j) continue; + j->prompt_done += pass_.rows[i]; + if (j->prompt_done >= j->T) j->req->ticket->t_prompt_ns = now; + } + break; + case RAD_GEN_PASS_FRAME: + for (uint64_t id : pass_.jobs) { + Job* j = job_locked(id); + if (!j || j->failed) continue; + const int32_t st = status_host_[j->lane]; + if (st < 0) { + j->ar_done = true; + j->req->ticket->model_ended = true; + if (j->kept == 0) { + fail_locked(*j, RAD_E_INVAL, "the model ended the piece before its first " + "frame; try other text or another seed"); + continue; + } + } else { + if (j->frame >= decl_.first_frame) j->kept = j->frame - decl_.first_frame + 1; + ++j->frame; + if (j->kept >= j->req->max_frames) j->ar_done = true; + } + if (j->ar_done) { + j->req->ticket->frames = j->kept; + j->req->ticket->t_frames_ns = now; + /* Every frame already played: nothing more is owed. */ + if (chunked() && j->played == j->kept) { + j->finished = true; + j->req->ticket->windows = j->windows_played; + j->req->ticket->t_done_ns = now; + j->req->ticket->finish(RAD_OK); + } + } + } + break; + case RAD_GEN_PASS_WINDOW: + for (uint64_t id : pass_.jobs) { + Job* j = job_locked(id); + if (!j) continue; + if (++j->win_step >= j->steps) { + j->voc_due = j->win; + j->win_step = 0; + } + } + break; + case RAD_GEN_PASS_VOCODE: { + Job* j = job_locked(pass_.voc_job); + if (!j) break; + AudioChunk c; + c.window = pass_.voc_window; + c.samples.assign(audio_host_, audio_host_ + pass_.voc_samples * decl_.channels); + j->req->ticket->push(std::move(c)); + if (j->windows_played == 0) j->req->ticket->t_first_audio_ns = now; + ++j->windows_played; + bool last; + if (chunked()) { + j->played += pass_.voc_frames; + last = j->ar_done && j->played == j->kept; + } else { + last = window_last(*j, j->voc_due) == 1; + j->voc_due = -1; + ++j->win; + } + if (last) { + j->finished = true; + j->req->ticket->windows = j->windows_played; + j->req->ticket->t_done_ns = now; + j->req->ticket->finish(RAD_OK); + } + break; + } + default: + break; + } + pass_ = Pass{}; + rb_.clear(); + return RAD_OK; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/audio_driver.h b/core/gen/audio_driver.h new file mode 100644 index 00000000..bb986103 --- /dev/null +++ b/core/gen/audio_driver.h @@ -0,0 +1,188 @@ +/* audio_driver.h -- the audio generator's pass driver (audio.h, abi/rad_builder.h's + * RadAudioGenDecl describes the passes). + * + * Driven by the engine thread like the image driver (driver.h): `next()` picks and stages a pass, + * `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads + * through `submit()` and leave through their AudioTicket. + * + * A request holds a lane and two KV sequences, its conditional and unconditional branches, from + * admission to its last window; both are reserved for the whole piece at admission (prompt plus + * every frame the request may make), so a request in flight never waits for KV. + * + * Pass priority, one pass at a time: + * + * 1. VOCODE a finished window is owed (it frees the lane's latent for the next window and gives + * the caller audio), or, for a vocoder that plays frames as they are made + * (RadAudioGenDecl::voc_chunk), a chunk of frames is ready: `voc_chunk` of them, or the + * piece's last. + * 2. PROMPT an admitted request's prompt is not all in the KV: the next chunk of it, both + * branches. + * 3. FRAME and WINDOW, taking turns when both have work: one frame of every request in its + * autoregressive stage, or one denoising step of the windows that are ready. A FRAME pass + * carries every lane at once, since its cost is reading the language model's weights, which + * the lanes share; a window's step is compute and carries what fits the pass's rows. + * + * A window is ready once the language model has made all its frames, or ended the piece. Its + * vocoding waits until it is known whether a window follows it (the crop at its end depends on + * that): once the frames of the next window have begun, or the piece has ended. + */ +#pragma once +#include "audio.h" +#include "pass.h" +#include "device/device.h" + +#include + +namespace rad { +struct IKVManager; +namespace gen { + +class AudioDriver final : public IPassDriver { +public: + struct RankIO { + int device = 0; + RadStream stream = nullptr; + }; + + /* `kv` is rank 0's KV manager: one block table serves every rank. */ + int init(const Program& prog, IKVManager* kv, const std::vector& ranks); + void fini(); + ~AudioDriver() override { fini(); } + + /* The bytes init() allocates on each rank's card, for the VRAM budget. */ + static int64_t device_bytes(const Program& prog); + /* The longest sequence a branch holds: the whole prompt and every frame. The KV group is + * sized from it. */ + static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; } + + /* ---------------------------------------------------------- HTTP threads */ + /* Queue a request, refused at once with `why` when it can never run. */ + int submit(std::unique_ptr r, std::string* why); + const RadAudioGenDecl& decl() const { return decl_; } + void shutdown(const char* why, int status) override; + + /* ---------------------------------------------------------- the engine thread */ + const RadBatch* next(int step) override; + const RadBatch* batch_for(int rank) const override; + const std::vector& readbacks() const override { return rb_; } + int done() override; + + int64_t queued() const override; + int64_t running() const override; + +private: + struct Job { + uint64_t id = 0; + std::unique_ptr req; + int32_t lane = -1; + uint64_t seq[2] = { 0, 0 }; + bool have_kv = false; + bool admitted = false; + bool failed = false; + int64_t T = 0; /* prompt tokens */ + std::vector neg; /* the unconditional prompt */ + int64_t Tn = 0; /* its tokens */ + int64_t prompt_done = 0; /* prompt rows in the KV */ + /* The autoregressive stage: the next frame to make, the frames kept, and whether it is + * over (the model ended the piece, or it reached max_frames). */ + int32_t frame = 0; + int64_t kept = 0; + bool ar_done = false; + /* The windows: the one being stepped (or next to start), its step, and the one owed a + * vocode pass (-1 none). */ + int32_t win = 0; + int32_t win_step = 0; + int32_t steps = 0; + float cfg = 1.0f; + int32_t voc_due = -1; + int32_t windows_played = 0; + /* A vocoder playing frames as they are made: the kept frames played so far. */ + int64_t played = 0; + bool finished = false; + }; + /* The pass in flight, for done(). */ + struct Pass { + int kind = 0; + std::vector jobs; /* PROMPT, FRAME, WINDOW: one per lane or window */ + std::vector rows; /* PROMPT: the chunk each job's branches advanced */ + uint64_t voc_job = 0; + int32_t voc_window = -1; + int64_t voc_samples = 0; + int64_t voc_frames = 0; /* a chunk's frames played */ + }; + + /* Staging regions: their offsets in the host span and every rank's slab. */ + struct Region { int64_t off = 0, bytes = 0, used = 0; }; + enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED, + R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC, + R_ESLOT, R_LROW, R_PREFIX, R_N }; + + template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } + template T* dptr(int rank, int r) const { + return reinterpret_cast((char*)dev_[(size_t)rank] + reg_[r].off); + } + int upload(); + void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step, + bool kv, int64_t bt_pitch); + + int admit_locked(); + void release_locked(Job& j); + void fail_locked(Job& j, int status, const std::string& why); + Job* job_locked(uint64_t id); + + /* Window geometry: window k's first frame and frames once the piece has `n` frames (or + * at least `n`, with `ended` false), whether it exists, and whether it is the last. */ + int64_t win_frame0(int32_t k) const { return (int64_t)k * decl_.win_hop; } + int64_t win_latents(int64_t frames) const { return frames * decl_.lat_num / decl_.lat_den; } + bool window_ready(const Job& j) const; + /* A vocoder playing frames as they are made: whether a chunk of `j`'s frames is due. */ + bool chunk_due(const Job& j) const; + bool chunked() const { return decl_.voc_chunk > 0; } + int window_last(const Job& j, int32_t k) const; /* 1 last, 0 not, -1 not yet known */ + int64_t window_frames(const Job& j, int32_t k) const; + + const RadBatch* build_prompt(Job& j, int step); + const RadBatch* build_frame(const std::vector& js, int step); + const RadBatch* build_window(const std::vector& js, int step); + const RadBatch* build_vocode(Job& j, int step); + const RadBatch* build_chunk(Job& j, int step); + + RadAudioGenDecl decl_{}; + std::string name_; + int64_t max_tok_ = 0, max_seqs_ = 0; + int64_t block_size_ = 0, max_blocks_ = 0; + int32_t kv_group_ = 0; + bool neg_own_ = false; /* the unconditional prompt is the request's own */ + std::vector ranks_; + IKVManager* kv_ = nullptr; + + char* host_ = nullptr; /* pinned, same layout as each slab */ + int64_t bytes_ = 0; + std::vector dev_; + Region reg_[R_N]; + int32_t* status_host_ = nullptr; + float* audio_host_ = nullptr; + int64_t audio_bytes_ = 0; + std::vector rb_; + + std::vector out_; /* one per rank */ + std::vector aout_; + std::vector kout_; + Pass pass_; + bool frame_turn_ = true; /* FRAME goes first when both are due */ + /* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */ + std::vector h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_, + h_wf0_, h_wnf_, h_lcu_; + + mutable std::mutex mu_; + std::deque> jobs_; /* arrival order */ + std::vector free_lanes_; + uint64_t next_id_ = 1; + uint64_t next_seq_ = 1; + bool closed_ = false; + std::string closed_why_; + int closed_status_ = RAD_E_STATE; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 73caf73c..500194b9 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -439,6 +439,7 @@ const RadBatch* Driver::next(int step) { std::lock_guard lk(mu_); pass_ = Pass{}; dec_bytes_ = 0; + rb_.clear(); if (closed_) return nullptr; /* Retire finished, failed and cancelled jobs, returning their KV and lanes before admitting. * Safe because next() runs between passes, with nothing in flight. */ @@ -820,6 +821,7 @@ const RadBatch* Driver::build_decode(int32_t l, bool preview, int step) { G.dec_preview = preview ? 1 : 0; } dec_bytes_ = (int64_t)j->req->width * j->req->height * decl_.pixel_channels; + rb_.assign(1, Readback{ decl_.image_out, dec_bytes_, img_host_ }); pass_.kind = RAD_GEN_PASS_DECODE; pass_.job = j->id; pass_.lane = l; @@ -889,6 +891,7 @@ int Driver::done() { } pass_ = Pass{}; dec_bytes_ = 0; + rb_.clear(); return RAD_OK; } diff --git a/core/gen/driver.h b/core/gen/driver.h index c8068a54..79c51fff 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -23,6 +23,7 @@ */ #pragma once #include "gen.h" +#include "pass.h" #include "device/device.h" #include @@ -31,7 +32,7 @@ namespace rad { namespace gen { -class Driver { +class Driver final : public IPassDriver { public: struct RankIO { int device = 0; @@ -54,25 +55,18 @@ public: * request. */ const RadGeneratorDecl& decl() const { return decl_; } int64_t max_cond_tokens() const { return max_tok_; } - /* Fail every request queued or in flight, and refuse new ones. */ - void shutdown(const char* why, int status); + void shutdown(const char* why, int status) override; /* ---------------------------------------------------------- the engine thread */ - /* The next pass, staged on every rank's stream, or null when there is nothing to run. - * `step` is the engine's pass counter, carried into RadBatch::step. */ - const RadBatch* next(int step); - const RadBatch* batch_for(int rank) const; - /* Bytes of image output the staged pass produces, 0 if none; the engine copies them to - * host_image() behind the pass. */ - int64_t decode_bytes() const { return dec_bytes_; } - void* host_image() const { return img_host_; } - /* The pass has run on every rank and its streams are drained. */ - int done(); + const RadBatch* next(int step) override; + const RadBatch* batch_for(int rank) const override; + /* A decode pass's pixels: `image_out` into the pinned image buffer. */ + const std::vector& readbacks() const override { return rb_; } + int done() override; bool busy() const; - /* For /health, /stats and the dashboard. */ - int64_t queued() const; - int64_t running() const; + int64_t queued() const override; + int64_t running() const override; private: struct Cond { @@ -160,6 +154,7 @@ private: void* img_host_ = nullptr; int64_t img_bytes_ = 0; int64_t dec_bytes_ = 0; + std::vector rb_; std::vector out_; /* one per rank */ std::vector gout_; diff --git a/core/gen/pass.h b/core/gen/pass.h new file mode 100644 index 00000000..0577382d --- /dev/null +++ b/core/gen/pass.h @@ -0,0 +1,45 @@ +/* pass.h -- what the engine's pass loop needs of a generator's driver. + * + * A generator program is driven by passes rather than token steps (abi/rad_builder.h, + * rad_declare_generator and rad_declare_audio_generator). Each kind has its own driver, which turns + * its requests into passes (core/gen/driver.h for images, core/gen/audio_driver.h for audio); the + * loop that runs them on the ranks is one (Engine::gen_loop). The loop asks for the next pass, + * runs it on every rank, copies back what the driver names and hands the pass back. + */ +#pragma once +#include "rad_core.h" + +#include + +namespace rad { +namespace gen { + +struct IPassDriver { + /* A device buffer the staged pass leaves for the host: `bytes` from the start of `buf` on + * rank 0, copied to `host` behind the pass. Every rank holds the same values. */ + struct Readback { + rad_buf buf = RAD_NULL_HANDLE; + int64_t bytes = 0; + void* host = nullptr; + }; + + virtual ~IPassDriver() = default; + + /* The next pass, staged on every rank's stream, or null when there is nothing to run. + * `step` is the engine's pass counter, carried into RadBatch::step. */ + virtual const RadBatch* next(int step) = 0; + virtual const RadBatch* batch_for(int rank) const = 0; + /* What the staged pass's results are, valid until done(). */ + virtual const std::vector& readbacks() const = 0; + /* The pass has run on every rank, its streams are drained and the readbacks have landed. */ + virtual int done() = 0; + /* Fail every request queued or in flight, and refuse new ones. */ + virtual void shutdown(const char* why, int status) = 0; + + /* For /health, /stats and the dashboard. */ + virtual int64_t queued() const = 0; + virtual int64_t running() const = 0; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/video.h b/core/gen/video.h new file mode 100644 index 00000000..31b16b25 --- /dev/null +++ b/core/gen/video.h @@ -0,0 +1,97 @@ +/* video.h -- video generation: the request and the channel its video comes back on. + * + * A video generator (abi/rad_builder.h, rad_declare_video_generator) makes a video and its + * soundtrack in one denoising loop over a packed sequence, then decodes the soundtrack and the + * frames, a chunk of frames at a time. core/gen/video_driver.h turns a request into those passes; + * this is what a caller hands it and what it hands back: progress as the steps run, the + * soundtrack, the frames chunk by chunk in order, then the end. + */ +#pragma once +#include "rad_core.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace gen { + +/* One thing a request has made. */ +struct VideoEvent { + enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 }; + int kind = 0; + int32_t steps_done = 0; /* STEP: denoising steps finished */ + /* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */ + std::vector samples; + /* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */ + int32_t first = 0, n = 0; + std::vector rgb; +}; + +/* As Ticket (gen.h) is for an image: the driver thread writes, the caller reads. */ +class VideoTicket { +public: + /* driver side */ + void push(VideoEvent&& e); + void finish(int status, const std::string& why = std::string()); + + /* caller side: the next event, or false once the request has ended and every event was + * taken. Waits at most `ms` milliseconds; `*timed_out` marks a false that was a timeout. */ + bool next(VideoEvent* out, int ms, bool* timed_out); + bool finished() const; + int status() const; + std::string why() const; + + std::atomic cancel{false}; + + /* What the request makes, written by the driver at submit: the frames and their size, the + * steps, and the soundtrack's rate and channels. */ + int32_t frames = 0, width = 0, height = 0, steps = 0; + int64_t sample_rate = 0, channels = 0; + double fps = 0.0; + /* Usage, written by the driver before finish(): prompt tokens, rows a step and per-phase + * times. */ + int64_t in_tokens = 0, rows = 0; + int64_t t_submit_ns = 0, t_cond_ns = 0, t_denoised_ns = 0, t_done_ns = 0; + +private: + mutable std::mutex mu_; + std::condition_variable cv_; + std::deque q_; + bool done_ = false; + int status_ = RAD_OK; + std::string why_; +}; + +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 */ + uint64_t seed = 0; + std::shared_ptr ticket; +}; + +/* A request's shape under a declaration: frames, latent grid, soundtrack latents and the rows of + * a step. Shared by the driver and the server, which checks a request before preparing it. */ +struct VideoShape { + int32_t frames = 0, lat_frames = 0, lat_h = 0, lat_w = 0, n_audio = 0; + int64_t video_rows = 0, audio_rows = 0; +}; +VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks); + +/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each + * the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a + * trained schedule any other step count than n_rungs + 1 gives no steps. */ +struct VideoSchedule { + std::vector sig_v, sig_a; + int32_t steps = 0; +}; +VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps); + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp new file mode 100644 index 00000000..6cd179b8 --- /dev/null +++ b/core/gen/video_driver.cpp @@ -0,0 +1,665 @@ +/* video_driver.cpp -- the video generator's pass driver (video_driver.h), the ticket a caller + * waits on, and a request's shape and schedule (video.h). */ +#include "video_driver.h" + +#include +#include +#include + +namespace rad { +namespace gen { + +/* ================================================================== the ticket */ +void VideoTicket::push(VideoEvent&& e) { + { + std::lock_guard lk(mu_); + q_.push_back(std::move(e)); + } + cv_.notify_all(); +} + +void VideoTicket::finish(int status, const std::string& why) { + { + std::lock_guard lk(mu_); + if (done_) return; + done_ = true; + status_ = status; + why_ = why; + } + cv_.notify_all(); +} + +bool VideoTicket::next(VideoEvent* out, int ms, bool* timed_out) { + std::unique_lock lk(mu_); + if (timed_out) *timed_out = false; + if (q_.empty() && !done_) + cv_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return !q_.empty() || done_; }); + if (!q_.empty()) { + *out = std::move(q_.front()); + q_.pop_front(); + return true; + } + if (!done_ && timed_out) *timed_out = true; + return false; +} + +bool VideoTicket::finished() const { + std::lock_guard lk(mu_); + return done_ && q_.empty(); +} + +int VideoTicket::status() const { + std::lock_guard lk(mu_); + return status_; +} + +std::string VideoTicket::why() const { + std::lock_guard lk(mu_); + return why_; +} + +/* ================================================================== shape and schedule */ +VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, int32_t chunks) { + VideoShape s; + s.frames = (int32_t)(d.frames_per_chunk * chunks + d.frames_tail); + s.lat_frames = (int32_t)(d.latents_per_chunk * chunks + d.latents_tail); + s.lat_h = (int32_t)(height / d.latent_scale); + s.lat_w = (int32_t)(width / d.latent_scale); + /* round(frames / fps * audio_rate), ties to even as the reference's float round; with an + * integer numerator and denominator a tie is exact. */ + const int64_t num = (int64_t)s.frames * d.fps_den * d.audio_rate, den = d.fps_num; + int64_t q = num / den; + const int64_t r2 = 2 * (num % den); + if (r2 > den || (r2 == den && (q & 1))) ++q; + s.n_audio = (int32_t)q; + s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch); + s.audio_rows = d.audio_channels * (int64_t)s.n_audio; + return s; +} + +/* The shift of one base time, in f32 as the reference's tensor arithmetic. */ +static float shift_sigma(double shift, float b) { + const float sh = (float)shift, sh1 = (float)(shift - 1.0); + return (sh * b) / (1.0f + sh1 * b); +} + +/* torch.linspace(1, 0, n) in f32, which computes the first half up from the start and the + * second half down from the end, then the exponential shift, consecutive duplicates dropped. */ +static std::vector shifted_sigmas(double shift, int64_t n) { + std::vector s; + if (n < 2) return s; + const float start = 1.0f, end = 0.0f; + const float step = (end - start) / (float)(n - 1); + const int64_t half = n / 2; + for (int64_t i = 0; i < n; ++i) { + const float b = i < half ? start + step * (float)i : end - step * (float)(n - i - 1); + const float v = shift_sigma(shift, b); + if (s.empty() || v != s.back()) s.push_back(v); + } + return s; +} + +/* A trained schedule: each rung taken to f32 and shifted, then the terminal 0. */ +static std::vector rung_sigmas(double shift, const double* rungs, int32_t n) { + std::vector s; + for (int32_t i = 0; i < n; ++i) s.push_back(shift_sigma(shift, (float)rungs[i])); + s.push_back(0.0f); + return s; +} + +VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) { + VideoSchedule v; + if (d.n_rungs > 0) { + if (steps != d.n_rungs + 1) return v; + v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs); + v.sig_a = rung_sigmas(d.shift_audio, d.rungs, d.n_rungs); + v.steps = d.n_rungs; + return v; + } + v.sig_v = shifted_sigmas(d.shift_video, steps); + v.sig_a = shifted_sigmas(d.shift_audio, steps); + const size_t n = std::min(v.sig_v.size(), v.sig_a.size()); + v.steps = n > 0 ? (int32_t)(n - 1) : 0; + return v; +} + +/* ================================================================== sizing */ +namespace { + +constexpr int64_t kAlign = 256; + +int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } + +/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the + * allocation and the VRAM budget. */ +int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) { + const int64_t want[] = { + d.max_text * 4, /* R_TOK */ + d.max_text * 4, /* R_POS */ + 2 * 4, /* R_CU */ + 3 * max_tok * 4, /* R_ROPE: a step's rotary positions */ + RAD_VGEOM_N * 4, /* R_GEOM */ + 6 * 4, /* R_SCHED */ + d.max_steps * 4, /* R_TV */ + d.max_steps * 4, /* R_TA */ + 4 * 4, /* R_SEED */ + 4, /* R_LANE */ + 4, /* R_FIRST */ + 4 * 4, /* R_SEG */ + 4 * 4, /* R_LAT */ + }; + int64_t off = 0; + for (int r = 0; r < n; ++r) { + bytes[r][0] = off; + bytes[r][1] = want[r]; + off = align_up(off + want[r]); + } + return off; +} + +int64_t frames_bytes_of(const RadVideoGenDecl& d) { + return (d.frames_per_chunk + d.frames_tail) * d.max_area * 3; +} + +/* The samples a channel of a soundtrack under `frames` frames: its latents rounded up, which + * bounds the rounding video_shape does. */ +int64_t samples_of(const RadVideoGenDecl& d, int32_t frames) { + const int64_t num = (int64_t)frames * d.fps_den * d.audio_rate; + return (num / d.fps_num + 1) * (d.sample_rate / d.audio_rate); +} + +} /* namespace */ + +int64_t VideoDriver::device_bytes(const Program& prog) { + if (!prog.is_video_generator()) return 0; + int64_t b[R_N][2]; + return carve(prog.video_gen, prog.ctx.max_tok, b, R_N); +} + +int VideoDriver::init(const Program& prog, PositionsFn positions, + const std::vector& ranks) { + fini(); + if (!prog.is_video_generator()) return RAD_E_STATE; + decl_ = prog.video_gen; + rungs_ = prog.vgen_str.rungs; + decl_.rungs = rungs_.empty() ? nullptr : rungs_.data(); + name_ = prog.vgen_str.name; + ranks_ = ranks; + positions_ = positions; + max_tok_ = prog.ctx.max_tok; + if (!positions_) { + RAD_ERR("video generator '%s': the plugin exports no rad_arch_video_positions, which a " + "video generator must", name_.c_str()); + return RAD_E_UNSUPPORTED; + } + if (max_tok_ < decl_.max_text) { + RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens", + name_.c_str(), (long long)max_tok_, (long long)decl_.max_text); + return RAD_E_UNSUPPORTED; + } + int64_t b[R_N][2]; + bytes_ = carve(decl_, max_tok_, b, R_N); + for (int r = 0; r < R_N; ++r) { reg_[r].off = b[r][0]; reg_[r].bytes = b[r][1]; reg_[r].used = 0; } + + frames_bytes_ = frames_bytes_of(decl_); + audio_bytes_ = samples_of(decl_, (int32_t)(decl_.frames_per_chunk * decl_.max_chunks + + decl_.frames_tail)) * + decl_.audio_channels * 4; + host_ = static_cast(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); + frames_host_ = static_cast(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED)); + audio_host_ = static_cast(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED)); + if (!host_ || !frames_host_ || !audio_host_) { + RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + " + "%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_, + (long long)audio_bytes_); + return RAD_E_NOMEM; + } + std::memset(host_, 0, (size_t)bytes_); + dev_.assign(ranks_.size(), nullptr); + for (size_t r = 0; r < ranks_.size(); ++r) { + RAD_TRY(rad_dev_set(ranks_[r].device)); + dev_[r] = rad_dev_alloc(bytes_, RAD_MEM_DEVICE); + if (!dev_[r]) { + RAD_ERR("video generator: rank %zu has no room for the pass staging (%lld bytes)", r, + (long long)bytes_); + return RAD_E_NOMEM; + } + } + if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device)); + out_.assign(ranks_.size(), RadBatch{}); + vout_.assign(ranks_.size(), RadVideoGenBatch{}); + free_lanes_.clear(); + for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i); + return RAD_OK; +} + +void VideoDriver::fini() { + for (size_t r = 0; r < dev_.size(); ++r) + if (dev_[r]) { + if (r < ranks_.size()) rad_dev_set(ranks_[r].device); + rad_dev_free(dev_[r], RAD_MEM_DEVICE); + } + dev_.clear(); + if (!ranks_.empty()) rad_dev_set(ranks_[0].device); + if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED); + if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED); + if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED); + host_ = nullptr; + frames_host_ = nullptr; + audio_host_ = nullptr; +} + +/* ================================================================== requests */ +int VideoDriver::submit(std::unique_ptr r, std::string* why) { + if (!r || !r->ticket) return RAD_E_INVAL; + const RadVideoGenDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + const int64_t T = (int64_t)r->tokens.size(); + if (T < 1 || T > d.max_text) + return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." + + std::to_string(d.max_text)); + if (r->chunks < d.min_chunks || r->chunks > d.max_chunks) + return no("the length must be " + std::to_string(d.min_chunks) + ".." + + std::to_string(d.max_chunks) + " chunks"); + const int64_t W = r->width, H = r->height; + if (W % d.size_multiple || H % d.size_multiple || W < d.min_side || H < d.min_side || + W * H > d.max_area || std::max(W, H) > d.max_aspect * std::min(W, H)) + return no("the size " + std::to_string(W) + "x" + std::to_string(H) + " is not one this " + "model makes: sides multiples of " + std::to_string(d.size_multiple) + " from " + + std::to_string(d.min_side) + ", at most " + std::to_string(d.max_area) + + " pixels, the long side at most " + std::to_string(d.max_aspect) + + " times the short"); + const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps; + if (d.n_rungs > 0 && steps != d.n_rungs + 1) + return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model " + "runs the schedule it was trained on, " + std::to_string(d.n_rungs) + + " evaluations"); + if (steps < 2 || steps > d.max_steps) + return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + " (sigma grid " + "points, the last one 0)"); + + auto j = std::make_unique(); + const VideoShape s = video_shape(d, r->width, r->height, r->chunks); + j->geom.n_text = (int32_t)T; + j->geom.frames = s.frames; + j->geom.lat_frames = s.lat_frames; + j->geom.lat_h = s.lat_h; + j->geom.lat_w = s.lat_w; + j->geom.n_audio = s.n_audio; + j->rows = T + s.audio_rows + s.video_rows; + if (j->rows > max_tok_) + return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass " + "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video"); + const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0); + const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0); + if (nr != j->rows || nd <= 0 || nd > max_tok_) + return no("the model lays this video out in " + std::to_string(nr) + " step rows and " + + std::to_string(nd) + " decoder rows, which this server cannot run"); + j->dec_rows = nd; + j->pos.assign((size_t)(3 * nr), 0.0f); + if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr) + return no("the model could not lay this video out"); + j->sched = video_schedule(d, steps); + if (j->sched.steps < 1) return no("the schedule has no steps"); + j->n_chunks = r->chunks; + j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate); + + VideoTicket& t = *r->ticket; + t.frames = s.frames; + t.width = r->width; + t.height = r->height; + t.steps = j->sched.steps; + t.sample_rate = d.sample_rate; + t.channels = d.audio_channels; + t.fps = (double)d.fps_num / (double)d.fps_den; + t.in_tokens = T; + t.rows = j->rows; + t.t_submit_ns = (int64_t)rad_mono_ns(); + std::lock_guard lk(mu_); + if (closed_) { + if (why) *why = closed_why_; + return closed_status_; + } + j->id = next_id_++; + j->req = std::move(r); + jobs_.push_back(std::move(j)); + return RAD_OK; +} + +void VideoDriver::shutdown(const char* why, int status) { + std::lock_guard lk(mu_); + closed_ = true; + closed_why_ = why ? why : "the engine stopped"; + closed_status_ = status; + for (auto& j : jobs_) j->req->ticket->finish(status, closed_why_); +} + +int64_t VideoDriver::queued() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (!j->admitted) ++n; + return n; +} + +int64_t VideoDriver::running() const { + std::lock_guard lk(mu_); + int64_t n = 0; + for (const auto& j : jobs_) if (j->admitted) ++n; + return n; +} + +VideoDriver::Job* VideoDriver::job_locked(uint64_t id) { + for (auto& j : jobs_) if (j->id == id) return j.get(); + return nullptr; +} + +void VideoDriver::release_locked(Job& j) { + if (j.lane >= 0) { + free_lanes_.push_back(j.lane); + j.lane = -1; + } +} + +void VideoDriver::fail_locked(Job& j, int status, const std::string& why) { + j.failed = true; + j.req->ticket->finish(status, why); +} + +/* In arrival order: a request needs only a lane. */ +void VideoDriver::admit_locked() { + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted || j.failed) continue; + if (free_lanes_.empty()) break; + j.lane = free_lanes_.back(); + free_lanes_.pop_back(); + j.admitted = true; + } +} + +/* ================================================================== staging */ +int VideoDriver::upload() { + for (size_t r = 0; r < ranks_.size(); ++r) + for (int g = 0; g < R_N; ++g) { + if (reg_[g].used <= 0) continue; + RAD_TRY(rad_memcpy_async((char*)dev_[r] + reg_[g].off, host_ + reg_[g].off, + reg_[g].used, ranks_[r].stream)); + } + return RAD_OK; +} + +/* The geometry a pass's ops read off the device (RAD_VGEOM_*), with chunk `chunk`'s span when it + * is a decode's. */ +void VideoDriver::stage_geom(const Job& j, int32_t chunk) { + int32_t* g = hptr(R_GEOM); + std::memset(g, 0, RAD_VGEOM_N * 4); + g[RAD_VGEOM_LAT_FRAMES] = j.geom.lat_frames; + g[RAD_VGEOM_LAT_H] = j.geom.lat_h; + g[RAD_VGEOM_LAT_W] = j.geom.lat_w; + g[RAD_VGEOM_N_TEXT] = j.geom.n_text; + g[RAD_VGEOM_N_AUDIO] = j.geom.n_audio; + g[RAD_VGEOM_CHUNK_LAT0] = (int32_t)(decl_.latents_per_chunk * chunk); + g[RAD_VGEOM_CHUNK_FRAMES] = (int32_t)decl_.dec_latents; + g[RAD_VGEOM_CHUNK_H] = j.geom.lat_h; + g[RAD_VGEOM_CHUNK_W] = j.geom.lat_w; + g[RAD_VGEOM_CHUNK_FIRST] = chunk == 0; + g[RAD_VGEOM_CHUNK_LAST] = chunk == j.n_chunks - 1; + g[RAD_VGEOM_PATCH_FRAMES] = (int32_t)decl_.dec_latents; + g[RAD_VGEOM_PATCH_H] = (int32_t)(j.geom.lat_h / decl_.patch); + g[RAD_VGEOM_PATCH_W] = (int32_t)(j.geom.lat_w / decl_.patch); + reg_[R_GEOM].used = RAD_VGEOM_N * 4; + const int64_t audio_rows = decl_.audio_channels * (int64_t)j.geom.n_audio; + const int64_t video_rows = j.rows - j.geom.n_text - audio_rows; + *hptr(R_LANE) = j.lane; + *hptr(R_FIRST) = j.step == 0; + int32_t* seg = hptr(R_SEG); + seg[0] = 0; + seg[1] = j.geom.n_text; + seg[2] = (int32_t)(j.geom.n_text + audio_rows); + seg[3] = (int32_t)j.rows; + int32_t* lat = hptr(R_LAT); + lat[0] = 0; + lat[1] = (int32_t)video_rows; + lat[2] = 0; + lat[3] = (int32_t)audio_rows; + reg_[R_LANE].used = 4; + reg_[R_FIRST].used = 4; + reg_[R_SEG].used = 4 * 4; + reg_[R_LAT].used = 4 * 4; +} + +void VideoDriver::base_batches(const Job& j, int64_t n_tok, int step) { + for (size_t r = 0; r < ranks_.size(); ++r) { + RadBatch& B = out_[r]; + RadVideoGenBatch& V = vout_[r]; + const int ri = (int)r; + B = RadBatch{}; + B.step = step; + B.phase = RAD_PHASE_PREFILL; + B.n_tok = n_tok; + B.n_seq = 1; + B.max_q_len = (int32_t)n_tok; + B.max_q_len_prefill = (int32_t)n_tok; + B.token_ids = dptr(ri, R_TOK); + B.positions = dptr(ri, R_POS); + B.cu_seqlens = dptr(ri, R_CU); + V = RadVideoGenBatch{}; + V.lane = j.lane; + V.geom = j.geom; + V.geom_d = dptr(ri, R_GEOM); + V.lane_d = dptr(ri, R_LANE); + V.first_d = dptr(ri, R_FIRST); + V.seg_cu = dptr(ri, R_SEG); + 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.sched = dptr(ri, R_SCHED); + V.pos = dptr(ri, R_ROPE); + V.seed = dptr(ri, R_SEED); + V.chunk = j.chunk; + V.n_chunks = j.n_chunks; + V.dec_rows = j.dec_rows; + V.n_samples = j.n_samples; + B.vgen_b = &V; + } +} + +/* ================================================================== the passes */ +const RadBatch* VideoDriver::next(int step) { + std::lock_guard lk(mu_); + pass_ = Pass{}; + rb_.clear(); + if (closed_) return nullptr; + /* Retire finished, failed and cancelled jobs, returning their lanes before admitting. Safe + * because next() runs between passes, with nothing in flight. */ + for (auto it = jobs_.begin(); it != jobs_.end();) { + Job& j = **it; + const bool cancelled = j.req->ticket->cancel.load(std::memory_order_acquire); + if (!(j.failed || cancelled || j.finished)) { ++it; continue; } + if (cancelled && !j.failed && !j.finished) + j.req->ticket->finish(RAD_E_CANCELLED, "the request was cancelled"); + release_locked(j); + it = jobs_.erase(it); + } + admit_locked(); + + /* 1. The decodes of a denoised lane: the soundtrack, then the chunks in order. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (!j.admitted || j.failed || j.step < j.sched.steps) continue; + if (!j.audio_done) return build_audio(j, step); + if (j.chunk < j.n_chunks) return build_chunk(j, step); + } + /* 2. A prompt. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step); + } + /* 3. The oldest lane's next step. */ + for (auto& jp : jobs_) { + Job& j = *jp; + if (j.admitted && !j.failed && j.cond_done && j.step < j.sched.steps) + return build_step(j, step); + } + return nullptr; +} + +const RadBatch* VideoDriver::batch_for(int rank) const { + if (rank < 0 || (size_t)rank >= out_.size() || pass_.kind == 0) return nullptr; + return &out_[(size_t)rank]; +} + +const RadBatch* VideoDriver::build_cond(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int64_t T = j.geom.n_text; + int32_t* tok = hptr(R_TOK); + int32_t* pos = hptr(R_POS); + std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4); + for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i; + int32_t* cu = hptr(R_CU); + cu[0] = 0; + cu[1] = (int32_t)T; + float* tv = hptr(R_TV); + float* ta = hptr(R_TA); + for (int32_t i = 0; i < j.sched.steps; ++i) { + tv[i] = 1.0f - j.sched.sig_v[(size_t)i]; + ta[i] = 1.0f - j.sched.sig_a[(size_t)i]; + } + reg_[R_TOK].used = T * 4; + reg_[R_POS].used = T * 4; + reg_[R_CU].used = 2 * 4; + reg_[R_TV].used = j.sched.steps * 4; + reg_[R_TA].used = j.sched.steps * 4; + stage_geom(j, 0); + if (upload() < 0) return nullptr; + base_batches(j, T, step); + for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND; + pass_.kind = RAD_GEN_PASS_VCOND; + pass_.job = j.id; + return &out_[0]; +} + +const RadBatch* VideoDriver::build_step(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + const int32_t i = j.step; + float* s = hptr(R_SCHED); + s[0] = 1.0f - j.sched.sig_v[(size_t)i]; + s[1] = j.sched.sig_v[(size_t)i]; + s[2] = j.sched.sig_v[(size_t)i + 1]; + s[3] = 1.0f - j.sched.sig_a[(size_t)i]; + s[4] = j.sched.sig_a[(size_t)i]; + s[5] = j.sched.sig_a[(size_t)i + 1]; + reg_[R_SCHED].used = 6 * 4; + std::memcpy(hptr(R_ROPE), j.pos.data(), j.pos.size() * 4); + reg_[R_ROPE].used = (int64_t)j.pos.size() * 4; + /* The video's noise seed is the request's; the soundtrack's the same with its top bit flipped, + * so the two streams never coincide. */ + uint32_t* sd = hptr(R_SEED); + const uint64_t seed = j.req->seed; + sd[0] = (uint32_t)seed; + sd[1] = (uint32_t)(seed >> 32); + sd[2] = (uint32_t)seed; + sd[3] = (uint32_t)(seed >> 32) ^ 0x80000000u; + reg_[R_SEED].used = 4 * 4; + /* The packed sequence is one attention document. */ + int32_t* cu = hptr(R_CU); + cu[0] = 0; + cu[1] = (int32_t)j.rows; + reg_[R_CU].used = 2 * 4; + stage_geom(j, 0); + if (upload() < 0) return nullptr; + base_batches(j, j.rows, step); + for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; + pass_.kind = RAD_GEN_PASS_VSTEP; + pass_.job = j.id; + return &out_[0]; +} + +const RadBatch* VideoDriver::build_audio(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + stage_geom(j, 0); + if (upload() < 0) return nullptr; + base_batches(j, 0, step); + for (auto& B : out_) B.gen = RAD_GEN_PASS_ADECODE; + rb_.assign(1, Readback{ decl_.audio_out, j.n_samples * decl_.audio_channels * 4, audio_host_ }); + pass_.kind = RAD_GEN_PASS_ADECODE; + pass_.job = j.id; + return &out_[0]; +} + +const RadBatch* VideoDriver::build_chunk(Job& j, int step) { + for (int g = 0; g < R_N; ++g) reg_[g].used = 0; + stage_geom(j, j.chunk); + if (upload() < 0) return nullptr; + base_batches(j, j.dec_rows, step); + const bool last = j.chunk == j.n_chunks - 1; + const int32_t n = (int32_t)(decl_.frames_per_chunk + (last ? decl_.frames_tail : 0)); + for (size_t r = 0; r < out_.size(); ++r) { + out_[r].gen = RAD_GEN_PASS_VDECODE; + vout_[r].n_frames_out = n; + } + const int64_t bytes = (int64_t)n * j.req->height * j.req->width * 3; + rb_.assign(1, Readback{ decl_.frames_out, bytes, frames_host_ }); + pass_.kind = RAD_GEN_PASS_VDECODE; + pass_.job = j.id; + pass_.n_frames = n; + return &out_[0]; +} + +int VideoDriver::done() { + std::lock_guard lk(mu_); + const int64_t now = (int64_t)rad_mono_ns(); + Job* j = job_locked(pass_.job); + switch (j ? pass_.kind : 0) { + case RAD_GEN_PASS_VCOND: + j->cond_done = true; + j->req->ticket->t_cond_ns = now; + break; + case RAD_GEN_PASS_VSTEP: { + ++j->step; + VideoEvent e; + e.kind = VideoEvent::STEP; + e.steps_done = j->step; + j->req->ticket->push(std::move(e)); + if (j->step >= j->sched.steps) j->req->ticket->t_denoised_ns = now; + break; + } + case RAD_GEN_PASS_ADECODE: { + VideoEvent e; + e.kind = VideoEvent::AUDIO; + e.samples.assign(audio_host_, audio_host_ + j->n_samples * decl_.audio_channels); + j->req->ticket->push(std::move(e)); + j->audio_done = true; + break; + } + case RAD_GEN_PASS_VDECODE: { + VideoEvent e; + e.kind = VideoEvent::FRAMES; + e.first = j->frames_out; + e.n = pass_.n_frames; + const size_t bytes = (size_t)pass_.n_frames * j->req->height * j->req->width * 3; + e.rgb.assign(frames_host_, frames_host_ + bytes); + j->req->ticket->push(std::move(e)); + j->frames_out += pass_.n_frames; + if (++j->chunk == j->n_chunks) { + j->finished = true; + j->req->ticket->t_done_ns = now; + j->req->ticket->finish(RAD_OK); + } + break; + } + default: + break; + } + pass_ = Pass{}; + rb_.clear(); + return RAD_OK; +} + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h new file mode 100644 index 00000000..ce97876f --- /dev/null +++ b/core/gen/video_driver.h @@ -0,0 +1,141 @@ +/* video_driver.h -- the video generator's pass driver (video.h; abi/rad_builder.h's + * RadVideoGenDecl describes the passes). + * + * Driven by the engine thread like the other drivers (driver.h): `next()` picks and stages a + * pass, `done()` folds its result back once every rank has run it. Requests arrive from HTTP + * threads through `submit()` and leave through their VideoTicket. + * + * A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary + * positions are fixed at submit, so nothing is computed between passes but the staging. + * + * Pass priority, one pass at a time: + * + * 1. ADECODE, then each VDECODE chunk in order, of a lane whose denoising is done: they finish + * a request and free its lane. + * 2. VCOND of an admitted request, so its steps can follow the current request's without a gap. + * 3. VSTEP of the oldest lane with steps left. Requests are denoised one after another, not in + * turns: a pass is one request's whole sequence, so taking turns would only delay the first. + */ +#pragma once +#include "video.h" +#include "pass.h" +#include "device/device.h" + +#include + +namespace rad { +namespace gen { + +class VideoDriver final : public IPassDriver { +public: + struct RankIO { + int device = 0; + RadStream stream = nullptr; + }; + using PositionsFn = int64_t (*)(int, const RadVideoGeom*, float*, int64_t); + + /* `positions` is the plugin's rad_arch_video_positions. */ + int init(const Program& prog, PositionsFn positions, const std::vector& ranks); + void fini(); + ~VideoDriver() override { fini(); } + + /* The bytes init() allocates on each rank's card, for the VRAM budget. */ + static int64_t device_bytes(const Program& prog); + + /* ---------------------------------------------------------- HTTP threads */ + /* Queue a request, refused at once with `why` when it can never run. */ + int submit(std::unique_ptr r, std::string* why); + const RadVideoGenDecl& decl() const { return decl_; } + void shutdown(const char* why, int status) override; + + /* ---------------------------------------------------------- the engine thread */ + const RadBatch* next(int step) override; + const RadBatch* batch_for(int rank) const override; + const std::vector& readbacks() const override { return rb_; } + int done() override; + + int64_t queued() const override; + int64_t running() const override; + +private: + struct Job { + uint64_t id = 0; + std::unique_ptr req; + RadVideoGeom geom{}; + int64_t rows = 0, dec_rows = 0; + int32_t n_chunks = 0; + int64_t n_samples = 0; /* the soundtrack's samples a channel */ + VideoSchedule sched; + std::vector pos; /* [3, rows] */ + int32_t lane = -1; + bool admitted = false; + bool cond_done = false; + int32_t step = 0; /* steps done */ + bool audio_done = false; + int32_t chunk = 0; /* chunks decoded */ + int32_t frames_out = 0; /* frames handed to the caller */ + bool failed = false; + bool finished = false; + }; + /* The pass in flight, for done(). */ + struct Pass { + int kind = 0; + uint64_t job = 0; + int32_t n_frames = 0; + }; + + /* Staging regions: their offsets in the host span and every rank's slab. */ + struct Region { int64_t off = 0, bytes = 0, used = 0; }; + enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST, + R_SEG, R_LAT, R_N }; + + template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } + template T* dptr(int rank, int r) const { + return reinterpret_cast((char*)dev_[(size_t)rank] + reg_[r].off); + } + int upload(); + void base_batches(const Job& j, int64_t n_tok, int step); + void stage_geom(const Job& j, int32_t chunk); + + void admit_locked(); + void release_locked(Job& j); + void fail_locked(Job& j, int status, const std::string& why); + Job* job_locked(uint64_t id); + + const RadBatch* build_cond(Job& j, int step); + const RadBatch* build_step(Job& j, int step); + const RadBatch* build_audio(Job& j, int step); + const RadBatch* build_chunk(Job& j, int step); + + RadVideoGenDecl decl_{}; + std::vector rungs_; /* decl_.rungs points here */ + std::string name_; + PositionsFn positions_ = nullptr; + int64_t max_tok_ = 0; + std::vector ranks_; + + char* host_ = nullptr; /* pinned, same layout as each slab */ + int64_t bytes_ = 0; + std::vector dev_; + Region reg_[R_N]; + uint8_t* frames_host_ = nullptr; + int64_t frames_bytes_ = 0; + float* audio_host_ = nullptr; + int64_t audio_bytes_ = 0; + std::vector rb_; + + std::vector out_; /* one per rank */ + std::vector vout_; + Pass pass_; + + mutable std::mutex mu_; + std::deque> jobs_; /* arrival order */ + std::vector free_lanes_; + uint64_t next_id_ = 1; + bool closed_ = false; + std::string closed_why_; + int closed_status_ = RAD_E_STATE; +}; + +} /* namespace gen */ +} /* namespace rad */ diff --git a/core/lora/config.h b/core/lora/config.h index 924ee32b..fa8ad018 100644 --- a/core/lora/config.h +++ b/core/lora/config.h @@ -2,11 +2,9 @@ * --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager * (what may be loaded into them) and by nothing else. * - * OFF UNLESS ASKED FOR: with no adapter named and no --max-loras, `enabled()` is false, declare - * appends nothing, the program has no pool and no extra op, and the engine computes exactly what it - * computed before this file existed. */ + * Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare + * appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */ #pragma once -#include #include #include #include @@ -20,11 +18,9 @@ struct LoraConfig { int max_loras = 0; /* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */ int max_rank = 16; - /* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for. Empty: - * the union of the startup adapters' target_modules, or -- with no startup adapter -- every - * LoRA-capable trunk linear (`all_linear`). */ - std::set targets; - bool all_linear = false; + /* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted + * and unique. Empty: the union of the startup adapters' target_modules. */ + std::vector targets; bool enabled() const { return max_loras > 0 || !adapters.empty(); } int slots() const { diff --git a/core/lora/declare.cpp b/core/lora/declare.cpp index 20a5d158..970e0f7f 100644 --- a/core/lora/declare.cpp +++ b/core/lora/declare.cpp @@ -28,6 +28,38 @@ bool is_coded(uint32_t dt) { return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_I8; } +/* The block of a scale stream of `blocks` groups over `ext` elements, as the kernel libraries + * read one (libref/ref_gemm.h's grid_block): the power of two whose ceiling division gives + * `blocks`, else the plain ceiling; one group is the whole extent. */ +int64_t grid_block(int64_t ext, int64_t blocks) { + if (ext <= 0) return 1; + if (blocks <= 1) return ext; + const int64_t lo = (ext + blocks - 1) / blocks; + int64_t b = 1; + while (b < lo) b <<= 1; + return (ext + b - 1) / b == blocks ? b : lo; +} + +/* The scale grid of a coded activation the GEMM `reads`: the read set's one f32 buffer beside + * the codes (reads[0]), [rows, groups] or one scale a row, over the codes' full width. The + * GEMM's own `group` is the weight's (an MXFP4 weight's 32-wide exponent block reads an + * activation scaled per 128), and a GEMM may read a column span of the activation, so neither + * its `group` nor its K gives the activation's grid. 0 when the stream is not one f32 buffer. */ +int64_t activation_grid(const Program& P, const std::vector& reads) { + const RadBufDecl& a = P.buffers[reads[0]].decl; + const RadBufDecl* s = nullptr; + for (size_t i = 1; i < reads.size(); ++i) { + const RadBufDecl& d = P.buffers[reads[i]].decl; + if (d.dtype != RAD_F32) continue; + if (s) return 0; + s = &d; + } + if (!s || a.rank < 1 || s->rank < 1) return 0; + const int64_t width = a.shape[a.rank - 1]; + const int64_t groups = s->rank >= 2 ? s->shape[s->rank - 1] : 1; + return groups > 0 ? grid_block(width, groups) : 0; +} + rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32_t rank, const int64_t* shape) { RadBufDecl d{}; @@ -44,6 +76,16 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32 int lora_declare(Builder& b, const LoraDeclare& d) { if (!d.cfg || !d.cfg->enabled()) return RAD_OK; Program& P = b.program(); + /* Adapters are chosen per request and applied on the token steps of a model that writes + * logits; a generator's passes and an embedding model's requests carry no adapter. */ + if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE || + P.logits_buf == RAD_NULL_HANDLE) { + RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s", + P.is_pass_driven() ? "is an image, audio or video generator" + : P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings" + : "declares no logits"); + return RAD_E_UNSUPPORTED; + } const int S = d.cfg->slots(); const int max_rank = d.cfg->max_rank; const int64_t max_tok = P.ctx.max_tok; @@ -53,10 +95,8 @@ int lora_declare(Builder& b, const LoraDeclare& d) { return RAD_E_INVAL; } - /* EVERY READER OF A TARGETED WEIGHT CARRIES THE DELTA, OR STARTUP REFUSES. A targeted weight - * that some op multiplies without the adapter is a model that is the base in one place and the - * adapter in another, and the text it writes is wrong in a way no test of the targeted GEMM - * would show. */ + /* Every reader of a targeted weight carries the delta, or startup refuses: a weight some op + * multiplies without the adapter would be the base in one place and the adapter in another. */ std::vector bad; int s = lora::find_unsupported_uses(P, d.targets, &bad); if (s < 0) return s; @@ -110,10 +150,10 @@ int lora_declare(Builder& b, const LoraDeclare& d) { } } - /* ---- t = A.x, one f32 plane per capacity R and lane. PERSIST and not TRANSIENT: the ops that - * use it are issued inside the GEMM's issue, at the GEMM's position, while the buffer plan would - * place a transient by the appended ops' own position at the end of the program -- and share - * its bytes with whatever is live there. */ + /* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that + * use it run at the GEMM's position, but the buffer plan would place a transient at the + * appended ops' own position, the end of the program, and share its bytes with buffers live + * mid-program. */ std::map t_by_r; P.lora_t.clear(); for (const lora::Site& x : sites) { @@ -136,14 +176,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) { const uint32_t gh = x.gemm; if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE; if (!b.op_resolved(gh)) continue; /* never handed to the plugin, so never issued */ - /* Copied out first: decl_op below appends to P.ops and moves every OpInfo. */ + /* Copied out first: decl_op below appends to P.ops, which may move every OpInfo. */ const OpInfo& g = P.ops[gh]; const std::string gop = g.op; const std::string rkey = g.ranged_key; const int64_t lo = g.range_lo, hi = g.range_hi; - long long gk = 0, gn = 0, gg = 0; + long long gk = 0, gn = 0; const bool has_k = g.base.get_i("K", &gk), has_n = g.base.get_i("N", &gn); - const bool has_group = g.base.get_i("group", &gg) && gg > 0; const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y"); const std::vector reads = b.op_read_set(gh), writes = b.op_write_set(gh); @@ -167,6 +206,12 @@ int lora_declare(Builder& b, const LoraDeclare& d) { const uint32_t y_dt = P.buffers[writes[0]].decl.dtype; const bool coded = is_coded(a_dt); if (coded && oas < 0) { refuse("a coded activation and no `a_scale` operand"); continue; } + const int64_t a_grid = coded ? activation_grid(P, reads) : 0; + if (coded && a_grid <= 0) { + refuse("a coded activation whose read set holds no single f32 scale stream beside the " + "codes, so the grid lora_shrink reads it at is not known at declare"); + continue; + } RadParam sp[6]; int n_sp = 0; @@ -174,7 +219,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) { sp[n_sp++] = RAD_INT("K", x.K_r); sp[n_sp++] = RAD_INT("R", x.R); sp[n_sp++] = RAD_INT("S", S); - if (coded && has_group) sp[n_sp++] = RAD_INT("group", gg); + if (coded) sp[n_sp++] = RAD_INT("group", a_grid); sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt)); const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0); @@ -200,10 +245,6 @@ int lora_declare(Builder& b, const LoraDeclare& d) { P.ops[he].anchor = (int32_t)gh; P.ops[gh].lora_site = (int32_t)P.lora_sites.size(); P.lora_sites.push_back(is); - - x.lora_shrink = hs; x.lora_expand = he; - const LoraPool& lp = P.lora_pools[(size_t)x.pool]; - x.pool_a = lp.a; x.pool_b = lp.b; x.pool_scale = lp.scale; } if (n_refused) return RAD_E_UNSUPPORTED; diff --git a/core/lora/declare.h b/core/lora/declare.h index e5f00d4b..3504fc88 100644 --- a/core/lora/declare.h +++ b/core/lora/declare.h @@ -2,9 +2,9 @@ * its program, build the sites (lora.h), declare the adapter pools and the two ops each targeted * GEMM is followed by, and record what the issue path needs (Program::lora_sites). * - * Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, on the real - * declare AND on every sizing declare -- identically, because a sizing declare must produce the - * same op list (rad_builder.cpp checks it op by op). */ + * Runs inside rad_tools_declare, after rad_arch_declare and before the sampler, identically on the + * real declare and on every sizing declare, which must produce the same op list (rad_builder.cpp + * checks it op by op). */ #pragma once #include "lora/config.h" #include "lora/lora.h" diff --git a/core/lora/lora.cpp b/core/lora/lora.cpp index e4d824f2..777d625c 100644 --- a/core/lora/lora.cpp +++ b/core/lora/lora.cpp @@ -130,7 +130,7 @@ struct MapIndex { } }; -/* THE predicate, over the maps already found. */ +/* weight_targeted(), over the maps already found. */ bool targeted_core(const Program& prog, const WeightInfo& w, const std::vector& maps, const TargetSet& targets) { if (targets.empty() || maps.empty()) return false; @@ -190,11 +190,6 @@ rad_weight b_weight(const OpInfo& op) { return op.weights.empty() ? 0 : op.weights[0]; } -void fnv(uint64_t* h, const void* p, size_t n) { - const uint8_t* b = static_cast(p); - for (size_t i = 0; i < n; ++i) { *h ^= b[i]; *h *= 1099511628211ull; } -} - bool read_file(const std::string& path, std::string* out) { std::ifstream f(path, std::ios::binary); if (!f) return false; @@ -339,11 +334,9 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, Site s; s.gemm = op_index; s.op = op.op; - s.w = wh; s.weight = W.name; s.shard = W.decl.shard; s.max_rank = max_rank; - s.res_unchecked = op.op == "gemm_nt_bias"; if (W.decl.rank != 2) return fail(err, RAD_E_SHAPE, fmt("weight '%s' is rank %u; a LoRA site needs a matrix", @@ -425,8 +418,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, int64_t N_full = 0; for (int64_t t : s.part_total) N_full = (t > 0 && N_full >= 0) ? N_full + t : -1; - /* ---- THE LOADER'S OWN FUNCTION AGREES, or this is not a site. weight_share is what puts the - * base weight's bytes on this rank; asked for a plain [N_full, K_full] entry it must name the + /* ---- the loader's own cut must agree, or this is not a site: weight_share, which puts the + * base weight's bytes on this rank, must name for a plain [N_full, K_full] entry the * rectangles this geometry names. */ if (N_full > 0 && s.K_full > 0) { WeightInfo v = W; @@ -483,7 +476,7 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, srcs.push_back(m->src[k] ? m->src[k] : ""); } if (alternatives) { - /* COPY with alternatives: the first one the container holds IS the weight, and which one + /* COPY with alternatives: the first one the container holds is the weight, and which one * that is is not recorded. Usable only when exactly one alternative is targeted. */ std::vector hit; for (const std::string& x : srcs) { @@ -580,6 +573,15 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s return no(fmt("gemm_nt_q over rotated parts (pb1=%lld pb2=%lld): its input is the " "rotated activation", p1, p2)); } + if (gq || gqb) { + /* At w4a8, w8a8 and w2a8 `a` is quant_act_i8's codes in the int8 WMMA's step order (the + * middle dwords of every 16-byte step exchanged, docs/OPS.md), which lora_shrink would + * read as the activation's columns. */ + const char* dt = op.base.get_s("dtype"); + if (dt && (!std::strcmp(dt, "w4a8") || !std::strcmp(dt, "w8a8") || !std::strcmp(dt, "w2a8"))) + return no(fmt("%s at %s reads quant_act_i8's codes in the int8 WMMA's step order, not " + "in the activation's column order", op.op.c_str(), dt)); + } const WeightInfo& w = prog.weights[b]; if (gq || gqb) { long long k = 0; @@ -607,7 +609,7 @@ int find_unsupported_uses(const Program& prog, const TargetSet& targets, const bool site = op_is_site(prog, op, &b, &why); for (rad_weight h : op.weights) { if (!targeted_idx(prog, mi, h, targets)) continue; - /* Every view of a targeted weight read by a site over the SAME logical weight is the + /* Every view of a targeted weight read by a site over the same logical weight is the * site's own (codes, scale, ref). Anything else reading it is not a site. */ if (site && b && prog.weights[b].source == prog.weights[h].source) continue; UnsupportedUse u; @@ -669,32 +671,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank, return RAD_OK; } -TargetSet all_capable_targets(const Program& prog) { - std::set leaves; - for (size_t h = 1; h < prog.weights.size(); ++h) { - const WeightInfo& w = prog.weights[h]; - if (excluded_weight(prog, w)) continue; - std::vector maps; - scan_maps(prog, w.source, &maps); - for (const RadNameMap* m : maps) - for (int k = 0; k < m->n_src && k < 8; ++k) { - std::string leaf; - const std::string src = m->src[k] ? m->src[k] : ""; - if (!module_of(src, &leaf).empty() && !excluded_source(src)) leaves.insert(leaf); - } - } - TargetSet ok; - for (const std::string& l : leaves) { - const TargetSet one{ l }; - std::vector s; - std::string e; - if (find_unsupported_uses(prog, one, nullptr) == 0 && build_sites(prog, one, 1, &s, &e) == RAD_OK && - !s.empty()) - ok.insert(l); - } - return ok; -} - std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) { const std::string want[3] = { module, @@ -817,6 +793,17 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max if (truthy("trainable_token_indices")) return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": trainable_token_indices -- embedding " "updates are not served"); + /* PEFT options that change the forward pass itself, not only the weights. */ + if (truthy("layer_replication")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": layer_replication -- an adapter over " + "repeated base layers is not served"); + if (truthy("use_qalora")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": use_qalora -- QA-LoRA's pooled input is " + "not served"); + if (truthy("alora_invocation_tokens")) + return fail(err, RAD_E_UNSUPPORTED, cfg_path + ": alora_invocation_tokens -- an activated " + "LoRA, which applies only after its " + "invocation, is not served"); if (!cfg.contains("r") || !cfg["r"].is_number_integer() || cfg["r"].get() <= 0) return fail(err, RAD_E_FORMAT, cfg_path + ": no positive integer `r`"); if (!cfg.contains("lora_alpha") || !cfg["lora_alpha"].is_number()) @@ -833,6 +820,9 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max else if (t.is_array()) for (const ojson& x : t) if (x.is_string()) info->target_modules.push_back(x.get()); } + /* PEFT's get_pattern_key: a key matches a module whose name ends in it on a dot boundary, + * `(.*\.)?(key)$` from the start of the name, and the first matching key in the file's order + * wins. */ struct Pat { std::string key; std::regex re; double v; }; std::vector rpat, apat; for (const char* which : { "rank_pattern", "alpha_pattern" }) { @@ -846,14 +836,17 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max Pat p; p.key = it.key(); try { - p.re = std::regex(p.key, std::regex::ECMAScript); + p.re = std::regex("(.*\\.)?(" + p.key + ")$", std::regex::ECMAScript); } catch (const std::regex_error& e) { return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + " key '" + p.key + "' is not a regex this engine reads (" + e.what() + ")"); } p.v = it.value().get(); + if (!std::isfinite(p.v)) + return fail(err, RAD_E_FORMAT, cfg_path + ": " + which + "[" + p.key + + "] is not a finite number"); if (!std::strcmp(which, "rank_pattern")) { - if (!it.value().is_number_integer() || p.v <= 0) + if (!it.value().is_number_integer() || p.v <= 0 || p.v > (double)INT32_MAX) return fail(err, RAD_E_FORMAT, cfg_path + ": rank_pattern[" + p.key + "] is not a positive integer"); info->rank_pattern.push_back({ p.key, (int64_t)p.v }); @@ -873,19 +866,10 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max "adapter as safetensors"); if (st.open(st_path) != RAD_OK) return fail(err, RAD_E_IO, st_path + ": cannot open as safetensors"); - uint64_t hash = 1469598103934665603ull; - fnv(&hash, text.data(), text.size()); std::vector order; for (const StTensor& t : st.tensors()) order.push_back(&t); std::sort(order.begin(), order.end(), [](const StTensor* a, const StTensor* b) { return a->name < b->name; }); - for (const StTensor* t : order) { - fnv(&hash, t->name.data(), t->name.size() + 1); - fnv(&hash, t->dtype_str.data(), t->dtype_str.size() + 1); - for (int64_t d : t->shape) fnv(&hash, &d, sizeof d); - if (t->data) fnv(&hash, t->data, (size_t)t->bytes); - } - info->content_hash = hash; static const std::regex key_re(R"(^(.*)\.lora_([AB])\.(weight|default\.weight)$)"); std::map mods; @@ -902,7 +886,7 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max "; only linear LoRA A/B pairs are served"); } std::string mod = m[1].str(); - const size_t at = mod.find("base_model.model."); /* rad-export: first occurrence */ + const size_t at = mod.find("base_model.model."); /* the first one, as rad-export strips it */ if (at != std::string::npos) mod.erase(at, 17); AdModule& am = mods[mod]; am.name = mod; @@ -932,8 +916,8 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max } int64_t rr = info->r; double aa = info->alpha; - for (const Pat& p : rpat) if (std::regex_search(am.name, p.re)) { rr = (int64_t)p.v; break; } - for (const Pat& p : apat) if (std::regex_search(am.name, p.re)) { aa = p.v; break; } + for (const Pat& p : rpat) if (std::regex_match(am.name, p.re)) { rr = (int64_t)p.v; break; } + for (const Pat& p : apat) if (std::regex_match(am.name, p.re)) { aa = p.v; break; } if (am.A->shape[0] != rr || am.B->shape[1] != rr) return fail(err, RAD_E_SHAPE, fmt("module %s: expected rank %lld (r / rank_pattern), found lora_A %s and " @@ -945,6 +929,9 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max am.rank = rr; am.alpha = aa; am.scale = (float)(info->rslora ? aa / std::sqrt((double)rr) : aa / (double)rr); + if (!std::isfinite(am.scale)) + return fail(err, RAD_E_FORMAT, fmt("module %s: alpha %g over rank %lld is no finite " + "f32 scale", am.name.c_str(), aa, (long long)rr)); info->max_module_rank = std::max(info->max_module_rank, rr); const size_t d = am.name.rfind('.'); info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1)); diff --git a/core/lora/lora.h b/core/lora/lora.h index df6103c4..9538343c 100644 --- a/core/lora/lora.h +++ b/core/lora/lora.h @@ -1,22 +1,19 @@ /* lora.h -- runtime LoRA: which declared GEMMs an adapter lands in, and the bytes of one adapter for - * one rank (research/radiance/lora/DESIGN.md §2, §5). + * one rank. Two host-only steps that read nothing but the declared Program: * - * TWO PURE STEPS, both host-only and both read nothing but the declared Program: + * build_sites() after declare, every LoRA-capable trunk GEMM whose weight a target names becomes + * a Site: the weight's per-rank geometry (K slice, output width, where each PEFT + * module's rows land in y), read from what the plugin recorded on the weight + * (shard mode, row parts, shard and part spans, name-map sources), never from a + * plugin's own split rule. One Site per GEMM op; the Sites of one declared weight + * share one pool. + * load_adapter() a PEFT directory -> one PackedSite per pool, the bytes of one slot. * - * build_sites() after declare: every LoRA-capable trunk GEMM whose weight a target names becomes - * a Site -- the weight's per-rank geometry (K slice, output width, which rows of - * which PEFT module land where in the GEMM's y) read off the facts the plugin - * recorded on the weight: its shard mode, row parts, shard / part spans and its - * name-map sources. Never a plugin's own split rule. One Site per GEMM op; the - * Sites of one declared weight share one POOL (one slot layout per weight). - * load_adapter() a PEFT directory -> one PackedSite per pool: exactly the bytes of one slot. + * Nothing here touches a device; the caller declares the pools and copies. * - * Nothing here allocates device memory or touches a device; the caller declares the pools and copies. - * - * TARGETS ARE HF MODULE LEAF NAMES ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is - * targeted when one of its name-map sources is `..weight`, `leaf` in the set, and the - * weight is not in a non-trunk scope (weight_targeted() states the rule; build_sites and - * find_unsupported_uses use exactly that predicate, and the builder may call it mid-declare). + * Targets are HF module leaf names ("q_proj", "gate_proj", "in_proj_qkv", ...). A declared weight is + * targeted when one of its name-map sources is `..weight` with `leaf` in the set and + * the weight is in the trunk; weight_targeted() is the one predicate everything here uses. */ #pragma once #include "../rad_core.h" @@ -30,25 +27,23 @@ namespace rad { namespace lora { -/* HF module LEAF names. A std::set so two callers that build it in different orders get the same - * answer. Empty targets nothing. */ +/* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */ using TargetSet = std::set; -/* ONE CONTIGUOUS RUN OF ONE PEFT MODULE'S ROWS INSIDE THIS SITE'S y, ON THIS RANK. - * A module may need SEVERAL parts: in_proj_qkv covers three row parts of the delta net's fused - * ssm_inz, and a rank holds a slice of EACH, so its B rows on that rank are three disjoint runs - * landing at three y columns. Every part of one module carries the same t_off. */ +/* One contiguous run of one PEFT module's rows inside this site's y, on this rank. A module may + * need several: in_proj_qkv covers three row parts of the delta net's fused ssm_inz and a rank + * holds a slice of each, so its B rows there are three runs at three y columns. Every part of one + * module has the same t_off. */ struct SitePart { std::string module; /* HF module path without ".weight", as the name map spells it */ int64_t src_lo = 0, src_hi = 0;/* rows [lo,hi) of the module's full output (= rows of lora_B) */ int64_t y_col = 0; /* column of this site's per-rank y where row src_lo lands */ int64_t t_off = 0; /* first t column of the module's block = module slot * max_rank */ - /* ADDED: the weight's row part this run lies in (0 for a weight of one part). */ - int32_t row_part = 0; + int32_t row_part = 0; /* the weight's row part this run lies in (0: a single part) */ }; -/* ADDED: one name-map source of the site's weight, in concatenation order -- targeted or not, - * because an untargeted source still occupies rows of the fused weight. */ +/* One name-map source of the site's weight, in concatenation order, targeted or not: an untargeted + * source still occupies rows of the fused weight. */ struct SiteSource { std::string module; /* source without ".weight" */ bool targeted = false; @@ -59,28 +54,20 @@ struct SiteSource { }; struct Site { - uint32_t gemm = 0; /* the gemm op handle (anchor) */ - uint32_t lora_shrink = 0, lora_expand = 0; /* appended op handles (stream G) */ + uint32_t gemm = 0; /* the gemm op handle */ std::string weight; /* declared weight name */ int shard = 0; /* RAD_SHARD_ROW / COL / NONE of the base weight */ int64_t K_r = 0, k_lo = 0, K_full = 0; /* x columns on this rank; COL: A columns * [k_lo, k_lo + K_r). K_full 0 = not recorded on * the weight (a COL span): taken from lora_A. */ int64_t N_r = 0; /* per-rank y width the gemm writes */ - int64_t R = 0; /* capacity: n_modules * max_rank (see report: - * DESIGN said parts.size() * max_rank) */ + int64_t R = 0; /* capacity: n_modules * max_rank */ std::vector parts; /* empty while !parts_resolved */ - uint32_t pool_a = 0, pool_b = 0, pool_scale = 0; /* PERSIST buffers; 0 here, the caller's */ - - /* ---- ADDED */ int32_t pool = -1; /* index of the weight in build_sites' per-weight pool list */ - uint32_t w = 0; /* the declared weight's handle */ std::string op; /* the gemm's op name */ int32_t n_modules = 0; /* targeted sources */ int32_t max_rank = 0; bool parts_resolved = true; /* false: the fused layout is decided by B rows at load */ - bool res_unchecked = false; /* gemm_nt_bias: its optional `res` operand is bound at - * issue, not at declare -- stream G checks it there */ std::vector sources; /* Per row part g of the weight (P = max(1, n_row_parts) entries): the part's rows in the * container (0 = not recorded: an equal-part single span), this rank's rows [lo, hi) of it in @@ -93,7 +80,6 @@ struct PackedSite { std::vector a; /* [R, K_r] bf16, zero rows past the module's rank in each block */ std::vector b; /* [N_r, R] bf16, zero outside the module's rows / rank block */ std::vector scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */ - /* ADDED */ int32_t pool = -1; bool empty = true; /* no module of this adapter lands in this pool */ }; @@ -121,7 +107,6 @@ struct AdapterInfo { std::set leaves; /* leaf names present in the tensors (targets present) */ std::vector absent; /* modules no site on THIS rank took (see check_placed) */ int64_t max_module_rank = 0; - uint64_t content_hash = 0; /* FNV-1a 64 over the config bytes and the tensors */ }; /* A targeted weight read by an op that is not a LoRA site. The caller refuses at startup. */ @@ -165,10 +150,6 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank, std::vector* out, std::string* err, std::vector* pool_weights = nullptr); -/* Every leaf whose every targeted weight in `prog` would be a site: what "all LoRA-capable trunk - * linears" means when no adapter names the targets. */ -TargetSet all_capable_targets(const Program& prog); - /* One adapter for one rank: `packed` gets one PackedSite per pool (index = Site::pool), in the * slot layout of the pool's sites. Refusals return a negative code and name module, expected and * found. A module with no site on THIS rank is not refused here -- an attention-zero rank holds no diff --git a/core/lora/slots.cpp b/core/lora/slots.cpp index 76464e0a..18d10014 100644 --- a/core/lora/slots.cpp +++ b/core/lora/slots.cpp @@ -29,9 +29,8 @@ int SlotTable::reserve(const std::string& name, int* slot, bool* cooling, std::s *err = "an adapter named '" + name + "' is already loaded"; return RAD_E_INVAL; } - /* The old adapter's requests are still running on its slot, and a request naming - * the new one would be told apart from them only by the uid: load it once the old one - * is gone (POST /v1/unload_lora_adapter says how many remain). */ + /* The old adapter's requests still run on its slot; the name loads again once they + * are gone (POST /v1/unload_lora_adapter says how many remain). */ const auto it = refs_.find(x.uid); const int n = it == refs_.end() ? 0 : it->second; *err = fmt("an adapter named '%s' is being unloaded: %d request%s still use%s it", name.c_str(), diff --git a/core/lora/slots.h b/core/lora/slots.h index d8aca774..f5e63cbc 100644 --- a/core/lora/slots.h +++ b/core/lora/slots.h @@ -2,22 +2,22 @@ * be written again. Host bookkeeping only: the engine copies the adapter's bytes (engine_lora.cpp) * and this table decides which slot, publishes the name, hands out holds and frees slots. * - * A SLOT'S LIFE: + * A slot's life: * * free --load--> loaded --unload, no request uses it--> free (cooling) * | ^ * +--unload, requests use it--> draining ---+ the last of them finishes * - * A request holds the adapter it names from admission until its reply is done (the server keeps - * the hold in the request's Generation), so an adapter is never unloaded under a request. An - * unload of an adapter in use DRAINS it: from that moment no new request can name it (it is gone - * from the names, and acquire answers as for a name never loaded), the requests already holding - * it finish normally, and the last hold to go frees the slot. A load of the same name waits for - * that rather than racing it. + * A request holds the adapter it names from admission until its reply is done or it is cancelled + * (the server keeps the hold in the request's Generation), so an adapter is never unloaded under a + * request. An unload of an adapter in use drains it: no new request can name it (acquire answers + * as for a name never loaded), the requests already holding it finish, and the last hold to go + * frees the slot. A load of the same name is refused until then. * - * COOLING: a freed slot is written again only once the step loop has gone round three times - * since (`epoch` below counts its rounds): the step after a request's last one may already be on - * the card, issued ahead, and reads the slot through the step batch until it runs. + * Cooling: a freed slot is written again only after the step loop has gone round + * kSlotCoolRounds times (`epoch` counts its rounds). A step that read the slot may still be on + * the card when the last hold goes, issued ahead of the readback; an idle round has no step in + * flight and a busy round collects one, so with one step issued ahead two rounds suffice. * * Thread-safe: every call takes the table's lock. Loads are serialised by the caller (one at a * time between reserve and publish), which is what keeps a reserved slot from being handed out @@ -85,7 +85,7 @@ private: const std::atomic* epoch_ = nullptr; }; -/* Step-loop rounds a freed slot waits before it is written again (see COOLING above). */ +/* Step-loop rounds a freed slot waits before it is written again (see Cooling above). */ inline constexpr uint64_t kSlotCoolRounds = 3; } /* namespace lora */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 64d4cddf..574889e4 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -82,6 +82,58 @@ void KeepAll::select(const std::vector& pos, std::vector* keep *keep = pos; } +/* A session's tip is usually a prompt's tail between two interval checkpoints, so each step also + * counts the ladder with a tail half an interval on as its tip. */ +int64_t CheckpointPolicy::held(int64_t ctx, int64_t interval) const { + if (interval <= 0 || ctx < interval) return 1; + std::vector kept, keep; + size_t most = 0; + for (int64_t p = interval; p <= ctx; p += interval) { + kept.push_back(p); + select(kept, &keep); + std::sort(keep.begin(), keep.end()); + kept.swap(keep); + most = std::max(most, kept.size()); + if (p + interval / 2 <= ctx) { + std::vector tipped = kept; + tipped.push_back(p + interval / 2); + select(tipped, &keep); + most = std::max(most, keep.size()); + } + } + return (int64_t)most; +} + +int64_t KeepAll::held(int64_t ctx, int64_t interval) const { + return interval > 0 && ctx >= interval ? ctx / interval : 1; +} + +std::unique_ptr make_checkpoint_policy(const std::string& name, + int64_t interval) { + if (name == "tip-only") return std::make_unique(); + if (name == "keep-all") return std::make_unique(); + return std::make_unique(interval); +} + +CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs, + int64_t ctx, int64_t interval, int64_t slot_bytes, + int64_t share_bytes, int64_t room_bytes) { + CheckpointSlots c; + c.per_seq = policy.held(ctx, interval) + 1; + const int64_t seqs = std::max(max_seqs, 1); + c.want = seqs > INT64_MAX / c.per_seq ? INT64_MAX : seqs * c.per_seq; + if (slot_bytes <= 0) return c; + const int64_t share = std::max(share_bytes, 0) / slot_bytes; + const int64_t room = std::max(room_bytes, 0) / slot_bytes; + c.slots = std::min(c.want, std::max(share, std::min(c.want, kCheckpointSlotsFloor))); + if (c.slots < c.want) c.bound = CheckpointSlots::Bound::Share; + if (room < c.slots) { + c.slots = room; + c.bound = CheckpointSlots::Bound::Room; + } + return c; +} + /* ------------------------------------------------------------------ configure */ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) { @@ -93,11 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ groups_.clear(); map_.clear(); lru_.clear(); ck_by_prefix_.clear(); ck_by_session_.clear(); - /* config_parse rejects unknown names, so the else branch is "geometric-backoff". - * set_policy() may override this afterwards. */ - if (cfg.checkpoint_policy == "tip-only") policy_ = std::make_unique(); - else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique(); - else policy_ = std::make_unique(checkpoint_interval); + /* set_policy() may override this afterwards. */ + policy_ = make_checkpoint_policy(cfg.checkpoint_policy, checkpoint_interval); report_.clear(); if (!kv) return RAD_E_INVAL; @@ -202,7 +251,7 @@ void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const { CacheHit PrefixCache::lookup(const std::vector& tokens, const std::vector& mm, std::vector>* blocks_out, - const HitCap* cap) const { + const HitCap* cap, uint64_t session) const { CacheHit hit; if (blocks_out) { blocks_out->assign(groups_.size(), {}); } if (!enabled_ || tokens.empty()) return hit; @@ -296,6 +345,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, best->second.used_ns = now; handed_.push_back(best->first); ++stats_.ckpt_hits; + if (session != 0) take_over(session, hs, hit.n_attn_tokens); return hit; } @@ -384,13 +434,16 @@ int PrefixCache::insert(uint64_t session, tiers_->note_session(session, hs, n_tokens, now, label); } - /* A conversation's snapshots belong to its latest turn. Sessions are keyed by request id, so - * without this each earlier turn's deepest snapshot would stay a protected tip. Every snapshot - * on the chain just published moves under this id, so the policy sees one session, one tip. */ + take_over(session, hs, n_full * block_size_); + return RAD_OK; +} + +void PrefixCache::take_over(uint64_t session, const std::vector& hs, + int64_t upto) const { for (auto& kvp : ck_by_prefix_) { Ckpt& c = kvp.second; - if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ || - c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first) + if (c.session == session || c.pos <= 0 || c.pos > upto || c.pos % block_size_ != 0 || + hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first) continue; auto old = ck_by_session_.find(c.session); if (old != ck_by_session_.end()) { @@ -401,7 +454,6 @@ int PrefixCache::insert(uint64_t session, c.session = session; ck_by_session_[session].push_back(kvp.first); } - return RAD_OK; } diff --git a/core/mem/prefix.h b/core/mem/prefix.h index 90c40efb..934d8350 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -110,6 +110,11 @@ public: * retain. The tip, positions.back(), must always be kept: an appending transcript resumes * from it. */ virtual void select(const std::vector& positions, std::vector* keep) const = 0; + /* The most snapshots the policy keeps for one session that grows to `ctx` tokens with a + * checkpoint on every `interval`, retention applied after each: the session's standing share + * of the store. The base applies select() to its own output one checkpoint at a time, which + * is cheap only for a policy that keeps few. */ + virtual int64_t held(int64_t ctx, int64_t interval) const; }; /* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's @@ -134,13 +139,40 @@ class KeepTipOnly final : public CheckpointPolicy { public: const char* name() const override { return "tip-only"; } void select(const std::vector& positions, std::vector* keep) const override; + int64_t held(int64_t, int64_t) const override { return 1; } }; class KeepAll final : public CheckpointPolicy { public: const char* name() const override { return "keep-all"; } void select(const std::vector& positions, std::vector* keep) const override; + int64_t held(int64_t ctx, int64_t interval) const override; }; +/* The policy --checkpoint-policy names, at the resolved checkpoint interval. config_parse admits + * only the three names, so any other is geometric backoff. */ +std::unique_ptr make_checkpoint_policy(const std::string& name, int64_t interval); + +/* ------------------------------------------------------------------ the store's size */ +/* --checkpoint-slots auto. Every sequence --max-num-seqs admits gets its session's standing share + * at --max-model-len (CheckpointPolicy::held) plus one slot for the checkpoint its running turn + * writes while the previous turn's snapshots are still held. The store is pinned for the life of + * the process, so the count is bounded by two byte budgets the engine measures: `share`, the part + * of host memory the store may take, and `room`, what the host can pin after everything still to + * be allocated. Under the share it never drops below kCheckpointSlotsFloor (or `want`, if fewer); + * the room is a hard bound. */ +constexpr int64_t kCheckpointSlotsFloor = 8; + +struct CheckpointSlots { + int64_t per_seq = 0; /* snapshots a sequence is given */ + int64_t want = 0; /* --max-num-seqs x per_seq */ + int64_t slots = 0; /* the store's size */ + enum class Bound { Want, Share, Room } bound = Bound::Want; +}; + +CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs, + int64_t ctx, int64_t interval, int64_t slot_bytes, + int64_t share_bytes, int64_t room_bytes); + /* ------------------------------------------------------------------ the cache */ class PrefixCache { public: @@ -168,11 +200,13 @@ public: * cached_groups() order, ready for KVManager::adopt(). * * Never returns the whole prompt: one token must remain to compute a logit from, so a full - * hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). */ + * hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`, + * when not 0, is the request being admitted: it takes over the snapshots on the chain it hit + * (take_over). */ CacheHit lookup(const std::vector& tokens, const std::vector& mm, std::vector>* blocks_out = nullptr, - const HitCap* cap = nullptr) const; + const HitCap* cap = nullptr, uint64_t session = 0) const; /* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of * cached_groups()[i]. Takes a KV reference on every newly indexed block. */ @@ -347,6 +381,12 @@ private: /* Retire one snapshot: free its slot and tell the tiers. The session index is left to the * caller. */ void retire_ckpt(std::unordered_map::iterator it); + /* Move every snapshot on the chain `hs` at or below `upto` tokens under `session`. A + * conversation's snapshots belong to its latest turn: sessions are request ids, so otherwise + * each earlier turn's deepest snapshot would stay a protected tip, and a running turn would be + * a second session beside its conversation, two ladders where retention should keep one. + * The admission's lookup and the publish both call it. */ + void take_over(uint64_t session, const std::vector& hs, int64_t upto) const; /* Take one key out of a session's index entry, and the entry when it empties. */ void unindex_ckpt(uint64_t session, const BlockHash& key); /* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a @@ -375,7 +415,7 @@ private: std::unordered_map held_; bool released_ = false; mutable std::unordered_map ck_by_prefix_; - std::unordered_map> ck_by_session_; + mutable std::unordered_map> ck_by_session_; /* Snapshots lookup handed out since begin_step; kept in their slots until the next one. */ mutable std::vector handed_; bool handed(const BlockHash& h) const { diff --git a/core/mm/mp4.cpp b/core/mm/mp4.cpp new file mode 100644 index 00000000..08548ea8 --- /dev/null +++ b/core/mm/mp4.cpp @@ -0,0 +1,405 @@ +/* mp4.cpp -- Mp4Writer (mp4.h) over libavformat, libavcodec and libswscale. */ +#include "mm/mp4.h" + +#include +#include +#include + +#ifdef RAD_HAVE_FFMPEG +extern "C" { +#include +#include +#include +#include +#include +} +#endif + +namespace rad { +namespace mm { + +#ifndef RAD_HAVE_FFMPEG + +struct Mp4Writer::Impl {}; +Mp4Writer::Mp4Writer() = default; +Mp4Writer::~Mp4Writer() = default; +static int no_ffmpeg(std::string* why) { + if (why) *why = "this build has no libavcodec, so it writes no video"; + return RAD_E_UNSUPPORTED; +} +int Mp4Writer::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why) { + return no_ffmpeg(why); +} +int Mp4Writer::add_frames(const uint8_t*, int32_t, std::string* why) { return no_ffmpeg(why); } +int Mp4Writer::add_audio(const float*, int64_t, std::string* why) { return no_ffmpeg(why); } +int Mp4Writer::finish(std::string*, std::string* why) { return no_ffmpeg(why); } + +#else + +namespace { + +/* The file in memory. The MP4 muxer seeks back to patch sizes and, to put the moov atom first, + * reopens its output for reading and moves the media data up (FFmpeg's shift_data): the reader is + * a second handle on the same bytes with a position of its own. */ +struct MemFile { + std::string data; + int64_t pos = 0; +}; +struct MemReader { + MemFile* f = nullptr; + int64_t pos = 0; +}; + +int mem_write(void* op, const uint8_t* buf, int n) { + MemFile* f = static_cast(op); + const int64_t end = f->pos + n; + if (end > (int64_t)f->data.size()) f->data.resize((size_t)end); + std::memcpy(&f->data[(size_t)f->pos], buf, (size_t)n); + f->pos = end; + return n; +} + +int64_t mem_seek(void* op, int64_t off, int whence) { + MemFile* f = static_cast(op); + const int64_t size = (int64_t)f->data.size(); + switch (whence & ~AVSEEK_FORCE) { + case AVSEEK_SIZE: return size; + case SEEK_SET: f->pos = off; break; + case SEEK_CUR: f->pos += off; break; + case SEEK_END: f->pos = size + off; break; + default: return AVERROR(EINVAL); + } + return f->pos < 0 ? AVERROR(EINVAL) : f->pos; +} + +int mem_read(void* op, uint8_t* buf, int n) { + MemReader* r = static_cast(op); + const int64_t size = (int64_t)r->f->data.size(); + if (r->pos >= size) return AVERROR_EOF; + const int k = (int)std::min(n, size - r->pos); + std::memcpy(buf, r->f->data.data() + r->pos, (size_t)k); + r->pos += k; + return k; +} + +int64_t mem_read_seek(void* op, int64_t off, int whence) { + MemReader* r = static_cast(op); + const int64_t size = (int64_t)r->f->data.size(); + switch (whence & ~AVSEEK_FORCE) { + case AVSEEK_SIZE: return size; + case SEEK_SET: r->pos = off; break; + case SEEK_CUR: r->pos += off; break; + case SEEK_END: r->pos = size + off; break; + default: return AVERROR(EINVAL); + } + return r->pos < 0 ? AVERROR(EINVAL) : r->pos; +} + +constexpr int kIoBuf = 1 << 16; + +std::string av_why(const char* what, int e) { + char b[AV_ERROR_MAX_STRING_SIZE] = {}; + av_strerror(e, b, sizeof b); + return std::string(what) + ": " + b; +} + +} /* namespace */ + +struct Mp4Writer::Impl { + MemFile file; + AVFormatContext* oc = nullptr; + AVCodecContext* vc = nullptr; + AVCodecContext* ac = nullptr; + AVStream* vs = nullptr; + AVStream* as = nullptr; + SwsContext* sws = nullptr; + AVFrame* vf = nullptr; + AVFrame* af = nullptr; + AVPacket* pkt = nullptr; + int32_t w = 0, h = 0; + int64_t channels = 0; + int64_t next_frame = 0; + std::vector audio; /* interleaved, encoded at finish */ + bool header = false; + + ~Impl() { + if (oc) { + if (oc->pb) { + av_freep(&oc->pb->buffer); + avio_context_free(&oc->pb); + } + avformat_free_context(oc); + } + avcodec_free_context(&vc); + avcodec_free_context(&ac); + sws_freeContext(sws); + av_frame_free(&vf); + av_frame_free(&af); + av_packet_free(&pkt); + } + + /* Every packet `c` has ready, onto stream `st`. */ + int drain(AVCodecContext* c, AVStream* st, std::string* why) { + for (;;) { + const int e = avcodec_receive_packet(c, pkt); + if (e == AVERROR(EAGAIN) || e == AVERROR_EOF) return RAD_OK; + if (e < 0) { + if (why) *why = av_why("encoding", e); + return RAD_E_INVAL; + } + av_packet_rescale_ts(pkt, c->time_base, st->time_base); + pkt->stream_index = st->index; + const int w2 = av_interleaved_write_frame(oc, pkt); + if (w2 < 0) { + if (why) *why = av_why("writing the file", w2); + return RAD_E_INVAL; + } + } + } +}; + +/* The reader shift_data opens on the output's own URL; any other URL is refused. */ +static int open_reader(AVFormatContext* s, AVIOContext** pb, const char*, int flags, AVDictionary**) { + if (!(flags & AVIO_FLAG_READ) || (flags & AVIO_FLAG_WRITE)) return AVERROR(EINVAL); + MemFile* f = static_cast(s->opaque); + MemReader* r = new MemReader{ f, 0 }; + uint8_t* buf = static_cast(av_malloc(kIoBuf)); + *pb = buf ? avio_alloc_context(buf, kIoBuf, 0, r, mem_read, nullptr, mem_read_seek) : nullptr; + if (!*pb) { + av_free(buf); + delete r; + return AVERROR(ENOMEM); + } + return 0; +} + +static int close_reader(AVFormatContext*, AVIOContext* pb) { + if (!pb) return 0; + delete static_cast(pb->opaque); + av_freep(&pb->buffer); + avio_context_free(&pb); + return 0; +} + +Mp4Writer::Mp4Writer() : p_(std::make_unique()) {} +Mp4Writer::~Mp4Writer() = default; + +int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, + int64_t sample_rate, int64_t channels, std::string* why) { + Impl& p = *p_; + /* The encoders print their settings and a file's statistics at FFmpeg's info level, on stderr, + * for every video; a failure comes back through the calls here, so only errors are let + * through. */ + static std::once_flag quiet; + std::call_once(quiet, [] { if (av_log_get_level() > AV_LOG_ERROR) av_log_set_level(AV_LOG_ERROR); }); + if (width <= 0 || height <= 0 || (width & 1) || (height & 1) || fps_num <= 0 || fps_den <= 0) { + if (why) *why = "the frames must be a positive even size at a positive rate"; + return RAD_E_INVAL; + } + p.w = width; + p.h = height; + p.channels = channels; + if (avformat_alloc_output_context2(&p.oc, nullptr, "mp4", nullptr) < 0 || !p.oc) { + if (why) *why = "this libavformat has no MP4 muxer"; + return RAD_E_UNSUPPORTED; + } + p.oc->url = av_strdup("radiance.mp4"); + p.oc->opaque = &p.file; + p.oc->io_open = open_reader; + p.oc->io_close2 = close_reader; + uint8_t* buf = static_cast(av_malloc(kIoBuf)); + p.oc->pb = buf ? avio_alloc_context(buf, kIoBuf, 1, &p.file, nullptr, mem_write, mem_seek) + : nullptr; + p.pkt = av_packet_alloc(); + if (!p.oc->url || !p.oc->pb || !p.pkt) { + if (!p.oc->pb) av_free(buf); + if (why) *why = "out of memory"; + return RAD_E_NOMEM; + } + + /* ---- video */ + const AVCodec* vcodec = nullptr; + for (const char* name : { "libx264", "libopenh264" }) + if ((vcodec = avcodec_find_encoder_by_name(name))) break; + if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_H264); + if (!vcodec) { + if (why) *why = "this libavcodec has no H.264 encoder"; + return RAD_E_UNSUPPORTED; + } + venc_name_ = vcodec->name; + p.vs = avformat_new_stream(p.oc, nullptr); + p.vc = avcodec_alloc_context3(vcodec); + if (!p.vs || !p.vc) { + if (why) *why = "out of memory"; + return RAD_E_NOMEM; + } + p.vc->width = width; + p.vc->height = height; + p.vc->pix_fmt = AV_PIX_FMT_YUV420P; + p.vc->time_base = AVRational{ (int)fps_den, (int)fps_num }; + p.vc->framerate = AVRational{ (int)fps_num, (int)fps_den }; + p.vc->gop_size = (int)std::max(1, 2 * fps_num / fps_den); + p.vc->colorspace = AVCOL_SPC_BT709; + p.vc->color_primaries = AVCOL_PRI_BT709; + p.vc->color_trc = AVCOL_TRC_BT709; + p.vc->color_range = AVCOL_RANGE_MPEG; + if (venc_name_ == "libx264") { + /* Constant quality, visually lossless for generated footage. */ + av_opt_set(p.vc->priv_data, "preset", "medium", 0); + av_opt_set(p.vc->priv_data, "crf", "18", 0); + } else { + /* An encoder without a quality mode: 0.2 bits a pixel, about 5 Mbit/s at 1344x768 x 24. */ + p.vc->bit_rate = (int64_t)((double)width * height * fps_num / fps_den * 0.2); + } + if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.vc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + int e = avcodec_open2(p.vc, vcodec, nullptr); + if (e < 0) { + if (why) *why = av_why(("opening the " + venc_name_ + " encoder").c_str(), e); + return RAD_E_INVAL; + } + avcodec_parameters_from_context(p.vs->codecpar, p.vc); + p.vs->time_base = p.vc->time_base; + p.vs->avg_frame_rate = p.vc->framerate; + p.vf = av_frame_alloc(); + if (!p.vf) return RAD_E_NOMEM; + p.vf->format = AV_PIX_FMT_YUV420P; + p.vf->width = width; + p.vf->height = height; + if (av_frame_get_buffer(p.vf, 0) < 0) return RAD_E_NOMEM; + p.sws = sws_getContext(width, height, AV_PIX_FMT_RGB24, width, height, AV_PIX_FMT_YUV420P, + SWS_BICUBIC | SWS_ACCURATE_RND, nullptr, nullptr, nullptr); + if (!p.sws) { + if (why) *why = "libswscale cannot convert RGB to yuv420p"; + return RAD_E_UNSUPPORTED; + } + /* Full-range RGB to limited-range BT.709, what the stream's colour tags say. */ + sws_setColorspaceDetails(p.sws, sws_getCoefficients(SWS_CS_DEFAULT), 1, + sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16); + + /* ---- audio */ + if (channels > 0) { + const AVCodec* acodec = avcodec_find_encoder(AV_CODEC_ID_AAC); + if (!acodec) { + if (why) *why = "this libavcodec has no AAC encoder"; + return RAD_E_UNSUPPORTED; + } + p.as = avformat_new_stream(p.oc, nullptr); + p.ac = avcodec_alloc_context3(acodec); + if (!p.as || !p.ac) return RAD_E_NOMEM; + p.ac->sample_fmt = AV_SAMPLE_FMT_FLTP; + p.ac->sample_rate = (int)sample_rate; + av_channel_layout_default(&p.ac->ch_layout, (int)channels); + p.ac->bit_rate = 96000 * channels; + p.ac->time_base = AVRational{ 1, (int)sample_rate }; + if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + e = avcodec_open2(p.ac, acodec, nullptr); + if (e < 0) { + if (why) *why = av_why("opening the AAC encoder", e); + return RAD_E_INVAL; + } + avcodec_parameters_from_context(p.as->codecpar, p.ac); + p.as->time_base = p.ac->time_base; + p.af = av_frame_alloc(); + if (!p.af) return RAD_E_NOMEM; + p.af->format = AV_SAMPLE_FMT_FLTP; + p.af->sample_rate = p.ac->sample_rate; + av_channel_layout_copy(&p.af->ch_layout, &p.ac->ch_layout); + p.af->nb_samples = p.ac->frame_size > 0 ? p.ac->frame_size : 1024; + if (av_frame_get_buffer(p.af, 0) < 0) return RAD_E_NOMEM; + } + + AVDictionary* opts = nullptr; + av_dict_set(&opts, "movflags", "+faststart", 0); + e = avformat_write_header(p.oc, &opts); + av_dict_free(&opts); + if (e < 0) { + if (why) *why = av_why("writing the MP4 header", e); + return RAD_E_INVAL; + } + p.header = true; + return RAD_OK; +} + +int Mp4Writer::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { + Impl& p = *p_; + if (!p.header) { + if (why) *why = "the writer is not open"; + return RAD_E_STATE; + } + const int64_t frame_bytes = (int64_t)p.w * p.h * 3; + for (int32_t i = 0; i < n; ++i) { + if (av_frame_make_writable(p.vf) < 0) return RAD_E_NOMEM; + const uint8_t* src[1] = { rgb + i * frame_bytes }; + const int stride[1] = { p.w * 3 }; + sws_scale(p.sws, src, stride, 0, p.h, p.vf->data, p.vf->linesize); + p.vf->pts = p.next_frame++; + const int e = avcodec_send_frame(p.vc, p.vf); + if (e < 0) { + if (why) *why = av_why("encoding a frame", e); + return RAD_E_INVAL; + } + RAD_TRY(p.drain(p.vc, p.vs, why)); + } + return RAD_OK; +} + +int Mp4Writer::add_audio(const float* samples, int64_t n_frames, std::string* why) { + Impl& p = *p_; + if (!p.header || !p.ac) { + if (why) *why = "the writer has no soundtrack"; + return RAD_E_STATE; + } + p.audio.insert(p.audio.end(), samples, samples + n_frames * p.channels); + return RAD_OK; +} + +int Mp4Writer::finish(std::string* out, std::string* why) { + Impl& p = *p_; + if (!p.header) { + if (why) *why = "the writer is not open"; + return RAD_E_STATE; + } + if (p.ac) { + /* The soundtrack in the encoder's frames, deinterleaved; the last frame padded with + * silence, which the encoder's own length bookkeeping trims. */ + const int64_t total = (int64_t)p.audio.size() / p.channels; + const int fs = p.af->nb_samples; + for (int64_t at = 0; at < total; at += fs) { + if (av_frame_make_writable(p.af) < 0) return RAD_E_NOMEM; + const int64_t k = std::min(fs, total - at); + p.af->nb_samples = (int)k; + for (int64_t c = 0; c < p.channels; ++c) { + float* d = reinterpret_cast(p.af->data[c]); + for (int64_t i = 0; i < k; ++i) + d[i] = p.audio[(size_t)((at + i) * p.channels + c)]; + } + p.af->pts = at; + const int e = avcodec_send_frame(p.ac, p.af); + if (e < 0) { + if (why) *why = av_why("encoding the soundtrack", e); + return RAD_E_INVAL; + } + RAD_TRY(p.drain(p.ac, p.as, why)); + p.af->nb_samples = fs; + } + avcodec_send_frame(p.ac, nullptr); + RAD_TRY(p.drain(p.ac, p.as, why)); + } + avcodec_send_frame(p.vc, nullptr); + RAD_TRY(p.drain(p.vc, p.vs, why)); + const int e = av_write_trailer(p.oc); + if (e < 0) { + if (why) *why = av_why("finishing the MP4 file", e); + return RAD_E_INVAL; + } + avio_flush(p.oc->pb); + *out = std::move(p.file.data); + p.file.data.clear(); + p.header = false; + return RAD_OK; +} + +#endif /* RAD_HAVE_FFMPEG */ + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/mm/mp4.h b/core/mm/mp4.h new file mode 100644 index 00000000..50f0ebb6 --- /dev/null +++ b/core/mm/mp4.h @@ -0,0 +1,52 @@ +/* mp4.h -- a video and its soundtrack written as an MP4 file in memory: H.264 video in yuv420p + * (BT.709, limited range) and AAC audio, the moov atom at the front so a player can start before + * the whole file has arrived. + * + * The frames arrive in order, in any number of calls; the soundtrack may come before, between or + * after them, whole or in pieces. Nothing is written until finish(), which encodes the soundtrack + * and interleaves it with the video: a video is at most tens of seconds, and its frames are + * encoded as they come so the RGB is never all held at once. + * + * The H.264 encoder is the best the linked libavcodec has: libx264 (constant quality), else + * libopenh264, else whatever encoder it registers for H.264. Without libavcodec every call + * returns RAD_E_UNSUPPORTED. + */ +#pragma once +#include "rad_core.h" + +#include +#include +#include + +namespace rad { +namespace mm { + +class Mp4Writer { +public: + Mp4Writer(); + ~Mp4Writer(); + Mp4Writer(const Mp4Writer&) = delete; + Mp4Writer& operator=(const Mp4Writer&) = delete; + + /* A video of `width` x `height` (even) at fps_num / fps_den frames a second, with a soundtrack + * of `channels` channels at `sample_rate` (0 channels: none). */ + int open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, int64_t sample_rate, + int64_t channels, std::string* why); + /* `n` frames, each [height, width, 3] u8 RGB, after those already added. */ + int add_frames(const uint8_t* rgb, int32_t n, std::string* why); + /* Samples interleaved over the channels, in [-1, 1], after those already added. */ + int add_audio(const float* samples, int64_t n_frames, std::string* why); + /* Flushes both encoders and writes the file into `out`. */ + int finish(std::string* out, std::string* why); + + /* The H.264 encoder in use, for the log. */ + const std::string& video_encoder() const { return venc_name_; } + +private: + struct Impl; + std::unique_ptr p_; + std::string venc_name_; +}; + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 6f2f4a31..8a496f6d 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -219,6 +219,12 @@ int Registry::commit_(Staged& s, int order) { /* Optional: absent means the model serves no speech route. */ p.arch_audio_format = dl_fn( s.handle, "rad_arch_audio_format"); + /* Optional: absent means an audio generator's prompt takes a request's texts as given. */ + p.arch_text_prepare = dl_fn( + s.handle, "rad_arch_text_prepare"); + /* A video generator's rotary positions; the driver refuses to start without it. */ + p.arch_video_positions = dl_fn( + s.handle, "rad_arch_video_positions"); /* The (architecture id, quantisation) pair selects the plugin, so no two plugins may claim * the same pair (§2.4). Sharing an id at different quantisations is normal (qwen35_bf16 diff --git a/core/plugin/registry.h b/core/plugin/registry.h index ddfc2e6b..3f773fd2 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -89,6 +89,11 @@ struct Plugin { const RadChatFormat* (*arch_chat_format)(const RadModelMeta*) = nullptr; /* Optional (rad_builder.h); null means the model serves no speech route. */ const RadAudioFormat* (*arch_audio_format)(const RadModelMeta*) = nullptr; + /* Optional (rad_builder.h); null means a request's texts go into the audio generator's + * prompt as given. */ + int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr; + /* Required of a video generator (rad_builder.h); null for every other plugin. */ + int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr; RadPluginCloseFn close = nullptr; }; diff --git a/core/rad_core.h b/core/rad_core.h index 599a8612..845b3537 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -265,15 +265,15 @@ struct OpInfo { const RadOpSchema* schema = nullptr; int32_t index = 0; /* position in the declared order */ bool issued = false; /* did the run phase ever issue it */ - /* RUNTIME LoRA (core/lora/). `anchor`: an op the CORE appended after the plugin's declare and - * issues inside another op's issue -- its buffers are that op's, so buffer liveness is judged - * at the anchor's position, not at this op's own (which is past every plugin op). -1 for every - * plugin op. `lora_site`: on a targeted gemm, its row in Program::lora_sites; -1 otherwise. */ + /* Runtime LoRA (core/lora/). `anchor`: the op a core-appended op is issued inside of; its + * buffers are that op's, so their liveness is judged at the anchor's position rather than this + * op's own (past every plugin op). -1 for a plugin op. `lora_site`: a targeted gemm's row in + * Program::lora_sites, -1 otherwise. */ int32_t anchor = -1; int32_t lora_site = -1; - /* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can follow): - * recorded unresolved on purpose, its handle never handed to the plugin, so it is never issued - * and the reference-kernel gate does not count it. */ + /* Declined at declare because runtime LoRA targets its weight (a fused GEMM no delta can + * follow): recorded unresolved and never handed to the plugin, so it is never issued and the + * reference-kernel gate does not count it. */ bool lora_declined = false; }; @@ -300,9 +300,9 @@ inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) { return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0); } -/* ONE TARGETED GEMM OF A RUNTIME-LoRA PROGRAM (core/lora/), as the issue path needs it: the two ops - * the core appended for it, where in the gemm's own operand list its activation and output are, - * and the buffers the appended ops read. Built once at declare; issue reads it and nothing else. */ +/* One targeted GEMM of a runtime-LoRA program (core/lora/), as the issue path needs it: the two ops + * the core appended for it, where the gemm's activation and output are in its operand list, and + * the buffers the appended ops read. Built once at declare. */ struct LoraIssueSite { uint32_t gemm = 0, shrink = 0, expand = 0; /* op handles */ int8_t opd_a = -1, opd_a_scale = -1, opd_y = -1; /* positions in the GEMM's schema */ @@ -312,7 +312,7 @@ struct LoraIssueSite { int64_t R = 0, K = 0, N = 0; }; /* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale - * [S, N] f32 -- PERSIST buffers, so the arena plan (and with it the KV budget) holds them. */ + * [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */ struct LoraPool { std::string weight; rad_buf a = 0, b = 0, scale = 0; @@ -345,7 +345,7 @@ public: * no logits buffer. */ rad_buf pooled_buf = 0; - /* RUNTIME LoRA (core/lora/), empty unless the engine was started with adapters enabled. */ + /* Runtime LoRA (core/lora/), empty unless the engine was started with adapters enabled. */ std::vector lora_sites; std::vector lora_pools; std::vector lora_t; @@ -380,6 +380,24 @@ public: std::vector sigmas; } gen_str; bool is_generator() const { return generator.layout != 0; } + /* The declared audio generator (rad_declare_audio_generator); `max_lanes` 0 when none. Its + * strings point at `agen_str`, as the image generator's do at `gen_str`. */ + RadAudioGenDecl audio_gen{}; + struct AudioGenStrings { + std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */ + } agen_str; + bool is_audio_generator() const { return audio_gen.max_lanes != 0; } + /* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */ + RadVideoGenDecl video_gen{}; + struct VideoGenStrings { + std::string name, tmpl; + std::vector rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */ + } vgen_str; + bool is_video_generator() const { return video_gen.max_lanes != 0; } + /* Driven by passes, not token steps: any generator. */ + bool is_pass_driven() const { + return is_generator() || is_audio_generator() || is_video_generator(); + } /* Two arenas, because a host-site activation cannot index device memory. The buffer plan * colours each domain separately (transients share storage only within a domain), so each is @@ -578,9 +596,9 @@ struct TokenScores { struct Request { uint64_t id = 0; - /* THE RUNTIME LoRA ADAPTER this request is served with (core/lora/): its slot in the adapter - * pools, -1 for the base model, and the uid of the load that slot held when the request was - * admitted -- the prefix cache keys on the uid, so a reload under the same name starts cold. */ + /* The runtime LoRA adapter this request runs with (core/lora/): its slot in the adapter pools, + * -1 for the base model, and the uid of the load that slot held at admission. The prefix cache + * keys on the uid, so a reload under the same name starts cold. */ int32_t lora_slot = -1; uint64_t lora_uid = 0; std::vector prompt; @@ -769,8 +787,9 @@ struct Config { /* Cap on linear-state (or sliding-window) snapshots held at once, for the whole server. The * slots are pinned host memory, all allocated at startup and never on the card (spec §7.3). * A slot is a sizeable fraction of a gigabyte on a linear-attention model, so raising the cap - * trades host RAM for retained checkpoints. */ - int64_t checkpoint_slots = 8; + * trades host RAM for retained checkpoints. -1 is `auto`, resolved by the engine when the + * store is opened (checkpoint_slots_auto in core/mem/prefix.h). */ + int64_t checkpoint_slots = -1; bool prefix_cache = true; /* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured; * core/mem/prefix.h ships the two extremes so they can be compared. */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index d887fd59..abc5443f 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -899,8 +899,9 @@ int Ctx::lane_join(int from, int to) { /* The key below reads every RadBatch field a pass's shape or arguments can depend on, by hand. A * field added to RadBatch changes its size: decide whether the key must read it, then update the - * size here. */ -static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 320, + * size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded + * (below). */ +static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); @@ -909,7 +910,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { /* Not recordable: encoder passes are shaped by their media, and passes carrying encoder rows * issue the scatter only when they have some. */ if (b->enc || b->n_mm_rows > 0) return 0; - /* A generator pass is shaped by what RadBatch::gen_b carries, which no key below reads. */ + /* A generator pass is shaped by what RadBatch::gen_b, agen_b or vgen_b carries, which no key + * below reads. */ if (b->gen) return 0; uint64_t h = 0x9e3779b97f4a7c15ull; auto mix = [&](uint64_t v) { @@ -927,9 +929,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids); ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted); ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids); - /* The adapter ops' slot pointer. One address per rank for the engine's life, null without - * adapters; the slots themselves are read on the card, and the ops are issued whether or not a - * row has an adapter, so what a recorded pass launches never depends on their values. */ + /* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the + * two are different passes. The slots themselves are read on the card. */ ptr(b->lora_slot); for (int g = 0; g < b->n_kv_groups; ++g) { const RadKVGroupBatch& k = b->kv[g]; diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 847eb01f..9ef3a898 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -86,7 +86,7 @@ struct OpPlan { /* The conventional all_reduce, whose `n` is the message's element count, so its link bytes * can be counted (ar_bytes) apart from the expert mover's. */ bool billed = false; - /* RUNTIME LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */ + /* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */ int32_t lora_site = -1; }; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 5584e2d2..05f33e02 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -415,27 +415,37 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { return rc; } -/* RUNTIME LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the +/* Runtime LoRA: the two ops the core appended for a targeted gemm, issued right behind it on the * same stream, over the same rows, through the ordinary issue path (bands, tape, hazards). * * t = A[slot] . x lora_shrink, x = the gemm's own activation operand(s) * y += scale . B[slot] . t lora_expand, y = the gemm's own output operand * - * Here and only here: a row-parallel gemm's y is this rank's PARTIAL sum and the plugin reduces it - * after this returns, so the delta rides the same reduction (B.A.x is linear in x's shards). Only - * the trunk pass: a draft pass runs the drafter's weights, an encoder pass the tower's. A base row - * (slot -1) is not touched by either kernel, so a step with no adapter rows computes exactly what - * the same step without LoRA does. */ + * A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns, + * so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a + * step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without + * adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator + * pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h), + * so reaching one here is refused rather than run without its delta. */ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { - if (!batch_ || batch_->draft_pass != 0 || batch_->enc != 0 || batch_->gen != 0) return RAD_OK; + if (!batch_) return RAD_OK; + if (batch_->enc != 0 || batch_->gen != 0) + return abort_step_msg(h, RAD_E_UNSUPPORTED, + "a LoRA-targeted gemm was issued by an encoder or generator pass, " + "which runtime LoRA does not reach; leave its module out of " + "--lora-target-modules"); + if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK; const OpPlan& p = plans_[h]; const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site]; if (n == RAD_N_BATCH) n = batch_->n_tok; if (n <= 0) return RAD_OK; - if (op_domain_[h].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE) + /* The adapter ops run in the gemm's domain and read the pools, which are device buffers: on a + * card that is the device domain, and on the host backend every domain is host memory. */ + const int dom = (int)op_domain_[h].load(std::memory_order_relaxed); + if (dom != RAD_DOMAIN_DEVICE && !device_is_host()) return abort_step_msg(h, RAD_E_UNSUPPORTED, - "a LoRA-targeted gemm was placed on the host; its adapter delta has " - "no host path, so the step would compute the base model's output"); + "a LoRA-targeted gemm was placed on the host, and the adapter pools " + "are on the card"); if (s.opd_a < 0 || s.opd_a >= n_opd || s.opd_y < 0 || s.opd_y >= n_opd) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm was issued with fewer operands " "than its schema names"); @@ -445,9 +455,9 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { (size_t)ya.handle >= program_->buffers.size() || (size_t)xa.handle >= program_->buffers.size()) return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the gemm's activation or output is " "not a declared buffer"); - /* THE ROWS THE GEMM WROTE ARE ROWS OF THE STEP'S TOKENS starting at r0, so the slot array is - * read from r0 too. A row slice offsets by whole rows of the buffer's declared width; a column - * slice offsets by less than one row. Anything else is a view this code cannot place. */ + /* The rows the gemm wrote are the step's token rows from r0 on, so the slot array is read from + * r0 too. A row slice offsets by whole rows of the buffer's declared width and a column slice + * by less than one row; any other view cannot be placed. */ const RadBufDecl& yd = program_->buffers[ya.handle].decl; const RadBufDecl& xd = program_->buffers[xa.handle].decl; if (yd.dtype != s.y_dtype || xd.dtype != s.a_dtype) @@ -461,30 +471,25 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a " "row, so its token rows cannot be told"); const int64_t r0 = ya.offset / yw; - /* ...and the activation must be the SAME rows: shrink reads x's row m and expand writes y's - * row m with one slot, so a GEMM whose two views start at different tokens cannot be followed. */ + /* The activation must start at the same row: shrink reads x's row m and expand writes y's row + * m with one slot. */ { const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0; if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output " "views do not start at the same token row"); } - if (op_domain_[s.shrink].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE || - op_domain_[s.expand].load(std::memory_order_relaxed) != RAD_DOMAIN_DEVICE) - return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed off " - "the device the gemm runs on"); + if ((int)op_domain_[s.shrink].load(std::memory_order_relaxed) != dom || + (int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom) + return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in " + "another domain than the gemm they follow"); if (r0 < 0 || r0 + n > batch_->n_tok) return abort_step_msg(h, RAD_E_STATE, fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step", (long long)r0, (long long)(r0 + n), (long long)batch_->n_tok)); - /* Each row's adapter is the step batch's (RadBatch::lora_slot), which the builder fills from - * every request's slot. It sits at one address per rank for the engine's life and is - * rewritten in stream order before each step's kernels, so the pointer this launch records is - * the one a replay of it reads. */ - if (!batch_->lora_slot) - return abort_step_msg(h, RAD_E_STATE, "LoRA site: the step batch carries no per-row adapter " - "slot (RadBatch::lora_slot), so the engine was started " - "without adapters and should have declared no site"); + /* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order + * before each step's kernels, so the pointer this launch records is the one a replay of it + * reads. */ const LoraPool& pool = program_->lora_pools[(size_t)s.pool]; const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0]; RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32); diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 5758cf09..6cd9ac0a 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -124,8 +124,8 @@ void BatchBuilder::carve(Set& s, char* h) { * moves a rotary position off the token index. */ pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0); pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0); - /* Each row's adapter slot, only when the engine serves adapters: with none the slab and every - * offset in it are what they were before adapters existed. */ + /* Each row's adapter slot, carved only when the engine serves adapters, so an engine without + * them lays the slab out as if the array did not exist. */ pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0); /* Host-only (derived metadata is copied into the planned arena), but carved on both sides to * keep device offsets equal to host offsets. */ @@ -871,6 +871,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, int64_t n_out = 0, n_dout = 0; int32_t rope_mixed = 0; int64_t n_mm = 0; + bool lora_rows = false; s.h_cu[0] = 0; for (int64_t i = 0; i < n_seq; ++i) { const StepEntry& e = plan.e[(size_t)i]; @@ -902,6 +903,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, if (lora_on_) { const int32_t ls = e.req ? e.req->lora_slot : -1; for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls; + if (ls >= 0 && e.n_tokens > 0) lora_rows = true; } /* Rotary position of each row at its own position (draft-head rows rotate at the index * they write, not the token they embed). Three planes of n_tok. */ @@ -1108,7 +1110,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, B.n_mm_rows = n_mm; B.mm_rows = n_mm ? on_rank(base, b0, s.d_mmrow) : nullptr; B.mm_embd = n_mm ? mm_dev_[r] : nullptr; - B.lora_slot = lora_on_ ? on_rank(base, b0, s.d_lora) : nullptr; + /* Null on a step with no adapter row: the core then issues no adapter op, and the step + * runs the same pass as an engine serving no adapters. */ + B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr; B.enc = 0; B.enc_n_patch = 0; B.enc_pixels = nullptr; diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 683c82b4..caaa16be 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -284,11 +284,10 @@ struct KVBinding final : IKVManager { * and segment: the same picture at the same place hits, two pictures never alias. */ inline void media_keys(const Request& r, std::vector* out) { out->clear(); - /* THE RUNTIME LoRA ADAPTER IS PART OF EVERY BLOCK'S KEY. KV written under an adapter is not - * the base's, so it rides into the chain as one span over the whole sequence, keyed by the - * adapter's load uid -- every block overlaps it, and with uid 0 (the base) there is no span and - * every hash is what it was before adapters existed. The uid, never the name: a reload under - * the same name is new weights and must start cold. */ + /* The runtime LoRA adapter is part of every block's key: KV written under an adapter is not + * the base's. It enters the chain as one span over the whole sequence, keyed by the adapter's + * load uid, so every block overlaps it; the base (uid 0) adds no span and its hashes are + * unchanged. The uid and not the name, because a reload under the same name is new weights. */ if (r.lora_uid != 0) { MMContentKey k; k.tok_begin = 0; @@ -319,7 +318,8 @@ struct PCBinding final : IPrefixCache { CacheHit lookup(const Request& r, std::vector>* out, const HitCap* cap) const override { media_keys(r, &mm_); - return m->lookup(r.prompt, mm_, out, cap); + /* r.id: the admission takes its conversation's snapshots over. */ + return m->lookup(r.prompt, mm_, out, cap, r.id); } /* Installed by the engine when the idle tiers are on; empty otherwise. */ diff --git a/core/server/admin.cpp b/core/server/admin.cpp index ff803505..ee6e450a 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -8,8 +8,9 @@ * * Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no * classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights - * are placed once, spec §5), the LoRA endpoints (no LoRA), /invocations (a SageMaker envelope), - * stored Responses-API responses (would need a conversation store), and llama-server's /slots. + * are placed once, spec §5), /invocations (a SageMaker envelope), stored Responses-API responses + * (would need a conversation store), and llama-server's /slots and /lora-adapters (a runtime LoRA + * adapter is chosen per request by `model`; vLLM's load and unload routes are in server.cpp). */ #include "server.h" @@ -311,6 +312,8 @@ HttpResponse Server::handle_props(const HttpRequest&) { params["backend_sampling"] = false; params["timings_per_token"] = false; params["post_sampling_probs"] = false; + /* The adapters a request runs with when it names none: never any, since an adapter is chosen + * by `model` (they are listed on /v1/models). */ params["lora"] = json::array(); json gen; @@ -385,7 +388,7 @@ json Server::capabilities() const { caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning(); /* An image model reads pictures only for edits and writes no text a grammar could constrain, * whatever its conditioning network's processor would take. */ - const bool img = opt_.image_model; + const bool img = opt_.image_model || opt_.video_model; caps["grammar"] = !img && deps_.grammar != nullptr; caps["embedding"] = deps_.embed != nullptr; caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image); @@ -394,6 +397,8 @@ json Server::capabilities() const { caps["logprobs"] = opt_.supports_logprobs; caps["image_generation"] = deps_.images != nullptr; caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0; + caps["audio_generation"] = deps_.audio != nullptr; + caps["video_generation"] = deps_.videos != nullptr; /* The efforts a chat request may send, probed from the template at startup; null when it * takes any word. "none" and "minimal" are this server's and turn thinking off. */ if (lim_.reasoning_efforts.empty()) { diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp new file mode 100644 index 00000000..ebe50260 --- /dev/null +++ b/core/server/audio_gen.cpp @@ -0,0 +1,442 @@ +/* audio_gen.cpp -- POST /v1/audio/speech over an audio generator (core/gen/audio_driver.h): music + * from a description and lyrics, or speech from text and a description of the voice. + * + * The request is OpenAI's speech request: `input` is the text the audio carries (a song's lyrics, + * as SGLang-Omni reads it for a music model, or the words to speak) and `instructions` describes + * it (the piece, or the voice). A model with a template for requests without instructions takes + * them as optional. `voice` is accepted and ignored (the instructions say who sings or speaks), + * `speed` must be 1. The length is `max_new_tokens`, in the model's frames as SGLang-Omni counts + * it, or `duration` in seconds; without either the audio may run to the model's longest, and the + * model usually ends it before that. Also read: `seed` (-1 or absent picks one), + * `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for + * a speech one) and, for a model with a denoiser, `num_inference_steps`. + * + * Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin + * into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with + * its special tokens and the texts without, so a caller cannot write the model's control tokens + * into a lyric. A model that declares the unconditional branch's own template gets that one + * rendered from the same texts. + * + * Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the + * model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the + * vocoder plays each window, in two forms (vLLM-Omni's reading of OpenAI's `stream_format`): + * `stream_format` "audio" sends the bytes themselves as they are made (a wav's header then states + * no length, as a stream's cannot), and `stream` true or `stream_format` "sse" sends Server-Sent + * Events, `speech.audio.delta` with a chunk of base64 PCM and `speech.audio.done` with the usage, + * or `speech.audio.error`. + */ +#include "server.h" +#include "oai.h" + +#include "gen/audio.h" +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +void put_le(std::string* s, uint32_t v, int bytes) { + for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff)); +} + +} /* namespace */ + +/* Samples in [-1, 1] as 16-bit PCM, as libsndfile writes float data to PCM_16 (scaled by 32767, + * rounded, clipped). */ +void append_pcm16(const std::vector& x, std::string* out) { + const size_t at = out->size(); + out->resize(at + 2 * x.size()); + char* p = &(*out)[at]; + for (size_t i = 0; i < x.size(); ++i) { + const float v = std::min(1.0f, std::max(-1.0f, x[i])); + const int16_t q = (int16_t)std::lrint(v * 32767.0f); + std::memcpy(p + 2 * i, &q, 2); + } +} + +/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's header must, + * with both sizes at their largest (how ffmpeg and libsndfile read a WAV of unknown length). */ +std::string wav_header(int64_t bytes, int64_t rate, int64_t channels) { + std::string h; + h += "RIFF"; + put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)(36 + bytes), 4); + h += "WAVEfmt "; + put_le(&h, 16, 4); + put_le(&h, 1, 2); /* PCM */ + put_le(&h, (uint32_t)channels, 2); + put_le(&h, (uint32_t)rate, 4); + put_le(&h, (uint32_t)(rate * channels * 2), 4); /* byte rate */ + put_le(&h, (uint32_t)(channels * 2), 2); /* block align */ + put_le(&h, 16, 2); /* bits a sample */ + h += "data"; + put_le(&h, bytes < 0 ? 0xffffffffu : (uint32_t)bytes, 4); + return h; +} + +/* The request's description of the audio, `text` its input: the instructions, the tempo, the + * length, the denoiser's steps, the guidance and the seed, and the prompt rendered from the + * model's templates. */ +int Server::speech_request(const json& body, const std::string& text, + std::unique_ptr* out, ApiError* err) { + const AudioGenInfo& info = deps_.audio->info(); + auto fail = [&](ApiError e) { + *err = std::move(e); + return -1; + }; + auto str = [&](const char* k, std::string* v) -> int { + if (!body.contains(k) || body[k].is_null()) return 0; + if (!body[k].is_string()) return -1; + *v = body[k].get(); + return 1; + }; + auto blank = [](const std::string& t) { + return t.find_first_not_of(" \t\r\n") == std::string::npos; + }; + std::string inst; + const int has_inst = str("instructions", &inst); + if (has_inst < 0) return fail(err_bad("instructions", "expected a string")); + if (has_inst > 0 && blank(inst)) inst.clear(); + if (inst.empty() && info.tmpl_plain.empty()) + return fail(err_bad("instructions", "this model needs instructions, as a non-empty " + "string: for a song its genre, mood, vocals and " + "instruments")); + if (body.contains("speed") && !body["speed"].is_null() && + !(body["speed"].is_number() && body["speed"].get() == 1.0)) + return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions " + "set it")); + + auto r = std::make_unique(); + /* The length: frames, or seconds, or the model's longest. */ + const bool has_frames = body.contains("max_new_tokens") && !body["max_new_tokens"].is_null(); + const bool has_dur = body.contains("duration") && !body["duration"].is_null(); + if (has_frames && has_dur) + return fail(err_bad("duration", "give max_new_tokens or duration, not both")); + r->max_frames = info.max_frames; + if (has_frames) { + if (!body["max_new_tokens"].is_number_integer() || + body["max_new_tokens"].get() < 1 || + body["max_new_tokens"].get() > info.max_frames) + return fail(err_bad("max_new_tokens", "expected an integer in 1.." + + std::to_string(info.max_frames) + " (frames, " + + rad::fmt("%g", (double)info.frame_rate_num / + (double)info.frame_rate_den) + + " a second)")); + r->max_frames = body["max_new_tokens"].get(); + } + if (has_dur) { + const double max_s = (double)info.max_frames * info.frame_rate_den / info.frame_rate_num; + if (!body["duration"].is_number() || !(body["duration"].get() > 0) || + body["duration"].get() > max_s) + return fail(err_bad("duration", "expected seconds in (0, " + + std::to_string((int64_t)max_s) + "]")); + r->max_frames = std::max( + 1, std::min(info.max_frames, + (int64_t)std::ceil(body["duration"].get() * + info.frame_rate_num / info.frame_rate_den))); + } + if (body.contains("num_inference_steps") && !body["num_inference_steps"].is_null()) { + if (info.default_steps <= 0) + return fail(err_unsupported("num_inference_steps", "this model has no denoiser")); + if (!body["num_inference_steps"].is_number_integer() || + body["num_inference_steps"].get() < 1 || + body["num_inference_steps"].get() > 1000) + return fail(err_bad("num_inference_steps", "expected an integer in 1..1000")); + r->steps = (int32_t)body["num_inference_steps"].get(); + } + if (body.contains("guidance_scale") && !body["guidance_scale"].is_null()) { + if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get() >= 1.0) || + body["guidance_scale"].get() > 30.0) + return fail(err_bad("guidance_scale", "expected a number in [1, 30]")); + r->cfg = (float)body["guidance_scale"].get(); + } + bool seed_given = false; + if (body.contains("seed") && !body["seed"].is_null()) { + if (!body["seed"].is_number_integer()) return fail(err_bad("seed", "expected an integer")); + r->seed = (uint64_t)body["seed"].get(); + seed_given = body["seed"].is_number_unsigned() || body["seed"].get() != -1; + } + if (!seed_given) { + /* 53 bits, as the images endpoints choose one: JavaScript reads a number as a double. */ + std::random_device rd; + r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); + } + + /* ---- the prompt */ + std::string i2, t2, why; + if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0) + return fail(err_bad("instructions", why)); + if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0) + return fail(err_bad("input", why)); + /* A template a segment at a time: its own text with special tokens, each slot without. */ + auto render = [&](const std::string& t, std::vector* ids_out) { + static const std::string kInst = "{instructions}", kInput = "{input}"; + size_t at = 0; + while (at <= t.size()) { + const size_t a = t.find(kInst, at), b = t.find(kInput, at); + const size_t p = std::min(a, b); + const std::string lit = + t.substr(at, p == std::string::npos ? std::string::npos : p - at); + if (!lit.empty()) { + const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true); + ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + } + if (p == std::string::npos) break; + const bool is_inst = p == a; + const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false); + ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + at = p + (is_inst ? kInst : kInput).size(); + } + }; + render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens); + if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens); + const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size()); + if ((int64_t)n_prompt > info.max_prompt) + return fail(err_bad("input", "the prompt is " + std::to_string(n_prompt) + + " tokens; this model takes at most " + + std::to_string(info.max_prompt))); + *out = std::move(r); + return 0; +} + +HttpResponse Server::handle_speech(const HttpRequest& req) { + if (!deps_.audio || !deps_.tok) + return error_response(err_not_implemented( + opt_.image_model ? "/v1/audio/speech requires an audio generation model; this one " + "makes images" + : "/v1/audio/speech requires an audio generation model; this one " + "generates text"), req.peer); + const AudioGenInfo& info = deps_.audio->info(); + + json body = json::object(); + { + ApiError err; + if (parse_request_object(req.body, lim_, &body, &err) < 0) + return error_response(err, req.peer); + } + static const char* kKnown[] = { + "model", "input", "instructions", "voice", "response_format", "speed", "stream", + "stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps", + "guidance_scale", "user", + }; + for (auto it = body.begin(); it != body.end(); ++it) { + bool known = false; + for (const char* k : kKnown) known = known || it.key() == k; + if (!known) + return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of " + "/v1/audio/speech"), req.peer); + } + auto str = [&](const char* k, std::string* out) -> int { + if (!body.contains(k) || body[k].is_null()) return 0; + if (!body[k].is_string()) return -1; + *out = body[k].get(); + return 1; + }; + std::string text, fmt; + if (str("input", &text) <= 0 || text.find_first_not_of(" \t\r\n") == std::string::npos) + return error_response(err_bad("input", "the text is required, as a non-empty string"), + req.peer); + /* How the audio comes back: whole, as raw bytes while it is made, or as events. */ + bool stream = false; + if (body.contains("stream") && !body["stream"].is_null()) { + if (!body["stream"].is_boolean()) + return error_response(err_bad("stream", "expected a boolean"), req.peer); + stream = body["stream"].get(); + } + std::string sfmt; + if (str("stream_format", &sfmt) < 0 || (!sfmt.empty() && sfmt != "sse" && sfmt != "audio")) { + ApiError e = err_unsupported("stream_format", "a stream is sent as sse or audio"); + e.supported = { "sse", "audio" }; + return error_response(e, req.peer); + } + if (stream && sfmt == "audio") + return error_response(err_bad("stream", "stream sends Server-Sent Events and " + "stream_format audio sends the bytes themselves; " + "give one"), req.peer); + const bool sse = stream || sfmt == "sse", raw = sfmt == "audio"; + if (str("response_format", &fmt) < 0) fmt = "?"; + if (fmt.empty()) fmt = sse ? "pcm" : "wav"; + if (fmt != "wav" && fmt != "pcm") { + ApiError e = err_unsupported("response_format", "this server writes wav or pcm"); + e.supported = { "wav", "pcm" }; + return error_response(e, req.peer); + } + if (sse && fmt != "pcm") + return error_response(err_unsupported("response_format", "an event carries raw PCM; set " + "response_format pcm"), req.peer); + std::unique_ptr r; + { + ApiError err; + if (speech_request(body, text, &r, &err) < 0) return error_response(err, req.peer); + } + + /* ---- admitted and queued */ + if (auto no = admit(1, req.peer)) return *no; + r->ticket = std::make_shared(); + std::shared_ptr ticket = r->ticket; + const int64_t frames_max = r->max_frames; + const uint64_t seed = r->seed; + const int64_t n_tok = (int64_t)r->tokens.size(); + { + std::string w; + const int s = deps_.audio->submit(std::move(r), &w); + if (s < 0) { + release(1); + ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w); + if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; } + return error_response(e, req.peer); + } + } + RAD_INFO("audio: %lld prompt tokens, up to %lld frames, seed=%llu", (long long)n_tok, + (long long)frames_max, (unsigned long long)seed); + + if (sse || raw) return stream_speech(ticket, info, n_tok, seed, sse, fmt == "wav"); + + /* ---- the windows as they are played, in order */ + std::vector chunks; + for (;;) { + gen::AudioChunk c; + bool to = false; + if (ticket->next(&c, 200, &to)) { + chunks.push_back(std::move(c)); + continue; + } + if (!to) break; + if (req.peer_gone()) { + ticket->cancel.store(true); + release(1); + metrics_.observe_http(499); + return HttpResponse::text(499, "client closed request\n"); + } + if (stopping_.load()) { + ticket->cancel.store(true); + release(1); + return error_response(err_overloaded("the server is shutting down"), req.peer); + } + } + release(1); + if (ticket->status() < 0 || chunks.empty()) { + /* RAD_E_INVAL is the driver's refusal of this request (or the model ending the piece + * before it began), so a 400; anything else failed while running. */ + ApiError e; + const bool client = ticket->status() == RAD_E_INVAL; + e.status = client ? 400 : 500; + e.type = client ? "invalid_request_error" : "server_error"; + e.message = ticket->why().empty() ? "the audio generator failed" : ticket->why(); + return error_response(e, req.peer); + } + std::sort(chunks.begin(), chunks.end(), [](const gen::AudioChunk& a, const gen::AudioChunk& b) { + return a.window < b.window; + }); + std::string pcm; + for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm); + const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate); + RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs, + (long long)ticket->frames, (long long)ticket->windows, + (double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9, + ticket->model_ended ? "" : " (the request's length)"); + HttpResponse res; + res.status = 200; + if (fmt == "wav") { + res.content_type = "audio/wav"; + res.body = wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) + pcm; + } else { + res.content_type = "audio/pcm"; + res.body = std::move(pcm); + } + res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate)); + res.set_header("X-Audio-Channels", std::to_string(info.channels)); + res.set_header("X-Seed", std::to_string(seed)); + metrics_.observe_http(200); + return res; +} + +/* The piece as it is played: each window's samples once every earlier window has gone (the driver + * may finish them out of order), as bytes or as `speech.audio.delta` events. */ +HttpResponse Server::stream_speech(std::shared_ptr ticket, + const AudioGenInfo& info, int64_t n_tok, uint64_t seed, + bool sse, bool wav) { + HttpResponse res; + res.status = 200; + res.content_type = sse ? "text/event-stream" : wav ? "audio/wav" : "audio/pcm"; + if (sse) res.set_header("Cache-Control", "no-cache"); + res.set_header("X-Audio-Sample-Rate", std::to_string(info.sample_rate)); + res.set_header("X-Audio-Channels", std::to_string(info.channels)); + res.set_header("X-Seed", std::to_string(seed)); + struct State { + std::map> held; /* windows ahead of the next one */ + int32_t next = 0; + bool header = false, finished = false, released = false; + }; + auto st = std::make_shared(); + st->header = !wav || sse; + const int64_t rate = info.sample_rate, channels = info.channels; + res.next = [this, ticket, st, sse, rate, channels, n_tok](std::string& chunk) -> bool { + if (st->finished) return false; + chunk.clear(); + if (!st->header) { + chunk = wav_header(-1, rate, channels); + st->header = true; + } + gen::AudioChunk c; + bool to = false; + if (ticket->next(&c, 100, &to)) { + st->held[c.window] = std::move(c.samples); + std::string pcm; + for (auto it = st->held.find(st->next); it != st->held.end(); + it = st->held.find(st->next)) { + append_pcm16(it->second, &pcm); + st->held.erase(it); + ++st->next; + } + if (pcm.empty()) return true; + if (!sse) { + chunk += pcm; + return true; + } + json ev; + ev["type"] = "speech.audio.delta"; + ev["audio"] = base64_encode(pcm.data(), pcm.size()); + ev["response_format"] = "pcm"; + ev["sample_rate"] = rate; + ev["channels"] = channels; + chunk += "event: speech.audio.delta\ndata: " + json_dump(ev) + "\n\n"; + return true; + } + if (to) return !stopping_.load(); + st->finished = true; + if (!st->released) { st->released = true; release(1); } + if (!sse) return !chunk.empty(); + json ev; + if (ticket->status() < 0 || st->next == 0) { + ev["type"] = "speech.audio.error"; + ev["error"] = json{ + { "message", ticket->why().empty() ? "the audio generator failed" : ticket->why() }, + { "type", ticket->status() == RAD_E_INVAL ? "invalid_request_error" + : "server_error" } }; + } else { + ev["type"] = "speech.audio.done"; + ev["usage"] = json{ { "input_tokens", n_tok }, { "output_tokens", ticket->frames }, + { "total_tokens", n_tok + ticket->frames } }; + } + chunk += "event: " + ev["type"].get() + "\ndata: " + json_dump(ev) + "\n\n"; + return true; + }; + res.on_close = [this, ticket, st](bool ok) { + if (!ok) ticket->cancel.store(true); + if (!st->released) { st->released = true; release(1); } + }; + metrics_.observe_http(200); + return res; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/http.cpp b/core/server/http.cpp index a3c605a2..d6361012 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -417,6 +417,9 @@ public: return true; } bool send(const std::string& text) override { return ws_.send(text); } + bool send_binary(const std::string& bytes) override { + return ws_.send(bytes.data(), bytes.size()); + } void close(int code, const std::string& reason) override { ws_.close((httplib::ws::CloseStatus)code, reason); } diff --git a/core/server/http.h b/core/server/http.h index a3f06829..69222329 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -90,6 +90,12 @@ public: virtual bool read(std::string* msg, bool* binary) = 0; /* A text message. Safe from any thread; false once the connection is gone. */ virtual bool send(const std::string& text) = 0; + /* A binary message (raw audio). Safe from any thread; false once the connection is gone, or + * for a connection that carries text only. */ + virtual bool send_binary(const std::string& bytes) { + (void)bytes; + return false; + } /* Ends the connection with a close code and reason (RFC 6455 §7.4); a read() blocked on it * returns false once the peer has answered or gone. Safe from any thread. */ virtual void close(int code, const std::string& reason) = 0; diff --git a/core/server/iface.h b/core/server/iface.h index 6566ed41..a91cd094 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -20,7 +20,7 @@ #include namespace rad { -namespace gen { struct Request; } +namespace gen { struct Request; struct AudioRequest; class AudioTicket; struct VideoRequest; class VideoTicket; } namespace mm { struct Frame; struct Item; } namespace server { @@ -599,5 +599,59 @@ public: virtual int64_t running() const = 0; }; +/* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from + * text: its declared prompt template and limits, the plugin's rewrite of a request's texts into + * the form it was trained on, and its request queue. The server renders and tokenises the prompt + * and reads the audio back off the ticket, a window at a time. */ +struct AudioGenInfo { + /* The prompt templates (RadAudioGenDecl): with instructions, without them ("" makes them + * required), and the unconditional branch's own ("" derives it from the conditional prompt). */ + std::string name, tmpl, tmpl_plain, neg_tmpl; + int64_t max_prompt = 0, max_frames = 0, frame_rate_num = 1, frame_rate_den = 1; + int64_t sample_rate = 0, channels = 0; + int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */ + double default_cfg = 1.0; +}; + +class IAudioGen { +public: + virtual ~IAudioGen() = default; + virtual const AudioGenInfo& info() const = 0; + /* `in` rewritten as the model wants text for `field` (RAD_TEXT_*); the text unchanged when the + * plugin states no rewrite. RAD_E_INVAL with `why` for text the model cannot take. */ + virtual int prepare(int field, const std::string& in, std::string* out, + std::string* why) const = 0; + /* Queue a request; refused at once, with `why`, when it can never run. */ + virtual int submit(std::unique_ptr r, std::string* why) = 0; + virtual int64_t queued() const = 0; + virtual int64_t running() const = 0; +}; + +/* The video generator (core/gen/video_driver.h), for a model that makes a video and its + * soundtrack from text: its declared prompt template, sizes and lengths, and its request queue. + * The server renders and tokenises the prompt, queues the request as a job, and turns what the + * ticket hands back into an MP4 file. */ +struct VideoGenInfo { + std::string name, tmpl; + int64_t max_text = 0; + int64_t fps_num = 1, fps_den = 1; + int64_t frames_per_chunk = 1, frames_tail = 0, min_chunks = 1, max_chunks = 1; + int64_t size_multiple = 32, min_side = 0, max_area = 0, max_aspect = 1; + int64_t default_width = 0, default_height = 0, default_chunks = 1; + int64_t sample_rate = 0, channels = 0; + int64_t default_steps = 0, max_steps = 0, max_lanes = 1; + bool fixed_steps = false; /* a trained schedule: max_steps grid points and no other */ +}; + +class IVideoGen { +public: + virtual ~IVideoGen() = default; + virtual const VideoGenInfo& info() const = 0; + /* Queue a request; refused at once, with `why`, when it can never run. */ + virtual int submit(std::unique_ptr r, std::string* why) = 0; + virtual int64_t queued() const = 0; + virtual int64_t running() const = 0; +}; + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 49429f9b..692368e4 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -313,7 +313,9 @@ const Guarded kGuarded[] = { "implemented" }, { "suffix", empty_value, "an empty string", "infilling through /v1/completions is not " "implemented" }, - { "lora", empty_value, "an empty list", "LoRA is explicitly out of scope (spec, Scope)" }, + { "lora", empty_value, "an empty list", + "a per-request adapter list is not served; a runtime LoRA adapter is chosen by `model` " + "(--lora)" }, { "modalities", text_only, "[\"text\"]", "output modalities other than text are not " "implemented" }, { "audio", empty_value, "null", "audio output is not implemented" }, diff --git a/core/server/server.cpp b/core/server/server.cpp index f9ec2ad6..52cc164a 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -96,6 +96,14 @@ void Server::register_routes() { router_.post("/v1/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); }); router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); }); /* Speech to text, for a model whose plugin says how it transcribes (RadAudioFormat). */ + router_.post("/v1/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); }); + router_.post("/v1/videos", [this](const HttpRequest& q) { return handle_video_create(q); }); + router_.get ("/v1/videos", [this](const HttpRequest& q) { return handle_video_list(q); }); + router_.get ("/v1/videos/:id", [this](const HttpRequest& q) { return handle_video_get(q); }); + router_.add ("DELETE", "/v1/videos/:id", + [this](const HttpRequest& q) { return handle_video_delete(q); }); + router_.get ("/v1/videos/:id/content", + [this](const HttpRequest& q) { return handle_video_content(q); }); router_.post("/v1/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); }); /* The same, live over a WebSocket (OpenAI's realtime transcription session). A plain GET @@ -110,6 +118,19 @@ void Server::register_routes() { r.set_header("Upgrade", "websocket"); return r; }); + /* Speech made while its text is still being written (vLLM-Omni's realtime speech session). */ + router_.socket("/v1/audio/speech/stream", + [this](const HttpRequest& q, WsConn& c) { handle_speech_stream(q, c); }); + router_.get ("/v1/audio/speech/stream", [this](const HttpRequest& q) { + ApiError e; + e.status = 426; + e.type = "invalid_request_error"; + e.message = "/v1/audio/speech/stream is a WebSocket: connect with an Upgrade: websocket " + "request"; + HttpResponse r = error_response(e, q.peer); + r.set_header("Upgrade", "websocket"); + return r; + }); router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); }); router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); }); @@ -126,6 +147,7 @@ void Server::register_routes() { router_.post("/images/generations", [this](const HttpRequest& q) { return handle_images(q, false); }); router_.post("/images/edits", [this](const HttpRequest& q) { return handle_images(q, true); }); router_.post("/audio/transcriptions", [this](const HttpRequest& q) { return handle_transcription(q); }); + router_.post("/audio/speech", [this](const HttpRequest& q) { return handle_speech(q); }); router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); }); /* llama-server's: the prompt a chat request renders to, and how many tokens it is. */ router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); }); @@ -281,6 +303,7 @@ std::string Server::check_thinking_budget() const { void Server::stop() { stopping_.store(true); transport_.stop(); + stop_videos(); drain_graveyard(2000); } @@ -390,9 +413,9 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr } } - /* RUNTIME LoRA: `model` picks the adapter. The served model's own name, or no name, is the - * base; with adapters enabled anything else must be a loaded adapter -- a typo served by the - * base would answer as the wrong model and say nothing. */ + /* Runtime LoRA: `model` picks the adapter. The served model's own name, or no name, is the + * base; with adapters enabled anything else must be a loaded adapter, since a typo served by + * the base would answer as the wrong model without a word. */ int32_t lora_slot = -1; uint64_t lora_uid = 0; std::shared_ptr lora_hold; @@ -1269,6 +1292,10 @@ std::optional Server::refuse_text(const std::string& peer, ApiShap "generates no text" : opt_.image_model ? "this is an image model: it serves /v1/images/generations " "and /v1/images/edits and generates no text" + : opt_.audio_model ? "this is an audio model: it serves /v1/audio/speech and " + "generates no text" + : opt_.video_model ? "this is a video model: it serves /v1/videos and generates " + "no text" : nullptr; if (!why) return std::nullopt; return error_response(err_not_implemented(why), peer, shape); @@ -1536,8 +1563,10 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) { if (!deps_.embed) return error_response(err_not_implemented( opt_.image_model ? "/v1/embeddings requires an embedding model; this one makes images" - : "/v1/embeddings requires an embedding model; this one generates " - "text"), req.peer); + : opt_.audio_model ? "/v1/embeddings requires an embedding model; this one makes audio" + : opt_.video_model ? "/v1/embeddings requires an embedding model; this one makes video" + : "/v1/embeddings requires an embedding model; this one generates " + "text"), req.peer); OaiRequest r; ApiError err; @@ -1775,7 +1804,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) { HttpResponse Server::handle_models(const HttpRequest& req) { const std::string id = req.param("id"); - /* RUNTIME LoRA: each loaded adapter is a model of its own, whose parent is the served one. */ + /* Runtime LoRA: each loaded adapter is a model of its own, whose parent is the served one. */ std::vector adapters; if (opt_.lora_names) adapters = opt_.lora_names(); const bool is_adapter = !id.empty() && std::find(adapters.begin(), adapters.end(), id) != adapters.end(); @@ -1805,9 +1834,9 @@ HttpResponse Server::handle_models(const HttpRequest& req) { return HttpResponse::json_body(200, id.empty() ? models_body(cards) : model_body(c)); } -/* RUNTIME LoRA ADMIN, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"} - * to unload. The path is read on THIS machine, so without --api-key only a loopback client may ask - * -- the rule /diagnostics follows. */ +/* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"} + * to unload. The path is read on this machine, so without --api-key only a loopback client may + * ask, the rule /diagnostics follows. */ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) { using json = nlohmann::json; auto fail = [&](int status, const char* type, const std::string& msg) { @@ -1845,10 +1874,10 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) { if (s == RAD_E_STATE) return fail(409, "conflict_error", err); if (s == RAD_E_FULL) return fail(503, "service_unavailable", err); if (s < 0) return fail(400, "invalid_request_error", err.empty() ? std::string(rad_strerror(s)) : err); - /* AN UNLOAD OF AN ADAPTER IN USE DRAINS IT (lora/slots.h): accepted, not done. New requests - * naming it are already refused as an unknown model and it is off /v1/models; the requests - * counted here finish normally, and the last of them frees the slot. Asking again answers - * the same with the count as it is then, and a 404 once it is gone. */ + /* An unload of an adapter in use drains it (lora/slots.h): accepted, not done. New requests + * naming it are refused as an unknown model and it is off /v1/models; the requests counted + * here finish, and the last of them frees the slot. Asking again answers with the count as it + * is then, and 404 once it is gone. */ if (!load && in_flight > 0) { metrics_.observe_http(202); return HttpResponse::json_body(202, json{ { "action", "draining" }, { "lora_name", name }, diff --git a/core/server/server.h b/core/server/server.h index a9bc7ab2..99822fe2 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -39,6 +39,8 @@ struct Deps { IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */ IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */ IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */ + IAudioGen* audio = nullptr; /* absent -> /v1/audio/speech is 501 */ + IVideoGen* videos = nullptr; /* absent -> /v1/videos is 501 */ const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */ /* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot @@ -56,6 +58,16 @@ struct ServerOptions { /* An image generator (rad_declare_generator) generates no text: the text endpoints answer * 501 naming /v1/images/generations and /v1/images/edits. */ bool image_model = false; + /* An audio generator (rad_declare_audio_generator) generates no text either: the text + * endpoints answer 501 naming /v1/audio/speech. */ + bool audio_model = false; + /* A video generator (rad_declare_video_generator) generates no text either: the text + * endpoints answer 501 naming /v1/videos. */ + bool video_model = false; + /* How long a finished video's file is kept for /v1/videos/{id}/content, in seconds, and how + * many finished videos are kept at most (the oldest go first). */ + int64_t video_ttl_s = 3600; + int64_t max_videos = 32; /* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone * (systemone.h); empty answers it 501. Never inferred from a name. */ std::string decision_type; @@ -119,7 +131,7 @@ struct ServerOptions { * clock only mean something under load: queried during a long prefill, it tells a link parked * below its maximum from one at rest. */ std::function diagnostics_json; - /* RUNTIME LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that + /* Runtime LoRA (Engine::lora_acquire): a request's `model` naming a loaded adapter gets that * adapter's slot, load uid and a hold on it. Unset with LoRA off, and then any `model` is * served by the base. `lora_names` lists the adapters a request may name (not the draining * ones). */ @@ -183,6 +195,8 @@ private: struct Generation; struct TranscriptionJob; /* speech.cpp */ struct RealtimeSession; /* realtime.cpp */ + struct SpeechSession; /* speech_stream.cpp */ + struct VideoJob; /* videos.cpp */ struct StreamState; static UsageOut usage_of(const OaiRequest& r, const std::vector& gens); @@ -226,6 +240,37 @@ private: /* ------------------------------------------------------------------ images.cpp */ HttpResponse handle_images(const HttpRequest& req, bool edit); + /* ------------------------------------------------------------------ audio_gen.cpp */ + HttpResponse handle_speech(const HttpRequest& req); + /* The audio a speech request describes, `text` its input, as the generator's request; -1 with + * `err` naming the field. Shared by the route and the realtime session. */ + int speech_request(const json& body, const std::string& text, + std::unique_ptr* out, ApiError* err); + HttpResponse stream_speech(std::shared_ptr ticket, const AudioGenInfo& info, + int64_t n_tok, uint64_t seed, bool sse, bool wav); + + /* ------------------------------------------------------------------ videos.cpp + * OpenAI's video jobs: created by POST, made in the background, polled and downloaded. */ + HttpResponse handle_video_create(const HttpRequest& req); + HttpResponse handle_video_list(const HttpRequest& req); + HttpResponse handle_video_get(const HttpRequest& req); + HttpResponse handle_video_delete(const HttpRequest& req); + HttpResponse handle_video_content(const HttpRequest& req); + /* A job's thread: the ticket's events into progress and an MP4 file. */ + void video_work(std::shared_ptr j); + /* Drops expired and surplus finished jobs; under videos_m_. */ + void sweep_videos_locked(int64_t now); + /* Cancels every job and joins its thread; at stop(). */ + void stop_videos(); + static json video_json(const VideoJob& j); + + /* ------------------------------------------------------------------ speech_stream.cpp */ + /* vLLM-Omni's realtime speech session over a WebSocket at /v1/audio/speech/stream: text + * streamed in, each sentence's audio streamed out as soon as the sentence is complete. */ + void handle_speech_stream(const HttpRequest& req, WsConn& ws); + void speech_stream_run(SpeechSession& s, WsConn& ws); + bool speech_stream_loop(SpeechSession& s, WsConn& ws); + /* ------------------------------------------------------------------ admin.cpp * vLLM's non-generation surface, answered on the HTTP thread without the step path, the * admission queue or a Sink. */ @@ -303,6 +348,7 @@ private: std::atomic in_flight_{0}; int64_t queue_depth_ = 0; std::atomic realtime_sessions_{0}; + std::atomic speech_sessions_{0}; std::atomic stopping_{false}; int64_t started_at_ = 0; @@ -311,6 +357,12 @@ private: * it under a running step is a use-after-free. */ std::mutex grave_m_; std::vector> grave_; + + /* The video jobs, oldest first, and the threads that make them (videos.cpp); deleted jobs + * wait in `videos_gone_` until their threads are done. */ + std::mutex videos_m_; + std::vector> videos_; + std::vector> videos_gone_; }; } /* namespace server */ diff --git a/core/server/server_priv.h b/core/server/server_priv.h index b4122cfa..ebcfe31f 100644 --- a/core/server/server_priv.h +++ b/core/server/server_priv.h @@ -86,5 +86,11 @@ size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, b * between words when there is a pause to cut in. */ int64_t speech_quiet_point(const std::vector& x, int64_t lo, int64_t hi, int32_t rate); +/* ---- audio_gen.cpp: what the audio generator's routes write */ +/* Samples in [-1, 1] as 16-bit little-endian PCM, appended. */ +void append_pcm16(const std::vector& x, std::string* out); +/* A RIFF/WAVE header for `bytes` of 16-bit PCM; -1 states no length, as a stream's must. */ +std::string wav_header(int64_t bytes, int64_t rate, int64_t channels); + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/speech_stream.cpp b/core/server/speech_stream.cpp new file mode 100644 index 00000000..120ed085 --- /dev/null +++ b/core/server/speech_stream.cpp @@ -0,0 +1,452 @@ +/* speech_stream.cpp -- vLLM-Omni's realtime speech session, over a WebSocket at + * /v1/audio/speech/stream. + * + * The POST route (audio_gen.cpp) speaks a text it is given whole. This one is sent the text as it + * is produced, a language model's reply token by token or a typist's keystrokes, and speaks each + * sentence as soon as it is complete: the first audio waits for the first sentence, not the text. + * + * Protocol: vLLM-Omni's, in its buffered text mode. The client sends `session.config` first (the + * POST route's fields but `input`, and `response_format` pcm or wav, `stream_audio`, + * `split_granularity` none / sentence / clause, `text_input_mode` buffered), then `input.text` + * {text} pieces, `input.done` to end an utterance, and `session.close`. The server answers each + * sentence with `audio.start` {utterance_index, sentence_index, sentence_text, format, + * sample_rate, channels}, its audio as binary messages of 16-bit little-endian PCM (one with + * `stream_audio` false; several, as the vocoder plays it, with it true; a wav begins with a header + * that states its length, or none while it streams), and `audio.done` {utterance_index, + * sentence_index, total_bytes, error}; once an utterance's last sentence is spoken, + * `session.done` {utterance_index, total_sentences}. The session stays open for the next + * utterance until `session.close` or the socket's close. A refusal or failure is `error` + * {message, param}; the session goes on. + * + * A sentence is one request, built from the session's fields as the POST route builds one + * (Server::speech_request), and the sentences of a session are spoken one at a time in order. + * + * Threads: the connection's thread reads messages and queues them. The session's thread does + * everything else, so the session's state has one owner and its messages go out in the order they + * happen. + */ +#include "server.h" +#include "server_priv.h" +#include "text_split.h" + +#include "gen/audio.h" +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +using ojson = nlohmann::ordered_json; + +/* The client messages a session may have queued and not yet taken in. */ +constexpr size_t kMaxQueuedBytes = 16u << 20; +/* An utterance's text not yet spoken: a client that never ends a sentence is refused past it. */ +constexpr size_t kMaxPendingBytes = 128u << 10; + +ojson event(const char* type) { + ojson o; + o["type"] = type; + return o; +} + +/* The fields that shape the session rather than each sentence's request. */ +bool session_field(const std::string& k) { + return k == "type" || k == "stream_audio" || k == "split_granularity" || + k == "text_input_mode" || k == "response_format"; +} + +} /* namespace */ + +struct Server::SpeechSession { + std::string id; + std::string peer; + + /* The connection's thread to the session's: messages, and whether the peer is gone. */ + std::mutex m; + std::condition_variable cv; + std::deque> inbox; /* (message, binary) */ + size_t inbox_bytes = 0; + bool peer_gone = false; + bool overflow = false; + + /* Everything below is the session thread's alone. */ + bool configured = false; + json fields = json::object(); /* every sentence's request, but its input */ + bool stream_audio = false; + bool wav = false; + TextSplit split = TextSplit::Sentence; + + std::string pending; /* the utterance's text not yet a sentence */ + std::deque sentences; /* complete, not yet spoken */ + bool done_asked = false; /* input.done: the utterance ends once spoken */ + int64_t utterance = 0; + int64_t sentence = 0; /* the utterance's next sentence index */ + int64_t spoken = 0; /* sentences over the session's life */ + + /* The sentence being spoken. */ + struct Current { + bool active = false; + std::shared_ptr ticket; + int64_t index = 0; + std::map> held; /* chunks ahead of the next one */ + int32_t next = 0; + std::string pcm; /* the whole sentence, when it is sent at once */ + int64_t bytes = 0; /* binary bytes sent for it */ + } cur; +}; + +/* ------------------------------------------------------------------ the connection's thread */ + +void Server::handle_speech_stream(const HttpRequest& req, WsConn& ws) { + auto refuse = [&](const std::string& why, int close_code, const char* reason) { + ojson o = event("error"); + o["message"] = why; + ws.send(json_dump(o)); + RAD_INFO("speech stream refused from %s: %s", req.peer.c_str(), why.c_str()); + ws.close(close_code, reason); + }; + if (stopping_.load()) return refuse("the server is shutting down", 1001, "shutting down"); + if (!deps_.audio || !deps_.tok) + return refuse("/v1/audio/speech/stream requires an audio generation model; this one " + "makes none", 1008, "model not supported"); + /* A session speaks one sentence at a time: more sessions than the generator has lanes would + * only queue. */ + const int64_t cap = std::max(1, deps_.audio->info().max_lanes); + if (speech_sessions_.fetch_add(1) >= cap) { + speech_sessions_.fetch_sub(1); + return refuse(fmt("this server holds %lld speech sessions at once; try again later", + (long long)cap), 1013, "session limit"); + } + struct Count { + std::atomic& n; + ~Count() { n.fetch_sub(1); } + } count{ speech_sessions_ }; + /* One admission place for the session's whole life, as the realtime transcription session + * holds one. */ + if (admit(1, req.peer)) + return refuse("the admission queue is full; try again later", 1013, "rate limited"); + struct Place { + Server& srv; + ~Place() { srv.release(1); } + } place{ *this }; + + SpeechSession s; + s.id = random_id("speech_"); + s.peer = req.peer; + std::thread worker([this, &s, &ws] { speech_stream_run(s, ws); }); + /* The session's thread ends once the peer is gone, however this one leaves. */ + struct Join { + SpeechSession& s; + std::thread& t; + ~Join() { + { + std::lock_guard lk(s.m); + s.peer_gone = true; + } + s.cv.notify_one(); + if (t.joinable()) t.join(); + } + } join{ s, worker }; + + std::string msg; + bool binary = false; + while (ws.read(&msg, &binary)) { + std::lock_guard lk(s.m); + if (s.inbox_bytes + msg.size() > kMaxQueuedBytes) { + s.overflow = true; + s.cv.notify_one(); + break; + } + s.inbox_bytes += msg.size(); + s.inbox.emplace_back(std::move(msg), binary); + s.cv.notify_one(); + } +} + +/* ------------------------------------------------------------------ the session's thread */ + +void Server::speech_stream_run(SpeechSession& s, WsConn& ws) { + try { + speech_stream_loop(s, ws); + } catch (const std::exception& e) { + RAD_ERR("speech stream %s failed: %s", s.id.c_str(), e.what()); + ojson o = event("error"); + o["message"] = std::string("the session failed: ") + e.what(); + ws.send(json_dump(o)); + ws.close(1011, "internal error"); + } + if (s.cur.active) s.cur.ticket->cancel.store(true); + RAD_INFO("speech stream %s closed: %lld utterances, %lld sentences", s.id.c_str(), + (long long)s.utterance, (long long)s.spoken); +} + +bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) { + const AudioGenInfo& info = deps_.audio->info(); + auto send = [&](const ojson& o) { ws.send(json_dump(o)); }; + auto error = [&](const std::string& why, const std::string& param = std::string()) { + ojson o = event("error"); + o["message"] = why; + o["param"] = param.empty() ? ojson(nullptr) : ojson(param); + send(o); + }; + auto binary = [&](const std::string& bytes) { + if (bytes.empty()) return; + ws.send_binary(bytes); + s.cur.bytes += (int64_t)bytes.size(); + }; + + /* ---- session.config: checked whole, then applied whole, between utterances only */ + auto configure = [&](const json& j) { + if (s.cur.active || !s.sentences.empty() || !s.pending.empty() || s.done_asked) + return error("session.config applies between utterances; this one is still being " + "spoken"); + static const char* kFields[] = { + "type", "model", "instructions", "voice", "response_format", "speed", "seed", + "max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user", + "stream_audio", "split_granularity", "text_input_mode", + }; + json fields = json::object(); + for (auto it = j.begin(); it != j.end(); ++it) { + bool known = false; + for (const char* k : kFields) known = known || it.key() == k; + if (it.key() == "input") + return error("the text arrives in input.text messages, not in the configuration", + "input"); + if (!known) + return error("'" + it.key() + "' is not a field of session.config", it.key()); + if (!session_field(it.key())) fields[it.key()] = it.value(); + } + if (j.contains("text_input_mode") && !j["text_input_mode"].is_null()) { + const json& m = j["text_input_mode"]; + if (!m.is_string() || (m != "buffered" && m != "commitment")) + return error("text_input_mode is buffered", "text_input_mode"); + if (m == "commitment") + return error("text_input_mode commitment is not served here; buffered is", + "text_input_mode"); + } + TextSplit split = TextSplit::Sentence; + if (j.contains("split_granularity") && !j["split_granularity"].is_null()) { + const json& g = j["split_granularity"]; + if (g == "none") split = TextSplit::None; + else if (g == "clause") split = TextSplit::Clause; + else if (g != "sentence") + return error("split_granularity is none, sentence or clause", "split_granularity"); + } + bool stream_audio = false; + if (j.contains("stream_audio") && !j["stream_audio"].is_null()) { + if (!j["stream_audio"].is_boolean()) + return error("stream_audio is a boolean", "stream_audio"); + stream_audio = j["stream_audio"].get(); + } + bool wav = false; + if (j.contains("response_format") && !j["response_format"].is_null()) { + const json& f = j["response_format"]; + if (f != "pcm" && f != "wav") + return error("response_format is pcm or wav", "response_format"); + wav = f == "wav"; + } + /* The request fields as every sentence will be made with them, tried on a stand-in. */ + std::unique_ptr probe; + ApiError err; + if (speech_request(fields, "a", &probe, &err) < 0) return error(err.message, err.param); + s.fields = std::move(fields); + s.split = split; + s.stream_audio = stream_audio; + s.wav = wav; + s.configured = true; + }; + + auto take = [&](bool final) { + for (std::string& u : take_text_units(&s.pending, s.split, final)) + s.sentences.push_back(std::move(u)); + }; + + /* Returns true when the session is over. */ + auto handle = [&](const std::string& msg, bool bin) -> bool { + if (bin) { + error("this session takes JSON messages: session.config, input.text, input.done and " + "session.close"); + return false; + } + const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false); + if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) { + error("a client message is a JSON object with a string `type`"); + return false; + } + const std::string type = j["type"].get(); + if (type == "session.config") { + configure(j); + return false; + } + if (type == "session.close") { + ws.close(1000, "session closed"); + return true; + } + if (type != "input.text" && type != "input.done") { + error("this session takes session.config, input.text, input.done and session.close; " + "not '" + type + "'", "type"); + return false; + } + if (!s.configured) { + error("send session.config before any text"); + return false; + } + if (type == "input.done") { + take(true); + s.done_asked = true; + return false; + } + if (!j.contains("text") || !j["text"].is_string()) { + error("input.text carries `text`, a string", "text"); + return false; + } + const std::string& t = j["text"].get_ref(); + if (s.pending.size() + t.size() > kMaxPendingBytes) { + error(fmt("the utterance holds more than %zu KiB of text without a sentence's end; " + "this piece was dropped", kMaxPendingBytes >> 10), "text"); + return false; + } + s.pending += t; + take(false); + return false; + }; + + /* ---- a sentence: begun, its chunks sent as they come in order, and ended */ + auto done = [&](bool failed) { + ojson o = event("audio.done"); + o["utterance_index"] = s.utterance; + o["sentence_index"] = s.cur.index; + o["total_bytes"] = s.cur.bytes; + o["error"] = failed; + send(o); + s.cur = SpeechSession::Current{}; + ++s.spoken; + }; + auto begin = [&]() { + const std::string text = std::move(s.sentences.front()); + s.sentences.pop_front(); + s.cur = SpeechSession::Current{}; + s.cur.index = s.sentence++; + ojson o = event("audio.start"); + o["utterance_index"] = s.utterance; + o["sentence_index"] = s.cur.index; + o["sentence_text"] = text; + o["format"] = s.wav ? "wav" : "pcm"; + o["sample_rate"] = info.sample_rate; + o["channels"] = info.channels; + send(o); + std::unique_ptr r; + ApiError err; + if (speech_request(s.fields, text, &r, &err) < 0) { + error(err.message, err.param); + return done(true); + } + r->ticket = std::make_shared(); + std::shared_ptr ticket = r->ticket; + std::string why; + const int st = deps_.audio->submit(std::move(r), &why); + if (st < 0) { + error(why.empty() ? std::string(rad_strerror(st)) : why); + return done(true); + } + s.cur.active = true; + s.cur.ticket = std::move(ticket); + if (s.stream_audio && s.wav) binary(wav_header(-1, info.sample_rate, info.channels)); + }; + auto poll = [&](int wait_ms) { + gen::AudioChunk c; + bool to = false; + for (int ms = wait_ms;; ms = 0) { + if (s.cur.ticket->next(&c, ms, &to)) { + s.cur.held[c.window] = std::move(c.samples); + std::string pcm; + for (auto it = s.cur.held.find(s.cur.next); it != s.cur.held.end(); + it = s.cur.held.find(s.cur.next)) { + append_pcm16(it->second, &pcm); + s.cur.held.erase(it); + ++s.cur.next; + } + if (s.stream_audio) binary(pcm); + else s.cur.pcm += pcm; + continue; + } + if (to) return; + /* The sentence has ended. */ + gen::AudioTicket& t = *s.cur.ticket; + if (t.status() < 0 || s.cur.next == 0) { + error(t.why().empty() ? "the audio generator failed" : t.why()); + return done(true); + } + if (!s.stream_audio) { + const std::string& pcm = s.cur.pcm; + binary(s.wav ? wav_header((int64_t)pcm.size(), info.sample_rate, info.channels) + + pcm + : pcm); + } + return done(false); + } + }; + + /* ---- the loop */ + RAD_INFO("speech stream %s open from %s", s.id.c_str(), s.peer.c_str()); + for (;;) { + std::deque> got; + bool gone = false, overflow = false; + { + std::unique_lock lk(s.m); + const bool work = s.cur.active || !s.sentences.empty() || s.done_asked; + if (s.inbox.empty() && !s.peer_gone && !s.overflow && !work) + s.cv.wait_for(lk, std::chrono::milliseconds(100)); + got.swap(s.inbox); + s.inbox_bytes = 0; + gone = s.peer_gone; + overflow = s.overflow; + } + if (overflow) { + error(fmt("the session fell more than %zu MiB of messages behind", + kMaxQueuedBytes >> 20)); + ws.close(1008, "buffer overflow"); + return true; + } + for (const auto& m : got) + if (handle(m.first, m.second)) return true; + if (gone) return false; + if (stopping_.load()) { + error("the server is shutting down"); + ws.close(1001, "closing"); + return true; + } + if (!s.cur.active && !s.sentences.empty()) begin(); + if (s.cur.active) { + bool idle; + { + std::lock_guard lk(s.m); + idle = s.inbox.empty() && !s.peer_gone; + } + poll(idle ? 10 : 0); + } + if (!s.cur.active && s.sentences.empty() && s.done_asked) { + ojson o = event("session.done"); + o["utterance_index"] = s.utterance; + o["total_sentences"] = s.sentence; + send(o); + ++s.utterance; + s.sentence = 0; + s.done_asked = false; + } + } +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/text_split.cpp b/core/server/text_split.cpp new file mode 100644 index 00000000..1b920d20 --- /dev/null +++ b/core/server/text_split.cpp @@ -0,0 +1,195 @@ +/* text_split.cpp -- sentence and clause units of text that arrives in pieces (text_split.h). */ +#include "text_split.h" + +#include +#include + +namespace rad { +namespace server { + +namespace { + +/* The code point at `i` and its length in bytes; a byte that starts no valid sequence is read as + * itself, one byte long, so malformed text still advances. */ +uint32_t cp_at(const std::string& s, size_t i, size_t* len) { + const unsigned char c = (unsigned char)s[i]; + auto cont = [&](size_t k) { + return i + k < s.size() && ((unsigned char)s[i + k] & 0xC0) == 0x80; + }; + if (c < 0x80) { *len = 1; return c; } + if ((c & 0xE0) == 0xC0 && cont(1)) { + *len = 2; + return ((uint32_t)(c & 0x1F) << 6) | ((unsigned char)s[i + 1] & 0x3F); + } + if ((c & 0xF0) == 0xE0 && cont(1) && cont(2)) { + *len = 3; + return ((uint32_t)(c & 0x0F) << 12) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 6) | + ((unsigned char)s[i + 2] & 0x3F); + } + if ((c & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) { + *len = 4; + return ((uint32_t)(c & 0x07) << 18) | ((uint32_t)((unsigned char)s[i + 1] & 0x3F) << 12) | + ((uint32_t)((unsigned char)s[i + 2] & 0x3F) << 6) | ((unsigned char)s[i + 3] & 0x3F); + } + *len = 1; + return c; +} + +bool ends_sentence(uint32_t c) { + switch (c) { + case '.': case '!': case '?': + case 0x3002: /* 。 */ + case 0xFF01: /* ! */ + case 0xFF1F: /* ? */ + case 0xFF0E: /* . */ + case 0x2026: /* … */ + case 0x0964: /* । */ + case 0x0965: /* ॥ */ + case 0x061F: /* ؟ */ + return true; + default: + return false; + } +} + +bool ends_clause(uint32_t c) { + switch (c) { + case ',': case ';': + case 0xFF0C: /* , */ + case 0xFF1B: /* ; */ + case 0x060C: /* ، */ + case 0x061B: /* ؛ */ + return true; + default: + return false; + } +} + +/* What may follow a unit's closing punctuation and still belong to it. */ +bool closes(uint32_t c) { + switch (c) { + case ')': case ']': case '}': case '"': case '\'': + case 0x201D: case 0x2019: case 0x00BB: /* ” ’ » */ + case 0x300D: case 0x300F: case 0xFF09: case 0x3011: /* 」 』 ) 】 */ + case 0x300B: case 0x3009: case 0x3015: case 0xFF3D: /* 》 〉 〕 ] */ + case 0xFF5D: /* } */ + return true; + default: + return false; + } +} + +bool space_cp(uint32_t c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' || + c == 0x00A0 || c == 0x3000; +} + +/* A full stop that ends no sentence: one closing a common abbreviation or an initial. `word` is + * the text from the last whitespace to the stop, the stop included. */ +bool no_stop(std::string word) { + while (!word.empty() && (word[0] == '(' || word[0] == '"' || word[0] == '\'' || + word[0] == '[')) + word.erase(0, 1); + std::string low; + for (char ch : word) low += (char)std::tolower((unsigned char)ch); + static const char* const kAbbrev[] = { + "mr.", "mrs.", "ms.", "dr.", "prof.", "sr.", "jr.", "st.", "mt.", "vs.", "etc.", "e.g.", + "i.e.", "inc.", "ltd.", "co.", "no.", "fig.", "approx.", "dept.", "est.", + }; + for (const char* a : kAbbrev) + if (low == a) return true; + /* An initial or a run of them: "J." or "J.R.", each an upper-case letter and a stop. */ + if (word.size() >= 2 && word.size() % 2 == 0 && std::isupper((unsigned char)word[0])) { + bool initials = true; + for (size_t k = 0; k < word.size(); k += 2) + initials = initials && std::isalpha((unsigned char)word[k]) && word[k + 1] == '.'; + if (initials) return true; + } + return false; +} + +std::string trim(const std::string& s, size_t a, size_t b) { + while (a < b) { + size_t n = 1; + if (!space_cp(cp_at(s, a, &n))) break; + a += n; + } + while (b > a && std::isspace((unsigned char)s[b - 1])) --b; + return s.substr(a, b - a); +} + +/* Whether a unit carries anything to say: some character that is no punctuation or space. */ +bool says_something(const std::string& u) { + for (size_t i = 0; i < u.size();) { + size_t n = 1; + const uint32_t c = cp_at(u, i, &n); + i += n; + if (space_cp(c) || ends_sentence(c) || ends_clause(c) || closes(c)) continue; + if (c < 0x80 && std::ispunct((int)c)) continue; + return true; + } + return false; +} + +} /* namespace */ + +std::vector take_text_units(std::string* pending, TextSplit mode, bool final) { + std::vector out; + std::string& s = *pending; + auto push = [&](std::string u) { + if (says_something(u)) out.push_back(std::move(u)); + }; + size_t start = 0; + if (mode != TextSplit::None) { + size_t i = 0; + while (i < s.size()) { + size_t n = 1; + const uint32_t c = cp_at(s, i, &n); + const bool term = ends_sentence(c) || (mode == TextSplit::Clause && ends_clause(c)); + if (!term) { i += n; continue; } + /* The punctuation run: further stops and closing quotes or brackets. */ + size_t j = i + n; + while (j < s.size()) { + size_t m = 1; + const uint32_t d = cp_at(s, j, &m); + if (!(ends_sentence(d) || ends_clause(d) || closes(d))) break; + j += m; + } + if (j == s.size()) { + /* Whether the unit ended shows only in what comes next. */ + if (!final) break; + i = j; + continue; + } + size_t m = 1; + const uint32_t next = cp_at(s, j, &m); + const bool ascii = c < 0x80; + bool boundary = ascii ? space_cp(next) : true; + if (boundary && c == '.') { + size_t w = i; + while (w > start && !std::isspace((unsigned char)s[w - 1])) --w; + boundary = !no_stop(s.substr(w, i + 1 - w)); + } + if (!boundary) { i = j; continue; } + push(trim(s, start, j)); + /* The next unit starts at its first character. */ + while (j < s.size()) { + size_t k = 1; + if (!space_cp(cp_at(s, j, &k))) break; + j += k; + } + start = j; + i = j; + } + } + if (final) { + push(trim(s, start, s.size())); + s.clear(); + } else { + s.erase(0, start); + } + return out; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/text_split.h b/core/server/text_split.h new file mode 100644 index 00000000..04f0b2ae --- /dev/null +++ b/core/server/text_split.h @@ -0,0 +1,35 @@ +/* text_split.h -- text that arrives in pieces, cut into the units a speech model reads one at a + * time: sentences, or clauses (text_split.cpp). + * + * The realtime speech session (speech_stream.cpp) is sent text as a client produces it, a language + * model's tokens or a typist's keystrokes, and speaks each unit as soon as it is complete, so the + * first audio does not wait for the whole text. A unit is complete once the text after its closing + * punctuation shows that it ended; the end of the input ends the last one. + */ +#pragma once + +#include +#include + +namespace rad { +namespace server { + +enum class TextSplit { + None, /* no cutting: the whole input is one unit */ + Sentence, /* after . ! ? and their CJK, Indic and Arabic forms */ + Clause, /* also after , ; and their full-width and Arabic forms */ +}; + +/* The complete units at the front of `*pending`, trimmed, in order; `*pending` keeps the rest. + * With `final` (the input has ended) the rest is a unit too and `*pending` is left empty. + * + * A unit ends at its closing punctuation together with any run of punctuation and closing quotes + * or brackets after it ("Really?!", "he said.”"). After ASCII punctuation the end needs + * whitespace to follow, so "3.14" and "a.b" do not end one; after full-width, CJK, Indic or Arabic + * punctuation any next character does, since those scripts put no space there. A full stop after a + * common abbreviation (Dr., Mr., e.g., etc.) or an initial (J., J.R.) ends nothing. A unit with + * nothing to say (only punctuation) is dropped. */ +std::vector take_text_units(std::string* pending, TextSplit mode, bool final); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/videos.cpp b/core/server/videos.cpp new file mode 100644 index 00000000..d086c7ab --- /dev/null +++ b/core/server/videos.cpp @@ -0,0 +1,621 @@ +/* videos.cpp -- OpenAI's video endpoints over a video generator (core/gen/video_driver.h): a video + * and its soundtrack from a prompt. + * + * A video takes minutes, so it is a job, as OpenAI's API has it: POST /v1/videos queues one and + * answers with the video object at once, GET /v1/videos/{id} reports its status and progress, and + * GET /v1/videos/{id}/content downloads the MP4 once it is completed (`variant` thumbnail gives + * the first frame as WebP). GET /v1/videos lists the jobs, newest first, and DELETE removes one, + * cancelling it when it is still running. A finished video is kept for `video_ttl_s` seconds + * (`expires_at`), at most `max_videos` of them. + * + * The request takes OpenAI's fields (`prompt`, `model`, `seconds`, `size`) as JSON or as a + * multipart form, and SGLang's for the same model: `task` (t2va), `target` {`short_edge`, + * `aspect_ratio`, `duration_seconds`}, `conditions` (empty), `seed`, and `num_inference_steps`. + * `size` is the frame's width x height, multiples of the model's size multiple; `aspect_ratio` + * (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or + * `short_edge`), the area capped at the model's largest, both sides rounded to the multiple. + * A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next. + * Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are + * refused. + * + * The prompt is the model's template with `{prompt}` filled; the template is tokenised with its + * special tokens and the prompt without, so a caller cannot write control tokens into it. + */ +#include "server.h" +#include "oai.h" + +#include "gen/video.h" +#include "mm/media.h" +#include "mm/mp4.h" +#include "rad_internal.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace server { + +struct Server::VideoJob { + std::string id, model, prompt, seconds, size; + int64_t created_at = 0; + uint64_t seed = 0; + std::shared_ptr ticket; + std::thread worker; + /* Under Server::videos_m_ from here on. */ + std::string status = "queued"; + int progress = 0; + int64_t completed_at = 0, expires_at = 0; + bool failed = false; + std::string err_code, err_message; + std::string mp4; + std::vector first; /* the first frame, RGB, for the thumbnail */ + int32_t w = 0, h = 0; + bool worker_done = false; /* its thread has nothing left to do but return */ +}; + +namespace { + +std::string new_video_id() { + static const char* hex = "0123456789abcdef"; + std::random_device rd; + std::string id = "video_"; + for (int i = 0; i < 32; ++i) id.push_back(hex[rd() & 15]); + return id; +} + +/* "1344x768" -> (1344, 768); false for anything else. */ +bool parse_size(const std::string& s, int64_t* w, int64_t* h) { + const size_t x = s.find_first_of("xX"); + if (x == std::string::npos || x == 0 || x + 1 >= s.size()) return false; + char* e = nullptr; + *w = std::strtoll(s.c_str(), &e, 10); + if (e != s.c_str() + x) return false; + *h = std::strtoll(s.c_str() + x + 1, &e, 10); + return *e == '\0' && *w > 0 && *h > 0; +} + +/* "16:9" -> 16/9 as two positives; false for anything else. */ +bool parse_ratio(const std::string& s, double* a, double* b) { + const size_t c = s.find(':'); + if (c == std::string::npos) return false; + char* e = nullptr; + *a = std::strtod(s.c_str(), &e); + if (e != s.c_str() + c) return false; + *b = std::strtod(s.c_str() + c + 1, &e); + return *e == '\0' && *a > 0 && *b > 0; +} + +/* The model's canvas for a ratio: the short edge, the area capped, both sides rounded to the + * multiple (ties to even, as the reference's float round). */ +void canvas_for(double rw, double rh, int64_t short_edge, int64_t max_area, int64_t mult, + int64_t* w, int64_t* h) { + const double ratio = rw / rh; + double W = ratio >= 1.0 ? short_edge * ratio : (double)short_edge; + double H = ratio >= 1.0 ? (double)short_edge : short_edge / ratio; + if (W * H > (double)max_area) { + const double sc = std::sqrt((double)max_area / (W * H)); + W *= sc; + H *= sc; + } + *w = std::max(mult, (int64_t)std::nearbyint(W / mult) * mult); + *h = std::max(mult, (int64_t)std::nearbyint(H / mult) * mult); +} + +} /* namespace */ + +HttpResponse Server::handle_video_create(const HttpRequest& req) { + if (!deps_.videos || !deps_.tok) + return error_response(err_not_implemented( + "/v1/videos requires a video generation model; this one does not make video"), + req.peer); + const VideoGenInfo& info = deps_.videos->info(); + + /* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form, + * since it may carry a file). */ + json body = json::object(); + if (!req.form.empty()) { + for (const FormPart& p : req.form) { + if (p.name == "input_reference") + return error_response(err_unsupported("input_reference", "this server makes video " + "from text only"), req.peer); + if (!p.filename.empty()) + return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"), + req.peer); + json v = p.data; + if (p.name == "target" || p.name == "conditions") { + v = json::parse(p.data, nullptr, false); + if (v.is_discarded()) + return error_response(err_bad(p.name, "expected JSON"), req.peer); + } + body[p.name] = v; + } + } else { + ApiError err; + if (parse_request_object(req.body, lim_, &body, &err) < 0) + return error_response(err, req.peer); + } + static const char* kKnown[] = { + "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", + "task", "target", "conditions", "user", + }; + for (auto it = body.begin(); it != body.end(); ++it) { + bool known = false; + for (const char* k : kKnown) known = known || it.key() == k; + if (!known) + return error_response(err_bad(it.key(), "'" + it.key() + "' is not a field of " + "/v1/videos"), req.peer); + } + auto bad = [&](const char* k, const std::string& why) { return error_response(err_bad(k, why), req.peer); }; + auto has = [&](const json& o, const char* k) { return o.contains(k) && !o[k].is_null(); }; + /* A number, or a string holding one (a form's fields are strings). */ + auto number = [&](const json& v, double* out) { + if (v.is_number()) { *out = v.get(); return true; } + if (!v.is_string()) return false; + const std::string s = v.get(); + char* e = nullptr; + *out = std::strtod(s.c_str(), &e); + return !s.empty() && *e == '\0'; + }; + + if (!has(body, "prompt") || !body["prompt"].is_string() || + body["prompt"].get().find_first_not_of(" \t\r\n") == std::string::npos) + return bad("prompt", "the prompt is required, as a non-empty string"); + const std::string prompt = body["prompt"].get(); + if (has(body, "input_reference")) + return error_response(err_unsupported("input_reference", "this server makes video from " + "text only"), req.peer); + if (has(body, "task") && (!body["task"].is_string() || body["task"].get() != "t2va")) { + ApiError e = err_unsupported("task", "this server makes video from text: t2va"); + e.supported = { "t2va" }; + return error_response(e, req.peer); + } + if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) + return error_response(err_unsupported("conditions", "this server makes video from text " + "only; conditions must be empty"), req.peer); + json target = json::object(); + if (has(body, "target")) { + if (!body["target"].is_object()) return bad("target", "expected an object"); + target = body["target"]; + for (auto it = target.begin(); it != target.end(); ++it) + if (it.key() != "short_edge" && it.key() != "aspect_ratio" && + it.key() != "duration_seconds") + return bad("target", "'" + it.key() + "' is not a field of target"); + } + + /* ---- the size */ + int64_t W = info.default_width, H = info.default_height; + const int64_t short_def = std::min(info.default_width, info.default_height); + if (has(body, "size")) { + if (!body["size"].is_string() || !parse_size(body["size"].get(), &W, &H)) + return bad("size", "expected WIDTHxHEIGHT, e.g. " + std::to_string(info.default_width) + + "x" + std::to_string(info.default_height)); + if (has(target, "aspect_ratio") || has(target, "short_edge")) + return bad("size", "give size or target's aspect_ratio and short_edge, not both"); + } else if (has(target, "aspect_ratio") || has(target, "short_edge")) { + double rw = (double)info.default_width, rh = (double)info.default_height; + if (has(target, "aspect_ratio")) { + if (!target["aspect_ratio"].is_string()) + return bad("target", "aspect_ratio is a string, w:h or auto"); + const std::string ar = target["aspect_ratio"].get(); + if (ar != "auto" && !parse_ratio(ar, &rw, &rh)) + return bad("target", "aspect_ratio must be w:h (16:9) or auto"); + } + int64_t se = short_def; + if (has(target, "short_edge")) { + double v = 0; + if (!number(target["short_edge"], &v) || v < 1 || v != std::floor(v)) + return bad("target", "short_edge must be a positive whole number of pixels"); + se = (int64_t)v; + } + if (std::max(rw, rh) > (double)info.max_aspect * std::min(rw, rh)) + return bad("target", "the aspect ratio may be at most " + + std::to_string(info.max_aspect) + ":1 either way"); + canvas_for(rw, rh, se, info.max_area, info.size_multiple, &W, &H); + } + if (W % info.size_multiple || H % info.size_multiple || W < info.min_side || + H < info.min_side || W * H > info.max_area || + std::max(W, H) > info.max_aspect * std::min(W, H)) { + int64_t sw = 0, sh = 0; + canvas_for((double)W, (double)H, short_def, info.max_area, info.size_multiple, &sw, &sh); + return bad("size", std::to_string(W) + "x" + std::to_string(H) + " is not a size this " + "model makes: sides are multiples of " + std::to_string(info.size_multiple) + + " from " + std::to_string(info.min_side) + ", at most " + + std::to_string(info.max_area) + " pixels and " + + std::to_string(info.max_aspect) + ":1; its canvas at that ratio is " + + std::to_string(sw) + "x" + std::to_string(sh)); + } + + /* ---- the length, in whole chunks */ + const double fps = (double)info.fps_num / (double)info.fps_den; + const double min_s = (double)(info.frames_per_chunk * info.min_chunks + info.frames_tail) / fps; + const double max_s = (double)(info.frames_per_chunk * info.max_chunks + info.frames_tail) / fps; + int64_t chunks = info.default_chunks; + const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds"); + if (has_sec && has_dur) + return bad("seconds", "give seconds or target's duration_seconds, not both"); + if (has_sec || has_dur) { + double sec = 0; + if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0)) + return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds"); + const int64_t want = (int64_t)std::ceil(sec * fps - 1e-9); + chunks = std::max(info.min_chunks, + (want - info.frames_tail + info.frames_per_chunk - 1) / + info.frames_per_chunk); + if (chunks > info.max_chunks) + return bad(has_sec ? "seconds" : "target", + "this model makes " + rad::fmt("%.2f", min_s) + " to " + + rad::fmt("%.2f", max_s) + " seconds"); + } + const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail; + + std::unique_ptr r = std::make_unique(); + r->width = (int32_t)W; + r->height = (int32_t)H; + r->chunks = (int32_t)chunks; + if (has(body, "num_inference_steps")) { + double v = 0; + if (info.fixed_steps && (!number(body["num_inference_steps"], &v) || + v != (double)info.max_steps)) + return bad("num_inference_steps", + "this model runs the schedule it was trained on: " + + std::to_string(info.max_steps) + " sigma grid points, the last one 0"); + if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 || + v > (double)info.max_steps) + return bad("num_inference_steps", "expected an integer in 2.." + + std::to_string(info.max_steps) + + " (sigma grid points, the last one 0)"); + r->steps = (int32_t)v; + } + bool seed_given = false; + if (has(body, "seed")) { + double v = 0; + if (!number(body["seed"], &v) || v != std::floor(v)) return bad("seed", "expected an integer"); + r->seed = (uint64_t)(int64_t)v; + seed_given = v != -1; + } + if (!seed_given) { + /* 53 bits, as the other generators choose one: JavaScript reads a number as a double. */ + std::random_device rd; + r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); + } + + /* ---- the prompt: the template's text with special tokens, the prompt without */ + { + static const std::string kSlot = "{prompt}"; + const std::string& t = info.tmpl; + const size_t p = t.find(kSlot); + auto put = [&](const std::string& s, bool special) { + if (s.empty()) return; + const auto ids = deps_.tok->encode(s, false, special); + r->tokens.insert(r->tokens.end(), ids.begin(), ids.end()); + }; + put(t.substr(0, p), true); + put(prompt, false); + put(t.substr(p + kSlot.size()), true); + if ((int64_t)r->tokens.size() > info.max_text) + return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) + + " tokens; this model takes at most " + + std::to_string(info.max_text)); + } + + /* ---- admitted and queued: the job holds its place until its file is written */ + if (auto no = admit(1, req.peer)) return *no; + auto j = std::make_shared(); + j->id = new_video_id(); + j->model = opt_.model_id; + j->prompt = prompt; + j->seconds = rad::fmt("%.2f", (double)frames / fps); + j->size = std::to_string(W) + "x" + std::to_string(H); + j->created_at = unix_now(); + j->seed = r->seed; + j->ticket = std::make_shared(); + r->ticket = j->ticket; + const int64_t n_tok = (int64_t)r->tokens.size(); + const int32_t steps = r->steps; + { + std::string w; + const int s = deps_.videos->submit(std::move(r), &w); + if (s < 0) { + release(1); + ApiError e = err_bad("", w.empty() ? std::string(rad_strerror(s)) : w); + if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; } + return error_response(e, req.peer); + } + } + RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps, seed=%llu", + j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(), + (long long)n_tok, steps > 0 ? steps : (int)j->ticket->steps, + (unsigned long long)j->seed); + std::lock_guard lk(videos_m_); + sweep_videos_locked(unix_now()); + videos_.push_back(j); + j->worker = std::thread([this, j] { video_work(j); }); + return HttpResponse::json_body(200, json_dump(video_json(*j))); +} + +/* The job's thread. Progress is the steps' share of 90, then the frames' of the last 10. */ +void Server::video_work(std::shared_ptr j) { + gen::VideoTicket& t = *j->ticket; + const VideoGenInfo& info = deps_.videos->info(); + mm::Mp4Writer mp4; + std::string why; + int st = mp4.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels, + &why); + int32_t frames = 0; + bool aborted = false; + while (st >= 0) { + gen::VideoEvent e; + bool to = false; + if (!t.next(&e, 500, &to)) { + if (!to) break; + if (stopping_.load()) { + t.cancel.store(true); + aborted = true; + break; + } + continue; + } + if (e.kind == gen::VideoEvent::STEP) { + std::lock_guard lk(videos_m_); + j->status = "in_progress"; + j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0; + } else if (e.kind == gen::VideoEvent::AUDIO) { + if (t.channels > 0) + st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why); + } else if (e.kind == gen::VideoEvent::FRAMES) { + if (e.first == 0 && e.n > 0) { + std::lock_guard lk(videos_m_); + j->first.assign(e.rgb.begin(), e.rgb.begin() + (size_t)t.width * t.height * 3); + j->w = t.width; + j->h = t.height; + } + st = mp4.add_frames(e.rgb.data(), e.n, &why); + frames += e.n; + std::lock_guard lk(videos_m_); + j->progress = 90 + (t.frames > 0 ? (int)(10LL * frames / t.frames) : 0); + } + } + if (st < 0) t.cancel.store(true); + std::string file; + if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames) + st = mp4.finish(&file, &why); + release(1); + + std::lock_guard lk(videos_m_); + const int64_t now = unix_now(); + if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames) { + j->status = "completed"; + j->progress = 100; + j->completed_at = now; + j->expires_at = now + opt_.video_ttl_s; + j->mp4 = std::move(file); + RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s", j->id.c_str(), + (double)j->mp4.size() / 1e6, mp4.video_encoder().c_str(), + (double)(t.t_done_ns - t.t_submit_ns) / 1e9); + } else { + j->status = "failed"; + j->failed = true; + j->completed_at = now; + if (st < 0) { + j->err_code = "encoding_failed"; + j->err_message = "the video could not be written: " + why; + } else if (aborted || t.status() == RAD_E_CANCELLED) { + j->err_code = "cancelled"; + j->err_message = aborted ? "the server is shutting down" : "the video was cancelled"; + } else { + j->err_code = t.status() == RAD_E_INVAL ? "invalid_request" : "generation_failed"; + j->err_message = t.why().empty() ? std::string(rad_strerror(t.status())) : t.why(); + } + RAD_WARN("video %s: failed: %s", j->id.c_str(), j->err_message.c_str()); + } + j->worker_done = true; +} + +void Server::sweep_videos_locked(int64_t now) { + /* Deleted jobs whose threads are done are joined. */ + for (size_t i = 0; i < videos_gone_.size();) { + if (!videos_gone_[i]->worker_done) { ++i; continue; } + if (videos_gone_[i]->worker.joinable()) videos_gone_[i]->worker.join(); + videos_gone_.erase(videos_gone_.begin() + (std::ptrdiff_t)i); + } + /* Expired files go first, then the oldest finished jobs past the count. A running job is + * never dropped here: it holds an admission place and its thread. */ + auto drop = [&](size_t i) { + if (videos_[i]->worker.joinable()) videos_[i]->worker.join(); + videos_.erase(videos_.begin() + (std::ptrdiff_t)i); + }; + for (size_t i = 0; i < videos_.size();) { + const VideoJob& j = *videos_[i]; + const bool done = j.status == "completed" || j.status == "failed"; + if (done && j.expires_at > 0 && j.expires_at <= now) drop(i); + else if (done && j.failed && j.completed_at + opt_.video_ttl_s <= now) drop(i); + else ++i; + } + int64_t finished = 0; + for (const auto& j : videos_) finished += j->status == "completed" || j->status == "failed"; + for (size_t i = 0; i < videos_.size() && finished > opt_.max_videos;) { + const VideoJob& j = *videos_[i]; + if (j.status == "completed" || j.status == "failed") { + drop(i); + --finished; + } else { + ++i; + } + } +} + +void Server::stop_videos() { + std::vector> all; + { + std::lock_guard lk(videos_m_); + all = videos_; + all.insert(all.end(), videos_gone_.begin(), videos_gone_.end()); + } + for (auto& j : all) j->ticket->cancel.store(true); + for (auto& j : all) + if (j->worker.joinable()) j->worker.join(); +} + +/* The video object, OpenAI's shape. */ +json Server::video_json(const VideoJob& j) { + json o; + o["id"] = j.id; + o["object"] = "video"; + o["model"] = j.model; + o["status"] = j.status; + o["progress"] = j.progress; + o["created_at"] = j.created_at; + o["completed_at"] = j.completed_at ? json(j.completed_at) : json(nullptr); + o["expires_at"] = j.expires_at ? json(j.expires_at) : json(nullptr); + o["prompt"] = j.prompt; + o["seconds"] = j.seconds; + o["size"] = j.size; + o["seed"] = j.seed; + o["remixed_from_video_id"] = nullptr; + if (j.failed) { + json e; + e["code"] = j.err_code; + e["message"] = j.err_message; + o["error"] = e; + } else { + o["error"] = nullptr; + } + return o; +} + +HttpResponse Server::handle_video_get(const HttpRequest& req) { + if (!deps_.videos) + return error_response(err_not_implemented("/v1/videos requires a video generation model"), + req.peer); + const std::string id = req.param("id"); + std::lock_guard lk(videos_m_); + for (const auto& j : videos_) + if (j->id == id) return HttpResponse::json_body(200, json_dump(video_json(*j))); + ApiError e = err_bad("id", "no video '" + id + "'; it may have expired"); + e.status = 404; + e.type = "not_found_error"; + return error_response(e, req.peer); +} + +HttpResponse Server::handle_video_list(const HttpRequest& req) { + if (!deps_.videos) + return error_response(err_not_implemented("/v1/videos requires a video generation model"), + req.peer); + int64_t limit = 20; + if (auto it = req.query.find("limit"); it != req.query.end()) { + char* e = nullptr; + limit = std::strtoll(it->second.c_str(), &e, 10); + if (*e || limit < 1 || limit > 100) + return error_response(err_bad("limit", "expected an integer in 1..100"), req.peer); + } + const auto ord = req.query.find("order"); + const bool asc = ord != req.query.end() && ord->second == "asc"; + if (ord != req.query.end() && ord->second != "asc" && ord->second != "desc") + return error_response(err_bad("order", "expected asc or desc"), req.peer); + const auto after = req.query.find("after"); + std::lock_guard lk(videos_m_); + sweep_videos_locked(unix_now()); + std::vector> v = videos_; + if (!asc) std::reverse(v.begin(), v.end()); + size_t at = 0; + if (after != req.query.end()) { + while (at < v.size() && v[at]->id != after->second) ++at; + if (at == v.size()) + return error_response(err_bad("after", "no video '" + after->second + "'"), req.peer); + ++at; + } + json data = json::array(); + for (size_t i = at; i < v.size() && (int64_t)data.size() < limit; ++i) + data.push_back(video_json(*v[i])); + json o; + o["object"] = "list"; + o["data"] = data; + o["first_id"] = data.empty() ? json(nullptr) : data.front()["id"]; + o["last_id"] = data.empty() ? json(nullptr) : data.back()["id"]; + o["has_more"] = at + data.size() < v.size(); + return HttpResponse::json_body(200, json_dump(o)); +} + +HttpResponse Server::handle_video_delete(const HttpRequest& req) { + if (!deps_.videos) + return error_response(err_not_implemented("/v1/videos requires a video generation model"), + req.peer); + const std::string id = req.param("id"); + std::lock_guard lk(videos_m_); + std::shared_ptr j; + for (size_t i = 0; i < videos_.size(); ++i) + if (videos_[i]->id == id) { + j = videos_[i]; + videos_.erase(videos_.begin() + (std::ptrdiff_t)i); + break; + } + if (!j) { + ApiError e = err_bad("id", "no video '" + id + "'"); + e.status = 404; + e.type = "not_found_error"; + return error_response(e, req.peer); + } + /* A running job is cancelled, and its thread ends once the driver has seen that (at its next + * pass, which may be seconds away); it is joined then. */ + j->ticket->cancel.store(true); + videos_gone_.push_back(j); + sweep_videos_locked(unix_now()); + json o; + o["id"] = id; + o["object"] = "video.deleted"; + o["deleted"] = true; + return HttpResponse::json_body(200, json_dump(o)); +} + +HttpResponse Server::handle_video_content(const HttpRequest& req) { + if (!deps_.videos) + return error_response(err_not_implemented("/v1/videos requires a video generation model"), + req.peer); + const std::string id = req.param("id"); + std::string variant = "video"; + if (auto it = req.query.find("variant"); it != req.query.end()) variant = it->second; + if (variant != "video" && variant != "thumbnail") { + ApiError e = err_unsupported("variant", "this server gives the video or its thumbnail"); + e.supported = { "video", "thumbnail" }; + return error_response(e, req.peer); + } + std::lock_guard lk(videos_m_); + for (const auto& j : videos_) { + if (j->id != id) continue; + if (variant == "thumbnail") { + if (j->first.empty()) + return error_response(err_bad("id", "video '" + id + "' has no frames yet"), + req.peer); + std::vector file; + std::string why; + if (mm::encode_image(j->first.data(), j->w, j->h, 3, "webp", 90, &file, &why) < 0) + return error_response(err_internal("the thumbnail could not be encoded: " + why), + req.peer); + HttpResponse res; + res.content_type = "image/webp"; + res.body.assign((const char*)file.data(), file.size()); + return res; + } + if (j->status != "completed") + return error_response(err_bad("id", "video '" + id + "' is " + j->status + + (j->failed ? ": " + j->err_message : "")), + req.peer); + HttpResponse res; + res.content_type = "video/mp4"; + res.body = j->mp4; + return res; + } + ApiError e = err_bad("id", "no video '" + id + "'; it may have expired"); + e.status = 404; + e.type = "not_found_error"; + return error_response(e, req.peer); +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/data/recipes/breeze-tts2-bf16.recipe b/data/recipes/breeze-tts2-bf16.recipe new file mode 100644 index 00000000..c0a42dbe --- /dev/null +++ b/data/recipes/breeze-tts2-bf16.recipe @@ -0,0 +1,23 @@ +# breeze-tts2-bf16.recipe -- Breeze-TTS-2 served at bf16, the precision its reference runs the +# text encoder, the backbone and the depth decoder at. +# +# rad-convert \ +# --recipe data/recipes/breeze-tts2-bf16.recipe -o breeze-tts2-bf16.rad +# +# The directory holds the model and, in audio_tokenizer/, the codec it plays frames through; both +# are read as one checkpoint. The model ships bf16 and is kept. The depth decoder's heads are +# stored (in, out) and are transposed here. The codec ships f32: its linears and convolutions are +# cast to bf16 here, its codebooks divided by their usage first (an EMA codebook), while its norms, +# layer scales and snake parameters stay f32 -- read once a pass or less. + +dep.heads.weight cast dtype=bf16 +codec.*.n1.weight cast dtype=f32 +codec.*.n2.weight cast dtype=f32 +codec.*.ls1.weight cast dtype=f32 +codec.*.ls2.weight cast dtype=f32 +codec.norm.weight cast dtype=f32 +codec.up*.ln.* cast dtype=f32 +codec.up*.gamma cast dtype=f32 +codec.*.alpha cast dtype=f32 +codec.*.beta cast dtype=f32 +codec.* cast dtype=bf16 diff --git a/data/recipes/minimax-h3-fp8.recipe b/data/recipes/minimax-h3-fp8.recipe new file mode 100644 index 00000000..bf1eb7b1 --- /dev/null +++ b/data/recipes/minimax-h3-fp8.recipe @@ -0,0 +1,46 @@ +# minimax-h3-fp8.recipe -- MiniMax-H3 (text to video and audio) with block-scaled fp8 linears. +# +# rad-convert --recipe data/recipes/minimax-h3-fp8.recipe \ +# -o minimax-h3-fp8.rad +# +# The directory needs the text-to-video-and-audio components only: text_encoder/, transformer/, +# vae/, audio_vae/, the processor or tokenizer and both scheduler folders (transformer_ref/ and +# the original-layout FL2VA/ and Ref2VA/ are not read). +# +# FastVideo's FastH3 releases (the denoiser distilled to eight steps with video sparse attention) +# take the same recipe: their text encoder and decoders are MiniMax-H3's files, so a container of +# the base model can supply them, with every transformer tensor listed as changed: +# +# rad-convert --recipe data/recipes/minimax-h3-fp8.recipe \ +# --reuse minimax-h3-fp8.rad --changed \ +# -o fasth3-8step-fp8.rad +# +# Every linear of the text encoder's first 50 layers, of the token refiner and of the DiT's 50 +# blocks, and the per-modality modulation projections, become E4M3 codes with a bf16 scale a +# 128 x 128 block, read by the fp8a8 GEMMs. What keeps the checkpoint's precision is read once a +# step or less: the embedding table, context_embedder and norm_out (bf16), the timestep MLP and the +# four patch projections (f32), every norm and bias. The video decoder's linears are cast to bf16 +# from the checkpoint's f32, its norms, layer scales, biases and register tokens stay f32; the +# audio decoder stays f32 (its weight norms folded at convert). + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_norm.weight cast dtype=f32 +te.blk.*.ffn_norm.weight cast dtype=f32 +ref.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +ref.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ada*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +vae.blk.*.attn_qkv.weight cast dtype=bf16 +vae.blk.*.attn_out.weight cast dtype=bf16 +vae.blk.*.ffn_up.weight cast dtype=bf16 +vae.blk.*.ffn_down.weight cast dtype=bf16 +vae.proj_out.* cast dtype=bf16 +aud.*.weight cast dtype=f32 diff --git a/data/recipes/minimax-music3-bf16.recipe b/data/recipes/minimax-music3-bf16.recipe new file mode 100644 index 00000000..ac92f2ad --- /dev/null +++ b/data/recipes/minimax-music3-bf16.recipe @@ -0,0 +1,18 @@ +# minimax-music3-bf16.recipe -- MiniMax-Music3 served at bf16, the precision diffusers runs it at. +# +# rad-convert \ +# --recipe data/recipes/minimax-music3-bf16.recipe -o minimax-music3-bf16.rad +# +# The language model and the depth decoder ship bf16 and are kept. The DiT, the condition encoder +# and the vocoder ship f32: their linears and convolutions are cast to bf16 here, once (the +# vocoder's weight norm folded in f32 first, rad_builder.h's RAD_MAP_WNORM), while their norms, the +# snake alphas, the Fourier projection and the layer mix stay f32 -- read once a pass or less. + +dit.*.ln1.* cast dtype=f32 +dit.*.ln2.* cast dtype=f32 +dit.t.fourier cast dtype=f32 +dit.* cast dtype=bf16 +cond.mix.* cast dtype=f32 +cond.* cast dtype=bf16 +voc.*.alpha cast dtype=f32 +voc.* cast dtype=bf16 diff --git a/data/recipes/q38-27b-modelopt-nvfp4.recipe b/data/recipes/q38-27b-modelopt-nvfp4.recipe new file mode 100644 index 00000000..37575f82 --- /dev/null +++ b/data/recipes/q38-27b-modelopt-nvfp4.recipe @@ -0,0 +1,39 @@ +# q38-27b-modelopt-nvfp4.recipe -- an NVIDIA ModelOpt NVFP4 release of Qwen3.8-27B (or a finetune of +# it, such as ukisai's Swift 1.5 NVFP4): FP8 attention and delta-net projections, NVFP4 MLPs and head. +# +# rad-convert --recipe data/recipes/q38-27b-modelopt-nvfp4.recipe -o model.rad +# +# The release is ModelOpt's MIXED_PRECISION: the attention q, k, v and output and the delta net's +# qkv, z and output projections are FP8 with one f32 scale per tensor; the MLPs and the lm_head are +# NVFP4 (e2m1 codes, an e4m3 scale per 16 of K, times an f32 weight_scale_2 per tensor); the delta +# net's a/b projections, the norms, the embedding, the vision tower and the MTP head are bf16. Its +# static input scales are not read: activations are quantised from their own values. +# +# - The FP8 projections keep their codes. The import rule writes each tensor's scale as the +# block plane the block-fp8 GEMM reads, rounded to bf16: one factor for the whole tensor, off +# by at most 2^-8 (3.3e-3 on Swift 1.5's 208 tensors); qkv and z keep their own scales, each +# a whole number of 128-row blocks. +# - No kernel reads NVFP4, so the MLPs are made OCP-MXFP4 (`fp4_e2m1`, an e8m0 scale per 32 of +# K, the encoding and kernel of q38-27b-quark-mxfp4-df2.recipe) from their exact values. That +# rounds twice (e4m3 scales per 16 to a power of two per 32): 0.116 relative error against +# the release's NVFP4 values on Swift 1.5, and unsloth's NVFP4 release made MXFP4 this way +# scores mean KL 0.287 against the block-fp8 base, AMD's Quark MXFP4 0.206. +# `codes=fp8_e4m3 block=128x128 scale=bf16` on the two MLP rules instead keeps them within +# 0.027 of the release at 28.2 GiB of weights against 20.8. +# - The head is block fp8 from its exact NVFP4 values, as in the other 27B recipes. +# - The MTP head stays bf16 as shipped (blk.64 is its layer); it drafts through a 2-bit copy of +# the head (u2 with a u8 zero, least-squares clip search) rescored against the fp8 head. + +blk.*.attn_qg.weight import block=128x128 scale=bf16 +blk.*.attn_k.weight import block=128x128 scale=bf16 +blk.*.attn_v.weight import block=128x128 scale=bf16 +blk.*.attn_output.weight import block=128x128 scale=bf16 +blk.*.ssm_inz.weight import block=128x128 scale=bf16 +blk.*.ssm_out.weight import block=128x128 scale=bf16 + +blk.64.ffn_*.weight cast dtype=bf16 +blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search diff --git a/data/recipes/q38-27b-w4a16.recipe b/data/recipes/q38-27b-w4a16.recipe new file mode 100644 index 00000000..64519056 --- /dev/null +++ b/data/recipes/q38-27b-w4a16.recipe @@ -0,0 +1,27 @@ +# q38-27b-w4a16.recipe -- an int4 W4A16 release of Qwen3.8-27B (or a finetune of it, such as +# ukisai's Swift 1.5 W4A16-AWQ, INT4 and W4A16-AutoRound), served at the 4-bit weights it ships. +# +# rad-convert --recipe data/recipes/q38-27b-w4a16.recipe -o model.rad +# +# The releases read are compressed-tensors' pack-quantized int4 in groups of 128, symmetric or +# asymmetric with a zero point per group (llm-compressor's AWQ, W4A16_ASYM), act-order none or +# `static`, and AutoRound's `auto_round:auto_gptq` export (symmetric, group 128). rad-convert +# imports each linear as it ships and the import rule writes it in the form the 4-bit GEMMs read: +# u4 codes, an f16 scale and a u4 zero point per 128 of K, a symmetric grid's codes made unsigned +# under a zero of 8. The numbers are the release's: every code and zero point as shipped, every +# f16 scale as shipped, and a bf16 scale converted to f16, which holds it exactly unless it lies +# below f16's normal range (2^-14); rad-convert reports how many it rounded. +# +# Served by the family's quantised plugin (qwen35_fp8): w4a16_asym over the input cast to f16 at +# up to 64 rows a step, w4a8i8_asym over an int8 activation with a scale per (row, 128) above. +# +# What the release keeps in bf16 stays bf16: the delta net's a/b projections, the norms, the +# embedding, the vision tower and the MTP head. Its head is made block fp8 as in the other 27B +# recipes (the widest GEMM, read every step, at half the bytes), and the MTP head drafts through a +# 2-bit copy of it (u2 with a u8 zero, least-squares clip search) whose top candidates the engine +# rescores against the fp8 head. + +blk.*.weight import codes=u4 zero=u4 scale=f16 + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search diff --git a/deploy/compose/breeze-tts2.yaml b/deploy/compose/breeze-tts2.yaml new file mode 100644 index 00000000..8081a2b2 --- /dev/null +++ b/deploy/compose/breeze-tts2.yaml @@ -0,0 +1,15 @@ +# Breeze-TTS-2 (BreezeBlue/Breeze-TTS-2) in bf16: speech on /v1/audio/speech, whole or streamed, +# and text spoken as it is written over the /v1/audio/speech/stream WebSocket. It runs on one card, +# RADIANCE_GPU in .env (default 0). Breeze-TTS-2 is licensed for research and non-commercial use +# only, and BreezeBlue counts hosting it as an API as commercial. +name: radiance-breeze-tts2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-breeze-tts2 + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/breeze-tts2-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/deploy/compose/fasth3.yaml b/deploy/compose/fasth3.yaml new file mode 100644 index 00000000..921fc5f6 --- /dev/null +++ b/deploy/compose/fasth3.yaml @@ -0,0 +1,13 @@ +# FastVideo's FastH3 8-Step V2 (FastVideo/FastVideo-FastH3-8-Step-V2) as block fp8: MiniMax-H3 +# distilled to eight steps with video sparse attention, the same /v1/videos API and host memory +# as minimax-h3.yaml, about 70 s a 1344x768 clip. It runs only its trained schedule, so a +# request's num_inference_steps may only be 9 (grid points). MiniMax-H3's license applies to it. +name: radiance-fasth3 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-fasth3 + command: > + --model /models/fasth3-8-step-v2-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --vision-tower-placement ram diff --git a/deploy/compose/minimax-h3.yaml b/deploy/compose/minimax-h3.yaml new file mode 100644 index 00000000..ad684a2e --- /dev/null +++ b/deploy/compose/minimax-h3.yaml @@ -0,0 +1,14 @@ +# MiniMax-H3 (MiniMaxAI/MiniMax-H3) as block fp8: video with its stereo soundtrack from text, on +# OpenAI's /v1/videos, 1344x768 and 5.17 s by default, about 9 minutes a clip at its 50 steps. +# The text encoder and the modulation projections are read from pinned host memory +# (--vision-tower-placement ram), about 39 GiB of it. MiniMax-H3's license excludes use in the EU, +# the UK, the Republic of Korea and the USA. +name: radiance-minimax-h3 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-minimax-h3 + command: > + --model /models/minimax-h3-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --vision-tower-placement ram diff --git a/deploy/compose/minimax-music3.yaml b/deploy/compose/minimax-music3.yaml new file mode 100644 index 00000000..acfdc678 --- /dev/null +++ b/deploy/compose/minimax-music3.yaml @@ -0,0 +1,12 @@ +# MiniMax-Music3 (MiniMaxAI/MiniMax-Music3) in bf16: songs from lyrics (`input`) and a description +# (`instructions`) on /v1/audio/speech, 44.1 kHz stereo, whole or streamed as they are made, at about +# the speed they play on two cards. +name: radiance-minimax-music3 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-minimax-music3 + command: > + --model /models/minimax-music3-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 10444b05..bf5cdad2 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -19,6 +19,9 @@ plugin claims. | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | +| `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | +| `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card | +| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) | The traps below are readings that are wrong without any error: the model produces fluent output. @@ -640,3 +643,258 @@ clips at their pauses (docs/GUIDE.md §5.14). Against transformers on LibriSpeec test-other clips, the encoder's rows are within 1.1-1.3% relative L2 of the bf16 reference's; on the one clip where they differed by 5%, the reference itself was 5.3% from a float32 run of the same model and this engine 0.8%. The transcripts match word for word. + +--- + +# `minimaxmusic3`: MiniMax-Music3, songs + +`arch/minimaxmusic3` declares an audio generator (`rad_declare_audio_generator`), which makes the +program a four-pass one the engine drives through `core/gen/audio_driver.h`: PROMPT runs the +language model over prompt chunks, FRAME samples one frame of every song in flight and runs the +language model over its embedding, WINDOW steps the denoiser over a window of frames, VOCODE plays +a finished window. A song is a lane; up to four are made at once. It is served on +`/v1/audio/speech` ([GUIDE §5.15](GUIDE.md)), bf16 on one card or two. The checkpoint is the +diffusers pipeline directory, read as one. + +``` +LM Qwen3-8B with its embedding and head adapted to music codes: 36 layers of 4096 (32 x 128, + 8 kv heads), theta 1e6. Two branches a song, conditional and unconditional. Each frame's + first code: one of 16384 semantic codes (ids 151675..) or the end of the song (151670), + from u + 1.5 (c - u); the candidates are the top 50 of c, of which the top 50 of the + guided logits are drawn +depth 4 layers of 4096, 16 heads of 256, SwiGLU 6144, learned positions: the frame's other + seven codes (1024 each) one at a time, each with the same guidance, the sequence + recomputed whole at every step. The next LM input is the eight codes' embeddings summed, + times 8^-0.5 +cond the frame's hidden planes mixed by softmax(learned logits), scaled; a window's rows + through a 3-tap conv to 2048 channels, resampled nearest to 441/128 latents a frame +DiT 36 layers of 2048 (32 x 64), LayerNorm with affine, SwiGLU 16384 with biases, RoPE over + the first 32 of 64 dims; input [latent 128 | zeros 128 | cond 2048] plus a 1x1-conv + residual, the timestep token prepended, non-causal. 30 Euler steps at t = i / 30, + guidance 1.7 against an all-zero conditioning +windows 200 frames, a new one every 100; each binds its first 172 latents to its predecessor's +vocoder DAC's decoder: the latent's two 64-channel halves as two streams (left, right), four + transposed convolutions (8, 8, 4, 2), dilated residual units with snake; 512 samples a + latent, 44.1 kHz stereo +``` + +Traps: + +- **The randomness is radiance's.** Each pick draws `rad_philox_uniform_s(seed, 2^32 + frame, + sub-step)` by inverse CDF in descending guided logit (ties to the lower index), and window k's + noise is `rad_philox_normal_s(seed, 1 + k, row * 128 + c)` (`abi/rad_philox.h`). Parity against + diffusers means handing diffusers the same picks and noise, which a NumPy port of the streams + does. +- **The unconditional prompt is the conditional one with its middle blanked**: its first token and + last two kept, every token between them the filler 151654, so both branches have one length. + An empty or shortened prompt is a different guidance and still sings. +- **The first frame after the prompt is consumed, not played**: it only moves the language model + past the prompt, and no conditioning row is stored for it. +- **The DiT's positions start at the timestep token**: position 0 is that token and the latents + follow from 1. Starting the latents at 0 shifts every rotation by one and the song still plays. +- **A window's join runs in one order**: its head is set from the previous window's kept tail + first, and only then is the next window's tail taken from the joined latent. The other order + binds a window to its own tail, and the song drops in level for a moment at every join. +- **The model card says 32 kHz; the vocoder plays 44.1 kHz** (512 samples a latent), as diffusers' + port and its config do. +- **Under tensor parallelism, a fused projection's stacked bias is cut per part**: a rank-1 + `[value | gate]` vector holds its share of each half, as the matrix it goes with does. A + contiguous slice of the stack runs and is 5-6% off in every DiT velocity. + +Against diffusers' own pipeline in bf16, from the same picks and noise: with radiance's codes +teacher-forced into the reference, the language model's last hidden row is 1.55% from the +reference's (relative L2; the reference is 1.27% from itself across bf16 and f32), the window +conditioning 1.33% (1.10%), a DiT step's velocity 1.3% (1.8%). At one card a 4 s song is 29.0 dB +SNR from the reference's audio, against 28.7 dB between the reference's own attention kernels; at +two cards a 12 s song of two windows is 26.3 dB (32.0), and the 4 s song 20.8 dB, one passage of it +having taken another turn, which a rounding-level change makes in the reference too. A pick is chaotic: with the same history, +the reference and radiance choose differently at 318 of 808 sub-steps, and the reference chooses +differently from itself across precisions at 314. + +--- + +# `breeze`: Breeze-TTS-2, speech + +`arch/breeze` declares an audio generator in its chunked form (`rad_declare_audio_generator` with +`voc_chunk`): PROMPT runs the text encoder and the backbone over both branches' whole prompts, +FRAME samples one frame of every speech in flight and runs the backbone over its embedding, VOCODE +plays a lane's newest frames, four at most, as soon as they are made. It is served on +`/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)), bf16 on one card. The +checkpoint is the release directory; its codec, in `audio_tokenizer/`, is read with it. + +``` +text T5Gemma 2's text encoder in Gemma 3 1B's shape: 26 layers of 1152, 4 query heads over one + KV head of 256 (q/k RMS-normed, scale 1/16), sandwich RMS norms with a (1 + w) gain, + gelu-tanh GLU 6912, the embedding times 34.0 (bf16 of sqrt 1152). BIDIRECTIONAL over the + whole prompt: sliding layers see 255 keys behind and 256 ahead (theta 1e4); layers 5, + 11, 17 and 23 see everything (theta 1e6, positions divided by 8). Final norm, then + 1152 -> 2048 +backbone Qwen3: 28 layers of 2048, 16 heads over 8 KV heads of 128, q/k norms, theta 1e6, eps + 1e-6. Its prompt rows ARE the encoder's projection; a frame's input is the bf16 of the + f32 sum of its 16 codes' rows of one table [16 x 2051, 2048]. Head 2052: 2048 codes, + three never drawn, the end of the speech +depth 12 layers of 1024, 8 heads over 2 KV heads of 128, Llama 3's rotary (theta 5e5, factor + 32, original length 16, low 1/512, high 1/128), no q/k norms: position 0 is the + backbone's hidden state, position p code p - 1's row of the table, both through one + 2048 -> 1024 projection; 15 heads, one a codebook +sampling u + g (c - u) against an unconditional prompt without the voice description (g 1, the + default: none); top 50 at temperature 0.9; the first code also takes a repetition penalty + of 1.1 over the speech's earlier first codes +codec the Qwen3-TTS 12 Hz tokenizer's decoder: EMA codebooks (the first code's, the other + fifteen's) projected 256 -> 512 and summed; a causal conv k3 to 1024; 8 layers of 512 + (16 heads of 64, rotary at the frame's index, causal over 72 frames, layer scales); + twice a transposed conv k2 s2 and a ConvNeXt block (causal depthwise k7, LayerNorm, + exact GELU over 4096); a causal conv k7 to 1536; four blocks of SnakeBeta, a causal + transposed conv (8, 5, 4, 3) and three residual units (dilations 1, 3, 9); SnakeBeta and + a conv k7 to one channel: 1920 samples a frame, 24 kHz mono +``` + +Traps (each still speaks, wrongly): + +- **The backbone's configuration is `backbone_config`.** The top level's Llama 3 rotary at theta + 5e5 and eps 1e-5 belong to a native backbone the release does not build; the Qwen3 backbone runs + at theta 1e6 and eps 1e-6. +- **The backbone never embeds text.** Every prompt row is the encoder's output projected; the + checkpoint's `embed_text_tokens` (0.5B parameters) is unused, and so is the Mimi codec in the + main file. +- **The encoder reads the whole prompt at once**, so a prompt is never split across passes + (`prompt_whole`), and its sliding window is lopsided: transformers' mask at 512 sees 255 keys + behind and 256 ahead. A symmetric window differs on prompts over 256 tokens. +- **The depth heads are stored (in, out)**, `[15, 1024, 2051]`, and are transposed at convert + (`RAD_MAP_TRANSPOSE`); the codec's codebooks are EMA sums, divided by their usage at convert + (`RAD_MAP_EMA`). +- **A frame's sixteen embeddings are summed in f32 and rounded once**, as torch sums a bf16 tensor; + rounding after each would move every backbone input. +- **The codec's first two transposed convolutions have a kernel of one stride**, the four after + them of two, all causal: the full output's last rows dropped, no padding in front. +- **The reference's streaming codec is not a reference.** Its 72-slot KV ring shifts with an + overlapping in-place copy that races on the GPU: three identical decodes agree at 20-26 dB. + Compare against the offline decode, which radiance's chunks reproduce: every codec layer is + causal, so a chunk decoded again over the 85 frames its outputs reach back to is exact. The + reference's own codec decoded on radiance's schedule is 117 dB from its whole decode (f32 + rounding); with 60 frames of context it is 30 dB. + +Against BreezeBlue's eager reference in bf16, teacher-forced with radiance's codes (a CPU run): +the backbone's hidden rows are 1.04% from the reference's (relative L2, median over the prompt and +72 frames; the reference is 0.94% from itself across bf16 and f32). The reference would have drawn +another code at 323 of 1168 picks, all near-ties: the code radiance drew had a median 0.998 of +the reference's own pick's probability, and the first code differed once in 73 frames. Through +the codec alone, radiance's bf16 audio is 38.4 dB SNR from the reference's f32 decode of the same +codes. Whisper large-v3 transcribes radiance's speech word for word. + +--- + +# `minimaxh3`: MiniMax-H3, video with sound + +`arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the +program a four-pass one the engine drives through `core/gen/video_driver.h`: VCOND runs the text +encoder and the refiner over the prompt and computes every step's modulation, VSTEP is one +denoising step of one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes +one temporal chunk of frames. A request is a lane; two hold state at once (one denoising, one +conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 on two +cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline directory, +read as one; only workflow t2va is served. + +``` +text Qwen3-VL-32B's language model: 64 layers of 5120 (64 q / 8 kv heads of 128, ff 25600, + eps 1e-6, theta 5e6, interleaved M-RoPE, which is NeoX for text). The conditioning is + the hidden state AFTER LAYER 50, before any norm; layers 50..63 are never read and the + container leaves them out. The prompt is tokenised as written, no template, no special + tokens +refiner context_embedder 5120 -> 5376 (bias), two plain pre-norm blocks over the prompt (full + attention, no rotary, q/k RMS norms), a final RMSNorm +DiT 50 blocks of 5376 (56 heads of 128), SwiGLU 14336, RMSNorm eps 1e-5, no biases, one + packed sequence [text | soundtrack ch0 | soundtrack ch1 | video] under full attention. + Each row is modulated by its modality (0 video, 1 text, 2 audio) at its timestep (text + rows take the video's): six vectors a block from Linear(silu(temb), 3 x 6 x 5376). + norm_out's shift and scale are per timestep. Video latents 24 channels in 1x2x2 patches + (96 values a row, proj_in f32), the soundtrack's 32 channels a row (f32). Guidance- + distilled: one forward a step +rotary 3 axes (time, row, column), 16 frequencies each (theta 1e4) over the first 96 of 128 + dims, rotate-half pairs (i, i + 48); f32 positions +schedule per modality: sigma = s x / (1 + (s - 1) x) over linspace(1, 0, N) (N grid points, N - 1 + evaluations), shift 12 for the video and 3 for the soundtrack; t = 1 - sigma; x0 = + x + (1 - t) v, then x' = r x + (1 - r) x0 with r = sigma_next / sigma +video ViT decoder, 36 layers of 2048 (32 heads of 64), f32 residual, RMSNorm, q/k RMS norms +VAE without weights, rotary 8/8/8 over 48 of 64 dims (theta 100, angles 2 pi (2 (i + .5) / + n - 1)), layer scales, SwiGLU 8192 with biases, 4 registers and a zero token a tile. + A token is a latent: 4 frames x 16 x 16 pixels. Tiles of 16 x 16 latents, overlap 4 at + least; chunks of 7 latent frames every 5. Pixels come out ImageNet-normalised +audio dec_in_proj 32 -> 2048, BigVGAN: conv_pre k7 to 1024, 7 transposed convolutions (5 5 2 2 +VAE 2 2 2), each followed by the mean of three AMP blocks (k 3/7/11, dilations 1/3/5) with + anti-aliased SnakeBeta (x2 up, x2 down, 12-tap Kaiser filters); conv_post k7 to one + channel, clamped. 800 samples a latent, 32 kHz, each stereo channel its own sequence +length 24 fps; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, n 7..20 + (5.17 to 14.4 s); the soundtrack is round-half-even(frames x 40 / 24) latents a channel +``` + +Traps: + +- **The feed-forward's value half comes first** in the checkpoint (`[value | gate]`, out = + `value * silu(gate)`), in the DiT, the refiner and the video decoder alike. The halves are + swapped at convert into the `[gate | value]` that `silu_mul` reads. +- **The modulation gate has no tanh**, and the residual is `h += gate * branch`. The timestep + embedding reads t in [0, 1] as it is, not scaled to 1000. +- **The grid's second half is linspace's from the end**: torch computes `linspace(1, 0, N)` half + from each end in f32, which `gen::video_schedule` reproduces. +- **The packed rows' positions are f64 rounded to f32**: a latent frame spans 5/3 x (1, 4, 4, 4, + 4)[i mod 5] time units from `n_text`, the spatial axes are each side's latents over the square + root of the frame's area, centred on the unit interval, times 32, and the soundtrack's two + channels sit at the two ends of the width axis. +- **A tile is blended with its neighbours as they were decoded**: the vertical blend reads the + original tile above, and the horizontal blend the original tile to the left, not the blended + ones. Chunks keep frames [3, 20) of their 28 and blend their last 5 linearly into the next + chunk's first 5. + +Tensor parallel: the text encoder, refiner and DiT blocks split by heads and feed-forward width. +A block's three modulation projections split by rows, three of the six vectors a rank, and +VCOND writes every step's modulation into the lane once a request, so the 13B modulation +parameters and the text encoder (RAD_ACCESS_PER_REQUEST) live in pinned host memory under +`--vision-tower-placement ram`. Each step gathers its row of the table across the ranks. The video +decoder is replicated and splits its tiles between the ranks, gathering the decoded pixels; the +audio decoder runs whole on each. + +Against diffusers' pipeline in bf16 from the same noise, a 256 x 256 clip of 4 grid points: the +fp8 text encoder's conditioning is 4.15% from the reference's (relative L2). With radiance's +conditioning given to both, the first evaluation's velocity is 5.4% (video) and 4.3% (soundtrack) +from the reference's, at slope 0.99 and cosine 0.9985; the reference itself, with radiance's +block-fp8 rounding emulated on the same linears, is 6.8% and 4.6% from its own bf16 and shows the +same per-channel bias. Fed the same latents, the video decoder is 36.9 dB PSNR from the +reference's frames (H.264 included) and the audio decoder 51.0 dB SNR from its samples. The same +seed gives the same latents, run to run. + +Attention precision: the DiT's attention takes its scores in int8 (the keys quantised per row and +head by `quant_act_i8g`, the query inside the op) and its P.V in fp8 (the values quantised per +column by `quant_cols_fp8`, the weights `e4m3(448 p)` against an exactly tracked row max), so both +halves run on the 8-bit matrix instruction. Along an exact trajectory in diffusers (256 x 256), the +int8 scores move the velocity 1.9-5.9% and the fp8 P.V another 1-3 points, where exact f32 +softmax and SDPA's bf16 flash kernel already differ by 1.7-4.4%; finished clips keep their shot, +motion and detail. + +## FastH3: eight trained steps with video sparse attention + +FastVideo's FastH3 releases (FastVideo/FastVideo-FastH3-8-Step-V2) are the same denoiser distilled +(DMD2) to eight evaluations with video sparse attention, and name both in their +`fastvideo_inference.json`, which the converter reads under `fastvideo_inference.` keys. The +plugin takes from it: + +``` +schedule the trained timesteps 999 874 749 624 500 375 250 125 over a 1000-step clock, each + shifted per modality (10 for the video, checked against scheduler_config.json, 3 for the + soundtrack), then 0: nine grid points, eight evaluations, no other count + (RadVideoGenDecl::rungs) +attention VIDEO_SPARSE_ATTN_H3 at sparsity 0.8 and 64-row tiles: the prompt's and the + soundtrack's rows in 64-row chunks of their own (dense: their queries see every key, and + every query sees them), the video's patches in 4 x 4 x 4 boxes of (time, row, column); + a video query tile keeps the ceil(0.2 V) video tiles of best mean-q . mean-k score, per + head. A fourth projection beside q, k and v (attn.to_gate_compress, appended to the + fused qkv) gates in an attention over the tiles' means: vsa_select, then attn_vsa + (docs/OPS.md) +name served as `fastvideo-fasth3-8-step-v2` +``` + +Its text encoder and both decoders are MiniMax-H3's files byte for byte, so a container of the base +model supplies them (`--reuse`, the transformer's tensors listed as `--changed`; see the recipe's +header). The distilled model's first evaluation moves 21-23% under any perturbation (the reference +itself between bf16 and emulated fp8, or with the fp8 text encoder's conditioning), so its per-step +numbers against the reference say little; radiance's frames and the reference's agree by eye. diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 14fedaf3..d57937e1 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -138,6 +138,10 @@ the cards the engine runs on. | `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits | | `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps | | `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) | +| `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory | +| `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps | +| `minimax-music3.yaml` | `minimax-music3-bf16.rad` | MiniMax-Music3 in bf16: songs from lyrics and a description on `/v1/audio/speech` | +| `breeze-tts2.yaml` | `breeze-tts2-bf16.rad` | Breeze-TTS-2 in bf16: speech on `/v1/audio/speech` and live over `/v1/audio/speech/stream`, on one card (`RADIANCE_GPU`) | The container names are the files the README's model table downloads or converts. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 19d17937..91076db6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -276,6 +276,8 @@ and runs. | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) | | `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) | +| `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) | +| `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) | **4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing @@ -389,6 +391,16 @@ rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \ --recipe data/recipes/qwen-image-2.1-fp8.recipe rad-convert /srv/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \ --recipe data/recipes/qwen-image-2.1-fp8.recipe + +# MiniMax-Music3, songs (§5.15): the diffusers pipeline directory is the checkpoint (language model, +# depth decoder, condition encoder, DiT, vocoder, tokenizer); bf16 throughout (21 GB, one card or two) +rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \ + --recipe data/recipes/minimax-music3-bf16.recipe + +# Breeze-TTS-2, speech (§5.15): the release directory, its codec in audio_tokenizer/ read with it; +# bf16 (6 GB, one card) +rad-convert /srv/models/BreezeBlue/Breeze-TTS-2 -o breeze-tts2-bf16.rad \ + --recipe data/recipes/breeze-tts2-bf16.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read @@ -409,18 +421,21 @@ dequantisation where the architecture's kernels read another form, and NVFP4 alw | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) | | `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | | `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) | -| `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `symmetric`, `strategy: group`, not `dynamic`, no `actorder` and no `input_activations` (e.g. Google's Gemma 4 QAT w4a16-ct) | `i4*[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. A zero point is refused by name, and an `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read | -| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped | +| `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `strategy: group`, not `dynamic`, no `input_activations`, `actorder` none, `static` or `weight` (e.g. Google's Gemma 4 QAT w4a16-ct, ukisai's Swift 1.5 27B INT4) | `i4*[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. Act-order `static`/`weight` keeps each group's columns together and reads as none; `group`/`dynamic` reorders the groups and is refused by name, as is an `X.weight_g_idx` that moves a column. An `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read, `data/recipes/q38-27b-w4a16.recipe` serves a group-128 one at its own numbers | +| the same with `symmetric: false` (W4A16_ASYM, as llm-compressor's AWQ writes it; e.g. ukisai's Swift 1.5 27B W4A16-AWQ) | `u4*[1xG]-u4[1xG]` | the stored nibbles as the codes and `X.weight_zero_point` (int32 `[N/8, G]`, eight zero points a word along N, offset 8) as the zero plane, so `(u - z) * s` is compressed-tensors' `(q - zero_point) * scale` bit for bit | +| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16 (the routed-expert GEMMs' scale). Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped; an `import` rule keeps them in their shipped f16 (`data/recipes/q38-27b-w4a16.recipe`) | | `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule (`data/recipes/q38-27b-nvfp4-df2.recipe` makes it MXFP4) | -| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale is refused at the weight. The quantisation is still the tool's, so the family's quantised plugin serves it | +| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale (`[1]`) is written once a row, so it is imported rather than byte for byte. The quantisation is still the tool's, so the family's quantised plugin serves it | +| `modelopt` (NVIDIA ModelOpt) with `quant_algo` `NVFP4`, `FP8`, or `MIXED_PRECISION` whose `quantized_layers` are each NVFP4 (group 16) or FP8 (e.g. ukisai's Swift 1.5 27B NVFP4) | NVFP4: `fp4_e2m1*f32[1x16]`; FP8: `fp8_e4m3*f32[1x*]` | NVFP4: `X.weight` (U8 `[N, K/2]`, the even k in the low nibble) beside an f32 scale per 16 of K, `float(X.weight_scale) * X.weight_scale_2`: ModelOpt's second level multiplies, where compressed-tensors' global scale divides. FP8: `X.weight` E4M3 with its one f32 `X.weight_scale`, written once a row. `X.input_scale` (a static activation scale) is not read: activations are quantised from their own values. Any other algorithm is refused by name. No kernel serves NVFP4, and none an FP8 scale per tensor, so both take recipe rules (`data/recipes/q38-27b-modelopt-nvfp4.recipe`) | The width is read per tensor, so a release mixing int4 experts with int8 projections imports both. A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads every weight by its own form: a weight without `X.weight_packed` is not NVFP4 and reads stock, its `float-quantized` FP8 with the per-row (`[N, 1]`) or block scale beside it. A compressed-tensors release whose groups are all `float-quantized` FP8 reads the same way, with nothing to import. -What an import cannot read (an asymmetric zero point, an act-order index, a group under 128, a -missing or zero global scale, a compressed-tensors format not listed here) is refused by name. The release's `quantization_config` names the tool, not a served +What an import cannot read (a GPTQ zero point other than the symmetric one, an act-order index +that reorders groups, a GPTQ group under 128, a missing or zero global scale, a format or +algorithm not listed here) is refused by name. The release's `quantization_config` names the tool, not a served form, so it is kept as `imported_quantization_config.*`, and the model is served by its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B, `qwen4exp_fp8` for Flash-Next). @@ -430,8 +445,17 @@ the source, so one recipe covers a mixed release in one pass. NVFP4 to MXFP4 rou scales per 16 to a power of two per 32), so it loses more than MXFP4 made from the bf16 original: against the block-fp8 Qwen3.8-27B on the same four documents, unsloth's NVFP4 release made MXFP4 scores mean KL 0.287 and top-1 agreement 87.5%, AMD's calibrated Quark MXFP4 container 0.206 and -89.3%. Prefer the Quark container unless you need that particular checkpoint. The recipes of -record: +89.3%. Prefer the Quark container unless you need that particular checkpoint. + +Where the kernels read the release's own numbers in another spelling, a recipe's `import` rule +(rad-convert's own, docs/TOOLS.md) writes them so instead of quantising again. An int4 W4A16 +release reaches the 4-bit GEMMs that way, `blk.*.weight import codes=u4 zero=u4 scale=f16`: u4 +codes, an f16 scale and a u4 zero point per 128 of K, a symmetric grid's codes made unsigned under a +zero of 8. Every code and zero point is the release's and every scale is exact in f16 except a bf16 +scale below f16's normal range (2^-14), which rounds; rad-convert reports how many did. Qwen3.8-27B +serves them on `gemm_nt_q` at `w4a16_asym` over the input cast to f16 up to 64 rows a step and at +`w4a8i8_asym` over an int8 activation with a scale per (row, 128) above (docs/OPS.md). The recipes +of record: ```sh # AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter @@ -451,6 +475,17 @@ rad-convert /srv/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model /srv/models rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ --recipe data/recipes/q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad +# An int4 W4A16 Qwen3.8-27B (compressed-tensors AWQ or GPTQ, AutoRound's auto_gptq; here ukisai's +# Swift 1.5 W4A16-AWQ, and its INT4 and W4A16-AutoRound the same way): the shipped grids on the +# 4-bit GEMMs, the head block fp8 +rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ \ + --recipe data/recipes/q38-27b-w4a16.recipe -o swift15-27b-w4a16-awq.rad + +# An NVIDIA ModelOpt NVFP4 Qwen3.8-27B (ukisai's Swift 1.5 NVFP4): the FP8 projections' codes kept +# as block fp8, the NVFP4 MLPs made MXFP4, the NVFP4 head block fp8 +rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b-NVFP4 \ + --recipe data/recipes/q38-27b-modelopt-nvfp4.recipe -o swift15-27b-nvfp4.rad + # An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8 rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \ --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad @@ -1030,6 +1065,32 @@ hit. Snapshots never take VRAM: each is copied to host memory after the step tha back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the linear half is served. +**How many snapshots.** The snapshot store (`--checkpoint-slots`) is shared by every conversation, +running or not, and a conversation without a snapshot under its next prompt reuses nothing. With +`auto`, the default, each of `--max-num-seqs` gets what `--checkpoint-policy` keeps for one +`--max-model-len` conversation plus one for the checkpoint its running turn writes: geometric +backoff keeps 9 for a 200K-token conversation at the default 2048-token interval, so 10 a sequence, +80 at `--max-num-seqs 8`. The store is pinned for the life of the server, so `auto` takes at most an +eighth of host memory (and never less than 8 slots where the host can pin them), and never more than +the host can pin after the host pools, the host tier and the activation arenas. The startup log says +what it chose; Flash-Next at `--tp 2 --max-num-seqs 8` on a host with 128 GB of RAM: + +``` +checkpoint slots: auto: 80 linear-state snapshot(s) of 113.50 MiB in pinned host memory (8.87 GiB), +none of it on the card; 10 a sequence for --max-num-seqs 8: geometric-backoff keeps 9 for a +200000-token session at a 2048-token interval, and one more for a running turn +``` + +A line that says `held to an eighth of host memory`, or (a warning) `held to what the host can +pin`, means the store is smaller than the policy wants; `--checkpoint-slots N` sets the count +outright. An agent client with subagents keeps more +conversations alive than it runs at once: a parent waits while its subagent runs, and in a store +much smaller than `auto`'s the subagent's snapshots displace the parent's, whose next turn then +prefills its whole history again. `radiance:prefix_hit_cut_tokens_total` counts the prompt tokens +the attention cache held and admission computed again for want of a snapshot, and +`radiance:prefix_cache_ckpt_evictions_by_reason_total{reason="store_full"}` the snapshots a full +store gave up; `scripts/agentreplay.py` drives that workload against a server. + ### 4.9 Request defaults Each default applies only to a request that does not name the field. @@ -1136,10 +1197,13 @@ radiance --model base.rad --lora mytune=/adapters/mytune --lora other=/adapters/ ``` Each request picks one by `model`: `"model": "mytune"` runs with that adapter, the served model's -own name (or no name) runs the base. Requests for different adapters and for the base share one -batch. The base weights are never touched, whatever their encoding; each targeted GEMM is followed -by `y += scale * B(A x)` in bf16 adapter weights and f32 accumulation, on every rank before the -all-reduce, so it works at any `--tp`. +own name (or no name) runs the base, and any other name is a 404 that lists what is served. +Requests for different adapters and for the base share one batch. The base weights are never +touched, whatever their encoding; each targeted GEMM is followed by `y += scale * B(A x)` in bf16 +adapter weights and f32 accumulation, on every rank before the all-reduce, so it works at any +`--tp`, and on the CPU (libavx) as on a card. A step that carries no adapter request runs no adapter +op, so base requests cost what they cost without `--lora`; the one exception is the fused GEMM +below. - `--max-loras N` reserves N slots (default: the number of `--lora`). Each slot holds one adapter's A and B for every targeted weight; startup prints the size. With free slots, adapters load and @@ -1156,18 +1220,21 @@ all-reduce, so it works at any `--tp`. already on the card may still read it), which a load waits for by itself. - `--max-lora-rank R` (default 16) is the rank every slot is sized for. A smaller rank is padded, a larger one refused. -- `--lora-target-modules q_proj,k_proj,...` names what adapters may target. Default: what the - `--lora` adapters target. Needed with `--max-loras` and no `--lora`. +- `--lora-target-modules q_proj,k_proj,...` names what adapters may target, as module leaf names. + Default: what the `--lora` adapters target. Needed with `--max-loras` and no `--lora`. A name + that is no trunk linear of the model is refused at startup. - `/v1/models` lists each adapter as its own model, `parent` naming the base. - The prefix cache keys every block on the adapter, so KV is never shared across adapters, and a reload under the same name starts cold. Refused at startup or load, by name: DoRA, embedding or `lm_head` LoRA, `modules_to_save`, trained -biases, a module the base does not have, and a module some op cannot carry -- a routed MoE expert, -a rotated (ParoQuant) or otherwise transformed weight. A fused GEMM over a targeted weight (the fp8 -gated gate_up fold) is not used while LoRA is on; the unfused pair runs instead. A drafter keeps the -base's weights: proposals are still verified by the adapter, so output is exact and only the -acceptance rate can drop. +biases, PEFT's `layer_replication`, QA-LoRA and activated LoRA, a module the base does not have, and +a module some op cannot carry -- a routed MoE expert, a rotated (ParoQuant) or otherwise transformed +weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). Adapters serve models that generate text: an +image, audio or video generator and an embedding model refuse `--lora` and `--max-loras`. A fused +GEMM over a targeted weight (the fp8 gated gate_up fold) is not used while LoRA is on, for base +requests too; the unfused pair runs instead. A drafter keeps the base's weights: proposals are +still verified by the adapter, so output is exact and only the acceptance rate can drop. ### 4.10 Every flag @@ -1229,7 +1296,7 @@ acceptance rate can drop. | `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine | | `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens | | `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) | -| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). A full store retires its least recently used snapshot. A store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start | +| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; the startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start | | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | | `--no-prefix-cache` | prefix cache on | disable prefix caching | @@ -1313,6 +1380,8 @@ a model that takes no images or video. A Qwen-VL container that states none uses | `--kld-ref DIR` | score this model against the reference in `DIR`: mean, median, 99/99.9/99.99th percentile KL divergence and top-1 agreement | | `--kld-corpus FILE` | JSONL, one `{"prompt", "score_from"?, "source"?}` a line; `--kld-record` only | | `--kld-out FILE` | the `--kld-ref` report as JSON, and every position's numbers in `FILE.rows` | +| `--kld-lora NAME` | run the documents through the `--lora` adapter `NAME` (§4.9.1), e.g. against a reference recorded from the merged checkpoint | +| `--kld-lora-sources PREFIX` | with `--kld-lora`, only the documents whose `source` starts with `PREFIX` run through the adapter; the rest run as the base, in the same steps | **Diagnostics** @@ -1341,6 +1410,9 @@ a model that takes no images or video. A Qwen-VL container that states none uses | `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) | | `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) | | `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) | +| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2), `instructions` describing the voice; songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) | +| `GET /v1/audio/speech/stream` (WebSocket) | vLLM-Omni's realtime speech session: text streamed in, each sentence's audio streamed out as soon as the sentence is complete; needs an audio generation model (§5.15) | +| `POST /v1/videos`, `GET /v1/videos[/:id[/content]]`, `DELETE /v1/videos/:id` | OpenAI's video jobs: a video with its soundtrack from a prompt, made in the background and downloaded as MP4; needs a video model (MiniMax-H3), else 501 (§5.16) | | `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) | | `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client (§5.9) | | `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and clients of llama-server's own API (§5.9) | @@ -1363,9 +1435,10 @@ a model that takes no images or video. A Qwen-VL container that states none uses Methods follow vLLM's: `/tokenize` is POST because its input is a body, and `/ping` answers GET and POST because load balancers differ. As in llama-server, `/chat/completions`, `/chat/completions/input_tokens`, `/embeddings`, `/images/generations`, `/images/edits`, -`/audio/transcriptions`, `/models`, `/responses` and `/responses/input_tokens` also answer without -`/v1`, for a client configured with the bare host as its base URL; `/completions` without `/v1` is -llama-server's native completion, as it is there. A path nothing serves is a JSON 404. +`/audio/transcriptions`, `/audio/speech`, `/models`, `/responses` and `/responses/input_tokens` also +answer without `/v1`, for a client configured with the bare host as its base URL; `/completions` +without `/v1` is llama-server's native completion, as it is there. A path nothing serves is a JSON +404. A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send @@ -1702,7 +1775,7 @@ fall into four kinds: | `post_sampling_probs` | false | logprobs are the raw distribution's; the sampler's are not returned | | `best_of` | ≤ 1 | not implemented | | `suffix` | empty | infilling through `/v1/completions` is not implemented | -| `lora` | empty | out of scope | +| `lora` | empty | an adapter is chosen by `model` (§4.9.1), not by a per-request list | | `modalities`, `audio` | `["text"]`, null | output other than text is not implemented | | `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, ≤ 0, false | not implemented (`return_tokens` is served on `/completion`, §5.9) | | `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty, empty | the chat format decides them | @@ -2083,6 +2156,181 @@ socket. --- +### 5.15 Speech and music: `/v1/audio/speech` + +An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model (Breeze-TTS-2) +speaks `input`, in a voice `instructions` may describe; a music model (MiniMax-Music3) sings `input` +as lyrics, as `instructions` describe the song (SGLang-Omni's reading of the route). Both are +converted from their release directories (§3.2). + +#### Speech: Breeze-TTS-2 + +```sh +radiance --model breeze-tts2-bf16.rad # one card + +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "The quick brown fox jumps over the lazy dog."}' -o fox.wav # 24 kHz mono, 16-bit +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "It was a bright cold day in April.", + "instructions": "A calm, warm female narrator, speaking slowly.", "guidance_scale": 4}' -o april.wav +``` + +- **`input`** is the text to speak, as written. **`instructions`**, optional, describe the voice + (who speaks, how); BreezeBlue suggests `guidance_scale` 4 with them, against a voice without the + description (1, the default, is none). +- **The length** is `duration` in seconds or `max_new_tokens` in frames (12.5 a second), up to two + minutes; the model ends the speech at the end of the text. The prompt holds at most 512 tokens. +- **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below + (`voice` is ignored here too: the instructions say who speaks); `num_inference_steps` is refused + (the model has no denoiser). Cloning a voice from a recording is not served. + +Speech is played four frames (0.32 s) at a time as it is made, so the streamed forms below carry it +as it is spoken. On one R9700 a sentence is made at 0.6 of the time it plays (5.1 s of speech in +3.1 s), and a stream's first audio comes 0.21 s after the request; four speak at once at about the +speed they play (43 s of speech in 12.1 s). Breeze-TTS-2 is licensed for research and +non-commercial use only, and BreezeBlue counts hosting it as an API as commercial. + +#### Music: MiniMax-Music3 + +```sh +radiance --model minimax-music3-bf16.rad --tp 2 + +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "[verse]\nMorning light filtering through the pine\n[chorus]\nSoftly the world begins to breathe", + "instructions": "Genre: acoustic pop. BPM: 96. Warm and intimate. Vocals: soft female lead.", + "duration": 30, "seed": 7}' -o song.wav # 44.1 kHz stereo, 16-bit +curl -sN http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "...", "instructions": "...", "stream_format": "audio", + "response_format": "pcm"}' | ffplay -nodisp -f s16le -ar 44100 -ch_layout stereo - # as made +``` + +- **`input`** (the lyrics, with the model's section tags such as `[verse]` and `[chorus]`) and + **`instructions`** (genre, tempo, key, mood, vocals, instruments) are both required. Each is + rewritten into the form the model was trained on and read as plain text, so neither can carry + the model's control tokens. +- **The length** is `duration` in seconds or `max_new_tokens` in frames (25 a second), up to six + minutes; without either the song runs until the model ends it, which it usually does at the end + of the lyrics. Give one, not both. +- **`seed`** makes a song repeatable: the same seed, text and length give the same samples again + on the same deployment. Another card count rounds differently, and a song can then take another + turn. Absent or -1 picks one; the `X-Seed` response header says which. +- **`num_inference_steps`** (30) and **`guidance_scale`** (1.7) are the denoiser's. +- **`response_format`** is `wav` (the default) or `pcm`, 16-bit little-endian at the model's rate + and channels, which the `X-Audio-Sample-Rate` and `X-Audio-Channels` headers state. `voice` is + accepted and ignored (the description says who sings); `speed` must be 1. + +A song's first window comes once its 200 frames are written and denoised; each later one follows +a hundred frames on. On two R9700s a song is made at about the speed it plays: 10 s of audio in +10.8 s with the first audio at 8.5 s, 12 s in 12.7 s; on one card, 4 s in 7.3 s. Up to four songs +are made at once. + +#### Streaming + +Without a stream field the response is the whole audio once it is finished. A song is played eight +seconds at a time (a 200-frame window, a new one every 100 frames), speech four frames at a time, +and two streamed forms send each piece as it is played, as vLLM-Omni's speech route does: + +- `"stream_format": "audio"` sends the bytes themselves; a `wav` stream's header states no length. +- `"stream": true` or `"stream_format": "sse"` sends Server-Sent Events: `speech.audio.delta` with + base64 PCM in `audio` (`response_format` must be `pcm`), then `speech.audio.done` with the usage + (prompt tokens in, frames out), or `speech.audio.error`. + +#### Live: `/v1/audio/speech/stream` + +The same model speaks text while it is still being written, over a WebSocket at +`/v1/audio/speech/stream` speaking vLLM-Omni's realtime speech protocol: the client streams the +text in (a language model's reply token by token, say), and each sentence is spoken as soon as it +is complete, so the first audio waits for the first sentence rather than the whole text. + +| client sends | server answers | +|---|---| +| `session.config` — first, and again only between utterances | nothing, or `error` naming the field it refused | +| `input.text` `{"text": "..."}` — any piece of the text | for each sentence it completes: `audio.start`, the audio as binary messages, `audio.done` | +| `input.done` — the utterance's text has ended | the rest of the text as its last sentence, then `session.done` | +| `session.close` | the socket closes (1000); a sentence being spoken is cancelled | + +- **`session.config`** takes the fields of `POST /v1/audio/speech` but `input` (`instructions`, + `voice`, `seed`, `guidance_scale`, `max_new_tokens` or `duration` for each sentence, `speed`, + `num_inference_steps` where the model has a denoiser), checked as that route checks them, and + four of its own: `response_format` `pcm` (the default) or `wav`; `stream_audio`, false (the + default) for one binary message a sentence or true for the audio as the model makes it; + `split_granularity`, `sentence` (the default), `clause` (also at commas and semicolons) or `none` + (the whole utterance at `input.done`); and `text_input_mode`, whose only value here is + `buffered` (vLLM-Omni's `commitment` mode is refused by name). Every sentence is one request made + with these fields; with a `seed`, every sentence uses it. +- **`audio.start`** carries `utterance_index`, `sentence_index` (from 0 in each utterance), + `sentence_text`, `format`, `sample_rate` and `channels`. The audio is 16-bit little-endian PCM at + that rate and channel count; a `wav` sentence is one file, whose header states its length, or + while it streams a header that states none before the samples. **`audio.done`** carries + `utterance_index`, `sentence_index`, `total_bytes` (of the binary messages) and `error`, true when + the sentence failed, after an `error` event saying why. **`session.done`** carries + `utterance_index` and `total_sentences`; the session then takes the next utterance. +- **Sentences** end after `.`, `!` and `?` followed by whitespace, and after their CJK (`。!?…`), + Indic (`।॥`) and Arabic (`؟`) forms followed by anything, since those scripts put no space there; + `clause` also ends one after `,` `;` and `,;،؛`. A decimal point, a common abbreviation (Dr., + Mr., e.g., etc.) and an initial (J., J.R.) end none, and a run of punctuation or a closing quote + or bracket stays with its sentence. A stop at the end of what has arrived waits for the next + piece, or for `input.done`. + +**Limits.** A server holds as many sessions as the model has lanes (four for both models), each +holding one admission place (`--max-queued-requests`) for its whole life; a session refused either +way gets an `error` event and a 1013 close. A session speaks its sentences one at a time, in order. +An utterance holds at most 128 KiB of text that no sentence has ended yet; a piece past that is +refused with an `error` and dropped. A message that is not JSON, or a binary one, is an `error`, +and the session goes on. + +### 5.16 Video: `/v1/videos` + +A video generation model (MiniMax-H3) answers OpenAI's video jobs: `POST /v1/videos` queues a video +with its stereo soundtrack and answers at once with the video object; `GET /v1/videos/{id}` reports +its `status` (`queued`, `in_progress`, `completed`, `failed`) and `progress` (0 to 100); +`GET /v1/videos/{id}/content` downloads the MP4 once it is completed (`?variant=thumbnail` gives the +first frame as WebP). `GET /v1/videos` lists the jobs, newest first (`limit`, `after`, `order`), and +`DELETE /v1/videos/{id}` removes one, cancelling it if it is still running. + +```sh +radiance --model minimax-h3-fp8.rad --tp 2 --vision-tower-placement ram + +curl -s http://localhost:8000/v1/videos -H 'Content-Type: application/json' -d '{ + "prompt": "A red fox trotting through a snowy pine forest, snow crunching underfoot", + "seconds": "5", "size": "1344x768", "seed": 7}' # -> {"id": "video_...", "status": "queued", ...} +curl -s http://localhost:8000/v1/videos/video_... # poll until "status": "completed" +curl -s http://localhost:8000/v1/videos/video_.../content -o fox.mp4 +``` + +- **`prompt`** is read as written, with no template; MiniMax-H3 was trained on long structured + descriptions (a shot, its soundscape, its music), which follow it best. At most 2048 tokens. +- **`seconds`** is rounded up to the model's length steps (17 frames, 0.71 s, at 24 frames a + second): 5.17 to 14.4 seconds, 5.17 by default. The video object's `seconds` is what is made. +- **`size`** is the frame's `WIDTHxHEIGHT`: both sides multiples of 32 from 256, at most + 1344 x 768 pixels of area, at most 4:1. By default 1344x768. SGLang's `target` + `{"aspect_ratio": "9:16", "short_edge": 768, "duration_seconds": 8}` lays the model's own canvas + over a ratio instead (768 on the short side, the area capped, rounded to 32). +- **`seed`** makes a video repeatable on the same deployment (absent or -1 picks one); + **`num_inference_steps`** counts sigma grid points as diffusers and SGLang do (50, so 49 model + evaluations, by default; at most 65). The model is guidance-distilled, so there is no guidance + scale and no negative prompt. A step-distilled release (FastH3, below) runs only the schedule it + was trained on: 9 grid points, and any other count is refused with a 400. +- Only text is read: `input_reference` and non-empty `conditions` are refused, as is a `task` + other than `t2va`. Fields are JSON or a multipart form (OpenAI's clients send the form). + +**FastH3.** FastVideo's FastH3 8-Step V2 (`FastVideo/FastVideo-FastH3-8-Step-V2`) is the same model +distilled to eight steps with video sparse attention; it is converted with the same recipe, its text +encoder and decoders taken from a MiniMax-H3 container (`data/recipes/minimax-h3-fp8.recipe` says +how), served the same way and named `fastvideo-fasth3-8-step-v2`. Its card notes that difficult +motion, fine detail and some audio may fall below the base model's; it serves text to video only. + +On two R9700s (`--tp 2`, 300 W) a 5.17 s clip at 1344x768 takes about 68 s with FastH3 and about +8.8 minutes with MiniMax-H3's default 50 steps. Both attentions run their scores in int8 and +P.V in fp8 (docs/ARCHITECTURES.md); a step's cost grows with the square of the rows, so a longer +clip or a larger frame costs more than in proportion. The text encoder and the modulation +projections (17.9 GiB a rank) and the token embedding (1.5 GiB a rank) are read from pinned host +memory, about 39 GiB of it in all, which `--vision-tower-placement ram` requires at two ranks. + +The MP4 holds H.264 video (yuv420p, BT.709) and AAC audio at 32 kHz stereo. A finished file is kept +for an hour (`expires_at`), at most 32 of them. MiniMax-H3's license excludes use in the EU, the UK, +the Republic of Korea and the USA without a separate license from MiniMax. + ## 6. Operation ### 6.1 The dashboard @@ -2265,7 +2513,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.7.0 +I STARTUP REPORT -- radiance 1.8.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] @@ -2310,7 +2558,7 @@ curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findin | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi` and stop the other process. The budget is stated before allocation, so the log says what it asked for | | `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates, so a card that refuses its weights pool lost that memory to another process in between (the next line says how much is free now). A refused `host_pool` is pinned memory: every rank pins its own `--host-pool-mib` (twice at `--tp 2`), and the amdgpu driver caps what all processes together pin at RAM less 1/64 and 1.5 GiB. It is locked user memory, which `ttm.pages_limit` does not count | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under both the cap and the available RAM the refusal names. `amdgpu.no_system_mem_limit=1` lifts the driver's cap, but not the RAM | | `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode can refuse a single pin above about 2.5 GiB; a failing piece means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through, but on such a host it can also remove peer access between the cards, moving every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line | -| `device: a synchronisation has waited 5 s; the queues:` with the packet each queue is on, then `device: no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue; the kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps moves under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits on a queue that never drains. Clock instability (a voltage offset) is the other cause seen on R9700s. If the follow-up line says the queues advanced, the wait was long, not stuck | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset restores the power cap, fan curve and voltage offset to firmware defaults; re-apply them before every start. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`, which a reboot loses. `docker inspect` shows exit code 0 for a container Docker already restarted, whatever ended the old process | +| `device: a synchronisation has seen no queue advance for 5 s; the queues:` with the packet each queue is on, then `device: no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue; the kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps moves under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits on a queue that never drains. Clock instability (a voltage offset) is the other cause seen on R9700s. A wait that is only long (a deep prefill, a video's denoising pass) reports nothing while any queue advances | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset restores the power cap, fan curve and voltage offset to firmware defaults; re-apply them before every start. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`, which a reboot loses. `docker inspect` shows exit code 0 for a container Docker already restarted, whatever ended the old process | | `--draft-model is not implemented` | The engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | | `context_length_exceeded` on a request | The prompt alone does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it | | `unknown option '--foo'` and the engine exits | An unknown flag is an error, so a typo in a budget flag cannot silently change the plan | Check `radiance --help` | diff --git a/docs/OPS.md b/docs/OPS.md index cca6a18f..60f04fa7 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -193,7 +193,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | | `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | | `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | -| `add` | `M`(range) `n` `dtype` | `a`, `b` → `y` | +| `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` | | `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` | | `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) | | `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) | @@ -204,7 +204,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` | | `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? | | `conv2d_unfold` | `M`(range) `width` `cin` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `t_last`/opt `dtype` | `x`, `cu_seqlens`, `valid`? → `y` | -| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` | +| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y`; `b`w? | | `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` | | `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) | | `seg_sinusoid` | `M`(range) `n` `period` `max_timescale`:f64/opt `cu_div`/opt `dtype` | `cu_seqlens` → `y` | @@ -237,7 +237,10 @@ does it. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.m with the gate in the first half. **`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a -bias add). Nothing else broadcasts, in these or any other elementwise op. +bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides +the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain +sum): the last step of a mean summed pairwise, as a vocoder averages its residual blocks, +`add(add(b0, b1), b2, div 3)` for `(b0 + b1 + b2) / 3`. A `div` of 0 is refused. **`sigmoid`**, with `mul`, gates a shared expert (`ffn_gate_inp_shexp`). Without it the shared expert runs ungated, which is a different model. @@ -326,8 +329,8 @@ is easy to miss. With `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`: the frame mask the subsampler applies before each convolution. f32 sum, one rounding. - **`conv1d_dw`** is a causal depthwise convolution over time, - `y[t, c] = sum_j w[c, 0, j] * x[t - (k - 1) + j, c]`, with rows before the segment's start - reading as zeros. + `y[t, c] = sum_j w[c, 0, j] * x[t - (k - 1) + j, c] + b[c]`, with rows before the segment's start + reading as zeros and `b` zero when unbound. - **`rel_sinusoid`** writes the sinusoidal relative-position table, row `d` for distance `d`: `sin(d * inv[i])` over the first half and `cos(d * inv[i])` over the second, `inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's @@ -485,6 +488,7 @@ and is optional. | op | params | operands | |---|---|---| | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `quant_cols_fp8` | `M` `n` `dtype` | `x` → `y`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` | | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | @@ -492,6 +496,11 @@ and is optional. | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +`quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, +`scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an +attention's values for its fp8 P.V form, where a column is one dimension of one head and its scale +multiplies out of the sum over keys. + `gemm_nt_q_gated` is `gemm_nt_q` over a `[N, K]` gate_up plane (`N` is the weight's rows, twice the fused width, gate half first) with `gated_quant_fp8`'s pass in the epilogue, so the `[M, N]` bf16 tensor between them is never written. It is a separate schema, not a flag on `gemm_nt_q`, because @@ -629,7 +638,8 @@ implementation reads `res` before it stores the product over it. | `lora_expand` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout | The two halves of `y += scale ⊙ (B · (A · x))` at a trunk GEMM, issued by the core right after the -GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step. `slot` is +GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step; a step +with no adapter row issues neither. `slot` is an i32 per row naming its adapter's pool slot -- the step batch's `RadBatch::lora_slot` from the GEMM's first row on; **a row with `slot < 0 || slot >= S` is a base row and neither op touches it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does not read or write its @@ -665,12 +675,12 @@ bytes). | op | params | operands | |---|---|---| | `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | -| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | +| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | -| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt | `qkv`:inout, `positions` | +| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | -| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w | +| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative @@ -689,7 +699,9 @@ maximum, which selects the band; the per-sequence lengths come from `cu_seqlens` or one input per entry so a whole batch is one launch. `window` is `attn_paged`'s rule over a segment's own positions (causal: key `j` is visible to query `i` when `i - j < window`; non-causal: when `|i - j| < window`), and 0 is no window. A bidirectional encoder's sliding layer of radius `r` -(`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or +(`|i - j| <= r`) is `window = r + 1`; one that sees `l` keys behind and `r` ahead is `window = l + 1` +with `window_right = r + 1` (non-causal only: key `j` visible when `i - j < window` and +`j - i < window_right`). `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read at its row pitch, so a tower's `[q|k|v]` row needs no copy. @@ -717,6 +729,19 @@ owns: With `[M]` positions every component is that one position, so `mrope` and `imrope` over a text batch are exactly `neox`. +**Positions** are integers or floats, and the operand's dtype says which. An integer `positions` +(i32) is read as an integer; an f32 one (bf16 and f16 too) as the value it holds, a fractional +coordinate such as a video decoder's normalised grid already multiplied by `2 pi`. Either way the +angle is `f32(pos / scale) * inv` in f32. `[C, M]` positions are read at the operand's own strides, +so a `[C, M]` view of a wider `[C, max]` plane is read in place. + +**`llama3_*`** applies Llama 3's frequency scaling (transformers' `rope_type` `llama3`) to `rope`'s +ladder: with wavelength `2 pi / inv`, a frequency shorter than `llama3_orig / llama3_high` is kept, +one longer than `llama3_orig / llama3_low` is divided by `llama3_factor`, and those between blend, +`s = (llama3_orig / wavelength - llama3_low) / (llama3_high - llama3_low)`, +`(1 - s) inv / llama3_factor + s inv`, in f32 (`abi/rad_yarn.h`, `RadLlama3`). It does not combine +with YaRN or a multi-component mode. + **`ladder`** names the width the base frequency ladder is measured in. Absent or `rotary`, the exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width. `head` divides by `head_dim` instead (the proportional variant), so the `rotary_dim / 2` frequencies are a @@ -726,8 +751,12 @@ ladders), and the head past `rotary_dim` is untouched either way. `rope_table` t the same reason: its angles must stay `rope`'s exactly. **`qk_norm_rope`** RMS-norms each q and k head of a fused `[q | k | v]` row against its gain (plus -`wadd`), rounds, and rotates in place. +`wadd`), rounds, and rotates in place. `positions` is read as `rope` reads it, integer or f32. +- An absent `q_w` or `k_w` is a unit gain, without `wadd`: the head is `x rsqrt(mean(x^2) + eps)`, + rounded (a video decoder's weightless q and k norms). +- `rotary_dim` 0 is the norm alone: nothing rotates, and `positions` may be absent (`M` is then + `qkv`'s rows). A rotation with no positions is refused. - `v_norm` 1 also RMS-norms every v head with a unit gain and does not rotate it: Gemma 4's value norm, which has no weight. - `mode` `blocks` rotates each section as its own block of channels: section `c` is `sections[c]` @@ -740,6 +769,14 @@ the same reason: its angles must stay `rope`'s exactly. a 3-axis image rotary's complex form. - `mode` `imrope` is `rope`'s `imrope` over NeoX pairs, reading three position planes (Qwen3-VL's text attention). +- `mode` `axial` is `rope`'s `axial` over NeoX pairs `(i, i + rotary_dim / 2)`: the + `rotary_dim / 2` frequencies split into contiguous `sections` (summing to `rotary_dim / 2`), + section `c`'s `j`-th frequency `theta^(-2j / (2 sections[c]))` turned by position component `c`. + `positions` is `[C, M]` with `C` at least the section count, or `[M]`, every component then that + one position on the same per-section ladders (unlike `rope`, whose `[M]` positions fall back to + the plain ladder). MiniMax-H3's DiT rotates 96 of its 128 channels with sections `16 16 16` + (theta 1e4) over f32 `(t, h, w)` positions; its video decoder 48 of 64 with `8 8 8` (theta 100) + over positions `grid_pos3` writes. **`qkv_norm_rope`** (device-only) is the same prologue over separate `q`, `k` and `v` projections (Gemma 4's text attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary @@ -819,7 +856,7 @@ says which (`libref/ref_gen.cpp`). | op | params | operands | |---|---|---| | `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` | -| `gate_add` | `M`(range) `n` `dtype` | `y`, `g`, `cu_seqlens`, `x`:inout | +| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout | | `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | | `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` | | `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` | @@ -827,7 +864,7 @@ says which (`libref/ref_gen.cpp`). | `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout | | `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout | | `flow_euler` | `M`(range) `n` `stride` `dtype` | `v`, `sigma`, `sigma_next`, `cfg`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `inp_lat`?, `inp_mask`?, `state`:inout, `preview`:inout? | -| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` | `x` → `y` | +| `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` `round`/opt | `x` → `y` | | `conv2d_nhwc` | `M`(range) `cin` `cout` `k` `stride` `pad` `up` `dtype` | `x`, `w`w, `b`w → `y` | | `l2norm_chan` | `M`(range) `n` `act` `dtype` | `x`, `gamma`w → `y` | | `d2s_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout | @@ -835,7 +872,7 @@ says which (`libref/ref_gen.cpp`). | `to_rgba8` | `M`(range) `n` `dtype` | `x` → `y` | | `gelu_tanh` | `M`(range) `n` `dtype` | `x` → `y` | | `scatter_add_rows` | `M`(range) `n` `dtype` | `v`, `idx`, `x`:inout | -| `attn_prefix_self` | `q_len` `head_dim` `gqa` `block_size`/der `causal` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `qk`/opt | `q`, `k`, `v`, `kv_cache`, `block_table`, `seqused`, `cu_seqlens`, `k_descale`?, `v_descale`?, `k_i8`?, `k_scale`? → `out` | +| `attn_prefix_self` | `q_len` `head_dim` `gqa` `block_size`/der `causal` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `qk`/opt `pv`/opt | `q`, `k`, `v`, `kv_cache`?, `block_table`?, `seqused`?, `cu_seqlens`, `k_descale`?, `v_descale`?, `k_i8`?, `k_scale`? → `out`, `v_scale`? | **Sequences and lanes.** `cu_seqlens` partitions the rows into entries (`[n_seq+1]` i32, entry `e` owning `[cu[e], cu[e+1])`; it need not start at 0). `ln_mod` and `gate_add` take each row's @@ -845,7 +882,10 @@ apart: `lane_gather` copies entry `e`'s rows out of lane `lane[e]`, and `lane_st source into every listed lane (a repainted picture's latent into each of its images). - `ln_mod`: `y = bf16(bf16(LN(x)) * bf16(1 + s[seq]))`, a layer norm with no gain and no bias. -- `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`. +- `gate_add`: `x = bf16(x + bf16(bf16(tanh(g[seq])) * y))`. `act` names the gate's activation, + `tanh` (the default) or `none`, the gate as it is and not rounded first: + `x = bf16(x + bf16(g[seq] * y))` (MiniMax-H3's last block, whose gates have no tanh). The + roundings are to `x`'s dtype. - `ln_mod_quant_fp8`: with `gated` 1, `gate_add` first; then `z = ln_mod(x)` and `(q, scale) = quant_act_fp8(z, group)`, `z` written when bound. Each value is rounded as its own store would round it, so the bytes are the three ops'. @@ -873,7 +913,10 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar - `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma` (three roundings), then `act` `none` or `silu`. - `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16; - `fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`. + `fma` is `bf16(bf16(x * mul) + add)`, `inv` is `bf16(bf16(x - add) / mul)`, the roundings to + `y`'s dtype. With `round` 0 (default 1) the lists stay f32 and so does the arithmetic, rounded + once into `y`: `fma` is `rd(f32(x * mul) + add)`, `inv` `rd(f32(x - add) / mul)` (MiniMax-H3 + denormalises its f32 audio latents with an f32 deviation and mean). - `d2s_add` (Wan's DupUp3D on one frame): `y[2r+i, 2c+j, o] += x[r, c, (o F + off + 2i + j) / rep]`, `F = 4 ft`, `off = 4` when `ft` is 2, `rep = cout F / cin`. - `s2d_avg_add` (AvgDown3D on one frame): `y` gains the mean of each output channel's group of @@ -889,7 +932,318 @@ segments before it. `qk` `"i8"` is the int8 score form and takes `k_i8` `[tokens head_dim]` and `k_scale` `[tokens, kv_heads]` f32, the own keys as `quant_act_i8g` writes them at group `head_dim`. The query and every prefix key are quantised inside the op by the same rule (scale `amax/127`, 1 for an all-zero row; code `rint(clamp(x * (1/scale), ±127))`), a score is the -exact integer dot product times both scales, and `k` is not read for the own rows. +exact integer dot product times both scales, and `k` is not read for the own rows. The prefix's +three operands come together or not at all: without them every entry's prefix is empty and the op +is self attention over each entry's rows (`max_ctx` 0 declares that form), which is how a single +long sequence takes the int8 score form. + +`pv` `"fp8"` is the fp8 P.V form, prefix-free only: `v` holds E4M3 codes and `v_scale` +`[kv_heads * head_dim]` their column scales (`quant_cols_fp8`). Over a row's visible keys, with +`p = exp(s - max)` against the row's max, each weight is taken to E4M3 as `w = e4m3(448 p)` and + + o = (sum w v) v_scale / (448 sum p) f32 sums in key order + +A kernel may take `p` against its running max in its own key order as long as every `p <= 1` +(E4M3's top is 448), which differs from this only by where each weight was rounded. + +## Audio generation + +The ops an audio generator declares (`rad_declare_audio_generator`, `abi/rad_builder.h`) beyond a +language model's and an image generator's: a frame sampler with guidance between branches over +residual codebooks, the frame embeddings, the window states of a latent denoiser, and a +vocoder's 1-D convolutions. Each rounds where the reference model materialises a bf16 tensor; the +libref function says which (`libref/ref_audio.cpp`). + +| op | params | operands | +|---|---|---| +| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? | +| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` | +| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? | +| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` | +| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | +| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` | +| `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout | +| `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout | +| `frame_store` | `M`(range) `n_codes` `stride` `rep`/opt `skip`/opt | `codes`, `lane`, `frame`, `status`, `dst`:inout | +| `resample_nearest` | `M`(range) `n` `dtype` | `x` → `y` | +| `fourier_embed` | `M`(range) `n` `round`/opt `dtype` | `t`, `w`w → `y` | +| `win_input` | `M`(range) `n_lat` `n_zero` `n_cond` `stride` `dtype` | `lat`, `cond`, `lat_cu`, `win_lane`, `pair` → `y` | +| `win_prep` | `M`(range) `n` `stride` `ov` `dtype` | `flags`, `t`, `seed`, `win_index`, `win_lane`, `pair`, `lat_cu`, `prev`, `noise`:inout, `lat`:inout | +| `win_finish` | `M`(range) `n` `n_cond` `stride` `ov` `dtype` | `flags`, `pair`, `win_lane`, `lat_cu`, `cond`, `lat`:inout, `prev`:inout, `prev_cond`:inout | +| `chan_split` | `M`(range) `n` `parts` `dtype` | `x` → `y` | +| `interleave2` | `M`(range) `dtype` | `a`, `b` → `y` | +| `iota` | `M`(range) `start` `step` `period`/opt | → `y` | +| `cu_repeat` | `M`(range) `mult` | `len` → `y` | + +**Frames.** A lane is one piece; a frame is one step of its language model, whose branches (the +conditional first, then the unconditional) are consecutive rows, `rep` of them a lane. + +- `cfg_topk_sample`: per lane, `g = u + cfg (c - u)` between its first two branch rows (`c` alone + at `rep` 1), `cfg` the operand's value for the lane when it is bound. With `hist` + `[lanes, n_vocab]` i32 and `lane` `[n]`, the lane's history row is cleared at frame 0 and every id + it holds is penalised, `g > 0 ? g / penalty : g * penalty` (a repetition penalty over the lane's + earlier picks); the pick is recorded in it. Ids in `[sup_lo, sup_hi)` are never candidates; with + `cond_k` > 0 only the entries where `c` reaches its `cond_k`-th largest value are. The `k` + largest `g` (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and drawn by + inverse CDF in descending `g`, `u = rad_philox_uniform_s(seed, 2^32 + frame, stream)` + (`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. `logits` + `[rep n, n_vocab]` f32 or bf16, `seed` `[n, 2]` u32 low word first, `frame` `[n]`. +- `end_status`: `status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]`. +- `rvq_embed`: `codes` is code-major `[n_codes, rows]`, read at the operand's own strides (a block + of a wider plane is a view); + `y = bf16(bf16(t0[c_0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale)`, or with `round` 1 + one f32 sum of every codebook's row in codebook order, times `scale`, rounded once to `y`'s dtype. + A first code outside `t0` leaves its row unwritten; a later code outside `t1` adds nothing. +- `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`, + when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each + codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes` + rows. +- `frame_mix_store`: `m = bf16(bf16(sum_l w_l h_l) * bf16(scale))`, `w = bf16(softmax(bf16(logits)))` + over the `L` planes of `hid` `[L, rows, n_embd]`, row `rep i` of each plane being lane `i`'s + conditional row; stored at `dst[lane * stride + frame - 1]` for `frame >= 1` and + `status[lane] >= 0` (frame 0 only moves past the prompt; a negative status ended the piece). +- `iota`: `y[i] = start + i * step`, or `start + (i % period) * step` with `period` (the + positions of equal sequences laid end to end). `cu_repeat`: `y[j] = j * len[0] * mult`, the bounds of equal + sequences whose length lives on the device. + +**Windows.** The denoiser runs over windows of frames, each entry of a window step a lane's latent +in a state buffer `stride` rows a lane (`lat_cu` bounds each entry's rows, `win_lane` names its +lane, `pair` is -2 for an unconditional branch, which moves no lane). `flags` carries 1 (the +window's first step), 8 (its last) and 16 (it overlaps the previous window by `ov` rows). + +- `win_input`: `y = [lat | zeros(n_zero) | cond]` from the entry's lane; an entry with `pair` -2 + takes zeros for `cond`. +- `win_prep`: flag 1 fills the lane with `rad_philox_normal_s(seed, 1 + win_index, k n + c)` as + bf16, keeping its first `ov` rows in `noise` with flag 16; flag 16 then binds the first + `min(ov, rows)` rows to the previous window's end, + `bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev))`, `t = bf16(t[e])`. +- `win_finish` (flag 8): with flag 16 the first `min(ov, rows)` rows become `prev` exactly; then + rows `[max(0, rows - 2 ov), max(.., rows - ov))` of the latent and of `cond` are kept as the next + window's `prev` and `prev_cond`. +- `fourier_embed`: `[cos(2 pi t w) | sin(2 pi t w)]`, `t` f32 `[M]`, `w` `[n / 2]`; with `round` 1 + `t`, `2 pi t`, the product and each cosine and sine are rounded to bf16. +- `resample_nearest`: output row `j` reads input row `min(floor(j * in / out), in - 1)`, the row + counts read off the operands (torch's `interpolate(mode="nearest")`). + +**The vocoder.** Rows are samples, channels innermost; `cu_seqlens` bounds each sequence and the +input reads zero outside it. + +- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding + `dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added + after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output + clamp; a NaN stays NaN). f32 accumulation, one rounding. +- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two + strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even; + 0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a + stride): output row `o` of a sequence is `b + sum_i x[i] w[(o + pad) - i stride]` over the + sequence's input rows `i` with `0 <= (o + pad) - i stride < k`, summed in f32 as + `q = (o + pad) / stride`, `r = (o + pad) % stride` and taps `t = 0, 1, ..` while + `r + t stride < k` reading `x[q - t] w[r + t stride]`; one rounding. Sequence `e`'s rows + `[cu[e], cu[e+1])` become `[stride cu[e], stride cu[e+1])`, `stride L` rows from `L`. BigVGAN + upsamples with `(k 9, stride 5, pad 2)` and `(k 4, stride 2)`. +- `snake`: `x + sin(alpha x)^2 / (alpha + 1e-9)`, `alpha` per channel; with `beta` the SnakeBeta + form `x + (1 / (beta + 1e-9)) sin(alpha x)^2`. `log` 1 reads both as logarithms, exponentiated + first. +- `snake_aa`: BigVGAN's alias-free SnakeBeta (diffusers' `MiniMaxH3AudioActivation1d`: an + upsampler, the activation, a low-pass downsampler) over each sequence, in f32. For channel `c` + of a sequence of `L` rows, `P = k / ratio - 1`: + - `xp` is the sequence replicate-padded by `P` rows on each side; + - `u_full[o] = sum_i f_up[o - i ratio] xp[i]` over the rows `i` with `0 <= o - i ratio < k`, in + ascending `i` (a depthwise `conv_transpose1d` at stride `ratio`), and + `u = ratio u_full[P ratio + (k - ratio) / 2 + m]` for `m < L ratio` (the full output cropped by + `P ratio + (k - ratio) / 2` rows at the start and `P ratio + (k - ratio + 1) / 2` at the end); + - `a = u + (1 / (B + 1e-9)) sin(A u)^2` as `snake`'s `beta` form evaluates it, `A = exp(alpha[c])` + and `B = exp(beta[c])` with `log` 1, the values themselves otherwise; + - `ap` is `a` replicate-padded by `k / 2` rows on the right and `k / 2` on the left less one for + an even `k`, and `y[o] = sum_j f_down[j] ap[o ratio + j]` over `j < k` in ascending `j`, for + `o < L`. + + `f_up` and `f_down` are the checkpoint's `[1, 1, k]` Kaiser filters, one for every channel + (MiniMax-H3: `k` 12, `ratio` 2). A sequence keeps its length. +- `chan_split`: `y[p rows + r] = x[r, p n .. p n + n)`, a stereo latent's halves as two streams. +- `interleave2`: `y [rows, 2] = (a[r], b[r])`, f32. + +## Video generation + +The ops a video generator (MiniMax-H3) needs beyond a language model's, an image generator's and +an audio generator's: its diffusion transformer's modulated RMS norm and its sampler step, and the +video decoder's patch unfold, the tiles it runs over, their stitch back into frames and their +rotary positions. The transformer's attention is `qk_norm_rope` `axial` (its step-distilled form's +is [video sparse attention](#video-sparse-attention)) and its gated residual +`gate_add` `act` none; the soundtrack's vocoder is `conv_t1d`, `snake_aa` and `conv1d` `clamp` +([Audio generation](#audio-generation)). Each op rounds where the reference model materialises a +bf16 tensor and keeps f32 where it computes in f32; the libref function says which +(`libref/ref_gen.cpp`, `libref/ref_video.cpp`). + +| op | params | operands | +|---|---|---| +| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `z` | +| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | +| `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout | +| `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` | +| `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` | +| `vtile_stitch` | `M`(range) `tile` `overlap` `scale` `pt` `skip` `keep` `blend` `period` `mean` `std` | `x`, `geom`, `prev`:inout → `y` | +| `grid_pos3` | `M`(range) `T` `H` `W` `period` `scale`:f64 | → `y` | + +**The transformer.** `cu_seqlens` partitions the rows into entries as for `ln_mod`, and each row +reads its entry's rows of `s` and `g`. + +- `rms_mod` is `norm(h) (1 + scale) + shift` after the branch before it is added: with `gated` 1 + first `x = bf16(x + bf16(g[e] y))`, no tanh, stored back to `x`; then + `n1 = bf16(x rsqrt(mean(x^2) + eps))` (the sum of squares f32 in ascending order, over the + stored `x`), `n2 = bf16(n1 w)`, `m = bf16(n2 bf16(1 + scale[e]))`, `z = bf16(m + shift[e])`. + `s` is `[n_seq, >= 2n]` at its own row pitch, `shift = s[e, 0:n]` and `scale = s[e, n:2n]` (a + column slice of the modulation table); `g` is `[n_seq, >= n]` at its own pitch; `w` is `[n]`. + The residual rounds to `x`'s dtype and the norm chain to `z`'s. +- `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16 + row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound. +- `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum + one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and + the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`, + `r = f32(sigma_next / sigma)`, `x = f32(f32(r x) + f32(f32(1 - r) d))`. `t` (the timestep the + transformer was conditioned on), `sigma` and `sigma_next` (the schedule's entries) are one f32 + value each; `v` is f32 or bf16, `x` f32. + +**The decoder** runs over a request's latent geometry, which `geom`, i32 on the device, carries +(the parameters are fixed at declare). `mul`, `add`, `mean` and `std` are space-separated lists +kept in f32. An output holds at least the rows the geometry writes; rows past them are not +written. + +- `patch_unfold`: patch rows `x [F Hp Wp, C pt ph pw]` (row `(f, i, j)` frame-major then + row-major, column `(c, a, b, d)` at `c pt ph pw + a ph pw + b pw + d`, `geom` = `(F, Hp, Wp)`) + to voxel rows `y [(F pt) (Hp ph) (Wp pw), C]`, row `(t, yy, xx)` row-major: + `y[(t, yy, xx), c] = f32(f32(x[(t/pt, yy/ph, xx/pw), (c, t%pt, yy%ph, xx%pw)] mul[c]) + add[c])`, + the latent denormalised with f32 statistics. `M` is the output's rows. +- The tiles of an axis of `L` latent units are diffusers' `_split_tiles` in latent units: a `tile` + at least as long as the axis is one tile `[0, L)`, refused unless `L == tile`; otherwise + `n = ceil(L / tile)`, raised while `tile n - overlap (n - 1) < L`; `ov = [overlap] * (n - 1)`, + the slack `tile n - sum(ov) - L` added one unit at a time to `ov[i % (n - 1)]` for + `i = 0, 1, ..`; `start[0] = 0`, `start[i + 1] = start[i] + tile - ov[i]`. `overlap` must be + below `tile`. A frame's tiles are row-major over (row band, column band). +- `vtile_gather`: the tiles out of voxel rows `x [frames H W, n]` (`(t, yy, xx)` row-major, + `geom` = `(frames, H, W)`, its frames the parameter's). Tile `k` is rows + `[k period, (k + 1) period)` of `y`: its `frames tile tile` voxels `(t, ty, tx)` row-major from + `x`'s row `(t, start_y + ty, start_x + tx)`, then `reg`'s first `n_reg` rows in `y`'s dtype (a + decoder's register tokens), then zero rows to the period, which holds at least + `frames tile tile + n_reg` rows. `M` is `y`'s rows, `n_tiles period`. +- `vtile_stitch`: a decoded chunk's tiles into RGB bytes. `x [>= n_tiles period, 3 pt scale^2]`: + tile `k`'s row `k period + (lt tile + ty) tile + tx`, column + `c pt scale^2 + a scale^2 + b scale + d`, is colour `c` of pixel `(ty scale + b, tx scale + d)` + of clip frame `lt pt + a`. `geom` = `(frames, H, W, first, last)`: the chunk's latent geometry, + and whether it is its video's first and its last chunk (nonzero). Pixel `(Y, X)` belongs to the + tile `(i, j)` whose kept range holds it, `[start_i scale, start_{i+1} scale)` on each axis (the + last tile to its end), at `(ly, lx)` within it, `T(i, j, ly, lx)` that tile's decoded value. With + every product and sum rounded to `x`'s dtype (`rd`), `wb(p, e) = rd(p / e)` and + `wa(p, e) = rd(1 - wb(p, e))`, the spatial stitch blends with the tile above, then with the tile + to the left, both as decoded: + + V = rd(rd(T(i-1, j, ly + tile scale - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev))) + when i > 0 and ly < ev = ov_y[i-1] scale, else T(i, j, ly, lx) + S = rd(rd(T(i, j-1, ly, lx + tile scale - eh) wa(lx, eh)) + rd(V wb(lx, eh))) + when j > 0 and lx < eh = ov_x[j-1] scale, else V + + Output frame `k < keep` is clip frame `skip + k`, its first `blend` frames blended with the + previous chunk's tail unless the chunk is first, + `v = rd(rd(prev[k] wa(k, blend)) + rd(S wb(k, blend)))`; then `prev[k'] = S(2 skip + keep + k')` + for `k' < blend` (`prev` `[blend, H scale, W scale, 3]`), which a last chunk also writes as + frames `keep + k'`. A byte is `round_half_even(255 clamp(f32(f32(v std[c]) + mean[c]), 0, 1))` + (a NaN is 0). `y` is u8 `[frames_out, H scale, W scale, 3]`, `frames_out` `keep` or + `keep + blend`; `M` is its pixels. Refused: `blend` past `keep`, clip frames (`frames pt`) short + of `2 skip + keep + blend`, a `period` short of `frames tile tile`. MiniMax-H3: `tile` 16, + `overlap` 4, `scale` 16, `pt` 4, `skip` 3, `keep` 17, `blend` 5, `period` 1797, ImageNet's + `mean` and `std`. +- `grid_pos3`: a ViT decoder's rotary positions over consecutive tiles of `period` rows, the + tile's `T x H x W` tokens first, then the period's other rows (register tokens). Row `m` is + token `k = m % period`; for `k < T H W`, `(t, i, j) = (k / (H W), (k / W) % H, k % W)` and + `y[0][m] = f32(f32(scale) g(t, T))`, `y[1][m] = f32(f32(scale) g(i, H))`, + `y[2][m] = f32(f32(scale) g(j, W))`, `g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1)` (torch's + `2 * (arange(0.5, n) / n) - 1`); otherwise all three are 0. `y` is f32 `[3, >= M]`, + component-major, at its own row pitch: a `[3, M]` view of a wider plane, which `qk_norm_rope` + `axial` then reads as f32 positions. MiniMax-H3: `T` 7, `H` 16, `W` 16, `period` 1797, + `scale` `2 pi`. + +### Video sparse attention + +MiniMax-H3's step-distilled form (FastH3) was trained with FastVideo's video sparse attention: a +video query sees the dense rows and only the video tiles it scores highest, scored per head from +tile means, and a coarse branch adds attention over every tile's mean, gated per element. +`vsa_select` makes the selection and the coarse term, `attn_vsa` the attention over them. They +share their parameters; `attn_vsa` recomputes `k` from `sparsity`. + +| op | params | operands | +|---|---|---| +| `vsa_select` | `M`(range) `head_dim` `tile_t` `tile_h` `tile_w` `patch` `sparsity`:f64 `scale`:f64/opt | `q`, `k`, `v`?, `segs`, `geom` → `sel`, `coarse`? | +| `attn_vsa` | `M`(range) `head_dim` `tile_t` `tile_h` `tile_w` `patch` `sparsity`:f64 `scale`:f64/opt `qk`/opt `pv`/opt | `q`, `k`, `v`, `segs`, `geom`, `sel`, `coarse`?, `gate`? → `out`, `k_i8`?, `k_scale`?, `v_scale`? | + +**The tiles.** A pass's `R` rows (`M` is their band) are one packed sequence. `segs`, i32 +`[n_seg + 1]`, cuts it into segments: `segs[0] = 0`, non-decreasing, `segs[n_seg] = R`; every +segment but the last is dense (the text, the soundtrack), the last is the video grid of +`F x Hp x Wp` rows in `(t, h, w)` order, `w` fastest. `geom` is the request's geometry on the +device, i32 `[RAD_VGEOM_N]` (`abi/rad_runtime.h`): `F = geom[RAD_VGEOM_LAT_FRAMES]`, +`Hp = geom[RAD_VGEOM_LAT_H] / patch`, `Wp = geom[RAD_VGEOM_LAT_W] / patch`. With +`TT = tile_t tile_h tile_w`: + +- each dense segment, on its own, is cut into chunks of `TT` rows from its start, the last chunk + shorter, an empty segment none: the prefix tiles `0 .. P-1`, in segment order; +- the grid is cut into `ceil(F / tile_t) x ceil(Hp / tile_h) x ceil(Wp / tile_w)` boxes. Box + `(a, b, c)` holds `t` in `[a tile_t, min(F, (a + 1) tile_t))` and likewise `h` and `w`, edge boxes + smaller, and is tile `P + (a nb + b) nc + c` (`nb = ceil(Hp / tile_h)`, `nc = ceil(Wp / tile_w)`): + `V` video tiles, `N = P + V` in all; +- a tile's rows are taken in its `(t, h, w)` raster order (a prefix tile's in row order), which + fixes the order of every f32 sum over a tile. `size(i)` is tile `i`'s row count. + +`k = max(1, min(ceil((1 - sparsity) V), V))`, computed in f64 from the f64 `sparsity`, as the +trained schedule computes it: `(1 - 0.8) 660` is `131.99999999999997`, so MiniMax-H3's 660 video +tiles at 1344 x 768 keep 132, and `(1 - 0.7) 10` keeps 4. + +Both ops refuse with `RAD_E_SHAPE` a `segs` that does not start at 0, decreases, or covers no row +or more rows than the operands hold; a last segment of other than `F Hp Wp` rows; a box extent or +`patch` below 1; a `sparsity` outside `[0, 1)`; and an optional operand without its partner. `sel` +must be i32 (`RAD_E_DTYPE`). Rows past `segs[n_seg]` are neither read nor written. `q`, `k`, `v`, +`gate` and `out` are `[R, n_head head_dim]`, a column slice of a wider projection read at its own +row pitch, or `[R, n_head, head_dim]`; the head count is read off `q`. + +**`vsa_select`.** Per head `h` and tile `i`, the tile means and the scores, in f32: + + qp[h][i] = (sum over the rows r of tile i, in raster order, of q[r, h, :]) / size(i) + kp[h][i], and vp[h][i] (read for `coarse` alone), likewise from k and v + S[h][i][j] = (qp[h][i] . kp[h][j]) scale the dot a sum over d ascending, then the product + +For a video query tile `i >= P`, `sel[h][i][0 .. k)` is the `k` video tiles `j` (`P <= j < N`) of +largest `S[h][i][j]`, written in ascending tile order; equal scores go to the lower tile, and a NaN +ranks above every number (`torch.topk`'s ranking). The prefix query tiles' rows of `sel` and its +slots past `k` are not written. `sel` is `[n_head, tiles_cap >= N, k_cap >= k]`. With `coarse` +(and `v`: both or neither), for every tile `i`, prefix tiles too: + + e_j = exp(S[h][i][j] - max over all N tiles of S[h][i][:]) + p[h][i][j] = e_j / (sum over all N tiles, j ascending, of e_j) + coarse[h][i][:] = (sum over j ascending of p[h][i][j] vp[h][j][:]), rounded once to its dtype + +`coarse` is `[n_head, tiles_cap >= N, head_dim]`. At `sparsity` 0, `k = V` and every video tile is +selected. + +**`attn_vsa`.** A query row of tile `i` sees the rows of every tile when `i < P` (dense prefix +queries), else of the prefix tiles and of the tiles `sel[h][i][0 .. k)`. Each such row of `sel` must +hold `k` ascending video tiles, `RAD_E_INVAL` otherwise, checked before anything is written; `sel`'s +other entries are not read. Per head (`q`, `k` and `v` have the same heads), `o` is the softmax over +the visible keys of `(q . k) scale` times `v`, accumulated in f32, and + + out[r, h, :] = o without coarse and gate + out[r, h, :] = rd(rd(o) + coarse[h][i][:] gate[r, h, :]) with them, in f32 + +`rd` rounding to `out`'s dtype: FastVideo's inference epilogue, the sparse output in bf16, then +`out.addcmul_(coarse, gate)` in bf16 with f32 arithmetic. Two bf16 values multiply exactly in f32, +so that is one f32 add between the two roundings. `gate` comes with `coarse`, both or neither. At +`sparsity` 0 (with `vsa_select`'s selection) `attn_vsa` is `attn_dense` over the whole sequence. +libref takes the keys by ascending tile, each tile in raster order, in `attn_dense`'s two passes. +`qk` `"i8"` is `attn_prefix_self`'s int8 score form: `k_i8` `[M, n_head * head_dim]` and `k_scale` +`[M, n_head]` f32 are k as `quant_act_i8g` writes it at group `head_dim`, each query row is +quantised inside the op by the same rule, a score is `((dot * q_scale) * k_scale) * scale` in f32 +with `dot` the codes' exact integer sum, and `k` is not read. `pv` `"fp8"` is `attn_prefix_self`'s +fp8 P.V form (`v` E4M3 codes, `v_scale` `[n_head * head_dim]`), before the epilogue. + +MiniMax-H3: `tile_t`, `tile_h` and `tile_w` 4, `patch` 2, `sparsity` 0.8, `head_dim` 128, the +default `scale` `1 / sqrt(head_dim)`. ## Mixture of experts diff --git a/docs/TOOLS.md b/docs/TOOLS.md index c11c1551..15a10d6f 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -180,8 +180,9 @@ also matches a norm leaves the norm as it is. | `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform | | `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` | | `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale | +| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded | -Every quantiser except `ggml` and `cast` takes the grid options: +Every quantiser except `ggml`, `cast` and `import` takes the grid options: | option | | |---|---| @@ -781,6 +782,13 @@ reference with the exact wire and a bf16 KV cache. agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be compared position by position. +A runtime LoRA adapter (GUIDE.md §4.9.1) is scored the same way: `--lora NAME=DIR --kld-lora NAME` +runs every document through the adapter, against a reference recorded from the merged checkpoint +(or from PEFT itself). `--kld-lora-sources PREFIX` runs only the documents whose `source` starts +with `PREFIX` through it and the rest as the base, in the same steps. The steps are those of the +all-adapter and all-base runs with the same flags, so each document's rows should be byte for byte +theirs: that is how a mixed batch is checked. + --- ## The shell harnesses diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index d8321df2..0f3b8d22 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -50,6 +50,9 @@ set(AVX_KERNEL_SRC avx_misc.cpp avx_gen.cpp avx_gen_attn.cpp + avx_video.cpp + avx_vsa.cpp + avx_audio.cpp ) # The flag sets, written out because each states which instructions the object may contain. diff --git a/libavx/README.md b/libavx/README.md index b4247bec..24816d51 100644 --- a/libavx/README.md +++ b/libavx/README.md @@ -3,7 +3,7 @@ The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time by CPU feature. libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host -implementation, and it is a slow reference. libavx implements all 123 of libref's ops with the +implementation, and it is a slow reference. libavx implements all 150 of libref's ops with the same schemas and the same answers to a tolerance, the image generator's included (below). cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH= && cmake --build build-avx -j4 @@ -64,7 +64,7 @@ four levels and the engine never reaches it. Every op `libref` implements, `libavx` implements, so the selector resolves no op of a CPU-only deployment to libref: Flash-Next's QSA indexer, the DFlash2 drafters' convolution and the image -generator included. `rad-avx-check` fails on any missing op, and reports a row that returns +and audio generators included. `rad-avx-check` fails on any missing op, and reports a row that returns `RAD_E_UNSUPPORTED` separately from one that is absent: a declining row is worse than none, because the selector resolves to it and the step fails at issue rather than at declare. @@ -76,6 +76,7 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the | `attn_local_rel` | a right context; head_dim or left context + 1 over 2048 | the same | | `rope`, `qk_norm_rope`, `qsa_block_key` | an unknown `mode`; for `rope`, an unknown `ladder` | the same | | `rope` | YaRN with `axial` or a position scale | the same | +| `rope` | Llama 3 scaling beside YaRN, with `axial`, or over multi-component positions | the same | | `rope` | a rotary half-width over 1024 | the same | | `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) | | `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same | @@ -91,8 +92,10 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the Everything but the last two rows refuses exactly where libref does, so the selector never resolves a geometry to libavx that libref would have served. The per-entry image ops -(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) check every entry before writing any, -where libref writes the entries before a bad one; they return libref's code, and refuse (with +(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) and the audio generator's +(`frame_mix_store`, `end_status`, `frame_store`, `win_input`, `win_prep`, `win_finish`, and +`cfg_topk_sample` with a lane history or a suppressed id range) check every entry before writing +any, where libref writes the entries before a bad one; they return libref's code, and refuse (with `RAD_E_SHAPE`) the entries libref would read or write past an operand for. `moe_gemm_q` and `moe_gemm_q_mod4` carry layout hooks for Qwen3.8-Flash-Next's codebook experts @@ -566,6 +569,76 @@ activation. With a bf16-pair path for block fp8 the fp8 container would cost abo one does. The decoder takes about 1.3 s at 512 x 512 and 5 s at 1024 x 1024, the condition (the 8B text encoder and the DiT over about 100 prompt tokens) about 0.6 s in bf16 and 8 s in fp8. +## Audio generation + +MiniMax-Music3 (`arch/minimaxmusic3`) adds 16 ops (`avx_audio.cpp`), and a speech model's frame +loop and causal codec one more (`frame_store`) and these forms: a causal `conv1d`, the causal +`conv_t1d` (`pad` 0, odd strides, a kernel of one stride), SnakeBeta (`snake` with `beta`, both as +logarithms with `log`), and a sampler that suppresses reserved ids, takes each lane's guidance and +penalises a lane's earlier picks (`hist`, cleared at frame 0). The sampler (`cfg_topk_sample`), +the window noise and its overlap binding (`win_prep`), the frame embeddings (`rvq_embed` in both +roundings, `frame_mix_store`, `fourier_embed`), the code history (`frame_store`), the window copies +and the index helpers are libref's bit for bit, held to zero error by the hand-built cases: a seed +gives the same codes, the same noise and the same piece on both host libraries. With a history the +sampler takes its lanes in order, as libref does, since two entries may share a lane's row. +`cfg_topk_sample` and `frame_mix_store` keep libref's two roundings where they multiply and add +(`keep`). The vocoder's three ops reduce in other orders and are held to the tolerance table: + +- **`conv1d`** is GEMMs over bands of patch rows, as `conv2d_nhwc`: the weight re-laid once a launch + as `[cout][k][cin]`, an output row's patch its k input rows' channel runs (zeros outside its own + sequence), each band one `gemm_nt_into` into f32 rows, then the residual and the tanh or the + clamp, rounded once. A 1-wide kernel over a dense input reads x in place. +- **`conv_t1d`** is one GEMM per phase: output row q s + r - pad reads input rows q, q - 1, .. + against taps r, r + s, .. below k (phases of one kernel may differ by a tap: kernel 9 at stride 5 + takes two taps in phases 0 to 3 and one in phase 4), so a phase's rows are a GEMM over + `[x[q] | x[q - 1] | ..]` patch rows and the weight re-laid per phase as `[cout][taps][cin]`. +- **`snake`** squares a sine reduced to [-pi/2, pi/2] (the sign does not matter once squared) and + evaluated as an odd Taylor polynomial through r^13; a row with an argument past 8192, where the + three-part pi stops being exact, is computed again with the libm sine. SnakeBeta's multiplier + 1 / (beta + 1e-9) is taken once a channel, as libref takes it. +- **`snake_aa`** (BigVGAN's alias-free SnakeBeta, MiniMax-H3's vocoder) works on bands of 64 output + rows, channels innermost: a band computes the upsampled rows its filter reads into scratch (a + row a function of its index, so neighbouring bands agree where they overlap), with `snake`'s + sine, and filters them down; both sums run in libref's order. + +At the vocoder's third stage (384 channels), bf16, this machine (`rad-avx-bench --op `): + +| op | geometry | libref, 1 thread | avx512, 1 thread | avx512, 16 threads | +|---|---|---|---|---| +| conv1d | 7 taps, dilation 3, 384 -> 384, 8192 rows | 10.9 s | 56.8 ms, 298 GFLOP/s | 6.5 ms, 2.6 TFLOP/s | +| conv1d | 1 x 1, 384 -> 384, 8192 rows | 1.57 s | 9.7 ms, 250 GFLOP/s | 1.4 ms, 1.7 TFLOP/s | +| conv_t1d | stride 4, 768 -> 384, 2048 -> 8192 rows | 6.33 s | 34.7 ms, 279 GFLOP/s | 3.8 ms, 2.5 TFLOP/s | +| snake | 8192 x 384 | 20.3 ms | 1.2 ms, 10.5 GB/s | 0.32 ms, 39 GB/s | + +A window's vocode (two streams, 689 latents to 705536 samples each, four upsampling stages of +three residual units) is about 2.2 TFLOP, of the order of a second on 16 cores at these rates; the +96-channel last stage was not timed. On one thread the convolutions reach 36-43% of the bf16 +dot-product ceiling, against the image decoder's 70-88%; they have not been tuned. + +## Video generation + +MiniMax-H3 adds eight ops (`avx_gen.cpp`, `avx_video.cpp`, and `snake_aa` in `avx_audio.cpp`) +and these forms: `qk_norm_rope` +`axial` over f32 positions (its positions a view of a wider plane), with absent gains and as the +norm alone; `rope` over f32 positions; `gate_add` without tanh; `add` with `div`; `chan_affine` in +f32; `conv_t1d` at any kernel of a stride or more; `conv1d` with its clamp; and `snake_aa` above. +The sampler step (`flow_x0_step`), the patch unfold, the decoder's tiles (`vtile_gather`), their +stitch into bytes (`vtile_stitch`) and their positions (`grid_pos3`) are libref's bit for bit, held +to zero error by the hand-built cases: a seed gives the same video bytes on both host libraries. +The stitch blends a line of a tile at a time, each product and sum a pass of the line through x's +dtype; the frames that refill the overlap run after the frames that read it, so no row is read +after another task rewrote it. `rms_mod` and its quantised form reduce in another order and are +held to the tolerance table. + +Its step-distilled form's video sparse attention adds two (`avx_vsa.cpp`). `vsa_select`'s +selection is libref's bit for bit, since one tile more or less changes what a whole query tile +sees: the tile means sum rows in libref's order with the vector lanes across the head, and each +score's dot runs over the head in libref's order with the vector lanes across tiles and every +product rounded before its add. Its coarse branch is held to the tolerance. `attn_vsa` is one task +per (head, query tile), 64 keys of a visible tile packed at a time for broadcast products and an +online softmax, as `attn_prefix_self`'s f32 form; a prefix query tile sees every tile, so the tasks +are scheduled dynamically. + ## Design choices Each choice below was measured on the platform above. The variants that did not pay are recorded @@ -628,6 +701,9 @@ and spills a 16-register file, costing more than the FMA saves, so the AVX and A avx_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp the kernels; compiled 4x avx_gen.cpp the image generator's norms, sampler, lanes and decoder ops; compiled 4x avx_gen_attn.cpp attn_prefix_self, the generator's attention; compiled 4x + avx_video.cpp the video decoder's patch unfold, tiles, stitch and positions; compiled 4x + avx_vsa.cpp video sparse attention: the tile selection and the attention; compiled 4x + avx_audio.cpp the audio generator's vocoder, sampler, embeddings and window ops; compiled 4x avx_harness.h plugin loading, row selection, the operand draw, guarded buffers, the geometry table -- shared by both tools avx_cases.cpp the geometries; one table so the check and the bench cannot disagree diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 66aa69a6..6ac77d3b 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -532,7 +532,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* const RadTensor* v, const RadTensor* cu, const RadTensor* o, int64_t D, int64_t gqa, int64_t kv_heads, int causal, int64_t window, - int64_t block, int64_t cdiv, float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds, + int64_t wright, int64_t block, int64_t cdiv, + float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds, int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs, int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs, int64_t o_ds) { @@ -589,7 +590,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* int64_t jbeg = 0, jend = causal ? q1 : len; if (window > 0) { jbeg = std::max(0, q0 - window + 1); - if (!causal) jend = std::min(len, q1 - 1 + window); + if (!causal) jend = std::min(len, q1 - 1 + wright); } if (block > 0) { jbeg = std::max(jbeg, q0 / block * block); @@ -617,7 +618,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* for (int64_t j = 0; j < kt; ++j) { const int64_t d = i - (j0 + j); bool ok = !causal || d >= 0; - if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window)); + if (window > 0) + ok = ok && (causal ? d < window : (d < window && -d < wright)); if (block > 0) ok = ok && i / block == (j0 + j) / block; if (!ok) S[r * KT + j] = -INFINITY; } @@ -729,12 +731,16 @@ AVX_KERNEL(attn_dense) { const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); const int64_t gqa = p_int(a, "gqa", 1); const int causal = (int)p_int(a, "causal", 0); - /* As libref: causal, i - j < window; non-causal, |i - j| < window; 0 means none. A `block` - * cuts a segment into blocks attending within themselves; `cu_div` reads cu_seqlens in units - * that many rows apart. */ - const int64_t window = p_int(a, "window", 0); + /* As libref: causal, i - j < window; non-causal, |i - j| < window, or i - j < window and + * j - i < window_right when that is given; 0 means none. A `block` cuts a segment into blocks + * attending within themselves; `cu_div` reads cu_seqlens in units that many rows apart. */ + const int64_t window = p_int(a, "window", 0), wright_p = p_int(a, "window_right", 0); const int64_t block = p_int(a, "block", 0), cdiv = p_int(a, "cu_div", 1); - if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE; + if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0 || wright_p < 0 || + (wright_p > 0 && (causal || window == 0))) + return RAD_E_SHAPE; + /* The right side of a non-causal window. */ + const int64_t wright = wright_p > 0 ? wright_p : window; if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED; /* A rank-2 operand is [tokens, heads * head_dim]: its head count is width / head_dim. */ @@ -768,8 +774,8 @@ AVX_KERNEL(attn_dense) { const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); #if AVX_LEVEL == 3 - if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, block, cdiv, - scale, q_rs, + if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, wright, block, + cdiv, scale, q_rs, q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds)) return RAD_OK; #endif @@ -792,7 +798,7 @@ AVX_KERNEL(attn_dense) { int64_t jbeg = b0, jend = causal ? (i + 1) : b1; if (window > 0) { jbeg = std::max(b0, i - window + 1); - if (!causal) jend = std::min(b1, i + window); + if (!causal) jend = std::min(b1, i + wright); } if (block > 0) { const int64_t blk = b0 + (i - b0) / block * block; @@ -1067,6 +1073,14 @@ AVX_KERNEL(kv_store) { * frequencies, and for `axial` a frequency ladder per section. Same rule as libref's rope_freqs. */ enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 }; +/* A position as libref's rope_pos reads it, divided by the position scale: a float operand's own + * value (a fractional coordinate), an integer operand's integer. */ +static inline float rope_pos(const RadTensor* pos, int64_t off, float div) { + const uint32_t dt = pos->dtype; + const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16; + return (flt ? ldt(pos, off) : (float)ldi(pos, off)) / div; +} + /* cos in [0, half), sin in [half, rot): the layout `rope_table` writes. * * Not sincosf: it gives the same bits but glibc's joint wrapper is slower than two separate @@ -1218,6 +1232,14 @@ AVX_KERNEL(rope) { if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED; for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i); } + /* Llama 3's frequency scaling, refused beside YaRN or a multi-component mode as libref + * refuses it. */ + const RadLlama3 l3 = rad_llama3_args(a); + if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL; + if (l3.factor != 0.0f) { + if (mode == ROPE_AXIAL || multi) return RAD_E_UNSUPPORTED; + for (int64_t i = 0; i < half; ++i) invf[i] = l3.frequency(invf[i]); + } for (int64_t i = nfreq; i < half; ++i) invf[i] = 0.0f; const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; @@ -1229,10 +1251,10 @@ AVX_KERNEL(rope) { float* buf = scratch_f32_b((size_t)rot); if (multi) { float pc[8]; - for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div; + for (int64_t c = 0; c < n_comp; ++c) pc[c] = rope_pos(pos, c * pcs + m * pms, div); angles_multi(cs, invf, comp, half, pc); } else { - angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div); + angles(cs, invf, half, rope_pos(pos, offlin(pos, m), div)); } if (yarn.factor != 0.0f) for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude; @@ -1244,14 +1266,16 @@ AVX_KERNEL(rope) { } /* ------------------------------------------------------------------ qk_norm_rope */ -/* Per-head RMS norm with its own gain, then RoPE. +/* Per-head RMS norm with its own gain, then RoPE. An absent gain is a unit gain without `wadd`, + * and `rotary_dim` 0 is the norm alone, `positions` then optional (libref). * * The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does * (and libr4d's r4d_qk_norm_rope_gate matches): it is stored with out_row and re-read by the * rotation rather than kept in f32. */ AVX_KERNEL(qk_norm_rope) { - if (!rad_args_have(a, 4)) return RAD_E_INVAL; - const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3]; + if (!a || a->n_t < 4 || !rad_arg_in(a, 0)) return RAD_E_INVAL; + const RadTensor *qkv = &a->t[0], *pos = rad_arg_in(a, 1); + const RadTensor *qw = rad_arg_in(a, 2), *kw = rad_arg_in(a, 3); const int64_t head_dim = p_int(a, "head_dim", 0); const int64_t n_head = p_int(a, "n_head", 0); @@ -1263,22 +1287,26 @@ AVX_KERNEL(qk_norm_rope) { const int v_norm = (int)p_int(a, "v_norm", 0); /* libref's modes: `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j, * start + 2j + 1), Qwen-Image's 3-axis rotary; `imrope` is `rope`'s interleaved M-RoPE over - * NeoX pairs (Qwen3-VL's text attention). */ - static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" }; - const int mode = p_enum(a, "mode", kModes, 5, ROPE_NEOX); + * NeoX pairs (Qwen3-VL's text attention); `axial` is `rope`'s axial form, its section ladders + * over rank-1 positions too. */ + static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" }; + const int mode = p_enum(a, "mode", kModes, 6, ROPE_NEOX); if (mode < 0) return RAD_E_UNSUPPORTED; const bool blocks = mode == 2 || mode == 3; const bool adjacent = mode == 3; const bool im = mode == 4; + const bool axial = mode == 5; const int64_t rot = p_int(a, "rotary_dim", head_dim); - if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; - if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE; + if (head_dim <= 0 || n_head <= 0 || rot < 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; + if ((qw && numel(qw) < head_dim) || (kw && numel(kw) < head_dim)) return RAD_E_SHAPE; + const bool turn = rot > 0; + if (turn && !pos) return RAD_E_INVAL; /* `blocks` mode (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired * (start + j, start + sec[c] + j), rotated by position component comps[c]. */ int64_t sec[8] = {}, comp[8] = {}; int n_sec = 0; - if (im) { + if (turn && (im || axial)) { for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) { char* end = nullptr; const long long x = std::strtoll(v, &end, 10); @@ -1287,9 +1315,9 @@ AVX_KERNEL(qk_norm_rope) { sec[n_sec++] = x; v = end; } - if (n_sec < 3) return RAD_E_SHAPE; + if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE; } - if (blocks) { + if (turn && blocks) { for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) { char* end = nullptr; const long long x = std::strtoll(v, &end, 10); @@ -1314,16 +1342,20 @@ AVX_KERNEL(qk_norm_rope) { if (k != n_sec) return RAD_E_SHAPE; } } - const bool multi = pos->rank >= 2; + const bool multi = pos && pos->rank >= 2; const int64_t n_comp = multi ? pos->shape[0] : 1; - if (multi && !blocks && !im) return RAD_E_SHAPE; - if (multi && im && n_comp < 3) return RAD_E_SHAPE; - for (int c = 0; blocks && c < n_sec; ++c) - if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE; + const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; + if (turn) { + if (multi && !blocks && !im && !axial) return RAD_E_SHAPE; + if (multi && im && n_comp < 3) return RAD_E_SHAPE; + if (multi && axial && n_comp < n_sec) return RAD_E_SHAPE; + for (int c = 0; blocks && c < n_sec; ++c) + if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE; + } + /* The component axis at the operand's own pitch: a [C, M] view of a wider plane. */ const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; - const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; - const int64_t M = multi ? pos->shape[1] : numel(pos); + const int64_t M = !pos ? rows_of(qkv, stride_row) : multi ? pos->shape[1] : numel(pos); if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row; const int64_t ds = laststride(qkv); @@ -1337,9 +1369,19 @@ AVX_KERNEL(qk_norm_rope) { float* gq = tab + 2 * half; float* gk = tab + 2 * half + head_dim; /* imrope's component per frequency, as libref's rope_freqs: 1 where i % 3 == 1 and - * i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. */ - const bool by_comp = blocks || (im && multi); - if (!blocks) { + * i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. axial's sections are + * contiguous, each its own ladder theta^(-2j / (2 sec[c])) and filling rot / 2 exactly. */ + const bool by_comp = blocks || (im && multi) || axial; + if (axial) { + int64_t i = 0; + for (int c = 0; c < n_sec; ++c) + for (int64_t j = 0; j < sec[c]; ++j, ++i) { + if (i >= half) return RAD_E_SHAPE; + invf[i] = 1.0f / sc_pow(theta, (float)(2 * j) / (float)(2 * sec[c])); + pcomp[i] = (float)c; + } + if (i != half) return RAD_E_SHAPE; + } else if (!blocks) { for (int64_t i = 0; i < half; ++i) { invf[i] = 1.0f / sc_pow(theta, (float)(2 * i) / (float)rot); pcomp[i] = !im ? 0.0f @@ -1355,19 +1397,19 @@ AVX_KERNEL(qk_norm_rope) { } } for (int64_t d = 0; d < head_dim; ++d) { - gq[d] = ldt(qw, d * laststride(qw)) + wadd; - gk[d] = ldt(kw, d * laststride(kw)) + wadd; + gq[d] = qw ? ldt(qw, d * laststride(qw)) + wadd : 1.0f; + gk[d] = kw ? ldt(kw, d * laststride(kw)) + wadd : 1.0f; } AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { const float div = rscale != 0.0f ? rscale : 1.0f; - float pc[8]; - if (multi) + float pc[8] = {}; + if (turn && multi) for (int64_t c = 0; c < n_comp && c < 8; ++c) - pc[c] = (float)ldi(pos, c * pcs + m * pms) / div; - else - pc[0] = (float)ldi(pos, offlin(pos, m)) / div; + pc[c] = rope_pos(pos, c * pcs + m * pms, div); + else if (turn) + for (float& v : pc) v = rope_pos(pos, offlin(pos, m), div); const int64_t row = m * rs; /* cos and sin, then for adjacent pairs the same per rotated channel: cc[2i] = cc[2i+1] * = cos_i, ss[2i] = -sin_i, ss[2i+1] = sin_i, so channel d becomes @@ -1404,8 +1446,9 @@ AVX_KERNEL(qk_norm_rope) { /* Store through the operand's dtype; the rotation re-reads it (see above). */ if (ds == 1) out_row(qkv, base, head_dim, rbuf); else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]); + if (!turn) continue; if (!blocks) { - rope_head(qkv, base, ds, rot, im ? (int)ROPE_NEOX : mode, cs, half, rbuf); + rope_head(qkv, base, ds, rot, im || axial ? (int)ROPE_NEOX : mode, cs, half, rbuf); continue; } if (pairs_vec) { diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp new file mode 100644 index 00000000..a25e7582 --- /dev/null +++ b/libavx/avx_audio.cpp @@ -0,0 +1,1108 @@ +/* avx_audio.cpp -- the audio generator's ops (docs/OPS.md, "Audio generation"): the vocoder's 1-D + * convolutions and snake activation, the guided frame sampler and the frame embeddings, the window + * states of the latent denoiser, and the index helpers that feed them. + * + * Bit-exact with libref (libref/ref_audio.cpp) for all but the three vocoder ops: the sampler (one + * pick decides every later frame), the window noise and its blends (a seed gives the same piece on + * every plugin), the embeddings, the copies and the index helpers. Where libref multiplies and then + * adds in two roundings, `keep` stops the compiler from fusing the pair (this plugin is built with + * -ffp-contract=fast, libref without contraction). conv1d and conv_t1d are GEMMs over bands of + * patch rows and snake takes a polynomial sine; those three are held to the tolerance table. + * + * The per-entry ops (frame_mix_store, end_status, frame_store, win_input, win_prep, win_finish, and + * cfg_topk_sample with a history) check every entry before writing any, where libref writes the + * entries before a bad one; they return libref's code, and refuse with RAD_E_SHAPE an entry libref + * would read or write past an operand for. + */ +#include "avx_vec.h" +#include "avx_common.h" +#include "rad_philox.h" + +#include +#include +#include + +using namespace avx; + +namespace avx { +inline namespace AVX_SUFFIX { +/* gemm_nt's product over operands assembled by a composite kernel (avx_gemm.cpp). */ +int gemm_nt_into(const RadTensor* A, const RadTensor* B, const RadTensor* bias, const RadTensor* Y, + int64_t M, int64_t N, int64_t K); +} /* inline namespace AVX_SUFFIX */ +} /* namespace avx */ + +namespace { + +/* A window entry's flags (RadAudioGenBatch, RAD_AGEN_F_*), restated as libref restates them, since + * a kernel library compiles against rad_abi.h only. */ +enum { kFirst = 1, kLast = 8, kJoin = 16 }; + +/* Element `i` of an index operand in logical order (libref's ldi), and entry `i` of a cu_seqlens + * operand. */ +inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); } +inline int64_t cu_at(const RadTensor* cu, int64_t i) { return at(cu, i); } +/* The sequence that owns row `r` (libref's linear scan). */ +inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) { + int64_t s = 0; + while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s; + return s; +} + +inline float rbf(float v) { return narrow1(RAD_BF16, v); } + +/* v[0, n) rounded through dtype `dt` in place, as a store and reload rounds it. `tmp` holds n + * floats. */ +inline void narrow_row(uint32_t dt, float* v, int64_t n, float* tmp) { + if (dt == RAD_F32) return; + row_from_f32(dt, v, tmp, n); + row_to_f32(dt, tmp, v, n); +} + +/* A value the compiler may not fuse into the next add. */ +#if AVX_LEVEL == 0 +inline vf keep(vf x) { __asm__("" : "+x"(x)); return x; } +#elif AVX_LEVEL == 3 +inline vf keep(vf x) { __asm__("" : "+v"(x)); return x; } +inline float keep(float x) { __asm__("" : "+v"(x)); return x; } +#else +inline vf keep(vf x) { __asm__("" : "+x"(x)); return x; } +inline float keep(float x) { __asm__("" : "+x"(x)); return x; } +#endif + +/* Round to the nearest integer, ties to even, lane by lane. */ +#if AVX_LEVEL == 0 +inline vf vf_round(vf x) { return std::nearbyint(x); } +#elif AVX_LEVEL == 3 +inline vf vf_round(vf x) { + return _mm512_roundscale_ps(x, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +} +#else +inline vf vf_round(vf x) { return _mm256_round_ps(x, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } +#endif + +/* n elements of row `base` of `t` as f32 into dst. */ +inline void load_row(const RadTensor* t, int64_t base, int64_t n, float* dst) { + const float* s = in_row(t, base, n, dst); + if (s != dst) std::memcpy(dst, s, (size_t)n * sizeof(float)); +} + +/* A row copied between operands, converted through f32 as libref's element loop is. Whole-byte + * float rows of one dtype are copied as bytes, which is the same thing for every non-NaN value. */ +inline void copy_row(const RadTensor* src, int64_t sb, const RadTensor* dst, int64_t db, int64_t n, + float* scr) { + const uint32_t dt = src->dtype; + const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 || + dt == RAD_F8E5M2; + if (flt && dt == dst->dtype && laststride(src) == 1 && laststride(dst) == 1) { + const size_t w = (size_t)(rad_dtype_bits(dt) / 8); + std::memcpy((char*)dst->data + (size_t)db * w, (const char*)src->data + (size_t)sb * w, + (size_t)n * w); + return; + } + out_row(dst, db, n, in_row(src, sb, n, scr)); +} + +inline uint64_t seed_of(const RadTensor* seed, int64_t e) { + return (uint64_t)(uint32_t)at(seed, 2 * e) | ((uint64_t)(uint32_t)at(seed, 2 * e + 1) << 32); +} + +/* Elements [e0, e0 + cnt) of the normal stream (seed, stream) into out (abi/rad_philox.h): the same + * arithmetic as rad_philox_normal_s, with one Philox block and one log per element pair instead of + * one each per element. */ +void philox_normals_s(uint64_t seed, uint64_t stream, uint64_t e0, int64_t cnt, float* out) { + uint64_t e = e0; + int64_t i = 0; + while (i < cnt) { + const uint64_t g = e >> 2; + uint32_t c[4] = { (uint32_t)g, (uint32_t)(g >> 32), (uint32_t)stream, + (uint32_t)(stream >> 32) }; + rad_philox4x32_10(c, (uint32_t)seed, (uint32_t)(seed >> 32)); + for (int pair = (int)((e & 3u) >> 1); pair < 2 && i < cnt; ++pair) { + const uint32_t wa = c[pair * 2], wb = c[pair * 2 + 1]; + const float ua = ((float)(wa >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float ub = ((float)(wb >> 8) + 0.5f) * (1.0f / 16777216.0f); + const float r = sqrtf(-2.0f * logf(ua)); + const float t = 6.28318530717958647692f * ub; + if ((e & 1u) == 0) { out[i++] = r * cosf(t); ++e; } + if (i < cnt) { out[i++] = r * sinf(t); ++e; } + } + } +} + +/* Patch rows a GEMM band holds: at least 8 Mi elements and eight times the weight, so the GEMM's + * per-call weight pack is amortised, at most 32 Mi (64 MiB of bf16 the buffer keeps). */ +inline int64_t band_rows(int64_t KK, int64_t cout, int64_t rows) { + const int64_t want = std::min((int64_t)1 << 25, + std::max((int64_t)1 << 23, 8 * cout * KK)); + return std::max(1, std::min(rows, want / std::max(1, KK))); +} + +/* A dense rank-2 view of `rows` x `cols` elements of dtype `dt` at `data`. */ +inline RadTensor mat_view(void* data, uint32_t dt, int64_t rows, int64_t cols) { + RadTensor t{}; + t.data = data; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; t.shape[1] = cols; + t.stride[0] = cols; t.stride[1] = 1; + return t; +} + +/* The weight a GEMM reads, re-laid from PyTorch's flat order: element `src(co, j)` of w goes to + * row co, column j of a [cout, KK] matrix, kept bf16 when w is bf16 (exact copies) and f32 + * otherwise. */ +template +void relay_weight(const RadTensor* w, int64_t cout, int64_t KK, std::vector& buf, + RadTensor* out, Src src) { + const bool b16 = w->dtype == RAD_BF16; + const size_t el = b16 ? 2 : 4; + buf.resize((size_t)(cout * KK) * el + 64); + uint8_t* wp = buf.data(); + AVX_PARALLEL_FOR_IF(cout * KK >= AVX_PAR_MIN) + for (int64_t co = 0; co < cout; ++co) + for (int64_t j = 0; j < KK; ++j) { + const int64_t s = src(co, j); + if (b16) ((uint16_t*)wp)[co * KK + j] = ((const uint16_t*)w->data)[s]; + else ((float*)wp)[co * KK + j] = ld_elem(w->data, w->dtype, s); + } + *out = mat_view(wp, b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32, cout, KK); +} + +/* `cin` channels of input row `ir` into a patch slot of dtype bf16 (x bf16 and dense, copied) or + * f32; zeros when `valid` is false. */ +inline void patch_slot(const RadTensor* x, int64_t ir, int64_t cin, bool valid, bool b16, char* d) { + if (!valid) { + std::memset(d, 0, (size_t)cin * (b16 ? 2 : 4)); + return; + } + const int64_t base = rowoff(x, ir, cin); + if (b16) std::memcpy(d, (const uint16_t*)x->data + base, (size_t)cin * 2); + else load_row(x, base, cin, (float*)d); +} + +/* sin(v)^2 by reduction to [-pi/2, pi/2] (the sign of the reduced sine does not matter once it is + * squared) and an odd Taylor polynomial through r^13, whose truncation at pi/2 is 7e-10. The + * three-part pi keeps k * P1 exact while |k| < 2^16; callers send |v| above kSinBig to the libm + * sine instead. */ +constexpr float kSinBig = 8192.0f; +inline vf sin_sq(vf v) { + const vf k = vf_round(vf_mul(v, vf_set1(0.318309886183790671538f))); + vf r = vf_sub(v, vf_mul(k, vf_set1(3.140625f))); + r = vf_sub(r, vf_mul(k, vf_set1(9.67502593994140625e-4f))); + r = vf_sub(r, vf_mul(k, vf_set1(1.509957990978376432e-7f))); + const vf r2 = vf_mul(r, r); + vf p = vf_set1(1.6059043836821614599e-10f); + p = vf_fma(p, r2, vf_set1(-2.5052108385441718775e-8f)); + p = vf_fma(p, r2, vf_set1(2.7557319223985890653e-6f)); + p = vf_fma(p, r2, vf_set1(-1.9841269841269841270e-4f)); + p = vf_fma(p, r2, vf_set1(8.3333333333333333333e-3f)); + p = vf_fma(p, r2, vf_set1(-1.6666666666666666667e-1f)); + const vf s = vf_fma(vf_mul(r, r2), p, r); + return vf_mul(s, s); +} + +/* sin_sq for one element, the same steps. */ +inline float sin_sq1(float v) { + const float k = std::nearbyint(v * 0.318309886183790671538f); + float r = v - k * 3.140625f; + r = r - k * 9.67502593994140625e-4f; + r = r - k * 1.509957990978376432e-7f; + const float r2 = r * r; + float p = 1.6059043836821614599e-10f; + p = p * r2 + -2.5052108385441718775e-8f; + p = p * r2 + 2.7557319223985890653e-6f; + p = p * r2 + -1.9841269841269841270e-4f; + p = p * r2 + 8.3333333333333333333e-3f; + p = p * r2 + -1.6666666666666666667e-1f; + const float sn = r * r2 * p + r; + return sn * sn; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ conv1d */ +/* A 1-D convolution over sequences, channels innermost, as GEMMs over bands of patch rows. The + * weight [cout, cin, k] is re-laid once a launch as [cout][k][cin], so an output row's patch is its + * k input rows' channel runs back to back, zeros outside its own sequence (padded on both sides, + * or with `causal` on the left only). A band's patches are one gemm_nt_into call into f32 rows (the + * bias added there); `res` and the tanh or the clamp to [-1, 1] are applied to the f32 rows, which + * are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. */ +AVX_KERNEL(conv1d) { + if (!rad_args_have(a, 3) || a->n_t < 5) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *cu = &a->t[2]; + const RadTensor *res = rad_arg_in(a, 3), *Y = &a->t[4], *B = rad_arg_in(a, 5); + if (!Y->data) return RAD_E_INVAL; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0); + const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0); + const char* act = p_str(a, "act", "none"); + const bool tanh_out = act && !std::strcmp(act, "tanh"); + const bool clamp_out = act && !std::strcmp(act, "clamp"); + if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL; + if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || + causal < 0 || causal > 1) + return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1) return RAD_E_SHAPE; + if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE; + if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE; + const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2, KK = k * cin; + static thread_local std::vector wbuf, pbuf; + static thread_local std::vector ybuf; + + RadTensor wt; + if (k == 1 && (W->dtype == RAD_BF16 || W->dtype == RAD_F32)) + wt = mat_view(W->data, W->dtype, cout, KK); + else + relay_weight(W, cout, KK, wbuf, &wt, [cin, k](int64_t co, int64_t j) { + return (co * cin + j % cin) * k + j / cin; + }); + + const bool b16 = X->dtype == RAD_BF16 && laststride(X) == 1; + const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + const size_t ael = b16 ? 2 : 4; + /* A 1-wide kernel's patch row is x's own row. */ + const bool direct = k == 1 && X->rank == 2 && X->shape[1] == cin && X->stride[1] == 1 && + (X->dtype == RAD_BF16 || X->dtype == RAD_F32); + const int64_t band = band_rows(KK, cout, r1 - r0); + if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64); + ybuf.resize((size_t)(band * cout) + 16); + char* pp = (char*)pbuf.data(); + float* yp = ybuf.data(); + for (int64_t b0 = r0; b0 < r1; b0 += band) { + const int64_t nb = std::min(band, r1 - b0); + RadTensor pt; + if (direct) { + pt = mat_view((char*)X->data + (size_t)(b0 * X->stride[0]) * rad_dtype_bits(X->dtype) / 8, + X->dtype, nb, KK); + pt.stride[0] = X->stride[0]; + } else { + pt = mat_view(pp, adt, nb, KK); + AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN) + for (int64_t p = 0; p < nb; ++p) { + const int64_t r = b0 + p, e = seq_of(cu, n_seq, r); + const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1); + for (int64_t t = 0; t < k; ++t) { + const int64_t ir = r + t * dil - pad; + patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16, + pp + (size_t)(p * KK + t * cin) * ael); + } + } + } + const RadTensor yt = mat_view(yp, RAD_F32, nb, cout); + const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK); + if (st < 0) return st; + AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN) + for (int64_t p = 0; p < nb; ++p) { + float* row = yp + p * cout; + if (res) { + const float* rr = in_row(res, rowoff(res, b0 + p, cout), cout, + scratch_f32((size_t)cout + 16)); + for (int64_t c = 0; c < cout; ++c) row[c] += rr[c]; + } + if (tanh_out) + for (int64_t c = 0; c < cout; ++c) row[c] = sc_tanh(row[c]); + /* A NaN stays NaN, as libref's comparisons leave it. */ + if (clamp_out) + for (int64_t c = 0; c < cout; ++c) + row[c] = row[c] < -1.0f ? -1.0f : (row[c] > 1.0f ? 1.0f : row[c]); + out_row(Y, rowoff(Y, b0 + p, cout), cout, row); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv_t1d */ +/* A transposed 1-D convolution of kernel k >= stride as `stride` GEMMs, one a phase. Output row lo + * of a sequence is q s + r - pad for phase r (pad (k - stride) / 2 by default, 0 the causal form) + * and reads input rows q - t against taps r + t stride for each t with r + t stride < k, so a + * phase's rows are one GEMM over patch rows [x[q] | x[q - 1] | ..] (zeros past the sequence) and + * the weight [cin, cout, k] re-laid per phase as [cout][taps][cin], the phases back to back. Each + * phase is computed into f32 rows (the bias added there) and rounded once into y's rows, `stride` + * apart. */ +AVX_KERNEL(conv_t1d) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *cu = &a->t[3], *Y = &a->t[4]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), s = p_int(a, "stride", 0); + /* Without `pad`, the symmetric (k - stride) / 2, which needs k - stride even. */ + const int64_t K = p_int(a, "k", 2 * s), pad = p_int(a, "pad", -1); + const int64_t P = pad >= 0 ? pad : (K - s) / 2; + if (cin <= 0 || cout <= 0 || s <= 0 || K < s || (pad < 0 && ((K - s) & 1))) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(X, cin) < r1 || rows_of(Y, cout) < r1 * s) return RAD_E_SHAPE; + if (numel(W) < cin * cout * K || numel(B) < cout) return RAD_E_SHAPE; + /* Phase r's taps, and the most any phase has (phase 0's). */ + auto taps_of = [K, s](int64_t r) { return (K - r + s - 1) / s; }; + const int64_t KKmax = taps_of(0) * cin; + static thread_local std::vector wbuf, pbuf; + static thread_local std::vector ybuf; + static thread_local std::vector woff; + + /* Phase r's [cout, taps cin] block starts at element woff[r]; its row co, column t cin + ci + * is w[ci, co, r + t s]. Kept bf16 when w is bf16 (exact copies), f32 otherwise. */ + const bool w16 = W->dtype == RAD_BF16; + const size_t wel = w16 ? 2 : 4; + woff.assign((size_t)s + 1, 0); + for (int64_t r = 0; r < s; ++r) woff[(size_t)r + 1] = woff[(size_t)r] + cout * taps_of(r) * cin; + wbuf.resize((size_t)woff[(size_t)s] * wel + 64); + uint8_t* wp = wbuf.data(); + const int64_t* wo = woff.data(); + AVX_PARALLEL_FOR_IF(wo[s] >= AVX_PAR_MIN) + for (int64_t rc = 0; rc < s * cout; ++rc) { + const int64_t r = rc / cout, co = rc % cout, KKr = taps_of(r) * cin; + for (int64_t j = 0; j < KKr; ++j) { + const int64_t src = ((j % cin) * cout + co) * K + r + (j / cin) * s; + const int64_t dst = wo[r] + co * KKr + j; + if (w16) ((uint16_t*)wp)[dst] = ((const uint16_t*)W->data)[src]; + else ((float*)wp)[dst] = ld_elem(W->data, W->dtype, src); + } + } + + const bool b16 = X->dtype == RAD_BF16 && laststride(X) == 1; + const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + const size_t ael = b16 ? 2 : 4; + int64_t longest = 0; + for (int64_t e = 0; e < n_seq; ++e) + longest = std::max(longest, cu_at(cu, e + 1) - cu_at(cu, e)); + const int64_t band = band_rows(KKmax, cout, std::max(1, longest)); + pbuf.resize((size_t)(band * KKmax) * ael + 64); + ybuf.resize((size_t)(band * cout) + 16); + char* pp = (char*)pbuf.data(); + float* yp = ybuf.data(); + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t i0 = cu_at(cu, e), i1 = cu_at(cu, e + 1), Lx = i1 - i0; + if (Lx <= 0) continue; + for (int64_t r = 0; r < s; ++r) { + /* Phase r's rows are the Lx rows lo = q s + r - pad in [0, Lx s), q from + * ceil((pad - r) / s) when pad > r, else from 0. */ + const int64_t q0 = P > r ? (P - r + s - 1) / s : 0; + const int64_t taps = taps_of(r), KK = taps * cin; + const RadTensor wt = mat_view(wp + (size_t)wo[r] * wel, + w16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32, cout, KK); + for (int64_t j0 = 0; j0 < Lx; j0 += band) { + const int64_t nb = std::min(band, Lx - j0); + AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN) + for (int64_t p = 0; p < nb; ++p) { + const int64_t q = q0 + j0 + p; + char* d = pp + (size_t)(p * KK) * ael; + for (int64_t t = 0; t < taps; ++t) + patch_slot(X, i0 + q - t, cin, q - t >= 0 && q - t < Lx, b16, + d + (size_t)(t * cin) * ael); + } + const RadTensor pt = mat_view(pp, adt, nb, KK); + const RadTensor yt = mat_view(yp, RAD_F32, nb, cout); + const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK); + if (st < 0) return st; + AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN) + for (int64_t p = 0; p < nb; ++p) { + const int64_t o = i0 * s + (q0 + j0 + p) * s + r - P; + out_row(Y, rowoff(Y, o, cout), cout, yp + p * cout); + } + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ snake */ +/* y = x + sin(alpha x)^2 / (alpha + 1e-9), or SnakeBeta's x + sin(alpha x)^2 / (beta + 1e-9) with + * `beta` (its reciprocal taken once a channel, as libref takes it), alpha and beta exponentiated + * first with `log` 1; the sine squared by sin_sq. A row holding an argument past kSinBig (or a + * non-finite one) is computed again with the libm sine, as libref computes it. */ +AVX_KERNEL(snake) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *AL = &a->t[1], *Y = &a->t[2], *BE = rad_arg_in(a, 3); + const int64_t n = p_int(a, "n", 0), lg = p_int(a, "log", 0); + if (n <= 0 || numel(AL) < n || (BE && numel(BE) < n) || lg < 0 || lg > 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + /* alpha and the divisor (alpha + 1e-9) for every channel, once a launch, before the parallel + * region; with beta, the multiplier 1 / (beta + 1e-9) in its place. */ + float* al = (float*)scratch_raw((size_t)(2 * n + 32) * sizeof(float)); + float* den = al + n + 16; + for (int64_t c = 0; c < n; ++c) { + al[c] = lg ? (float)std::exp((double)ldt(AL, c)) : ldt(AL, c); + if (BE) { + const float b = lg ? (float)std::exp((double)ldt(BE, c)) : ldt(BE, c); + den[c] = 1.0f / (b + 1e-9f); + } else { + den[c] = al[c] + 1e-9f; + } + } + const bool mul = BE != nullptr; + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const float* x = in_row(X, rowoff(X, r, n), n, scratch_f32((size_t)n + 16)); + float* y = scratch_f32_b((size_t)n + 16); + vf big = vf_zero(); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + const vf xv = vf_loadu(x + c), v = vf_mul(vf_loadu(al + c), xv); + /* |v| first: a NaN lane keeps the running maximum (vmaxps returns its second + * operand on NaN). */ + big = vf_max(vf_abs(v), big); + const vf s2 = sin_sq(v), dv = vf_loadu(den + c); + vf_storeu(y + c, vf_add(xv, mul ? vf_mul(dv, s2) : vf_div(s2, dv))); + } + bool slow = !(vf_hmax(big) <= kSinBig); + for (; c < n; ++c) { + const float v = al[c] * x[c]; + slow = slow || !(std::fabs(v) <= kSinBig); + y[c] = x[c] + (mul ? den[c] * sin_sq1(v) : sin_sq1(v) / den[c]); + } + if (slow) + for (c = 0; c < n; ++c) { + const float sn = sc_sin(al[c] * x[c]); + y[c] = x[c] + (mul ? den[c] * (sn * sn) : sn * sn / den[c]); + } + out_row(Y, rowoff(Y, r, n), n, y); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ snake_aa */ +/* BigVGAN's alias-free SnakeBeta over each sequence (libref's snake_aa): the replicate-padded + * sequence upsampled `ratio` times by the transposed f_up filter, SnakeBeta, and the + * replicate-padded result filtered by f_down at stride `ratio`, in f32. Channels are innermost, so + * every step is vector work along a row. A task is a band of output rows: it computes the + * upsampled rows the band reads (each a function of its index alone, so two bands' overlaps + * agree) into scratch, then filters them down. Each sum runs in libref's order; the sine is + * sin_sq, a row holding an argument past kSinBig taken again with the libm sine, as `snake` + * does. */ +AVX_KERNEL(snake_aa) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *AL = &a->t[1], *BE = &a->t[2], *FU = &a->t[3]; + const RadTensor *FD = &a->t[4], *cu = &a->t[5], *Y = &a->t[6]; + const int64_t n = p_int(a, "n", 0), R = p_int(a, "ratio", 0), k = p_int(a, "k", 0); + const int64_t lg = p_int(a, "log", 0); + if (n <= 0 || R <= 0 || k < R || lg < 0 || lg > 1) return RAD_E_SHAPE; + if (numel(AL) < n || numel(BE) < n || numel(FU) < k || numel(FD) < k) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(X, n) < r1 || rows_of(Y, n) < r1) return RAD_E_SHAPE; + const int64_t P = k / R - 1, crop = P * R + (k - R) / 2, pl = k / 2 - (k % 2 == 0 ? 1 : 0); + /* alpha, the multiplier 1 / (beta + 1e-9) and both filters, once a launch. */ + float* tab = (float*)scratch_raw((size_t)(2 * n + 2 * k + 64) * sizeof(float)); + float *al = tab, *mb = tab + n, *fup = tab + 2 * n, *fdn = fup + k; + for (int64_t c = 0; c < n; ++c) { + al[c] = lg ? sc_exp(ldt(AL, c)) : ldt(AL, c); + mb[c] = 1.0f / ((lg ? sc_exp(ldt(BE, c)) : ldt(BE, c)) + 1e-9f); + } + for (int64_t j = 0; j < k; ++j) { + fup[j] = ldt(FU, offlin(FU, j)); + fdn[j] = ldt(FD, offlin(FD, j)); + } + auto clampi = [](int64_t v, int64_t lo, int64_t hi) { return v < lo ? lo : (v > hi ? hi : v); }; + constexpr int64_t kBand = 64; /* output rows a task */ + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t s0 = cu_at(cu, e), L = cu_at(cu, e + 1) - s0; + if (L <= 0) continue; + const int64_t LR = L * R, bands = (L + kBand - 1) / kBand; + /* The padded input rows an upsampled row m sums over, ascending. */ + auto i_lo = [=](int64_t m) { return crop + m < k ? 0 : (crop + m - k) / R + 1; }; + auto i_hi = [=](int64_t m) { return std::min((crop + m) / R, L + 2 * P - 1); }; + AVX_PARALLEL_FOR_IF(L * n * k >= AVX_PAR_MIN) + for (int64_t b = 0; b < bands; ++b) { + const int64_t o0 = b * kBand, o1 = std::min(L, o0 + kBand); + const int64_t m_lo = clampi(o0 * R - pl, 0, LR - 1); + const int64_t m_hi = clampi((o1 - 1) * R + k - 1 - pl, 0, LR - 1); + const int64_t ia = i_lo(m_lo), ib = i_hi(m_hi); + float* xb = scratch_f32((size_t)((ib - ia + 1) * n + 16)); + float* ab = scratch_f32_b((size_t)((m_hi - m_lo + 1) * n + 16)); + float* yr = scratch_f32_c((size_t)n + 16); + for (int64_t i = ia; i <= ib; ++i) + load_row(X, rowoff(X, s0 + clampi(i - P, 0, L - 1), n), n, xb + (i - ia) * n); + for (int64_t m = m_lo; m <= m_hi; ++m) { + const int64_t o = crop + m, il = i_lo(m), ih = i_hi(m); + float* am = ab + (m - m_lo) * n; + const vf vR = vf_set1((float)R); + vf big = vf_zero(); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + vf acc = vf_zero(); + for (int64_t i = il; i <= ih; ++i) + acc = vf_fma(vf_set1(fup[o - i * R]), vf_loadu(xb + (i - ia) * n + c), acc); + const vf u = vf_mul(vR, acc), v = vf_mul(u, vf_loadu(al + c)); + /* |v| first: a NaN lane keeps the running maximum. */ + big = vf_max(vf_abs(v), big); + vf_storeu(am + c, vf_add(u, vf_mul(vf_loadu(mb + c), sin_sq(v)))); + } + bool slow = !(vf_hmax(big) <= kSinBig); + for (; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = il; i <= ih; ++i) acc += fup[o - i * R] * xb[(i - ia) * n + c]; + const float u = (float)R * acc, v = u * al[c]; + slow = slow || !(std::fabs(v) <= kSinBig); + am[c] = u + mb[c] * sin_sq1(v); + } + if (slow) + for (c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = il; i <= ih; ++i) + acc += fup[o - i * R] * xb[(i - ia) * n + c]; + const float u = (float)R * acc, sn = sc_sin(u * al[c]); + am[c] = u + mb[c] * (sn * sn); + } + } + for (int64_t o = o0; o < o1; ++o) { + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + vf acc = vf_zero(); + for (int64_t j = 0; j < k; ++j) { + const int64_t m = clampi(o * R + j - pl, 0, LR - 1); + acc = vf_fma(vf_set1(fdn[j]), vf_loadu(ab + (m - m_lo) * n + c), acc); + } + vf_storeu(yr + c, acc); + } + for (; c < n; ++c) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) + acc += fdn[j] * ab[(clampi(o * R + j - pl, 0, LR - 1) - m_lo) * n + c]; + yr[c] = acc; + } + out_row(Y, rowoff(Y, s0 + o, n), n, yr); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ cfg_topk_sample */ +/* One pick a lane, libref's arithmetic step for step: g = u + cfg (c - u) in two roundings (the + * lane's own guidance when `cfg` is bound), the repetition penalty over the lane's history (its + * row cleared at frame 0, the pick recorded after), the suppressed ids and the candidates at or + * above the conditional's cond_k-th largest left out, the k largest g with ties to the lower index, + * the softmax over temp in double, and the inverse CDF against + * rad_philox_uniform_s(seed, 2^32 + frame, stream). Every entry's history row and candidate set is + * checked before anything is written. Lanes run in parallel without a history; with one they run + * in order, as two entries may share a lane's row. */ +AVX_KERNEL(cfg_topk_sample) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *lg = &a->t[0], *seed = &a->t[1], *fr = &a->t[2], *ids = &a->t[3]; + const RadTensor *cfgs = rad_arg_in(a, 4), *lane = rad_arg_in(a, 5), *hist = rad_arg_in(a, 6); + const int64_t V = p_int(a, "n_vocab", 0), K = p_int(a, "k", 0), rep = p_int(a, "rep", 1); + const int64_t ck = p_int(a, "cond_k", 0), sub = p_int(a, "stream", 0); + const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0); + const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f); + const float pen = p_f32(a, "penalty", 1.0f); + if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) || + sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane)) + return RAD_E_SHAPE; + const int64_t n = numel(ids) / rep; + if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n || + (cfgs && numel(cfgs) < n) || (lane && numel(lane) < n)) + return RAD_E_SHAPE; + auto open = [sup_lo, sup_hi](int64_t j) { return j < sup_lo || j >= sup_hi; }; + /* Before anything is written: each entry's history row inside `hist`, and a candidate left + * for each lane once the suppressed ids are out. */ + for (int64_t i = 0; hist && i < n; ++i) { + const int64_t L = at(lane, i); + if (L < 0 || (L + 1) * V > numel(hist)) return RAD_E_SHAPE; + } + if (sup_hi - sup_lo >= V) return RAD_E_SHAPE; + if (ck > 0 && sup_hi > sup_lo) + for (int64_t i = 0; i < n; ++i) { + float* c = scratch_f32((size_t)V + 16); + float* cc = scratch_f32_b((size_t)V + 16); + load_row(lg, rowoff(lg, rep * i, V), V, c); + std::memcpy(cc, c, (size_t)V * sizeof(float)); + std::nth_element(cc, cc + (ck - 1), cc + V, std::greater()); + const float thr = cc[ck - 1]; + bool any = false; + for (int64_t j = 0; j < V && !any; ++j) any = c[j] >= thr && open(j); + if (!any) return RAD_E_SHAPE; + } + auto one = [&](int64_t i) { + float* c = scratch_f32((size_t)V + 16); + float* g = scratch_f32_b((size_t)V + 16); + char* raw = (char*)scratch_raw((size_t)V * (2 * sizeof(int64_t) + sizeof(float)) + 256); + int64_t* idx = (int64_t*)raw; + double* e = (double*)(raw + (size_t)V * sizeof(int64_t)); + float* cc = (float*)(raw + (size_t)V * 2 * sizeof(int64_t)); + load_row(lg, rowoff(lg, rep * i, V), V, c); + if (rep == 2) { + const float gi = cfgs ? ldt(cfgs, offlin(cfgs, i)) : cfg; + load_row(lg, rowoff(lg, rep * i + 1, V), V, g); + for (int64_t j = 0; j < V; ++j) g[j] = g[j] + keep(gi * (c[j] - g[j])); + } else { + std::memcpy(g, c, (size_t)V * sizeof(float)); + } + int64_t hb = -1; + if (hist) { + hb = at(lane, i) * V; + if (at(fr, i) == 0) + for (int64_t j = 0; j < V; ++j) + st_int_dt(hist->dtype, hist->data, offlin(hist, hb + j), 0); + for (int64_t j = 0; j < V; ++j) + if (at(hist, hb + j) != 0) g[j] = g[j] > 0.0f ? g[j] / pen : g[j] * pen; + } + int64_t nc = 0; + if (ck > 0) { + std::memcpy(cc, c, (size_t)V * sizeof(float)); + std::nth_element(cc, cc + (ck - 1), cc + V, std::greater()); + const float thr = cc[ck - 1]; + for (int64_t j = 0; j < V; ++j) if (c[j] >= thr && open(j)) idx[nc++] = j; + } else { + for (int64_t j = 0; j < V; ++j) if (open(j)) idx[nc++] = j; + } + const int64_t kk = std::min(K, nc); + std::partial_sort(idx, idx + kk, idx + nc, [g](int64_t p, int64_t q) { + return g[p] > g[q] || (g[p] == g[q] && p < q); + }); + const float m = g[idx[0]] / temp; + double tot = 0; + for (int64_t t = 0; t < kk; ++t) { + e[t] = std::exp((double)(g[idx[t]] / temp - m)); + tot += e[t]; + } + const double u = (double)rad_philox_uniform_s(seed_of(seed, i), + ((uint64_t)1 << 32) + (uint64_t)at(fr, i), + (uint64_t)sub) * tot; + int64_t pick = idx[kk - 1]; + double acc = 0; + for (int64_t t = 0; t < kk; ++t) { + acc += e[t]; + if (u < acc) { pick = idx[t]; break; } + } + for (int64_t r = 0; r < rep; ++r) + st_int_dt(ids->dtype, ids->data, offlin(ids, rep * i + r), pick); + if (hist) st_int_dt(hist->dtype, hist->data, offlin(hist, hb + pick), 1); + }; + if (hist) { + for (int64_t i = 0; i < n; ++i) one(i); + } else { + AVX_PARALLEL_FOR_IF(n * V >= AVX_PAR_MIN) + for (int64_t i = 0; i < n; ++i) one(i); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ rvq_embed */ +/* y = bf16(bf16(t0[c0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale), the sum over the + * codebooks in libref's order, a whole row at a time; with `round` 1 one f32 sum from t0's row on, + * times scale, rounded once into y. A row whose first code is out of range is not written, as in + * libref. */ +AVX_KERNEL(rvq_embed) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *codes = &a->t[0], *t0 = &a->t[1], *t1 = &a->t[2], *Y = &a->t[3]; + const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0); + const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0); + const float scale = p_f32(a, "scale", 1.0f); + const int64_t round1 = p_int(a, "round", 0); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, D); + if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE; + const int64_t n0 = rows_of(t0, D), n1 = rows_of(t1, D); + /* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */ + const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows; + const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + AVX_PARALLEL_FOR_IF(rows * D * K >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t c0 = ld_int_dt(codes->dtype, codes->data, r * rp) + off0; + if (c0 < 0 || c0 >= n0) continue; + float* acc = scratch_f32((size_t)D + 16); + float* buf = scratch_f32_b((size_t)D + 16); + float* tmp = scratch_f32_c((size_t)D + 16); + if (round1) { + const float* e0 = in_row(t0, rowoff(t0, c0, D), D, buf); + for (int64_t d = 0; d < D; ++d) acc[d] = e0[d]; + } else { + for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f; + } + for (int64_t k = 1; k < K; ++k) { + const int64_t cb = + ld_int_dt(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc; + if (cb < 0 || cb >= n1) continue; + const float* tr = in_row(t1, rowoff(t1, cb, D), D, buf); + for (int64_t d = 0; d < D; ++d) acc[d] += tr[d]; + } + if (round1) { + for (int64_t d = 0; d < D; ++d) acc[d] *= scale; + out_row(Y, rowoff(Y, r, D), D, acc); + continue; + } + narrow_row(RAD_BF16, acc, D, tmp); + const float* e0 = in_row(t0, rowoff(t0, c0, D), D, buf); + for (int64_t d = 0; d < D; ++d) acc[d] = e0[d] + acc[d]; + narrow_row(RAD_BF16, acc, D, tmp); + for (int64_t d = 0; d < D; ++d) acc[d] *= scale; + out_row(Y, rowoff(Y, r, D), D, acc); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ frame_mix_store */ +/* m = bf16(bf16(sum_l w_l h_l) * bf16(scale)), w = bf16(softmax(bf16(logits))) in libref's double + * arithmetic, the planes summed in order with each product rounded before its add (`keep`). Entries + * are stored one after another, a row's channels a vector at a time. */ +AVX_KERNEL(frame_mix_store) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + const RadTensor *hid = &a->t[0], *lw = &a->t[1], *sc = &a->t[2], *lane = &a->t[3]; + const RadTensor *fr = &a->t[4], *st = &a->t[5], *dst = &a->t[6]; + const int64_t D = p_int(a, "n_embd", 0), L = p_int(a, "L", 0), stride = p_int(a, "stride", 0); + const int64_t rep = p_int(a, "rep", 1); + if (D <= 0 || L <= 0 || stride <= 0 || rep < 1 || numel(lw) < L || numel(sc) < 1) + return RAD_E_SHAPE; + const int64_t n = numel(lane), plane = rows_of(hid, D) / L; + if (n <= 0 || plane < rep * n || numel(fr) < n) return RAD_E_SHAPE; + const int64_t drows = rows_of(dst, D), nst = numel(st); + auto stores = [&](int64_t i) { + const int64_t ln = at(lane, i), f = at(fr, i); + return !(f < 1 || ln < 0 || ln >= nst || at(st, ln) < 0); + }; + for (int64_t i = 0; i < n; ++i) { + if (!stores(i)) continue; + const int64_t f = at(fr, i); + if (f > stride || at(lane, i) * stride + f - 1 >= drows) return RAD_E_SHAPE; + } + float* wl = (float*)scratch_raw((size_t)(L + 16) * sizeof(float)); + float mx = -INFINITY; + for (int64_t l = 0; l < L; ++l) { wl[l] = rbf(ldt(lw, l)); mx = std::max(mx, wl[l]); } + double tot = 0; + for (int64_t l = 0; l < L; ++l) tot += std::exp((double)(wl[l] - mx)); + for (int64_t l = 0; l < L; ++l) wl[l] = rbf((float)(std::exp((double)(wl[l] - mx)) / tot)); + const float scale = rbf(ldt(sc, 0)); + float* acc = scratch_f32((size_t)D + 16); + float* buf = scratch_f32_b((size_t)D + 16); + float* tmp = scratch_f32_c((size_t)D + 16); + for (int64_t i = 0; i < n; ++i) { + if (!stores(i)) continue; + const int64_t row = at(lane, i) * stride + at(fr, i) - 1; + for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f; + for (int64_t l = 0; l < L; ++l) { + const float* h = in_row(hid, rowoff(hid, l * plane + rep * i, D), D, buf); + const vf w = vf_set1(wl[l]); + int64_t d = 0; + for (; d + VF_N <= D; d += VF_N) + vf_storeu(acc + d, vf_add(vf_loadu(acc + d), keep(vf_mul(w, vf_loadu(h + d))))); + for (; d < D; ++d) acc[d] = acc[d] + keep(wl[l] * h[d]); + } + narrow_row(RAD_BF16, acc, D, tmp); + for (int64_t d = 0; d < D; ++d) acc[d] *= scale; + out_row(dst, rowoff(dst, row, D), D, acc); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ end_status */ +/* status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]. */ +AVX_KERNEL(end_status) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *ids = &a->t[0], *lane = &a->t[1], *st = &a->t[2]; + const int64_t end = p_int(a, "end", -1), rep = p_int(a, "rep", 1); + const int64_t n = numel(lane); + if (n <= 0 || rep < 1 || numel(ids) < rep * n) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t ln = at(lane, i); + if (ln < 0 || ln >= numel(st)) return RAD_E_SHAPE; + } + for (int64_t i = 0; i < n; ++i) { + const int64_t v = at(ids, rep * i); + st_int_dt(st->dtype, st->data, offlin(st, at(lane, i)), v == end ? -1 : v); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ frame_store */ +/* dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i] for each entry whose frame is at + * least `skip` and whose lane has not ended, every entry checked first. codes is read at libref's + * linear offsets (a codebook's row at the plane's pitch, a frame's code at its stride). */ +AVX_KERNEL(frame_store) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *codes = &a->t[0], *lane = &a->t[1], *fr = &a->t[2], *st = &a->t[3]; + const RadTensor *dst = &a->t[4]; + const int64_t K = p_int(a, "n_codes", 0), stride = p_int(a, "stride", 0); + const int64_t rep = p_int(a, "rep", 1), skip = p_int(a, "skip", 0); + if (K <= 0 || stride <= 0 || rep < 1 || skip < 0) return RAD_E_SHAPE; + const int64_t n = numel(lane); + if (n <= 0 || numel(fr) < n || numel(codes) < K * rep * n) return RAD_E_SHAPE; + const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rep * n; + const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + const int64_t nst = numel(st), nd = numel(dst); + auto stores = [&](int64_t i) { + return at(fr, i) - skip >= 0 && at(st, at(lane, i)) >= 0; + }; + for (int64_t i = 0; i < n; ++i) { + const int64_t L = at(lane, i); + if (L < 0 || L >= nst) return RAD_E_SHAPE; + if (!stores(i)) continue; + if (at(fr, i) - skip >= stride || (L + 1) * K * stride > nd) return RAD_E_SHAPE; + } + for (int64_t i = 0; i < n; ++i) { + if (!stores(i)) continue; + const int64_t L = at(lane, i), f = at(fr, i) - skip; + for (int64_t k = 0; k < K; ++k) + st_int_dt(dst->dtype, dst->data, offlin(dst, (L * K + k) * stride + f), + ld_int_dt(codes->dtype, codes->data, k * kp + rep * i * rp)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ resample_nearest */ +/* Output row j is input row min(floor(j * (in / out)), in - 1), the ratio in f32 as libref forms + * it. */ +AVX_KERNEL(resample_nearest) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t in = rows_of(X, n), out = rows_of(Y, n); + if (in <= 0 || out <= 0) return RAD_E_SHAPE; + const float scale = (float)in / (float)out; + AVX_PARALLEL_FOR_IF(out * n >= AVX_PAR_MIN) + for (int64_t j = 0; j < out; ++j) { + const int64_t src = std::min((int64_t)std::floor((float)j * scale), in - 1); + copy_row(X, rowoff(X, src, n), Y, rowoff(Y, j, n), n, scratch_f32((size_t)n + 16)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ fourier_embed */ +/* [cos(2 pi t w) | sin(2 pi t w)] with libref's libm calls and, with `round` 1, its bf16 roundings + * of t, 2 pi t and the product. */ +AVX_KERNEL(fourier_embed) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *T = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + const bool rnd = p_int(a, "round", 0) != 0; + if (n <= 0 || (n & 1) || numel(W) < n / 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE; + const int64_t h = n / 2; + const float two_pi = 6.28318530717958647692f; + float* w = (float*)scratch_raw((size_t)(h + 16) * sizeof(float)); + for (int64_t i = 0; i < h; ++i) w[i] = ldt(W, i); + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN / 16) + for (int64_t r = 0; r < rows; ++r) { + float* row = scratch_f32((size_t)n + 16); + float tv = ldt(T, offlin(T, r)); + tv = rnd ? rbf(rbf(tv) * two_pi) : tv * two_pi; + for (int64_t i = 0; i < h; ++i) { + float ang = tv * w[i]; + if (rnd) ang = rbf(ang); + row[i] = sc_cos(ang); + row[h + i] = sc_sin(ang); + } + out_row(Y, rowoff(Y, r, n), n, row); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_input */ +/* y[cu[e] + k] = [lat | zeros | cond] of row k of lane win_lane[e], zeros for the conditioning of an + * unconditional entry (pair -2). */ +AVX_KERNEL(win_input) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const RadTensor *lat = &a->t[0], *cond = &a->t[1], *lcu = &a->t[2], *wl = &a->t[3]; + const RadTensor *pair = &a->t[4], *Y = &a->t[5]; + const int64_t C = p_int(a, "n_lat", 0), Z = p_int(a, "n_zero", 0), D = p_int(a, "n_cond", 0); + const int64_t stride = p_int(a, "stride", 0), W = C + Z + D; + if (C <= 0 || Z < 0 || D <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(wl) < S || numel(pair) < S) return RAD_E_SHAPE; + const int64_t y_rows = rows_of(Y, W); + if (y_rows < cu_at(lcu, S)) return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + const int64_t L = at(wl, e), neg = at(pair, e) == -2; + const int64_t b0 = cu_at(lcu, e), len = cu_at(lcu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, C)) return RAD_E_SHAPE; + if (len > 0 && (b0 < 0 || b0 + len > y_rows)) return RAD_E_SHAPE; + if (len > 0 && !neg && (L + 1) * stride > rows_of(cond, D)) return RAD_E_SHAPE; + } + for (int64_t e = 0; e < S; ++e) { + const int64_t L = at(wl, e), neg = at(pair, e) == -2; + const int64_t b0 = cu_at(lcu, e), len = cu_at(lcu, e + 1) - b0; + AVX_PARALLEL_FOR_IF(len * W >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + float* row = scratch_f32((size_t)W + 16); + load_row(lat, rowoff(lat, L * stride + k, C), C, row); + for (int64_t c = 0; c < Z; ++c) row[C + c] = 0.0f; + if (neg) for (int64_t c = 0; c < D; ++c) row[C + Z + c] = 0.0f; + else load_row(cond, rowoff(cond, L * stride + k, D), D, row + C + Z); + out_row(Y, rowoff(Y, b0 + k, W), W, row); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_prep */ +/* A window step's start for each entry that moves its lane: FIRST draws the window's noise + * (rad_philox_normal_s(seed, 1 + win_index, k n + c), as bf16) into the lane and, with JOIN, into + * `noise`; JOIN binds the first min(ov, rows) rows to the previous window's end, + * bf16(bf16(wn noise) + bf16(t prev)). A row's draw and its binding depend on that row alone, so + * an entry's rows run in parallel, each doing both. */ +AVX_KERNEL(win_prep) { + if (!rad_args_have(a, 10)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *T = &a->t[1], *seed = &a->t[2], *widx = &a->t[3]; + const RadTensor *wl = &a->t[4], *pair = &a->t[5], *lcu = &a->t[6], *prev = &a->t[7]; + const RadTensor *noise = &a->t[8], *lat = &a->t[9]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0); + if (n <= 0 || stride <= 0 || ov < 0 || ov > stride) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(fl) < S || numel(T) < S || numel(widx) < S) return RAD_E_SHAPE; + if (numel(pair) < S || numel(wl) < S) return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + if (at(pair, e) == -2) continue; + const int64_t f = at(fl, e), L = at(wl, e); + const int64_t len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) || + (ov && (L + 1) * ov > rows_of(noise, n))) + return RAD_E_SHAPE; + if ((f & kFirst) && numel(seed) < 2 * (e + 1)) return RAD_E_SHAPE; + if ((f & kJoin) && ov && len > 0 && (L + 1) * ov > rows_of(prev, n)) return RAD_E_SHAPE; + } + for (int64_t e = 0; e < S; ++e) { + if (at(pair, e) == -2) continue; + const int64_t f = at(fl, e), L = at(wl, e); + const int64_t len = cu_at(lcu, e + 1) - cu_at(lcu, e); + const bool first = (f & kFirst) != 0, join = (f & kJoin) != 0; + const uint64_t sd = first ? seed_of(seed, e) : 0; + const uint64_t sm = 1 + (uint64_t)at(widx, e); + const float tb = join ? rbf(ldt(T, offlin(T, e))) : 0.0f; + const float wn = rbf(1.0f - rbf((1.0f - 1e-6f) * tb)); + const int64_t m = std::min(ov, len); + const int64_t todo = first ? len : (join ? m : 0); + AVX_PARALLEL_FOR_IF(todo * n >= AVX_PAR_MIN / 4) + for (int64_t k = 0; k < todo; ++k) { + float* v = scratch_f32((size_t)n + 16); + float* tmp = scratch_f32_c((size_t)n + 16); + if (first) { + philox_normals_s(sd, sm, (uint64_t)(k * n), n, v); + narrow_row(RAD_BF16, v, n, tmp); + out_row(lat, rowoff(lat, L * stride + k, n), n, v); + if (join && k < ov) out_row(noise, rowoff(noise, L * ov + k, n), n, v); + } + if (join && k < m) { + float* pv = scratch_f32_b((size_t)n + 16); + load_row(noise, rowoff(noise, L * ov + k, n), n, v); + load_row(prev, rowoff(prev, L * ov + k, n), n, pv); + for (int64_t c = 0; c < n; ++c) v[c] = wn * v[c]; + narrow_row(RAD_BF16, v, n, tmp); + for (int64_t c = 0; c < n; ++c) pv[c] = tb * pv[c]; + narrow_row(RAD_BF16, pv, n, tmp); + for (int64_t c = 0; c < n; ++c) v[c] = v[c] + pv[c]; + narrow_row(RAD_BF16, v, n, tmp); + out_row(lat, rowoff(lat, L * stride + k, n), n, v); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_finish */ +/* A window's end for each entry that moves its lane and carries LAST: with JOIN its first + * min(ov, rows) rows become the previous window's end; then rows [max(0, rows - 2 ov), + * max(.., rows - ov)) of the latent and the conditioning are kept as the next window's prev and + * prev_cond. The two copies run one after the other, since the second may read rows the first + * wrote. */ +AVX_KERNEL(win_finish) { + if (!rad_args_have(a, 8)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *pair = &a->t[1], *wl = &a->t[2], *lcu = &a->t[3]; + const RadTensor *cond = &a->t[4], *lat = &a->t[5], *prev = &a->t[6], *pc = &a->t[7]; + const int64_t n = p_int(a, "n", 0), D = p_int(a, "n_cond", 0); + const int64_t stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0); + if (n <= 0 || D <= 0 || stride <= 0 || ov <= 0 || ov > stride) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(fl) < S || numel(wl) < S) return RAD_E_SHAPE; + if (numel(pair) < S) return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + const int64_t f = at(fl, e); + if (at(pair, e) == -2 || !(f & kLast)) continue; + const int64_t L = at(wl, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) || + (L + 1) * ov > rows_of(prev, n) || (L + 1) * ov > rows_of(pc, D)) + return RAD_E_SHAPE; + if (len > ov && (L + 1) * stride > rows_of(cond, D)) return RAD_E_SHAPE; + } + for (int64_t e = 0; e < S; ++e) { + const int64_t f = at(fl, e); + if (at(pair, e) == -2 || !(f & kLast)) continue; + const int64_t L = at(wl, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (f & kJoin) { + const int64_t m = std::min(ov, len); + AVX_PARALLEL_FOR_IF(m * n >= AVX_PAR_MIN) + for (int64_t k = 0; k < m; ++k) + copy_row(prev, rowoff(prev, L * ov + k, n), lat, rowoff(lat, L * stride + k, n), n, + scratch_f32((size_t)n + 16)); + } + const int64_t s0 = std::max(0, len - 2 * ov); + const int64_t s1 = std::max(s0, len - ov); + AVX_PARALLEL_FOR_IF((s1 - s0) * (n + D) >= AVX_PAR_MIN) + for (int64_t k = s0; k < s1; ++k) { + float* scr = scratch_f32((size_t)std::max(n, D) + 16); + copy_row(lat, rowoff(lat, L * stride + k, n), prev, rowoff(prev, L * ov + k - s0, n), n, + scr); + copy_row(cond, rowoff(cond, L * stride + k, D), pc, rowoff(pc, L * ov + k - s0, D), D, + scr); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_split */ +/* y[p rows + r] = x[r, p n .. p n + n): channel groups as sequences of their own. */ +AVX_KERNEL(chan_split) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), P = p_int(a, "parts", 0); + if (n <= 0 || P <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n) / P; + if (rows <= 0 || rows_of(X, P * n) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(X); + AVX_PARALLEL_FOR_IF(P * rows * n >= AVX_PAR_MIN) + for (int64_t q = 0; q < P * rows; ++q) { + const int64_t p = q / rows, r = q % rows; + copy_row(X, rowoff(X, r, P * n) + p * n * xs, Y, rowoff(Y, q, n), n, + scratch_f32((size_t)n + 16)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ interleave2 */ +/* y [rows, 2] = (a[r], b[r]). */ +AVX_KERNEL(interleave2) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x0 = &a->t[0], *x1 = &a->t[1], *Y = &a->t[2]; + const int64_t rows = rows_of(Y, 2); + if (rows <= 0 || numel(x0) < rows || numel(x1) < rows) return RAD_E_SHAPE; + const int64_t ys = laststride(Y); + AVX_PARALLEL_FOR_IF(rows >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t yb = rowoff(Y, r, 2); + stt(Y, yb, ldt(x0, offlin(x0, r))); + stt(Y, yb + ys, ldt(x1, offlin(x1, r))); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ iota */ +/* y[i] = start + i * step over y's elements. */ +AVX_KERNEL(iota) { + if (!rad_args_have(a, 1)) return RAD_E_INVAL; + const RadTensor* Y = &a->t[0]; + const int64_t start = p_int(a, "start", 0), step = p_int(a, "step", 1); + const int64_t period = p_int(a, "period", 0); + const int64_t n = numel(Y); + if (n <= 0 || period < 0) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) + st_int_dt(Y->dtype, Y->data, offlin(Y, i), start + (period ? i % period : i) * step); + return RAD_OK; +} + +/* ------------------------------------------------------------------ cu_repeat */ +/* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */ +AVX_KERNEL(cu_repeat) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *len = &a->t[0], *Y = &a->t[1]; + const int64_t mult = p_int(a, "mult", 1); + const int64_t n = numel(Y); + if (n <= 0 || numel(len) < 1 || mult <= 0) return RAD_E_SHAPE; + const int64_t l = at(len, 0); + for (int64_t j = 0; j < n; ++j) st_int_dt(Y->dtype, Y->data, offlin(Y, j), j * l * mult); + return RAD_OK; +} diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index b101f0d8..a36dbb2b 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -43,6 +43,8 @@ std::vector build_cases() { add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) }, EB(5, 645, w, 2)); add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3)); + add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt), HF("div", 3.0) }, + EB(9, 645, w, 3)); add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3)); add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3)); add("gelu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3)); @@ -132,6 +134,10 @@ std::vector build_cases() { } add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) }); + /* One scale per column over the rows: no group. */ + add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); + add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25)); + /* Quantisation. 128 is the real grid; 64 tests a second block edge. n = 256 is divisible by * both, which the had_* forms require (a rotation block may not straddle the row end). */ for (int group : { 64, 128 }) { @@ -254,13 +260,12 @@ std::vector build_cases() { 2.0 * M * 192 * 256); add("gemm_nt_q_gated", { HI("M", 7), HI("N", 512), HI("K", 256), HI("group", 128), HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256); - /* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself -- a base row -- - * comes up in every case of more than one row and the comparison covers rows neither op may - * touch (a single row draws an adapter, or the case would compare nothing). M = 1 takes the - * shrink's team-over-columns arm and 9 and 65 its team-over-rows one; K = 1000 - * leaves a partial scale group and a vector tail at every level; R = 48 is not a power of two. - * The dtype is `a`'s for shrink -- the coded ones with their scale stream -- and `y`'s for - * expand. */ + /* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself, a base row, comes + * up in every case of more than one row (a single row draws an adapter, or the case would + * compare nothing). M = 1 takes the shrink's team-over-columns arm and 9 and 65 its + * team-over-rows one; K = 1000 leaves a partial scale group and a vector tail at every level; + * R = 48 is not a power of two. The dtype is `a`'s for shrink (the coded ones with their scale + * stream) and `y`'s for expand. */ for (int M : { 1, 9, 65 }) { for (const char* dt : { "f32", "bf16", "f16", "fp8_e4m3", "i8" }) for (int K : { 256, 1000 }) @@ -300,6 +305,12 @@ std::vector build_cases() { add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", causal), HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), HI("window", 5) }); + /* A non-causal window reaching further right than left (a sliding encoder layer that sees 4 + * keys behind and 7 ahead). */ + for (const char* dt : { "f32", "bf16" }) + add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", 0), + HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), + HI("window", 5), HI("window_right", 8) }); /* Blocks: each segment cut into blocks of 7 rows that attend within themselves (a chunked * encoder's windows), the last block of a segment short. */ for (const char* dt : { "f32", "bf16" }) @@ -436,6 +447,13 @@ std::vector build_cases() { } add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0), HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") }); + /* Llama 3's frequency scaling at a depth decoder's settings (theta 5e5, factor 32, original + * length 16): kept, blended and divided frequencies all present. */ + for (const char* dt : { "f32", "bf16" }) + add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2), + HF("theta", 500000.0), HF("scale", 1.0), HS("mode", "neox"), + HF("llama3_factor", 32.0), HF("llama3_low", 0.001953125), + HF("llama3_high", 0.0078125), HF("llama3_orig", 16.0), HS("dtype", dt) }); /* A rotary wider than 1024 (libref takes up to 2048, i.e. 1024 frequencies), plain and with * contiguous sections, and QSA's key at the same width. */ add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1), @@ -456,6 +474,18 @@ std::vector build_cases() { add("rope", { HI("M", 12), HI("head_dim", 72), HI("n_head", 4), HI("n_head_kv", 4), HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"), HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) }); + /* MiniMax-H3's: the DiT's 3-axis rotary over 96 of 128 channels, the video decoder's + * over 48 of 64; and the norm alone (rotary_dim 0, no positions). f32 positions and + * absent gains are avx_check_hand.cpp's. */ + add("qk_norm_rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 2), HI("n_head_kv", 2), + HF("theta", 10000.0), HF("eps", 1e-5), HS("mode", "axial"), + HI("rotary_dim", 96), HS("sections", "16 16 16"), HS("dtype", dt) }); + add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4), + HF("theta", 100.0), HF("eps", 1e-5), HS("mode", "axial"), + HI("rotary_dim", 48), HS("sections", "8 8 8"), HS("dtype", dt) }); + add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2), + HF("theta", 10000.0), HF("eps", 1e-6), HI("rotary_dim", 0), + HI("v_norm", 1), HS("dtype", dt) }); add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) }); /* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by * avx_check's hand-built case. */ @@ -617,6 +647,8 @@ std::vector build_cases() { EB(7, 645, dt[0] == 'f' ? 4 : 2, 2)); add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, dt[0] == 'f' ? 4 : 2, 3)); + add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt), HS("act", "none") }, + EB(7, 645, dt[0] == 'f' ? 4 : 2, 3)); for (int gated : { 1, 0 }) add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128), HI("gated", gated), HS("dtype", dt) }); @@ -631,8 +663,10 @@ std::vector build_cases() { HS("dtype", dt) }); add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) }); for (const char* mode : { "fma", "inv" }) - add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()), - HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt) }); + for (int round : { 1, 0 }) + add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()), + HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt), + HI("round", round) }); for (const char* act : { "silu", "none" }) add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) }); add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) }); @@ -671,6 +705,187 @@ std::vector build_cases() { HI("n_head", 4), HS("qk", qk) }); } + /* ================================================================== video generation + * + * MiniMax-H3's DiT row ops at an odd width, both gated forms; its sampler step over an f32 + * state; the decoder's patch unfold, tiles, stitch and positions over the cube geometry + * libref describes (one value in every `geom` entry). Uneven grids, a chunk between two + * others and views of wider planes are avx_check_hand.cpp's. */ + static const std::string kStd24 = [] { + std::string s; + for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.4 + 0.07 * i); + return s; + }(); + static const std::string kMean24 = [] { + std::string s; + for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.031 * i - 0.37); + return s; + }(); + for (const char* dt : { "f32", "bf16" }) { + for (int gated : { 1, 0 }) { + add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated), + HS("dtype", dt) }); + add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128), + HI("gated", gated), HS("dtype", dt) }); + } + add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) }); + for (int pt : { 1, 4 }) + add("patch_unfold", { HI("M", 8 * 4 * pt), HI("C", 24), HI("pt", pt), HI("ph", 2), + HI("pw", 2), HS("mul", kStd24.c_str()), + HS("add", kMean24.c_str()), HS("dtype", dt) }); + /* Three frames of 3 x 3: two tiles of 2 a side overlapping by 1, two register rows and + * one zero row a tile. */ + add("vtile_gather", { HI("M", 60), HI("n", 37), HI("tile", 2), HI("overlap", 1), + HI("frames", 3), HI("period", 15), HI("n_reg", 2), HS("dtype", dt) }); + } + /* A 3 x 3 latent of 3 frames, 2 x 2 tiles a row apart past their voxels, decoded at scale 2 + * and two clip frames a latent one: the kept frames and the overlap of a video's only + * chunk. */ + add("vtile_stitch", { HI("M", 108), HI("tile", 2), HI("overlap", 1), HI("scale", 2), + HI("pt", 2), HI("skip", 1), HI("keep", 2), HI("blend", 1), + HI("period", 13), HS("mean", "0.485 0.456 0.406"), + HS("std", "0.229 0.224 0.225") }); + add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27), + HF("scale", 6.283185307179586) }); + + /* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2 + * after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without + * the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after + * one segment (P 4, V 12). attn_vsa at k = 1, the one selection a description draws; the + * others are avx_check_hand.cpp's. `n_head`, `coarse` and `dtype` are the description's. */ + for (const char* dt : { "f32", "bf16" }) { + for (int coarse : { 1, 0 }) { + add("vsa_select", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2), + HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.8), + HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) }); + add("attn_vsa", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2), + HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.9), + HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) }); + } + for (double sp : { 0.5, 0.0 }) + add("vsa_select", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4), + HI("tile_w", 4), HI("patch", 2), HF("sparsity", sp), + HI("n_head", 2), HS("dtype", dt) }); + add("attn_vsa", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4), + HI("tile_w", 4), HI("patch", 2), HF("sparsity", 0.95), HI("n_head", 2), + HS("dtype", dt) }); + } + + /* ================================================================== audio generation + * + * The vocoder's convolutions over two sequences (a stereo latent's halves as libref describes + * them), odd channel counts, the codec's kernel widths and dilations and every stride an + * upsampling block uses; the sampler at both branch counts, with and without the conditional + * candidate cut; the window ops over three and four entries, so the drawn flags reach FIRST, + * JOIN and LAST in several combinations. The first case of each op stays inside libref's four + * lanes at twice its rows, which the zero-row check describes. */ + for (const char* dt : { "f32", "bf16", "f16" }) { + for (int dil : { 1, 3 }) + for (const char* act : { "none", "tanh" }) + add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7), + HI("dil", dil), HS("act", act), HS("dtype", dt) }); + add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 3), HI("dil", 9), + HS("dtype", dt) }); + add("conv1d", { HI("M", 9), HI("cin", 33), HI("cout", 17), HI("k", 1), HI("dil", 1), + HS("dtype", dt) }); + /* Causal: all of the padding on the left (odd k; an even k is a hand-built case, which + * libref's description does not draw). */ + for (int dil : { 1, 3 }) + add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7), + HI("dil", dil), HI("causal", 1), HS("dtype", dt) }); + for (int s : { 2, 4, 8 }) + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s), + HS("dtype", dt) }); + /* The causal transposed form, a codec's upsampler: no padding, a sequence's first + * output rows reading its first input row alone. */ + for (int s : { 2, 4, 8 }) + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s), + HI("pad", 0), HS("dtype", dt) }); + /* A kernel of one stride (one tap a phase), without padding and with some. An odd stride + * is a hand-built case, which libref's description does not draw. */ + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2), + HI("k", 2), HS("dtype", dt) }); + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 4), + HI("k", 4), HI("pad", 1), HS("dtype", dt) }); + /* BigVGAN's upsamplers: kernel 9 at stride 5 (three taps in some phases, two in + * others), and a kernel of six strides whose padding passes a stride. */ + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 5), + HI("k", 9), HS("dtype", dt) }); + add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2), + HI("k", 12), HS("dtype", dt) }); + add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7), HI("dil", 1), + HS("act", "clamp"), HS("dtype", dt) }); + add("snake", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); + add("snake", { HI("M", 6), HI("n", 645), HI("log", 1), HS("dtype", dt) }); + /* The alias-free SnakeBeta at BigVGAN's 12-tap filters over two sequences, and an odd + * filter at ratio 3. */ + for (int lg : { 0, 1 }) + add("snake_aa", { HI("M", 24), HI("n", 37), HI("ratio", 2), HI("k", 12), + HI("log", lg), HS("dtype", dt) }); + add("snake_aa", { HI("M", 10), HI("n", 645), HI("ratio", 3), HI("k", 7), HS("dtype", dt) }); + add("resample_nearest", { HI("M", 9), HI("n", 645), HS("dtype", dt) }); + add("resample_nearest", { HI("M", 4), HI("n", 64), HS("dtype", dt) }); + add("chan_split", { HI("M", 9), HI("n", 645), HI("parts", 2), HS("dtype", dt) }); + add("chan_split", { HI("M", 5), HI("n", 64), HI("parts", 3), HS("dtype", dt) }); + add("interleave2", { HI("M", 645), HS("dtype", dt) }); + } + for (int rep : { 1, 2 }) + for (int ck : { 0, 40 }) + add("cfg_topk_sample", { HI("M", 4 * rep), HI("n_vocab", 645), HI("k", 50), + HI("rep", rep), HI("cond_k", ck), HF("cfg", 1.5), + HI("stream", 3), HS("dtype", "f32") }); + add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2), + HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0), + HS("dtype", "f32") }); + /* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a + * candidate), a temperature, the penalty idle without a history. */ + for (int rep : { 1, 2 }) + add("cfg_topk_sample", { HI("M", 2 * rep), HI("n_vocab", 645), HI("k", 50), + HI("rep", rep), HF("cfg", 4.0), HF("temp", 0.9), HI("stream", 0), + HI("sup_lo", 600), HI("sup_hi", 644), HF("penalty", 1.1), + HS("dtype", "f32") }); + for (const char* dt : { "f32", "bf16" }) { + for (double sc : { 1.0, 0.7 }) + add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64), + HI("off0", 5), HF("scale", sc), HS("dtype", dt) }); + /* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */ + for (double sc : { 1.0, 0.7 }) + add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64), + HI("off0", 0), HF("scale", sc), HI("round", 1), HS("dtype", dt) }); + add("frame_mix_store", { HI("M", 2), HI("n_embd", 645), HI("L", 9), HI("stride", 5), + HI("rep", 2), HS("dtype", dt) }); + add("frame_mix_store", { HI("M", 4), HI("n_embd", 64), HI("L", 3), HI("stride", 2), + HI("rep", 1), HS("dtype", dt) }); + for (int round : { 1, 0 }) + add("fourier_embed", { HI("M", 5), HI("n", 256), HI("round", round), + HS("dtype", dt) }); + add("win_input", { HI("M", 24), HI("n_lat", 37), HI("n_zero", 0), HI("n_cond", 64), + HI("stride", 12), HS("dtype", dt) }); + add("win_input", { HI("M", 36), HI("n_lat", 64), HI("n_zero", 3), HI("n_cond", 37), + HI("stride", 16), HS("dtype", dt) }); + for (int ov : { 6, 16 }) + add("win_prep", { HI("M", 32), HI("n", 64), HI("stride", 16), HI("ov", ov), + HS("dtype", dt) }); + add("win_prep", { HI("M", 64), HI("n", 37), HI("stride", 16), HI("ov", 4), + HS("dtype", dt) }); + add("win_finish", { HI("M", 32), HI("n", 64), HI("n_cond", 37), HI("stride", 16), + HI("ov", 6), HS("dtype", dt) }); + add("win_finish", { HI("M", 64), HI("n", 64), HI("n_cond", 37), HI("stride", 16), + HI("ov", 4), HS("dtype", dt) }); + add("win_finish", { HI("M", 36), HI("n", 37), HI("n_cond", 64), HI("stride", 12), + HI("ov", 5), HS("dtype", dt) }); + } + add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) }); + add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) }); + add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2), + HI("skip", 0) }); + add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1), + HI("skip", 1) }); + add("iota", { HI("M", 645), HI("start", 3), HI("step", 2) }); + add("iota", { HI("M", 7), HI("start", -5), HI("step", 1) }); + add("cu_repeat", { HI("M", 5), HI("mult", 3) }); + add("cu_repeat", { HI("M", 9), HI("mult", 1) }); + /* ================================================================== speed-only, at model size * * Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels; @@ -880,6 +1095,16 @@ std::vector build_cases() { 2.0 * 1024 * 12288 * 4096); speed("gemm_nt_q", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HI("group", 128), HS("dtype", "fp8a8") }, 0, 2.0 * 1024 * 12288 * 4096); + /* The music vocoder's third stage (384 channels; a window's two streams there are 88192 rows, + * timed over 8192): a residual unit's dilated 7-tap convolution and its 1 x 1, the stage's + * stride-4 upsampling from 768 channels, and the snake before each. */ + speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 7), HI("dil", 3), + HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384 * 7); + speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 1), HI("dil", 1), + HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384); + speed("conv_t1d", { HI("M", 2048), HI("cin", 768), HI("cout", 384), HI("stride", 4), + HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 2 * 768); + speed("snake", { HI("M", 8192), HI("n", 384), HS("dtype", "bf16") }, 8192.0 * 384 * 2 * 2, 0); return c; } diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index e0de7805..9d4b12c0 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -19,6 +19,7 @@ * be unchanged, and the parallel rerun applies as for the table (avx_check.cpp). */ #include "avx_check.h" #include "rad_planes.h" +#include "rad_runtime.h" /* RAD_VGEOM_* */ #include "rad_sample.h" #ifdef AVX_CHECK_CORE_DECODER #include "format/encoding.h" @@ -1944,6 +1945,45 @@ void gen_cases(std::vector& hs) { .pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16"); hs.push_back(std::move(h)); } + /* ---- the prefix-free form: no cache, block table or prefix lengths; two entries of + * 37 and 8 rows, bf16 and int8 scores, columns of a fused projection. */ + for (const bool pv8 : { false, true }) + for (const bool i8 : { false, true }) + for (const int causal : { 0, 1 }) { + const int64_t T = 45, kvh = 2, gqa = 1, qh = 2, hd = 64; + const int64_t W = (qh + 2 * kvh) * hd; + char nm[128]; + std::snprintf(nm, sizeof nm, "no prefix, 2 entries%s%s%s%s", i8 ? ", i8" : "", + pv8 ? ", fp8 P.V" : "", causal ? ", causal" : "", sfx.c_str()); + Hand h(nm, "attn_prefix_self", dt == RAD_F32 ? 1e-4 : 2e-2); + h.view(dt, { T, qh * hd }, { W, 1 }, T * W, hfill(280)) + .view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(281)); + if (pv8) h.dense(RAD_F8E4M3, { T, kvh * hd }, hfill(282, 64.0f)); + else h.view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(282)); + h.none().none().none() + .idx({ 0, 37, T }) + .none().none(); + if (i8) { + h.dense(RAD_I8, { T, kvh * hd }, [](int64_t i) { + return (float)((int)((i * 41) % 255) - 127); + }) + .dense(RAD_F32, { T, kvh }, [](int64_t i) { + return 0.004f + 0.0005f * (float)(i % 5); + }); + } else { + h.none().none(); + } + h.view(dt, { T, qh * hd }, { W, 1 }, T * W, zero, true); + if (pv8) h.dense(RAD_F32, { kvh * hd }, [](int64_t i) { + return 0.01f + 0.001f * (float)(i % 11); + }); + else h.none(); + h.pi("q_len", T).pi("head_dim", hd).pi("gqa", gqa).pi("block_size", 16) + .pi("causal", causal).ps("q_dtype", dn).ps("kv_dtype", dn).pi("max_ctx", 0) + .pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16") + .ps("pv", pv8 ? "fp8" : "bf16"); + hs.push_back(std::move(h)); + } { /* One segment of a longer sequence: cu is its two bounding offsets, rows [5, 30), and * the rows outside it stay as they were. */ @@ -2004,6 +2044,360 @@ void gen_cases(std::vector& hs) { } } +/* ================================================================== the video generator */ +/* Forms libref's descriptions do not draw: f32 positions as a [3, M] view of a wider plane, absent + * gains and a partial rotary; the DiT's norm over three entries (one empty) with [shift | scale] a + * column slice of a wider modulation table; a latent grid of different extents on every axis, so + * the tiles overlap unevenly; a chunk between two others (the temporal blend and the overlap it + * hands on), a last one and a first one; positions into a view of a wider plane. Everything but + * the norms and the rotaries is held to zero error: libref's arithmetic bit for bit. */ +void video_cases(std::vector& hs) { + const auto zero = [](int64_t) { return 0.0f; }; + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const std::string sfx = std::string(", ") + dn; + const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3; + + /* ---- the rotaries: positions f32, component-major, rows 32 apart ------------------- */ + { + const int64_t M = 9, hd = 128, nh = 2, nkv = 2, W = (nh + 2 * nkv) * hd; + const auto pos = [](int64_t i) { return 0.37f * (float)(i % 32) - 2.5f; }; + Hand h(("the DiT's axial 16 16 16 over 96 of 128, f32 positions" + sfx).c_str(), + "qk_norm_rope", norm_tol); + h.dense(dt, { M, W }, hfill(400), true) + .view(RAD_F32, { 3, M }, { 32, 1 }, 96, pos) + .dense(dt, { hd }, hfill(401, 0.1f)) + .dense(dt, { hd }, hfill(402, 0.1f)) + .pi("M", M).pi("head_dim", hd).pi("n_head", nh).pi("n_head_kv", nkv) + .pf("theta", 10000.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 96) + .ps("sections", "16 16 16"); + hs.push_back(std::move(h)); + + /* The decoder's: no gains, positions 2 pi (2 (c + 0.5) / n - 1), theta 100. */ + const int64_t hv = 64, Wv = 3 * 4 * hv; + const auto vpos = [](int64_t i) { + const int64_t c = i / 32, m = i % 32; + const int64_t n = c == 0 ? 3 : 4, k = c == 0 ? m % 3 : c == 1 ? (m / 4) % 4 : m % 4; + return 6.2831855f * (2.0f * (((float)k + 0.5f) / (float)n) - 1.0f); + }; + Hand g(("the decoder's axial 8 8 8 over 48 of 64, no gains" + sfx).c_str(), + "qk_norm_rope", norm_tol); + g.dense(dt, { M, Wv }, hfill(403), true) + .view(RAD_F32, { 3, M }, { 32, 1 }, 96, vpos) + .none().none() + .pi("M", M).pi("head_dim", hv).pi("n_head", 4).pi("n_head_kv", 4) + .pf("theta", 100.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 48) + .ps("sections", "8 8 8"); + hs.push_back(std::move(g)); + + Hand r(("rope over fractional f32 positions, scale 2" + sfx).c_str(), "rope", + norm_tol); + r.dense(dt, { M, 4 * 64 }, hfill(404), true) + .dense(RAD_F32, { M }, [](int64_t i) { return 0.73f * (float)i - 1.1f; }) + .pi("M", M).pi("head_dim", 64).pi("n_head", 2).pi("n_head_kv", 1) + .pf("theta", 10000.0).pf("scale", 2.0).ps("mode", "neox"); + hs.push_back(std::move(r)); + } + + /* ---- the DiT's norm: three entries (one empty), [shift | scale] at a 6n pitch ------- */ + { + const int64_t R = 11, D = 160, W6 = 6 * D; + for (const bool gated : { true, false }) { + Hand h((std::string(gated ? "gated" : "ungated") + ", three entries, s at a 6n " + "pitch" + sfx).c_str(), "rms_mod", norm_tol); + if (gated) { + h.dense(dt, { R, D }, hfill(410)) + .view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(411, 0.5f)); + } else { + h.none().none(); + } + h.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(412, 0.5f)) + .dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; }) + .idx({ 0, 4, 4, R }) + .dense(dt, { R, D }, hfill(413, 2.0f), true) + .dense(dt, { R, D }, zero, true) + .pi("M", R).pi("n", D).pf("eps", 1e-5).pi("gated", gated ? 1 : 0) + .ps("dtype", dn); + hs.push_back(std::move(h)); + + Hand q((std::string(gated ? "gated" : "ungated") + ", quantised, three entries" + + sfx).c_str(), "rms_mod_quant_fp8", 1e-2); + if (gated) { + q.dense(dt, { R, D }, hfill(414)) + .view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(415, 0.5f)); + } else { + q.none().none(); + } + q.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(416, 0.5f)) + .dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; }) + .idx({ 0, 4, 4, R }) + .dense(dt, { R, D }, hfill(417, 2.0f), true) + .dense(RAD_F8E4M3, { R, D }, zero, true) + .dense(RAD_F32, { R, D / 32 }, zero, true) + .dense(RAD_BF16, { R, D }, zero, true) + .pi("M", R).pi("n", D).pf("eps", 1e-5).pi("group", 32) + .pi("gated", gated ? 1 : 0).ps("dtype", dn); + hs.push_back(std::move(q)); + } + } + + /* ---- the sampler: a bf16 velocity into an f32 state ------------------------------- */ + { + Hand h(("bf16 velocity, f32 state, rows at a wider pitch" + sfx).c_str(), + "flow_x0_step", 0.0); + h.dense(dt, { 7, 96 }, hfill(420, 2.0f)) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.3046875f; }) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.6953125f; }) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.4413f; }) + .view(RAD_F32, { 7, 96 }, { 101, 1 }, 7 * 101, hfill(421), true) + .pi("M", 7).pi("n", 96).ps("dtype", dn); + hs.push_back(std::move(h)); + } + + /* ---- the decoder's geometry: 3 frames of 6 x 9 latents, tiles of 4 over 1 ------------ * + * Rows split 6 -> starts 0, 2 (overlap 2); columns 9 -> 0, 2, 5 (overlaps 2, 1). */ + { + Hand h(("2 x 3 x 2 patches of 2 x 2 x 2, rows past the voxels" + sfx).c_str(), + "patch_unfold", 0.0); + h.dense(RAD_F32, { 12, 5 * 8 }, hfill(430, 3.0f)) + .idx({ 2, 3, 2 }) + .dense(dt, { 100, 5 }, hfill(431), true) + .pi("M", 100).pi("C", 5).pi("pt", 2).pi("ph", 2).pi("pw", 2) + .ps("mul", "0.5 1.25 -2 0.3 1.7").ps("add", "0.1 -0.2 0.3 0 2.5").ps("dtype", dn); + hs.push_back(std::move(h)); + + /* Two register rows and two zero rows a tile. */ + const int64_t n = 37, period = 52, tiles = 6; + Hand g(("6 x 9 in tiles of 4 over 1, registers and zero rows" + sfx).c_str(), + "vtile_gather", 0.0); + g.dense(dt, { 3 * 6 * 9, n }, hfill(432)) + .dense(dt, { 2, n }, hfill(433)) + .idx({ 3, 6, 9 }) + .dense(dt, { tiles * period, n }, hfill(434), true) + .pi("M", tiles * period).pi("n", n).pi("tile", 4).pi("overlap", 1).pi("frames", 3) + .pi("period", period).pi("n_reg", 2).ps("dtype", dn); + hs.push_back(std::move(g)); + + /* The decoded tiles at scale 2, two clip frames a latent one: skip 1, keep 3, blend 1; + * each tile's 48 token rows, then 4 rows the stitch does not read. */ + struct Chunk { int first, last; const char* what; }; + static const Chunk kChunks[] = { { 0, 0, "a chunk between two others" }, + { 0, 1, "a video's last chunk" }, + { 1, 0, "a video's first chunk" } }; + const int64_t npx = 12 * 18; + for (const Chunk& ch : kChunks) { + const int64_t fout = 3 + (ch.last ? 1 : 0); + Hand s((std::string(ch.what) + ", 6 x 9 in tiles of 4 over 1" + sfx).c_str(), + "vtile_stitch", 0.0); + s.dense(dt, { tiles * period, 3 * 2 * 2 * 2 }, hfill(435, 2.0f)) + .idx({ 3, 6, 9, ch.first, ch.last }) + .dense(RAD_BF16, { npx, 3 }, hfill(436, 2.0f), true) + .dense(RAD_U8, { fout * npx, 3 }, zero, true) + .pi("M", fout * npx).pi("tile", 4).pi("overlap", 1).pi("scale", 2).pi("pt", 2) + .pi("skip", 1).pi("keep", 3).pi("blend", 1).pi("period", period) + .ps("mean", "0.485 0.456 0.406").ps("std", "0.229 0.224 0.225"); + hs.push_back(std::move(s)); + } + } + } + + /* ---- positions into a [3, 40] view of a [3, 64] plane ---------------------------------- */ + { + Hand h("two periods of 2 x 3 x 4 and its registers, rows 64 apart", "grid_pos3", 0.0); + h.view(RAD_F32, { 3, 40 }, { 64, 1 }, 192, [](int64_t) { return -7.0f; }, true) + .pi("M", 40).pi("T", 2).pi("H", 3).pi("W", 4).pi("period", 27) + .pf("scale", 6.283185307179586); + hs.push_back(std::move(h)); + } +} + +/* ================================================================== video sparse attention + * What libref's descriptions cannot draw: uneven dense segments (13 and 14 rows: a tile each in + * boxes of 4, two each in boxes of 2) before a 6 x 5 x 7 grid (a 10 x 14 latent at patch 2) with + * edge boxes on every axis, and `geom`'s other entries holding values no tile reads; q, k, v and + * the gate at a fused projection's row pitch and the output at a pitch of its own; `sel` and + * `coarse` wider than the tiles and the selection; attn_vsa over selections of every size from 1 + * to V that are not a top-k of anything; and what both refuse. Outputs start as a sentinel, so an + * element one side writes and the other leaves shows as a difference, and attn_vsa's `sel` holds + * one wherever the op must not read. */ + +/* attn_vsa's `sel`, [nh, cap, kc]: per head and video query tile, k distinct video tiles of + * [P, N) in ascending order, drawn from `seed`; `fill` everywhere else. */ +std::vector vsa_selection(int64_t nh, int64_t cap, int64_t kc, int64_t P, int64_t N, + int64_t k, uint64_t seed, float fill) { + std::vector s((size_t)(nh * cap * kc), fill); + std::vector pool; + uint64_t x = seed; + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = P; i < N; ++i) { + pool.clear(); + for (int64_t j = P; j < N; ++j) pool.push_back(j); + for (int64_t a = 0; a < k; ++a) { + const int64_t b = a + (int64_t)(hsplitmix(x) % (uint64_t)(N - P - a)); + std::swap(pool[(size_t)a], pool[(size_t)b]); + } + std::sort(pool.begin(), pool.begin() + k); + for (int64_t a = 0; a < k; ++a) + s[(size_t)((h * cap + i) * kc + a)] = (float)pool[(size_t)a]; + } + return s; +} + +void vsa_cases(std::vector& hs) { + const int64_t R = 237, NH = 2, HD = 64, W = 4 * NH * HD, WO = NH * HD + 24; + const auto sentinel = [](int64_t) { return -7.0f; }; + const auto geom = [](int64_t i) { + return i == RAD_VGEOM_LAT_FRAMES ? 6.0f : i == RAD_VGEOM_LAT_H ? 10.0f + : i == RAD_VGEOM_LAT_W ? 14.0f : (float)(1000 + i); + }; + struct Geo { int64_t tt, P, V; const char* what; }; + static const Geo kGeo[] = { { 4, 2, 8, "boxes of 4" }, { 2, 4, 36, "boxes of 2" } }; + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const double sel_tol = dt == RAD_F32 ? 1e-5 : 6e-3, att_tol = dt == RAD_F32 ? 1e-4 : 2e-2; + for (const Geo& g : kGeo) + for (const double sp : { 0.8, 0.0, 0.95 }) { + const int64_t N = g.P + g.V; + const int64_t k = std::max( + 1, std::min((int64_t)std::ceil((1.0 - sp) * (double)g.V), g.V)); + char sfx[96]; + std::snprintf(sfx, sizeof sfx, ", 13 | 14 then 6 x 5 x 7, %s, sparsity %g, %s", + g.what, sp, dn); + for (const bool coarse : { true, false }) { + Hand h((std::string(coarse ? "q, k, v at a pitch, coarse" : "q, k at a pitch, " + "no coarse") + sfx).c_str(), "vsa_select", sel_tol); + h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(500)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(501)); + if (coarse) h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(502, 2.0f)); + else h.none(); + h.idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, geom) + .dense(RAD_I32, { NH, N + 2, k + 2 }, sentinel, true); + if (coarse) h.dense(dt, { NH, N + 1, HD }, sentinel, true); + else h.none(); + h.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt) + .pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp); + hs.push_back(std::move(h)); + + const std::vector sv = + vsa_selection(NH, N + 1, k + 1, g.P, N, k, 503 + (uint64_t)k, -9.0f); + Hand a((std::string(coarse ? "q, k, v, gate at a pitch, coarse, out at its " + "own" : "q, k, v at a pitch, out at its own") + sfx + + ", a drawn selection").c_str(), "attn_vsa", att_tol); + a.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f)) + .idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, geom) + .dense(RAD_I32, { NH, N + 1, k + 1 }, + [sv](int64_t i) { return sv[(size_t)i]; }); + if (coarse) { + a.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508)); + } else { + a.none().none(); + } + a.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true) + .pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt) + .pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp); + hs.push_back(std::move(a)); + if (!coarse) continue; + /* The int8 score form: k's codes and per-(row, head) scales beside it. */ + Hand q8((std::string("int8 scores, coarse") + sfx + ", a drawn selection").c_str(), + "attn_vsa", att_tol); + q8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f)) + .idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, geom) + .dense(RAD_I32, { NH, N + 1, k + 1 }, + [sv](int64_t i) { return sv[(size_t)i]; }) + .dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508)) + .view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true) + .dense(RAD_I8, { R, NH * HD }, [](int64_t i) { + return (float)((int)((i * 53) % 255) - 127); + }) + .dense(RAD_F32, { R, NH }, [](int64_t i) { return 0.004f + 0.0005f * (float)(i % 9); }) + .pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt) + .pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8"); + hs.push_back(std::move(q8)); + /* The same with the fp8 P.V form: E4M3 values and a scale per column. */ + Hand p8((std::string("int8 scores, fp8 P.V, coarse") + sfx + + ", a drawn selection").c_str(), "attn_vsa", att_tol); + p8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505)) + .dense(RAD_F8E4M3, { R, NH * HD }, hfill(506, 64.0f)) + .idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, geom) + .dense(RAD_I32, { NH, N + 1, k + 1 }, + [sv](int64_t i) { return sv[(size_t)i]; }) + .dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f)) + .view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508)) + .view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true) + .dense(RAD_I8, { R, NH * HD }, [](int64_t i) { + return (float)((int)((i * 53) % 255) - 127); + }) + .dense(RAD_F32, { R, NH }, [](int64_t i) { + return 0.004f + 0.0005f * (float)(i % 9); + }) + .dense(RAD_F32, { NH * HD }, [](int64_t i) { + return 0.01f + 0.001f * (float)(i % 13); + }) + .pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt) + .pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8") + .ps("pv", "fp8"); + hs.push_back(std::move(p8)); + } + } + } + + /* ---- refusals: nothing written --------------------------------------------------------- */ + const int64_t N = 10, k = 2; + std::vector sv = vsa_selection(NH, N, k, 2, N, k, 509, -9.0f); + std::swap(sv[(size_t)(5 * k)], sv[(size_t)(5 * k + 1)]); /* head 0, tile 5: descending */ + struct Bad { const char* what; int rc; bool gate; float frames; }; + static const Bad kBad[] = { + { "a selection row out of order", RAD_E_INVAL, true, 6.0f }, + { "coarse without its gate", RAD_E_SHAPE, false, 6.0f }, + { "a grid of 5 frames short of the last segment", RAD_E_SHAPE, true, 5.0f }, + }; + for (const Bad& b : kBad) { + const float fr = b.frames; + const std::vector sel = b.rc == RAD_E_INVAL + ? sv : vsa_selection(NH, N, k, 2, N, k, 509, -9.0f); + Hand a((std::string("refused: ") + b.what).c_str(), "attn_vsa", 2e-2); + a.dense(RAD_BF16, { R, NH * HD }, hfill(510)) + .dense(RAD_BF16, { R, NH * HD }, hfill(511)) + .dense(RAD_BF16, { R, NH * HD }, hfill(512)) + .idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, + [fr, geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? fr : geom(i); }) + .dense(RAD_I32, { NH, N, k }, [sel](int64_t i) { return sel[(size_t)i]; }) + .dense(RAD_BF16, { NH, N, HD }, hfill(513)); + if (b.gate) a.dense(RAD_BF16, { R, NH * HD }, hfill(514)); + else a.none(); + a.dense(RAD_BF16, { R, NH * HD }, sentinel, true) + .pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4) + .pi("patch", 2).pf("sparsity", 0.8).refuses(b.rc); + hs.push_back(std::move(a)); + } + { + Hand s("refused: a grid of 5 frames short of the last segment", "vsa_select", 6e-3); + s.dense(RAD_BF16, { R, NH * HD }, hfill(515)) + .dense(RAD_BF16, { R, NH * HD }, hfill(516)) + .none() + .idx({ 0, 13, 27, R }) + .dense(RAD_I32, { RAD_VGEOM_N }, + [geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? 5.0f : geom(i); }) + .dense(RAD_I32, { NH, N, k }, sentinel, true) + .none() + .pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4) + .pi("patch", 2).pf("sparsity", 0.8).refuses(RAD_E_SHAPE); + hs.push_back(std::move(s)); + } +} + /* ================================================================== the QSA indexer and DFlash2 * What libref's descriptions cannot draw: cu not starting at 0 and rows no sequence holds, -1 * pages, the score plane as a column slice of the declared width, the block keys in the KV @@ -3013,6 +3407,481 @@ void encoder_cases(std::vector& hs) { } } +/* ================================================================== the audio generator */ +/* Forms libref's descriptions do not draw: weights at a trained snake's scale (the drawn 0.02 + * leaves the sine almost linear) and arguments past the polynomial's range, SnakeBeta, several + * sequences of uneven length starting past row 0 with an empty one, a convolution without its bias + * and residual, a causal one with an even kernel, a depthwise one with a bias, transposed ones at + * odd strides and at a kernel of one stride, sampler rows full of ties, a sampler with per-lane + * guidance and a history (one lane twice), the window entries the run phase issues: unconditional + * branches (pair -2), every flag combination, a window shorter than its overlap, a frame 0, an + * ended lane; codes as a block of a wider plane; and refusals that must write nothing. Everything + * but the convolutions and snake is held to zero error. */ +void audio_cases(std::vector& hs) { + const auto zero = [](int64_t) { return 0.0f; }; + for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) { + const char* dn = dt == RAD_F32 ? "f32" : "bf16"; + const std::string sfx = std::string(", ") + dn; + const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3; + { + /* alpha 0.25 .. 4.2 and x in [-8, 8]: arguments to about 34. Row 3 holds 30000 (past + * the polynomial's range, so the row takes the libm sine), row 2 a NaN, row 4 an + * infinity. */ + const int64_t n = 67; + Hand h(("trained alphas, a large argument, NaN and infinity" + sfx).c_str(), "snake", + norm_tol); + h.dense(dt, { 5, n }, [n](int64_t i) { + if (i == 3 * n + 4) return 30000.0f; + if (i == 2 * n + 10) return NAN; + if (i == 4 * n + 66) return INFINITY; + return hfill(260, 8.0f)(i); + }) + .dense(RAD_F32, { n }, [](int64_t c) { return 0.25f + 0.06f * (float)c; }) + .dense(dt, { 5, n }, zero, true) + .pi("M", 5).pi("n", n).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Three sequences from row 2, the second empty, no bias and no residual; rows 0, 1, + * 16 and 17 of y are outside every sequence and keep their bytes. */ + const int64_t cin = 20, cout = 13; + Hand h(("rows 2..16 in three sequences, no bias or residual, tanh" + sfx).c_str(), + "conv1d", norm_tol); + h.dense(dt, { 18, cin }, hfill(261)) + .dense(dt, { cout, cin, 5 }, hfill(262, 0.3f)) + .idx({ 2, 7, 7, 16 }) + .none() + .dense(dt, { 18, cout }, hfill(263), true) + .none() + .pi("M", 18).pi("cin", cin).pi("cout", cout).pi("k", 5).pi("dil", 2) + .ps("act", "tanh").ps("dtype", dn); + hs.push_back(std::move(h)); + + /* x rows at a wider pitch than its channels, with the residual and the bias. */ + Hand g(("input rows at a wider pitch, residual and bias" + sfx).c_str(), "conv1d", + norm_tol); + g.view(dt, { 16, cin }, { cin + 3, 1 }, 16 * (cin + 3), hfill(264)) + .dense(dt, { cout, cin, 3 }, hfill(265, 0.3f)) + .idx({ 0, 9, 16 }) + .dense(dt, { 16, cout }, hfill(266)) + .dense(dt, { 16, cout }, zero, true) + .dense(dt, { cout }, hfill(267, 0.5f)) + .pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("dil", 1) + .ps("dtype", dn); + hs.push_back(std::move(g)); + } + for (const int64_t s : { 4, 2 }) { + /* Sequences of 3, 1 and 5 rows from row 1: output rows [s, 10 s); the first s rows of + * y keep their bytes. */ + const int64_t cin = 12, cout = 7; + Hand h(("three uneven sequences from row 1, stride " + std::to_string(s) + sfx).c_str(), + "conv_t1d", norm_tol); + h.dense(dt, { 10, cin }, hfill(268)) + .dense(dt, { cin, cout, 2 * s }, hfill(269, 0.3f)) + .dense(dt, { cout }, hfill(270, 0.5f)) + .idx({ 1, 4, 5, 10 }) + .dense(dt, { 10 * s, cout }, hfill(271), true) + .pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Lanes 2, 0, 1, 3 of four ten-row lanes, overlap 4, seven channels (a Philox block of + * four straddles rows): FIRST | JOIN over a whole window; the same flags on an + * unconditional branch, which moves nothing; JOIN alone over a window of 3 rows, + * shorter than the overlap; FIRST alone over 6 rows. */ + static const uint32_t kSeeds[8] = { 0x9e3779b9u, 1u, 7u, 0u, 3u, 0xfffffffeu, 11u, + 0x80000001u }; + Hand h(("every flag combination, an unconditional entry, a short window" + sfx).c_str(), + "win_prep", 0.0); + h.idx({ 17, 17, 16, 1 }) + .dense(RAD_F32, { 4 }, [](int64_t i) { return 0.7f - 0.13f * (float)i; }) + .raw(RAD_U32, { 8 }, kSeeds) + .idx({ 0, 5, 2, 9 }) + .idx({ 2, 0, 1, 3 }) + .idx({ 1, -2, -1, -1 }) + .idx({ 0, 10, 20, 23, 29 }) + .dense(RAD_BF16, { 16, 7 }, hfill(272)) + .dense(RAD_BF16, { 16, 7 }, hfill(273), true) + .dense(RAD_BF16, { 40, 7 }, hfill(274), true) + .pi("M", 29).pi("n", 7).pi("stride", 10).pi("ov", 4).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* LAST | JOIN over a whole window; LAST over 7 rows (rows - 2 ov < 0, so the kept + * overlap starts at row 0); LAST on an unconditional branch; JOIN without LAST. */ + Hand h(("LAST with and without JOIN, a short window, two skipped" + sfx).c_str(), + "win_finish", 0.0); + h.idx({ 24, 8, 8, 16 }) + .idx({ -1, -1, -2, 0 }) + .idx({ 1, 3, 2, 0 }) + .idx({ 0, 10, 17, 20, 25 }) + .dense(dt, { 40, 5 }, hfill(275)) + .dense(RAD_BF16, { 40, 7 }, hfill(276), true) + .dense(RAD_BF16, { 16, 7 }, hfill(277), true) + .dense(dt, { 16, 5 }, hfill(278), true) + .pi("M", 25).pi("n", 7).pi("n_cond", 5).pi("stride", 10).pi("ov", 4) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Lane 1 twice, the second an unconditional branch (zeros for its conditioning). */ + Hand h(("an unconditional entry beside its conditional one" + sfx).c_str(), + "win_input", 0.0); + h.dense(dt, { 24, 9 }, hfill(279)) + .dense(dt, { 24, 5 }, hfill(280)) + .idx({ 0, 6, 12, 15 }) + .idx({ 1, 1, 0 }) + .idx({ 1, -2, -1 }) + .dense(dt, { 15, 16 }, hfill(281), true) + .pi("M", 15).pi("n_lat", 9).pi("n_zero", 2).pi("n_cond", 5).pi("stride", 8) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Four lanes, two branch rows each: entry 0 at frame 0 (moves past the prompt only), + * entry 1 on an ended lane, entries 2 and 3 stored. */ + Hand h(("frame 0, an ended lane, two stored" + sfx).c_str(), "frame_mix_store", 0.0); + h.dense(dt, { 3 * 8, 37 }, hfill(282, 4.0f)) + .dense(RAD_F32, { 3 }, [](int64_t l) { return l == 0 ? 0.3f : l == 1 ? -1.2f : 2.0f; }) + .dense(RAD_F32, { 1 }, [](int64_t) { return 1.7f; }) + .idx({ 2, 0, 3, 1 }) + .idx({ 0, 3, 2, 5 }) + .idx({ -1, 2, 5, 7 }) + .dense(dt, { 20, 37 }, hfill(283), true) + .pi("M", 4).pi("n_embd", 37).pi("L", 3).pi("stride", 5).pi("rep", 2) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Codes past either table: row 1's first code (its row is not written), row 2's + * second (skipped in the sum). Code-major [3, 4]. */ + static const int32_t kCodes[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 }; + Hand h(("codes past either table" + sfx).c_str(), "rvq_embed", 0.0); + h.raw(RAD_I32, { 3, 4 }, kCodes) + .dense(RAD_BF16, { 12, 9 }, hfill(284)) + .dense(RAD_BF16, { 20, 9 }, hfill(285)) + .dense(dt, { 4, 9 }, hfill(286), true) + .pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2) + .pf("scale", 0.75).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (int round : { 1, 0 }) { + /* A trained projection's scale: angles to about 25 radians. */ + Hand h(("trained frequencies, round " + std::to_string(round) + sfx).c_str(), + "fourier_embed", 0.0); + h.dense(RAD_F32, { 5 }, [](int64_t i) { return i == 4 ? 1.0f : 0.23f * (float)i; }) + .dense(RAD_F32, { 32 }, hfill(287, 4.0f)) + .dense(dt, { 5, 64 }, zero, true) + .pi("M", 5).pi("n", 64).pi("round", round).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + Hand h(("ten rows down to four" + sfx).c_str(), "resample_nearest", 0.0); + h.dense(dt, { 10, 7 }, hfill(288)) + .dense(dt, { 4, 7 }, zero, true) + .pi("M", 4).pi("n", 7).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + Hand h(("three groups of input rows at a wider pitch" + sfx).c_str(), "chan_split", + 0.0); + h.view(dt, { 5, 21 }, { 25, 1 }, 125, hfill(289)) + .dense(dt, { 15, 7 }, zero, true) + .pi("M", 5).pi("n", 7).pi("parts", 3).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (int lg : { 0, 1 }) { + /* SnakeBeta over x in [-8, 8]: alpha and beta as a codec stores them (logarithms in + * [-1, 1], `log` 1) or as positive values. */ + const int64_t n = 37; + const std::function al = + lg ? hfill(291) : std::function([](int64_t c) { + return 0.3f + 0.05f * (float)c; + }); + const std::function be = + lg ? hfill(292) : std::function([](int64_t c) { + return 0.2f + 0.03f * (float)c; + }); + Hand h(("SnakeBeta, alpha and beta as " + std::string(lg ? "logarithms" : "values") + + sfx).c_str(), "snake", norm_tol); + h.dense(dt, { 4, n }, hfill(293, 8.0f)) + .dense(RAD_F32, { n }, al) + .dense(dt, { 4, n }, zero, true) + .dense(RAD_F32, { n }, be) + .pi("M", 4).pi("n", n).pi("log", lg).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* Two segments from row 1, with a bias; row 0 keeps its bytes. */ + const int64_t C = 21; + Hand h(("two segments from row 1, with a bias" + sfx).c_str(), "conv1d_dw", norm_tol); + h.dense(dt, { 12, C }, hfill(294)) + .dense(dt, { C, 1, 5 }, hfill(295, 0.4f)) + .idx({ 1, 6, 12 }) + .dense(dt, { 12, C }, zero, true) + .dense(dt, { C }, hfill(296, 0.5f)) + .pi("M", 12).pi("n", C).pi("k", 5).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (int dil : { 1, 3 }) { + /* Causal with an even kernel (a codec's), two sequences, a bias. */ + const int64_t cin = 20, cout = 13; + Hand h(("causal, k 4, dilation " + std::to_string(dil) + sfx).c_str(), "conv1d", + norm_tol); + h.dense(dt, { 16, cin }, hfill(296 + dil)) + .dense(dt, { cout, cin, 4 }, hfill(300, 0.3f)) + .idx({ 0, 7, 16 }) + .none() + .dense(dt, { 16, cout }, zero, true) + .dense(dt, { cout }, hfill(301, 0.5f)) + .pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 4).pi("dil", dil) + .pi("causal", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const int64_t s : { 5, 3 }) { + /* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows + * from row 1. */ + const int64_t cin = 12, cout = 7; + Hand h(("odd stride " + std::to_string(s) + ", causal" + sfx).c_str(), "conv_t1d", + norm_tol); + h.dense(dt, { 10, cin }, hfill(314 + s)) + .dense(dt, { cin, cout, 2 * s }, hfill(320, 0.3f)) + .dense(dt, { cout }, hfill(321, 0.5f)) + .idx({ 1, 4, 5, 10 }) + .dense(dt, { 10 * s, cout }, hfill(322), true) + .pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const int64_t s : { 5, 2 }) { + /* BigVGAN's upsamplers (kernel 9 at stride 5, pad 2; kernel 12 at stride 2, its + * default pad 5 past a stride) over sequences of 3, 1 and 5 rows from row 1. */ + const int64_t cin = 12, cout = 7, K = s == 5 ? 9 : 12; + Hand h(("kernel " + std::to_string(K) + " at stride " + std::to_string(s) + + ", three uneven sequences" + sfx).c_str(), "conv_t1d", norm_tol); + h.dense(dt, { 10, cin }, hfill(330 + s)) + .dense(dt, { cin, cout, K }, hfill(336, 0.3f)) + .dense(dt, { cout }, hfill(337, 0.5f)) + .idx({ 1, 4, 5, 10 }) + .dense(dt, { 10 * s, cout }, hfill(338), true) + .pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", K) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const int64_t k : { 12, 7 }) { + /* The alias-free SnakeBeta over sequences of 5, 1 and 9 rows from row 1 (row 0 and + * rows past 16 keep their bytes), at a trained scale: alpha and beta logarithms, + * x in [-4, 4], a smooth low-pass pair of filters. */ + const int64_t n = 21; + const auto lowpass = [k](int64_t j) { + const float t = ((float)j + 0.5f) / (float)k - 0.5f; + return (1.0f - 4.0f * t * t) / (float)k * 1.5f; + }; + Hand h(("three uneven sequences, filters of " + std::to_string(k) + sfx).c_str(), + "snake_aa", norm_tol); + h.dense(dt, { 18, n }, hfill(340, 4.0f)) + .dense(RAD_F32, { n }, hfill(341, 0.8f)) + .dense(RAD_F32, { n }, hfill(342, 0.8f)) + .dense(RAD_F32, { 1, 1, k }, lowpass) + .dense(RAD_F32, { 1, 1, k }, lowpass) + .idx({ 1, 6, 7, 16 }) + .dense(dt, { 18, n }, hfill(343), true) + .pi("M", 18).pi("n", n).pi("ratio", 2).pi("k", k).pi("log", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* A kernel of one stride at an odd stride: each output row reads one input row. */ + const int64_t cin = 12, cout = 7, s = 3; + Hand h(("kernel 3 at stride 3" + sfx).c_str(), "conv_t1d", norm_tol); + h.dense(dt, { 10, cin }, hfill(323)) + .dense(dt, { cin, cout, s }, hfill(324, 0.3f)) + .dense(dt, { cout }, hfill(325, 0.5f)) + .idx({ 1, 4, 5, 10 }) + .dense(dt, { 10 * s, cout }, hfill(326), true) + .pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", s) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* The causal transposed form over sequences of 3, 1 and 5 rows from row 1. */ + const int64_t cin = 12, cout = 7, s = 4; + Hand h(("the causal form over three uneven sequences" + sfx).c_str(), "conv_t1d", + norm_tol); + h.dense(dt, { 10, cin }, hfill(302)) + .dense(dt, { cin, cout, 2 * s }, hfill(303, 0.3f)) + .dense(dt, { cout }, hfill(304, 0.5f)) + .idx({ 1, 4, 5, 10 }) + .dense(dt, { 10 * s, cout }, hfill(305), true) + .pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0) + .ps("dtype", dn); + hs.push_back(std::move(h)); + } + { + /* One rounding of the whole sum, with codes past either table (row 1's first code + * leaves its row unwritten, row 2's second adds nothing). Code-major [3, 4]. */ + static const int32_t kCodes1[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 }; + Hand h(("one rounding, codes past either table" + sfx).c_str(), "rvq_embed", 0.0); + h.raw(RAD_I32, { 3, 4 }, kCodes1) + .dense(RAD_BF16, { 12, 9 }, hfill(306)) + .dense(RAD_BF16, { 20, 9 }, hfill(307)) + .dense(dt, { 4, 9 }, hfill(308), true) + .pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2) + .pf("scale", 0.75).pi("round", 1).ps("dtype", dn); + hs.push_back(std::move(h)); + + /* The codes as a block of a wider plane (a lane's history over a run of frames): rows + * at pitch 11, read at the operand's strides. */ + Hand g(("one rounding, codes a block of a wider plane" + sfx).c_str(), "rvq_embed", + 0.0); + g.view(RAD_I32, { 3, 5 }, { 11, 1 }, 33, [](int64_t i) { return (float)(i % 9); }) + .dense(RAD_BF16, { 12, 9 }, hfill(309)) + .dense(RAD_BF16, { 20, 9 }, hfill(310)) + .dense(dt, { 5, 9 }, zero, true) + .pi("M", 5).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2) + .pf("scale", 1.0).pi("round", 1).ps("dtype", dn); + hs.push_back(std::move(g)); + } + } + { + /* Logits on a grid of 0.05 over [-1, 1]: ties throughout, at the k-th place and at the + * conditional's cond_k-th. Three lanes, two branches each. */ + static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u }; + const auto grid = [](int64_t i) { return std::round(hfill(290)(i) * 20.0f) / 20.0f; }; + Hand h("ties at the cut and in the guided order", "cfg_topk_sample", 0.0); + h.dense(RAD_F32, { 6, 40 }, grid) + .raw(RAD_U32, { 6 }, kSeeds) + .idx({ 0, 17, 123456 }) + .dense(RAD_I32, { 6 }, zero, true) + .pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pi("cond_k", 9).pf("cfg", 1.5) + .pi("stream", 2).ps("dtype", "f32"); + hs.push_back(std::move(h)); + + Hand g("one branch, every entry a candidate, a temperature", "cfg_topk_sample", 0.0); + g.dense(RAD_F32, { 3, 40 }, grid) + .raw(RAD_U32, { 6 }, kSeeds) + .idx({ 4, 4, 9 }) + .dense(RAD_I32, { 3 }, zero, true) + .pi("M", 3).pi("n_vocab", 40).pi("k", 40).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.6) + .pi("stream", 0).ps("dtype", "f32"); + hs.push_back(std::move(g)); + } + { + /* A speech model's frame: three lanes with their own guidance, each lane's history of + * earlier picks penalised (lane 2 at frame 0, its row cleared first), reserved ids + * suppressed; the picks recorded in the history. */ + static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u }; + Hand h("guidance a lane, a history, reserved ids", "cfg_topk_sample", 0.0); + h.dense(RAD_F32, { 6, 40 }, hfill(311, 3.0f)) + .raw(RAD_U32, { 6 }, kSeeds) + .idx({ 4, 0, 9 }) + .dense(RAD_I32, { 6 }, zero, true) + .dense(RAD_F32, { 3 }, [](int64_t i) { return 1.0f + 1.5f * (float)i; }) + .idx({ 1, 2, 3 }) + .dense(RAD_I32, { 4, 40 }, [](int64_t i) { return (float)((i * 7) % 3 == 0); }, true) + .pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pf("cfg", 1.0).pf("temp", 0.9) + .pi("stream", 0).pi("sup_lo", 36).pi("sup_hi", 39).pf("penalty", 1.1) + .ps("dtype", "f32"); + hs.push_back(std::move(h)); + + /* One lane twice, in order: logits 4 - 0.5 j at temperature 0.01, so each entry takes its + * best candidate; the first takes id 0, which the second sees penalised (4 / 1.5 falls + * below id 1's 3.5). */ + static const uint32_t kSeeds2[4] = { 9u, 0u, 9u, 0u }; + Hand g("one lane twice: the second entry sees the first's pick", "cfg_topk_sample", 0.0); + g.dense(RAD_F32, { 2, 40 }, [](int64_t i) { return 4.0f - 0.5f * (float)(i % 40); }) + .raw(RAD_U32, { 4 }, kSeeds2) + .idx({ 3, 4 }) + .dense(RAD_I32, { 2 }, zero, true) + .none() + .idx({ 1, 1 }) + .dense(RAD_I32, { 2, 40 }, zero, true) + .pi("M", 2).pi("n_vocab", 40).pi("k", 3).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.01) + .pi("stream", 0).pf("penalty", 1.5).ps("dtype", "f32") + .expect(3, { 0, 1 }); + hs.push_back(std::move(g)); + + /* Refusals before anything is written: a lane past the history, every id suppressed, and + * the conditional's best ids all suppressed. */ + Hand r1("a lane past the history", "cfg_topk_sample", 0.0); + r1.dense(RAD_F32, { 2, 40 }, hfill(312)) + .raw(RAD_U32, { 2 }, kSeeds) + .idx({ 0 }) + .dense(RAD_I32, { 2 }, zero, true) + .none() + .idx({ 5 }) + .dense(RAD_I32, { 4, 40 }, zero, true) + .pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pf("cfg", 2.0) + .pi("stream", 0).pf("penalty", 1.1).ps("dtype", "f32") + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(r1)); + Hand r2("every id suppressed", "cfg_topk_sample", 0.0); + r2.dense(RAD_F32, { 1, 40 }, hfill(313)) + .raw(RAD_U32, { 2 }, kSeeds) + .idx({ 2 }) + .dense(RAD_I32, { 1 }, zero, true) + .pi("M", 1).pi("n_vocab", 40).pi("k", 5).pi("rep", 1).pf("cfg", 1.0) + .pi("stream", 0).pi("sup_lo", 0).pi("sup_hi", 40).ps("dtype", "f32") + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(r2)); + Hand r3("the conditional's best ids all suppressed", "cfg_topk_sample", 0.0); + r3.dense(RAD_F32, { 2, 40 }, [](int64_t i) { + const int64_t j = i % 40; + return j >= 10 && j < 15 ? 5.0f : -0.01f * (float)j; + }) + .raw(RAD_U32, { 2 }, kSeeds) + .idx({ 2 }) + .dense(RAD_I32, { 2 }, zero, true) + .pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pi("cond_k", 5).pf("cfg", 1.5) + .pi("stream", 0).pi("sup_lo", 10).pi("sup_hi", 20).ps("dtype", "f32") + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(r3)); + } + { + /* Four entries, codes a block of a wider plane (pitch 11, each lane's two branch columns): + * entry 0 at frame 0 under skip 1 (moves past the prompt), entry 3 on an ended lane, + * entries 1 and 2 stored. */ + Hand h("frame 0 under skip, an ended lane, codes a block", "frame_store", 0.0); + h.view(RAD_I32, { 3, 8 }, { 11, 1 }, 33, [](int64_t i) { return (float)(100 + i); }) + .idx({ 2, 0, 3, 1 }) + .idx({ 0, 3, 2, 5 }) + .idx({ 1, -1, 4, 2 }) + .dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true) + .pi("M", 4).pi("n_codes", 3).pi("stride", 6).pi("rep", 2).pi("skip", 1); + hs.push_back(std::move(h)); + + /* Refusals before anything is written: a frame past its lane's row, a lane past the + * status. */ + Hand r1("a frame past its lane's row", "frame_store", 0.0); + r1.idx({ 1, 2, 3, 4, 5, 6 }) + .idx({ 0, 1 }) + .idx({ 7, 2 }) + .idx({ 0, 0 }) + .dense(RAD_I32, { 6, 6 }, [](int64_t) { return -7.0f; }, true) + .pi("M", 2).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 1) + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(r1)); + Hand r2("a lane past the status", "frame_store", 0.0); + r2.idx({ 1, 2, 3 }) + .idx({ 4 }) + .idx({ 2 }) + .idx({ 0, 0, 0, 0 }) + .dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true) + .pi("M", 1).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 0) + .refuses(RAD_E_SHAPE); + hs.push_back(std::move(r2)); + } + { + /* Lane 2 ends (its pick is `end`), lanes 0 and 1 continue, lane 3 is not in the frame. */ + Hand h("an ending lane among continuing ones", "end_status", 0.0); + h.idx({ 5, 5, 3, 3, 5, 5 }) + .idx({ 2, 0, 1 }) + .idx({ 7, 7, 7, 7 }, true) + .pi("M", 3).pi("end", 5).pi("rep", 2) + .expect(2, { 3, -1, -1, 7 }); + hs.push_back(std::move(h)); + } +} + } // namespace bool hand_cases(const Check& ck) { @@ -3022,8 +3891,11 @@ bool hand_cases(const Check& ck) { anchor_cases(hs); packed_cases(hs); gen_cases(hs); + video_cases(hs); + vsa_cases(hs); qsa_cases(hs); encoder_cases(hs); + audio_cases(hs); Broken broken; planes_cases(ck, hs, broken); diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index 1d991cac..87a4d7c6 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -32,12 +32,15 @@ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) { /* ------------------------------------------------------------------ add / mul */ /* y = a op b over the output's extent. A one-row `b` is broadcast down the rows; nothing else - * broadcasts, so a shape bug fails instead of producing plausible numbers. */ + * broadcasts, so a shape bug fails instead of producing plausible numbers. `add`'s `div` divides + * the sum rounded through y's dtype, as libref rounds it. */ template static int elementwise2(const RadArgs* a) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2]; const int64_t n = p_int(a, "n", numel(Y)); + const float div = MUL ? 1.0f : p_f32(a, "div", 1.0f); + if (!(div != 0.0f) || !std::isfinite(div)) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; const int64_t rows = rows_of(Y, n); if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE; @@ -57,6 +60,13 @@ static int elementwise2(const RadArgs* a) { vf_storeu(sy + i, MUL ? vf_mul(u, v) : vf_add(u, v)); } for (; i < n; ++i) sy[i] = MUL ? x[i] * y[i] : x[i] + y[i]; + if (div != 1.0f) { + /* sa is free once x is read: the sum's narrowing goes through it. */ + roundtrip(Y->dtype, sy, n, sa); + const vf vd = vf_set1(div); + for (i = 0; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_div(vf_loadu(sy + i), vd)); + for (; i < n; ++i) sy[i] /= div; + } out_row(Y, rowoff(Y, r, n), n, sy); } return RAD_OK; @@ -371,22 +381,27 @@ AVX_KERNEL(conv2d_unfold) { } /* ------------------------------------------------------------------ conv1d_dw */ -/* libref's causal depthwise convolution over time. The weight is transposed to [k][C] once per - * launch so each tap is a vector FMA over the row. */ +/* libref's causal depthwise convolution over time, plus the optional bias. The weight is + * transposed to [k][C] once per launch so each tap is a vector FMA over the row. */ AVX_KERNEL(conv1d_dw) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3]; + const RadTensor* B = rad_arg_in(a, 4); const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1); - if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE; + if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K || (B && numel(B) < C)) + return RAD_E_SHAPE; const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t Mx = rows_of(X, C), My = rows_of(Y, C); if (Mx <= 0 || My <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0))) return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */ - float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64); + /* The taps tap-major, then the bias (zeros when unbound), once a launch. */ + float* wt = (float*)scratch_raw((size_t)((K + 1) * C) * sizeof(float) + 64); + float* bias = wt + K * C; for (int64_t c = 0; c < C; ++c) for (int64_t j = 0; j < K; ++j) wt[j * C + c] = ldt(Wt, (c * K + j) * laststride(Wt)); + for (int64_t c = 0; c < C; ++c) bias[c] = B ? ldt(B, c) : 0.0f; for (int64_t s = 0; s < S; ++s) { const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); @@ -409,6 +424,8 @@ AVX_KERNEL(conv1d_dw) { vf_storeu(acc + c, vf_fma(vf_loadu(xr + c), vf_loadu(wr + c), vf_loadu(acc + c))); for (; c < C; ++c) acc[c] += xr[c] * wr[c]; } + if (B) + for (int64_t c = 0; c < C; ++c) acc[c] += bias[c]; out_row(Y, rowoff(Y, t, C), C, acc); } } diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index 038c1d6d..608e1df2 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -1,18 +1,19 @@ /* avx_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation") except * attn_prefix_self (avx_gen_attn.cpp): the diffusion transformer's adaptive norms and gated * residual, the timestep embedding, the per-image latent lanes and the flow-matching sampler, and - * the image decoder's convolution, channel norm, resampling shortcuts and pixel output. + * the image decoder's convolution, channel norm, resampling shortcuts and pixel output; and a video + * generator's modulated RMS norms and sampler step ("Video generation"). * * Each op rounds where libref/ref_gen.cpp rounds, which is where the upstream bf16 model stores a * tensor. Rows are computed in f32 scratch and every such rounding is a pass through the stored * dtype (`narrow_row`), so a fused kernel produces the bytes of the unfused chain. * - * Bit-exact with libref, not only within tolerance: randn_lanes and flow_euler (a seed gives the - * same picture on every plugin, and the sampler's state feeds every later step), gate_add, - * chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed. Where libref - * multiplies and then adds in two roundings, `keep` stops the compiler from fusing the pair (this - * plugin is built with -ffp-contract=fast, libref without contraction). The norms reduce in a - * different order from libref's and are held to the tolerance table. + * Bit-exact with libref, not only within tolerance: randn_lanes, flow_euler and flow_x0_step (a + * seed gives the same picture on every plugin, and the sampler's state feeds every later step), + * gate_add, chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed. + * Where libref multiplies and then adds in two roundings, `keep` stops the compiler from fusing + * the pair (this plugin is built with -ffp-contract=fast, libref without contraction). The norms + * reduce in a different order from libref's and are held to the tolerance table. * * Per-entry tables (a sequence's modulation row, its tanh gate) are built once per launch before * the parallel region, in scratch_raw; the row loops use only scratch_f32 / _b / _c, so the @@ -107,6 +108,12 @@ inline void mul_rows(float* v, const float* w, int64_t n) { for (; i < n; ++i) v[i] *= w[i]; } +inline void mul_into(float* out, const float* a, const float* b, int64_t n) { + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(a + i), vf_loadu(b + i))); + for (; i < n; ++i) out[i] = a[i] * b[i]; +} + inline void add_rows(float* v, const float* w, int64_t n) { int64_t i = 0; for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_add(vf_loadu(v + i), vf_loadu(w + i))); @@ -116,7 +123,8 @@ inline void add_rows(float* v, const float* w, int64_t n) { /* An entry's modulation row through `f`, rounded to `dt`, for every entry: [n_seq][n] floats in * scratch_raw. `s` is [n_seq, >= n] at its own row pitch (a column slice of the shared * modulation projection), read as libref reads it. `f` 0 is 1 + s, 1 is tanh(s), the exact libm - * tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element. */ + * tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element. + * `f` 2 is s itself, unrounded. */ float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int f) { float* t = (float*)scratch_raw((size_t)(n_seq * n + 16) * sizeof(float)); const int64_t rs = row_stride(s, n), cs = laststride(s); @@ -124,7 +132,7 @@ float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int float* row = t + e * n; for (int64_t i = 0; i < n; ++i) { const float v = ldt(s, e * rs + i * cs); - row[i] = narrow1(dt, f ? sc_tanh(v) : 1.0f + v); + row[i] = f == 2 ? v : narrow1(dt, f ? sc_tanh(v) : 1.0f + v); } } return t; @@ -173,14 +181,15 @@ inline uint64_t seed_of(const RadTensor* seed, int64_t e) { ((uint64_t)(uint32_t)ldi(seed, offlin(seed, 2 * e + 1)) << 32); } -/* The bf16 values of a space-separated list (libref's parse_list): up to `cap` into out. */ -int64_t parse_list(const char* s, float* out, int64_t cap) { +/* The bf16 values of a space-separated list (libref's parse_list), or with `bf16` false its f32 + * values: up to `cap` into out. */ +int64_t parse_list(const char* s, float* out, int64_t cap, bool bf16 = true) { int64_t k = 0; while (s && *s) { char* end = nullptr; const double v = std::strtod(s, &end); if (end == s) break; - if (k < cap) out[k] = narrow1(RAD_BF16, (float)v); + if (k < cap) out[k] = bf16 ? narrow1(RAD_BF16, (float)v) : (float)v; ++k; s = end; } @@ -217,15 +226,19 @@ AVX_KERNEL(ln_mod) { } /* ------------------------------------------------------------------ gate_add */ -/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype. */ +/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype; with `act` none the + * gate is g itself, unrounded. */ AVX_KERNEL(gate_add) { if (!rad_args_have(a, 4)) return RAD_E_INVAL; const RadTensor *Yv = &a->t[0], *G = &a->t[1], *cu = &a->t[2], *X = &a->t[3]; const int64_t n = p_int(a, "n", 0); + static const char* kActs[] = { "tanh", "none" }; + const int act = p_enum(a, "act", kActs, 2, 0); + if (act < 0 || act > 1) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; const int64_t rows = rows_of(Yv, n), n_seq = numel(cu) - 1; if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; - const float* gate = entry_rows(G, n_seq, n, X->dtype, 1); + const float* gate = entry_rows(G, n_seq, n, X->dtype, act ? 2 : 1); AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { @@ -308,6 +321,89 @@ AVX_KERNEL(ln_mod_quant_fp8) { return RAD_OK; } +/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */ +/* Both forms: with `gated` the branch added through the gate row (no tanh) and the residual stored + * in x's dtype; then n1 = rd(x rsqrt(mean(x^2) + eps)), n2 = rd(n1 w), m = rd(n2 rd(1 + scale)), + * z = rd(m + shift), rd the norm chain's dtype (z's for rms_mod, bf16 for the quantised form, + * libref's rule). The sum of squares is the vector reduction, held to the tolerance table; every + * rounding is a pass through the stored dtype, so the rest is libref's arithmetic. The per-entry + * rows (1 + scale rounded, the shift and the gate) and the gain are built once a launch. */ +static int rms_mod_run(const RadArgs* a, bool quant) { + if (a->n_t < (quant ? 9 : 7)) return RAD_E_INVAL; + const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *W = &a->t[3]; + const RadTensor *cu = &a->t[4], *X = &a->t[5]; + const RadTensor *Q = quant ? &a->t[6] : nullptr, *SC = quant ? &a->t[7] : nullptr; + const RadTensor* Z = quant ? rad_arg_in(a, 8) : &a->t[6]; + const int64_t n = p_int(a, "n", 0), grp = quant ? p_int(a, "group", 0) : 1; + const bool gated = p_int(a, "gated", 0) != 0; + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0 || grp <= 0 || n % grp || (gated && (!Yv || !G))) return RAD_E_SHAPE; + const int64_t rows = rows_of(quant ? Q : Z, n), n_seq = numel(cu) - 1, ngrp = n / grp; + if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || numel(W) < n || + numel(S) < n_seq * 2 * n) + return RAD_E_SHAPE; + if (gated && (rows_of(Yv, n) < rows || numel(G) < n_seq * n)) return RAD_E_SHAPE; + if (quant && (numel(SC) < rows * ngrp || (Z && rows_of(Z, n) < rows))) return RAD_E_SHAPE; + const uint32_t dt = quant ? (uint32_t)RAD_BF16 : Z->dtype; + /* The tables from one scratch_raw call, [gain | shift | gate] a sequence and the weight row: + * a second call may reallocate the first. */ + const int64_t tw = gated ? 3 * n : 2 * n; + float* tabs = (float*)scratch_raw((size_t)(n_seq * tw + n + 32) * sizeof(float)); + { + const int64_t s_rs = row_stride(S, 2 * n), s_cs = laststride(S); + const int64_t g_rs = gated ? row_stride(G, n) : 0, g_cs = gated ? laststride(G) : 0; + for (int64_t e = 0; e < n_seq; ++e) + for (int64_t i = 0; i < n; ++i) { + float* row = tabs + e * tw; + row[i] = narrow1(dt, 1.0f + ldt(S, e * s_rs + (n + i) * s_cs)); + row[n + i] = ldt(S, e * s_rs + i * s_cs); + if (gated) row[2 * n + i] = ldt(G, e * g_rs + i * g_cs); + } + for (int64_t i = 0; i < n; ++i) tabs[n_seq * tw + i] = ldt(W, i * laststride(W)); + } + const float* wrow = tabs + n_seq * tw; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(5 * n + 80)); + float *xs = buf, *v = buf + n + 16, *o = v + n + 16, *codes = o + n + 16; + float* tmp = codes + n + 16; + const float* ent = tabs + seq_of(cu, n_seq, r) * tw; + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + if (gated) { + const float* yv = in_row(Yv, rowoff(Yv, r, n), n, codes); + mul_into(v, ent + 2 * n, yv, n); + narrow_row(X->dtype, v, n, tmp); + add_rows(v, xv, n); + narrow_row(X->dtype, v, n, tmp); + out_row(X, rowoff(X, r, n), n, v); + } else { + std::memcpy(v, xv, (size_t)n * sizeof(float)); + } + const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps); + const vf vr = vf_set1(rs); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(o + i, vf_mul(vf_loadu(v + i), vr)); + for (; i < n; ++i) o[i] = v[i] * rs; + narrow_row(dt, o, n, tmp); + mul_rows(o, wrow, n); + narrow_row(dt, o, n, tmp); + mul_rows(o, ent, n); + narrow_row(dt, o, n, tmp); + add_rows(o, ent + n, n); + if (!quant) { + out_row(Z, rowoff(Z, r, n), n, o); + continue; + } + narrow_row(dt, o, n, tmp); + fp8_emit(o, codes, n, grp, Q, SC, Z, r); + } + return RAD_OK; +} + +AVX_KERNEL(rms_mod) { return rms_mod_run(a, false); } +AVX_KERNEL(rms_mod_quant_fp8) { return rms_mod_run(a, true); } + /* ------------------------------------------------------------------ timestep_embed */ /* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})] with libref's libm * calls: a pass embeds one row per entry, so this is a few thousand transcendentals. */ @@ -559,20 +655,60 @@ AVX_KERNEL(flow_euler) { return RAD_OK; } +/* ------------------------------------------------------------------ flow_x0_step */ +/* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and + * r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own + * rounding. */ +AVX_KERNEL(flow_x0_step) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *V = &a->t[0], *T = &a->t[1], *sg = &a->t[2], *sgn = &a->t[3], *X = &a->t[4]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows <= 0 || rows_of(V, n) < rows || numel(T) < 1 || numel(sg) < 1 || numel(sgn) < 1) + return RAD_E_SHAPE; + const float st = 1.0f - ldt(T, offlin(T, 0)); + const float r = ldt(sgn, offlin(sgn, 0)) / ldt(sg, offlin(sg, 0)); + const float omr = 1.0f - r; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t k = 0; k < rows; ++k) { + float* buf = scratch_f32((size_t)(3 * n + 48)); + float *vs = buf, *xs = buf + n + 16, *o = xs + n + 16; + const float* v = in_row(V, rowoff(V, k, n), n, vs); + const float* x = in_row(X, rowoff(X, k, n), n, xs); + const vf vst = vf_set1(st), vr = vf_set1(r), vo = vf_set1(omr); + int64_t c = 0; + for (; c + VF_N <= n; c += VF_N) { + const vf xv = vf_loadu(x + c); + const vf d = vf_add(xv, keep(vf_mul(vst, vf_loadu(v + c)))); + vf_storeu(o + c, vf_add(keep(vf_mul(vr, xv)), keep(vf_mul(vo, d)))); + } + for (; c < n; ++c) { + const float d = x[c] + keep(st * v[c]); + o[c] = keep(r * x[c]) + keep(omr * d); + } + out_row(X, rowoff(X, k, n), n, o); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ chan_affine */ /* A per-channel affine from two lists of n bf16 values: `fma` is bf16(bf16(x * mul) + add), `inv` * is bf16(bf16(x - add) / mul), the inner rounding in y's dtype. */ AVX_KERNEL(chan_affine) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Y = &a->t[1]; - const int64_t n = p_int(a, "n", 0); + const int64_t n = p_int(a, "n", 0), rnd = p_int(a, "round", 1); + if (rnd < 0 || rnd > 1) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", ""); /* Each number takes at least two characters but the last, so this bounds the count. */ const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2); float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float)); float *mul = lists, *add = lists + cap; - if (parse_list(ms, mul, cap) != n || parse_list(as, add, cap) != n) return RAD_E_SHAPE; + if (parse_list(ms, mul, cap, rnd) != n || parse_list(as, add, cap, rnd) != n) + return RAD_E_SHAPE; const char* mode = p_str(a, "mode", "fma"); const bool inv = mode && !std::strcmp(mode, "inv"); if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL; @@ -589,16 +725,21 @@ AVX_KERNEL(chan_affine) { for (; c + VF_N <= n; c += VF_N) vf_storeu(t + c, vf_sub(vf_loadu(x + c), vf_loadu(add + c))); for (; c < n; ++c) t[c] = x[c] - add[c]; - narrow_row(Y->dtype, t, n, tmp); + if (rnd) narrow_row(Y->dtype, t, n, tmp); for (c = 0; c + VF_N <= n; c += VF_N) vf_storeu(t + c, vf_div(vf_loadu(t + c), vf_loadu(mul + c))); for (; c < n; ++c) t[c] /= mul[c]; - } else { + } else if (rnd) { for (; c + VF_N <= n; c += VF_N) vf_storeu(t + c, vf_mul(vf_loadu(x + c), vf_loadu(mul + c))); for (; c < n; ++c) t[c] = x[c] * mul[c]; narrow_row(Y->dtype, t, n, tmp); add_rows(t, add, n); + } else { + for (; c + VF_N <= n; c += VF_N) + vf_storeu(t + c, vf_add(keep(vf_mul(vf_loadu(x + c), vf_loadu(mul + c))), + vf_loadu(add + c))); + for (; c < n; ++c) t[c] = keep(x[c] * mul[c]) + add[c]; } out_row(Y, rowoff(Y, r, n), n, t); } diff --git a/libavx/avx_gen_attn.cpp b/libavx/avx_gen_attn.cpp index 050055ec..6837d27f 100644 --- a/libavx/avx_gen_attn.cpp +++ b/libavx/avx_gen_attn.cpp @@ -52,9 +52,18 @@ struct Geo { int causal; int64_t hd, gqa, kvh, qh, n_seq, bs, max_blocks, bt_rs, bt_cs; int64_t q_rs, k_rs, v_rs, o_rs, k8_rs, ks_rs, sb, sh, so; + int64_t rows_total; /* the fp8 P.V form's rows */ float scale; }; +/* f32 to the nearest E4M3 and back. */ +inline float e4m3_round(float x) { + const uint8_t c = rad_f32_to_fp8e4m3(x); + float y; + cvt_fp8e4m3_to_f32(&c, &y, 1); + return y; +} + inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); } /* One (entry, kv head)'s key sequence: P prefix keys then the entry's own rows from b0. */ @@ -532,12 +541,77 @@ PS_BF16 void task_bf16(const Geo& g, const Seq& q, const uint8_t* pack, int64_t } /* namespace */ +/* ------------------------------------------------------------------ attn_prefix_self, fp8 P.V */ +/* libref's fp8 P.V form, prefix-free, row by row: every score (bf16 or int8 form, libref's + * order), the max, then p = exp(s - max) in f64 rounded to f32, w = e4m3(448 p), and + * o = (sum w v) v_scale / (448 sum p), sums in key order. Two passes, as libref's, because the + * weights are rounded against the row's final max. */ +static int ps_pv8(const Geo& g, const RadTensor* vsc) { + const int64_t hd = g.hd, qh = g.qh; + AVX_PARALLEL_FOR_IF(g.rows_total * qh * hd >= AVX_PAR_MIN) + for (int64_t idx = 0; idx < g.rows_total * qh; ++idx) { + const int64_t h = idx % qh, r = cu_at(g.cu, 0) + idx / qh, kh = h / g.gqa; + int64_t s = 0; + while (s + 1 < g.n_seq && r >= cu_at(g.cu, s + 1)) ++s; + const int64_t b0 = cu_at(g.cu, s), b1 = cu_at(g.cu, s + 1), i = r - b0; + const int64_t nk = g.causal ? i + 1 : b1 - b0; + float* qf = scratch_f32((size_t)(3 * hd + nk)); + float* kf = qf + hd; + float* acc = kf + hd; + float* sc = acc + hd; + for (int64_t d = 0; d < hd; ++d) qf[d] = ldt(g.q, r * g.q_rs + h * hd + d); + float sq = 1.0f; + if (g.i8) { + float am = 0.0f; + for (int64_t d = 0; d < hd; ++d) am = std::max(am, std::fabs(qf[d])); + sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sq; + for (int64_t d = 0; d < hd; ++d) + qf[d] = std::rint(std::min(std::max(qf[d] * inv, -127.0f), 127.0f)); + } + float mx = -INFINITY; + for (int64_t j = 0; j < nk; ++j) { + const int64_t row = b0 + j; + float dot = 0.0f; + if (g.i8) { + for (int64_t d = 0; d < hd; ++d) kf[d] = ldt(g.k8, row * g.k8_rs + kh * hd + d); + for (int64_t d = 0; d < hd; ++d) dot += qf[d] * kf[d]; + dot = dot * sq * ldt(g.ks, row * g.ks_rs + kh) * g.scale; + } else { + const int64_t kb = row * g.k_rs + kh * hd; + for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(g.k, kb + d); + dot *= g.scale; + } + sc[j] = dot; + mx = std::max(mx, dot); + } + for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t j = 0; j < nk; ++j) { + const float p = (float)std::exp((double)(sc[j] - mx)); + sum += p; + const float w = e4m3_round(448.0f * p); + const int64_t vb = (b0 + j) * g.v_rs + kh * hd; + for (int64_t d = 0; d < hd; ++d) acc[d] += w * ldt(g.v, vb + d); + } + const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f; + for (int64_t d = 0; d < hd; ++d) + stt(g.o, r * g.o_rs + h * hd + d, acc[d] * ldt(vsc, offlin(vsc, kh * hd + d)) * inv8); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ attn_prefix_self */ AVX_KERNEL(attn_prefix_self) { if (a->n_t < 12) return RAD_E_INVAL; Geo g{}; - g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.kv = &a->t[3]; - g.bt = &a->t[4]; g.su = &a->t[5]; g.cu = &a->t[6]; g.o = &a->t[11]; + g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.cu = &a->t[6]; g.o = &a->t[11]; + /* The paged prefix, all three operands or none (every prefix empty). */ + g.kv = rad_arg_in(a, 3); + g.bt = rad_arg_in(a, 4); + g.su = rad_arg_in(a, 5); + if ((g.kv == nullptr) != (g.bt == nullptr) || (g.kv == nullptr) != (g.su == nullptr)) + return RAD_E_INVAL; g.kdes = rad_arg_in(a, 7); g.vdes = rad_arg_in(a, 8); g.k8 = rad_arg_in(a, 9); @@ -548,19 +622,22 @@ AVX_KERNEL(attn_prefix_self) { g.hd = p_int(a, "head_dim", 0); g.gqa = p_int(a, "gqa", 1); g.causal = (int)p_int(a, "causal", 0); - g.bs = g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0); + g.bs = !g.kv ? 1 : g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0); if (g.hd <= 0 || g.gqa <= 0 || g.bs <= 0) return RAD_E_SHAPE; if (g.hd > PS_HD_MAX) return RAD_E_UNSUPPORTED; - g.kvh = g.kv->rank == 4 ? g.kv->shape[1] : 0; + /* Without a cache the key heads are the own keys' width over head_dim. */ + g.kvh = g.kv ? (g.kv->rank == 4 ? g.kv->shape[1] : 0) + : g.k->rank >= 3 ? g.k->shape[g.k->rank - 2] + : g.k->rank == 2 ? g.k->shape[1] / g.hd : 0; if (g.kvh <= 0) return RAD_E_SHAPE; g.qh = g.kvh * g.gqa; g.n_seq = numel(g.cu) - 1; - if (g.n_seq <= 0 || numel(g.su) < g.n_seq) return RAD_E_SHAPE; + if (g.n_seq <= 0 || (g.su && numel(g.su) < g.n_seq)) return RAD_E_SHAPE; if (cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0) <= 0) return RAD_E_SHAPE; - g.max_blocks = g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq; - g.bt_rs = g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks; - g.bt_cs = g.bt->rank >= 2 ? g.bt->stride[1] : 1; - for (int64_t s = 0; s < g.n_seq; ++s) + g.max_blocks = !g.bt ? 0 : g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq; + g.bt_rs = g.bt && g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks; + g.bt_cs = g.bt && g.bt->rank >= 2 ? g.bt->stride[1] : 1; + for (int64_t s = 0; g.su && s < g.n_seq; ++s) if (ldi(g.su, offlin(g.su, s)) > g.max_blocks * g.bs) return RAD_E_SHAPE; g.q_rs = row_stride(g.q, g.qh * g.hd); g.k_rs = row_stride(g.k, g.kvh * g.hd); @@ -568,15 +645,28 @@ AVX_KERNEL(attn_prefix_self) { g.o_rs = row_stride(g.o, g.qh * g.hd); g.k8_rs = g.i8 ? row_stride(g.k8, g.kvh * g.hd) : 0; g.ks_rs = g.i8 ? row_stride(g.ks, g.kvh) : 0; - g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2]; + if (g.kv) { g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2]; } g.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)g.hd)); + /* The fp8 P.V form (libref's ref_attn_prefix_self): prefix-free, its own two-pass loop. */ + { + const RadTensor* vsc = a->n_t > 12 ? rad_arg_in(a, 12) : nullptr; + const char* pv = p_str(a, "pv", "bf16"); + const bool pv8 = std::strcmp(pv, "fp8") == 0; + if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL; + if (pv8) { + if (g.kv || g.kdes || g.vdes) return RAD_E_UNSUPPORTED; + g.rows_total = cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0); + return ps_pv8(g, vsc); + } + } /* ---- which form, and each (entry, kv head)'s key sequence */ [[maybe_unused]] bool bf16 = false; #if AVX_LEVEL == 3 static const bool have_bf16 = __builtin_cpu_supports("avx512bf16"); bf16 = have_bf16 && g.hd % 64 == 0 && g.gqa <= 16 && !g.kdes && !g.vdes && - g.q->dtype == RAD_BF16 && g.kv->dtype == RAD_BF16 && g.v->dtype == RAD_BF16 && + g.q->dtype == RAD_BF16 && (!g.kv || g.kv->dtype == RAD_BF16) && + g.v->dtype == RAD_BF16 && (g.i8 || g.k->dtype == RAD_BF16); #endif const size_t tile_bytes = @@ -594,7 +684,7 @@ AVX_KERNEL(attn_prefix_self) { for (int64_t s = 0; s < g.n_seq; ++s) { Seq q{}; q.s = s; q.kh = kh; - q.P = ldi(g.su, offlin(g.su, s)); + q.P = g.su ? ldi(g.su, offlin(g.su, s)) : 0; q.b0 = cu_at(g.cu, s); q.len = std::max(0, cu_at(g.cu, s + 1) - q.b0); /* A negative prefix count makes key j own row b0 + j - P, as libref indexes it. */ diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 8fb22e2a..85ad14cc 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -83,7 +83,7 @@ int avx_par_force(int threads); /* ---- quantisation and rotation */ \ X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \ X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \ - X(dequant) \ + X(dequant) X(quant_cols_fp8) \ X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \ /* ---- gemm and the vocabulary edges */ \ X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \ @@ -108,6 +108,16 @@ int avx_par_force(int threads); X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \ X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \ X(scatter_add_rows) X(attn_prefix_self) \ + /* ---- video generation */ \ + X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \ + X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \ + X(attn_vsa) \ + /* ---- audio generation */ \ + X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \ + X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \ + X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \ + X(win_finish) X(chan_split) X(interleave2) X(iota) \ + X(cu_repeat) X(snake_aa) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ diff --git a/libavx/avx_lora.cpp b/libavx/avx_lora.cpp index da3d028b..1e43dcd7 100644 --- a/libavx/avx_lora.cpp +++ b/libavx/avx_lora.cpp @@ -1,19 +1,17 @@ /* avx_lora.cpp -- runtime LoRA's two halves on the host: lora_shrink and lora_expand. * - * libref/ref_lora.cpp is the DEFINITION and says what the ops are; this is the same arithmetic over - * the same bytes with the dot products vectorised, which is the only difference and a tolerance - * question (avx_check). What is EXACT, and has to be, is which rows are touched: a row whose slot - * is outside [0, S) is a base row, its `t` row is never written and its `y` row is neither read nor - * written -- not a store of what was read, no store -- because the engine promises that a base row - * is bit for bit what the GEMM wrote. + * libref/ref_lora.cpp defines the ops; this is the same arithmetic over the same bytes with the dot + * products vectorised, a tolerance question (avx_check). Which rows are touched is exact: a row + * whose slot is outside [0, S) is a base row, its `t` row is never written and its `y` row is + * neither read nor stored, so it stays bit for bit what the GEMM wrote. * * x(m, k) is gemm_nt_q's activation value: the code times its group's scale, read through the same * scale-stream rule as avx_gemm.cpp (copied below for the reason avx_moe.cpp gives for its copy). * - * THREADING. A row's dots never split, so its bytes do not depend on the team or on M. A prefill - * has rows to spare and goes wide over them; a decode step has one row and R columns, so there the - * row's activation is decoded once on the calling thread and the team goes wide over the columns. - * Either way each output element is one dotf() over the same two f32 rows. + * Threading: a row's dots never split, so its bytes do not depend on the team or on M. A prefill + * goes wide over rows; a decode step has one row and R columns, so the row is decoded once on the + * calling thread and the team goes wide over the columns. Either way each output element is one + * dotf() over the same two f32 rows. */ #include "avx_common.h" #include "avx_vec.h" diff --git a/libavx/avx_quant.cpp b/libavx/avx_quant.cpp index 6e8a1734..ed409cc8 100644 --- a/libavx/avx_quant.cpp +++ b/libavx/avx_quant.cpp @@ -34,6 +34,8 @@ using namespace avx; #include "avx_had.h" +#include +#include /* Codes are stored with out_row; for RAD_I8 that is the vectorised clamp + cvtps/packs path * (avx_vec.h), bit-exact with libref's nearbyintf-and-clamp. */ @@ -393,6 +395,43 @@ AVX_KERNEL(quant_act_fp8) { return RAD_OK; } +/* ------------------------------------------------------------- quant_cols_fp8 */ +/* libref's ref_quant_cols_fp8: one scale per column over all rows (amax * (1/448), 1 for an + * all-zero column), codes clamp(x * (1/scale), +-448) to nearest even. Two passes over the rows, + * each row's columns at once: the column maxima, then the codes. */ +AVX_KERNEL(quant_cols_fp8) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1], *s = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = numel(x) / n; + if (rows <= 0 || numel(y) < rows * n || numel(s) < n) return RAD_E_SHAPE; + std::vector amax((size_t)n, 0.0f), inv((size_t)n); + { + float* buf = scratch_f32((size_t)n); + for (int64_t r = 0; r < rows; ++r) { + const float* v = in_row(x, rowoff(x, r, n), n, buf); + for (int64_t c = 0; c < n; ++c) + amax[(size_t)c] = std::max(amax[(size_t)c], std::fabs(v[c])); + } + } + for (int64_t c = 0; c < n; ++c) { + const float sc = amax[(size_t)c] > 0.0f ? amax[(size_t)c] * (1.0f / 448.0f) : 1.0f; + inv[(size_t)c] = 1.0f / sc; + stt(s, c * laststride(s), sc); + } + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)n); + float* out = scratch_f32_b((size_t)n); + const float* v = in_row(x, rowoff(x, r, n), n, buf); + for (int64_t c = 0; c < n; ++c) + out[c] = std::min(std::max(v[c] * inv[(size_t)c], -448.0f), 448.0f); + out_row(y, rowoff(y, r, n), n, out); + } + return RAD_OK; +} + /* ------------------------------------------------------------- rmsnorm_quant_fp8 */ /* RMS norm, optional residual add, and quant_act_fp8 in one pass. * diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 32819f3c..832f2127 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -111,6 +111,8 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +/* `add`'s `div` divides the rounded sum (libref's pAdd). */ +static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; /* `cap` is required (as in libref's pMnCap). */ static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") }; @@ -140,7 +142,8 @@ static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD OUT("y") }; static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype") }; -static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y"), + WGT_O("b") }; static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype") }; static const RadOperandSpec oRelSin[] = { OUT("y") }; @@ -167,6 +170,8 @@ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") }; static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; +static const RadParamSpec pQuantCols[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oQuantCols[] = { OPD("x"), OUT("y"), OUT("scale") }; /* ParoQuant's rotation, as libref declares it: the tables come from the "givens" encoding * (abi/rad_encoding.h) and are weight operands, placed with the weight they belong to. */ static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), @@ -252,7 +257,8 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) }; static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"), P_F64O("scale"), P_INTO("max_seqlen"), P_INTO("window"), - P_INTO("cu_div"), P_INTO("block") }; + P_INTO("cu_div"), P_INTO("block"), + P_INTO("window_right") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; @@ -267,7 +273,9 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_ P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), P_F64O("yarn_factor"), P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude"), - P_STRO("ladder") }; + P_STRO("ladder"), P_F64O("llama3_factor"), + P_F64O("llama3_low"), P_F64O("llama3_high"), + P_F64O("llama3_orig") }; static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"), @@ -316,8 +324,9 @@ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_I P_INTO("rotary_dim"), P_F64O("wadd"), P_INTO("v_norm"), P_STRO("sections"), P_STRO("comps") }; -static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"), - WGT("k_w") }; +/* `positions` may be absent at `rotary_dim` 0, and an absent gain is a unit one (libref). */ +static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD_O("positions"), WGT_O("q_w"), + WGT_O("k_w") }; /* ---- mixture of experts ------------------------------------------------------------------- */ static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"), @@ -459,11 +468,23 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") }; /* ---- image generation --------------------------------------------------------------------- */ static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; +static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_INT("gated"), P_STR("dtype") }; static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; +static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), + P_STR("dtype") }; +static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + OPD("cu_seqlens"), INOUT("x"), OUT("z") }; +static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), + OUT_O("z") }; +static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"), + INOUT("x") }; static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), P_INTO("round"), P_STR("dtype") }; static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; @@ -478,7 +499,7 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), INOUT("state"), INOUT_O("preview") }; static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), - P_STR("mode"), P_STR("dtype") }; + P_STR("mode"), P_STR("dtype"), P_INTO("round") }; static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; @@ -490,11 +511,107 @@ static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") }; static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), - P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; -static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"), - OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk"), + P_STRO("pv") }; +static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD_O("kv_cache"), + OPD_O("block_table"), OPD_O("seqused"), OPD("cu_seqlens"), OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"), - OPD_O("k_scale"), OUT("out") }; + OPD_O("k_scale"), OUT("out"), OPD_O("v_scale") }; + +/* ---- video generation (avx_video.cpp), as libref declares it ------------------------------ */ +static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"), + P_INT("pw"), P_STR("mul"), P_STR("add"), + P_STR("dtype") }; +static const RadOperandSpec oPatchUnfold[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileGather[] = { P_INT("M"), P_INT("n"), P_INT("tile"), + P_INT("overlap"), P_INT("frames"), P_INT("period"), + P_INT("n_reg"), P_STR("dtype") }; +static const RadOperandSpec oVtileGather[] = { OPD("x"), WGT("reg"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("scale"), P_INT("pt"), P_INT("skip"), + P_INT("keep"), P_INT("blend"), P_INT("period"), + P_STR("mean"), P_STR("std") }; +static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") }; +static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), + P_INT("period"), P_F64("scale") }; +static const RadOperandSpec oGridPos3[] = { OUT("y") }; +/* ---- video sparse attention (avx_vsa.cpp), as libref declares it ------------------------- */ +static const RadParamSpec pVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale") }; +static const RadOperandSpec oVsaSelect[] = { OPD("q"), OPD("k"), OPD_O("v"), OPD("segs"), + OPD("geom"), OUT("sel"), OUT_O("coarse") }; +/* attn_vsa adds attn_prefix_self's int8 Q.K form at the end: `qk` "i8" with `k_i8` and `k_scale`, + * quant_act_i8g's codes and scales of k at group head_dim. */ +static const RadParamSpec pAttnVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale"), P_STRO("qk"), + P_STRO("pv") }; +static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("segs"), + OPD("geom"), OPD("sel"), OPD_O("coarse"), + OPD_O("gate"), OUT("out"), OPD_O("k_i8"), + OPD_O("k_scale"), OPD_O("v_scale") }; + +/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */ +static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("dil"), P_STRO("act"), P_STR("dtype"), + P_INTO("causal") }; +static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"), + OUT("y"), WGT_O("b") }; +static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"), + P_STR("dtype"), P_INTO("pad"), P_INTO("k") }; +static const RadOperandSpec oConvT1d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("cu_seqlens"), + OUT("y") }; +static const RadParamSpec pSnake[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("log") }; +static const RadOperandSpec oSnake[] = { OPD("x"), WGT("alpha"), OUT("y"), WGT_O("beta") }; +static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"), + P_INTO("log"), P_STR("dtype") }; +static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"), WGT("f_up"), + WGT("f_down"), OPD("cu_seqlens"), OUT("y") }; +static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), + P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), + P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), + P_INTO("sup_hi"), P_F64O("penalty") }; +static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"), + OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; +static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), + P_INT("vocab"), P_INT("off0"), P_F64("scale"), + P_STR("dtype"), P_INTO("round") }; +static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; +static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), + P_INTO("rep"), P_STR("dtype") }; +static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), + OPD("frame"), OPD("status"), INOUT("dst") }; +static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") }; +static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") }; +static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), + P_INTO("rep"), P_INTO("skip") }; +static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"), + OPD("status"), INOUT("dst") }; +static const RadParamSpec pFourier[] = { P_INT("M"), P_INT("n"), P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oFourier[] = { OPD("t"), WGT("w"), OUT("y") }; +static const RadParamSpec pWinInput[] = { P_INT("M"), P_INT("n_lat"), P_INT("n_zero"), + P_INT("n_cond"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oWinInput[] = { OPD("lat"), OPD("cond"), OPD("lat_cu"), OPD("win_lane"), + OPD("pair"), OUT("y") }; +static const RadParamSpec pWinPrep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_INT("ov"), + P_STR("dtype") }; +static const RadOperandSpec oWinPrep[] = { OPD("flags"), OPD("t"), OPD("seed"), OPD("win_index"), + OPD("win_lane"), OPD("pair"), OPD("lat_cu"), + OPD("prev"), INOUT("noise"), INOUT("lat") }; +static const RadParamSpec pWinFinish[] = { P_INT("M"), P_INT("n"), P_INT("n_cond"), P_INT("stride"), + P_INT("ov"), P_STR("dtype") }; +static const RadOperandSpec oWinFinish[] = { OPD("flags"), OPD("pair"), OPD("win_lane"), + OPD("lat_cu"), OPD("cond"), INOUT("lat"), + INOUT("prev"), INOUT("prev_cond") }; +static const RadParamSpec pChanSplit[] = { P_INT("M"), P_INT("n"), P_INT("parts"), P_STR("dtype") }; +static const RadParamSpec pInterleave[] = { P_INT("M"), P_STR("dtype") }; +static const RadOperandSpec oInterleave2[] = { OPD("a"), OPD("b"), OUT("y") }; +static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), + P_INTO("period") }; +static const RadOperandSpec oIota[] = { OUT("y") }; +static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; +static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") }; /* ---- vocabulary edges --------------------------------------------------------------------- */ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), @@ -579,8 +696,9 @@ static const RadOpSchema kSchemas[] = { "x += a side x side position table resampled bilinearly to the row's grid." }, { "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), "x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." }, -{ "add", ARR(pMnD), ARR(oBinary), - "y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows." }, +{ "add", ARR(pAdd), ARR(oBinary), + "y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows. With " + "`div`, y = rd(rd(a + b) / div), bit for bit libref's." }, { "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same broadcast rule as `add`." }, { "mul_weight", ARR(pMulWeight), ARR(oMulWeight), "y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." }, @@ -593,7 +711,7 @@ static const RadOpSchema kSchemas[] = { { "conv2d", ARR(pConv2d), ARR(oConv2d), "segment-wise 2-D convolution over (time, width), channels innermost, optional row mask." }, { "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw), - "segment-wise causal depthwise convolution over time." }, + "segment-wise causal depthwise convolution over time, an optional bias." }, { "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." }, { "conv2d_unfold", ARR(pConv2dUnfold), ARR(oConv2dUnfold), "a convolution's receptive fields as rows, columns in the weight's order." }, @@ -634,6 +752,7 @@ static const RadOpSchema kSchemas[] = { { "quant_act_i8g", ARR(pQuant), ARR(oQuantFp8), "symmetric int8, one f32 scale per `group` contiguous elements, row-major." }, { "quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "symmetric block-scaled E4M3 quantiser." }, +{ "quant_cols_fp8", ARR(pQuantCols), ARR(oQuantCols), "E4M3 with one scale per column." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: " "the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." }, @@ -682,7 +801,9 @@ static const RadOpSchema kSchemas[] = { { "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged), "paged causal / sliding-window attention, any query length, online-softmax so one pass over the " "cache suffices." }, -{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." }, +{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), + "dense varlen attention over cu_seqlens; a non-causal window may reach further right " + "(`window_right`)." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." }, { "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey), @@ -749,8 +870,9 @@ static const RadOpSchema kSchemas[] = { { "ln_mod", ARR(pLnMod), ARR(oLnMod), "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's " "modulation row of `s` ([n_seq, >= n] at its own pitch)." }, -{ "gate_add", ARR(pMnD), ARR(oGateAdd), - "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), bit for bit libref's." }, +{ "gate_add", ARR(pGateAdd), ARR(oGateAdd), + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), or with `act` none the gate g itself, bit for bit " + "libref's." }, { "timestep_embed", ARR(pTimestep), ARR(oTimestep), "the sinusoidal timestep embedding [cos | sin], libref's libm calls; `round` 1 takes t through " "bf16 at scale and back first." }, @@ -767,7 +889,8 @@ static const RadOpSchema kSchemas[] = { "one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the " "repaint's kept region; libref's roundings bit for bit." }, { "chan_affine", ARR(pChanAffine), ARR(oUnary), - "a per-channel affine from two lists of n bf16 values, `fma` or `inv`." }, + "a per-channel affine from two lists of n bf16 values, `fma` or `inv`; `round` 0 keeps the " + "lists and the arithmetic in f32, rounded once." }, { "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc), "an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the " "input upsampled nearest-neighbour, `pad` same or down." }, @@ -786,6 +909,73 @@ static const RadOpSchema kSchemas[] = { { "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS), "attention over `seqused[s]` prefix positions in the paged cache and the step's own rows, " "flash-attention tiles; `qk` \"i8\" is the int8 score form (docs/OPS.md)." }, +{ "rms_mod", ARR(pRmsMod), ARR(oRmsMod), + "the gated residual (no tanh), then an RMS norm with a gain times bf16(1 + scale row) plus the " + "shift row, `s` holding [shift | scale]; libref's roundings." }, +{ "rms_mod_quant_fp8", ARR(pRmsModQ), ARR(oRmsModQ), + "rms_mod with its norm chain in bf16, then the E4M3 codes and scales of that row." }, +{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0), + "x = r x + (1 - r)(x + (1 - t) v), r = sigma_next / sigma, each step one f32 rounding, bit for " + "bit libref's." }, +{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold), + "patch rows to denormalised voxel rows, f32(f32(x * mul) + add), bit for bit libref's." }, +{ "vtile_gather", ARR(pVtileGather), ARR(oVtileGather), + "a video decoder's tiles out of the latent's voxel rows, then the register rows and zeros." }, +{ "vtile_stitch", ARR(pVtileStitch), ARR(oVtileStitch), + "decoded tiles blended into frames, the chunk overlap blended and kept, RGB bytes out; bit for " + "bit libref's." }, +{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3), + "a video decoder's rotary positions over its tiles, [3, >= M] at the operand's row pitch, bit " + "for bit libref's." }, +{ "vsa_select", ARR(pVsa), ARR(oVsaSelect), + "video sparse attention's tile selection over libref's tiles: the k video tiles of largest " + "pooled score per video query tile, ascending, bit for bit libref's; with `coarse`, the softmax " + "over every tile's score times the tiles' means of v." }, +{ "attn_vsa", ARR(pAttnVsa), ARR(oAttnVsa), + "video sparse attention over libref's tiles: prefix queries dense, video queries the prefix " + "and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded " + "to its dtype." }, +{ "conv1d", ARR(pConv1d), ARR(oConv1d), + "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's " + "[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside " + "each sequence; `res` added after the bias, then `act` none, tanh or clamp. GEMMs over bands " + "of patch rows." }, +{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d), + "a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` " + "((k - stride) / 2, or 0 the causal form), each sequence growing `stride` times; one GEMM a " + "phase." }, +{ "snake", ARR(pSnake), ARR(oSnake), + "x + sin(alpha x)^2 / (alpha + 1e-9) per channel, or SnakeBeta's x + sin(alpha x)^2 / " + "(beta + 1e-9) with `beta`, both read as logarithms with `log` 1; a polynomial sine." }, +{ "snake_aa", ARR(pSnakeAa), ARR(oSnakeAa), + "BigVGAN's alias-free SnakeBeta: replicate-padded upsampling by `f_up`, SnakeBeta, " + "replicate-padded filtering by `f_down` at stride `ratio`; a polynomial sine." }, +{ "cfg_topk_sample", ARR(pCfgTopk), ARR(oCfgTopk), + "one guided top-k pick a lane by inverse CDF over rad_philox_uniform_s, with a suppressed id " + "range, a repetition penalty over each lane's history and per-lane guidance; bit for bit " + "libref's." }, +{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed), + "a frame's embedding from code-major residual codes, libref's roundings (`round` 1: one)." }, +{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), + "a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." }, +{ "end_status", ARR(pEndStatus), ARR(oEndStatus), + "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." }, +{ "frame_store", ARR(pFrameStore), ARR(oFrameStore), + "a frame's codes into its lane's history, code-major rows over the lane's frames." }, +{ "resample_nearest", ARR(pMnD), ARR(oUnary), + "rows resampled nearest-neighbour, the row counts read off the operands." }, +{ "fourier_embed", ARR(pFourier), ARR(oFourier), + "[cos(2 pi t w) | sin(2 pi t w)], libref's libm calls and roundings." }, +{ "win_input", ARR(pWinInput), ARR(oWinInput), + "a denoiser's input [lat | zeros | cond] from each window entry's lane." }, +{ "win_prep", ARR(pWinPrep), ARR(oWinPrep), + "a window step's noise and overlap binding, bit for bit libref's." }, +{ "win_finish", ARR(pWinFinish), ARR(oWinFinish), + "a window's end and the overlap it hands on." }, +{ "chan_split", ARR(pChanSplit), ARR(oUnary), "channel groups to sequences." }, +{ "interleave2", ARR(pInterleave), ARR(oInterleave2), "two streams interleaved, y [rows, 2]." }, +{ "iota", ARR(pIota), ARR(oIota), "y[i] = start + i * step." }, +{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." }, { "embed_lookup", ARR(pEmbedM), ARR(oEmbed), "embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." }, { "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), @@ -1014,6 +1204,8 @@ SIMPLE("avx_had_quant_act_i8", "had_quant_act_i8", "quant", L(had_quant_act_i8)), SIMPLE("avx_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale", L(quant_act_fp8)), +SIMPLE("avx_quant_cols_fp8", "quant_cols_fp8", "quant", "E4M3 with one scale per column", + "float in, fp8_e4m3 out, f32 scale", L(quant_cols_fp8)), SIMPLE("avx_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", @@ -1141,7 +1333,8 @@ SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_s SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry's scale row)", DT_FLOAT, L(ln_mod)), -SIMPLE("avx_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, L(gate_add)), +SIMPLE("avx_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT, + L(gate_add)), SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm", "gated residual, adaptive norm and the E4M3 quantiser in one pass", "float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)), @@ -1174,6 +1367,63 @@ SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn", "attention over a paged prefix and the step's own rows, flash-attention tiles", "bf16 or f32 q, k, v and cache; int8 score form", L(attn_prefix_self)), +SIMPLE("avx_rms_mod", "rms_mod", "norm", + "gated residual, RMS norm with a gain times (1 + scale row) plus a shift row", DT_FLOAT, + L(rms_mod)), +SIMPLE("avx_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm", + "gated residual, modulated RMS norm and the E4M3 quantiser in one pass", DT_FLOAT, + L(rms_mod_quant_fp8)), +SIMPLE("avx_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate", + DT_FLOAT, L(flow_x0_step)), +SIMPLE("avx_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows", + DT_FLOAT, L(patch_unfold)), +SIMPLE("avx_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent", + DT_FLOAT, L(vtile_gather)), +SIMPLE("avx_vtile_stitch", "vtile_stitch", "elem", + "decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT, + L(vtile_stitch)), +SIMPLE("avx_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles", + DT_FLOAT, L(grid_pos3)), +SIMPLE("avx_vsa_select", "vsa_select", "attn", + "video sparse attention's top-k tiles by pooled score, and the coarse branch", + "float q, k, v and coarse; i32 segs, geom and sel", L(vsa_select)), +SIMPLE("avx_attn_vsa", "attn_vsa", "attn", + "block-sparse attention over the prefix and selected video tiles, the gated coarse term", + "float q, k, v, coarse, gate and out; i32 segs, geom and sel", L(attn_vsa)), + +SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows", + DT_FLOAT, L(conv1d)), +SIMPLE("avx_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution, one GEMM a phase", + DT_FLOAT, L(conv_t1d)), +SIMPLE("avx_snake", "snake", "elem", "the snake activation", DT_FLOAT, L(snake)), +SIMPLE("avx_snake_aa", "snake_aa", "elem", "the alias-free SnakeBeta: upsample, snake, downsample", + DT_FLOAT, L(snake_aa)), +SIMPLE("avx_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick a lane", DT_FLOAT, + L(cfg_topk_sample)), +SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes", + DT_FLOAT, L(rvq_embed)), +SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem", + "a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)), +SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, + L(end_status)), +SIMPLE("avx_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY, + L(frame_store)), +SIMPLE("avx_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour", + DT_ANY, L(resample_nearest)), +SIMPLE("avx_fourier_embed", "fourier_embed", "elem", "random Fourier features of a time", + DT_FLOAT, L(fourier_embed)), +SIMPLE("avx_win_input", "win_input", "elem", "a denoiser's input from the window states", + DT_FLOAT, L(win_input)), +SIMPLE("avx_win_prep", "win_prep", "elem", "a window step's noise and overlap", DT_FLOAT, + L(win_prep)), +SIMPLE("avx_win_finish", "win_finish", "elem", "a window's end and the overlap it hands on", + DT_FLOAT, L(win_finish)), +SIMPLE("avx_chan_split", "chan_split", "elem", "channel groups to sequences", DT_ANY, + L(chan_split)), +SIMPLE("avx_interleave2", "interleave2", "elem", "two streams interleaved", DT_ANY, + L(interleave2)), +SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iota)), +SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)), SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)), /* Its layout hook only validates: the table is read as stored and other encodings are refused diff --git a/libavx/avx_video.cpp b/libavx/avx_video.cpp new file mode 100644 index 00000000..0ad422c9 --- /dev/null +++ b/libavx/avx_video.cpp @@ -0,0 +1,353 @@ +/* avx_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video + * generation"): the latent's patch rows unfolded to voxels, the tiles a video decoder runs over, + * gathered from the latent and stitched back into frames, and the rotary positions of a tile's + * tokens. + * + * Bit-exact with libref (libref/ref_video.cpp): they are copies and roundings, and a seed must + * give the same video bytes on both host libraries. Where libref multiplies and then adds in two + * roundings, `keep` stops the compiler from fusing the pair (this plugin is built with + * -ffp-contract=fast, libref without contraction); the stitch's bf16 blends are passes of whole + * rows through x's dtype (`narrow_row`), so a product is rounded before the sum reads it. + */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include + +using namespace avx; + +namespace { + +inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); } + +/* v[0, n) rounded through dtype `dt` in place, as a store and reload rounds it. `tmp` holds n + * floats. */ +inline void narrow_row(uint32_t dt, float* v, int64_t n, float* tmp) { + if (dt == RAD_F32) return; + row_from_f32(dt, v, tmp, n); + row_to_f32(dt, tmp, v, n); +} + +/* A value the compiler may not fuse into the next add. */ +#if AVX_LEVEL == 0 +inline float keep(float x) { __asm__("" : "+x"(x)); return x; } +#elif AVX_LEVEL == 3 +inline float keep(float x) { __asm__("" : "+v"(x)); return x; } +#else +inline float keep(float x) { __asm__("" : "+x"(x)); return x; } +#endif + +/* The f32 values of a space-separated list (libref's parse_f32_list): up to `cap` into out, the + * count returned whatever it is. */ +int64_t parse_f32(const char* s, float* out, int64_t cap) { + int64_t k = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (k < cap) out[k] = (float)v; + ++k; + s = end; + } + return k; +} + +/* libref's split_tiles: the tile starts and overlaps over `len` latent units. */ +bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector* start, + std::vector* ov) { + start->clear(); + ov->clear(); + if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return false; + if (tile >= len) { + start->push_back(0); + return len == tile; + } + int64_t nt = (len + tile - 1) / tile; + while (tile * nt - overlap * (nt - 1) - len < 0) ++nt; + ov->assign((size_t)(nt - 1), overlap); + const int64_t rem = tile * nt - overlap * (nt - 1) - len; + for (int64_t i = 0; i < rem; ++i) (*ov)[(size_t)(i % (nt - 1))] += 1; + start->push_back(0); + for (int64_t i = 0; i + 1 < nt; ++i) start->push_back(start->back() + tile - (*ov)[(size_t)i]); + return true; +} + +/* A row copied between operands, converted through f32 as libref's element loop is. Whole-byte + * float rows of one dtype are copied as bytes, which is the same thing for every non-NaN value. */ +inline void copy_row(const RadTensor* src, int64_t sb, const RadTensor* dst, int64_t db, int64_t n, + float* scr) { + const uint32_t dt = src->dtype; + const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 || + dt == RAD_F8E5M2; + if (flt && dt == dst->dtype && laststride(src) == 1 && laststride(dst) == 1) { + const size_t w = (size_t)(rad_dtype_bits(dt) / 8); + std::memcpy((char*)dst->data + (size_t)db * w, (const char*)src->data + (size_t)sb * w, + (size_t)n * w); + return; + } + out_row(dst, db, n, in_row(src, sb, n, scr)); +} + +/* out[e] = rd(rd(a[e] wa) + rd(b[e] wb)) over e < cnt, pixels of three values with a weight pair + * each (`ws` 1) or one pair for every pixel (`ws` 0), rd a pass through `dt`. `out` may be `b`; + * `p2` and `tmp` hold cnt floats. */ +void blend_rgb(const float* a, const float* wa, const float* b, const float* wb, int64_t ws, + int64_t cnt, float* out, float* p2, float* tmp, uint32_t dt) { + for (int64_t e = 0; e < cnt; ++e) { + p2[e] = b[e] * wb[(e / 3) * ws]; + out[e] = a[e] * wa[(e / 3) * ws]; + } + narrow_row(dt, out, cnt, tmp); + narrow_row(dt, p2, cnt, tmp); + for (int64_t e = 0; e < cnt; ++e) out[e] += p2[e]; + narrow_row(dt, out, cnt, tmp); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ patch_unfold */ +/* Patch rows to denormalised voxel rows, f32(f32(x * mul[c]) + add[c]) (libref): a task is a + * patch, its row read once and dealt into its pt ph pw voxel rows. */ +AVX_KERNEL(patch_unfold) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0); + const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0); + const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", ""); + /* Each number takes at least two characters but the last, so this bounds the count. */ + const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2); + float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float)); + float *mul = lists, *add = lists + cap; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32(ms, mul, cap) != C || + parse_f32(as, add, cap) != C || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t F = at(G, 0), Hp = at(G, 1), Wp = at(G, 2); + if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE; + const int64_t vol = pt * ph * pw, Hv = Hp * ph, Wv = Wp * pw, K = C * vol; + if (rows_of(Y, C) < F * pt * Hv * Wv || rows_of(X, K) < F * Hp * Wp) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(F * Hp * Wp * K >= AVX_PAR_MIN) + for (int64_t pi = 0; pi < F * Hp * Wp; ++pi) { + float* buf = scratch_f32((size_t)(K + C + 32)); + float *xs = buf, *row = buf + K + 16; + const float* xr = in_row(X, rowoff(X, pi, K), K, xs); + const int64_t f = pi / (Hp * Wp), i = (pi / Wp) % Hp, j = pi % Wp; + for (int64_t sub = 0; sub < vol; ++sub) { + const int64_t ta = sub / (ph * pw), yb = (sub / pw) % ph, xd = sub % pw; + for (int64_t c = 0; c < C; ++c) row[c] = keep(xr[c * vol + sub] * mul[c]) + add[c]; + const int64_t r = ((f * pt + ta) * Hv + i * ph + yb) * Wv + j * pw + xd; + out_row(Y, rowoff(Y, r, C), C, row); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ grid_pos3 */ +/* A tile's rotary positions, f32(scale) g(c, n), g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1) + * (libref): one value an axis index, taken once a launch. */ +AVX_KERNEL(grid_pos3) { + if (!rad_args_have(a, 1)) return RAD_E_INVAL; + const RadTensor* Y = &a->t[0]; + const int64_t T = p_int(a, "T", 0), H = p_int(a, "H", 0), W = p_int(a, "W", 0); + const int64_t period = p_int(a, "period", 0); + const float scale = p_f32(a, "scale", 1.0f); + if (T <= 0 || H <= 0 || W <= 0 || period < T * H * W || Y->rank != 2 || Y->shape[0] < 3) + return RAD_E_SHAPE; + const int64_t M = Y->shape[1], rs = Y->stride[0], cs = Y->stride[1]; + if (M <= 0) return RAD_E_SHAPE; + float* g = (float*)scratch_raw((size_t)(T + H + W + 16) * sizeof(float)); + auto axis = [scale](int64_t c, int64_t n) { + const float q = ((float)c + 0.5f) / (float)n; + return scale * (keep(2.0f * q) - 1.0f); + }; + for (int64_t c = 0; c < T; ++c) g[c] = axis(c, T); + for (int64_t c = 0; c < H; ++c) g[T + c] = axis(c, H); + for (int64_t c = 0; c < W; ++c) g[T + H + c] = axis(c, W); + AVX_PARALLEL_FOR_IF(M * 3 >= AVX_PAR_MIN) + for (int64_t m = 0; m < M; ++m) { + const int64_t k = m % period; + const bool tok = k < T * H * W; + stt(Y, m * cs, tok ? g[k / (H * W)] : 0.0f); + stt(Y, rs + m * cs, tok ? g[T + (k / W) % H] : 0.0f); + stt(Y, 2 * rs + m * cs, tok ? g[T + H + k % W] : 0.0f); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_gather */ +/* A video decoder's tiles out of the latent's voxel rows, then the register rows and zeros + * (libref): one copied row a y row. */ +AVX_KERNEL(vtile_gather) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *R = &a->t[1], *G = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), frames = p_int(a, "frames", 0); + const int64_t period = p_int(a, "period", 0), n_reg = p_int(a, "n_reg", 0); + const int64_t vox = frames * tile * tile; + if (n <= 0 || tile <= 0 || frames <= 0 || n_reg < 0 || period < vox + n_reg || + numel(G) < 3 || rows_of(R, n) < n_reg) + return RAD_E_SHAPE; + const int64_t H = at(G, 1), W = at(G, 2); + std::vector sy, sx, oy, ox; + if (at(G, 0) != frames || !split_tiles(H, tile, overlap, &sy, &oy) || + !split_tiles(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nw = (int64_t)sx.size(), rows = (int64_t)sy.size() * nw * period; + if (rows_of(Y, n) < rows || rows_of(X, n) < frames * H * W) return RAD_E_SHAPE; + const int64_t* py = sy.data(); + const int64_t* px = sx.data(); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t row = 0; row < rows; ++row) { + float* scr = scratch_f32((size_t)n + 16); + const int64_t k = row / period, p = row % period, yb = rowoff(Y, row, n); + if (p < vox) { + const int64_t t = p / (tile * tile), ty = (p / tile) % tile, tx = p % tile; + const int64_t src = (t * H + py[k / nw] + ty) * W + px[k % nw] + tx; + copy_row(X, rowoff(X, src, n), Y, yb, n, scr); + } else if (p < vox + n_reg) { + copy_row(R, rowoff(R, p - vox, n), Y, yb, n, scr); + } else { + for (int64_t c = 0; c < n; ++c) scr[c] = 0.0f; + out_row(Y, yb, n, scr); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_stitch */ +/* A decoded chunk's tiles stitched into frames, the chunk overlap blended and kept, RGB bytes out + * (libref's rule and roundings). A task is one pixel row of one frame: each tile column's line of + * the owner tile is read out of x, blended with the tile above's line and then the left tile's + * (both as decoded), a whole line at a time, every product and sum a pass through x's dtype. The + * kept frames are made first, reading `prev`; the frames that refill it after, in a second pass, + * so no task reads a row another has rewritten. */ +AVX_KERNEL(vtile_stitch) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *PV = &a->t[2], *Y = &a->t[3]; + const int64_t tile = p_int(a, "tile", 0), overlap = p_int(a, "overlap", 0); + const int64_t S = p_int(a, "scale", 0), pt = p_int(a, "pt", 0), skip = p_int(a, "skip", 0); + const int64_t keep_n = p_int(a, "keep", 0), blend = p_int(a, "blend", 0); + const int64_t period = p_int(a, "period", 0); + float mean[3], stdv[3]; + if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep_n <= 0 || blend < 0 || + blend > keep_n || parse_f32(p_str(a, "mean", ""), mean, 3) != 3 || + parse_f32(p_str(a, "std", ""), stdv, 3) != 3 || numel(G) < 5 || Y->dtype != RAD_U8) + return RAD_E_SHAPE; + const int64_t frames = at(G, 0), H = at(G, 1), W = at(G, 2); + const bool first = at(G, 3) != 0, last = at(G, 4) != 0; + std::vector sy, sx, oy, ox; + if (frames <= 0 || 2 * skip + keep_n + blend > frames * pt || period < frames * tile * tile || + !split_tiles(H, tile, overlap, &sy, &oy) || !split_tiles(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(), cols = 3 * pt * S * S; + if (rows_of(X, cols) < nh * nw * period) return RAD_E_SHAPE; + const int64_t Hp = H * S, Wp = W * S, npx = Hp * Wp; + const int64_t fout = keep_n + (last ? blend : 0); + if (rows_of(Y, 3) < fout * npx || (blend > 0 && rows_of(PV, 3) < blend * npx)) + return RAD_E_SHAPE; + std::vector own_y((size_t)Hp); + for (int64_t Yp = 0, i = 0; Yp < Hp; ++Yp) { + while (i + 1 < nh && Yp >= sy[(size_t)(i + 1)] * S) ++i; + own_y[(size_t)Yp] = i; + } + const uint32_t dt = X->dtype; + const int64_t TW = tile * S, RW = Wp * 3, TW3 = TW * 3; + const int64_t *psy = sy.data(), *psx = sx.data(), *poy = oy.data(), *pox = ox.data(); + const int64_t* pown = own_y.data(); + auto wb = [dt](int64_t p, int64_t e) { return narrow1(dt, (float)p / (float)e); }; + auto wa = [dt](int64_t p, int64_t e) { + return narrow1(dt, 1.0f - narrow1(dt, (float)p / (float)e)); + }; + + /* Tile (i, j)'s decoded line at row ly of clip frame fc: out[lx * 3 + c], lx < TW. */ + auto tile_line = [&](int64_t i, int64_t j, int64_t ly, int64_t fc, float* out) { + const int64_t base = (i * nw + j) * period + ((fc / pt) * tile + ly / S) * tile; + const int64_t xs = laststride(X); + for (int64_t tx = 0; tx < tile; ++tx) { + const int64_t xb = rowoff(X, base + tx, cols); + for (int64_t c = 0; c < 3; ++c) { + const int64_t col0 = ((c * pt + fc % pt) * S + ly % S) * S; + for (int64_t d = 0; d < S; ++d) + out[(tx * S + d) * 3 + c] = ldt(X, xb + (col0 + d) * xs); + } + } + }; + /* The stitched pixel row Yp of clip frame fc into row[0, RW). `l0`, `l1` hold TW3 floats, + * `w` 2 TW, `p2` and `tmp` RW. */ + auto stitch_row = [&](int64_t fc, int64_t Yp, float* row, float* l0, float* l1, float* w, + float* p2, float* tmp) { + const int64_t i = pown[Yp], ly = Yp - psy[i] * S; + const int64_t ev = i > 0 ? poy[i - 1] * S : 0; + const float wv[2] = { ly < ev ? wa(ly, ev) : 0.0f, ly < ev ? wb(ly, ev) : 0.0f }; + for (int64_t j = 0; j < nw; ++j) { + const int64_t x0 = psx[j] * S, x1 = j + 1 < nw ? psx[j + 1] * S : Wp; + tile_line(i, j, ly, fc, l0); + if (ly < ev) { + tile_line(i - 1, j, ly + TW - ev, fc, l1); + blend_rgb(l1, &wv[0], l0, &wv[1], 0, TW3, l0, p2, tmp, dt); + } + const int64_t eh = j > 0 ? std::min(pox[j - 1] * S, x1 - x0) : 0; + if (eh > 0) { + const int64_t full = pox[j - 1] * S; + tile_line(i, j - 1, ly, fc, l1); + for (int64_t lx = 0; lx < eh; ++lx) { + w[lx] = wa(lx, full); + w[TW + lx] = wb(lx, full); + } + blend_rgb(l1 + (TW - full) * 3, w, l0, w + TW, 1, eh * 3, l0, p2, tmp, dt); + } + std::memcpy(row + x0 * 3, l0, (size_t)((x1 - x0) * 3) * sizeof(float)); + } + }; + /* Frame f's pixel row Yp as bytes. */ + auto bytes = [&](int64_t f, int64_t Yp, const float* row) { + for (int64_t X0 = 0; X0 < Wp; ++X0) { + const int64_t yb = rowoff(Y, f * npx + Yp * Wp + X0, 3); + for (int64_t c = 0; c < 3; ++c) { + float p = keep(row[X0 * 3 + c] * stdv[c]) + mean[c]; + p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p); + stt(Y, yb + c * laststride(Y), p * 255.0f); + } + } + }; + const size_t need = (size_t)(3 * RW + 2 * TW3 + 2 * TW + 96); + + AVX_PARALLEL_FOR_IF(keep_n * npx * 3 * 8 >= AVX_PAR_MIN) + for (int64_t task = 0; task < keep_n * Hp; ++task) { + const int64_t k = task / Hp, Yp = task % Hp; + float* buf = scratch_f32(need); + float *row = buf, *p2 = row + RW + 16, *tmp = p2 + RW + 16, *l0 = tmp + RW + 16; + float *l1 = l0 + TW3 + 16, *w = l1 + TW3 + 16; + stitch_row(skip + k, Yp, row, l0, l1, w, p2, tmp); + if (!first && k < blend) { + float* pr = l0; /* the overlap row, a line's worth at a time */ + const float pw[2] = { wa(k, blend), wb(k, blend) }; + for (int64_t x0 = 0; x0 < Wp; x0 += TW) { + const int64_t cnt = std::min(TW, Wp - x0); + for (int64_t e = 0; e < cnt * 3; ++e) { + const int64_t pxi = k * npx + Yp * Wp + x0 + e / 3; + pr[e] = ldt(PV, rowoff(PV, pxi, 3) + (e % 3) * laststride(PV)); + } + blend_rgb(pr, &pw[0], row + x0 * 3, &pw[1], 0, cnt * 3, row + x0 * 3, p2, tmp, dt); + } + } + bytes(k, Yp, row); + } + + AVX_PARALLEL_FOR_IF(blend * npx * 3 * 8 >= AVX_PAR_MIN) + for (int64_t task = 0; task < blend * Hp; ++task) { + const int64_t k = task / Hp, Yp = task % Hp; + float* buf = scratch_f32(need); + float *row = buf, *p2 = row + RW + 16, *tmp = p2 + RW + 16, *l0 = tmp + RW + 16; + float *l1 = l0 + TW3 + 16, *w = l1 + TW3 + 16; + stitch_row(2 * skip + keep_n + k, Yp, row, l0, l1, w, p2, tmp); + if (last) bytes(keep_n + k, Yp, row); + for (int64_t X0 = 0; X0 < Wp; ++X0) { + const int64_t pb = rowoff(PV, k * npx + Yp * Wp + X0, 3); + for (int64_t c = 0; c < 3; ++c) stt(PV, pb + c * laststride(PV), row[X0 * 3 + c]); + } + } + return RAD_OK; +} diff --git a/libavx/avx_vsa.cpp b/libavx/avx_vsa.cpp new file mode 100644 index 00000000..63674b97 --- /dev/null +++ b/libavx/avx_vsa.cpp @@ -0,0 +1,705 @@ +/* avx_vsa.cpp -- video sparse attention (docs/OPS.md, "Video sparse attention"): vsa_select's + * top-k of pooled tile scores and its coarse branch, and attn_vsa's block-sparse attention. + * + * The tiles are libref's (libref/ref_vsa.cpp), read off the same operands with the same refusals + * in the same order: each dense segment of `segs` in chunks of tile_t tile_h tile_w rows, then the + * boxes over the video grid `geom` describes, a tile's rows in its (t, h, w) raster order. + * + * vsa_select's `sel` is libref's bit for bit: one tile more or less changes the keys a whole query + * tile sees. The tile means are summed row by row in raster order with the vector lanes across + * head_dim, each lane libref's sum, then divided by the size; a score's dot runs over d in + * ascending order with each product rounded before the add (the lanes across tiles, `keep` + * stopping the pair from fusing), then the scale; the selection is libref's threshold rule. The + * coarse branch takes the vector exp and is held to the tolerance. + * + * attn_vsa: a task is one (head, query tile), up to 64 of its rows at a time. Per visible key tile, + * 64 keys at a time are widened and packed (K as Kt [hd][64], V as [64][hp]), then S = Q K^T as + * broadcast-against-tile products, the online softmax (the running max moved at tile boundaries) + * and O += P V, avx_gen_attn.cpp's f32 form. Results differ from libref's two-pass softmax in + * summation order and the rescales' roundings, within the attention tolerance. Each output row is + * one task's, so they do not depend on the thread count. + */ +#include "avx_vec.h" +#include "avx_common.h" +#include "rad_runtime.h" /* RAD_VGEOM_* */ + +#include +#include + +using namespace avx; + +namespace { + +/* ================================================================== the tiles (libref's) */ +inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); } + +/* `sparsity` at full precision: k is computed from it in f64. NaN when absent. */ +double p_f64(const RadArgs* a, const char* k) { + const RadParam* p = p_find(a, k); + if (!p) return NAN; + if (p->kind == RAD_P_F64) return p->dval; + if (p->kind == RAD_P_STR && p->sval) return std::strtod(p->sval, nullptr); + if (p->kind == RAD_P_INT) return (double)p->ival; + return NAN; +} + +struct Tiles { + int64_t R = 0, v0 = 0; + int64_t tt = 0, th = 0, tw = 0; + int64_t F = 0, Hp = 0, Wp = 0, nb = 0, nc = 0; + int64_t P = 0, V = 0, N = 0, k = 0; + std::vector start, len; +}; + +int tiles_of(const RadArgs* a, const RadTensor* segs, const RadTensor* geom, int64_t rows, + Tiles* g) { + g->tt = p_int(a, "tile_t", 0); + g->th = p_int(a, "tile_h", 0); + g->tw = p_int(a, "tile_w", 0); + const int64_t patch = p_int(a, "patch", 0); + const double sparsity = p_f64(a, "sparsity"); + if (g->tt <= 0 || g->th <= 0 || g->tw <= 0 || patch <= 0 || + !(sparsity >= 0.0 && sparsity < 1.0)) + return RAD_E_SHAPE; + const int64_t n_seg = numel(segs) - 1; + if (n_seg < 1 || numel(geom) <= RAD_VGEOM_LAT_W || at(segs, 0) != 0) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seg; ++s) + if (at(segs, s + 1) < at(segs, s)) return RAD_E_SHAPE; + g->R = at(segs, n_seg); + g->v0 = at(segs, n_seg - 1); + if (g->R <= 0 || g->R > rows) return RAD_E_SHAPE; + g->F = at(geom, RAD_VGEOM_LAT_FRAMES); + g->Hp = at(geom, RAD_VGEOM_LAT_H) / patch; + g->Wp = at(geom, RAD_VGEOM_LAT_W) / patch; + const int64_t vr = g->R - g->v0; + if (g->F <= 0 || g->Hp <= 0 || g->Wp <= 0 || g->F > vr || g->Hp > vr || g->Wp > vr || + g->F * g->Hp * g->Wp != vr) + return RAD_E_SHAPE; + const int64_t TT = g->tt * g->th * g->tw; + g->start.clear(); + g->len.clear(); + for (int64_t s = 0; s + 1 < n_seg; ++s) + for (int64_t r = at(segs, s), e = at(segs, s + 1); r < e; r += TT) { + g->start.push_back(r); + g->len.push_back(std::min(TT, e - r)); + } + g->nb = (g->Hp + g->th - 1) / g->th; + g->nc = (g->Wp + g->tw - 1) / g->tw; + g->P = (int64_t)g->start.size(); + g->V = (g->F + g->tt - 1) / g->tt * g->nb * g->nc; + g->N = g->P + g->V; + const double keep = (1.0 - sparsity) * (double)g->V; + g->k = std::max(1, std::min((int64_t)std::ceil(keep), g->V)); + return RAD_OK; +} + +struct Box { int64_t t0, t1, h0, h1, w0, w1; }; +Box box_of(const Tiles& g, int64_t j) { + const int64_t b = j - g.P, c = b % g.nc, bh = (b / g.nc) % g.nb, ta = b / (g.nc * g.nb); + return { ta * g.tt, std::min(g.F, (ta + 1) * g.tt), bh * g.th, std::min(g.Hp, (bh + 1) * g.th), + c * g.tw, std::min(g.Wp, (c + 1) * g.tw) }; +} + +int64_t tile_size(const Tiles& g, int64_t j) { + if (j < g.P) return g.len[(size_t)j]; + const Box x = box_of(g, j); + return (x.t1 - x.t0) * (x.h1 - x.h0) * (x.w1 - x.w0); +} + +/* The n-th row of tile j in its raster order. */ +int64_t row_at(const Tiles& g, int64_t j, int64_t n) { + if (j < g.P) return g.start[(size_t)j] + n; + const Box x = box_of(g, j); + const int64_t dh = x.h1 - x.h0, dw = x.w1 - x.w0; + const int64_t t = x.t0 + n / (dh * dw), h = x.h0 + (n / dw) % dh, w = x.w0 + n % dw; + return g.v0 + (t * g.Hp + h) * g.Wp + w; +} + +/* fn(row) for every row of tile j, in its raster order. */ +template +void tile_rows(const Tiles& g, int64_t j, Fn&& fn) { + if (j < g.P) { + for (int64_t r = g.start[(size_t)j], e = r + g.len[(size_t)j]; r < e; ++r) fn(r); + return; + } + const Box x = box_of(g, j); + for (int64_t t = x.t0; t < x.t1; ++t) + for (int64_t h = x.h0; h < x.h1; ++h) + for (int64_t w = x.w0; w < x.w1; ++w) fn(g.v0 + (t * g.Hp + h) * g.Wp + w); +} + +/* An operand read as [rows, n_head, head_dim] (libref's reading). */ +struct Heads { + const RadTensor* t; + int64_t rs, hs, ds; +}; +Heads heads_of(const RadTensor* t, int64_t nh, int64_t hd) { + Heads v{ t, 0, 0, 0 }; + v.ds = t->rank >= 2 ? t->stride[t->rank - 1] : 1; + v.hs = t->rank >= 3 ? t->stride[t->rank - 2] : hd * v.ds; + v.rs = row_stride(t, nh * hd); + return v; +} + +int64_t heads_in(const RadTensor* q, int64_t hd) { + if (q->rank >= 3) return q->shape[q->rank - 1] == hd ? q->shape[q->rank - 2] : 0; + if (q->rank == 2) return q->shape[1] % hd == 0 ? q->shape[1] / hd : 0; + return 0; +} + +int64_t tiles_cap(const RadTensor* t, int64_t cols, int64_t nh) { + const int64_t r = rows_of(t, cols); + return r % nh == 0 ? r / nh : 0; +} + +/* libref's selection order: the larger score first, NaN above every number, equal scores tied. */ +inline bool above(float a, float b) { + if (a != a) return b == b; + return b == b && a > b; +} + +/* A product the compiler may not fuse into the next add: libref rounds every product before the + * sum (it is built without contraction, this plugin with -ffp-contract=fast). */ +inline vf keep(vf x) { +#if AVX_LEVEL == 3 + __asm__("" : "+v"(x)); +#else + __asm__("" : "+x"(x)); +#endif + return x; +} +#if AVX_LEVEL >= 1 +inline float keep(float x) { +#if AVX_LEVEL == 3 + __asm__("" : "+v"(x)); +#else + __asm__("" : "+x"(x)); +#endif + return x; +} +#endif + +inline void axpy(float* acc, const float* x, float w, int64_t n) { + const vf vw = vf_set1(w); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(acc + i, vf_fma(vw, vf_loadu(x + i), vf_loadu(acc + i))); + for (; i < n; ++i) acc[i] += w * x[i]; +} + +/* The checks both ops share, in libref's order. */ +struct Call { + Tiles g; + int64_t hd = 0, nh = 0, kc = 0, scap = 0, ccap = 0; +}; + +int common(const RadArgs* a, const RadTensor* q, const RadTensor* segs, const RadTensor* geom, + Call* c) { + c->hd = p_int(a, "head_dim", 0); + if (c->hd <= 0) return RAD_E_SHAPE; + c->nh = heads_in(q, c->hd); + if (c->nh <= 0) return RAD_E_SHAPE; + return tiles_of(a, segs, geom, numel(q) / (c->nh * c->hd), &c->g); +} + +int caps(const RadTensor* sel, const RadTensor* co, Call* c) { + c->kc = sel->rank ? sel->shape[sel->rank - 1] : 0; + c->scap = tiles_cap(sel, c->kc, c->nh); + if (c->kc < c->g.k || c->scap < c->g.N) return RAD_E_SHAPE; + c->ccap = co ? tiles_cap(co, c->hd, c->nh) : 0; + if (co && (co->shape[co->rank - 1] != c->hd || c->ccap < c->g.N)) return RAD_E_SHAPE; + return RAD_OK; +} + +/* ================================================================== attn_vsa's blocks */ +/* Keys per packed block and query rows per block. */ +enum { KT = 64, QB = 64 }; +#if AVX_LEVEL == 3 +constexpr int RB = 6; +#else +constexpr int RB = 2; +#endif +constexpr int64_t CK = 4 * VF_N; + +inline int64_t padded(int64_t hd) { return (hd + CK - 1) / CK * CK; } + +/* The next row block: `top` rows, the last two kept at four or more (avx_gen_attn.cpp). */ +inline int row_block(int64_t left, int top) { + if (top < 4) return left >= top ? top : (int)left; + if (left >= top + 4 || left == top) return top; + return left > top ? (int)(left - 4) : (int)left; +} + +#define VSA_ROWS(fn, mb, ...) \ + switch (mb) { \ + case 6: fn<6>(__VA_ARGS__); break; \ + case 5: fn<5>(__VA_ARGS__); break; \ + case 4: fn<4>(__VA_ARGS__); break; \ + case 3: fn<3>(__VA_ARGS__); break; \ + case 2: fn<2>(__VA_ARGS__); break; \ + default: fn<1>(__VA_ARGS__); break; \ + } + +/* S[i][0, 64) = Q[i] . K for MB_ query rows (pitch ldq) over the packed Kt. */ +template +inline void qk_rows(const float* Q, int64_t ldq, const float* Kt, int64_t hd, float* S) { + for (int64_t c = 0; c < KT; c += CK) { + vf acc[MB_][4]; + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) acc[i][v] = vf_zero(); + for (int64_t d = 0; d < hd; ++d) { + const float* kr = Kt + d * KT + c; + const vf k0 = vf_loadu(kr), k1 = vf_loadu(kr + VF_N); + const vf k2 = vf_loadu(kr + 2 * VF_N), k3 = vf_loadu(kr + 3 * VF_N); + for (int i = 0; i < MB_; ++i) { + const vf b = vf_set1(Q[i * ldq + d]); + acc[i][0] = vf_fma(b, k0, acc[i][0]); + acc[i][1] = vf_fma(b, k1, acc[i][1]); + acc[i][2] = vf_fma(b, k2, acc[i][2]); + acc[i][3] = vf_fma(b, k3, acc[i][3]); + } + } + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) vf_storeu(S + i * KT + c + v * VF_N, acc[i][v]); + } +} + +/* acc[i][0, hp) += P[i] . V for MB_ rows over the block's `kt` keys. */ +template +inline void pv_rows(float* acc, int64_t hp, const float* Pm, const float* Vt, int64_t kt) { + for (int64_t c = 0; c < hp; c += CK) { + vf o[MB_][4]; + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) o[i][v] = vf_loadu(acc + i * hp + c + v * VF_N); + for (int64_t j = 0; j < kt; ++j) { + const float* vr = Vt + j * hp + c; + const vf v0 = vf_loadu(vr), v1 = vf_loadu(vr + VF_N); + const vf v2 = vf_loadu(vr + 2 * VF_N), v3 = vf_loadu(vr + 3 * VF_N); + for (int i = 0; i < MB_; ++i) { + const vf p = vf_set1(Pm[i * KT + j]); + o[i][0] = vf_fma(p, v0, o[i][0]); + o[i][1] = vf_fma(p, v1, o[i][1]); + o[i][2] = vf_fma(p, v2, o[i][2]); + o[i][3] = vf_fma(p, v3, o[i][3]); + } + } + for (int i = 0; i < MB_; ++i) + for (int v = 0; v < 4; ++v) vf_storeu(acc + i * hp + c + v * VF_N, o[i][v]); + } +} + +/* The online softmax over one block of R rows: m, l and acc (rows of `hp`) rescaled at a new + * maximum, S replaced by exp(S - m). A row with nothing visible in the block becomes zeros. */ +void softmax_block(float* S, int64_t R, float* m, float* l, float* acc, int64_t hp) { + for (int64_t r = 0; r < R; ++r) { + float* sr = S + r * KT; + const float tmax = row_max(sr, KT); + if (tmax == -INFINITY) { + for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f; + continue; + } + if (tmax > m[r]) { + const float alpha = m[r] == -INFINITY ? 0.0f : sc_exp(m[r] - tmax); + if (alpha != 1.0f) { + float* ar = acc + r * hp; + const vf va = vf_set1(alpha); + for (int64_t d = 0; d < hp; d += VF_N) + vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), va)); + l[r] *= alpha; + } + m[r] = tmax; + } + const vf vm = vf_set1(m[r]); + for (int64_t j = 0; j < KT; j += VF_N) + vf_storeu(sr + j, vf_exp(vf_sub(vf_loadu(sr + j), vm))); + l[r] += row_sum(sr, KT); + } +} + +struct Att { + const Call* c; + const RadTensor *q, *k, *v, *sel, *co, *gt, *o, *k8, *ks; + Heads Q, K, Vh, O, G, K8; + int64_t ks_rs; + float scale; + bool i8; /* the int8 score form (libref's ref_attn_vsa) */ +}; + +/* quant_act_i8g's rule for one row, in place: the codes rint(clamp(x * (1/scale), +-127)) and the + * scale amax/127 (1 for an all-zero row). */ +float q8_row(float* x, int64_t n) { + float am = 0.0f; + for (int64_t d = 0; d < n; ++d) am = std::max(am, std::fabs(x[d])); + const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t d = 0; d < n; ++d) x[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f)); + return sc; +} + +/* Query tile i of head h. */ +void attn_task(const Att& t, int64_t h, int64_t i) { + const Tiles& g = t.c->g; + const int64_t hd = t.c->hd, hp = padded(hd), P = g.P, kk = g.k; + float* frame = scratch_f32((size_t)(QB * hd + QB * hp + QB * KT + 2 * QB + hd * KT + KT * hp + + 4 * hp + QB + KT) + 64); + float* Qb = frame; + float* acc = Qb + QB * hd; + float* S = acc + QB * hp; + float* m = S + QB * KT; + float* l = m + QB; + float* Kt = l + QB; + float* Vt = Kt + hd * KT; + float* row = Vt + KT * hp; /* 4 hp: a widened row, the epilogue's rows */ + float* qsc = row + 4 * hp; /* the int8 form's query scales, then key scales */ + float* ksc = qsc + QB; + const int64_t sb = rowoff(t.sel, h * t.c->scap + i, t.c->kc), ss = laststride(t.sel); + const int64_t nvis = i < P ? g.N : P + kk; + auto vis = [&](int64_t n) { + return n < P || i < P ? n : ldi(t.sel, sb + (n - P) * ss); + }; + const int64_t sz = tile_size(g, i); + for (int64_t q0 = 0; q0 < sz; q0 += QB) { + const int64_t nq = std::min(QB, sz - q0); + for (int64_t r = 0; r < nq; ++r) { + float* qr = Qb + r * hd; + const float* src = in_row(t.q, row_at(g, i, q0 + r) * t.Q.rs + h * t.Q.hs, hd, qr); + if (src != qr) std::memcpy(qr, src, sizeof(float) * (size_t)hd); + if (t.i8) qsc[r] = q8_row(qr, hd); + m[r] = -INFINITY; + l[r] = 0.0f; + } + std::memset(acc, 0, sizeof(float) * (size_t)(nq * hp)); + for (int64_t n = 0; n < nvis; ++n) { + const int64_t j = vis(n), kz = tile_size(g, j); + for (int64_t c0 = 0; c0 < kz; c0 += KT) { + const int64_t kt = std::min(KT, kz - c0); + for (int64_t jj = 0; jj < KT; ++jj) { + float* vr = Vt + jj * hp; + if (jj >= kt) { + for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = 0.0f; + std::memset(vr, 0, sizeof(float) * (size_t)hp); + continue; + } + const int64_t kr = row_at(g, j, c0 + jj); + const float* kx = t.i8 ? in_row(t.k8, kr * t.K8.rs + h * t.K8.hs, hd, row) + : in_row(t.k, kr * t.K.rs + h * t.K.hs, hd, row); + for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = kx[d]; + if (t.i8) ksc[jj] = ldt(t.ks, kr * t.ks_rs + h); + const float* vx = in_row(t.v, kr * t.Vh.rs + h * t.Vh.hs, hd, vr); + if (vx != vr) std::memcpy(vr, vx, sizeof(float) * (size_t)hd); + for (int64_t d = hd; d < hp; ++d) vr[d] = 0.0f; + } + for (int64_t r = 0, mb; r < nq; r += mb) { + mb = row_block(nq - r, RB); + VSA_ROWS(qk_rows, mb, Qb + r * hd, hd, Kt, hd, S + r * KT); + } + const vf vs = vf_set1(t.scale); + for (int64_t r = 0; r < nq; ++r) { + float* sr = S + r * KT; + if (t.i8) { + /* libref's order: (dot * q scale) * k scale, then the softmax scale. */ + for (int64_t j2 = kt; j2 < KT; ++j2) ksc[j2] = 0.0f; + const vf vq = vf_set1(qsc[r]); + for (int64_t j2 = 0; j2 < KT; j2 += VF_N) + vf_storeu(sr + j2, keep(vf_mul(keep(vf_mul(keep(vf_mul( + vf_loadu(sr + j2), vq)), vf_loadu(ksc + j2))), + vs))); + } else { + for (int64_t j2 = 0; j2 < KT; j2 += VF_N) + vf_storeu(sr + j2, vf_mul(vf_loadu(sr + j2), vs)); + } + for (int64_t j2 = kt; j2 < KT; ++j2) sr[j2] = -INFINITY; + } + softmax_block(S, nq, m, l, acc, hp); + for (int64_t r = 0, mb; r < nq; r += mb) { + mb = row_block(nq - r, RB); + VSA_ROWS(pv_rows, mb, acc + r * hp, hp, S + r * KT, Vt, kt); + } + } + } + /* o = acc / l; with the coarse term o rounded to out's dtype, then + coarse gate, the + * product rounded before the add as libref rounds it. */ + const uint32_t odt = t.o->dtype; + float* tmp = row + hp; + float* cb = row + 2 * hp; + float* gb = row + 3 * hp; + const float* cr = + t.co ? in_row(t.co, rowoff(t.co, h * t.c->ccap + i, hd), hd, cb) : nullptr; + for (int64_t r = 0; r < nq; ++r) { + const int64_t qr = row_at(g, i, q0 + r); + float* y = acc + r * hp; + const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r]; + const vf vi = vf_set1(inv); + int64_t d = 0; + for (; d + VF_N <= hd; d += VF_N) vf_storeu(y + d, vf_mul(vf_loadu(y + d), vi)); + for (; d < hd; ++d) y[d] *= inv; + if (cr) { + if (odt != RAD_F32) { + row_from_f32(odt, y, tmp, hd); + row_to_f32(odt, tmp, y, hd); + } + const float* ge = in_row(t.gt, qr * t.G.rs + h * t.G.hs, hd, gb); + d = 0; + for (; d + VF_N <= hd; d += VF_N) + vf_storeu(y + d, vf_add(vf_loadu(y + d), + keep(vf_mul(vf_loadu(cr + d), vf_loadu(ge + d))))); + for (; d < hd; ++d) y[d] = y[d] + keep(cr[d] * ge[d]); + } + out_row(t.o, qr * t.O.rs + h * t.O.hs, hd, y); + } + } +} + +/* The fp8 P.V form of query tile i of head h (libref's ref_attn_vsa): per row every visible score + * (bf16 or int8 form), the max, then p = exp(s - max) in f64 rounded to f32, w = e4m3(448 p), and + * o = (sum w v) v_scale / (448 sum p), sums in key order; then the epilogue. Two passes, as libref, + * because the weights are rounded against the row's final max. */ +void attn_task_pv8(const Att& t, const RadTensor* vsc, int64_t h, int64_t i) { + const Tiles& g = t.c->g; + const int64_t hd = t.c->hd, P = g.P, kk = g.k; + const int64_t sb = rowoff(t.sel, h * t.c->scap + i, t.c->kc), ss = laststride(t.sel); + const int64_t nvis = i < P ? g.N : P + kk; + auto vis = [&](int64_t n) { + return n < P || i < P ? n : ldi(t.sel, sb + (n - P) * ss); + }; + int64_t nk = 0; + for (int64_t n = 0; n < nvis; ++n) nk += tile_size(g, vis(n)); + float* qf = scratch_f32((size_t)(4 * hd + nk)); + float* kf = qf + hd; + float* acc = kf + hd; + float* y = acc + hd; + float* sc = y + hd; + const uint32_t odt = t.o->dtype; + const int64_t sz = tile_size(g, i); + for (int64_t q0 = 0; q0 < sz; ++q0) { + const int64_t qr = row_at(g, i, q0); + const float* src = in_row(t.q, qr * t.Q.rs + h * t.Q.hs, hd, qf); + if (src != qf) std::memcpy(qf, src, sizeof(float) * (size_t)hd); + const float qs = t.i8 ? q8_row(qf, hd) : 1.0f; + int64_t m = 0; + float mx = -INFINITY; + for (int64_t n = 0; n < nvis; ++n) { + const int64_t j = vis(n), kz = tile_size(g, j); + for (int64_t c0 = 0; c0 < kz; ++c0) { + const int64_t kr = row_at(g, j, c0); + const float* kx = t.i8 ? in_row(t.k8, kr * t.K8.rs + h * t.K8.hs, hd, kf) + : in_row(t.k, kr * t.K.rs + h * t.K.hs, hd, kf); + float dot = 0.0f; + for (int64_t d = 0; d < hd; ++d) dot = keep(dot + keep(qf[d] * kx[d])); + if (t.i8) dot = keep(keep(dot * qs) * ldt(t.ks, kr * t.ks_rs + h)); + dot = keep(dot * t.scale); + sc[m++] = dot; + mx = std::max(mx, dot); + } + } + for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f; + float sum = 0.0f; + m = 0; + for (int64_t n = 0; n < nvis; ++n) { + const int64_t j = vis(n), kz = tile_size(g, j); + for (int64_t c0 = 0; c0 < kz; ++c0) { + const int64_t kr = row_at(g, j, c0); + const float p = (float)std::exp((double)(sc[m++] - mx)); + sum += p; + const float w = narrow1(RAD_F8E4M3, 448.0f * p); + const float* vx = in_row(t.v, kr * t.Vh.rs + h * t.Vh.hs, hd, kf); + for (int64_t d = 0; d < hd; ++d) acc[d] = keep(acc[d] + keep(w * vx[d])); + } + } + const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f; + for (int64_t d = 0; d < hd; ++d) + y[d] = keep(keep(acc[d] * ldt(vsc, offlin(vsc, h * hd + d))) * inv8); + if (t.co) { + const int64_t cb = rowoff(t.co, h * t.c->ccap + i, hd), cs = laststride(t.co); + for (int64_t d = 0; d < hd; ++d) { + const float c = ldt(t.co, cb + d * cs); + const float e = ldt(t.gt, qr * t.G.rs + h * t.G.hs + d * t.G.ds); + y[d] = keep(narrow1(odt, y[d]) + keep(c * e)); + } + } + out_row(t.o, qr * t.O.rs + h * t.O.hs, hd, y); + } +} + +} /* namespace */ + +/* ------------------------------------------------------------------ vsa_select */ +AVX_KERNEL(vsa_select) { + const RadTensor *q = rad_arg_in(a, 0), *k = rad_arg_in(a, 1), *v = rad_arg_in(a, 2); + const RadTensor *segs = rad_arg_in(a, 3), *geom = rad_arg_in(a, 4), *sel = rad_arg_in(a, 5); + const RadTensor* co = rad_arg_in(a, 6); + if (!q || !k || !segs || !geom || !sel) return RAD_E_INVAL; + if (!v != !co) return RAD_E_SHAPE; + if (sel->dtype != RAD_I32) return RAD_E_DTYPE; + Call c; + if (const int rc = common(a, q, segs, geom, &c); rc < 0) return rc; + const Tiles& g = c.g; + const int64_t hd = c.hd, nh = c.nh, need = g.R * nh * hd; + if (numel(k) < need || (v && numel(v) < need)) return RAD_E_SHAPE; + if (const int rc = caps(sel, co, &c); rc < 0) return rc; + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd)); + const Heads Q = heads_of(q, nh, hd), K = heads_of(k, nh, hd); + const Heads Vh = v ? heads_of(v, nh, hd) : Heads{ nullptr, 0, 0, 0 }; + const int64_t N = g.N, P = g.P, V = g.V, kk = g.k; + /* The scores run in whole vectors across tiles, through zero key columns up to Np: from tile + * 0 for the coarse branch, else from the last multiple of the width at or below P. */ + const int64_t Np = (N + VF_N - 1) / VF_N * VF_N; + const int64_t j0 = co ? 0 : P / VF_N * VF_N; + + /* The tile means [n_head][N][hd], and the key means transposed, [n_head][hd][Np]. Kept at + * their high-water size; the parallel regions read them through pointers taken here. */ + static thread_local std::vector pool; + const size_t per = (size_t)(nh * N * hd); + pool.resize(per * (co ? 3 : 2) + (size_t)(nh * hd * Np)); + float* qp = pool.data(); + float* kp = qp + per; + float* vp = co ? kp + per : nullptr; + float* kt = kp + per * (co ? 2 : 1); + + AVX_PARALLEL_FOR_IF(nh * g.R * hd >= AVX_PAR_MIN) + for (int64_t u = 0; u < nh * N; ++u) { + const int64_t h = u / N, j = u % N; + float* scr = scratch_f32((size_t)(hd + 16)); + float* means[3] = { qp + u * hd, kp + u * hd, vp ? vp + u * hd : nullptr }; + const RadTensor* src[3] = { q, k, v }; + const Heads* hv[3] = { &Q, &K, &Vh }; + for (int s = 0; s < 3; ++s) { + float* mu = means[s]; + if (!mu) continue; + std::memset(mu, 0, sizeof(float) * (size_t)hd); + tile_rows(g, j, [&](int64_t r) { + const float* x = in_row(src[s], r * hv[s]->rs + h * hv[s]->hs, hd, scr); + int64_t d = 0; + for (; d + VF_N <= hd; d += VF_N) + vf_storeu(mu + d, vf_add(vf_loadu(mu + d), vf_loadu(x + d))); + for (; d < hd; ++d) mu[d] += x[d]; + }); + const float n = (float)tile_size(g, j); + const vf vn = vf_set1(n); + int64_t d = 0; + for (; d + VF_N <= hd; d += VF_N) vf_storeu(mu + d, vf_div(vf_loadu(mu + d), vn)); + for (; d < hd; ++d) mu[d] /= n; + } + } + AVX_PARALLEL_FOR_IF(nh * Np * hd >= AVX_PAR_MIN) + for (int64_t hdd = 0; hdd < nh * hd; ++hdd) { + const int64_t h = hdd / hd, d = hdd % hd; + float* kr = kt + hdd * Np; + for (int64_t j = 0; j < N; ++j) kr[j] = kp[(h * N + j) * hd + d]; + for (int64_t j = N; j < Np; ++j) kr[j] = 0.0f; + } + + const int64_t kc = c.kc, scap = c.scap, ccap = c.ccap, ss = laststride(sel); + AVX_PARALLEL_FOR_IF(nh * N * Np * hd >= AVX_PAR_MIN) + for (int64_t u = 0; u < nh * N; ++u) { + const int64_t h = u / N, i = u % N; + if (i < P && !co) continue; + float* frame = scratch_f32((size_t)(Np + V + hd) + 64); + float* S = frame; + float* ord = S + Np; + float* acc = ord + V; + const float* qs = qp + u * hd; + const float* kth = kt + h * hd * Np; + for (int64_t j = j0; j < Np; j += VF_N) vf_storeu(S + j, vf_zero()); + for (int64_t d = 0; d < hd; ++d) { + const vf b = vf_set1(qs[d]); + const float* kr = kth + d * Np; + for (int64_t j = j0; j < Np; j += VF_N) + vf_storeu(S + j, vf_add(vf_loadu(S + j), keep(vf_mul(b, vf_loadu(kr + j))))); + } + const vf vs = vf_set1(scale); + for (int64_t j = j0; j < Np; j += VF_N) vf_storeu(S + j, vf_mul(vf_loadu(S + j), vs)); + if (i >= P) { + std::copy(S + P, S + N, ord); + std::nth_element(ord, ord + (kk - 1), ord + V, above); + const float thr = ord[kk - 1]; + int64_t ties = kk; + for (int64_t j = 0; j < V; ++j) ties -= above(S[P + j], thr); + const int64_t sb = rowoff(sel, h * scap + i, kc); + int64_t n = 0; + for (int64_t j = 0; j < V; ++j) { + const float s = S[P + j]; + if (above(s, thr) || (!above(thr, s) && ties-- > 0)) + st_int_dt(sel->dtype, sel->data, sb + (n++) * ss, P + j); + } + } + if (co) { + float mx = -INFINITY; + for (int64_t j = 0; j < N; ++j) if (S[j] > mx) mx = S[j]; + const vf vm = vf_set1(mx); + int64_t j = 0; + for (; j + VF_N <= N; j += VF_N) vf_storeu(S + j, vf_exp(vf_sub(vf_loadu(S + j), vm))); + for (; j < N; ++j) S[j] = sc_exp(S[j] - mx); + const float sum = row_sum(S, N); + std::memset(acc, 0, sizeof(float) * (size_t)hd); + for (j = 0; j < N; ++j) axpy(acc, vp + (h * N + j) * hd, S[j] / sum, hd); + out_row(co, rowoff(co, h * ccap + i, hd), hd, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ attn_vsa */ +AVX_KERNEL(attn_vsa) { + const RadTensor *q = rad_arg_in(a, 0), *k = rad_arg_in(a, 1), *v = rad_arg_in(a, 2); + const RadTensor *segs = rad_arg_in(a, 3), *geom = rad_arg_in(a, 4), *sel = rad_arg_in(a, 5); + const RadTensor *co = rad_arg_in(a, 6), *gt = rad_arg_in(a, 7), *o = rad_arg_in(a, 8); + const RadTensor *k8 = rad_arg_in(a, 9), *ks = rad_arg_in(a, 10); + const RadTensor* vsc = a->n_t > 11 ? rad_arg_in(a, 11) : nullptr; + if (!q || !k || !v || !segs || !geom || !sel || !o) return RAD_E_INVAL; + const char* pv = p_str(a, "pv", "bf16"); + const bool pv8 = std::strcmp(pv, "fp8") == 0; + if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL; + if (!co != !gt) return RAD_E_SHAPE; + if (sel->dtype != RAD_I32) return RAD_E_DTYPE; + const char* qk = p_str(a, "qk", "bf16"); + const bool i8 = std::strcmp(qk, "i8") == 0; + if ((!i8 && std::strcmp(qk, "bf16") != 0) || i8 != (k8 != nullptr) || i8 != (ks != nullptr)) + return RAD_E_INVAL; + Call c; + if (const int rc = common(a, q, segs, geom, &c); rc < 0) return rc; + const Tiles& g = c.g; + const int64_t hd = c.hd, nh = c.nh, need = g.R * nh * hd; + if (numel(k) < need || numel(v) < need || numel(o) < need || (gt && numel(gt) < need)) + return RAD_E_SHAPE; + if (const int rc = caps(sel, co, &c); rc < 0) return rc; + const int64_t N = g.N, P = g.P, kk = g.k, ss = laststride(sel); + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = P; i < N; ++i) { + const int64_t sb = rowoff(sel, h * c.scap + i, c.kc); + int64_t prev = P - 1; + for (int64_t s = 0; s < kk; ++s) { + const int64_t j = ldi(sel, sb + s * ss); + if (j <= prev || j >= N) return RAD_E_INVAL; + prev = j; + } + } + Att t{}; + t.c = &c; + t.q = q; t.k = k; t.v = v; t.sel = sel; t.co = co; t.gt = gt; t.o = o; + t.Q = heads_of(q, nh, hd); + t.K = heads_of(k, nh, hd); + t.Vh = heads_of(v, nh, hd); + t.O = heads_of(o, nh, hd); + t.G = gt ? heads_of(gt, nh, hd) : Heads{ nullptr, 0, 0, 0 }; + t.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd)); + t.i8 = i8; + if (i8) { + if (numel(k8) < need || numel(ks) < g.R * nh) return RAD_E_SHAPE; + t.k8 = k8; + t.ks = ks; + t.K8 = heads_of(k8, nh, hd); + t.ks_rs = row_stride(ks, nh); + } + /* Dynamic: a prefix query tile sees every tile, a video one the prefix and k tiles, and a + * unit's arithmetic does not depend on the thread that runs it. */ +#ifdef _OPENMP + AVX_PRAGMA(omp parallel for schedule(dynamic, 1) if(nh * g.R * hd >= AVX_PAR_MIN || + avx_par_forced()) num_threads(avx_team_size())) +#endif + for (int64_t u = 0; u < nh * N; ++u) { + if (pv8) attn_task_pv8(t, vsc, u / N, u % N); + else attn_task(t, u / N, u % N); + } + return RAD_OK; +} diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 10537213..5cd62ee7 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -72,9 +72,22 @@ set(R4D_UNITS # implicit-GEMM convolution and pixel ops. "r4d_attn_gen|" "r4d_gen|" + # The audio generator: a vocoder's 1-D convolutions and snake activation, the guided top-k + # sampler for a frame's codes, the frame and window ops, and a depth decoder's short attention. + "r4d_audio|" + # The video generator: a diffusion transformer's modulated RMS norm and sampler step, the video + # decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's + # alias-free SnakeBeta. + "r4d_video|" + # Video sparse attention: the tile selection a distilled video transformer was trained with and + # the block-sparse attention over it. + "r4d_vsa|" # Vision tower ops: layer norm, the learned-grid position embedding, and the biased GEMM with # activation and residual fused into its store. "r4d_vit_bf16|" + # The same biased GEMM over f32 operands (a diffusion transformer's patch projections and heads, + # a video decoder's 1x1 projections), on the f32 FMA tile r4d_audio's f32 convolutions share. + "r4d_gemm_f32_nt_bias|" "r4d_gdn_chunk_scan_k128_v128_c64_bf16|-mcumode" "r4d_gdn_conv_w4_h128_bf16|" "r4d_gdn_kkt_solve_k128_c64_bf16|" @@ -149,7 +162,7 @@ set(R4D_UNITS # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" "r4d_expert_scale_bf16|" - # Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot; scalar f32 v1. + # Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot: scalar and tiled rows. "r4d_lora_bf16|" "r4d_dflash_conv_t2_g16_bf16|" "r4d_dflash_select_bf16|" diff --git a/libr4d/README.md b/libr4d/README.md index e5976422..acc2529b 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -59,7 +59,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set. | `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups | | `dflash_select_bf16` | the drafter's candidate selector: edge scores and the greedy path walk | | `dequant_w4_bf16` | unpacks a 4-bit fragment-ordered weight back to bf16 | -| `lora_shrink` / `lora_expand` | runtime LoRA's two halves beside a trunk GEMM, each row's adapter read from a per-row slot on the device (base rows untouched). Tiled rows (preferred): `t = x A[slot]^T` WMMA bf16 over 16-row x 16-j tiles with a K split fixed by K and R (`lora_shrink_wmma`, `lora_shrink_wmma_q` for fp8/i8 codes), `y += scale ⊙ (t B[slot]^T)` over 32-row x 128-column tiles with B[slot] staged in LDS, libref's bytes (`lora_expand_tiled`); a tile of base rows leaves on one ballot, a mixed tile runs one pass a slot. Scalar v1 rows (`_scalar`): one block a row / one thread an output, and the f16/f32-activation shrink. A row's bytes are independent of M in every row | +| `lora_shrink` / `lora_expand` | runtime LoRA's two halves beside a trunk GEMM, each row's adapter read from a per-row slot on the device (base rows untouched). Tiled rows (preferred): `t = x A[slot]^T` WMMA bf16 over 16-row x 16-j tiles with a K split fixed by K and R (`lora_shrink_wmma`, `lora_shrink_wmma_q` for fp8/i8 codes), `y += scale ⊙ (t B[slot]^T)` over 32-row x 128-column tiles with B[slot] staged in LDS, libref's bytes (`lora_expand_tiled`); a tile of base rows leaves on one ballot, a mixed tile runs one pass a slot. Scalar rows (`_scalar`): one block a row / one thread an output, and the f16/f32-activation shrink. A row's bytes are independent of M in every row | | `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, in the r4d GEMMs' fragment byte order; the `_asum` form also emits the per-group row sums the asymmetric GEMMs need | | `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first, which is what makes one scale per row viable | | `rmsnorm_had_quant_i8` | residual add, RMS norm, rotate and quantise in one kernel | diff --git a/libr4d/isa/README.md b/libr4d/isa/README.md index d1026043..694b65b5 100644 --- a/libr4d/isa/README.md +++ b/libr4d/isa/README.md @@ -1,19 +1,20 @@ # libr4d/isa: reading the machine code the kernels became -Nine scripts and four microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from +Nine scripts and six microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from "this kernel is at the memory wall"; the disassembly plus one calibration number can, without a GPU run. The trace tools are the exception: they need the GPU, and they are the only instruments here that report the geometry a kernel was launched with rather than every geometry it could have had. BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch - BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E + BUILD=... ./dis.sh r4d_gemm_fp8a8 gemm_8a8_prefill_kernelILb0E BUILD=... ./waterfall.sh # divergent VGPR indices, per kernel ./loop.sh # its K loop, classified ./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv `res.sh` prints mangled names; the substring `dis.sh` takes picks one template instantiation, and the parameter order is in the kernel's declaration (`gemm_fp8a8_kernel` is -``, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile). +``, so `ILb1ELj4ELj8ELj256ELb0E` is the narrow tile at four token +tiles and eight waves; `gemm_8a8_prefill_kernelILb0E` is the fp8 prefill tile). `loop.sh` anchors on `v_wmma` by default and takes the smallest backward branch containing every anchor, because a largest-loop search finds the epilogue, a long unrolled store chain. @@ -34,10 +35,13 @@ anchor, because a largest-loop search finds the epilogue, a long unrolled store | `graphrate.hip` | what a dispatch costs the host to submit, and what capturing a fixed sequence saves | | `launchreg.hip` + `launchreg_lib.hip` | whether a launch costs more when the module registers more kernels, and what crossing into a `.so` costs | | `blockcopy.hip` | contiguous versus scattered device-to-host copy, at KV-block granularity | +| `wmmapeak.hip` | sustained fp8, iu8 and bf16 WMMA TFLOP/s at the card's clock and power limit, with the sclk, power and temperature it ran at | +| `wmmamix.hip` | what a VALU instruction, an LDS read and an LDS write cost next to fp8 WMMA, and LDS bandwidth per CU | Each script's header states its traps and how to read its output. The microbenchmarks are built by hand: `clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 .hip -o ` for `isarate`, -`graphrate` and `blockcopy`, and `build_launchreg.sh` for the two-object launchreg pair. +`graphrate`, `blockcopy`, `wmmapeak` and `wmmamix`, and `build_launchreg.sh` for the two-object +launchreg pair. ## Instruction slot cost on gfx1201 @@ -62,6 +66,39 @@ gfx1201 has no dense 16x16x32 fp8 WMMA (`llvm-mc -mcpu=gfx1201` rejects it). The form is `v_swmmac_f32_16x16x32_fp8_fp8`, the 2:4 sparse one, so the GEMMs here already use the widest dense op there is. +## Sustained WMMA rate, and what the rest of a K loop costs + +`wmmapeak.hip` measures the ceiling a GEMM is held against: random operands rotating through eight +fragments, every block resident, eight seconds after eight of warm-up. At the 300 W limit, with +three blocks a WGP (the occupancy of the prefill tiles): + +| op | TFLOP/s | sclk | per CU per clock | +|---|---|---|---| +| `v_wmma_f32_16x16x16_fp8_fp8` | 330 | 2536 MHz | 2037 FLOP (8 clocks a WMMA a SIMD) | +| `v_wmma_i32_16x16x16_iu8` | 334 | 2561 MHz | 2038 | +| `v_wmma_f32_16x16x16_bf16` | 170 | 2703 MHz | 984 (16 clocks) | + +The power limit, not issue, sets these: with zero operands the same fp8 loop runs 418 TFLOP/s at +3.25 GHz, so how hard the multipliers switch is most of the power, and a GEMM timed on constant +operands reads fast (the fp8 prefill tile: 262 TFLOP/s on `--perfw8`'s 0x38 fill, 205 on random +codes; `--perfvideo` fills random ones). At full occupancy the fp8 run sometimes +settles at 260-270 TFLOP/s with hwmon reporting 2.8 GHz, a state in which the reported clock +overstates the delivered one; quote the three-blocks figure. + +`wmmamix.hip` adds one kind of instruction at a time to eight independent WMMA chains a wave. With +zero operands (the clock is then real), against 8.36 SIMD clocks a WMMA at six waves a SIMD: + +- a VALU instruction costs 1.05-1.4 SIMD clocks, serial with the WMMA (8 adds per 8 WMMA: 9.63 + clocks a WMMA; 64: 16.7). A fold's arithmetic does not hide under the matrix work; VOPD pairs + are the only way to halve it. +- LDS serves 64 bytes a clock per CU, loads and stores alike (32 `ds_load_b64` or 16 + `ds_load_b128` per 8 WMMA: 31.5 clocks a WMMA). At the WMMA rate that is 256 bytes of LDS per + fp8 WMMA and 512 per bf16 one. Below the limit a load costs about a clock of issue. +- nine fragment reads and two staging stores per 8 WMMA (a 1 x 8 tile staging both operands) + run at 73% with nothing else in the loop; four and one at 90%. +- one dependent chain a wave runs as fast as eight at six waves a SIMD (96%); occupancy moves the + rate from 94% (four waves) to 98% (twelve). + ## The profiler `rocprofv3 --pmc` does not work on this platform. With any counter set and any kernel filter, on diff --git a/libr4d/isa/dis.sh b/libr4d/isa/dis.sh index 4e78544e..a7563d0c 100755 --- a/libr4d/isa/dis.sh +++ b/libr4d/isa/dis.sh @@ -1,7 +1,7 @@ #!/bin/sh # Disassemble ONE kernel out of one translation unit, into $ISA_OUT/one.s. # -# BUILD=... dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E +# BUILD=... dis.sh r4d_gemm_fp8a8 gemm_8a8_prefill_kernelILb0E # # The pattern is a substring of the MANGLED name, which is how a template instantiation is named: # res.sh prints those, and the template parameter order is in the kernel declaration. llvm-objdump diff --git a/libr4d/isa/wmmamix.hip b/libr4d/isa/wmmamix.hip new file mode 100644 index 00000000..a428f221 --- /dev/null +++ b/libr4d/isa/wmmamix.hip @@ -0,0 +1,229 @@ +// What a VALU instruction, an LDS read and an LDS write cost next to fp8 WMMA on gfx1201, what LDS +// delivers per CU, and how the WMMA rate depends on waves per SIMD. A GEMM's K loop is a mix of +// these, and the answer decides its tile: whether the fold's arithmetic hides under the matrix work +// (it does not: VALU and WMMA issue serially on a SIMD) and how many LDS bytes a WMMA may cost +// (64 B a clock per CU, loads and stores together, so 256 B per WMMA at the WMMA rate). +// +// Every row is a kernel of eight independent WMMA chains a wave plus V VALU adds, L LDS loads and S +// LDS stores per eight WMMA, at the occupancy its LDS padding allows (every block resident, so no +// tail). It runs about a second; the result is SIMD clocks per WMMA from the elapsed time and the +// card's mean sclk (hwmon freq1_input), so it is clock-independent as long as the clock is real. +// +// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 wmmamix.hip -o wmmamix +// ./wmmamix [z] +// +// With `z` every operand is zero: the multipliers barely switch, the card stays under its power +// limit at its top clock, and the per-clock costs are clean. With random operands a power limit +// holds the clock down and, at some settings, stretches it below what hwmon reports; wmmapeak.hip +// is the throughput instrument for that case. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef int i2v __attribute__((ext_vector_type(2))); +typedef float f8v __attribute__((ext_vector_type(8))); +typedef unsigned u2v __attribute__((ext_vector_type(2))); +typedef unsigned u4v __attribute__((ext_vector_type(4))); + +// V VALU adds, L LDS loads of B bytes a lane, S ds_store_b64 per eight WMMA; C independent chains +// (8 = all independent, 1 = one dependent chain). +template +__global__ __launch_bounds__(256) void mix(const uint32_t* src, float* out, int iters) { + __shared__ __attribute__((aligned(16))) char pad[LDS]; + const uint32_t lane = threadIdx.x & 31u, wave = threadIdx.x >> 5; + pad[threadIdx.x] = (char)threadIdx.x; + __syncthreads(); + const uint32_t* p = src + ((blockIdx.x & 63u) * 32u + lane) * 32u; + i2v a[8], b[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + a[i] = (i2v){ (int)p[2 * i], (int)p[2 * i + 1] }; + b[i] = (i2v){ (int)p[16 + 2 * i], (int)p[17 + 2 * i] }; + } + f8v c[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) c[i] = (f8v)(0.0f); + float f[32]; +#pragma unroll + for (int i = 0; i < 32; ++i) f[i] = (float)(threadIdx.x + i); + const float kk = 1.0000001f; + typedef typename std::conditional::type RT; + RT r[L > 0 ? L : 1]; +#pragma unroll + for (int i = 0; i < (L > 0 ? L : 1); ++i) r[i] = RT{}; + // A fragment read's address pattern: lane row (l & 15) at a padded pitch, half k by lane half, + // so sixteen rows land on distinct banks. + const uint32_t la = (uint32_t)(uintptr_t)pad + (lane & 15u) * (B == 8 ? 72u : 144u) + + (lane >> 4) * B + wave * 2304u; + const uint32_t sa = (uint32_t)(uintptr_t)pad + threadIdx.x * 8u; + const u2v sv = { threadIdx.x, lane }; + for (int it = 0; it < iters; ++it) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + c[i % C] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a[i], b[(i + 3) & 7], + c[i % C]); +#pragma unroll + for (int v = i * V / 8; v < (i + 1) * V / 8; ++v) + asm volatile("v_add_f32 %0, %0, %1" : "+v"(f[v & 31]) : "v"(kk)); +#pragma unroll + for (int l = i * L / 8; l < (i + 1) * L / 8; ++l) { + if constexpr (B == 8) + asm volatile("ds_load_b64 %0, %1 offset:%2" : "+v"(r[l]) : "v"(la), "i"((l % 8) * 16)); + else + asm volatile("ds_load_b128 %0, %1 offset:%2" : "+v"(r[l]) : "v"(la), "i"((l % 4) * 32)); + } +#pragma unroll + for (int s = i * S / 8; s < (i + 1) * S / 8; ++s) + asm volatile("ds_store_b64 %0, %1 offset:%2" ::"v"(sa), "v"(sv), "i"((s % 8) * 2048)); + } + if (L > 0 || S > 0) asm volatile("s_wait_dscnt 0x0" ::: "memory"); + } + float s = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int t = 0; t < 8; ++t) s += c[i][t]; +#pragma unroll + for (int i = 0; i < 32; ++i) s += f[i]; +#pragma unroll + for (int i = 0; i < (L > 0 ? L : 1); ++i) s += (float)(r[i].x ^ r[i].y); + s += (float)pad[(threadIdx.x * 7u) % LDS]; + if (s == -1.0f) out[0] = s; +} + +static long read_long(const std::string& path) { + FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return -1; + long v = -1; + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + return v; +} + +static std::string g_hw; // the hwmon directory of device 0 + +template +static void run(const char* name, const uint32_t* d, float* o) { + hipDeviceProp_t prop; + (void)hipGetDeviceProperties(&prop, 0); + int per = 0; + (void)hipOccupancyMaxActiveBlocksPerMultiprocessor(&per, mix, 256, 0); + const int blocks = per * prop.multiProcessorCount; + const int iters = 20000; + hipEvent_t e0, e1; + (void)hipEventCreate(&e0); + (void)hipEventCreate(&e1); + (void)hipEventRecord(e0); + hipLaunchKernelGGL((mix), dim3(blocks), dim3(256), 0, 0, d, o, iters); + (void)hipEventRecord(e1); + (void)hipEventSynchronize(e1); + float ms1 = 0; + (void)hipEventElapsedTime(&ms1, e0, e1); + const int reps = (int)(1000.0f / ms1) + 1; + for (int r = 0; r < reps / 3; ++r) + hipLaunchKernelGGL((mix), dim3(blocks), dim3(256), 0, 0, d, o, iters); + (void)hipDeviceSynchronize(); + std::atomic stop{ false }; + double mhz = 0, watt = 0; + int n = 0; + std::thread th([&] { + while (!stop) { + const long f = read_long(g_hw + "/freq1_input"); + if (f > 0) { mhz += f / 1e6; watt += read_long(g_hw + "/power1_average") / 1e6; ++n; } + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + }); + (void)hipEventRecord(e0); + for (int r = 0; r < reps; ++r) + hipLaunchKernelGGL((mix), dim3(blocks), dim3(256), 0, 0, d, o, iters); + (void)hipEventRecord(e1); + (void)hipEventSynchronize(e1); + stop = true; + th.join(); + float ms = 0; + (void)hipEventElapsedTime(&ms, e0, e1); + const double clk = n ? mhz / n : 0.0; + const double wmma = 8.0 * iters * (double)blocks * 8.0 * reps; + // 64 CUs x 2 SIMDs; HIP's multiProcessorCount is the WGP count, 32. + const double simds = 4.0 * prop.multiProcessorCount; + const double clk_per = simds * (double)ms * 1e-3 * clk * 1e6 / wmma; + std::printf(" %-28s %4.1f waves/SIMD %5.0f MHz %4.0f W %6.1f TFLOP/s %6.2f clk/WMMA/SIMD" + " (%5.1f%% of 8)\n", + name, (double)blocks * 8.0 / simds, clk, n ? watt / n : 0.0, + wmma * 8192.0 / ((double)ms * 1e9), clk_per, 800.0 / clk_per); + (void)hipEventDestroy(e0); + (void)hipEventDestroy(e1); +} + +int main(int argc, char** argv) { + const bool zero = argc > 1 && argv[1][0] == 'z'; + char bus[64] = {}; + if (hipDeviceGetPCIBusId(bus, sizeof(bus), 0) == hipSuccess) { + for (char* q = bus; *q; ++q) *q = (char)std::tolower(*q); + const std::string base = std::string("/sys/bus/pci/devices/") + bus + "/hwmon"; + if (DIR* dd = opendir(base.c_str())) { + while (dirent* e = readdir(dd)) + if (!std::strncmp(e->d_name, "hwmon", 5)) { g_hw = base + "/" + e->d_name; break; } + closedir(dd); + } + } + if (g_hw.empty()) { std::printf("no hwmon node for device 0: the clock cannot be read\n"); return 1; } + const size_t nw = 64 * 32 * 32; + std::vector h(nw); + uint64_t x = 88172645463325252ull; + for (auto& w : h) { + uint32_t v = 0; + for (int b = 0; b < 4; ++b) { + x ^= x << 13; x ^= x >> 7; x ^= x << 17; + const uint32_t r = (uint32_t)x; + v |= (((r & 0x80u) | ((6u + (r >> 8) % 4u) << 3) | (r & 7u)) & 0xFFu) << (8 * b); + } + w = zero ? 0u : v; + } + uint32_t* d; + float* o; + (void)hipMalloc(&d, nw * 4); + (void)hipMalloc(&o, 4); + (void)hipMemcpy(d, h.data(), nw * 4, hipMemcpyHostToDevice); + std::printf("fp8 WMMA mixes, %s operands, sensors %s\n", zero ? "zero" : "random", g_hw.c_str()); + std::printf("occupancy (blocks a WGP set by LDS)\n"); + run<65536, 0, 0, 8, 0, 8>("wmma only", d, o); + run<40000, 0, 0, 8, 0, 8>("wmma only", d, o); + run<32768, 0, 0, 8, 0, 8>("wmma only", d, o); + run<20480, 0, 0, 8, 0, 8>("wmma only", d, o); + run<8192, 0, 0, 8, 0, 8>("wmma only", d, o); + std::printf("dependent chains\n"); + run<40000, 0, 0, 8, 0, 1>("1 chain", d, o); + run<40000, 0, 0, 8, 0, 4>("4 chains", d, o); + std::printf("VALU adds per 8 WMMA\n"); + run<40000, 8, 0, 8, 0, 8>("8 valu", d, o); + run<40000, 16, 0, 8, 0, 8>("16 valu", d, o); + run<40000, 32, 0, 8, 0, 8>("32 valu", d, o); + run<40000, 64, 0, 8, 0, 8>("64 valu", d, o); + std::printf("LDS loads per 8 WMMA (a bf16 or fp8 fragment read is 256 or 512 B a wave)\n"); + run<40000, 0, 4, 8, 0, 8>("4 ds_load_b64", d, o); + run<40000, 0, 9, 8, 0, 8>("9 ds_load_b64", d, o); + run<40000, 0, 12, 8, 0, 8>("12 ds_load_b64", d, o); + run<40000, 0, 16, 8, 0, 8>("16 ds_load_b64", d, o); + run<40000, 0, 32, 8, 0, 8>("32 ds_load_b64", d, o); + run<40000, 0, 8, 16, 0, 8>("8 ds_load_b128", d, o); + run<40000, 0, 16, 16, 0, 8>("16 ds_load_b128", d, o); + std::printf("LDS stores per 8 WMMA\n"); + run<40000, 0, 0, 8, 2, 8>("2 ds_store_b64", d, o); + run<40000, 0, 0, 8, 16, 8>("16 ds_store_b64", d, o); + std::printf("mixes\n"); + run<40000, 0, 9, 8, 2, 8>("9 load + 2 store", d, o); + run<40000, 0, 4, 8, 1, 8>("4 load + 1 store", d, o); + run<40000, 16, 9, 8, 2, 8>("16 valu + 9 load + 2 store", d, o); + return 0; +} diff --git a/libr4d/isa/wmmapeak.hip b/libr4d/isa/wmmapeak.hip new file mode 100644 index 00000000..62ff742c --- /dev/null +++ b/libr4d/isa/wmmapeak.hip @@ -0,0 +1,242 @@ +// Sustained WMMA throughput on gfx1201 at the card's own clock and power limit: the ceiling a GEMM +// is measured against. isarate.hip answers a ratio of issue slots and needs no clock; this answers +// TFLOP/s, which at a power limit depends on how hard the multipliers switch, so the operands are +// random bits rotating through eight A and eight B fragments (consecutive instructions never see +// the same inputs) and the run is long enough for the clock to settle under the limit. +// +// Each wave issues eight independent accumulator chains back to back, every block of the launch is +// resident at once (the grid is the occupancy calculator's answer times the WGP count, so there is +// no tail), and launches repeat for the requested seconds after a warm-up of the same length. The +// card's own sensors (hwmon freq1_input, power1_average, temp edge) are sampled from a host thread +// during the timed window; the hwmon node is found from the HIP device's PCI bus id. +// +// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 wmmapeak.hip -o wmmapeak +// ./wmmapeak [device] [seconds] [tile] +// +// A non-zero `tile` pads every block to 36864 B of unused LDS, the fp8 prefill tile's footprint +// (three blocks a WGP), to read the ceiling at that occupancy; 0 is full occupancy. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef int i2v __attribute__((ext_vector_type(2))); +typedef int i8v __attribute__((ext_vector_type(8))); +typedef float f8v __attribute__((ext_vector_type(8))); +typedef __bf16 v8bf __attribute__((ext_vector_type(8))); + +enum { kFp8 = 0, kBf16 = 1, kIu8 = 2 }; + +// Operand dwords a lane holds per fragment: two for the 8-bit forms, four for bf16. +template struct Frag; +template <> struct Frag { typedef i2v T; static constexpr int dw = 2; }; +template <> struct Frag { typedef i2v T; static constexpr int dw = 2; }; +template <> struct Frag { typedef v8bf T; static constexpr int dw = 4; }; + +template +__device__ __forceinline__ f8v mma(typename Frag::T a, typename Frag::T b, f8v c) { + if constexpr (OP == kFp8) return __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c); + if constexpr (OP == kBf16) return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); + if constexpr (OP == kIu8) + return __builtin_bit_cast(f8v, __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, a, true, b, __builtin_bit_cast(i8v, c), false)); +} + +template +__device__ __forceinline__ typename Frag::T load_frag(const uint32_t* p) { + typedef typename Frag::T T; + union { uint32_t w[Frag::dw]; T f; } u; +#pragma unroll + for (int i = 0; i < Frag::dw; ++i) u.w[i] = p[i]; + return u.f; +} + +// `src` holds 16 fragments' worth of random dwords per lane (8 A, then 8 B); `out` receives a sum +// that is never -1 in practice, so the chains stay live. +template +__global__ __launch_bounds__(256) void peak(const uint32_t* __restrict__ src, float* out, + int iters) { + __shared__ char pad[LDS ? LDS : 4]; + pad[threadIdx.x & 3] = (char)threadIdx.x; + typedef typename Frag::T T; + constexpr int dw = Frag::dw; + const uint32_t lane = threadIdx.x & 31u; + const uint32_t* p = src + ((size_t)(blockIdx.x & 63u) * 32u + lane) * 16u * dw; + T a[8], b[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { a[i] = load_frag(p + i * dw); b[i] = load_frag(p + (8 + i) * dw); } + f8v c[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) c[i] = (f8v)(0.0f); + for (int it = 0; it < iters; ++it) { +#pragma unroll + for (int i = 0; i < 8; ++i) c[i] = mma(a[i], b[(i + 3) & 7], c[i]); + } + float s = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) +#pragma unroll + for (int t = 0; t < 8; ++t) s += c[i][t]; + if (s == -1.0f) out[0] = s + (float)pad[0]; +} + +// ---- the card's sensors ------------------------------------------------------------------------ +static std::string hwmon_dir(int dev) { + char bus[64] = {}; + if (hipDeviceGetPCIBusId(bus, sizeof(bus), dev) != hipSuccess) return ""; + for (char* q = bus; *q; ++q) *q = (char)std::tolower(*q); + const std::string base = std::string("/sys/bus/pci/devices/") + bus + "/hwmon"; + DIR* d = opendir(base.c_str()); + if (!d) return ""; + std::string found; + while (dirent* e = readdir(d)) + if (!std::strncmp(e->d_name, "hwmon", 5)) { found = base + "/" + e->d_name; break; } + closedir(d); + return found; +} + +static long read_long(const std::string& path) { + FILE* f = std::fopen(path.c_str(), "r"); + if (!f) return -1; + long v = -1; + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + return v; +} + +struct Sensors { + double mhz_sum = 0, mhz_min = 1e30, mhz_max = 0, w_sum = 0, t_max = 0; + int n = 0; +}; + +static void sample(const std::string& hw, std::atomic* stop, Sensors* s) { + while (!stop->load()) { + const long f = read_long(hw + "/freq1_input"), p = read_long(hw + "/power1_average"), + t = read_long(hw + "/temp1_input"); + if (f > 0) { + const double mhz = (double)f / 1e6; + s->mhz_sum += mhz; + if (mhz < s->mhz_min) s->mhz_min = mhz; + if (mhz > s->mhz_max) s->mhz_max = mhz; + s->w_sum += p > 0 ? (double)p / 1e6 : 0.0; + if ((double)t / 1e3 > s->t_max) s->t_max = (double)t / 1e3; + ++s->n; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } +} + +template +static void run(const char* name, int dev, double secs, const uint32_t* d_src, float* d_out, + const std::string& hw) { + hipDeviceProp_t prop; + (void)hipGetDeviceProperties(&prop, dev); + int per = 0; + (void)hipOccupancyMaxActiveBlocksPerMultiprocessor(&per, peak, 256, 0); + const int blocks = per * prop.multiProcessorCount; + // About 20 ms a launch at any rate: calibrate on one short launch. + int iters = 4096; + hipEvent_t e0, e1; + (void)hipEventCreate(&e0); + (void)hipEventCreate(&e1); + hipLaunchKernelGGL((peak), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters); + (void)hipEventRecord(e0); + hipLaunchKernelGGL((peak), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters); + (void)hipEventRecord(e1); + (void)hipEventSynchronize(e1); + float ms = 0; + (void)hipEventElapsedTime(&ms, e0, e1); + iters = (int)((double)iters * 20.0 / (ms > 0.01f ? ms : 0.01f)); + if (iters < 256) iters = 256; + const int launches = (int)(secs * 1000.0 / 20.0) + 1; + // Warm-up of the same length, so the timed window starts at the settled clock. + for (int i = 0; i < launches; ++i) + hipLaunchKernelGGL((peak), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters); + (void)hipDeviceSynchronize(); + Sensors s; + std::atomic stop{false}; + std::thread th; + if (!hw.empty()) th = std::thread(sample, hw, &stop, &s); + (void)hipEventRecord(e0); + for (int i = 0; i < launches; ++i) + hipLaunchKernelGGL((peak), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters); + (void)hipEventRecord(e1); + (void)hipEventSynchronize(e1); + stop = true; + if (th.joinable()) th.join(); + (void)hipEventElapsedTime(&ms, e0, e1); + const double flop = 8192.0 * 8.0 * 8.0 * (double)iters * (double)blocks * (double)launches; + const double tf = flop / ((double)ms * 1e9); + const double mhz = s.n ? s.mhz_sum / s.n : 0.0; + // Per CU per clock (64 CUs; HIP's multiProcessorCount is the WGP count, half of it). + const double per_clk = mhz > 0 ? tf * 1e12 / (2.0 * prop.multiProcessorCount * mhz * 1e6) : 0.0; + std::printf(" %-6s %3d blocks x 256 %8.1f ms %7.1f TFLOP/s sclk %6.0f MHz (min %4.0f max " + "%4.0f) %5.1f W %4.0f C %6.0f FLOP/clk/CU\n", + name, blocks, ms, tf, mhz, s.n ? s.mhz_min : 0.0, s.mhz_max, s.n ? s.w_sum / s.n : 0.0, + s.t_max, per_clk); + (void)hipEventDestroy(e0); + (void)hipEventDestroy(e1); +} + +int main(int argc, char** argv) { + const int dev = argc > 1 ? std::atoi(argv[1]) : 0; + const double secs = argc > 2 ? std::atof(argv[2]) : 3.0; + const int tile = argc > 3 ? std::atoi(argv[3]) : 0; + (void)hipSetDevice(dev); + const std::string hw = hwmon_dir(dev); + std::printf(" WMMA sustained, device %d, %.1f s timed after %.1f s warm, sensors %s, power cap " + "%.0f W\n", + dev, secs, secs, hw.empty() ? "(none)" : hw.c_str(), + hw.empty() ? 0.0 : (double)read_long(hw + "/power1_cap") / 1e6); + // Random operand bits, 64 blocks' worth so neighbouring blocks differ. The 8-bit forms take + // every byte but E4M3's NaN codes and keep the exponent near one; bf16 likewise near one, so + // nothing overflows over the run. + const size_t nw = (size_t)64 * 32 * 16 * 4; + std::vector h8(nw), h16(nw), hi8(nw); + uint64_t x = 0x9E3779B97F4A7C15ull; + auto rnd = [&]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return (uint32_t)x; }; + for (size_t i = 0; i < nw; ++i) { + uint32_t w = 0; + for (int b = 0; b < 4; ++b) { + const uint32_t r = rnd(); + const uint32_t e = 6u + (r >> 8) % 4u; // exponent field 6..9 + w |= (((r & 0x80u) | (e << 3) | (r & 7u)) & 0xFFu) << (8 * b); + } + h8[i] = w; + uint32_t v = 0; + for (int hh = 0; hh < 2; ++hh) { + const uint32_t r = rnd(); + const uint32_t e = 125u + (r >> 16) % 4u; // 2^-2 .. 2^1 + v |= (((r & 0x8000u) | (e << 7) | (r & 0x7Fu)) & 0xFFFFu) << (16 * hh); + } + h16[i] = v; + hi8[i] = rnd(); + } + uint32_t *d8, *d16, *di8; + float* dout; + (void)hipMalloc(&d8, nw * 4); + (void)hipMalloc(&d16, nw * 4); + (void)hipMalloc(&di8, nw * 4); + (void)hipMalloc(&dout, 4); + (void)hipMemcpy(d8, h8.data(), nw * 4, hipMemcpyHostToDevice); + (void)hipMemcpy(d16, h16.data(), nw * 4, hipMemcpyHostToDevice); + (void)hipMemcpy(di8, hi8.data(), nw * 4, hipMemcpyHostToDevice); + if (tile == 0) { + run("fp8", dev, secs, d8, dout, hw); + run("iu8", dev, secs, di8, dout, hw); + run("bf16", dev, secs, d16, dout, hw); + } else { + run("fp8", dev, secs, d8, dout, hw); + run("iu8", dev, secs, di8, dout, hw); + run("bf16", dev, secs, d16, dout, hw); + } + return 0; +} diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 9c7880de..62d488ed 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -554,12 +554,13 @@ int r4d_gemm_mxfp4a8_decode_max_m(void); // R4D_GEMM_W4A8_GROUP). The `_block()` queries report it, and every entry point rejects a K that // would leave a partial block. // -// Three kernels, one per band, because the operand carrying the coarse (per-128-row) scale must be -// the one whose tile is wide; see the AW comment in r4d_gemm_fp8a8.hip. +// Three kernels, one per band. The two W8A8 ones put the weight on the WMMA A operand, so a lane's +// accumulator slots share one activation scale; see r4d_gemm_fp8a8.hip. // // M == 1 r4d_gemm_fp8a16_nt_m1 bf16 activation read directly, no quantise launch -// M <= 16 r4d_gemm_fp8a8_nt_m16 E4M3 activation, one 16-wide token tile, split-K -// any M r4d_gemm_fp8a8_tiled E4M3 activation, 128x128 tile, eight waves +// M <= 64 r4d_gemm_fp8a8_nt_m16 E4M3 activation, up to four 16-wide token tiles, split-K +// any M r4d_gemm_fp8a8_tiled E4M3 activation, 128x128 tile, eight waves; the weight read +// into registers, the activation staged through LDS // // `w_ld` is bytes per weight row and `sw_ld` elements per scale row, 0 meaning tight. All return 0 // or a negative code instead of throwing, since they are reachable from C consumers. @@ -652,6 +653,12 @@ int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, int a_ld, int sa_ld, int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream); int r4d_gemm_fp8a8_gated_nt_m16_max_m(void); +// The narrow GEMM with a bias: `bias` bf16 [N], added to each output column's f32 accumulator before +// its one rounding, and C written at row pitch `c_ld` (0 = N), so C may be a column slice of a wider +// buffer. Never split. M up to r4d_gemm_fp8a8_nt_m16_max_m(); K a multiple of 128, N of 16. +int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws, long bias, long c, + int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, + int c_ld, long stream); int r4d_gemm_fp8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream); diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip index bdc0a1cb..6ef0329e 100644 --- a/libr4d/r4d_attn_dense_bf16.hip +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -1,6 +1,8 @@ -// R4D dense attention for an encoder: non-causal, varlen over cu_seqlens segments, grouped-query, -// with an optional two-sided window |i - j| < window. bf16 in and out, f16 operands, f32 -// accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row. +// R4D dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with +// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is +// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional +// window behind (a codec's sliding layers). bf16 in and out, f16 operands, f32 accumulate. Head +// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row. // // Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32 // column-distributed accumulator gives each lane one query row, softmax state is lane-private, and @@ -36,8 +38,8 @@ template __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32) void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, - const int* __restrict__ cu, float scale, int window, int block, - int cdiv, int q_ld, int k_ld, int v_ld, int o_ld) + const int* __restrict__ cu, float scale, int window, int wright, + int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld) { typedef DT16<1> D; typedef D::frag frag16; @@ -79,12 +81,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re if (slen <= 0 || q0 >= slen) return; const int qlast = min(q0 + BQ, slen) - 1; - // The keys any query of this workgroup can see. + // The keys any query of this workgroup can see: none past its last query when causal. int kb = 0, ke = slen; if (window > 0) { kb = max(0, q0 - (window - 1)); - ke = min(slen, qlast + window); + if (!causal) ke = min(slen, qlast + wright); } + if (causal) ke = min(ke, qlast + 1); const bool blocks = block > 0; if (blocks) { kb = max(kb, q0 / block * block); @@ -128,8 +131,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re // Whether any (query, key) pair of this tile is outside the window or past the keys. // Workgroup-uniform, so interior tiles skip the test. const bool mask = (k0 + TILE > ke) || + (causal && k0 + TILE - 1 > q0) || (window > 0 && (k0 < qlast - (window - 1) || - k0 + TILE - 1 > q0 + (window - 1))) || + k0 + TILE - 1 > q0 + (wright - 1))) || (blocks && (q_straddle || k0 / block != (k0 + TILE - 1) / block || k0 / block != q0 / block)); @@ -223,7 +227,8 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re for (int e = 0; e < 8; ++e) { const int key = kq + e; const int d = qpos - key; - const bool ok = key < ke && (window <= 0 || (d < window && -d < window)) && + const bool ok = key < ke && (!causal || d >= 0) && + (window <= 0 || (d < window && -d < wright)) && (!blocks || key / block == qpos / block); sc[e] = ok ? sc[e] : -INFINITY; } @@ -297,51 +302,63 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re // One instantiation per (head_dim, gqa), at a workgroup shape picked for it: // h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads) // h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB) +// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB) // h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB) template static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o, const void* cu, int num_seqs, int max_seqlen, int n_head_kv, - float scale, int window, int block, int cdiv, int q_ld, int k_ld, - int v_ld, int o_ld, hipStream_t s) + float scale, int window, int wright, int block, int cdiv, + int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s) { constexpr int BQ = NQB * 16; dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs); hipLaunchKernelGGL((r4d_attn_dense_kernel), grid, dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, - (const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, block, - cdiv, q_ld, k_ld, v_ld, o_ld); + (const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright, + block, cdiv, causal, q_ld, k_ld, v_ld, o_ld); const hipError_t e = hipGetLastError(); return e == hipSuccess ? 0 : -100 - (int)e; } // q, o: [tokens, n_head * head_dim]; k, v: [tokens, n_head_kv * head_dim], each at its own token // pitch in elements. cu_seqlens is [num_seqs + 1] int32 on the device; max_seqlen is a host-side -// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment, block -// 0 no blocks; cu_seqlens counts in units cdiv rows apart. +// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment (with +// causal, every earlier key), wright 0 the window's own right side, block 0 no blocks; cu_seqlens +// counts in units cdiv rows apart. extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, void* o, const void* cu_seqlens, int num_seqs, int max_seqlen, int n_head, int n_head_kv, int head_dim, float scale, int window, int block, int cdiv, int q_ld, int k_ld, int v_ld, - int o_ld, void* stream) + int o_ld, void* stream, int wright = 0, int causal = 0) { if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2; if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3; - if (window < 0 || block < 0 || cdiv <= 0) return -4; + if (window < 0 || wright < 0 || block < 0 || cdiv <= 0 || + (wright > 0 && (window == 0 || causal))) + return -4; if (num_seqs <= 0 || max_seqlen <= 0) return 0; + if (wright == 0) wright = window; const int gqa = n_head / n_head_kv; hipStream_t s = (hipStream_t)stream; if (head_dim == 64 && gqa == 1) return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, - n_head_kv, scale, window, block, cdiv, q_ld, - k_ld, v_ld, o_ld, s); + n_head_kv, scale, window, wright, block, + cdiv, causal, q_ld, k_ld, v_ld, o_ld, s); if (head_dim == 256 && gqa == 2) return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, block, - cdiv, q_ld, k_ld, v_ld, o_ld, s); + max_seqlen, n_head_kv, scale, window, + wright, block, cdiv, causal, q_ld, k_ld, + v_ld, o_ld, s); + if (head_dim == 256 && gqa == 4) + return r4d_attn_dense_launch<256, 4, 4, 1, 32>(q, k, v, o, cu_seqlens, num_seqs, + max_seqlen, n_head_kv, scale, window, + wright, block, cdiv, causal, q_ld, k_ld, + v_ld, o_ld, s); if (head_dim == 512 && gqa == 4) return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, block, - cdiv, q_ld, k_ld, v_ld, o_ld, s); + max_seqlen, n_head_kv, scale, window, + wright, block, cdiv, causal, q_ld, k_ld, + v_ld, o_ld, s); return -1; } @@ -357,7 +374,8 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) { const RadTensor* o = r4d_opt(a, DN_OUT); if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); - if (r4d_geti_or(a, "causal", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED); + const long long causal = r4d_geti_or(a, "causal", 0); + if (causal < 0 || causal > 1) return R4D_NO(RAD_E_SHAPE); const long long head_dim = r4d_geti_or(a, "head_dim", 0); const long long gqa = r4d_geti_or(a, "gqa", 1); @@ -381,13 +399,16 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) { if (msl <= 0 || msl > total) msl = total; const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim)); const long long window = r4d_geti_or(a, "window", 0); + const long long wright = r4d_geti_or(a, "window_right", 0); const long long block = r4d_geti_or(a, "block", 0); const long long cdiv = r4d_geti_or(a, "cu_div", 1); + /* A right side needs a non-causal window to be the right side of (libref refuses it alike). */ + if (wright < 0 || (wright > 0 && (window == 0 || causal))) return R4D_NO(RAD_E_SHAPE); const int e = r4d_attn_dense_bf16(q->data, k->data, v->data, o->data, cu->data, num_seqs, (int)msl, (int)nh, (int)hk, (int)head_dim, scale, (int)window, (int)block, (int)cdiv, (int)q_ld, (int)k_ld, - (int)v_ld, (int)o_ld, s); + (int)v_ld, (int)o_ld, s, (int)wright, (int)causal); if (e == 0) return RAD_OK; return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } diff --git a/libr4d/r4d_attn_gen.hip b/libr4d/r4d_attn_gen.hip index a689224e..025043fd 100644 --- a/libr4d/r4d_attn_gen.hip +++ b/libr4d/r4d_attn_gen.hip @@ -22,6 +22,13 @@ // prefix tiles (a few hundred conditioning rows) as they are staged. A score is (q . k) * qs * ks // with an exact integer dot product. At a DiT's 16384 rows this is ~38 -> ~32 ms, with image // error below the spread between exact attention implementations. +// +// FP8 P.V form (`PV8`, op parameter `pv` "fp8", prefix-free and one query head a KV head): V as +// E4M3 codes with a scale per column (quant_cols_fp8's), P.V on v_wmma_f32_16x16x16_fp8_fp8 (half +// the cycles of bf16) with P as E4M3 codes of 448 p. E4M3 ends at 448, so the softmax keeps an +// exact running max, taken over a whole 64-key tile so that its test runs once a tile; the row +// sum takes the unrounded 448 p and the epilogue multiplies by the column scale. The V tile is +// staged as the transposing load over pairs of codes, split by byte permutes into V^T rows. #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" @@ -48,12 +55,16 @@ __device__ __forceinline__ float ps_amax8(uint4 u) { fmaxf(fmaxf(fabsf(ps_lo(u.z)), fabsf(ps_hi(u.z))), fmaxf(fabsf(ps_lo(u.w)), fabsf(ps_hi(u.w))))); } +// log2(448) less 2^-16: exp2 of it is 448 (1 - 1.1e-5), under 448 with room for the hardware +// exp2's error, and still the E4M3 code of 448. +constexpr float kPsLog448 = 8.8073397f; + __device__ __forceinline__ uint2 ps_q8x8(uint4 u, float inv) { return make_uint2(ps_q8x4(ps_lo(u.x), ps_hi(u.x), ps_lo(u.y), ps_hi(u.y), inv), ps_q8x4(ps_lo(u.z), ps_hi(u.z), ps_lo(u.w), ps_hi(u.w), inv)); } -template +template __global__ __launch_bounds__(NQB * GQA * 32) void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, const int8_t* __restrict__ gk8, const float* __restrict__ gks, @@ -62,7 +73,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr const int* __restrict__ bt, int bt_pitch, const uint16_t* __restrict__ kvc, int kv_heads, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, - int v_ld, int o_ld) + int v_ld, int o_ld, const float* __restrict__ gvs) { typedef DT16<0> D; typedef D::frag frag16; @@ -92,11 +103,18 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR; static_assert(!I8 || (DG == 16 && NTHR % 32 == 0), "an int8 prefix key is one half-wave"); + // E4M3 V^T tile: HD rows of TILE key bytes padded by 8, so a fragment read's sixteen rows + // (8 bytes a lane) fall on distinct bank pairs. One 16-byte unit (16 dims of 8 keys) a thread: + // unit u is key group u / DG8 and dims 16 (u % DG8), so a wave reads whole half-rows. + constexpr int VSTR8 = TILE + 8; + constexpr int DG8 = HD / 16; + static_assert(!PV8 || (GQA == 1 && KGRP * DG8 == LGRP), "one E4M3 V unit a thread"); __shared__ __align__(16) uint16_t sK[I8 ? 8 : TILE * KSTR]; __shared__ __align__(16) int8_t sK8[I8 ? TILE * KSTR8 : 16]; __shared__ __align__(16) float sKs[I8 ? TILE : 4]; - __shared__ __align__(16) uint16_t sV[HD * VSTR]; + __shared__ __align__(16) uint16_t sV[PV8 ? 8 : HD * VSTR]; + __shared__ __align__(16) uint8_t sV8[PV8 ? HD * VSTR8 : 16]; const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; const int c = lane & 15, h = lane >> 4; @@ -222,14 +240,21 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr } } } - #pragma unroll - for (int r = 0; r < VP; ++r) { - const int u = lgi + r * LGRP; - if (NTR % LGRP == 0 || u < NTR) { - const int kg = u % KGRP, dg = u / KGRP; - const int kk0 = k0 + kg * 8 + vj; - const int kk = (kk0 < klim) ? kk0 : klim - 1; - vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8)); + if constexpr (PV8) { + const int kk0 = k0 + (lgi / DG8) * 8 + vj; + const int kk = (kk0 < klim) ? kk0 : klim - 1; + const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD; + vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16)); + } else { + #pragma unroll + for (int r = 0; r < VP; ++r) { + const int u = lgi + r * LGRP; + if (NTR % LGRP == 0 || u < NTR) { + const int kg = u % KGRP, dg = u / KGRP; + const int kk0 = k0 + kg * 8 + vj; + const int kk = (kk0 < klim) ? kk0 : klim - 1; + vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8)); + } } } // Int8 prefix key: row absmax over its DG lanes (one half-wave, DPP butterfly), then eight @@ -250,12 +275,25 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr } lds_barrier(); - #pragma unroll - for (int r = 0; r < VP; ++r) { - const int u = lgi + r * LGRP; - if (NTR % LGRP == 0 || u < NTR) { - const int kg = u % KGRP, dg = u / KGRP; - *(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r]; + if constexpr (PV8) { + // Lane j holds dims 2 j and 2 j + 1 of the group's eight keys interleaved, a key a + // 16-bit pair: even bytes are one V^T row, odd bytes the next. + const int row = (lgi % DG8) * 16 + 2 * vj, col = (lgi / DG8) * 8; + const uint4 w = vr[0]; + *(uint2*)&sV8[row * VSTR8 + col] = + make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x06040200u), + __builtin_amdgcn_perm(w.w, w.z, 0x06040200u)); + *(uint2*)&sV8[(row + 1) * VSTR8 + col] = + make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x07050301u), + __builtin_amdgcn_perm(w.w, w.z, 0x07050301u)); + } else { + #pragma unroll + for (int r = 0; r < VP; ++r) { + const int u = lgi + r * LGRP; + if (NTR % LGRP == 0 || u < NTR) { + const int kg = u % KGRP, dg = u / KGRP; + *(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r]; + } } } if constexpr (I8) { @@ -290,6 +328,133 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr } lds_barrier(); + if constexpr (PV8) { + // The whole tile's scores, one exact running max over them, P as E4M3 codes of 448 p, + // then the tile's fp8 WMMAs. The max is kept in the scores' own units (the int8 + // form's are unscaled, `qs` being one positive factor a row), so s - max is at most 0 + // exactly and x = exp2((s - max) qs + kPsLog448) cannot pass exp2(kPsLog448) < 448, + // where v_cvt_pk_fp8_f32 would give NaN. x is 448 p up to a factor common to every + // key, which the row sum shares. + float sc[MT][8]; + #pragma unroll + for (int mt = 0; mt < MT; mt += (I8 ? 2 : 1)) { + if constexpr (I8) { + // Two blocks' int8 chains interleaved: each WMMA waits on the one two back. + v8i_ps s0 = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0}, s1 = s0; + const int8_t* r0 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h; + const int8_t* r1 = r0 + 16 * KSTR8; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_ps k0[4], k1[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) { + const uint2 u0 = *(const uint2*)(r0 + 16 * (t0 + j)); + const uint2 u1 = *(const uint2*)(r1 + 16 * (t0 + j)); + k0[j] = (v2i_ps){ (int)u0.x, (int)u0.y }; + k1[j] = (v2i_ps){ (int)u1.x, (int)u1.y }; + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) { + s0 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, k0[j], true, qf[t0 + j], s0, false); + s1 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, k1[j], true, qf[t0 + j], s1, false); + } + } + #pragma unroll + for (int b = 0; b < 2; ++b) { + const float4 ka = *(const float4*)&sKs[(mt + b) * 16 + 8 * h]; + const float4 kb = *(const float4*)&sKs[(mt + b) * 16 + 8 * h + 4]; + const float ks[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) + sc[mt + b][e] = (float)(b ? s1[e] : s0[e]) * ks[e]; + } + } else { + v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + const uint16_t* kr2 = &sK[(mt * 16 + c) * KSTR] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 kf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) { + const uint4 u = *(const uint4*)(kr2 + 16 * (t0 + j)); + kf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) s = D::wmma(kf[j], qf[t0 + j], s); + } + #pragma unroll + for (int e = 0; e < 8; ++e) sc[mt][e] = s[e]; + } + } + if (mask) { + #pragma unroll + for (int mt = 0; mt < MT; ++mt) { + const int kq0 = k0 + mt * 16 + 8 * h; + #pragma unroll + for (int e = 0; e < 8; ++e) { + const int key = kq0 + e; + const bool ok = key < klim && (!causal || key <= qpos); + sc[mt][e] = ok ? sc[mt][e] : -INFINITY; + } + } + } + float smax = sc[0][0]; + #pragma unroll + for (int mt = 0; mt < MT; ++mt) + #pragma unroll + for (int e = 0; e < 8; ++e) smax = fmaxf(smax, sc[mt][e]); + if (wave_any(smax > m_ref)) { + const float rmax = fmaxf(smax, swap16(smax)); + const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f); + const float alpha = ex2(I8 ? (m_ref - mnew) * qs : m_ref - mnew); + #pragma unroll + for (int t = 0; t < NKS; ++t) + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= alpha; + l_i *= alpha; + m_ref = mnew; + } + #pragma unroll + for (int mt = 0; mt < MT; ++mt) { + float x[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) { + const float d = sc[mt][e] - m_ref; + x[e] = ex2(I8 ? __builtin_fmaf(d, qs, kPsLog448) : d + kPsLog448); + } + l_i += ((x[0] + x[1]) + (x[2] + x[3])) + ((x[4] + x[5]) + (x[6] + x[7])); + // The first conversion's high half is dead (the second writes it), so any live + // register serves as its old value: no zeroing moves. + int w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[0], x[1], __builtin_bit_cast(int, x[0]), + false); + w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[2], x[3], w0, true); + int w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[4], x[5], __builtin_bit_cast(int, x[4]), + false); + w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[6], x[7], w1, true); + const v2i_ps p8 = (v2i_ps){ w0, w1 }; + const uint8_t* vr2 = &sV8[c * VSTR8 + mt * 16 + 8 * h]; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_ps vf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) { + const uint2 u = *(const uint2*)(vr2 + (t0 + j) * 16 * VSTR8); + vf[j] = (v2i_ps){ (int)u.x, (int)u.y }; + } + sched_barrier(); + #pragma unroll + for (int j = 0; j < 4; ++j) + acc[t0 + j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12( + vf[j], p8, acc[t0 + j]); + } + } + continue; + } + #pragma unroll 1 for (int mt = 0; mt < MT; ++mt) { // Scores of 16 keys, in log2 units once multiplied by `qs` (int8 only; the bf16 query @@ -414,6 +579,14 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr #pragma unroll for (int t = 0; t < NKS; ++t) { uint32_t tw[4]; + if constexpr (PV8) { + // The column scales of the lane's eight dims. + const float4 sa = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h); + const float4 sb = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h + 4); + const float vsc[8] = { sa.x, sa.y, sa.z, sa.w, sb.x, sb.y, sb.z, sb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= vsc[e]; + } #pragma unroll for (int e = 0; e < 8; e += 2) tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv) @@ -422,22 +595,23 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr } } -template +template static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks, const void* v, void* o, const int* cu, const int* used, const int* bt, int bt_pitch, const void* kvc, int num_seqs, int max_q, int n_head_kv, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld, - hipStream_t s) + const float* vs, hipStream_t s) { constexpr int BQ = NQB * 16; // At most total / BQ full blocks plus one partial block per sequence. dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1); - hipLaunchKernelGGL((r4d_attn_ps_kernel), grid, dim3(NQB * GQA * 32), 0, s, + hipLaunchKernelGGL((r4d_attn_ps_kernel), grid, + dim3(NQB * GQA * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks, (const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch, (const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld, - v_ld, o_ld); + v_ld, o_ld, vs); const hipError_t e = hipGetLastError(); return e == hipSuccess ? 0 : -100 - (int)e; } @@ -445,13 +619,14 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons /* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form). * `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8` * selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in - * `ks`, `ks_ld` floats per row), gqa 1 only. */ + * `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3 + * codes, `v_ld` bytes per row; `vs` their column scales), gqa 1 and no prefix only. */ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks, const void* v, void* o, const int* cu, const int* used, const int* bt, int bt_pitch, const void* kvc, int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, - int v_ld, int o_ld, hipStream_t s) + int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr) { if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2; if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3; @@ -460,12 +635,23 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float const int gqa = n_head / n_head_kv; if (head_dim != 128) return -1; #define R4D_PS(G, NQB, T, I8) \ - return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \ - num_seqs, max_q, n_head_kv, scale, causal, \ - q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s) + return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \ + bt_pitch, kvc, num_seqs, max_q, \ + n_head_kv, scale, causal, q_ld, k_ld, \ + k8_ld, ks_ld, v_ld, o_ld, nullptr, s) /* Sixteen query tiles per workgroup at gqa 1: a workgroup streams its head's whole K and V * once, so more rows per workgroup divide that traffic. At 16384 rows a head's K/V (8 MB) do * not fit L2; 128 rows per workgroup gave 66 TFLOP/s, 256 gave 111, 512 gave 102. */ + if (vs) { + if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1; + if (k8) + return r4d_attn_ps_launch<128, 1, 16, 64, true, true>( + q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, + scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s); + return r4d_attn_ps_launch<128, 1, 16, 64, false, true>( + q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale, + causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s); + } if (k8) { if (gqa != 1) return -1; R4D_PS(1, 16, 64, true); @@ -482,7 +668,7 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float // ============================================================== the plugin ABI entry points enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS, - PS_OUT }; + PS_OUT, PS_VS }; extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { const RadTensor* q = r4d_opt(a, PS_Q); @@ -493,16 +679,32 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { const RadTensor* su = r4d_opt(a, PS_USED); const RadTensor* cu = r4d_opt(a, PS_CU); const RadTensor* o = r4d_opt(a, PS_OUT); - if (!q || !k || !v || !kv || !bt || !su || !cu || !o) return R4D_NO(RAD_E_INVAL); + if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); + /* The paged prefix is the cache, its block table and the per-sequence prefix lengths, all + * three or none: without them the op is self attention over each sequence's rows. */ + const bool pre = kv != nullptr; + if (pre != (bt != nullptr) || pre != (su != nullptr)) return R4D_NO(RAD_E_INVAL); if (r4d_opt(a, PS_KDES) || r4d_opt(a, PS_VDES)) return R4D_NO(RAD_E_UNSUPPORTED); - if (kv->dtype != RAD_BF16 || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if ((pre && kv->dtype != RAD_BF16) || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + /* The fp8 P.V form (`pv` "fp8"): `v` as E4M3 codes [tokens, kv_heads * head_dim] and their + * column scales `v_scale` [kv_heads * head_dim], as quant_cols_fp8 writes them; prefix-free, + * one query head a KV head. */ + const RadTensor* vs = r4d_opt(a, PS_VS); + const char* pvs = r4d_gets(a, "pv"); + const bool pv8 = pvs && !std::strcmp(pvs, "fp8"); + if (pvs && !pv8 && std::strcmp(pvs, "bf16")) return R4D_NO(RAD_E_INVAL); + if (pv8 != (vs != nullptr)) return R4D_NO(RAD_E_INVAL); + if (pv8 && pre) return R4D_NO(RAD_E_UNSUPPORTED); + if (pv8 && (v->dtype != RAD_F8E4M3 || vs->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE); + if (pv8 && r4d_geti_or(a, "gqa", 1) != 1) return R4D_NO(RAD_E_UNSUPPORTED); const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); - if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd) return R4D_NO(RAD_E_SHAPE); - if (!r4d_contig(cu) || !r4d_contig(su) || cu->rank != 1 || cu->shape[0] < 2) + if (pre && (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd)) + return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(cu) || (pre && !r4d_contig(su)) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const int num_seqs = (int)(cu->shape[0] - 1); - if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE); + if (pre && r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE); long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; long long to = 0, ho = 0, o_ld = 0; if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) || @@ -510,10 +712,11 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { !r4d_head_rows(v, hd, &tv, &hv, &v_ld) || !r4d_head_rows(o, hd, &to, &ho, &o_ld)) return R4D_NO(RAD_E_STRIDE); - if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE); + if (hk != hv || ho != nh || hk * gqa != nh || (pre && hk != kv->shape[1])) + return R4D_NO(RAD_E_SHAPE); if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); - const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs; - if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); + const long long bt_pitch = !pre ? 0 : bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs; + if (pre && bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); const long long mq = total; /* Int8 Q.K form (`qk` "i8"): own-key codes [tokens, kv_heads * head_dim] and scales * [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */ @@ -532,13 +735,21 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) { if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE); if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE); } + if (pv8) { + if (!r4d_contig(vs) || ((uintptr_t)vs->data & 15) || (v_ld & 15) || + ((uintptr_t)v->data & 15)) + return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(vs) < hk * hd) return R4D_NO(RAD_E_SHAPE); + } const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); const int e = r4d_attn_ps(q->data, k->data, k8 ? k8->data : nullptr, ks ? (const float*)ks->data : nullptr, v->data, o->data, - (const int*)cu->data, (const int*)su->data, (const int*)bt->data, - (int)bt_pitch, kv->data, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd, + (const int*)cu->data, pre ? (const int*)su->data : nullptr, + pre ? (const int*)bt->data : nullptr, (int)bt_pitch, + pre ? kv->data : nullptr, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd, scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, - (int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s); + (int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s, + pv8 ? (const float*)vs->data : nullptr); if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); if (e == 0) return RAD_OK; return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip new file mode 100644 index 00000000..8bf20db2 --- /dev/null +++ b/libr4d/r4d_audio.hip @@ -0,0 +1,1610 @@ +// R4D -- the audio generator's ops (docs/OPS.md, "Audio generation"): a vocoder's 1-D +// convolutions and snake activation, the guided top-k sampler a frame's codes are drawn with, a +// frame's residual-code embedding and conditioning row, and the window ops of a denoiser that +// runs over overlapping runs of frames. +// +// Each kernel rounds where its libref function does (libref/ref_audio.cpp). Only reduction order +// differs (a WMMA tile here, a sequential sum there), so a sum can land one bf16 step apart. +// +// Sequenced operands follow every sequenced op here: `cu_seqlens` holds row indices of the +// operands themselves, and each sequence is padded on its own. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_f32_tile.h" +#include "r4d_gdn_wmma.h" +#include "rad_philox.h" + +#include +#include + +namespace { + +constexpr int kT = 256; + +// A window entry's flags (RadAudioGenBatch, RAD_AGEN_F_*), as libref restates them. +enum { kFirst = 1, kLast = 8, kJoin = 16 }; + +__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); } + +__device__ __forceinline__ void ld8(const uint16_t* p, float* f) { + const uint4 u = *(const uint4*)p; + f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y); + f[4] = bf16w_lo(u.z); f[5] = bf16w_hi(u.z); f[6] = bf16w_lo(u.w); f[7] = bf16w_hi(u.w); +} +__device__ __forceinline__ void st8(uint16_t* p, const float* f) { + uint4 u; + u.x = (uint32_t)f32_to_bf16(f[0]) | ((uint32_t)f32_to_bf16(f[1]) << 16); + u.y = (uint32_t)f32_to_bf16(f[2]) | ((uint32_t)f32_to_bf16(f[3]) << 16); + u.z = (uint32_t)f32_to_bf16(f[4]) | ((uint32_t)f32_to_bf16(f[5]) << 16); + u.w = (uint32_t)f32_to_bf16(f[6]) | ((uint32_t)f32_to_bf16(f[7]) << 16); + *(uint4*)p = u; +} + +// The sequence that owns row r: linear, because a vocoder pass has two (a stereo pair) and a +// window pass a handful. +__device__ __forceinline__ int seq_of(const int* cu, int n_seq, int r) { + int s = 0; + while (s + 1 < n_seq && cu[s + 1] <= r) ++s; + return s; +} + +__device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) { + return (uint64_t)seed[2 * e] | ((uint64_t)seed[2 * e + 1] << 32); +} + +// ---------------------------------------------------------------------------- conv1d +// An implicit GEMM, r4d_gen.hip's conv_igemm_kernel cut to one dimension: y[row][cout] = sum +// over (tap, cin) of x[row + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored +// tap-major (r4d_layout.cpp relayouts PyTorch's [cout][cin][k] at load), so a 64-wide K tile is +// eight 16-byte reads of input rows. A chunk outside its row's sequence reads zeros, which is the +// per-sequence padding. Eight waves, BP rows x BC output channels a block, the next K tile's +// loads in flight under the current WMMA. +#define C1_BK 64 +#define C1_PITCH (C1_BK + 8) + +// The output activation: 0 none, 1 tanh, 2 a clamp to [-1, 1] (a vocoder's output clamp), which +// leaves a NaN a NaN as libref's comparisons do (fminf / fmaxf would return the bound). +__device__ __forceinline__ float conv_act(float v, int act) { + if (act == 1) return tanhf(v); + if (act == 2) return v < -1.0f ? -1.0f : (v > 1.0f ? 1.0f : v); + return v; +} + +template +__global__ __launch_bounds__(256) void conv1d_igemm_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res, + const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end, + int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16; + constexpr int CPR = C1_BK / 8; + constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256; + static_assert(AL >= 1 && WL >= 1, "every thread stages whole chunks"); + __shared__ __attribute__((aligned(16))) uint16_t sA[BP * C1_PITCH]; + __shared__ __attribute__((aligned(16))) uint16_t sW[BC * C1_PITCH]; + + const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31; + const int wp = wave / 4, wc = wave % 4; + const int p0 = r_beg + blockIdx.x * BP, c0 = blockIdx.y * BC; + const int K = k * cin; + + int a_row[AL], a_t[AL], a_ci[AL], a_s0[AL], a_s1[AL]; + bool a_ok[AL]; + uint16_t* adst[AL]; + #pragma unroll + for (int i = 0; i < AL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int m = p0 + r; + a_ok[i] = m < r_end; + a_row[i] = a_ok[i] ? m : r_beg; + const int sq = seq_of(cu, n_seq, a_row[i]); + a_s0[i] = cu[sq]; + a_s1[i] = cu[sq + 1]; + a_t[i] = e / cin; + a_ci[i] = e % cin; + adst[i] = sA + r * C1_PITCH + e; + } + size_t w_off[WL]; + int w_e[WL]; + bool w_ok[WL]; + uint16_t* wdst[WL]; + #pragma unroll + for (int i = 0; i < WL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int co = c0 + r; + w_ok[i] = co < cout; + w_off[i] = (size_t)(w_ok[i] ? co : 0) * K + e; + w_e[i] = e; + wdst[i] = sW + r * C1_PITCH + e; + } + const r4d_u32x4 zero = {0u, 0u, 0u, 0u}; + auto loadA = [&](int i) -> r4d_u32x4 { + if (!a_ok[i] || a_t[i] >= k) return zero; + const int ir = a_row[i] + a_t[i] * dil - pad; + if (ir < a_s0[i] || ir >= a_s1[i]) return zero; + return *(const r4d_u32x4*)(x + (size_t)ir * x_ld + a_ci[i]); + }; + auto loadW = [&](int i, int kt) -> r4d_u32x4 { + if (!w_ok[i] || kt * C1_BK + w_e[i] >= K) return zero; + return *(const r4d_u32x4*)(w + w_off[i] + (size_t)kt * C1_BK); + }; + + const uint16_t* fa = sA + (wp * TP * 16 + (lane & 15)) * C1_PITCH + 4 * (lane >> 4); + const uint16_t* fw = sW + (wc * TC * 16 + (lane & 15)) * C1_PITCH + 4 * (lane >> 4); + + v8f acc[TC][TP]; + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = (v8f)(0.f); + + r4d_u32x4 ra[AL], rw[WL]; + #pragma unroll + for (int i = 0; i < AL; ++i) ra[i] = loadA(i); + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, 0); + + const int nk = (K + C1_BK - 1) / C1_BK; + for (int kt = 0; kt < nk; ++kt) { + __syncthreads(); + #pragma unroll + for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i]; + #pragma unroll + for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i]; + __syncthreads(); + if (kt + 1 < nk) { + #pragma unroll + for (int i = 0; i < AL; ++i) { + a_ci[i] += C1_BK; + while (a_ci[i] >= cin) { a_ci[i] -= cin; ++a_t[i]; } + ra[i] = loadA(i); + } + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, kt + 1); + } + #pragma unroll + for (int s = 0; s < C1_BK / 16; ++s) { + v8bf af[TP], wf[TC]; + #pragma unroll + for (int i = 0; i < TP; ++i) af[i] = fragP(fa + i * 16 * C1_PITCH + s * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) wf[j] = fragP(fw + j * 16 * C1_PITCH + s * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = mma(wf[j], af[i], acc[j][i]); + } + } + + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) { + const int row = p0 + (wp * TP + i) * 16 + (lane & 15); + const int co = c0 + (wc * TC + j) * 16 + 8 * (lane >> 4); + if (row >= r_end || co >= cout) continue; + uint16_t* dst = y + (size_t)row * y_ld + co; + float f[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) { + float v = acc[j][i][e]; + if (co + e < cout) { + if (bias) v += bf2f(bias[co + e]); + if (res) v += bf2f(res[(size_t)row * res_ld + co + e]); + v = conv_act(v, act); + } + f[e] = v; + } + if (co + 8 <= cout && (cout & 7) == 0) { + st8(dst, f); + } else { + #pragma unroll + for (int e = 0; e < 8; ++e) + if (co + e < cout) dst[e] = f32_to_bf16(f[e]); + } + } +} + +// The direct form, for a channel count the tiled kernel does not take (a cin not a multiple of +// eight, or a handful of output channels -- a vocoder's last conv has one): a thread an output +// element, f32 over (tap, cin), the same tap-major weight. +__global__ __launch_bounds__(kT) void conv1d_direct_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res, + const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end, + int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + const int64_t total = (int64_t)(r_end - r_beg) * cout; + if (t >= total) return; + const int co = (int)(t % cout); + const int row = r_beg + (int)(t / cout); + const int sq = seq_of(cu, n_seq, row); + const int s0 = cu[sq], s1 = cu[sq + 1]; + float acc = 0.0f; + for (int kk = 0; kk < k; ++kk) { + const int ir = row + kk * dil - pad; + if (ir < s0 || ir >= s1) continue; + const uint16_t* xp = x + (size_t)ir * x_ld; + const uint16_t* wp = w + ((size_t)co * k + kk) * cin; + for (int ci = 0; ci < cin; ++ci) acc += bf2f(wp[ci]) * bf2f(xp[ci]); + } + if (bias) acc += bf2f(bias[co]); + if (res) acc += bf2f(res[(size_t)row * res_ld + co]); + acc = conv_act(acc, act); + y[(size_t)row * y_ld + co] = f32_to_bf16(acc); +} + +// ---------------------------------------------------------------------------- conv_t1d +// The transposed convolution of kernel `taps` s (two taps or one), stride s, padding P +// ((k - s) / 2, or 0 for the causal form) as s convolutions of `taps` taps, one a grid slice +// (blockIdx.z is the phase r): output row lo = q s + r - P of a sequence of L input rows reads +// x[q - t] for each tap t (PyTorch's tap r + t s). For a phase below P the q that land inside the +// sequence are 1..L, otherwise 0..L-1, so each phase has L output rows, one per input row: the M +// dimension is the input rows, as for conv1d. The weight is relayouted to [s][cout][taps][cin], +// which does not depend on P. +template +__global__ __launch_bounds__(256) void conv_t1d_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + const uint16_t* __restrict__ bias, const int* __restrict__ cu, uint16_t* __restrict__ y, + int n_seq, int r_beg, int r_end, int cin, int cout, int s, int P, int taps, int x_ld, + int y_ld) { + constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16; + constexpr int CPR = C1_BK / 8; + constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256; + static_assert(AL >= 1 && WL >= 1, "every thread stages whole chunks"); + __shared__ __attribute__((aligned(16))) uint16_t sA[BP * C1_PITCH]; + __shared__ __attribute__((aligned(16))) uint16_t sW[BC * C1_PITCH]; + + const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31; + const int wp = wave / 4, wc = wave % 4; + const int p0 = r_beg + blockIdx.x * BP, c0 = blockIdx.y * BC; + const int ph = blockIdx.z, qoff = ph < P ? 1 : 0; + const int K = taps * cin; + const uint16_t* wph = w + (size_t)ph * cout * K; + + int a_q[AL], a_t[AL], a_ci[AL], a_s0[AL], a_len[AL]; + bool a_ok[AL]; + uint16_t* adst[AL]; + #pragma unroll + for (int i = 0; i < AL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int m = p0 + r; + a_ok[i] = m < r_end; + const int mm = a_ok[i] ? m : r_beg; + const int sq = seq_of(cu, n_seq, mm); + a_s0[i] = cu[sq]; + a_len[i] = cu[sq + 1] - cu[sq]; + a_q[i] = mm - cu[sq] + qoff; + a_t[i] = e / cin; + a_ci[i] = e % cin; + adst[i] = sA + r * C1_PITCH + e; + } + size_t w_off[WL]; + int w_e[WL]; + bool w_ok[WL]; + uint16_t* wdst[WL]; + #pragma unroll + for (int i = 0; i < WL; ++i) { + const int c = tid + 256 * i, r = c / CPR, e = (c % CPR) * 8; + const int co = c0 + r; + w_ok[i] = co < cout; + w_off[i] = (size_t)(w_ok[i] ? co : 0) * K + e; + w_e[i] = e; + wdst[i] = sW + r * C1_PITCH + e; + } + const r4d_u32x4 zero = {0u, 0u, 0u, 0u}; + auto loadA = [&](int i) -> r4d_u32x4 { + if (!a_ok[i] || a_t[i] >= taps) return zero; + const int qi = a_q[i] - a_t[i]; + if (qi < 0 || qi >= a_len[i]) return zero; + return *(const r4d_u32x4*)(x + (size_t)(a_s0[i] + qi) * x_ld + a_ci[i]); + }; + auto loadW = [&](int i, int kt) -> r4d_u32x4 { + if (!w_ok[i] || kt * C1_BK + w_e[i] >= K) return zero; + return *(const r4d_u32x4*)(wph + w_off[i] + (size_t)kt * C1_BK); + }; + + const uint16_t* fa = sA + (wp * TP * 16 + (lane & 15)) * C1_PITCH + 4 * (lane >> 4); + const uint16_t* fw = sW + (wc * TC * 16 + (lane & 15)) * C1_PITCH + 4 * (lane >> 4); + + v8f acc[TC][TP]; + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = (v8f)(0.f); + + r4d_u32x4 ra[AL], rw[WL]; + #pragma unroll + for (int i = 0; i < AL; ++i) ra[i] = loadA(i); + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, 0); + + const int nk = (K + C1_BK - 1) / C1_BK; + for (int kt = 0; kt < nk; ++kt) { + __syncthreads(); + #pragma unroll + for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i]; + #pragma unroll + for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i]; + __syncthreads(); + if (kt + 1 < nk) { + #pragma unroll + for (int i = 0; i < AL; ++i) { + a_ci[i] += C1_BK; + while (a_ci[i] >= cin) { a_ci[i] -= cin; ++a_t[i]; } + ra[i] = loadA(i); + } + #pragma unroll + for (int i = 0; i < WL; ++i) rw[i] = loadW(i, kt + 1); + } + #pragma unroll + for (int ss = 0; ss < C1_BK / 16; ++ss) { + v8bf af[TP], wf[TC]; + #pragma unroll + for (int i = 0; i < TP; ++i) af[i] = fragP(fa + i * 16 * C1_PITCH + ss * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) wf[j] = fragP(fw + j * 16 * C1_PITCH + ss * 16); + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) acc[j][i] = mma(wf[j], af[i], acc[j][i]); + } + } + + #pragma unroll + for (int j = 0; j < TC; ++j) + #pragma unroll + for (int i = 0; i < TP; ++i) { + const int m = p0 + (wp * TP + i) * 16 + (lane & 15); + const int co = c0 + (wc * TC + j) * 16 + 8 * (lane >> 4); + if (m >= r_end || co >= cout) continue; + const int sq = seq_of(cu, n_seq, m); + const int q = m - cu[sq] + qoff; + const int orow = cu[sq] * s + q * s + ph - P; + uint16_t* dst = y + (size_t)orow * y_ld + co; + float f[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) f[e] = acc[j][i][e] + (co + e < cout ? bf2f(bias[co + e]) : 0.f); + if (co + 8 <= cout && (cout & 7) == 0) { + st8(dst, f); + } else { + #pragma unroll + for (int e = 0; e < 8; ++e) + if (co + e < cout) dst[e] = f32_to_bf16(f[e]); + } + } +} + +// ---------------------------------------------------------------------------- f32 convolutions +// conv1d and conv_t1d over f32 rows, weights and biases (a vocoder kept in f32): the implicit GEMMs +// above on r4d_f32_tile.h's f32 tile, the weights relayouted alike by r4d_layout.cpp's _f32 hooks. +// The tile's rows are the output rows (conv1d) or one phase's input rows (conv_t1d), its columns +// the output channels, its K the (tap, channel) pairs, channel innermost. A thread stages one K +// column a slab and steps it sixteen at a time, so no K index is divided after the first. + +// conv1d's A: output row m's tap t reads input row m + t dil - pad of m's own sequence, zero +// outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an address +// clamped into x's first `r_end` rows and the zero selected after it. +template +struct Conv1dRows { + const float* x; + const int* cu; + int n_seq, r_end, cin, k, dil, pad, x_ld; + int row[CNT], s0[CNT], s1[CNT]; + int t = 0, ci = 0; + __device__ void init(int first_row, int kk) { +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const int m = first_row + 16 * j; + row[j] = m < r_end ? m : -1; + const int sq = seq_of(cu, n_seq, m < r_end ? m : r_end - 1); + s0[j] = cu[sq]; + s1[j] = cu[sq + 1]; + } + t = kk / cin; + ci = kk % cin; + } + __device__ void fetch(float (&v)[CNT]) const { +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const int ir = row[j] + t * dil - pad; + const bool live = row[j] >= 0 && t < k && ir >= s0[j] && ir < s1[j]; + const int irc = ir < 0 ? 0 : (ir >= r_end ? r_end - 1 : ir); + const float xv = x[(uint32_t)irc * (uint32_t)x_ld + (uint32_t)ci]; + v[j] = live ? xv : 0.0f; + } + } + __device__ void advance() { + ci += r4d_f32::kBK; + while (ci >= cin) { ci -= cin; ++t; } + } +}; + +// `res` may be `y` itself (a residual chain updated in place): each element is read by the thread +// that stores it, before the store. +template +__global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel( + const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias, + const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin, + int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + constexpr int TM = 8, BM = 16 * TM, BN = 16 * TN; + const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; + const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; + const int K = k * cin; + Conv1dRows la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld }; + r4d_f32::RowsLoader lw{ w, K, cout, K }; + la.init(m0 + ty, tx); + lw.init(n0 + ty, tx); + auto ep = [&](int r, int c, int cnt, float4 q, int) { + const int m = m0 + r, co = n0 + c; + if (m >= rows) return; + const float v[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < 4; ++e) { + if (e >= cnt || co + e >= cout) continue; + float a = v[e]; + if (bias) a += bias[co + e]; + if (res) a += res[(size_t)m * res_ld + co + e]; + y[(size_t)m * y_ld + co + e] = conv_act(a, act); + } + }; + r4d_f32::tile(la, lw, K, ep); +} + +// The direct form for a handful of output channels (a vocoder's last convolutions have 8 and 1): +// a thread an output element over the same tap-major weight. +__global__ __launch_bounds__(kT) void conv1d_f32_direct_kernel( + const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias, + const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin, + int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= (int64_t)rows * cout) return; + const int co = (int)(t % cout); + const int row = (int)(t / cout); + const int sq = seq_of(cu, n_seq, row); + const int s0 = cu[sq], s1 = cu[sq + 1]; + float acc = 0.0f; + for (int kk = 0; kk < k; ++kk) { + const int ir = row + kk * dil - pad; + if (ir < s0 || ir >= s1) continue; + const float* xp = x + (size_t)ir * x_ld; + const float* wp = w + ((size_t)co * k + kk) * cin; + for (int ci = 0; ci < cin; ++ci) acc = __builtin_fmaf(wp[ci], xp[ci], acc); + } + if (bias) acc += bias[co]; + if (res) acc += res[(size_t)row * res_ld + co]; + y[(size_t)row * y_ld + co] = conv_act(acc, act); +} + +// conv_t1d's A at phase r: input row m of a sequence at s0 is that phase's q = m - s0 + qoff, +// whose output row is q stride + r - pad, and its tap t reads input row q - t of the sequence, +// zero outside it. `qoff` is the phase's first q with a non-negative output row. Loads are +// issued unguarded, as Conv1dRows'. +template +struct ConvT1dRows { + const float* x; + const int* cu; + int n_seq, r_end, cin, taps, qoff, x_ld; + int s0[CNT], len[CNT], q[CNT]; + bool ok[CNT]; + int t = 0, ci = 0; + __device__ void init(int first_row, int kk) { +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const int m = first_row + 16 * j; + ok[j] = m < r_end; + const int sq = seq_of(cu, n_seq, ok[j] ? m : r_end - 1); + s0[j] = cu[sq]; + len[j] = cu[sq + 1] - cu[sq]; + q[j] = m - s0[j] + qoff; + } + t = kk / cin; + ci = kk % cin; + } + __device__ void fetch(float (&v)[CNT]) const { +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const int qi = q[j] - t; + const bool live = ok[j] && t < taps && qi >= 0 && qi < len[j]; + const int ir = s0[j] + qi; + const int irc = ir < 0 ? 0 : (ir >= r_end ? r_end - 1 : ir); + const float xv = x[(uint32_t)irc * (uint32_t)x_ld + (uint32_t)ci]; + v[j] = live ? xv : 0.0f; + } + } + __device__ void advance() { + ci += r4d_f32::kBK; + while (ci >= cin) { ci -= cin; ++t; } + } +}; + +// One phase a grid slice (blockIdx.z): its weight is [cout][taps cin], taps past k zero. +template +__global__ __launch_bounds__(r4d_f32::kThr) void conv_t1d_f32_kernel( + const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias, + const int* __restrict__ cu, float* __restrict__ y, int n_seq, int rows, int cin, int cout, + int s, int P, int taps, int x_ld, int y_ld) { + constexpr int TM = 8, BM = 16 * TM, BN = 16 * TN; + const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; + const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN, ph = blockIdx.z; + const int K = taps * cin; + const int qoff = P >= ph ? (P - ph + s - 1) / s : 0; + ConvT1dRows la{ x, cu, n_seq, rows, cin, taps, qoff, x_ld }; + r4d_f32::RowsLoader lw{ w + (size_t)ph * cout * K, K, cout, K }; + la.init(m0 + ty, tx); + lw.init(n0 + ty, tx); + auto ep = [&](int r, int c, int cnt, float4 qv, int) { + const int m = m0 + r, co = n0 + c; + if (m >= rows) return; + const int sq = seq_of(cu, n_seq, m); + const int orow = cu[sq] * s + (m - cu[sq] + qoff) * s + ph - P; + const float v[4] = { qv.x, qv.y, qv.z, qv.w }; +#pragma unroll + for (int e = 0; e < 4; ++e) + if (e < cnt && co + e < cout) y[(size_t)orow * y_ld + co + e] = v[e] + bias[co + e]; + }; + r4d_f32::tile(la, lw, K, ep); +} + +// ---------------------------------------------------------------------------- elementwise +// Snake, or with `beta` the SnakeBeta form x + (1 / (beta + 1e-9)) sin(alpha x)^2; with `lg` both +// parameters are stored as logarithms and exponentiated here, as the reference does each pass. +__global__ __launch_bounds__(kT) void snake_kernel( + const uint16_t* __restrict__ x, const float* __restrict__ alpha, const float* __restrict__ beta, + uint16_t* __restrict__ y, int n, int lg, int x_ld, int y_ld, int64_t total) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int64_t r = t / n; + const int c = (int)(t % n); + const float v = bf2f(x[(size_t)r * x_ld + c]); + const float a = lg ? expf(alpha[c]) : alpha[c]; + const float sn = sinf(v * a); + if (beta) { + const float b = lg ? expf(beta[c]) : beta[c]; + y[(size_t)r * y_ld + c] = f32_to_bf16(v + 1.0f / (b + 1e-9f) * (sn * sn)); + } else { + y[(size_t)r * y_ld + c] = f32_to_bf16(v + sn * sn / (a + 1e-9f)); + } +} + +// ---------------------------------------------------------------------------- the sampler +// An order-preserving key: larger floats map to larger unsigned values. +__device__ __forceinline__ uint32_t fkey(float f) { + const uint32_t b = __float_as_uint(f); + return (b & 0x80000000u) ? ~b : (b | 0x80000000u); +} + +// A block-wide sum of an integer, every thread receiving it. `sh` is 8 ints of LDS. +__device__ __forceinline__ int block_sum_i(int v, int* sh) { + #pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor(v, o, 32); + __syncthreads(); + if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = v; + __syncthreads(); + int t = 0; + #pragma unroll + for (int i = 0; i < kT / 32; ++i) t += sh[i]; + return t; +} + +// The key of the `kth` largest of the values each thread produces through `val(j, &ok)` over its +// slice [j0, j1): an MSB-first radix select, one block-wide count a bit. +template +__device__ uint32_t kth_key(F val, int j0, int j1, int kth, int* sh) { + uint32_t prefix = 0, mask = 0; + int want = kth; + for (int bit = 31; bit >= 0; --bit) { + const uint32_t b = 1u << bit; + int c = 0; + for (int j = j0; j < j1; ++j) { + bool ok; + const float v = val(j, &ok); + if (!ok) continue; + const uint32_t kk = fkey(v); + if ((kk & mask) == prefix && (kk & b)) ++c; + } + const int tot = block_sum_i(c, sh); + if (tot >= want) prefix |= b; + else want -= tot; + mask |= b; + } + return prefix; +} + +// One workgroup a lane (see libref's ref_cfg_topk_sample for the rule). Thread t owns the +// contiguous slice [t chunk, (t + 1) chunk) of the vocabulary, so a prefix over threads is a +// prefix over indices, which decides the ties at the k-th value exactly as libref does. +// +// `cfgs` (per-lane guidance), `lane` + `hist` (the repetition penalty's history, [n_hist, V], a +// lane whose row is out of range read and written as no history) and the suppressed range +// [sup_lo, sup_hi) are optional. The kept values are divided by the temperature, as libref divides: +// a multiply by its inverse rounds differently and can move a pick across a CDF boundary. A lane +// with no candidate left writes -1. +constexpr int kMaxK = 256; + +__global__ __launch_bounds__(kT) void cfg_topk_kernel( + const void* __restrict__ lg, int lg_bf16, int lg_ld, const uint32_t* __restrict__ seed, + const int* __restrict__ frame, int* __restrict__ ids, int V, int K, int rep, int cond_k, + float cfg, float temp, uint64_t stream, const float* __restrict__ cfgs, + const int* __restrict__ lane, int* __restrict__ hist, int n_hist, int sup_lo, int sup_hi, + float pen) { + __shared__ int sh[8]; + __shared__ int s_pre[kT]; + __shared__ float s_g[kMaxK]; + __shared__ int s_i[kMaxK]; + __shared__ float s_e[kMaxK]; + __shared__ int s_pick; + const int ln = blockIdx.x, tid = threadIdx.x; + const int chunk = (V + kT - 1) / kT; + const int j0 = min(V, tid * chunk), j1 = min(V, j0 + chunk); + auto ldl = [&](int row, int j) -> float { + return lg_bf16 ? bf2f(((const uint16_t*)lg)[(size_t)row * lg_ld + j]) + : ((const float*)lg)[(size_t)row * lg_ld + j]; + }; + const int rc = rep * ln, ru = rep * ln + (rep > 1 ? 1 : 0); + const float gl = cfgs ? cfgs[ln] : cfg; + // The lane's history row; at the lane's first frame it holds nothing yet and is cleared below. + int hb = -1; + if (hist) { + const int L = lane[ln]; + if (L >= 0 && L < n_hist) hb = L * V; + } + const bool fresh = frame[ln] == 0; + auto cval = [&](int j) { return ldl(rc, j); }; + auto gval = [&](int j) { + const float c = ldl(rc, j); + float g = c; + if (rep != 1) { + const float u = ldl(ru, j); + g = u + gl * (c - u); + } + if (hb >= 0 && !fresh && hist[hb + j] != 0) g = g > 0.0f ? g / pen : g * pen; + return g; + }; + // The candidates: every entry outside the suppressed range, or of those the ones at or above + // the conditional's cond_k-th largest (taken over every entry, as libref takes it). + uint32_t cthr = 0; + if (cond_k > 0) + cthr = kth_key([&](int j, bool* ok) { *ok = true; return cval(j); }, j0, j1, cond_k, sh); + auto cand = [&](int j) { + return (j < sup_lo || j >= sup_hi) && (cond_k <= 0 || fkey(cval(j)) >= cthr); + }; + // The k-th largest guided value among the candidates; fewer candidates than k takes them all. + int nc = 0; + for (int j = j0; j < j1; ++j) nc += cand(j) ? 1 : 0; + const int n_cand = block_sum_i(nc, sh); + const int kk = min(K, n_cand); + if (kk == 0) { + if (tid < rep) ids[rep * ln + tid] = -1; + return; + } + const uint32_t gthr = kth_key([&](int j, bool* ok) { *ok = cand(j); return gval(j); }, j0, j1, + kk, sh); + // Every candidate above it, and of those equal to it the lowest indices up to k. + int gt = 0, eq = 0; + for (int j = j0; j < j1; ++j) { + if (!cand(j)) continue; + const uint32_t key = fkey(gval(j)); + gt += key > gthr ? 1 : 0; + eq += key == gthr ? 1 : 0; + } + const int n_gt = block_sum_i(gt, sh); + // An exclusive prefix over threads of (gt, eq): a thread's first slot and how many equal + // entries precede it. + __syncthreads(); + s_pre[tid] = (gt << 16) | eq; + __syncthreads(); + int pg = 0, pe = 0; + for (int t = 0; t < tid; ++t) { pg += s_pre[t] >> 16; pe += s_pre[t] & 0xffff; } + int og = pg; + int oe = n_gt + pe; + for (int j = j0; j < j1; ++j) { + if (!cand(j)) continue; + const float g = gval(j); + const uint32_t key = fkey(g); + if (key > gthr) { s_g[og] = g; s_i[og] = j; ++og; } + else if (key == gthr && oe < kk) { s_g[oe] = g; s_i[oe] = j; ++oe; } + } + __syncthreads(); + // The kept entries in descending g, ties to the lower index, each placed by its rank. + float mg = 0.f; + int mi = 0; + if (tid < kk) { mg = s_g[tid]; mi = s_i[tid]; } + __syncthreads(); + if (tid < kk) { + int rank = 0; + for (int t = 0; t < kk; ++t) + if (s_g[t] > mg || (s_g[t] == mg && s_i[t] < mi)) ++rank; + s_e[rank] = mg; + s_pre[rank] = mi; + } + __syncthreads(); + if (tid == 0) { + const float m = s_e[0] / temp; + double tot = 0; + for (int t = 0; t < kk; ++t) tot += exp((double)(s_e[t] / temp - m)); + const double u = (double)rad_philox_uniform_s(seed_of(seed, ln), + ((uint64_t)1 << 32) + (uint64_t)frame[ln], + stream) * tot; + int pick = s_pre[kk - 1]; + double acc = 0; + for (int t = 0; t < kk; ++t) { + acc += exp((double)(s_e[t] / temp - m)); + if (u < acc) { pick = s_pre[t]; break; } + } + s_pick = pick; + } + __syncthreads(); + if (tid < rep) ids[rep * ln + tid] = s_pick; + // The history: a new piece's row cleared, then the pick recorded. Every read of the row above + // is done (the barrier after the pick), and a fresh row was not read at all. + if (hb >= 0) { + if (fresh) + for (int j = j0; j < j1; ++j) hist[hb + j] = 0; + __syncthreads(); + if (tid == 0) hist[hb + s_pick] = 1; + } +} + +// ---------------------------------------------------------------------------- frames +// A table element as f32, the table bf16 or f32. +__device__ __forceinline__ float ldtab(const void* t, int f32, size_t i) { + return f32 ? ((const float*)t)[i] : bf2f(((const uint16_t*)t)[i]); +} + +// Code (k, r) at k * kp + r * rp: the plane's own strides, so a block of a wider plane (a lane's +// codebooks over a run of its frames) is read in place. With `round1` the whole sum is one f32 +// accumulation in codebook order, as libref's; otherwise t0 + bf16(sum of the rest), rounded as +// the reference rounds. A first code outside t0 leaves its row unwritten. +__global__ __launch_bounds__(kT) void rvq_embed_kernel( + const int* __restrict__ codes, int64_t kp, int64_t rp, const void* __restrict__ t0, + int t0_f32, const void* __restrict__ t1, int t1_f32, void* __restrict__ y, int y_f32, int D, + int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1) { + const int r = blockIdx.x; + const int c0 = codes[(size_t)r * rp] + off0; + if (c0 < 0 || c0 >= r0) return; + for (int d = threadIdx.x; d < D; d += kT) { + const float e0 = ldtab(t0, t0_f32, (size_t)c0 * D + d); + float acc = round1 ? e0 : 0.0f; + for (int k = 1; k < K; ++k) { + const int ck = codes[(size_t)k * kp + (size_t)r * rp] + (k - 1) * voc; + if (ck >= 0 && ck < r1) acc += ldtab(t1, t1_f32, (size_t)ck * D + d); + } + const float v = (round1 ? acc : bfr(e0 + bfr(acc))) * scale; + if (y_f32) ((float*)y)[(size_t)r * y_ld + d] = v; + else ((uint16_t*)y)[(size_t)r * y_ld + d] = f32_to_bf16(v); + } +} + +// dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]; a thread a (lane, code). A lane +// outside `status`, or a frame past `stride` or a lane past `dst`, stores nothing (libref refuses +// the call). +__global__ __launch_bounds__(kT) void frame_store_kernel( + const int* __restrict__ codes, int64_t kp, int64_t rp, const int* __restrict__ lane, + const int* __restrict__ frame, const int* __restrict__ status, int* __restrict__ dst, int n, + int K, int stride, int rep, int skip, int n_status, int64_t n_dst) { + const int t = blockIdx.x * kT + threadIdx.x; + if (t >= n * K) return; + const int i = t / K, k = t % K; + const int L = lane[i], f = frame[i] - skip; + if (L < 0 || L >= n_status || f < 0 || status[L] < 0) return; + if (f >= stride || (int64_t)(L + 1) * K * stride > n_dst) return; + dst[((size_t)L * K + k) * stride + f] = codes[(size_t)k * kp + (size_t)rep * i * rp]; +} + +__global__ __launch_bounds__(kT) void frame_mix_kernel( + const uint16_t* __restrict__ hid, int plane, const float* __restrict__ logits, + const float* __restrict__ scale, const int* __restrict__ lane, const int* __restrict__ frame, + const int* __restrict__ status, uint16_t* __restrict__ dst, int D, int L, int stride, int rep, + int h_ld, int d_ld) { + __shared__ float w[16]; + const int i = blockIdx.x; + const int ln = lane[i], f = frame[i]; + if (f < 1 || status[ln] < 0) return; + if (threadIdx.x == 0) { + float mx = -INFINITY; + for (int l = 0; l < L; ++l) mx = fmaxf(mx, bfr(logits[l])); + double tot = 0; + for (int l = 0; l < L; ++l) tot += exp((double)(bfr(logits[l]) - mx)); + for (int l = 0; l < L; ++l) w[l] = bfr((float)(exp((double)(bfr(logits[l]) - mx)) / tot)); + } + __syncthreads(); + const float sc = bfr(scale[0]); + uint16_t* out = dst + ((size_t)ln * stride + f - 1) * d_ld; + for (int d = threadIdx.x; d < D; d += kT) { + float acc = 0.0f; + for (int l = 0; l < L; ++l) acc += w[l] * bf2f(hid[((size_t)l * plane + rep * i) * h_ld + d]); + out[d] = f32_to_bf16(bfr(acc) * sc); + } +} + +__global__ __launch_bounds__(kT) void end_status_kernel( + const int* __restrict__ ids, const int* __restrict__ lane, int* __restrict__ status, int n, + int rep, int end) { + const int i = blockIdx.x * kT + threadIdx.x; + if (i >= n) return; + const int v = ids[rep * i]; + status[lane[i]] = v == end ? -1 : v; +} + +// ---------------------------------------------------------------------------- rows +__global__ __launch_bounds__(kT) void resample_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int in, int out, int x_ld, + int y_ld) { + const int j = blockIdx.x; + const float sc = (float)in / (float)out; + const int src = min((int)floorf((float)j * sc), in - 1); + for (int c = threadIdx.x; c < n; c += kT) y[(size_t)j * y_ld + c] = x[(size_t)src * x_ld + c]; +} + +__global__ __launch_bounds__(kT) void fourier_kernel( + const float* __restrict__ t, const float* __restrict__ w, uint16_t* __restrict__ y, int h, + int rnd, int y_ld) { + const int r = blockIdx.x; + const float two_pi = 6.28318530717958647692f; + const float tv = rnd ? bfr(bfr(t[r]) * two_pi) : t[r] * two_pi; + for (int i = threadIdx.x; i < h; i += kT) { + float ang = tv * w[i]; + if (rnd) ang = bfr(ang); + y[(size_t)r * y_ld + i] = f32_to_bf16(cosf(ang)); + y[(size_t)r * y_ld + h + i] = f32_to_bf16(sinf(ang)); + } +} + +__global__ __launch_bounds__(kT) void win_input_kernel( + const uint16_t* __restrict__ lat, const uint16_t* __restrict__ cond, + const int* __restrict__ lcu, const int* __restrict__ wlane, const int* __restrict__ pair, + uint16_t* __restrict__ y, int S, int C, int Z, int D, int stride, int l_ld, int c_ld, + int y_ld) { + const int row = lcu[0] + blockIdx.x; + if (row >= lcu[S]) return; + const int e = seq_of(lcu, S, row); + const int k = row - lcu[e], L = wlane[e]; + const bool neg = pair[e] == -2; + uint16_t* yr = y + (size_t)row * y_ld; + const uint16_t* lr = lat + ((size_t)L * stride + k) * l_ld; + const uint16_t* cr = cond + ((size_t)L * stride + k) * c_ld; + for (int c = threadIdx.x; c < C + Z + D; c += kT) + yr[c] = c < C ? lr[c] : (c < C + Z || neg) ? (uint16_t)0 : cr[c - C - Z]; +} + +__global__ __launch_bounds__(kT) void win_prep_kernel( + const int* __restrict__ flags, const float* __restrict__ t, const uint32_t* __restrict__ seed, + const int* __restrict__ widx, const int* __restrict__ wlane, const int* __restrict__ pair, + const int* __restrict__ lcu, const uint16_t* __restrict__ prev, uint16_t* __restrict__ noise, + uint16_t* __restrict__ lat, int n, int stride, int ov, int l_ld, int p_ld, int nz_ld) { + const int e = blockIdx.y; + if (pair[e] == -2) return; + const int f = flags[e]; + if (!(f & (kFirst | kJoin))) return; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + const int len = lcu[e + 1] - lcu[e]; + if (i >= (int64_t)len * n) return; + const int k = (int)(i / n), c = (int)(i % n), L = wlane[e]; + uint16_t* lp = lat + ((size_t)L * stride + k) * l_ld + c; + float nz = 0.0f; + if (f & kFirst) { + const float v = bfr(rad_philox_normal_s(seed_of(seed, e), 1 + (uint64_t)widx[e], + (uint64_t)i)); + *lp = f32_to_bf16(v); + if ((f & kJoin) && k < ov) noise[((size_t)L * ov + k) * nz_ld + c] = f32_to_bf16(v); + nz = v; + } + if ((f & kJoin) && k < ov) { + if (!(f & kFirst)) nz = bf2f(noise[((size_t)L * ov + k) * nz_ld + c]); + const float tb = bfr(t[e]); + const float wn = bfr(1.0f - bfr((1.0f - 1e-6f) * tb)); + const float pv = bf2f(prev[((size_t)L * ov + k) * p_ld + c]); + *lp = f32_to_bf16(bfr(wn * nz) + bfr(tb * pv)); + } +} + +// The overlap copies run in two kernels so a row is not read and written by different threads in +// one: the join (the head from the previous window's prev) first, then the hand-on (the next prev +// from the joined latent's tail). The other order would join the head to the window's own tail. +__global__ __launch_bounds__(kT) void win_handon_kernel( + const int* __restrict__ flags, const int* __restrict__ pair, const int* __restrict__ wlane, + const int* __restrict__ lcu, const uint16_t* __restrict__ cond, const uint16_t* __restrict__ lat, + uint16_t* __restrict__ prev, uint16_t* __restrict__ pcond, int n, int D, int stride, int ov, + int l_ld, int c_ld, int p_ld, int pc_ld) { + const int e = blockIdx.y; + if (pair[e] == -2 || !(flags[e] & kLast)) return; + const int len = lcu[e + 1] - lcu[e], L = wlane[e]; + const int s0 = max(0, len - 2 * ov), s1 = max(s0, len - ov); + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + const int w = n + D; + if (i >= (int64_t)(s1 - s0) * w) return; + const int k = s0 + (int)(i / w), c = (int)(i % w); + if (c < n) + prev[((size_t)L * ov + k - s0) * p_ld + c] = lat[((size_t)L * stride + k) * l_ld + c]; + else + pcond[((size_t)L * ov + k - s0) * pc_ld + c - n] = + cond[((size_t)L * stride + k) * c_ld + c - n]; +} + +__global__ __launch_bounds__(kT) void win_join_kernel( + const int* __restrict__ flags, const int* __restrict__ pair, const int* __restrict__ wlane, + const int* __restrict__ lcu, const uint16_t* __restrict__ prev, uint16_t* __restrict__ lat, + int n, int stride, int ov, int l_ld, int p_ld) { + const int e = blockIdx.y; + const int f = flags[e]; + if (pair[e] == -2 || !(f & kLast) || !(f & kJoin)) return; + const int len = lcu[e + 1] - lcu[e], L = wlane[e]; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= (int64_t)min(ov, len) * n) return; + const int k = (int)(i / n), c = (int)(i % n); + lat[((size_t)L * stride + k) * l_ld + c] = prev[((size_t)L * ov + k) * p_ld + c]; +} + +__global__ __launch_bounds__(kT) void chan_split_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int P, int rows, int x_ld, + int y_ld, int64_t total) { + const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; + if (t >= total) return; + const int c = (int)(t % n); + const int64_t pr = t / n; + const int p = (int)(pr / rows), r = (int)(pr % rows); + y[(size_t)pr * y_ld + c] = x[(size_t)r * x_ld + (size_t)p * n + c]; +} + +// The two streams bf16 (widened exactly) or f32 (copied), the samples f32. +__device__ __forceinline__ float il_ld(const uint16_t* p, int64_t i) { return bf2f(p[i]); } +__device__ __forceinline__ float il_ld(const float* p, int64_t i) { return p[i]; } + +template +__global__ __launch_bounds__(kT) void interleave2_kernel( + const T* __restrict__ a, const T* __restrict__ b, float* __restrict__ y, int64_t rows) { + const int64_t r = (int64_t)blockIdx.x * kT + threadIdx.x; + if (r >= rows) return; + y[2 * r] = il_ld(a, r); + y[2 * r + 1] = il_ld(b, r); +} + +// ---------------------------------------------------------------------------- indices +// y[i] = start + i step, or with `period` > 0 start + (i % period) step: positions that restart +// every `period` rows. +__global__ __launch_bounds__(kT) void iota_kernel(int* __restrict__ y, int n, int start, int step, + int period) { + const int i = blockIdx.x * kT + threadIdx.x; + if (i < n) y[i] = start + (period > 0 ? i % period : i) * step; +} + +__global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ len, + int* __restrict__ y, int n, int mult) { + const int j = blockIdx.x * kT + threadIdx.x; + if (j < n) y[j] = j * len[0] * mult; +} + +// ---------------------------------------------------------------------------- attention +// Dense causal attention over short sequences, head_dim 256, one query head a key head: a depth +// decoder runs a frame's handful of positions, the codebooks so far. A workgroup a (sequence, +// head) holds the sequence's keys and values in LDS; each of eight waves takes query rows, a lane +// eight dims. Sequences are at most kSmallSeq rows (the row's predicate). +constexpr int kSmallSeq = 32; + +__global__ __launch_bounds__(kT) void attn_small_h256_kernel( + const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int* __restrict__ cu, uint16_t* __restrict__ o, int q_ld, int k_ld, int v_ld, int o_ld, + float scale, int causal) { + constexpr int HD = 256; + __shared__ __attribute__((aligned(16))) uint16_t sk[kSmallSeq * HD]; + __shared__ __attribute__((aligned(16))) uint16_t sv[kSmallSeq * HD]; + const int sq = blockIdx.x, h = blockIdx.y; + const int r0 = cu[sq], len = min(cu[sq + 1] - r0, kSmallSeq); + for (int i = threadIdx.x; i < len * (HD / 8); i += kT) { + const int r = i / (HD / 8), c = (i % (HD / 8)) * 8; + *(uint4*)(sk + r * HD + c) = *(const uint4*)(k + (size_t)(r0 + r) * k_ld + h * HD + c); + *(uint4*)(sv + r * HD + c) = *(const uint4*)(v + (size_t)(r0 + r) * v_ld + h * HD + c); + } + __syncthreads(); + const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31; + for (int i = wave; i < len; i += kT / 32) { + float qf[8]; + ld8(q + (size_t)(r0 + i) * q_ld + h * HD + lane * 8, qf); + const int nk = causal ? i + 1 : len; + float sc[kSmallSeq]; + float mx = -INFINITY; + for (int j = 0; j < nk; ++j) { + float kf[8]; + ld8(sk + j * HD + lane * 8, kf); + float d = 0.f; + #pragma unroll + for (int e = 0; e < 8; ++e) d += qf[e] * kf[e]; + #pragma unroll + for (int off = 16; off > 0; off >>= 1) d += __shfl_xor(d, off, 32); + sc[j] = d * scale; + mx = fmaxf(mx, sc[j]); + } + float tot = 0.f, acc[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int j = 0; j < nk; ++j) { + const float p = expf(sc[j] - mx); + tot += p; + float vf[8]; + ld8(sv + j * HD + lane * 8, vf); + #pragma unroll + for (int e = 0; e < 8; ++e) acc[e] += p * vf[e]; + } + #pragma unroll + for (int e = 0; e < 8; ++e) acc[e] /= tot; + st8(o + (size_t)(r0 + i) * o_ld + h * HD + lane * 8, acc); + } +} + +// ---------------------------------------------------------------------------- shims +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } +inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); } +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; } +inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } + +// conv1d's `act` as conv_act's code, -1 for a name it does not know. Absent is none. +inline int conv1d_act(const char* act) { + if (!act || !std::strcmp(act, "none")) return 0; + if (!std::strcmp(act, "tanh")) return 1; + if (!std::strcmp(act, "clamp")) return 2; + return -1; +} + +} // namespace + +// The conv shims grid over the rows of the operand they were handed (the output's for conv1d, the +// input's for conv_t1d), which is the pass's own row count: cu_seqlens lives on the device, so its +// ends are not read here, and its sequences start at row 0 and cover those rows. +extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *cu = r4d_opt(a, 2); + const RadTensor *res = r4d_opt(a, 3), *y = r4d_opt(a, 4), *b = r4d_opt(a, 5); + if (!x || !w || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || (b && !is_bf16(b)) || !is_bf16(y) || (res && !is_bf16(res)) || + !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1); + const long long causal = r4d_geti_or(a, "causal", 0); + const int act = conv1d_act(r4d_gets(a, "act")); + if (act < 0) return R4D_NO(RAD_E_INVAL); + if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 || + causal > 1) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0, rr = 0; + const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); + const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0; + if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k || + (b && r4d_numel(b) < cout)) + return R4D_NO(RAD_E_SHAPE); + const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr; + /* Both kernels read input row row + tap * dil - pad: half the reach a side, or all of it on + * the left for the causal form. */ + const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2); + const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 && + ((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0; + const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr; + if (tiled) { + // 128 rows a block; 128 output channels where there are that many, else 64. + if (cout >= 128) { + constexpr int TP = 4, TC = 2, BP = 128, BC = 128; + hipLaunchKernelGGL((conv1d_igemm_kernel), + dim3((unsigned)((ry + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC)), + dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, + (const uint16_t*)w->data, bp, rp, + (const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry, + (int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, + (int)rl, act); + } else { + constexpr int TP = 4, TC = 1, BP = 128, BC = 64; + hipLaunchKernelGGL((conv1d_igemm_kernel), + dim3((unsigned)((ry + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC)), + dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, + (const uint16_t*)w->data, bp, rp, + (const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry, + (int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, + (int)rl, act); + } + } else { + hipLaunchKernelGGL(conv1d_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data, + bp, rp, (const int*)cu->data, (uint16_t*)y->data, + (int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad, + (int)xl, (int)yl, (int)rl, act); + } + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_conv_t1d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *b = r4d_opt(a, 2), *cu = r4d_opt(a, 3); + const RadTensor *y = r4d_opt(a, 4); + if (!x || !w || !b || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || !is_bf16(b) || !is_bf16(y) || !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long st = r4d_geti_or(a, "stride", 0); + /* Kernel 2 stride (two taps) or stride (one); without `pad`, the symmetric (k - stride) / 2, + * which needs k - stride even. */ + const long long kw = r4d_geti_or(a, "k", 2 * st), pad = r4d_geti_or(a, "pad", -1); + const long long P = pad >= 0 ? pad : (kw - st) / 2; + if (cin <= 0 || cout <= 0 || st <= 0 || (kw != st && kw != 2 * st) || + (pad < 0 && ((kw - st) & 1)) || P >= st || (cin % 8)) + return R4D_NO(RAD_E_SHAPE); + const int taps = (int)(kw / st); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); + if (xl < 0 || yl < 0 || (xl % 8) || ((uintptr_t)x->data & 15) || ((uintptr_t)w->data & 15)) + return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n_seq <= 0 || rx <= 0 || ry < rx * st || r4d_numel(w) < cin * cout * kw || + r4d_numel(b) < cout) + return R4D_NO(RAD_E_SHAPE); + if (cout >= 128) { + constexpr int TP = 4, TC = 2, BP = 128, BC = 128; + hipLaunchKernelGGL((conv_t1d_kernel), + dim3((unsigned)((rx + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC), + (unsigned)st), + dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, + (const uint16_t*)w->data, (const uint16_t*)b->data, (const int*)cu->data, + (uint16_t*)y->data, (int)n_seq, 0, (int)rx, (int)cin, (int)cout, (int)st, + (int)P, taps, (int)xl, (int)yl); + } else { + constexpr int TP = 4, TC = 1, BP = 128, BC = 64; + hipLaunchKernelGGL((conv_t1d_kernel), + dim3((unsigned)((rx + BP - 1) / BP), (unsigned)((cout + BC - 1) / BC), + (unsigned)st), + dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, + (const uint16_t*)w->data, (const uint16_t*)b->data, (const int*)cu->data, + (uint16_t*)y->data, (int)n_seq, 0, (int)rx, (int)cin, (int)cout, (int)st, + (int)P, taps, (int)xl, (int)yl); + } + return st_of(hipGetLastError()); +} + +/* The f32 rows. The weight is the _f32 layout hooks' (tap-major for conv1d, phase-major with + * ceil(k / stride) taps for conv_t1d). The column tile is the narrowest of 128, 64 and 32 that + * covers cout in as few workgroups; fewer than 16 channels take the direct conv1d kernel. */ +extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *cu = r4d_opt(a, 2); + const RadTensor *res = r4d_opt(a, 3), *y = r4d_opt(a, 4), *b = r4d_opt(a, 5); + if (!x || !w || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(w) || (b && !is_f32(b)) || !is_f32(y) || (res && !is_f32(res)) || + !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(w) || (b && !r4d_contig(b)) || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1); + const long long causal = r4d_geti_or(a, "causal", 0); + const int act = conv1d_act(r4d_gets(a, "act")); + if (act < 0) return R4D_NO(RAD_E_INVAL); + if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 || + causal > 1) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0, rr = 0; + const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); + const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0; + if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + /* The tile's loaders index x and w with 32-bit element offsets. */ + if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k || + (b && r4d_numel(b) < cout) || ry > 0x7fffffffll || (ry + 127) / 128 > 65535 || + ry * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32)) + return R4D_NO(RAD_E_SHAPE); + const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2); + const float* bp = b ? (const float*)b->data : nullptr; + const float* rp = res ? (const float*)res->data : nullptr; + if (cout < 16) { + hipLaunchKernelGGL(conv1d_f32_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0, + (hipStream_t)s, (const float*)x->data, (const float*)w->data, bp, rp, + (const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, + (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act); + return st_of(hipGetLastError()); + } + const int tn = cout > 64 ? 8 : cout > 32 ? 4 : 2; + const dim3 grid((unsigned)((cout + 16 * tn - 1) / (16 * tn)), (unsigned)((ry + 127) / 128)); +#define C1F(TN) \ + hipLaunchKernelGGL((conv1d_f32_kernel), grid, dim3(r4d_f32::kThr), 0, (hipStream_t)s, \ + (const float*)x->data, (const float*)w->data, bp, rp, \ + (const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, \ + (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act) + if (tn == 8) C1F(8); + else if (tn == 4) C1F(4); + else C1F(2); +#undef C1F + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_conv_t1d_f32(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *b = r4d_opt(a, 2), *cu = r4d_opt(a, 3); + const RadTensor *y = r4d_opt(a, 4); + if (!x || !w || !b || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(w) || !is_f32(b) || !is_f32(y) || !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); + const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); + const long long st = r4d_geti_or(a, "stride", 0); + /* Any kernel of at least a stride (two strides by default); without `pad`, the symmetric + * (k - stride) / 2, which needs k - stride even. A pad of a stride or more is served: the + * phase's first input row just moves. */ + const long long kw = r4d_geti_or(a, "k", 2 * st), pad = r4d_geti_or(a, "pad", -1); + const long long P = pad >= 0 ? pad : (kw - st) / 2; + if (cin <= 0 || cout <= 0 || st <= 0 || kw < st || (pad < 0 && ((kw - st) & 1)) || + st > 65535) + return R4D_NO(RAD_E_SHAPE); + const int taps = (int)((kw + st - 1) / st); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + /* The weight operand carries its declared [cin, cout, k]; its stored phase-major form (zero + * taps included) is what the layout hook sized. */ + if (n_seq <= 0 || rx <= 0 || ry < rx * st || r4d_numel(w) < cin * cout * kw || + r4d_numel(b) < cout || rx > 0x7fffffffll || ry > 0x7fffffffll || + (rx + 127) / 128 > 65535 || rx * xl >= (1ll << 32) || st * cout * taps * cin >= (1ll << 32)) + return R4D_NO(RAD_E_SHAPE); + const int tn = cout > 64 ? 8 : cout > 32 ? 4 : 2; + const dim3 grid((unsigned)((cout + 16 * tn - 1) / (16 * tn)), (unsigned)((rx + 127) / 128), + (unsigned)st); +#define CTF(TN) \ + hipLaunchKernelGGL((conv_t1d_f32_kernel), grid, dim3(r4d_f32::kThr), 0, (hipStream_t)s, \ + (const float*)x->data, (const float*)w->data, (const float*)b->data, \ + (const int*)cu->data, (float*)y->data, (int)n_seq, (int)rx, (int)cin, \ + (int)cout, (int)st, (int)P, taps, (int)xl, (int)yl) + if (tn == 8) CTF(8); + else if (tn == 4) CTF(4); + else CTF(2); +#undef CTF + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_snake(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *al = r4d_opt(a, 1), *y = r4d_opt(a, 2); + const RadTensor* be = r4d_opt(a, 3); + if (!x || !al || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y) || al->dtype != RAD_F32 || (be && be->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(al) || (be && !r4d_contig(be))) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_geti_or(a, "n", 0), lg = r4d_geti_or(a, "log", 0); + long long rx = 0, ry = 0; + const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1; + const long long yl = n > 0 ? r4d_rows_pitch(y, n, &ry) : -1; + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry || r4d_numel(al) < n || (be && r4d_numel(be) < n) || lg < 0 || lg > 1) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(snake_kernel, dim3(blocks_for(ry * n)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (const float*)al->data, + be ? (const float*)be->data : nullptr, (uint16_t*)y->data, (int)n, (int)lg, + (int)xl, (int)yl, (int64_t)(ry * n)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) { + const RadTensor *lg = r4d_opt(a, 0), *seed = r4d_opt(a, 1), *fr = r4d_opt(a, 2); + const RadTensor *ids = r4d_opt(a, 3), *cfgs = r4d_opt(a, 4), *lane = r4d_opt(a, 5); + const RadTensor* hist = r4d_opt(a, 6); + if (!lg || !seed || !fr || !ids) return R4D_NO(RAD_E_INVAL); + if ((lg->dtype != RAD_F32 && lg->dtype != RAD_BF16) || !is_i32(ids) || !is_i32(fr) || + (cfgs && cfgs->dtype != RAD_F32) || (lane && !is_i32(lane)) || (hist && !is_i32(hist))) + return R4D_NO(RAD_E_DTYPE); + if ((cfgs && !r4d_contig(cfgs)) || (lane && !r4d_contig(lane)) || (hist && !r4d_contig(hist))) + return R4D_NO(RAD_E_STRIDE); + const long long V = r4d_geti_or(a, "n_vocab", 0), K = r4d_geti_or(a, "k", 0); + const long long rep = r4d_geti_or(a, "rep", 1), ck = r4d_geti_or(a, "cond_k", 0); + const long long stream = r4d_geti_or(a, "stream", 0); + const long long sup_lo = r4d_geti_or(a, "sup_lo", 0), sup_hi = r4d_geti_or(a, "sup_hi", 0); + const double cfg = r4d_getf(a, "cfg", 1.0), temp = r4d_getf(a, "temp", 1.0); + const double pen = r4d_getf(a, "penalty", 1.0); + if (V <= 0 || K <= 0 || K > kMaxK || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || + !(temp > 0) || V > (1 << 16) * kT || sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || + !(pen > 0) || (!hist != !lane)) + return R4D_NO(RAD_E_SHAPE); + long long rl = 0; + const long long ll = r4d_rows_pitch(lg, V, &rl); + if (ll < 0) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_numel(ids) / rep; + if (n <= 0 || rl < rep * n || r4d_numel(fr) < n || r4d_numel(seed) < 2 * n || + (cfgs && r4d_numel(cfgs) < n) || (lane && r4d_numel(lane) < n)) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(cfg_topk_kernel, dim3((unsigned)n), dim3(kT), 0, (hipStream_t)s, lg->data, + lg->dtype == RAD_BF16 ? 1 : 0, (int)ll, (const uint32_t*)seed->data, + (const int*)fr->data, (int*)ids->data, (int)V, (int)K, (int)rep, (int)ck, + (float)cfg, (float)temp, (uint64_t)stream, + cfgs ? (const float*)cfgs->data : nullptr, + lane ? (const int*)lane->data : nullptr, hist ? (int*)hist->data : nullptr, + hist ? (int)(r4d_numel(hist) / V) : 0, (int)sup_lo, (int)sup_hi, + (float)pen); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) { + const RadTensor *codes = r4d_opt(a, 0), *t0 = r4d_opt(a, 1), *t1 = r4d_opt(a, 2); + const RadTensor *y = r4d_opt(a, 3); + if (!codes || !t0 || !t1 || !y) return R4D_NO(RAD_E_INVAL); + auto bf_or_f32 = [](const RadTensor* t) { return t->dtype == RAD_BF16 || t->dtype == RAD_F32; }; + if (!is_i32(codes) || !bf_or_f32(t0) || !bf_or_f32(t1) || !bf_or_f32(y)) + return R4D_NO(RAD_E_DTYPE); + const long long D = r4d_geti_or(a, "n_embd", 0), K = r4d_geti_or(a, "n_codes", 0); + const long long voc = r4d_geti_or(a, "vocab", 0), off0 = r4d_geti_or(a, "off0", 0); + const long long round1 = r4d_geti_or(a, "round", 0); + const double scale = r4d_getf(a, "scale", 1.0); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return R4D_NO(RAD_E_SHAPE); + long long ry = 0; + const long long yl = r4d_rows_pitch(y, D, &ry); + if (yl < 0 || !r4d_contig(t0) || !r4d_contig(t1)) return R4D_NO(RAD_E_STRIDE); + /* Code (k, r) at the plane's own strides (libref reads it so). */ + const long long kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : ry; + const long long rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + if (ry <= 0 || r4d_numel(codes) < K * ry) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(rvq_embed_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const int*)codes->data, (int64_t)kp, (int64_t)rp, t0->data, + t0->dtype == RAD_F32 ? 1 : 0, t1->data, t1->dtype == RAD_F32 ? 1 : 0, + y->data, y->dtype == RAD_F32 ? 1 : 0, (int)D, (int)K, (int)voc, (int)off0, + (int)(r4d_numel(t0) / D), (int)(r4d_numel(t1) / D), (float)scale, (int)yl, + (int)round1); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_frame_mix_store(const RadArgs* a, RadStream s) { + const RadTensor *hid = r4d_opt(a, 0), *lw = r4d_opt(a, 1), *sc = r4d_opt(a, 2); + const RadTensor *lane = r4d_opt(a, 3), *fr = r4d_opt(a, 4), *st = r4d_opt(a, 5); + const RadTensor *dst = r4d_opt(a, 6); + if (!hid || !lw || !sc || !lane || !fr || !st || !dst) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(hid) || !is_bf16(dst) || lw->dtype != RAD_F32 || sc->dtype != RAD_F32 || + !is_i32(lane) || !is_i32(fr) || !is_i32(st)) + return R4D_NO(RAD_E_DTYPE); + const long long D = r4d_geti_or(a, "n_embd", 0), L = r4d_geti_or(a, "L", 0); + const long long stride = r4d_geti_or(a, "stride", 0), rep = r4d_geti_or(a, "rep", 1); + if (D <= 0 || L <= 0 || L > 16 || stride <= 0 || rep < 1) return R4D_NO(RAD_E_SHAPE); + long long rh = 0, rd = 0; + const long long hl = r4d_rows_pitch(hid, D, &rh), dl = r4d_rows_pitch(dst, D, &rd); + if (hl < 0 || dl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_numel(lane); + if (n <= 0 || rh / L < rep * n || r4d_numel(fr) < n || r4d_numel(lw) < L) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(frame_mix_kernel, dim3((unsigned)n), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)hid->data, (int)(rh / L), (const float*)lw->data, + (const float*)sc->data, (const int*)lane->data, (const int*)fr->data, + (const int*)st->data, (uint16_t*)dst->data, (int)D, (int)L, (int)stride, + (int)rep, (int)hl, (int)dl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_end_status(const RadArgs* a, RadStream s) { + const RadTensor *ids = r4d_opt(a, 0), *lane = r4d_opt(a, 1), *st = r4d_opt(a, 2); + if (!ids || !lane || !st) return R4D_NO(RAD_E_INVAL); + if (!is_i32(ids) || !is_i32(lane) || !is_i32(st)) return R4D_NO(RAD_E_DTYPE); + const long long end = r4d_geti_or(a, "end", -1), rep = r4d_geti_or(a, "rep", 1); + const long long n = r4d_numel(lane); + if (n <= 0 || rep < 1 || r4d_numel(ids) < rep * n) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(end_status_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s, + (const int*)ids->data, (const int*)lane->data, (int*)st->data, (int)n, + (int)rep, (int)end); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_frame_store(const RadArgs* a, RadStream s) { + const RadTensor *codes = r4d_opt(a, 0), *lane = r4d_opt(a, 1), *fr = r4d_opt(a, 2); + const RadTensor *st = r4d_opt(a, 3), *dst = r4d_opt(a, 4); + if (!codes || !lane || !fr || !st || !dst) return R4D_NO(RAD_E_INVAL); + if (!is_i32(codes) || !is_i32(lane) || !is_i32(fr) || !is_i32(st) || !is_i32(dst)) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(lane) || !r4d_contig(fr) || !r4d_contig(st) || !r4d_contig(dst)) + return R4D_NO(RAD_E_STRIDE); + const long long K = r4d_geti_or(a, "n_codes", 0), stride = r4d_geti_or(a, "stride", 0); + const long long rep = r4d_geti_or(a, "rep", 1), skip = r4d_geti_or(a, "skip", 0); + if (K <= 0 || stride <= 0 || rep < 1 || skip < 0) return R4D_NO(RAD_E_SHAPE); + const long long n = r4d_numel(lane); + if (n <= 0 || r4d_numel(fr) < n || r4d_numel(codes) < K * rep * n) return R4D_NO(RAD_E_SHAPE); + const long long kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rep * n; + const long long rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + hipLaunchKernelGGL(frame_store_kernel, dim3(blocks_for(n * K)), dim3(kT), 0, (hipStream_t)s, + (const int*)codes->data, (int64_t)kp, (int64_t)rp, (const int*)lane->data, + (const int*)fr->data, (const int*)st->data, (int*)dst->data, (int)n, (int)K, + (int)stride, (int)rep, (int)skip, (int)r4d_numel(st), + (int64_t)r4d_numel(dst)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_resample_nearest(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (x->dtype != y->dtype || (x->dtype != RAD_BF16)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, ry = 0; + const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1; + const long long yl = n > 0 ? r4d_rows_pitch(y, n, &ry) : -1; + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(resample_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (uint16_t*)y->data, (int)n, (int)rx, (int)ry, + (int)xl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_fourier_embed(const RadArgs* a, RadStream s) { + const RadTensor *t = r4d_opt(a, 0), *w = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!t || !w || !y) return R4D_NO(RAD_E_INVAL); + if (t->dtype != RAD_F32 || w->dtype != RAD_F32 || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), rnd = r4d_geti_or(a, "round", 0); + long long ry = 0; + const long long yl = n > 0 ? r4d_rows_pitch(y, n, &ry) : -1; + if (yl < 0) return R4D_NO(RAD_E_STRIDE); + if (n <= 0 || (n & 1) || ry <= 0 || r4d_numel(t) < ry || r4d_numel(w) < n / 2) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(fourier_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const float*)t->data, (const float*)w->data, (uint16_t*)y->data, + (int)(n / 2), (int)rnd, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_win_input(const RadArgs* a, RadStream s) { + const RadTensor *lat = r4d_opt(a, 0), *cond = r4d_opt(a, 1), *lcu = r4d_opt(a, 2); + const RadTensor *wl = r4d_opt(a, 3), *pair = r4d_opt(a, 4), *y = r4d_opt(a, 5); + if (!lat || !cond || !lcu || !wl || !pair || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(lat) || !is_bf16(cond) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "n_lat", 0), Z = r4d_geti_or(a, "n_zero", 0); + const long long D = r4d_geti_or(a, "n_cond", 0), stride = r4d_geti_or(a, "stride", 0); + if (C <= 0 || Z < 0 || D <= 0 || stride <= 0) return R4D_NO(RAD_E_SHAPE); + long long rl = 0, rc = 0, ry = 0; + const long long ll = r4d_rows_pitch(lat, C, &rl), cl = r4d_rows_pitch(cond, D, &rc); + const long long yl = r4d_rows_pitch(y, C + Z + D, &ry); + if (ll < 0 || cl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + const long long S = r4d_numel(lcu) - 1; + if (S <= 0 || ry <= 0 || r4d_numel(wl) < S || r4d_numel(pair) < S) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(win_input_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)lat->data, (const uint16_t*)cond->data, + (const int*)lcu->data, (const int*)wl->data, (const int*)pair->data, + (uint16_t*)y->data, (int)S, (int)C, (int)Z, (int)D, (int)stride, (int)ll, + (int)cl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_win_prep(const RadArgs* a, RadStream s) { + const RadTensor *fl = r4d_opt(a, 0), *t = r4d_opt(a, 1), *seed = r4d_opt(a, 2); + const RadTensor *widx = r4d_opt(a, 3), *wl = r4d_opt(a, 4), *pair = r4d_opt(a, 5); + const RadTensor *lcu = r4d_opt(a, 6), *prev = r4d_opt(a, 7), *noise = r4d_opt(a, 8); + const RadTensor *lat = r4d_opt(a, 9); + if (!fl || !t || !seed || !widx || !wl || !pair || !lcu || !prev || !noise || !lat) + return R4D_NO(RAD_E_INVAL); + if (!is_bf16(prev) || !is_bf16(noise) || !is_bf16(lat) || t->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + const long long ov = r4d_geti_or(a, "ov", 0); + if (n <= 0 || stride <= 0 || ov < 0 || ov > stride) return R4D_NO(RAD_E_SHAPE); + long long rl = 0, rp = 0, rn = 0; + const long long ll = r4d_rows_pitch(lat, n, &rl), pl = r4d_rows_pitch(prev, n, &rp); + const long long nl = r4d_rows_pitch(noise, n, &rn); + if (ll < 0 || pl < 0 || nl < 0) return R4D_NO(RAD_E_STRIDE); + const long long S = r4d_numel(lcu) - 1; + if (S <= 0 || rl < stride) return R4D_NO(RAD_E_SHAPE); + for (const RadTensor* e : { fl, t, widx, wl, pair }) + if (r4d_numel(e) < S) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(win_prep_kernel, dim3(blocks_for(stride * n), (unsigned)S), dim3(kT), 0, + (hipStream_t)s, (const int*)fl->data, (const float*)t->data, + (const uint32_t*)seed->data, (const int*)widx->data, (const int*)wl->data, + (const int*)pair->data, (const int*)lcu->data, (const uint16_t*)prev->data, + (uint16_t*)noise->data, (uint16_t*)lat->data, (int)n, (int)stride, (int)ov, + (int)ll, (int)pl, (int)nl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_win_finish(const RadArgs* a, RadStream s) { + const RadTensor *fl = r4d_opt(a, 0), *pair = r4d_opt(a, 1), *wl = r4d_opt(a, 2); + const RadTensor *lcu = r4d_opt(a, 3), *cond = r4d_opt(a, 4), *lat = r4d_opt(a, 5); + const RadTensor *prev = r4d_opt(a, 6), *pc = r4d_opt(a, 7); + if (!fl || !pair || !wl || !lcu || !cond || !lat || !prev || !pc) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(cond) || !is_bf16(lat) || !is_bf16(prev) || !is_bf16(pc)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), D = r4d_geti_or(a, "n_cond", 0); + const long long stride = r4d_geti_or(a, "stride", 0), ov = r4d_geti_or(a, "ov", 0); + if (n <= 0 || D <= 0 || stride <= 0 || ov <= 0 || ov > stride) return R4D_NO(RAD_E_SHAPE); + long long rl = 0, rc = 0, rp = 0, rq = 0; + const long long ll = r4d_rows_pitch(lat, n, &rl), cl = r4d_rows_pitch(cond, D, &rc); + const long long pl = r4d_rows_pitch(prev, n, &rp), ql = r4d_rows_pitch(pc, D, &rq); + if (ll < 0 || cl < 0 || pl < 0 || ql < 0) return R4D_NO(RAD_E_STRIDE); + const long long S = r4d_numel(lcu) - 1; + if (S <= 0 || r4d_numel(fl) < S || r4d_numel(wl) < S || r4d_numel(pair) < S) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(win_join_kernel, dim3(blocks_for(ov * n), (unsigned)S), dim3(kT), 0, + (hipStream_t)s, (const int*)fl->data, (const int*)pair->data, + (const int*)wl->data, (const int*)lcu->data, (const uint16_t*)prev->data, + (uint16_t*)lat->data, (int)n, (int)stride, (int)ov, (int)ll, (int)pl); + int rc2 = st_of(hipGetLastError()); + if (rc2 < 0) return rc2; + hipLaunchKernelGGL(win_handon_kernel, dim3(blocks_for(ov * (n + D)), (unsigned)S), dim3(kT), 0, + (hipStream_t)s, (const int*)fl->data, (const int*)pair->data, + (const int*)wl->data, (const int*)lcu->data, (const uint16_t*)cond->data, + (const uint16_t*)lat->data, (uint16_t*)prev->data, (uint16_t*)pc->data, + (int)n, (int)D, (int)stride, (int)ov, (int)ll, (int)cl, (int)pl, (int)ql); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_chan_split(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), P = r4d_geti_or(a, "parts", 0); + if (n <= 0 || P <= 0) return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, P * n, &rx), yl = r4d_rows_pitch(y, n, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + const long long rows = ry / P; + if (rows <= 0 || rx < rows) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(chan_split_kernel, dim3(blocks_for(P * rows * n)), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, (int)n, (int)P, + (int)rows, (int)xl, (int)yl, (int64_t)(P * rows * n)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_interleave2(const RadArgs* a, RadStream s) { + const RadTensor *x0 = r4d_opt(a, 0), *x1 = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x0 || !x1 || !y) return R4D_NO(RAD_E_INVAL); + /* Both streams bf16 or both f32; the samples f32. */ + if ((!is_bf16(x0) && x0->dtype != RAD_F32) || x1->dtype != x0->dtype || y->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(x0) || !r4d_contig(x1) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + const long long rows = r4d_numel(y) / 2; + if (rows <= 0 || r4d_numel(x0) < rows || r4d_numel(x1) < rows) return R4D_NO(RAD_E_SHAPE); + if (x0->dtype == RAD_F32) + hipLaunchKernelGGL(interleave2_kernel, dim3(blocks_for(rows)), dim3(kT), 0, + (hipStream_t)s, (const float*)x0->data, (const float*)x1->data, + (float*)y->data, (int64_t)rows); + else + hipLaunchKernelGGL(interleave2_kernel, dim3(blocks_for(rows)), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)x0->data, (const uint16_t*)x1->data, + (float*)y->data, (int64_t)rows); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_attn_dense_small_h256(const RadArgs* a, RadStream s) { + const RadTensor *q = r4d_opt(a, 0), *k = r4d_opt(a, 1), *v = r4d_opt(a, 2), *cu = r4d_opt(a, 3); + const RadTensor *o = r4d_opt(a, 4); + if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(q) || !is_bf16(k) || !is_bf16(v) || !is_bf16(o) || !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); + const long long causal = r4d_geti_or(a, "causal", 0); + if (hd != 256 || gqa != 1) return R4D_NO(RAD_E_SHAPE); + /* Every key of a sequence, causally or not: no window, blocks or cu_div. */ + if (r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "window_right", 0) != 0 || + r4d_geti_or(a, "block", 0) != 0 || r4d_geti_or(a, "cu_div", 1) != 1) + return R4D_NO(RAD_E_UNSUPPORTED); + const long long width = q->rank >= 2 ? q->shape[q->rank - 1] : 0; + if (width <= 0 || width % 256) return R4D_NO(RAD_E_SHAPE); + const long long n_head = width / 256; + long long rq = 0, rk = 0, rv = 0, ro = 0; + const long long ql = r4d_rows_pitch(q, width, &rq), kl = r4d_rows_pitch(k, width, &rk); + const long long vl = r4d_rows_pitch(v, width, &rv), ol = r4d_rows_pitch(o, width, &ro); + if (ql < 0 || kl < 0 || vl < 0 || ol < 0 || (ql % 8) || (kl % 8) || (vl % 8) || (ol % 8)) + return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n_seq <= 0) return R4D_NO(RAD_E_SHAPE); + const double sc = r4d_getf(a, "scale", 1.0 / std::sqrt(256.0)); + hipLaunchKernelGGL(attn_small_h256_kernel, dim3((unsigned)n_seq, (unsigned)n_head), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)q->data, (const uint16_t*)k->data, + (const uint16_t*)v->data, (const int*)cu->data, (uint16_t*)o->data, (int)ql, + (int)kl, (int)vl, (int)ol, (float)sc, (int)causal); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_iota(const RadArgs* a, RadStream s) { + const RadTensor* y = r4d_opt(a, 0); + if (!y) return R4D_NO(RAD_E_INVAL); + if (!is_i32(y)) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_numel(y), period = r4d_geti_or(a, "period", 0); + if (n <= 0 || period < 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(iota_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s, (int*)y->data, + (int)n, (int)r4d_geti_or(a, "start", 0), (int)r4d_geti_or(a, "step", 1), + (int)period); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) { + const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!len || !y) return R4D_NO(RAD_E_INVAL); + if (!is_i32(len) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_numel(y), mult = r4d_geti_or(a, "mult", 1); + if (n <= 0 || mult <= 0 || r4d_numel(len) < 1) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(cu_repeat_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s, + (const int*)len->data, (int*)y->data, (int)n, (int)mult); + return st_of(hipGetLastError()); +} diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index fc27f612..e8c28402 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -7,6 +7,7 @@ #include "r4d_args.h" #include "r4d_common.h" +#include #include #include #include @@ -98,14 +99,26 @@ struct QkBlocks { int comp[8] = {}; }; +// A norm gain element, the gains bf16 or (w_f32) f32; an absent gain is one, without `wadd`. +__device__ __forceinline__ float qk_gain(const void* w, uint32_t e, int w_f32, float wadd) { + if (!w) return 1.0f; + return (w_f32 ? ((const float*)w)[e] : bf2f(((const uint16_t*)w)[e])) + wadd; +} + +// Element `i` of the positions: an i32 value, or with `pos_f32` an f32 one read as the value it +// holds (a fractional coordinate, such as a video decoder's normalised grid times 2 pi). +__device__ __forceinline__ float qk_pos(const void* pos, int pos_f32, size_t i) { + return pos_f32 ? ((const float*)pos)[i] : (float)((const int*)pos)[i]; +} + // MODE: 0 neox, 1 gptj, 2 blocks. Positions are [M] for the first two and [C, M] (plane stride // `pplane`) for blocks. template __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( - uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw, - const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, + uint16_t* __restrict__ qkv, const void* __restrict__ pos, const void* __restrict__ qw, + const void* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, - QkBlocks blk, uint32_t pplane) { + QkBlocks blk, uint32_t pplane, int w_f32, int pos_f32) { __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; const uint32_t m = blockIdx.x; const uint32_t n_rope = n_head + n_head_kv; @@ -119,12 +132,12 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) { int c = 0, s0 = 0; while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; } - const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div; + const float p = qk_pos(pos, pos_f32, (size_t)blk.comp[c] * pplane + m) / div; const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]); sincosf(p * inv, &sn_s[i], &cs_s[i]); } } else { - const float p = (float)pos[m] / div; + const float p = qk_pos(pos, pos_f32, m) / div; for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) { const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot); sincosf(p * inv, &sn_s[i], &cs_s[i]); @@ -148,11 +161,11 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( ss = r4d_wave_sum(ss); const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps); const bool is_v = hh >= n_rope; - const uint16_t* w = hh < n_head ? qw : kw; + const void* w = hh < n_head ? qw : kw; #pragma unroll for (int j = 0; j < kQkMaxE; ++j) if (j < E) { - const float g = is_v ? 1.0f : bf2f(w[at(j)]) + wadd; + const float g = is_v ? 1.0f : qk_gain(w, at(j), w_f32, wadd); x[j] = bf2f(f32_to_bf16(x[j] * sc * g)); } if (!is_v) { @@ -226,11 +239,17 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( // 2 imrope NeoX pairs (i, i + rot/2) on one ladder theta^(-2i/rot), the position // component interleaved: 1 where i % 3 == 1 and i < 3 * sec[1], 2 where // i % 3 == 2 and i < 3 * sec[2], 0 elsewhere (Qwen3-VL's text attention) +// 3 axial NeoX pairs (i, i + rot/2), the rot/2 frequencies in contiguous sections, +// section c on its own ladder theta^(-2j/(2 sec[c])) and turned by component c +// (a video transformer's or decoder's (t, h, w) rotary). With rank-1 positions +// (`pplane` 0) every component is the one position. +// +// `rot` 0 is the norm alone and reads no positions. __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( - uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw, - const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, + uint16_t* __restrict__ qkv, const void* __restrict__ pos, const void* __restrict__ qw, + const void* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, - QkBlocks blk, uint32_t pplane, int pm) { + QkBlocks blk, uint32_t pplane, int pm, int w_f32, int pos_f32) { __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; __shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf]; const uint32_t m = blockIdx.x; @@ -244,7 +263,7 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( int c = 0; if (i % 3 == 1 && (int)i < 3 * blk.sec[1]) c = 1; else if (i % 3 == 2 && (int)i < 3 * blk.sec[2]) c = 2; - const float p = (float)pos[(size_t)c * pplane + m] / div; + const float p = qk_pos(pos, pos_f32, (size_t)c * pplane + m) / div; const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot); sincosf(p * inv, &sn_s[i], &cs_s[i]); pa_s[i] = (int)i; @@ -253,7 +272,16 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( } int c = 0, s0 = 0; while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; } - const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div; + if (pm == 3) { + const float p = qk_pos(pos, pos_f32, (size_t)c * pplane + m) / div; + const float inv = + 1.0f / powf(theta, (float)(2 * ((int)i - s0)) / (float)(2 * blk.sec[c])); + sincosf(p * inv, &sn_s[i], &cs_s[i]); + pa_s[i] = (int)i; + pb_s[i] = (int)(i + half); + continue; + } + const float p = qk_pos(pos, pos_f32, (size_t)blk.comp[c] * pplane + m) / div; const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]); sincosf(p * inv, &sn_s[i], &cs_s[i]); if (pm == 1) { @@ -273,9 +301,9 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( ss = r4d_wave_sum(ss); const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps); const bool is_v = hh >= n_rope; - const uint16_t* w = hh < n_head ? qw : kw; + const void* w = hh < n_head ? qw : kw; auto nrm = [&](uint32_t e) { - const float g = is_v ? 1.0f : bf2f(w[e]) + wadd; + const float g = is_v ? 1.0f : qk_gain(w, e, w_f32, wadd); return bf2f(f32_to_bf16(bf2f(h[e]) * sc * g)); }; if (is_v) { @@ -318,6 +346,19 @@ __global__ __launch_bounds__(kThreads) void widen_kernel( y[(size_t)m * y_ld + i] = bf2f(x[(size_t)m * x_ld + i]); } +// ---------------------------------------------------------------------------- cast bf16 -> f16 +// ref_cast: the value rounded to nearest even once, so a bf16 value in f16's normal range is kept +// exactly and one past it becomes an infinity (rad_f32_to_f16). +__global__ __launch_bounds__(kThreads) void narrow_f16_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, + uint32_t y_ld, uint32_t M) { + const uint32_t i = blockIdx.x * kThreads + threadIdx.x; + if (i >= n) return; + for (uint32_t m = blockIdx.y; m < M; m += gridDim.y) + y[(size_t)m * y_ld + i] = + __builtin_bit_cast(uint16_t, (_Float16)bf2f(x[(size_t)m * x_ld + i])); +} + // ---------------------------------------------------------------------------- the audio tower // Gemma 4's USM conformer: elementwise rectifier and clamp, the subsampler's segment-wise // convolution, the light-conv block's causal depthwise convolution, the relative-position table, @@ -350,6 +391,37 @@ __global__ __launch_bounds__(kThreads) void silu_kernel( } } +// The f32 form: f32 in, f32 out or bf16 rounded once (a timestep MLP's activation, rounded where +// the bf16 projection after it reads it). Flat over the extent. +__device__ __forceinline__ void st_act(float* p, float v) { *p = v; } +__device__ __forceinline__ void st_act(uint16_t* p, float v) { *p = f32_to_bf16(v); } + +template +__global__ __launch_bounds__(kThreads) void silu_f32_kernel( + const float* __restrict__ x, TY* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld, + uint64_t total) { + for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total; + t += (uint64_t)gridDim.x * kThreads) { + const uint64_t m = t / n; + const uint32_t i = (uint32_t)(t - m * n); + const float v = x[m * x_ld + i]; + st_act(y + m * y_ld + i, v * (1.0f / (1.0f + expf(-v)))); + } +} + +// ref_gelu: the exact erf form, 0.5 x (1 + erf(x / sqrt 2)) in libref's order, one rounding (a +// ConvNeXt block's feed-forward activation; gated feed-forwards use the tanh form). +__global__ __launch_bounds__(kThreads) void gelu_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, + uint32_t y_ld, uint32_t M) { + const uint32_t i = blockIdx.x * kThreads + threadIdx.x; + if (i >= n) return; + for (uint32_t m = blockIdx.y; m < M; m += gridDim.y) { + const float v = bf2f(x[(size_t)m * x_ld + i]); + y[(size_t)m * y_ld + i] = f32_to_bf16(0.5f * v * (1.0f + erff(v * 0.70710678118654752f))); + } +} + // ref_clamp: the two bounds are one-element weights, bf16 or f32. __global__ __launch_bounds__(kThreads) void clamp_kernel( const uint16_t* __restrict__ x, const void* __restrict__ lo, const void* __restrict__ hi, @@ -533,10 +605,11 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel( } // ref_conv1d_dw. One thread per (row, channel); the segment is found by a scan over cu_seqlens. +// `b`, when bound, is a bias per channel (bf16, or f32 with b_f32), added before the rounding. __global__ __launch_bounds__(kThreads) void conv1d_dw_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ y, int C, int K, int cdiv, int S, uint32_t x_ld, uint32_t y_ld, - int rows) { + int rows, const void* __restrict__ b, int b_f32) { const int c = (int)(blockIdx.x * kThreads + threadIdx.x); if (c >= C) return; for (int t = (int)blockIdx.y; t < rows; t += (int)gridDim.y) { @@ -553,6 +626,7 @@ __global__ __launch_bounds__(kThreads) void conv1d_dw_kernel( if (tt < t0) continue; acc += bf2f(x[(size_t)tt * x_ld + c]) * bf2f(w[(size_t)c * K + j]); } + if (b) acc += b_f32 ? ((const float*)b)[c] : bf2f(((const uint16_t*)b)[c]); y[(size_t)t * y_ld + c] = f32_to_bf16(acc); } } @@ -682,32 +756,43 @@ extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld return hipGetLastError() == hipSuccess ? 0 : -4; } -// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope (`blk` and the position plane stride -// `pplane` used only by the last three). +// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope, 5 axial (`blk` and the position plane +// stride `pplane` used only by the last four). A null gain is a unit gain; `rot` 0 is the norm +// alone, and then `pos` may be null. `pos_f32` reads f32 positions as the values they hold. extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M, int head_dim, int n_head, int n_head_kv, int rot, int mode, int v_norm, float theta, float eps, float rscale, float wadd, int ld, - const QkBlocks* blk, int pplane, long stream) { - if (!qkv || !pos || !qw || !kw) return -1; - if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim || - (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4) + const QkBlocks* blk, int pplane, long stream, int w_f32, + int pos_f32) { + if (!qkv || (rot > 0 && !pos)) return -1; + if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot < 0 || rot > head_dim || + (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 5) return -2; + if (rot == 0) { + /* The norm alone: no pair is rotated, so no position is read. */ + hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, + (hipStream_t)stream, (uint16_t*)qkv, (const void*)nullptr, + (const void*)qw, (const void*)kw, (uint32_t)head_dim, + (uint32_t)n_head, (uint32_t)n_head_kv, 0u, v_norm, theta, eps, rscale, + wadd, (uint32_t)ld, QkBlocks{}, 0u, 0, w_f32, 0); + return hipGetLastError() == hipSuccess ? 0 : -4; + } if (mode >= 3) { - /* gptj_blocks and imrope: general kernel only (its pair table is built per mode). */ + /* gptj_blocks, imrope and axial: general kernel only (its pair table is built per mode). */ if (!blk || blk->n <= 0 || blk->n > 8) return -2; int total = 0; for (int c = 0; c < blk->n; ++c) { if (blk->sec[c] <= 0) return -2; total += blk->sec[c]; } - if (mode == 3 && 2 * total != rot) return -2; + if ((mode == 3 || mode == 5) && 2 * total != rot) return -2; if (mode == 4 && (blk->n < 3 || 2 * total != rot)) return -2; hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, - (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, - (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, + (hipStream_t)stream, (uint16_t*)qkv, (const void*)pos, + (const void*)qw, (const void*)kw, (uint32_t)head_dim, (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, eps, rscale, wadd, (uint32_t)ld, *blk, (uint32_t)pplane, - mode == 3 ? 1 : 2); + mode == 3 ? 1 : mode == 4 ? 2 : 3, w_f32, pos_f32); return hipGetLastError() == hipSuccess ? 0 : -4; } if (mode != 2 && head_dim % 32) return -2; @@ -729,18 +814,19 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M } if (any) { hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, - (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, - (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, + (hipStream_t)stream, (uint16_t*)qkv, (const void*)pos, + (const void*)qw, (const void*)kw, (uint32_t)head_dim, (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, - eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0); + eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0, w_f32, + pos_f32); return hipGetLastError() == hipSuccess ? 0 : -4; } #define R4D_QN(MD) \ hipLaunchKernelGGL(qk_norm_rope_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, \ - (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, (const uint16_t*)qw, \ - (const uint16_t*)kw, (uint32_t)head_dim, (uint32_t)n_head, \ + (hipStream_t)stream, (uint16_t*)qkv, (const void*)pos, (const void*)qw, \ + (const void*)kw, (uint32_t)head_dim, (uint32_t)n_head, \ (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, eps, rscale, wadd, \ - (uint32_t)ld, b, (uint32_t)pplane) + (uint32_t)ld, b, (uint32_t)pplane, w_f32, pos_f32) if (mode == 1) R4D_QN(1); else if (mode == 2) R4D_QN(2); else R4D_QN(0); @@ -769,6 +855,17 @@ extern "C" int r4d_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_ return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_narrow_bf16_f16(long x, long y, int M, int n, int x_ld, int y_ld, + long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + hipLaunchKernelGGL(narrow_f16_kernel, + dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_relu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -778,6 +875,15 @@ extern "C" int r4d_relu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, l return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + hipLaunchKernelGGL(gelu_kernel, dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -830,14 +936,15 @@ extern "C" int r4d_conv2d_unfold_bf16(long x, long cu, long valid, long y, int r } extern "C" int r4d_conv1d_dw_bf16(long x, long w, long cu, long y, int rows, int C, int K, - int cdiv, int S, int x_ld, int y_ld, long stream) { + int cdiv, int S, int x_ld, int y_ld, long stream, long b = 0, + int b_f32 = 0) { if (!x || !w || !cu || !y) return -1; if (rows <= 0 || C <= 0 || K <= 0 || cdiv <= 0 || S <= 0) return -2; hipLaunchKernelGGL(conv1d_dw_kernel, dim3((uint32_t)((C + kThreads - 1) / kThreads), grid_rows(rows)), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w, (const int*)cu, (uint16_t*)y, C, K, cdiv, S, - (uint32_t)x_ld, (uint32_t)y_ld, rows); + (uint32_t)x_ld, (uint32_t)y_ld, rows, (const void*)b, b_f32); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -958,32 +1065,60 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { const RadTensor* pos = r4d_opt(a, QN_POS); const RadTensor* qw = r4d_opt(a, QN_QW); const RadTensor* kw = r4d_opt(a, QN_KW); - if (!qkv || !pos || !qw || !kw) return R4D_NO(RAD_E_INVAL); + if (!qkv) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(qkv)); - R4D_NEED(dt_bf16(qw)); - R4D_NEED(dt_bf16(kw)); - if (pos->dtype != RAD_I32 || !r4d_contig(pos)) return R4D_NO(RAD_E_DTYPE); - if (!r4d_contig(qw) || !r4d_contig(kw)) return R4D_NO(RAD_E_STRIDE); + /* The gains bf16 or f32, both alike (a model may keep its norms f32, libref reads either); an + * absent gain is a unit gain. */ + const RadTensor* w0 = qw ? qw : kw; + if (w0 && ((w0->dtype != RAD_BF16 && w0->dtype != RAD_F32) || + (qw && kw && kw->dtype != qw->dtype))) + return R4D_NO(RAD_E_DTYPE); + if ((qw && !r4d_contig(qw)) || (kw && !r4d_contig(kw))) return R4D_NO(RAD_E_STRIDE); const long long hd = r4d_geti_or(a, "head_dim", 0); const long long nh = r4d_geti_or(a, "n_head", 0); const long long nkv = r4d_geti_or(a, "n_head_kv", 0); const long long rot = r4d_geti_or(a, "rotary_dim", hd); - if (hd <= 0 || nh <= 0 || nkv <= 0 || r4d_numel(qw) < hd || r4d_numel(kw) < hd) + if (hd <= 0 || nh <= 0 || nkv <= 0 || (qw && r4d_numel(qw) < hd) || + (kw && r4d_numel(kw) < hd)) return R4D_NO(RAD_E_SHAPE); /* The register layout holds head_dim up to 1024 (32 lanes x kQkMaxE). */ - if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (hd > 1024 || rot < 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + /* A rotation needs positions; the norm alone (rotary_dim 0) may go without. Positions are + * i32, or f32 read as the values they hold, M-contiguous ([M], or [C, M] at any plane + * pitch). */ + if (rot > 0 && !pos) return R4D_NO(RAD_E_INVAL); + if (pos && pos->dtype != RAD_I32 && pos->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (pos && (pos->rank == 2 ? pos->stride[1] != 1 : !r4d_contig(pos))) + return R4D_NO(RAD_E_STRIDE); + const int pos_f32 = pos && pos->dtype == RAD_F32; const char* mode = r4d_gets(a, "mode"); int md = 0; if (mode && !std::strcmp(mode, "gptj")) md = 1; else if (mode && !std::strcmp(mode, "blocks")) md = 2; else if (mode && !std::strcmp(mode, "gptj_blocks")) md = 3; else if (mode && !std::strcmp(mode, "imrope")) md = 4; + else if (mode && !std::strcmp(mode, "axial")) md = 5; else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); /* Any head_dim in the section modes (qk_norm_rope_any_kernel); the others need multiples of 32. */ - if (md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); + if (rot > 0 && md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); QkBlocks blk{}; long long M = 0, pplane = 0; - if (md == 4) { + if (rot == 0) { + /* Nothing turns: the rows are the positions' when bound, qkv's otherwise. */ + M = !pos ? 0 : pos->rank == 2 ? pos->shape[1] : r4d_numel(pos); + } else if (md == 5) { + /* Contiguous sections on their own ladders, one position component each; rank-1 + * positions turn every section by the one position. */ + blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); + if (blk.n <= 0) return R4D_NO(RAD_E_SHAPE); + if (pos->rank == 2) { + if (pos->shape[0] < blk.n) return R4D_NO(RAD_E_SHAPE); + M = pos->shape[1]; + pplane = pos->stride[0]; + } else { + M = r4d_numel(pos); + } + } else if (md == 4) { /* Interleaved M-RoPE reads three position planes; its sections only bound the * interleave. */ blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); @@ -1002,12 +1137,16 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { M = pos->shape[1]; pplane = pos->stride[0]; } else { + /* neox and gptj turn by one position a row. */ + if (pos->rank >= 2 && pos->shape[0] != 1 && pos->shape[pos->rank - 1] != 1) + return R4D_NO(RAD_E_SHAPE); M = r4d_numel(pos); } const long long width = (nh + 2 * nkv) * hd; long long Mq = 0; const long long ld = r4d_rows_pitch(qkv, width, &Mq); if (ld < 0) return R4D_NO(RAD_E_STRIDE); + if (rot == 0 && !pos) M = Mq; if (M <= 0 || Mq < M) return R4D_NO(RAD_E_SHAPE); const int e = r4d_qk_norm_rope_bf16(r4d_addr(qkv), r4d_addr(pos), r4d_addr(qw), r4d_addr(kw), (int)M, (int)hd, (int)nh, (int)nkv, (int)rot, md, @@ -1016,7 +1155,8 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "scale", 1.0), (float)r4d_getf(a, "wadd", 0.0), (int)ld, &blk, - (int)pplane, (long)(uintptr_t)s); + (int)pplane, (long)(uintptr_t)s, + w0 && w0->dtype == RAD_F32 ? 1 : 0, pos_f32); if (e == -2) return R4D_NO(RAD_E_SHAPE); return enc_status(e); } @@ -1058,6 +1198,24 @@ extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) { (int)y_ld, (long)(uintptr_t)s)); } +/* ------------------------------------------------------------------ cast bf16 -> f16 */ +extern "C" int r4d_rad_cast_f16(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r4d_rows_pitch(y, n, &M); + const long long x_ld = r4d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); + return enc_status(r4d_narrow_bf16_f16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + /* ------------------------------------------------------------------ the audio tower */ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) { @@ -1077,7 +1235,40 @@ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) { (long)(uintptr_t)s)); } +/* Both rows: silu_bf16 (bf16 in and out) and silu_f32 (f32 in, f32 or bf16 out). */ extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* Y = r4d_opt(a, 1); + if (!X || !Y) return R4D_NO(RAD_E_INVAL); + const bool x_f32 = X->dtype == RAD_F32; + if (x_f32 ? (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16) + : (X->dtype != RAD_BF16 || Y->dtype != RAD_BF16)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r4d_rows_pitch(Y, n, &M); + const long long x_ld = r4d_rows_pitch(X, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); + if (x_f32) { + const uint64_t total = (uint64_t)M * (uint64_t)n; + const dim3 grid((uint32_t)std::min((total + kThreads - 1) / kThreads, 65536u)); + if (Y->dtype == RAD_F32) + hipLaunchKernelGGL(silu_f32_kernel, grid, dim3(kThreads), 0, (hipStream_t)s, + (const float*)X->data, (float*)Y->data, (uint32_t)n, + (uint32_t)x_ld, (uint32_t)y_ld, total); + else + hipLaunchKernelGGL(silu_f32_kernel, grid, dim3(kThreads), 0, (hipStream_t)s, + (const float*)X->data, (uint16_t*)Y->data, (uint32_t)n, + (uint32_t)x_ld, (uint32_t)y_ld, total); + return enc_status(hipGetLastError() == hipSuccess ? 0 : -4); + } + return enc_status(r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); +} + +extern "C" int r4d_rad_gelu(const RadArgs* a, RadStream s) { const RadTensor* X = r4d_opt(a, 0); const RadTensor* Y = r4d_opt(a, 1); if (!X || !Y) return R4D_NO(RAD_E_INVAL); @@ -1090,7 +1281,7 @@ extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) { const long long x_ld = r4d_rows_pitch(X, n, &Mx); if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return enc_status(r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + return enc_status(r4d_gelu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, (long)(uintptr_t)s)); } @@ -1207,15 +1398,18 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) { const RadTensor* Wt = r4d_opt(a, 1); const RadTensor* cu = r4d_opt(a, 2); const RadTensor* Y = r4d_opt(a, 3); + const RadTensor* B = r4d_opt(a, 4); if (!X || !Wt || !cu || !Y) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(X)); R4D_NEED(dt_bf16(Wt)); R4D_NEED(dt_bf16(Y)); + if (B && B->dtype != RAD_BF16 && B->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); - if (!r4d_contig(Wt)) return R4D_NO(RAD_E_STRIDE); + if (!r4d_contig(Wt) || (B && !r4d_contig(B))) return R4D_NO(RAD_E_STRIDE); const long long C = r4d_geti_or(a, "n", 0), K = r4d_geti_or(a, "k", 0); const long long cdiv = r4d_geti_or(a, "cu_div", 1); - if (C <= 0 || K <= 0 || cdiv <= 0 || r4d_numel(Wt) < C * K) return R4D_NO(RAD_E_SHAPE); + if (C <= 0 || K <= 0 || cdiv <= 0 || r4d_numel(Wt) < C * K || (B && r4d_numel(B) < C)) + return R4D_NO(RAD_E_SHAPE); long long Mx = 0, My = 0; const long long x_ld = r4d_rows_pitch(X, C, &Mx); const long long y_ld = r4d_rows_pitch(Y, C, &My); @@ -1224,7 +1418,8 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) { return enc_status(r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y), (int)My, (int)C, (int)K, (int)cdiv, (int)(r4d_numel(cu) - 1), (int)x_ld, (int)y_ld, - (long)(uintptr_t)s)); + (long)(uintptr_t)s, B ? r4d_addr(B) : 0, + B && B->dtype == RAD_F32 ? 1 : 0)); } extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_f32_tile.h b/libr4d/r4d_f32_tile.h new file mode 100644 index 00000000..d809915e --- /dev/null +++ b/libr4d/r4d_f32_tile.h @@ -0,0 +1,155 @@ +// r4d_f32_tile.h -- the register-blocked f32 GEMM tile under libr4d's f32 GEMM (gemm_nt_bias at +// f32) and its f32 convolutions (conv1d and conv_t1d as implicit GEMMs, r4d_audio.hip). +// +// One 256-thread workgroup computes a BM x BN block (BM = 16 TM, BN = 16 TN) of C = A . W^T over +// K. Both operands are staged through LDS k-major, sixteen K a slab and two slabs of LDS, so the +// next slab's global loads are in flight under the current slab's FMAs and one barrier a slab +// suffices. A thread owns TM x TN accumulators and reads its operands from LDS as float4 (or +// float2) rows; every product is a fused multiply-add in ascending K, one rounding a product and +// sum, against libref's separate multiply and add in the same order. +// +// The operands come from loader policies: a thread stages rows `r0 + 16 j` of A (j < TM) and of W +// (j < TN) at one K column a slab, `kk = 16 slab + (tid % 16)`, so a GEMM reads rows in place and +// a convolution gathers the input row a tap reads, with its sequence's zero padding, from the same +// slot. A row or column past the operand reads zero. The epilogue is the caller's: it receives +// each run of contiguous columns a thread owns, in registers. +// +// Thread (tx, ty) = (tid % 16, tid / 16) owns rows g 16 RW + ty RW + r and columns +// g 16 CW + tx CW + c, RW = run_of(TM) and CW = run_of(TN): a wave's sixteen tx read 16 CW +// contiguous floats of W's slab row, conflict-free, and the two ty values of a wave read two A +// vectors, each broadcast. The LDS pitch is padded by four floats, which spreads the staging +// stores (a wave's 16 K columns of one row) over distinct banks. +#pragma once + +#include +#include + +namespace r4d_f32 { + +constexpr int kThr = 256; +constexpr int kBK = 16; // K a staged slab + +// The run a thread owns along an axis of `t` values: four where `t` is whole fours, else two (a +// tile of 6 columns is three runs of two, so a 96-wide output fills its tile exactly). +constexpr int run_of(int t) { return t % 4 == 0 ? 4 : 2; } + +// A plain row-major f32 operand: row r, column k at p[r * ld + k], zero past `rows` or `K`. Every +// load is issued, at an address clamped into the operand, and the zero selected after it: a load +// guarded by a branch serialises the slab's loads behind one another. Offsets are 32-bit, so the +// operand spans fewer than 2^32 elements (the shims check). +template +struct RowsLoader { + const float* p; + int ld, rows, K; + int k = 0; + uint32_t off[CNT]; + bool live[CNT]; + __device__ void init(int first_row, int kk) { + k = kk; +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const int r = first_row + 16 * j; + live[j] = r < rows; + off[j] = (uint32_t)(r < rows ? r : rows - 1) * (uint32_t)ld; + } + } + __device__ void fetch(float (&v)[CNT]) const { + const bool kl = k < K; + const uint32_t kc = (uint32_t)(kl ? k : K - 1); +#pragma unroll + for (int j = 0; j < CNT; ++j) { + const float x = p[off[j] + kc]; + v[j] = (live[j] && kl) ? x : 0.0f; + } + } + __device__ void advance() { k += kBK; } +}; + +template +__device__ __forceinline__ void tile(LA& la, LW& lw, int K, EP& ep) { + constexpr int BM = 16 * TM, BN = 16 * TN; + constexpr int AP = BM + 4, WP = BN + 4; + constexpr int RW = run_of(TM), RG = TM / RW; + constexpr int CW = run_of(TN), CG = TN / CW; + static_assert(RW * RG == TM && CW * CG == TN && (RW == 2 || RW == 4) && (CW == 2 || CW == 4), + "a thread's rows and columns are whole runs of two or four"); + __shared__ __attribute__((aligned(16))) float sA[2][kBK][AP]; + __shared__ __attribute__((aligned(16))) float sW[2][kBK][WP]; + + const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; + + float acc[TM][TN]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = 0.0f; + + float ra[TM], rw[TN]; + la.fetch(ra); + lw.fetch(rw); + const int ns = (K + kBK - 1) / kBK; + for (int s = 0; s < ns; ++s) { + const int b = s & 1; +#pragma unroll + for (int j = 0; j < TM; ++j) sA[b][tx][ty + 16 * j] = ra[j]; +#pragma unroll + for (int j = 0; j < TN; ++j) sW[b][tx][ty + 16 * j] = rw[j]; + __syncthreads(); + if (s + 1 < ns) { + la.advance(); + lw.advance(); + la.fetch(ra); + lw.fetch(rw); + } +#pragma unroll + for (int k = 0; k < kBK; ++k) { + float a[TM], w[TN]; +#pragma unroll + for (int g = 0; g < RG; ++g) { + const float* src = &sA[b][k][g * 16 * RW + ty * RW]; + if constexpr (RW == 4) { + const float4 q = *(const float4*)src; + a[g * 4] = q.x; a[g * 4 + 1] = q.y; a[g * 4 + 2] = q.z; a[g * 4 + 3] = q.w; + } else { + const float2 q = *(const float2*)src; + a[g * 2] = q.x; a[g * 2 + 1] = q.y; + } + } +#pragma unroll + for (int g = 0; g < CG; ++g) { + const float* src = &sW[b][k][g * 16 * CW + tx * CW]; + if constexpr (CW == 4) { + const float4 q = *(const float4*)src; + w[g * 4] = q.x; w[g * 4 + 1] = q.y; w[g * 4 + 2] = q.z; w[g * 4 + 3] = q.w; + } else { + const float2 q = *(const float2*)src; + w[g * 2] = q.x; w[g * 2 + 1] = q.y; + } + } +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) acc[i][j] = __builtin_fmaf(a[i], w[j], acc[i][j]); + } + /* One barrier a slab: the next slab goes to the other buffer, which every thread finished + * reading before it passed this slab's barrier. */ + } + + /* A run of CW columns as one float4 (the last two lanes unused at CW 2), so the accumulators + * stay in registers through the caller's store; `gj` says which of the thread's CG runs it + * is, for state the caller keeps per run. */ +#pragma unroll + for (int gi = 0; gi < RG; ++gi) +#pragma unroll + for (int r = 0; r < RW; ++r) +#pragma unroll + for (int gj = 0; gj < CG; ++gj) { + const float* q = acc[gi * RW + r] + gj * CW; + float4 v; + if constexpr (CW == 4) v = make_float4(q[0], q[1], q[2], q[3]); + else v = make_float4(q[0], q[1], 0.0f, 0.0f); + ep(gi * 16 * RW + ty * RW + r, gj * 16 * CW + tx * CW, CW, v, gj); + } +} + +} // namespace r4d_f32 diff --git a/libr4d/r4d_gemm_f32_nt_bias.hip b/libr4d/r4d_gemm_f32_nt_bias.hip new file mode 100644 index 00000000..eb74447c --- /dev/null +++ b/libr4d/r4d_gemm_f32_nt_bias.hip @@ -0,0 +1,163 @@ +// r4d_gemm_f32_nt_bias.hip -- gemm_nt_bias at f32: C = res + act(A @ W^T + bias) with an f32 +// activation and weight, f32 accumulation, and the result f32 or rounded to bf16 at the store. +// The epilogue is libref's: the biased product, the activation of it and the residual sum each +// rounded to C's dtype, as the unfused chain's tensors would be; at an f32 C only the arithmetic +// rounds. A diffusion transformer's patch projections and output heads, its timestep MLP, and a +// video decoder's 1x1 projections run here: K from 24 to a few thousand, N from 24 to 5376, M up +// to a hundred thousand rows. +// +// The tile is r4d_f32_tile.h's at 128 rows: 128 columns where N is wider than 96, 96 where it is +// wider than 64, 64 where it is wider than 32, 32 otherwise, so a narrow head (N 32 or 96) fills +// its tile. No split-K: the narrow-N shapes have hundreds of row tiles. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_f32_tile.h" + +#include +#include + +namespace { + +constexpr int kTM = 8, kBM = 16 * kTM; + +__device__ __forceinline__ float gelu_erf(float x) { + return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f)); +} +__device__ __forceinline__ float gelu_tanh(float x) { + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + return 0.5f * x * (1.0f + tanhf(k0 * (x + k1 * x * x * x))); +} + +// C's element: f32 as it is, or bf16 rounded to nearest even. +__device__ __forceinline__ float rd(const float*, float v) { return v; } +__device__ __forceinline__ float rd(const uint16_t*, float v) { return bf16_to_f32(f32_to_bf16(v)); } +__device__ __forceinline__ float ld1(const float* p) { return *p; } +__device__ __forceinline__ float ld1(const uint16_t* p) { return bf16_to_f32(*p); } +__device__ __forceinline__ void st1(float* p, float v) { *p = v; } +__device__ __forceinline__ void st1(uint16_t* p, float v) { *p = f32_to_bf16(v); } +// Four (or two) adjacent elements in one store: 16 (8) bytes at f32, 8 (4) at bf16. +__device__ __forceinline__ void stv(float* p, int cnt, const float* v) { + if (cnt == 4) *(float4*)p = make_float4(v[0], v[1], v[2], v[3]); + else *(float2*)p = make_float2(v[0], v[1]); +} +__device__ __forceinline__ void stv(uint16_t* p, int cnt, const float* v) { + if (cnt == 4) *(uint2*)p = make_uint2(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3])); + else *(uint32_t*)p = bf16x2_rne(v[0], v[1]); +} + +// `act` 0 none, 1 exact GELU, 2 tanh GELU. `R` may be `C` itself (a residual updated in place): +// each element is read by the thread that stores it, before the store. `vec` says C's rows take +// whole-run stores (a pitch of whole runs at an aligned base). +template +__global__ __launch_bounds__(r4d_f32::kThr) void gemm_f32_bias_kernel( + const float* __restrict__ A, int lda, const float* __restrict__ W, int K, + const void* __restrict__ bias, int bias_f32, const TY* R, int ldr, TY* C, int ldc, int M, + int N, int act, int vec) { + constexpr int BN = 16 * TN, CW = r4d_f32::run_of(TN); + const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; + const int m0 = blockIdx.y * kBM, n0 = blockIdx.x * BN; + r4d_f32::RowsLoader la{ A, lda, M, K }; + r4d_f32::RowsLoader lw{ W, K, N, K }; + la.init(m0 + ty, tx); + lw.init(n0 + ty, tx); + /* The bias of this thread's TN columns (runs of CW, 16 CW apart), read once. */ + float bc[TN]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int n = n0 + (j / CW) * 16 * CW + tx * CW + j % CW; + const int nc = n < N ? n : N - 1; + bc[j] = bias_f32 ? ((const float*)bias)[nc] : bf16_to_f32(((const uint16_t*)bias)[nc]); + } + auto ep = [&](int r, int c, int cnt, float4 q, int g) { + const int m = m0 + r, n = n0 + c; + if (m >= M || n >= N) return; + float v[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < CW; ++e) { + float t = rd(C, v[e] + bc[g * CW + e]); + if (act == 1) t = rd(C, gelu_erf(t)); + else if (act == 2) t = rd(C, gelu_tanh(t)); + if (R && n + e < N) t = ld1(R + (size_t)m * ldr + n + e) + t; + v[e] = t; + } + TY* dst = C + (size_t)m * ldc + n; + if (vec && n + cnt <= N) { + stv(dst, cnt, v); + } else { +#pragma unroll + for (int e = 0; e < 4; ++e) + if (e < cnt && n + e < N) st1(dst + e, v[e]); + } + }; + r4d_f32::tile(la, lw, K, ep); +} + +} // namespace + +// ============================================================== the plugin ABI entry point +enum { GF_A = 0, GF_W, GF_BIAS, GF_RES, GF_Y }; + +extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) { + const RadTensor* A = r4d_opt(a, GF_A); + const RadTensor* W = r4d_opt(a, GF_W); + const RadTensor* B = r4d_opt(a, GF_BIAS); + const RadTensor* R = r4d_opt(a, GF_RES); + const RadTensor* Y = r4d_opt(a, GF_Y); + if (!A || !W || !B || !Y) return R4D_NO(RAD_E_INVAL); + /* f32 A and W; C f32 or bf16, the residual C's dtype; the bias f32 or bf16. */ + if (A->dtype != RAD_F32 || W->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_F32 && B->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (R && R->dtype != Y->dtype) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(W) || !r4d_contig(B)) return R4D_NO(RAD_E_STRIDE); + + const long long K = r4d_geti_or(a, "K", r4d_dim(W, (int)W->rank - 1)); + const long long N = r4d_geti_or(a, "N", r4d_numel(W) / (K > 0 ? K : 1)); + if (K <= 0 || N <= 0 || r4d_numel(W) < N * K || r4d_numel(B) < N) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Ma = 0, Mr = 0; + const long long ldc = r4d_rows_pitch(Y, N, &M); + const long long lda = r4d_rows_pitch(A, K, &Ma); + const long long ldr = R ? r4d_rows_pitch(R, N, &Mr) : 0; + if (ldc < 0 || lda < 0 || ldr < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Ma < M || (R && Mr < M)) return R4D_NO(RAD_E_SHAPE); + /* The tile's loaders index A and W with 32-bit element offsets. */ + if (M > 0x7fffffffll || N > 0x7fffffffll || K > 0x7fffffffll || lda > 0x7fffffffll || + ldc > 0x7fffffffll || ldr > 0x7fffffffll || (M + kBM - 1) / kBM > 65535 || + M * lda >= (1ll << 32) || N * K >= (1ll << 32)) + return R4D_NO(RAD_E_SHAPE); + + const char* act_s = r4d_gets(a, "act"); + int act = 0; + if (act_s && *act_s) { + if (!std::strcmp(act_s, "gelu")) act = 1; + else if (!std::strcmp(act_s, "gelu_tanh")) act = 2; + else if (std::strcmp(act_s, "none")) return R4D_NO(RAD_E_SCHEMA); + } + const int bias_f32 = B->dtype == RAD_F32; + const bool f32 = Y->dtype == RAD_F32; + /* Whole-run stores where every row starts aligned to a run of four. */ + const unsigned run_bytes = f32 ? 16u : 8u; + const int vec = (ldc % 4) == 0 && r4d_aligned(r4d_p(Y), run_bytes); + + const int tn = N > 96 ? 8 : N > 64 ? 6 : N > 32 ? 4 : 2; + const dim3 grid((unsigned)((N + 16 * tn - 1) / (16 * tn)), (unsigned)((M + kBM - 1) / kBM)); + const dim3 block(r4d_f32::kThr); +#define GF_L(TN, TY) \ + return R4D_EMIT(stream, (gemm_f32_bias_kernel), grid, block, 0, \ + (const float*)r4d_p(A), (int)lda, (const float*)r4d_p(W), (int)K, r4d_p(B), \ + bias_f32, (const TY*)r4d_p(R), (int)ldr, (TY*)r4d_wp(Y), (int)ldc, (int)M, \ + (int)N, act, vec) + if (f32) { + if (tn == 8) GF_L(8, float); + if (tn == 6) GF_L(6, float); + if (tn == 4) GF_L(4, float); + GF_L(2, float); + } + if (tn == 8) GF_L(8, uint16_t); + if (tn == 6) GF_L(6, uint16_t); + if (tn == 4) GF_L(4, uint16_t); + GF_L(2, uint16_t); +#undef GF_L +} diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 12fffcdd..bbaf0964 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -1,8 +1,9 @@ -// Block-scaled FP8 weight, fp8 activation. Two entry points share one K loop with two tile shapes: +// Block-scaled FP8 weight, fp8 activation. Two entry points, two kernels with one operand mapping: // -// r4d_gemm_fp8a8_nt_m16 M <= 16 (decode and speculative verify). One 16-wide token tile, -// split-K over the caller's scratch. -// r4d_gemm_fp8a8_tiled any M (prefill). 128x128 tile, eight waves. +// r4d_gemm_fp8a8_nt_m16 M <= 64 (decode and speculative verify). A wave's 16 weight rows +// against up to four 16-token tiles, split-K over the caller's scratch. +// r4d_gemm_fp8a8_tiled any M (prefill). 128x128 tile, eight waves, each 2 weight tiles x 4 +// activation tiles; the weight from registers, the activation from LDS. // // Reads block-scaled FP8 checkpoints as shipped (DeepSeek-style, e.g. Qwen3.8-27B-FP8): // `.weight` is F8_E4M3 [N][K] and `.weight_scale_inv` is a BF16 scale per @@ -11,15 +12,15 @@ // // Properties of the K loop: // 1. The bf16 scale decodes as `__uint_as_float(s << 16)` (r4d_fp8_wmma.h). -// 2. Operand roles are a template parameter (`AW`): with the weight on A the kernel computes -// Y[rows][nb], i.e. C^T of `C[M,N] = A[M,K] @ W[N,K]^T`. +// 2. The weight is the WMMA A operand on both tiles, so D is C^T of `C[M,N] = A[M,K] @ W[N,K]^T` +// and a lane's eight accumulator slots are eight weight rows of one activation row. // 3. Split-K uses the caller's scratch (nothing on a launch path allocates), sized by // r4d_gemm_fp8a8_nt_m16_scratch(). The summation order is fixed. // 4. C is bf16, like every GEMM in this library. // // Load-bearing: the padded LDS row pitch (r4d_fp8_wmma.h `lds_pitch`), the one-K-tile-ahead -// register prefetch, the two accumulator sets, and the staging assignment (`kTPR`). Reasons are at -// each. +// register prefetch, the two accumulator sets, the staging assignment (`kTPR`) and, on the prefill +// tile, keeping the weight out of LDS. Reasons are at each. // // Entry points return a negative code rather than throwing: they are reachable from a kernel // plugin, and an exception must not cross the .so boundary. @@ -48,41 +49,25 @@ constexpr uint32_t kWave = 32; // a property of the checkpoint. constexpr uint32_t kBlock = 128; -// Prefill tile: kFN 128, 8 waves. A block re-reads its weight row band once per M tile, but that is -// not the limit: the passes are absorbed by the 64 MB MALL (the grid is x-fastest, so one N band's -// M tiles dispatch together), and doubling FM to halve the traffic is slower. The fragment read's -// LDS bank conflicts are fixed by the padded pitch (r4d_fp8_wmma.h `lds_pitch`). The remaining time -// is spread over the per-128-column fold, the global fetch, the B fragment reads, the activation -// scale gather (4-13% each) and the loop itself (barrier, staging stores, loop arithmetic); with all -// per-iteration costs removed the loop reaches about 65% of the WMMA issue rate. -constexpr uint32_t kFN = 128, kFK = 64; // kFK is BYTES per LDS row // Narrow-tile K width: one gfx1201 cacheline, 256 B. `kTPR` is FK/32, so this puts eight threads // on a row, which makes the weight stream coalesce (64 B would put two and cost a third of the -// bandwidth; 128 B is also full speed; 512 B needs 64 VGPRs of prefetch and does not build). The -// prefill tile stays at 64: it is not fetch-bound, and a 256 B row of its 128-row LDS tile would be -// 32 KiB of A alone. +// bandwidth; 128 B is also full speed; 512 B needs 64 VGPRs of prefetch and does not build). constexpr uint32_t kFKNarrow = 256; -constexpr uint32_t kFWaves = 8; + +// ---- the prefill tile's geometry --------------------------------------------------------------- +// +// A block owns 128 weight rows x 128 activation rows: eight waves as kPWW (weight) x kPWA +// (activation), each wave kPTW weight tiles x kPTA activation tiles of 16 x 16. Eight accumulator +// tiles a wave is a hard cap: each is two f32 sets (`raw` and `out`), so more spills. The staged K +// tile is kPFK bytes, two per 128-column scale block. See gemm_8a8_prefill_kernel for the layout +// and what was measured. +constexpr uint32_t kPTW = 2, kPTA = 4, kPWW = 4, kPWA = 2; +constexpr uint32_t kPBN = kPWW * kPTW * 16, kPBM = kPWA * kPTA * 16; // weight x activation rows +constexpr uint32_t kPWaves = kPWW * kPWA; +constexpr uint32_t kPFK = 64; +static_assert(kPBN == kBlock, "a block's weight rows are one scale row"); // Activation bands per raster group of the prefill tile; see the kernel's grouping. -constexpr uint32_t kGroupM = 16; -// Prefill register tile: 1 M tile x 8 N tiles per wave, so the 8 waves cover 8 distinct row tiles. -// It is a template parameter so the narrow instantiation keeps 1x1. Eight accumulator tiles is a -// hard cap: each is two f32 accumulator sets, so MT*NT > 8 spills (2x8 runs at a third the rate). -// 1x8 and 2x4 tie. Measured and rejected: -// - 1x4 (FN = 64, four resident blocks instead of three): ~20% slower; -// - 2x4 on a second wave axis (4x2 waves, same 128x128 block, a third fewer fragment reads): -// a wash, since the fragment reads are not the limit; -// - a whole 128-column scale block per iteration (compile-time fold position): costs 44 VGPRs -// and two waves per SIMD, slower; zero-C first WMMA instead of clearing `raw`, explicit -// sched_group_barrier interleaving, and a manual fragment-read pipeline: neutral or worse; -// - lds_barrier() instead of __syncthreads(): a few percent slower here (the vector-cache -// invalidate it skips is worth having in this loop); -// - a transposed 1xMW wave grid (e.g. 64x256 blocks for a SwiGLU epilogue): about 4x slower even -// at the same 128x128 tile. The AW=false fold keeps one activation scale per row the wave owns -// (`as[MT][8]`), so a grid that raises MT pays in registers; the MWx1 grid gives a wave one row -// tile, and the weight's scale (one scalar per 128 columns) tolerates being spread. Hence the -// GATED epilogue exists only for the decode tile. -constexpr uint32_t kFMTiles = 1, kFNTiles = 8; +constexpr uint32_t kGroupM = 8; // Blocks the split aims for. A fixed tuning default, not derived from the CU count: `ksplit` sets // the order K partials are summed in, so deriving it would make output depend on the card. @@ -123,22 +108,16 @@ constexpr uint32_t kSplitThinCap = 64u; // are applied once per block: `raw` accumulates 128 columns unscaled and then folds into `out` // (64 extra VGPRs, no per-element arithmetic in the inner loop). // -// Both operands are row-major [row][k] byte planes, so staging is a byte copy of 32 consecutive k. +// ---- the weight is the A operand --------------------------------------------------------------- // -// ---- AW: which operand is the weight ----------------------------------------------------------- -// -// The scales differ in shape (weight: one per 128 rows; activation: one per token), and the -// accumulator is column-distributed (a lane owns one B row and eight A rows), so a per-B-row scale -// is one scalar per lane and a per-A-row scale eight. -// -// AW = true A is the weight. D is [N][M] and the epilogue transposes on the way out (sixteen -// lanes write addresses `N` apart). Used only at M <= 16, where the output is -// negligible against the weight read. The small dimension lands on B (one 16-wide -// N tile) and the grid runs over the weight rows. -// -// AW = false A is the activation (prefill). D is [M][N] and the store is coalesced. Correct -// only when FN divides 128, so the weight's block scale is one scalar per block -// (static_assert'd below). +// On both tiles: a lane's A fragment bytes are its 32 bytes of the fragment-order plane, and the +// activation is B. The scales differ in shape (weight: one per 128 rows; activation: one per token), +// and the accumulator is column-distributed (a lane owns one B row and eight A rows), so with the +// weight on A a lane's eight accumulator slots share one activation scale, and a wave whose weight +// rows sit in one 128-row scale row folds with one weight scale. D is [N][M]: the narrow tile's +// epilogue transposes on the way out (sixteen lanes write addresses `N` apart), which at M <= 64 is +// negligible against the weight read; the prefill tile stores C row by row, eight consecutive +// weight rows of one activation row as one 16-byte store. // ---- GATED: SwiGLU and the quantiser folded into the epilogue --------------------------------- // // Replaces `gated_quant_fp8` re-reading this kernel's [M, 2n] bf16 output and writing [M, n] E4M3 @@ -166,13 +145,12 @@ constexpr uint32_t kSplitThinCap = 64u; /* I8 is the same kernel at int8 codes (gemm_i8a8_*): i8 operands in the same staging and fragment * order, v_wmma_i32_16x16x16_iu8, and a weight scale per row per 128 K (bf16, tile-major * [N/16][K/128][16], r4d_fp8_layout.cpp) instead of per 128x128 tile. Only the fold differs: one - * weight scale per accumulator row on the narrow path, one per lane's column on the prefill tile. */ -/* Waves per SIMD for each tile shape (R4D_WAVES): pins the register budget each shape was tuned at - * (the narrow tile's NT accumulators and K-step unroll are sized against it), so a compiler release + * weight scale per accumulator row, eight a lane, read as one 16-byte load. */ +/* Waves per SIMD for each narrow tile shape (R4D_WAVES): pins the register budget each shape was + * tuned at (the NT accumulators and K-step unroll are sized against it), so a compiler release * cannot change occupancy. Shapes with one or two waves per block are LDS-bound and use that * count. */ -constexpr uint32_t f8_waves(bool full, bool aw, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) { - if (!aw) return 6u; +constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) { if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u; if (mw == 2u) return nt == 1u ? 12u : nt == 2u ? 8u : nt == 3u ? 5u : 4u; if (!i8) { @@ -190,9 +168,17 @@ constexpr uint32_t f8_waves(bool full, bool aw, uint32_t nt, uint32_t mw, uint32 return full ? (mw == 4u ? 5u : 6u) : (mw == 4u ? 7u : 8u); } -template -__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, AW, NT, MW, FK, I8)) +// ---- BIAS: gemm_nt_q_bias's epilogue on the narrow tile --------------------------------------- +// +// With BIAS (never split) the store adds the bf16 `Bias` of each weight row to the f32 accumulator +// before its one rounding, libref's order, and writes C at row pitch `c_ld`, so C may be a column +// slice of a wider buffer (a modulation table's block of columns). +// +// The narrow tile: MW waves a block, a wave one 16-row weight tile (A, fragments straight from the +// plane into registers) against NT 16-token tiles (B, staged through LDS). +template +__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8)) void gemm_fp8a8_kernel( const uint8_t* __restrict__ Ap, const void* __restrict__ Sa, const uint8_t* __restrict__ Bp, const void* __restrict__ Sb, @@ -201,33 +187,18 @@ void gemm_fp8a8_kernel( uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck, uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr, uint16_t* __restrict__ Yb = nullptr, - uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0) { + uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0, + const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) { constexpr uint32_t FN = NT * 16; // B rows a block - constexpr uint32_t FM = MW * MT * 16; // A rows a block + constexpr uint32_t FM = MW * 16; // A rows a block + // The weight scale is folded as one scalar per wave, indexed at `(m0 + wm) / kBlock`, so a + // wave's 16 rows (not the block's FM) must sit in one 128-row scale row; m0 is FM-aligned and FM + // a multiple of 16, so they never straddle one. Requiring it of the block would cap MW at 8. - // The AW=false fold reads the weight's scale as one scalar for the block's B rows, so they must - // sit in one 128-row scale row: FN divides 128 and n0 is FN-aligned. - static_assert(AW || kBlock % FN == 0, "AW=false folds the weight scale as one scalar per block"); - // With AW the A-side (weight) scale is folded as one scalar per wave, indexed at - // `(m0 + wm) / kBlock`, so a wave's MT*16 rows (not the block's FM) must sit in one 128-row - // scale row. Requiring it of the block would cap MW at 8. - static_assert(!AW || (MT * 16 <= kBlock && kBlock % (MT * 16) == 0), - "a wave's A rows must sit in one scale row"); - // ...and m0 is FM-aligned with FM a multiple of MT*16, so a wave's rows never straddle either. - static_assert(!AW || FM % (MT * 16) == 0, "FM must be a whole number of wave row tiles"); - - // Double-buffered on the prefill tile only: one buffer needs two barriers per K tile (finish - // reading, then publish) around just 32 WMMA; two buffers leave only the publish barrier (~5% - // at gate_up's prefill shape, despite 3 resident blocks per WGP instead of 4). The narrow tile - // keeps one buffer (two would be 74 KiB, over the 64 KiB limit; decode waits on HBM anyway) and - // the two-barrier structure is kept by the `else` at the loop foot. - constexpr uint32_t kBufs = AW ? 1u : 2u; - __shared__ uint8_t s_b[kBufs][FN * lds_pitch()]; - // No LDS for A when A is the (fragment-order) weight: a lane loads its fragment bytes straight - // from global, so the narrow tile needs 4 KiB of LDS instead of 38. One byte, since a - // zero-length array is not a type. - __shared__ uint8_t s_a[kBufs][AW ? 1u : FM * lds_pitch()]; - uint32_t buf = 0; + // One buffer: two (74 KiB) would be over the 64 KiB limit, and decode waits on HBM anyway, so + // the two-barrier structure is kept by the barrier at the loop foot. No LDS for A: a lane loads + // its fragment bytes straight from global, so the tile needs 4 KiB of LDS instead of 38. + __shared__ uint8_t s_b[FN * lds_pitch()]; const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; // Split-K. `ck` is a multiple of both 128 (the scale block) and FK, and the launcher derives @@ -236,25 +207,10 @@ void gemm_fp8a8_kernel( const uint32_t kend = ck ? min(cols, kbeg + ck) : cols; if (kbeg >= kend) return; - // The prefill grid runs in groups of kGroupM activation bands. Blocks dispatch in flattened-id - // order; with the plain x-fastest grid the activation is read once per 128 weight rows, which - // halves the rate once it exceeds the 64 MB MALL. Within a group the bands stay cached across - // the N sweep and the weight is read once per group. With kGroupM bands or fewer the plain order - // is used and the division skipped. - uint32_t bm = blockIdx.x, bn = blockIdx.y; - if (!AW && gridDim.x > kGroupM) { - const uint32_t per = kGroupM * gridDim.y; - const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; - const uint32_t first = (lin / per) * kGroupM, r = lin % per; - const uint32_t gm = min(gridDim.x - first, kGroupM); - bm = first + r % gm; - bn = r / gm; - } - const uint32_t m0 = bm * FM; - const uint32_t n0 = bn * FN; - // Wave grid MW(M) x 1(N): a wave owns MT*16 A rows and all FN B rows (see kFMTiles for why - // there is no second wave axis). - const uint32_t wm = wave * (MT * 16), wn = 0; + const uint32_t m0 = blockIdx.x * FM; + const uint32_t n0 = blockIdx.y * FN; + // Wave grid MW(M) x 1(N): a wave owns 16 A rows and all FN B rows. + const uint32_t wm = wave * 16u, wn = 0; /* GATED changes which weight rows a wave owns before the epilogue: the gate and up halves are * `rows/2` apart, so later uses of `m0 + wm` (fragment tile, liveness, A-side scale) go through * wrow0. A wave still owns 16 consecutive rows, so they stay in one scale row. */ @@ -263,16 +219,13 @@ void gemm_fp8a8_kernel( GATED ? ((wave < kGHalf ? 0u : rows / 2u) + blockIdx.x * (FM / 2u) + (wave % kGHalf) * 16u) : (m0 + wm); - static_assert(!GATED || (AW && MT == 1u && (MW % 2u) == 0u), - "the gated fold is the narrow tile's epilogue: A is the weight, one M tile a " - "wave, and the waves split in half"); + static_assert(!GATED || (MW % 2u) == 0u, "the gated fold splits the waves in half"); static_assert(!(GATED && I8), "the gated epilogue quantises to E4M3 and has no int8 form"); + static_assert(!BIAS || (!GATED && !I8), "the bias epilogue is the fp8 narrow tile's"); - f8v raw[MT][NT], out[MT][NT]; + f8v raw[NT], out[NT]; #pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) { raw[i][j] = acc_zero(); out[i][j] = acc_zero(); } + for (uint32_t j = 0; j < NT; ++j) { raw[j] = acc_zero(); out[j] = acc_zero(); } // ---- staging assignment (a bandwidth decision) ------------------------------------------------ // @@ -283,76 +236,47 @@ void gemm_fp8a8_kernel( // threads per row 2 4 8 16 32 // GB/s 422 626 633 635 636 (plain stream: 638) // - // Two threads per row leaves a third of the bandwidth unused; four recover it. kTPR = FK/32: 2 on - // the prefill tile (not fetch-bound), 8 on the 256-byte narrow tile (fetch-bound). A pass covers - // blockDim/kTPR rows; a thread holds kAP granule pairs at one column across kAP rows. + // Two threads per row leaves a third of the bandwidth unused; four recover it. kTPR = FK/32 is 8 + // on the 256-byte K tile (fetch-bound). A pass covers blockDim/kTPR rows. constexpr uint32_t kSeg = 32; // bytes a thread stages, contiguous constexpr uint32_t kTPR = FK / kSeg; // threads covering one row constexpr uint32_t kRPP = (MW * kWave) / kTPR; // rows one pass covers - constexpr uint32_t kAP = AW ? 0u : (FM + kRPP - 1) / kRPP; // passes over the A tile - // Fragment-order supertiles per staged K tile when A is the weight: one 32-byte load per lane, - // four fragments each (see r4d_fp8_frag.h). - constexpr uint32_t kAF = AW ? FK / r4d_fp8::kSuperK : 0u; - constexpr uint32_t kBP = AW ? (FN + kRPP - 1) / kRPP : 0u; // ... and over the B tile + // Fragment-order supertiles per staged K tile: one 32-byte load per lane, four fragments each + // (see r4d_fp8_frag.h). + constexpr uint32_t kAF = FK / r4d_fp8::kSuperK; + constexpr uint32_t kBP = (FN + kRPP - 1) / kRPP; // passes over the B tile static_assert(kTPR >= 1 && kRPP >= 1, "FK must be at least 32 B and no wider than the block"); const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg; - const uint32_t am = sn; // A staging, identical assignment // The B rows this lane owns, one per N tile (column `frag_c` of each of its NT accumulators, // 16 apart). A per-B-row scale must be looked up for each, not just the first. const uint32_t brow0 = n0 + wn + frag_c(lane); - // ---- B from the fragment-order plane, when B is the weight ----------------------------------- - // - // A wave reads one (16 row, 64 k) tile per pass: 32 lanes x 32 contiguous bytes, the full 1 KiB. - // It is de-permuted in the LDS store, so LDS holds the usual row-major padded tile. - constexpr uint32_t kBSK = FK / r4d_fp8::kSuperK; // k supertiles a staged tile - constexpr uint32_t kBTL = (FN / 16u) * (kBSK ? kBSK : 1u); // 16-row tiles in it - constexpr uint32_t kBFP = AW ? 0u : (kBTL * 32u + MW * kWave - 1u) / (MW * kWave); - const uint32_t btile = tid / 32u, blane = tid % 32u; const uint8_t* bsrc = Bp + (size_t)(n0 + sn) * b_ld + sk; - const uint8_t* asrc = Ap + (size_t)(m0 + am) * a_ld + sk; - // A as fragments: a wave owns one 16-row weight tile (MT is 1 on the narrow path), so its A - // operand for 64 k is this lane's 32 bytes. `ksuper` is the plane's tile stride; `arow` is out - // of range only when N is not a multiple of FM. + // A as fragments: a wave owns one 16-row weight tile, so its A operand for 64 k is this lane's + // 32 bytes. `ksuper` is the plane's tile stride; `arow` is out of range only when N is not a + // multiple of FM. const uint32_t ksuper = cols / r4d_fp8::kSuperK; const uint32_t arow = wrow0 / 16u; - const bool alive = !AW || wrow0 < rows; + const bool alive = wrow0 < rows; const uint8_t* afrag = Ap + (size_t)lane * r4d_fp8::kLaneBytes; // One K tile ahead in registers: the load for tile c0+FK is issued before tile c0's WMMA and // consumed after it, hiding memory latency under arithmetic. `sk` is the same column for every // pass, so only row existence varies per pass. const bool k_live = Full || (kbeg + sk + kSeg <= cols); - // `pa` stages A row-major into LDS; `pf` is A read as fragments. Exactly one is live; the other - // is a zero-length array. /* `pf` is read straight from registers by the mma loop, so its prefetch goes to `pfn` and the * loop foot rotates them; prefetching into `pf` would overwrite the current tile (a bug hidden * whenever split-K gives a block only one K iteration). */ - Stage8 pb[kBP ? kBP : 1u], pa[kAP ? kAP : 1u], pw[kBFP ? kBFP : 1u]; - Stage8 pf[kAF ? kAF : 1u], pfn[kAF ? kAF : 1u]; + Stage8 pb[kBP]; + Stage8 pf[kAF], pfn[kAF]; #pragma unroll for (uint32_t p = 0; p < kBP; ++p) { const uint32_t r = sn + p * kRPP; pb[p] = stage8_load(bsrc + (size_t)p * kRPP * b_ld + kbeg, k_live && r < FN && (Full || (n0 + r) < nb)); } -#pragma unroll - for (uint32_t p = 0; p < kBFP; ++p) { - const uint32_t ti = btile + p * ((MW * kWave) / 32u); - const uint32_t rt = ti / (kBSK ? kBSK : 1u), ks = ti % (kBSK ? kBSK : 1u); - const uint32_t st = kbeg / r4d_fp8::kSuperK + ks; - pw[p] = stage8_load(Bp + (size_t)((n0 / 16u + rt) * ksuper + st) * r4d_fp8::kTileBytes - + (size_t)blane * r4d_fp8::kLaneBytes, - ti < kBTL && (n0 + rt * 16u) < nb && st < ksuper); - } -#pragma unroll - for (uint32_t p = 0; p < kAP; ++p) { - const uint32_t r = am + p * kRPP; - pa[p] = stage8_load(asrc + (size_t)p * kRPP * a_ld + kbeg, - k_live && r < FM && (Full || (m0 + r) < rows)); - } #pragma unroll for (uint32_t p = 0; p < kAF; ++p) { const uint32_t st = kbeg / r4d_fp8::kSuperK + p; @@ -364,20 +288,7 @@ void gemm_fp8a8_kernel( #pragma unroll for (uint32_t p = 0; p < kBP; ++p) { const uint32_t r = sn + p * kRPP; - if (r < FN) stage8_store(s_b[buf], r, sk, pb[p]); - } -#pragma unroll - for (uint32_t p = 0; p < kBFP; ++p) { - const uint32_t ti = btile + p * ((MW * kWave) / 32u); - if (ti >= kBTL) continue; - const uint32_t rt = ti / (kBSK ? kBSK : 1u), ks = ti % (kBSK ? kBSK : 1u); - stage8_store_frag(s_b[buf], rt * 16u + (blane & 15u), - ks * r4d_fp8::kSuperK + (blane >> 4) * 8u, pw[p]); - } -#pragma unroll - for (uint32_t p = 0; p < kAP; ++p) { - const uint32_t r = am + p * kRPP; - if (r < FM) stage8_store(s_a[buf], r, sk, pa[p]); + if (r < FN) stage8_store(s_b, r, sk, pb[p]); } __syncthreads(); const uint32_t c1 = c0 + FK; @@ -390,22 +301,6 @@ void gemm_fp8a8_kernel( pb[p] = stage8_load(bsrc + (size_t)p * kRPP * b_ld + c1, live && (Full || (n0 + r) < nb)); } -#pragma unroll - for (uint32_t p = 0; p < kBFP; ++p) { - const uint32_t ti = btile + p * ((MW * kWave) / 32u); - const uint32_t rt = ti / (kBSK ? kBSK : 1u), ks = ti % (kBSK ? kBSK : 1u); - const uint32_t st = c1 / r4d_fp8::kSuperK + ks; - pw[p] = stage8_load(Bp + (size_t)((n0 / 16u + rt) * ksuper + st) * r4d_fp8::kTileBytes - + (size_t)blane * r4d_fp8::kLaneBytes, - ti < kBTL && (n0 + rt * 16u) < nb && st < ksuper); - } -#pragma unroll - for (uint32_t p = 0; p < kAP; ++p) { - const uint32_t r = am + p * kRPP; - if (r < FM) - pa[p] = stage8_load(asrc + (size_t)p * kRPP * a_ld + c1, - live && (Full || (m0 + r) < rows)); - } #pragma unroll for (uint32_t p = 0; p < kAF; ++p) { const uint32_t st = c1 / r4d_fp8::kSuperK + p; @@ -415,64 +310,34 @@ void gemm_fp8a8_kernel( } } - /* fp8 prefill tile: the fold's activation scales (eight per lane) are read at the top of a - * staged tile that ends in a fold, so its WMMA hide them. At FK <= kBlock the fold fires - * only at a tile's last step, so that tile is known here. */ - constexpr bool kAsAhead = !AW && !I8 && FK <= kBlock; - [[maybe_unused]] float asn[kAsAhead ? MT : 1][8]; - if constexpr (kAsAhead) { - if ((c0 + FK) % kBlock == 0 || c0 + FK >= kend) { - const uint32_t kb = (c0 + FK - 1) / kBlock; -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t); - asn[i][t] = (Full || r < rows) ? ((const float*)Sa)[(size_t)r * sa_ld + kb] - : 0.0f; - } - } - } #pragma unroll for (uint32_t ks = 0; ks < FK; ks += kK) { - i2v af[MT], bf[NT]; - // When A is the weight it comes from registers: the 32 bytes this lane loaded for the - // 64-k supertile are its four fragments (+0, +8, +16, +24). `ks` is constant after - // unrolling, so the selection folds away. - if (AW) { - af[0] = frag_of(pf[ks / r4d_fp8::kSuperK], (ks % r4d_fp8::kSuperK) / 16u); - } else { + // A comes from registers: the 32 bytes this lane loaded for the 64-k supertile are its + // four fragments (+0, +8, +16, +24). `ks` is constant after unrolling, so the selection + // folds away. + const i2v af = frag_of(pf[ks / r4d_fp8::kSuperK], (ks % r4d_fp8::kSuperK) / 16u); + i2v bf[NT]; #pragma unroll - for (uint32_t i = 0; i < MT; ++i) - af[i] = frag(s_a[buf], wm + i * 16, ks, lane); - } + for (uint32_t j = 0; j < NT; ++j) bf[j] = frag(s_b, wn + j * 16, ks, lane); #pragma unroll - for (uint32_t j = 0; j < NT; ++j) bf[j] = frag(s_b[buf], wn + j * 16, ks, lane); -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) raw[i][j] = mma8(af[i], bf[j], raw[i][j]); + for (uint32_t j = 0; j < NT; ++j) raw[j] = mma8(af, bf[j], raw[j]); // End of a 128-column scale block: fold both scales in and reset. Inside the ks loop // because at FK = 256 one staged tile spans two scale blocks. // - // `c0` is a runtime value, so the compiler if-converts this test at every unrolled ks - // (libr4d/isa/loop.sh: ~150 of ~190 instructions per eight WMMA on the prefill tile). - // Gating it at the compile-time-known positions is legal and byte-identical, cuts the - // loop from 847 to 310 instructions, but raises the kernel from 203 to 253 VGPRs and is - // ~16% slower on the prefill tile (narrow tiles unchanged). The fold's register live - // range, not the instruction count, is the cost; see libr4d/isa/README.md. + // `c0` is a runtime value, so the compiler if-converts this test at every unrolled ks. + // Gating it at the compile-time-known positions is legal and byte-identical but raises + // the register live range of the fold; see libr4d/isa/README.md. if ((c0 + ks + kK) % kBlock == 0 || c0 + ks + kK >= kend) { const uint32_t kb = (c0 + ks) / kBlock; - if (AW && I8) { + if constexpr (I8) { // A is the int8 weight with a bf16 scale per row. A lane's eight accumulator // slots are eight consecutive rows of one 16-row tile, adjacent in the // tile-major [N/16][K/128][16] plane: one 16-byte load. B is the activation. const uint32_t nkb8 = (cols + kBlock - 1) / kBlock; - float wsr[MT][8]; -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) { - const uint32_t tr = wrow0 / 16u + i; + float wsr[8]; + { + const uint32_t tr = wrow0 / 16u; uint4 w8 = make_uint4(0u, 0u, 0u, 0u); if (Full || tr * 16u < rows) w8 = *(const uint4*)((const uint16_t*)Sa + @@ -480,57 +345,23 @@ void gemm_fp8a8_kernel( const uint32_t d[4] = { w8.x, w8.y, w8.z, w8.w }; #pragma unroll for (uint32_t t = 0; t < 8; ++t) - wsr[i][t] = bscale((uint16_t)(d[t / 2] >> (16 * (t % 2)))); + wsr[t] = bscale((uint16_t)(d[t / 2] >> (16 * (t % 2)))); } #pragma unroll for (uint32_t j = 0; j < NT; ++j) { const uint32_t tok = brow0 + j * 16; const float s = (Full || tok < nb) ? ((const float*)Sb)[(size_t)tok * sb_ld + kb] : 0.0f; -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - out[i][j][t] += acc_val(raw[i][j][t]) * (wsr[i][t] * s); - raw[i][j][t] = 0.0f; - } - } - } else if (I8) { - // B is the int8 weight with a bf16 scale per row; a lane owns one weight row per - // tile (frag_c), so one scale. A is the activation, f32 scale per (token, - // 128 K), eight per lane per tile. - const uint32_t nkb8 = (cols + kBlock - 1) / kBlock; - float wsc[NT]; -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) { - const uint32_t col = n0 + wn + j * 16 + frag_c(lane); - wsc[j] = (Full || col < nb) - ? bscale(((const uint16_t*)Sb)[((size_t)(col / 16u) * nkb8 + kb) - * 16u + col % 16u]) - : 0.0f; - } - float as[MT][8]; -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) #pragma unroll for (uint32_t t = 0; t < 8; ++t) { - const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t); - as[i][t] = (Full || r < rows) - ? ((const float*)Sa)[(size_t)r * sa_ld + kb] : 0.0f; + out[j][t] += acc_val(raw[j][t]) * (wsr[t] * s); + raw[j][t] = 0.0f; } -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - out[i][j][t] += acc_val(raw[i][j][t]) * (as[i][t] * wsc[j]); - raw[i][j][t] = 0.0f; - } - } else if (AW) { - // A is the weight: one bf16 scale for this wave's MT*16 rows, which sit in one - // scale row (see the static_assert). B is the activation: one f32 scale per - // (token, 128-column block), one per lane per tile. + } + } else { + // A is the weight: one bf16 scale for this wave's 16 rows, which sit in one + // scale row. B is the activation: one f32 scale per (token, 128-column block), + // one per lane per tile. const float ws = bscale(((const uint16_t*)Sa)[(size_t)(wrow0 / kBlock) * sa_ld + kb]); #pragma unroll @@ -539,55 +370,27 @@ void gemm_fp8a8_kernel( const float s = ws * ((Full || tok < nb) ? ((const float*)Sb)[(size_t)tok * sb_ld + kb] : 0.0f); -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - out[i][j][t] += raw[i][j][t] * s; - raw[i][j][t] = 0.0f; - } - } - } else { - // B is the weight: one bf16 scale for the block's B rows. A is the activation: - // one f32 scale per token, eight per lane (acc_row). - const float ws = bscale(((const uint16_t*)Sb)[(size_t)(n0 / kBlock) * sb_ld + kb]); - float as[MT][8]; -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) #pragma unroll for (uint32_t t = 0; t < 8; ++t) { - const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t); - if constexpr (kAsAhead) - as[i][t] = (Full || r < rows) ? ws * asn[i][t] : 0.0f; - else - as[i][t] = (Full || r < rows) - ? ws * ((const float*)Sa)[(size_t)r * sa_ld + kb] - : 0.0f; + out[j][t] += raw[j][t] * s; + raw[j][t] = 0.0f; } -#pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - out[i][j][t] += raw[i][j][t] * as[i][t]; - raw[i][j][t] = 0.0f; - } + } } } } - // Two buffers: the next store lands in the other one. One buffer: wait until every wave has - // finished reading before it is overwritten. The prefetched fragments become current. + // Wait until every wave has finished reading before the tile is overwritten. The + // prefetched fragments become current. #pragma unroll for (uint32_t p = 0; p < kAF; ++p) pf[p] = pfn[p]; - if (kBufs > 1u) buf ^= 1u; else __syncthreads(); + __syncthreads(); } if constexpr (GATED) { constexpr uint32_t kStash = kGHalf * kWave * NT * 8u; // bf16 gate values static_assert(kStash * 2u <= FN * lds_pitch(), "the gate stash must fit in the staging buffer it reuses"); - uint16_t* const gst = (uint16_t*)&s_b[0][0]; + uint16_t* const gst = (uint16_t*)&s_b[0]; __shared__ float s_amx[kGHalf][FN]; const uint32_t half = wave / kGHalf, w2 = wave % kGHalf; const uint32_t c = frag_c(lane); @@ -600,7 +403,7 @@ void gemm_fp8a8_kernel( if (!Full && n0 + wn + j * 16u >= nb) continue; #pragma unroll for (uint32_t t = 0; t < 8; ++t) - gst[((w2 * kWave + lane) * NT + j) * 8u + t] = f32_to_bf16(out[0][j][t]); + gst[((w2 * kWave + lane) * NT + j) * 8u + t] = f32_to_bf16(out[j][t]); } } __syncthreads(); @@ -620,7 +423,7 @@ void gemm_fp8a8_kernel( const float g = bf16_to_f32(gst[((w2 * kWave + lane) * NT + j) * 8u + t]); const float a = g / (1.0f + expf(-g)); const uint16_t h = - f32_to_bf16(a * bf16_to_f32(f32_to_bf16(out[0][j][t]))); + f32_to_bf16(a * bf16_to_f32(f32_to_bf16(out[j][t]))); v[j][t] = bf16_to_f32(h); m = fmaxf(m, fabsf(v[j][t])); } @@ -682,11 +485,14 @@ void gemm_fp8a8_kernel( const uint32_t c = frag_c(lane); /* ---- eight consecutive elements in one store --------------------------------------------- * - * `acc_row(lane, t)` is `(lane>>4)*8 + t`, so with AW (output index `col * rows + r`) a lane's + * `acc_row(lane, t)` is `(lane>>4)*8 + t`, so with the output index `col * rows + r` a lane's * eight slots are eight consecutive addresses in one 16-byte piece; one store instead of eight - * removes the epilogue's M-proportional cost. Bit-identical. Requires AW (otherwise the eight - * are `nb` apart) and `rows` % 8 == 0 for 16-byte alignment (`r` is already a multiple of 8). */ - const bool vec8 = AW && (rows & 7u) == 0u; + * removes the epilogue's M-proportional cost. Bit-identical. Requires `rows` % 8 == 0 for + * 16-byte alignment (`r` is already a multiple of 8). */ + const bool vec8 = BIAS ? (c_ld & 7u) == 0u && ((uintptr_t)Y & 15u) == 0u : (rows & 7u) == 0u; + /* C's row pitch: N, or the caller's with BIAS. The split-K partial plane (never with BIAS) + * stays dense at N. */ + const uint32_t cld = BIAS ? c_ld : rows; /* The split-K and vec8 tests are hoisted out of the store loop as template arguments; * otherwise the compiler keeps a compare and branch at every store and assembles the vec8 * words from register halves. */ @@ -694,40 +500,46 @@ void gemm_fp8a8_kernel( constexpr bool CK = decltype(split)::value; constexpr bool V8 = decltype(v8)::value; #pragma unroll - for (uint32_t i = 0; i < MT; ++i) -#pragma unroll - for (uint32_t j = 0; j < NT; ++j) { - const uint32_t col = n0 + wn + j * 16 + c; - if (!Full && col >= nb) continue; - const uint32_t rb = m0 + wm + i * 16; - const uint32_t r0 = rb + acc_row(lane, 0); - if (V8 && (Full || r0 + 8u <= rows)) { - const size_t o = (size_t)col * rows + r0; - if constexpr (CK) { - __attribute__((aligned(16))) float pv[8]; -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) pv[t] = out[i][j][t]; - *(uint4*)(part + o) = *(const uint4*)pv; - *(uint4*)(part + o + 4) = *(const uint4*)(pv + 4); - } else { - /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits); a - * uint16_t[8] would be assembled from register halves. */ - const f8v& ov = out[i][j]; - *(uint4*)(c16 + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]), - bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7])); - } - continue; - } + for (uint32_t j = 0; j < NT; ++j) { + const uint32_t col = n0 + wn + j * 16 + c; + if (!Full && col >= nb) continue; + const uint32_t rb = m0 + wm; + const uint32_t r0 = rb + acc_row(lane, 0); + /* The bias of each of this lane's eight weight rows (zero past N). */ + f8v ov = out[j]; + if constexpr (BIAS) { #pragma unroll for (uint32_t t = 0; t < 8; ++t) { - const uint32_t r = rb + acc_row(lane, t); - if (!Full && r >= rows) continue; - // AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. - const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col; - if constexpr (CK) part[o] = out[i][j][t]; - else c16[o] = f32_to_bf16(out[i][j][t]); + const uint32_t r = r0 + t; + ov[t] += (Full || r < rows) ? bf16_to_f32(Bias[r]) : 0.0f; } } + if (V8 && (Full || r0 + 8u <= rows)) { + const size_t o = (size_t)col * cld + r0; + if constexpr (CK) { + __attribute__((aligned(16))) float pv[8]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) pv[t] = ov[t]; + *(uint4*)(part + o) = *(const uint4*)pv; + *(uint4*)(part + o + 4) = *(const uint4*)(pv + 4); + } else { + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits); a + * uint16_t[8] would be assembled from register halves. */ + *(uint4*)(c16 + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]), + bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7])); + } + continue; + } +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + const uint32_t r = rb + acc_row(lane, t); + if (!Full && r >= rows) continue; + // A held the weight, so [r][col] is [N][M] and C is [M][N]. + const size_t o = (size_t)col * cld + r; + if constexpr (CK) part[o] = ov[t]; + else c16[o] = f32_to_bf16(ov[t]); + } + } }; if (vec8) { if (ck) store(std::true_type{}, std::true_type{}); @@ -770,7 +582,7 @@ void gemm_fp8a8_kernel( uint16_t* const cy = (uint16_t*)C; for (uint32_t idx = tid; idx < (rhi - rlo) * nb; idx += MW * kWave) { const uint32_t r = rlo + idx / nb, col = idx % nb; - const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col; + const size_t o = (size_t)col * rows + r; float acc = 0.0f; for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[(size_t)z * rows * nb + o]; cy[o] = f32_to_bf16(acc); @@ -801,6 +613,192 @@ __global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __r y[i] = f32_to_bf16(acc); } +// ---- the prefill tile --------------------------------------------------------------------------- +// +// 128 weight rows x 128 activation rows a block, eight waves as kPWW (weight) x kPWA (activation), +// a wave kPTW weight tiles x kPTA activation tiles. The weight is the WMMA A operand, read from the +// fragment-order plane straight into registers: a lane's 32 bytes are its four fragments for 64 k, +// so a wave's load is one contiguous KiB and the weight never touches LDS. The activation is the B +// operand, staged through LDS and read by the four waves that share its rows. A lane's accumulator +// is eight consecutive weight rows of one activation row, so the fold takes one activation scale a +// lane a tile (and the block's one weight scale), and the store is one 16-byte write. +// +// What decides the layout is LDS bandwidth. gfx1201 serves 64 bytes of LDS a clock per CU, loads +// and stores alike, and issues an fp8 WMMA every 8 clocks per SIMD, so a CU has 256 bytes of LDS +// per WMMA at the WMMA rate (libr4d/isa/wmmamix.hip). Staging both operands with one activation +// tile x eight weight tiles a wave moves 288 bytes of fragment reads and 64 of stores per WMMA, +// which alone caps a loop at ~73% of the WMMA rate (measured with nothing else in it). This layout +// reads 128 bytes and stores 32 per WMMA, and the weight's 64 bytes come through the vector cache. +// +// At the 300 W limit every GEMM shape here is power-bound (sclk 2.1-2.3 GHz against 2.55 for bare +// WMMA on random operands), so a variant's speed tracks the bytes it moves as much as the +// instructions it issues. Measured against the both-operands-through-LDS 1x8 tile at the DiT's +// shapes (M 18648) and LLM prefill shapes (M 300-4096), 160 TFLOP/s at gate_up: +// - this layout with the per-row activation scales gathered from global, mul + add fold: +12%; +// - the activation scales staged through LDS (`s_as`), one row a thread: +4%. A lane's gather +// touched sixteen cachelines a load, more bytes than its weight fragments; +// - the fold as one fma instead of a rounded multiply and an add: +4-5%. Not bit-identical to +// the separate multiply (rel_l2 ~2e-5 against it, both well inside bf16 output); +// - unconditional prefetch (the last tile's prefetch re-reads the last tile, discarded): +1%. +// A conditional load joins two paths with different counts and the compiler waits for zero; +// - the LDS-only barrier (lds_barrier) instead of __syncthreads: +1%; the latter's release waits +// for every outstanding load, the weight prefetch included; +// - kGroupM 8 instead of 16: +1-3%; 4 ties 8. +// Measured and rejected: +// - 2 x 4 waves of 4 weight x 2 activation tiles (half the LDS reads, twice the weight bytes +// through the vector cache): 3-5% slower; +// - 8 x 1 waves (256 x 64 blocks, no weight tile read twice in a block): ties at o and gate_up; +// - the weight two tiles ahead: 240 VGPRs and scratch spills, 25-38% slower; +// - 12 or 16 waves (192 or 256 activation rows a block, up to a quarter less L2 traffic): ties +// to 1% slower, a higher clock at a lower rate per clock; +// - four threads an activation row, 16 bytes each (whole 64-byte segments a load): neutral; +// - raw buffer loads with 32-bit offsets for both operands: 20% slower; +// - s_setprio around the WMMA run: neutral. CU mode (-mcumode): ~10% slower. +template +__global__ __launch_bounds__(kPWaves * kWave) R4D_WAVES(6) +void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restrict__ Sa, + const uint8_t* __restrict__ W, const uint16_t* __restrict__ Sw, + uint16_t* __restrict__ C, uint32_t M, uint32_t K, uint32_t N, + uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld) { + constexpr uint32_t P = lds_pitch(); + static_assert(kPBM * 2u == kPWaves * kWave, "two threads stage an activation row"); + // Double-buffered: one barrier a staged tile, which publishes it. + __shared__ __attribute__((aligned(16))) uint8_t s_a[2][kPBM * P]; + // The activation scales of the current and the next 128-column block, one per block row. + __shared__ float s_as[2][kPBM]; + + const uint32_t tid = threadIdx.x, lane = tid % kWave; + // Uniform per wave, and through readfirstlane known so, so what derives from it stays scalar. + const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave); + const uint32_t ww = wave % kPWW, wa = wave / kPWW; + + // The grid runs in groups of kGroupM activation bands. Blocks dispatch in flattened-id order; + // with the plain x-fastest grid the activation is read once per 128 weight rows, which halves + // the rate once it exceeds the 64 MB MALL. Within a group the bands stay cached across the N + // sweep and the weight is read once per group. With kGroupM bands or fewer the plain order is + // used and the division skipped. + uint32_t bm = blockIdx.x, bn = blockIdx.y; + if (gridDim.x > kGroupM) { + const uint32_t per = kGroupM * gridDim.y; + const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t first = (lin / per) * kGroupM, r = lin % per; + const uint32_t gm = min(gridDim.x - first, kGroupM); + bm = first + r % gm; + bn = r / gm; + } + const uint32_t m0 = bm * kPBM, n0 = bn * kPBN; + const uint32_t ksuper = K / kSuperK, nkb = K / kBlock; + + // Staging: two threads a row, 32 bytes each. Rows past M re-read row M-1, and every load is + // issued unconditionally (the last tile's prefetch re-reads the last tile), so the loop has no + // branch and its waits count exactly; nothing past M is stored. + const uint32_t sr = tid / 2u, sc = (tid % 2u) * 32u; + const uint8_t* const asrc = A + (size_t)min(m0 + sr, M - 1u) * a_ld + sc; + // Thread t loads the scale of block row t % 128; both threads of a row write the same value. + const float* const ssrc = Sa + (size_t)min(m0 + tid % kPBM, M - 1u) * sa_ld; + // This wave's weight tiles, kTileBytes a 64-k supertile, `ksuper` supertiles a tile row. + const uint32_t wt0 = n0 / 16u + ww * kPTW; + const uint8_t* const wsrc = W + (size_t)wt0 * ksuper * kTileBytes + lane * kLaneBytes; + // Activation rows this wave reads from the staged tile, and the lane's column in each. + const uint32_t arow = wa * kPTA * 16u; + + f8v raw[kPTW][kPTA], out[kPTW][kPTA]; +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kPTA; ++j) out[i][j] = acc_zero(); + + Stage8 pa = stage8_load(asrc, true); + Stage8 w0[kPTW], w1[kPTW]; +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) + w0[i] = stage8_load(wsrc + (size_t)i * ksuper * kTileBytes, true); + s_as[0][tid % kPBM] = ssrc[0]; + float scn = ssrc[min(1u, nkb - 1u)]; + + /* One staged K tile, the first or second half of scale block `kb`: publish the activation + * tile (and in the second half the next block's scales), issue the next tile's loads, then four + * k steps from `cur`. The first k step of a block starts from a zero accumulator, so `raw` needs + * no clearing after the fold. */ + auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kPTW], Stage8 (&nxt)[kPTW]) { + stage8_store(s_a[half], sr, sc, pa); + if (half == 1u) s_as[(kb + 1u) % 2u][tid % kPBM] = scn; + lds_barrier(); + const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK); + pa = stage8_load(asrc + c1, true); +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) + nxt[i] = stage8_load(wsrc + ((size_t)i * ksuper + c1 / kSuperK) * kTileBytes, true); + if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)]; +#pragma unroll + for (uint32_t ks = 0; ks < kPFK / kK; ++ks) { + i2v bf[kPTA]; +#pragma unroll + for (uint32_t j = 0; j < kPTA; ++j) bf[j] = frag(s_a[half], arow + j * 16u, ks * kK, lane); +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) { + const i2v af = frag_of(cur[i], ks); +#pragma unroll + for (uint32_t j = 0; j < kPTA; ++j) + raw[i][j] = mma8(af, bf[j], (half == 0u && ks == 0u) ? acc_zero() : raw[i][j]); + } + } + }; + + for (uint32_t kb = 0; kb < nkb; ++kb) { + // The weight's scales for this block, read ahead of the two tiles that hide them: one bf16 + // for the block's 128 rows, or with I8 one per row, a lane's eight rows of a tile adjacent + // in the tile-major [N/16][K/128][16] plane. + float ws = 0.0f; + uint4 w8[I8 ? kPTW : 1u]; + if constexpr (I8) { +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) + w8[i] = *(const uint4*)(Sw + ((size_t)(wt0 + i) * nkb + kb) * 16u + (lane >> 4) * 8u); + } else { + ws = bscale(Sw[(size_t)(n0 / kBlock) * sw_ld + kb]); + } + tile(kb, 0u, w0, w1); + tile(kb, 1u, w1, w0); +#pragma unroll + for (uint32_t j = 0; j < kPTA; ++j) { + const float as = s_as[kb % 2u][arow + j * 16u + frag_c(lane)]; +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) { + float s[8]; + if constexpr (I8) { + const uint32_t d[4] = { w8[i].x, w8[i].y, w8[i].z, w8[i].w }; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) + s[t] = as * bscale((uint16_t)(d[t / 2] >> (16 * (t % 2)))); + } else { +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) s[t] = ws * as; + } +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) + out[i][j][t] = __builtin_fmaf(acc_val(raw[i][j][t]), s[t], out[i][j][t]); + } + } + } + + // D is [weight row][activation row]: eight consecutive columns of one C row a lane a tile. +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kPTA; ++j) { + const uint32_t m = m0 + arow + j * 16u + frag_c(lane); + const uint32_t n = n0 + (ww * kPTW + i) * 16u + acc_row(lane, 0); + if (m < M) { + const f8v v = out[i][j]; + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits). */ + *(uint4*)(C + (size_t)m * N + n) = + make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]), + bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7])); + } + } +} + // The narrow tile's K width is kFKNarrow (256 B); 128 B loses at every wave count (see `kTPR`), and // is used only via narrow_fk for a K that 256 does not divide. @@ -843,12 +841,11 @@ unsigned int* split_ctr(RadStream s, const void* out) { // [M, K] activation, so a call moves N*K + M*K*N/(MW*16) bytes; the second term matches the // weight at M = 64 (served from cache, but it is the drop from 586 to 460 GB/s on gate_up). // MW = 8 halves it at the same N/16 waves. The crossover is where NT leaves 1. -// - M > 32 and N >= 2048: MW = 16 (FM = 256, legal because the AW fold reads the weight scale -// per wave). Halves the re-read again; narrower N would leave too few blocks for 32 WGPs. +// - M > 32 and N >= 2048: MW = 16 (FM = 256, legal because the fold reads the weight scale per +// wave). Halves the re-read again; narrower N would leave too few blocks for 32 WGPs. // // Token tiles NT = ceil(M/16), including 3: rounding 33..48 up to a 64-token tile would spend -// three-eighths of the work at M = 40 on padding. NT = 3 (FN = 48) is legal only here, where AW = -// true; the prefill tile requires FN to divide 128. +// three-eighths of the work at M = 40 on padding. // // Neither MW nor NT changes the output bits: `narrow_ksplit` depends on `gx * mw` = N/16 (the rule // requires `n % 128` so that holds), so every element is one wave's accumulation over the same K @@ -904,7 +901,7 @@ uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out) { *ck_out = 0; const uint32_t mw = narrow_mw(N, M); const uint32_t fm = mw * 16u; // the narrow tile is one M tile a wave - const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over N here: AW = true + const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over the weight rows if (K < 512u || gx * mw >= kSplitTarget) return 1; const uint32_t want = (kSplitTarget + gx * mw - 1) / (gx * mw); uint32_t ckw = ((K / want) + kBlock - 1u) / kBlock * kBlock; @@ -1022,18 +1019,19 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, (ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr; #define R4D_F8D(f, mw_, nt_, fk_, i8_) \ - emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel), \ + emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel), \ grid, dim3(mw_ * kWave), \ 0, (const uint8_t*)wq, (const void*)ws, \ (const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \ (uint32_t)N, (uint32_t)K, \ (uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \ (uint32_t)sa_ld, ck, \ - /* The six defaulted parameters, spelled out: r4d_emit passes \ + /* The eight defaulted parameters, spelled out: r4d_emit passes \ * kernelParams as an array, which cannot fill defaults, and asserts the \ * arity. */ \ (uint8_t*)nullptr, (float*)nullptr, (uint16_t*)nullptr, \ - (uint32_t)0, (uint32_t)0, (uint32_t)0) + (uint32_t)0, (uint32_t)0, (uint32_t)0, (const uint16_t*)nullptr, \ + (uint32_t)0) #define R4D_F8D_NT(f, mw_, fk_, i8_) \ do { if (nt == 4u) R4D_F8D(f, mw_, 4u, fk_, i8_); \ else if (nt == 3u) R4D_F8D(f, mw_, 3u, fk_, i8_); \ @@ -1077,6 +1075,62 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, return 0; } +// gemm_nt_q_bias on the narrow tile (see BIAS on the kernel): the same operands plus a bf16 bias +// per weight row, added to the accumulator before its one rounding, and C at row pitch `c_ld` (0 = +// N), so C may be a column slice of a wider buffer. Never split: the split's partial plane and +// finisher carry neither, and the shapes it serves (a modulation projection's thousands of rows) +// fill the card unsplit. The tile, NT and MW rules are the unbiased launch's; Full is not +// instantiated. +extern "C" int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws, long bias, + long c, int M, int K, int N, int a_ld, int sa_ld, + int w_ld, int sw_ld, int c_ld, long stream) { + int emit_rc = RAD_OK; + if (!a || !ascale || !wq || !ws || !bias || !c) return -1; + if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return -2; + if (K % 128) return -4; + if (N % 16) return -5; + if (!a_ld) a_ld = K; + if (!w_ld) w_ld = K; + if (!c_ld) c_ld = N; + if (c_ld < N) return -5; + const int nkb = (K + (int)kBlock - 1) / (int)kBlock; + if (!sa_ld) sa_ld = nkb; + if (!sw_ld) sw_ld = nkb; + + const uint32_t mw = narrow_mw((uint32_t)N, (uint32_t)M); + const uint32_t fm = mw * 16u; + const dim3 grid(((uint32_t)N + fm - 1) / fm, 1, 1); + uint32_t nt = (M > 48) ? 4u : ((M > 32) ? 3u : ((M > 16) ? 2u : 1u)); + if (const uint32_t f = g_nt_force.load(std::memory_order_relaxed)) { if ((uint32_t)M <= f * 16u) nt = f; } + const RadStream s = (RadStream)(uintptr_t)stream; +#define R4D_F8B(mw_, nt_, fk_) \ + emit_rc = R4D_EMIT(s, (gemm_fp8a8_kernel), \ + grid, dim3(mw_ * kWave), 0, (const uint8_t*)wq, (const void*)ws, \ + (const uint8_t*)a, (const void*)ascale, (void*)c, (void*)c, \ + (unsigned int*)nullptr, (uint32_t)N, (uint32_t)K, (uint32_t)M, \ + (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, (uint32_t)sa_ld, 0u, \ + (uint8_t*)nullptr, (float*)nullptr, (uint16_t*)nullptr, (uint32_t)0, \ + (uint32_t)0, (uint32_t)0, (const uint16_t*)bias, (uint32_t)c_ld) +#define R4D_F8B_NT(mw_, fk_) \ + do { if (nt == 4u) R4D_F8B(mw_, 4u, fk_); \ + else if (nt == 3u) R4D_F8B(mw_, 3u, fk_); \ + else if (nt == 2u) R4D_F8B(mw_, 2u, fk_); \ + else R4D_F8B(mw_, 1u, fk_); } while (0) +#define R4D_F8B_MW(fk_) \ + do { if (mw == 4u) R4D_F8B_NT(4u, fk_); \ + else if (mw == 8u) R4D_F8B_NT(8u, fk_); \ + else R4D_F8B_NT(16u, fk_); } while (0) + /* Only the selftest's pin reaches MW 1 or 2, which the bias form does not build. */ + if (mw != 4u && mw != 8u && mw != 16u) return -4; + if (narrow_fk((uint32_t)K) == kFKNarrow) R4D_F8B_MW(kFKNarrow); + else R4D_F8B_MW(128u); +#undef R4D_F8B_MW +#undef R4D_F8B_NT +#undef R4D_F8B + if (emit_rc != RAD_OK || hipGetLastError() != hipSuccess) return -6; + return 0; +} + // The same GEMM with gated_quant_fp8's pass folded into its epilogue (see `GATED` on the kernel). // Every unmet shape condition is a refusal: a gated call running ungated would write the wrong // buffer. @@ -1125,7 +1179,7 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws const dim3 grid((uint32_t)(nout / 128), 1, 1); #define R4D_F8G_NT(f, nt_) \ - hipLaunchKernelGGL((gemm_fp8a8_kernel), grid, \ + hipLaunchKernelGGL((gemm_fp8a8_kernel), grid, \ dim3(kGmw * kWave), \ 0, (hipStream_t)stream, (const uint8_t*)wq, (const void*)ws, \ (const uint8_t*)a, (const void*)ascale, nullptr, nullptr, nullptr, \ @@ -1144,9 +1198,9 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws return hipGetLastError() == hipSuccess ? 0 : -6; } -// The same GEMM for prefill row counts: same operands and layouts, but a 128x128 tile with the -// activation on A, so the store is coalesced. No split-K: the grid is ceil(M/128) x ceil(N/128), -// hundreds of blocks at any prefill shape. +// The same GEMM for prefill row counts: same operands and layouts, the 128x128 prefill tile +// (gemm_8a8_prefill_kernel). No split-K: the grid is ceil(M/128) x N/128, hundreds of blocks at any +// prefill shape. template static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream); @@ -1177,32 +1231,25 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int a_ld, int sa_ld, int w_ld, int sw_ld, long stream) { if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; - // Required: the fold assumes whole 128-column scale blocks, and the AW=false branch reads the - // weight's scale as one scalar for 128 B rows. + // Required: the fold assumes whole 128-column scale blocks, and a block's 128 weight rows are + // one scale row. if (K % (int)kBlock) return -4; - if (N % (int)kBlock) return -5; + if (N % (int)kPBN) return -5; + // C is written 16 bytes at a time. + if ((uintptr_t)c & 15u) return -3; if (!a_ld) a_ld = K; - if (!w_ld) w_ld = K; + (void)w_ld; // the fragment-order plane has no row pitch const int nkb = (K + (int)kBlock - 1) / (int)kBlock; if (!sa_ld) sa_ld = nkb; if (!sw_ld) sw_ld = nkb; - constexpr uint32_t FM = kFWaves * kFMTiles * 16; - const dim3 grid(((uint32_t)M + FM - 1) / FM, ((uint32_t)N + kFN - 1) / kFN, 1); - const bool full = ((uint32_t)M % FM == 0); // N % 128 and K % 128 are already required - if (full) - hipLaunchKernelGGL((gemm_fp8a8_kernel), grid, - dim3(kFWaves * kWave), 0, (hipStream_t)stream, (const uint8_t*)a, - (const void*)ascale, (const uint8_t*)wq, (const void*)ws, (void*)c, (void*)c, nullptr, - (uint32_t)M, (uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)w_ld, - (uint32_t)sa_ld, (uint32_t)sw_ld, 0u); - else - hipLaunchKernelGGL((gemm_fp8a8_kernel), grid, - dim3(kFWaves * kWave), 0, (hipStream_t)stream, (const uint8_t*)a, - (const void*)ascale, (const uint8_t*)wq, (const void*)ws, (void*)c, (void*)c, nullptr, - (uint32_t)M, (uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)w_ld, - (uint32_t)sa_ld, (uint32_t)sw_ld, 0u); - return hipGetLastError() == hipSuccess ? 0 : -6; + const dim3 grid(((uint32_t)M + kPBM - 1) / kPBM, (uint32_t)N / kPBN, 1); + const int rc = R4D_EMIT((RadStream)(uintptr_t)stream, gemm_8a8_prefill_kernel, grid, + dim3(kPWaves * kWave), 0, (const uint8_t*)a, (const float*)ascale, + (const uint8_t*)wq, (const uint16_t*)ws, (uint16_t*)c, (uint32_t)M, + (uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)sa_ld, + (uint32_t)sw_ld); + return rc == RAD_OK && hipGetLastError() == hipSuccess ? 0 : -6; } // ============================================================== the plugin ABI entry points @@ -1230,6 +1277,46 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { return e == 0 ? RAD_OK : RAD_E_SHAPE; } +/* gemm_nt_q_bias's shim: gemm_nt_q's four operands, then the bias and C (oGemmNtQBias in + * r4d_rows.cpp). Not fp8_ops: C is operand 5 and may be a column slice of a wider buffer, which + * fp8_ops refuses for the unbiased kernels' dense store. */ +enum { GQB_A = 0, GQB_AS = 1, GQB_B = 2, GQB_BS = 3, GQB_BIAS = 4, GQB_Y = 5 }; + +extern "C" int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, GQB_A); + const RadTensor* xs = r4d_opt(a, GQB_AS); + const RadTensor* w = r4d_opt(a, GQB_B); + const RadTensor* wsc = r4d_opt(a, GQB_BS); + const RadTensor* b = r4d_opt(a, GQB_BIAS); + const RadTensor* y = r4d_opt(a, GQB_Y); + if (!x || !xs || !w || !wsc || !b || !y) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || w->dtype != RAD_F8E4M3 || + wsc->dtype != RAD_BF16 || b->dtype != RAD_BF16 || y->dtype != RAD_BF16) + return R4D_NO(RAD_E_DTYPE); + if (w->rank != 2 || wsc->rank != 2 || y->rank != 2 || xs->rank != 2 || x->rank < 2) + return R4D_NO(RAD_E_SHAPE); + const long long blk = r4d_gemm_fp8a8_block(); + if (blk != R4D_FP8_BLOCK || r4d_geti_or(a, "group", blk) != blk) return R4D_NO(RAD_E_SHAPE); + const long long M = y->shape[0], N = y->shape[1], K = w->shape[1]; + if (M < 1 || N < 1 || K < 1 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE); + if (r4d_geti_or(a, "N", N) != N || r4d_geti_or(a, "K", K) != K) return R4D_NO(RAD_E_SHAPE); + const long long nkb = (K + blk - 1) / blk; + if (w->shape[0] != N || wsc->shape[0] != (N + blk - 1) / blk || wsc->shape[1] != nkb) + return R4D_NO(RAD_E_SHAPE); + if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE); + if (xs->shape[0] != M || xs->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(b) < N || !r4d_contig(b)) return R4D_NO(RAD_E_SHAPE); + const long long ap = r4d_row_pitch(x), asp = r4d_row_pitch(xs); + const long long wp = r4d_row_pitch(w), wsp = r4d_row_pitch(wsc), yp = r4d_row_pitch(y); + if (ap < 0 || asp < 0 || wp < 0 || wsp < 0 || yp < N || y->stride[1] != 1) + return R4D_NO(RAD_E_STRIDE); + if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16)) return R4D_NO(RAD_E_ALIGN); + const int e = r4d_gemm_fp8a8_bias_nt_m16( + r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc), r4d_addr(b), r4d_addr(y), (int)M, + (int)K, (int)N, (int)ap, (int)asp, (int)wp, (int)wsp, (int)yp, (long)(uintptr_t)s); + return e == 0 ? RAD_OK : R4D_NO(e == -6 ? RAD_E_DEVICE : RAD_E_SHAPE); +} + /* The gated GEMM's shim. Not fp8_ops: that derives M and N from operand 4, which here is the * quantiser's [M, nout] output rather than the GEMM's [M, 2*nout]. Operand indices are * `gemm_nt_q_gated`'s (oGemmNtQGated in r4d_rows.cpp). */ diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index c52a86a5..73cbfd21 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -99,9 +99,10 @@ __global__ __launch_bounds__(kT) void ln_mod_kernel( } // ---------------------------------------------------------------------------- gate_add +// `act` 0 gates through bf16(tanh(g)), 1 through g as it is (a gate with no tanh). __global__ __launch_bounds__(kT) void gate_add_kernel( const uint16_t* __restrict__ y, const uint16_t* __restrict__ g, const int* __restrict__ cu, - uint16_t* __restrict__ x, int n, int n_seq, int y_ld, int g_ld, int x_ld) { + uint16_t* __restrict__ x, int n, int n_seq, int y_ld, int g_ld, int x_ld, int act) { const int r = blockIdx.x; const uint16_t* gr = g + (size_t)seq_of(cu, n_seq, r) * g_ld; for (int i = threadIdx.x * 8; i < n; i += kT * 8) { @@ -110,7 +111,7 @@ __global__ __launch_bounds__(kT) void gate_add_kernel( ld8(gr + i, b); ld8(x + (size_t)r * x_ld + i, c); #pragma unroll - for (int j = 0; j < 8; ++j) c[j] = c[j] + bfr(bfr(tanhf(b[j])) * a[j]); + for (int j = 0; j < 8; ++j) c[j] = c[j] + bfr((act ? b[j] : bfr(tanhf(b[j]))) * a[j]); st8(x + (size_t)r * x_ld + i, c); } } @@ -196,8 +197,13 @@ __global__ __launch_bounds__(kT) void ln_mod_quant_kernel( } // ---------------------------------------------------------------------------- timestep_embed +// An output element, bf16 rounded once or f32 as it is. +__device__ __forceinline__ void st1(uint16_t* p, float v) { *p = f32_to_bf16(v); } +__device__ __forceinline__ void st1(float* p, float v) { *p = v; } + +template __global__ __launch_bounds__(kT) void timestep_kernel( - const float* __restrict__ t, uint16_t* __restrict__ y, int h, float scale, float coef, + const float* __restrict__ t, TY* __restrict__ y, int h, float scale, float coef, int round, int y_ld) { const int m = blockIdx.x; const float tv = t[m]; @@ -205,8 +211,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel( for (int i = threadIdx.x; i < h; i += kT) { const float f = expf(coef * (float)i / (float)h); const float arg = tt * f; - y[(size_t)m * y_ld + i] = f32_to_bf16(cosf(arg)); - y[(size_t)m * y_ld + h + i] = f32_to_bf16(sinf(arg)); + st1(y + (size_t)m * y_ld + i, cosf(arg)); + st1(y + (size_t)m * y_ld + h + i, sinf(arg)); } } @@ -268,17 +274,19 @@ __device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) { return (uint64_t)seed[2 * e] | ((uint64_t)seed[2 * e + 1] << 32); } +// `TD` is the lane's element: bf16 latents, or f32 ones the sampler keeps in f32. +template __global__ __launch_bounds__(kT) void randn_lanes_kernel( const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ lane, - const int* __restrict__ cu, uint16_t* __restrict__ dst, int n, int stride, int d_ld) { + const int* __restrict__ cu, TD* __restrict__ dst, int n, int stride, int d_ld) { const int e = blockIdx.y; if (!(flags[e] & 1)) return; const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; const int64_t len = cu[e + 1] - cu[e]; if (i >= len * n) return; const int64_t k = i / n, c = i % n; - dst[((size_t)lane[e] * stride + k) * d_ld + c] = - f32_to_bf16(rad_philox_normal(seed_of(seed, e), (uint64_t)i)); + st1(dst + ((size_t)lane[e] * stride + k) * d_ld + c, + rad_philox_normal(seed_of(seed, e), (uint64_t)i)); } __global__ __launch_bounds__(kT) void flow_euler_kernel( @@ -321,14 +329,27 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel( constexpr int kChanMax = 64; struct ChanLists { float mul[kChanMax], add[kChanMax]; }; +// `T` is x's and y's element, bf16 or f32. With `rnd` the inner product or difference rounds to +// y's dtype (and the lists were rounded to bf16 by the shim); without it the arithmetic stays f32 +// and rounds once into y. +__device__ __forceinline__ float ca_ld(const uint16_t* p, size_t i) { return bf2f(p[i]); } +__device__ __forceinline__ float ca_ld(const float* p, size_t i) { return p[i]; } +__device__ __forceinline__ float ca_rd(const uint16_t*, float v) { return bfr(v); } +__device__ __forceinline__ float ca_rd(const float*, float v) { return v; } +__device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); } +__device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; } + +template __global__ __launch_bounds__(kT) void chan_affine_kernel( - const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int64_t total, int n, int x_ld, - int inv, ChanLists l) { + const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd, + ChanLists l) { const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; if (i >= total) return; const int c = (int)(i % n); - const float v = bf2f(x[(size_t)(i / n) * x_ld + c]); - y[i] = f32_to_bf16(inv ? bfr(v - l.add[c]) / l.mul[c] : bfr(v * l.mul[c]) + l.add[c]); + const float v = ca_ld(x, (size_t)(i / n) * x_ld + c); + const float t = inv ? v - l.add[c] : v * l.mul[c]; + const float r = rnd ? ca_rd(y, t) : t; + ca_st(y, i, inv ? r / l.mul[c] : r + l.add[c]); } // A wave a pixel: the sum of squares over its channels, then the three roundings. @@ -625,18 +646,21 @@ inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W return true; } -// A parameter list of floats, each rounded to bf16 as the reference's bf16 tensor of it. -int parse_bf16_list(const char* s, float* out, int max) { +// A parameter list of floats, each rounded to bf16 as the reference's bf16 tensor of it, or kept +// in f32 with `bf16` false. +int parse_bf16_list(const char* s, float* out, int max, bool bf16 = true) { int n = 0; while (s && *s && n < max) { char* end = nullptr; const double v = std::strtod(s, &end); if (end == s) break; float f = (float)v; - uint32_t u; - std::memcpy(&u, &f, 4); - u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; - std::memcpy(&f, &u, 4); + if (bf16) { + uint32_t u; + std::memcpy(&u, &f, 4); + u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; + std::memcpy(&f, &u, 4); + } out[n++] = f; s = end; } @@ -718,16 +742,23 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) { if (gl < 0 || (gl & 7) || ((uintptr_t)g->data & 15)) return R4D_NO(RAD_E_STRIDE); const long long n_seq = r4d_numel(cu) - 1; if (ry <= 0 || rx < ry || n_seq <= 0 || rg < n_seq) return R4D_NO(RAD_E_SHAPE); + /* The gate's activation: tanh (the default) or none. */ + const char* act = r4d_gets(a, "act"); + const int none = act && !std::strcmp(act, "none"); + if (!none && act && std::strcmp(act, "tanh")) return R4D_NO(RAD_E_INVAL); hipLaunchKernelGGL(gate_add_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, (const uint16_t*)y->data, (const uint16_t*)g->data, (const int*)cu->data, - (uint16_t*)x->data, (int)n, (int)n_seq, (int)yl, (int)gl, (int)xl); + (uint16_t*)x->data, (int)n, (int)n_seq, (int)yl, (int)gl, (int)xl, none); return st_of(hipGetLastError()); } +/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep + * MLP kept in f32). */ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) { const RadTensor *t = r4d_opt(a, 0), *y = r4d_opt(a, 1); if (!t || !y) return R4D_NO(RAD_E_INVAL); - if (t->dtype != RAD_F32 || !r4d_contig(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + if (t->dtype != RAD_F32 || !r4d_contig(t) || (!is_bf16(y) && y->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", 0); if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE); long long ry = 0; @@ -736,10 +767,16 @@ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) { if (ry <= 0 || r4d_numel(t) < ry) return R4D_NO(RAD_E_SHAPE); const float mp = (float)r4d_getf(a, "max_period", 10000.0); const float coef = (float)(-std::log((double)mp)); - hipLaunchKernelGGL(timestep_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, - (const float*)t->data, (uint16_t*)y->data, (int)(n / 2), - (float)r4d_getf(a, "scale", 1000.0), coef, - (int)r4d_geti_or(a, "round", 0), (int)yl); + const float scale = (float)r4d_getf(a, "scale", 1000.0); + const int round = (int)r4d_geti_or(a, "round", 0); + if (y->dtype == RAD_F32) + hipLaunchKernelGGL(timestep_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const float*)t->data, (float*)y->data, (int)(n / 2), + scale, coef, round, (int)yl); + else + hipLaunchKernelGGL(timestep_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const float*)t->data, (uint16_t*)y->data, (int)(n / 2), + scale, coef, round, (int)yl); return st_of(hipGetLastError()); } @@ -817,7 +854,8 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) { const RadTensor *fl = r4d_opt(a, 0), *seed = r4d_opt(a, 1), *lane = r4d_opt(a, 2); const RadTensor *cu = r4d_opt(a, 3), *dst = r4d_opt(a, 4); if (!fl || !seed || !lane || !cu || !dst) return R4D_NO(RAD_E_INVAL); - if (!is_bf16(dst)) return R4D_NO(RAD_E_DTYPE); + /* bf16 lanes (randn_lanes_bf16) or f32 ones (randn_lanes_f32). */ + if (!is_bf16(dst) && dst->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); long long rd = 0; const long long dl = r4d_rows_pitch(dst, n, &rd); @@ -827,10 +865,17 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) { /* One flag and lane an entry, two seed words. A lane's rows (device data) are not checked. */ if (r4d_numel(fl) < n_seq || r4d_numel(lane) < n_seq || r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE); - hipLaunchKernelGGL(randn_lanes_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), - 0, (hipStream_t)s, (const int*)fl->data, (const uint32_t*)seed->data, - (const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, (int)n, - (int)stride, (int)dl); + const dim3 grid(blocks_for(stride * n), (unsigned)n_seq); + if (dst->dtype == RAD_F32) + hipLaunchKernelGGL(randn_lanes_kernel, grid, dim3(kT), 0, (hipStream_t)s, + (const int*)fl->data, (const uint32_t*)seed->data, + (const int*)lane->data, (const int*)cu->data, (float*)dst->data, (int)n, + (int)stride, (int)dl); + else + hipLaunchKernelGGL(randn_lanes_kernel, grid, dim3(kT), 0, (hipStream_t)s, + (const int*)fl->data, (const uint32_t*)seed->data, + (const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, + (int)n, (int)stride, (int)dl); return st_of(hipGetLastError()); } @@ -870,26 +915,36 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +/* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the + * lists and the arithmetic in f32. */ extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) { const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); if (!x || !y) return R4D_NO(RAD_E_INVAL); - if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); - const long long n = r4d_geti_or(a, "n", 0); + const bool f32 = y->dtype == RAD_F32; + if (x->dtype != y->dtype || (!f32 && !is_bf16(y))) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), rnd = r4d_geti_or(a, "round", 1); + if (rnd < 0 || rnd > 1) return R4D_NO(RAD_E_INVAL); long long rx = 0; const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1; if (xl < 0 || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); ChanLists l{}; - if (n <= 0 || n > kChanMax || parse_bf16_list(r4d_gets(a, "mul"), l.mul, kChanMax) != n || - parse_bf16_list(r4d_gets(a, "add"), l.add, kChanMax) != n) + if (n <= 0 || n > kChanMax || + parse_bf16_list(r4d_gets(a, "mul"), l.mul, kChanMax, rnd != 0) != n || + parse_bf16_list(r4d_gets(a, "add"), l.add, kChanMax, rnd != 0) != n) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); const int inv = mode && !std::strcmp(mode, "inv"); if (!inv && mode && std::strcmp(mode, "fma")) return R4D_NO(RAD_E_INVAL); const long long total = r4d_numel(y); if (total <= 0 || total % n || rx * n < total) return R4D_NO(RAD_E_SHAPE); - hipLaunchKernelGGL(chan_affine_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, - (const uint16_t*)x->data, (uint16_t*)y->data, (int64_t)total, (int)n, - (int)xl, inv, l); + if (f32) + hipLaunchKernelGGL(chan_affine_kernel, dim3(blocks_for(total)), dim3(kT), 0, + (hipStream_t)s, (const float*)x->data, (float*)y->data, (int64_t)total, + (int)n, (int)xl, inv, (int)rnd, l); + else + hipLaunchKernelGGL(chan_affine_kernel, dim3(blocks_for(total)), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, + (int64_t)total, (int)n, (int)xl, inv, (int)rnd, l); return st_of(hipGetLastError()); } diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index a0321290..1cc610eb 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -275,8 +275,14 @@ const uint8_t* pdata(const RadTensor& t) { return (const uint8_t*)t.data; } /* The f16 scale of a canonical plane as f32; scale_zero_dword narrows it back exactly. */ float f16_at(const RadTensor& t, long long i) { return f16_to_f32(((const uint16_t*)t.data)[i]); } -/* An integer zero point from a u4 or u8 plane. */ -int zero_at(const RadTensor& t, long long i) { return (int)rad_load_f32(t.data, t.dtype, i); } +/* Zero point `gi` of row `n` of a [N, nsz] u4 or u8 plane. Rows start on a byte (rad_encoding.h), + * so a u4 row of an odd number of groups ends in a pad nibble and the next row starts after it. */ +uint8_t* zero_row(const RadTensor& t, long long n, long long nsz) { + return (uint8_t*)t.data + n * rad_enc_row_bytes(t.dtype, nsz); +} +int zero_at(const RadTensor& t, long long n, long long nsz, long long gi) { + return (int)rad_load_f32(zero_row(t, n, nsz), t.dtype, gi); +} /* The dense w4/w8/w2 families' scale operand: (scale) for a symmetric grid, (scale, zero) for an * asymmetric one, tile-major [N/16][(K/group)*16] in dwords or, for w8a8, halves. */ @@ -298,7 +304,7 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) { for (long long r = 0; r < R4D_NTILE; ++r) for (long long gi = 0; gi < nsz; ++gi) { const long long n = t * R4D_NTILE + r; - const int z = zfixed >= 0 ? zfixed : zero_at(pl[1], n * nsz + gi); + const int z = zfixed >= 0 ? zfixed : zero_at(pl[1], n, nsz, gi); const float sc = f16_at(pl[0], n * nsz + gi); sz[(t * nsz + gi) * R4D_NTILE + r] = scale_zero_dword(sc, z); } @@ -308,11 +314,12 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) { * reads five bits of the zero out of the scale dword where the f16 kernel reads the whole value, * so a larger zero would make the two disagree. */ bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) { - const long long nz = g.N * (g.K / g.group); - for (long long i = 0; i < nz; ++i) { - const int z = zero_at(zp, i); - if (z < 0 || z >= (1 << bits)) return false; - } + const long long nsz = g.K / g.group; + for (long long n = 0; n < g.N; ++n) + for (long long gi = 0; gi < nsz; ++gi) { + const int z = zero_at(zp, n, nsz, gi); + if (z < 0 || z >= (1 << bits)) return false; + } return true; } @@ -326,7 +333,7 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) ((uint16_t*)pl[0].data)[n * nsz + gi] = (uint16_t)(d & 0xFFFFu); if (asym) { const int z = (int)(-f16_to_f32((uint16_t)(d >> 16)) - 1024.0f + 0.5f); - rad_store_code(pl[1].data, pl[1].dtype, n * nsz + gi, z); + rad_store_code(zero_row(pl[1], n, nsz), pl[1].dtype, gi, z); } } } @@ -1282,3 +1289,283 @@ extern "C" int r4d_rad_unrelayout_conv_tap(const RadParam* p, int n_p, int opera d[(o * ci + c) * kk + t] = s[(o * kk + t) * ci + c]; return RAD_OK; } + +/* ---- conv1d and conv_t1d: a vocoder's 1-D weights, reordered so K runs over (tap, channel) with + * the channel innermost, as conv2d_nhwc's (r4d_audio.hip). Operand 1 of both. + * + * conv1d PyTorch's Conv1d [cout][cin][k] stored [cout][k][cin] + * conv_t1d PyTorch's ConvTranspose1d [cin][cout][2s] stored [s][cout][2][cin], phase r's + * taps (r, r + s) one [cout][2 cin] GEMM operand + */ +namespace { +int conv1d_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* k) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + *k = r4d_pgeti_or(p, n_p, "k", 0); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE; + if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cout * *cin * *k) return RAD_E_SHAPE; + return RAD_OK; +} +/* The transposed convolution's kernel is `k` = 2 stride (the default) or stride: `taps` = k / + * stride input rows feed each output row. */ +int convt_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* s, long long* taps) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + *s = r4d_pgeti_or(p, n_p, "stride", 0); + const long long k = r4d_pgeti_or(p, n_p, "k", 2 * *s); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *s <= 0 || (k != *s && k != 2 * *s)) + return RAD_E_SHAPE; + *taps = k / *s; + if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cin * *cout * k) + return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_conv1d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, const RadTensor* pl, + int n, RadLayout* out) { + (void)sel; + if (!out) return RAD_E_INVAL; + if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED; + if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE; + long long co, ci, k; + const int rc = conv1d_geom(p, n_p, pl, n, &co, &ci, &k); + if (rc != RAD_OK) return rc; + fill(out, "r4d.conv1d.tap_major", RAD_BF16, co, k * ci, co * k * ci * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_conv1d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = r4d_rad_layout_conv1d_tap(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, k; + conv1d_geom(p, n_p, pl, n, &co, &ci, &k); + const uint16_t* s = (const uint16_t*)pl[0].data; + uint16_t* d = (uint16_t*)dst; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < k; ++t) d[(o * k + t) * ci + c] = s[(o * ci + c) * k + t]; + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_conv1d_tap(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = r4d_rad_layout_conv1d_tap(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, k; + conv1d_geom(p, n_p, pl, n, &co, &ci, &k); + const uint16_t* s = (const uint16_t*)src; + uint16_t* d = (uint16_t*)pl[0].data; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < k; ++t) d[(o * ci + c) * k + t] = s[(o * k + t) * ci + c]; + return RAD_OK; +} + +extern "C" int r4d_rad_layout_convt_phase(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + (void)sel; + if (!out) return RAD_E_INVAL; + if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED; + if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE; + long long co, ci, st, tp; + const int rc = convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp); + if (rc != RAD_OK) return rc; + fill(out, "r4d.convt1d.phase_major", RAD_BF16, st * co, tp * ci, st * co * tp * ci * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_convt_phase(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = r4d_rad_layout_convt_phase(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, st, tp; + convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp); + const uint16_t* s = (const uint16_t*)pl[0].data; + uint16_t* d = (uint16_t*)dst; + const long long K = tp * st; + for (long long r = 0; r < st; ++r) + for (long long o = 0; o < co; ++o) + for (long long t = 0; t < tp; ++t) + for (long long c = 0; c < ci; ++c) + d[((r * co + o) * tp + t) * ci + c] = s[(c * co + o) * K + r + t * st]; + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_convt_phase(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = r4d_rad_layout_convt_phase(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, st, tp; + convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp); + const uint16_t* s = (const uint16_t*)src; + uint16_t* d = (uint16_t*)pl[0].data; + const long long K = tp * st; + for (long long r = 0; r < st; ++r) + for (long long o = 0; o < co; ++o) + for (long long t = 0; t < tp; ++t) + for (long long c = 0; c < ci; ++c) + d[(c * co + o) * K + r + t * st] = s[((r * co + o) * tp + t) * ci + c]; + return RAD_OK; +} + +/* ---- the f32 rows of conv1d and conv_t1d (r4d_audio.hip's f32 implicit GEMMs), a vocoder kept + * in f32 throughout: + * + * conv1d PyTorch's Conv1d [cout][cin][k] stored [cout][k][cin], as bf16's + * conv_t1d PyTorch's ConvTranspose1d [cin][cout][k] stored [s][cout][taps][cin], + * taps = ceil(k / s): phase r's taps r, r + s, .. below k, the rest zeros, so any + * k of at least a stride is one [cout][taps cin] GEMM operand a phase + */ +namespace { +int conv1d_geom_f32(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* k) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + *k = r4d_pgeti_or(p, n_p, "k", 0); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE; + if (pl[0].dtype != RAD_F32 || rad_tensor_numel(&pl[0]) != *cout * *cin * *k) return RAD_E_SHAPE; + return RAD_OK; +} +int convt_geom_f32(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout, + long long* cin, long long* s, long long* k, long long* taps) { + *cout = r4d_pgeti_or(p, n_p, "cout", 0); + *cin = r4d_pgeti_or(p, n_p, "cin", 0); + *s = r4d_pgeti_or(p, n_p, "stride", 0); + *k = r4d_pgeti_or(p, n_p, "k", 2 * *s); + if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *s <= 0 || *k < *s) return RAD_E_SHAPE; + *taps = (*k + *s - 1) / *s; + if (pl[0].dtype != RAD_F32 || rad_tensor_numel(&pl[0]) != *cin * *cout * *k) + return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_conv1d_tap_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + (void)sel; + if (!out) return RAD_E_INVAL; + if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED; + if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE; + long long co, ci, k; + const int rc = conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k); + if (rc != RAD_OK) return rc; + fill(out, "r4d.conv1d.tap_major.f32", RAD_F32, co, k * ci, co * k * ci * 4); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_conv1d_tap_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = r4d_rad_layout_conv1d_tap_f32(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, k; + conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k); + const float* s = (const float*)pl[0].data; + float* d = (float*)dst; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < k; ++t) d[(o * k + t) * ci + c] = s[(o * ci + c) * k + t]; + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_conv1d_tap_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = r4d_rad_layout_conv1d_tap_f32(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, k; + conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k); + const float* s = (const float*)src; + float* d = (float*)pl[0].data; + for (long long o = 0; o < co; ++o) + for (long long c = 0; c < ci; ++c) + for (long long t = 0; t < k; ++t) d[(o * ci + c) * k + t] = s[(o * k + t) * ci + c]; + return RAD_OK; +} + +extern "C" int r4d_rad_layout_convt_phase_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + (void)sel; + if (!out) return RAD_E_INVAL; + if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED; + if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE; + long long co, ci, st, k, tp; + const int rc = convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp); + if (rc != RAD_OK) return rc; + fill(out, "r4d.convt1d.phase_major.f32", RAD_F32, st * co, tp * ci, st * co * tp * ci * 4); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_convt_phase_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + const int rc = r4d_rad_layout_convt_phase_f32(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, st, k, tp; + convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp); + const float* s = (const float*)pl[0].data; + float* d = (float*)dst; + for (long long r = 0; r < st; ++r) + for (long long o = 0; o < co; ++o) + for (long long t = 0; t < tp; ++t) + for (long long c = 0; c < ci; ++c) { + const long long tap = r + t * st; + d[((r * co + o) * tp + t) * ci + c] = tap < k ? s[(c * co + o) * k + tap] : 0.0f; + } + return RAD_OK; +} + +extern "C" int r4d_rad_unrelayout_convt_phase_f32(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const void* src, int64_t src_bytes, + const RadTensor* pl, int n) { + RadLayout L; + const int rc = r4d_rad_layout_convt_phase_f32(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE; + long long co, ci, st, k, tp; + convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp); + const float* s = (const float*)src; + float* d = (float*)pl[0].data; + for (long long r = 0; r < st; ++r) + for (long long o = 0; o < co; ++o) + for (long long t = 0; t < tp; ++t) + for (long long c = 0; c < ci; ++c) { + const long long tap = r + t * st; + if (tap < k) d[(c * co + o) * k + tap] = s[((r * co + o) * tp + t) * ci + c]; + } + return RAD_OK; +} diff --git a/libr4d/r4d_lora_bf16.hip b/libr4d/r4d_lora_bf16.hip index 802156b4..bce778f2 100644 --- a/libr4d/r4d_lora_bf16.hip +++ b/libr4d/r4d_lora_bf16.hip @@ -5,62 +5,45 @@ * * The core issues the pair right after a targeted trunk GEMM, in the GEMM's own row slice, with * `a`/`a_scale` the GEMM's activation operands and `y` its output (docs/OPS.md). A row whose slot - * is outside [0, S) is a BASE row and both kernels leave it before touching anything: shrink - * writes no `t`, expand neither reads nor writes `y` -- `y + 0` would already turn a -0 into +0, - * and the engine's promise is that a base row is bit for bit what the GEMM wrote. + * is outside [0, S) is a base row and both kernels leave it before touching anything: shrink + * writes no `t`, expand neither reads nor writes `y` (`y + 0` would turn -0 into +0), so a base + * row stays bit for bit what the GEMM wrote. * - * V1, SCALAR f32 AND CORRECT FIRST. The adapter term is a rank-R correction (R <= 64 a module) - * next to an N x K GEMM, so it is small whatever it costs per FLOP; the WMMA form -- a 16-row tile - * per distinct slot, other slots' rows masked out of the fragment -- is a later speed pass. What - * this form already guarantees, and the later one must keep: + * Invariants every row here keeps: + * - No split that moves with M: a row's arithmetic does not depend on the batch it arrives in, + * so a request alone and the same request in a mixed batch get the same bytes. + * - The grid is M and the declared parameters. Which adapters are active is read on the device + * from `slot` and the pools, so a recorded pass replays the same packets whatever they hold. + * - x(m, k) is gemm_nt_q's activation value: a code times its group's scale (one f32 product), + * or a bf16/f16/f32 element as it stands, the scale stream's grid read as libref's make_scales + * reads it. The decodes below are the ABI's conversions (rad_plugin.h) restated for the device + * bit for bit; gfx1201 has no bf16 convert, so the narrowing is the ABI's RTNE with its + * quiet-NaN rule. Every multiply-add rounds twice (-ffp-contract=off, RadAddPlugin.cmake). * - * * NO SPLIT THAT MOVES WITH M. A row's shrink is one wave per column j, lane l summing the k - * that are l mod 32 in ascending order, then a fixed xor butterfly; expand is one thread per - * (m, n) summing j ascending. Neither depends on the batch a row arrives in, which is what - * lets the engine claim "a request alone == the same request in a mixed batch" for the LoRA - * term. - * * THE GRID IS M AND THE DECLARED PARAMETERS. Which adapters are active is read on the device, - * from `slot` and the pools, so a recorded pass replays the same packets whatever the slots - * hold. - * * NO HOST READS, NO SCRATCH, NO LDS: the reduction is cross-lane only, so a block never waits - * on another wave and a base row leaves before any cross-lane op. + * The scalar rows (lora_shrink_scalar, lora_expand_scalar): shrink is one block a row, one wave a + * column j, lane l summing the k that are l mod 32 in ascending order, then a fixed xor butterfly; + * expand is one thread an (m, n), j ascending, so its bytes are libref's. No scratch and no LDS. They + * serve every dtype, and are the only rows for f16 and f32 activations. * - * x(m, k) IS gemm_nt_q's ACTIVATION VALUE: a code times its group's scale (one f32 product), or a - * bf16/f16/f32 element as it stands, with the scale stream's grid read the way libref's - * make_scales reads it. The decodes below are the ABI's conversions (rad_plugin.h) restated for - * the device, bit for bit, so a code decodes here exactly as it does in the oracle. gfx1201 has no - * bf16 convert; the narrowing is the ABI's RTNE with its quiet-NaN rule. Every multiply-add rounds - * twice (-ffp-contract=off, RadAddPlugin.cmake), so expand computes libref's bytes and shrink - * differs from them only by its summation order. - * - * V2, THE TILED ROWS (lora_shrink_wmma, lora_shrink_wmma_q, lora_expand_tiled), below the v1 - * kernels. v1's grid is a ROW: shrink is one block a row walking K serially, expand one block a - * (row, 256 columns) re-reading all of B[s] for every row, and a chunk of base rows still launches - * M * ceil(N/256) blocks that read a slot and leave. On the card that is a prefill at a third of - * the base speed and base requests 7-8 % slower. The tiled rows keep every promise above and - * change only who computes what: - * - * * THE GRID'S UNIT IS A ROW TILE (16 rows shrink, 32 expand). Every wave reads the tile's slots - * and a ballot decides; a tile of base rows leaves before any barrier or operand load, so a - * base step costs one small block a tile. A tile holding rows of several adapters runs ONE - * PASS PER DISTINCT SLOT, ascending, each pass with its own slot's pools; a row's value comes - * out of its own slot's pass alone and other rows' results are never stored. The passes of a - * tile may be spread over blockIdx.z when the grid is small (decode with several adapters); - * that decides which block runs a pass, never the pass's arithmetic. - * * SHRINK IS WMMA bf16 (16 x 16 x 16), with the pool fragment as the A operand and the x - * fragment as B, so a lane's accumulator is one row. Its order is fixed by K and R alone: K - * in 32-wide steps, a block's run of steps split over its 4 waves (wave w takes every 4th), - * the waves summed 0..3 in LDS, and -- for a K long enough that one tile would leave the card - * idle at decode -- the run split over KS blocks whose f32 partials the LAST to arrive sums - * 0..KS-1 (sh_plan). bf16 activations feed the WMMA as they are; fp8 and i8 codes are exact - * in bf16 and feed it as codes, and each step's partial is scaled by its group's f32 scale, - * which needs the group to be whole steps (a multiple of 32, or one group across K) and is - * otherwise the v1 kernel. Every one of those roundings is a sum or product of the terms the - * contract names, so the result is inside v1's (K + 2) 2^-24 sum|terms| bound; no code times - * scale is ever rounded on its own. f16 and f32 activations have no exact WMMA and stay v1. - * * EXPAND IS v1's ARITHMETIC IN A TILE. B[s]'s [128 columns, 32 j] slab is staged in LDS as f32 - * (exact) and reused by the tile's 32 rows; each output keeps v1's sequence (acc = 0, j - * ascending acc = acc + t*B, d = scale*acc, one rounding into y), so its bytes are libref's. + * The tiled rows (lora_shrink_wmma, lora_shrink_wmma_q, lora_expand_tiled), preferred: + * - The grid's unit is a row tile (16 rows shrink, 32 expand). Every wave reads the tile's slots + * and a ballot decides; a tile of base rows leaves before any barrier or operand load. A tile + * holding rows of several adapters runs one pass per distinct slot, ascending, each with its + * own slot's pools; a row's value comes from its own slot's pass alone. The passes may be + * spread over blockIdx.z when the grid is small, which decides which block runs a pass, never + * its arithmetic. + * - Shrink is WMMA bf16 (16 x 16 x 16) with the pool fragment as the A operand and x as B, so a + * lane's accumulator is one row. Its order is fixed by K and R alone: K in 32-wide steps, a + * block's steps split over its 4 waves (wave w takes every 4th), the waves summed 0..3 in LDS, + * and for a long K the steps split over KS blocks whose f32 partials the last to arrive sums + * 0..KS-1 (sh_plan). fp8 and i8 codes are exact in bf16 and feed the WMMA as codes; each step's + * partial is scaled by its group's f32 scale, which needs the group to be whole steps (a + * multiple of 32, or one group across K). Every rounding is a sum or product of the contract's + * terms, so the result is inside the scalar row's (K + 2) 2^-24 sum|terms| bound. + * - Expand is the scalar arithmetic in a tile: B[s]'s [128 columns, 32 j] slab is staged in LDS + * as f32 (exact) and reused by the tile's 32 rows; each output keeps the scalar sequence (acc = + * 0, j ascending acc = acc + t*B, d = scale*acc, one rounding into y), so its bytes are + * libref's. * * Kernels are written against r4d_launch.h so tests/r4d_emu runs this source on the host. */ @@ -248,7 +231,7 @@ __global__ __launch_bounds__(256) void lora_expand_kernel(ExpandArgs A) { } } -/* ================================================================ v2: the tiled rows */ +/* ================================================================ the tiled rows */ typedef short lr_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the WMMA takes them */ typedef float lr_v8f __attribute__((ext_vector_type(8))); @@ -368,7 +351,7 @@ __device__ __forceinline__ lr_v8f wmma_bf16(lr_v8s a, lr_v8s b, lr_v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); } -/* SHRINK, one block a (j tile x K split, row tile, z), 4 waves. The pool fragment is the WMMA's A +/* Shrink, one block a (j tile x K split, row tile, z), 4 waves. The pool fragment is the WMMA's A * operand (16 j x 16 k) and the x fragment its B (16 k x 16 rows), so lane l's eight outputs are * row l % 16 at j = 8 (l / 16) .. +7: one row, one group scale a lane. A lane holds 16 contiguous * k of its row in both operands, the first 8 in the step's first WMMA and the next 8 in its @@ -464,9 +447,9 @@ __global__ __launch_bounds__(kShThreads) void lora_shrink_wmma_kernel(ShrinkTArg } if (T.ks == 1) return; - /* THE K SPLIT'S SUM, in the last block to arrive. Every thread's partial stores are fenced - * before the arrival, and the counter is left zero for the next launch (they are ordered: the - * lora rows are not concurrent, and each lane's `t` keys its own counter block). */ + /* The K split's sum, in the last block to arrive. Every thread's partial stores are fenced + * before the arrival, and the counter is left zero for the next launch (launches are ordered: + * the lora rows are not concurrent, and each lane's `t` keys its own counter block). */ __threadfence(); __syncthreads(); const int cidx = ((int)blockIdx.y * T.jt + jt) * kZMax + z; @@ -491,10 +474,10 @@ __global__ __launch_bounds__(kShThreads) void lora_shrink_wmma_kernel(ShrinkTArg } } -/* EXPAND, one block a (128 columns, 32 rows, z), 8 waves: wave w owns rows 4w..4w+3 and lane l +/* Expand, one block a (128 columns, 32 rows, z), 8 waves: wave w owns rows 4w..4w+3 and lane l * columns 4l..4l+3, sixteen outputs a thread. B[s]'s slab [128 columns][32 j] is staged as f32 - * (a bf16 widens exactly) and t's [32 rows][32 j] beside it; then every output runs v1's sequence - * over the slab and the next, so the bytes are v1's and libref's. A pass's accumulators start at + * (a bf16 widens exactly) and t's [32 rows][32 j] beside it; every output runs the scalar row's + * sequence over the slab and the next, so the bytes are libref's. A pass's accumulators start at * zero and only its own rows are written back: a row of another slot accumulates against zeros it * never stores. V: B is dense, 16-byte aligned and R a multiple of 8, so 16-byte loads. */ template @@ -667,8 +650,8 @@ static bool dtype_agrees(const RadArgs* a, uint32_t dt) { return !d || rad_dtype_parse(d) == dt; } -/* The launches, one per dtype instantiation: the v1 grid is M blocks for shrink and M strips of - * 256 columns for expand, 256 threads each, whatever the slots hold. */ +/* The scalar rows' launches, one per dtype instantiation: M blocks for shrink and M strips of 256 + * columns for expand, 256 threads each, whatever the slots hold. */ template static void launch_shrink(const ShrinkArgs& P, int64_t blocks, RadStream stream) { (void)stream; /* the host emulator's launch takes none */ @@ -819,12 +802,11 @@ static int shrink_scalar(const ShrinkArgs& P, int adt, int64_t M, RadStream stre /* ---------------------------------------------------------------- the tiled rows' plans (host) */ -/* THE SHRINK SPLIT, from K and R alone -- never M, because it is the summation order. A row tile +/* The shrink split, from K and R alone and never M, because it is the summation order. A row tile * covers ceil(R / 16) j tiles; at decode that tile is the whole grid, so K is split until j tiles * times splits reach kShFill blocks, but never below 16 steps (512 k) a block, past which the - * split's partial traffic and its arrival outweigh what the extra blocks read. The split is then - * rounded so no block is left without a step. MiniCPM5-2B's four sites at TP1, for scale: K 2048 - * R 48 -> 3 x 4 blocks; K 2048 R 32 -> 2 x 4; K 2048 R 16 -> 1 x 4; K 6144 R 16 -> 1 x 12. */ + * partials' traffic and the arrival outweigh what the extra blocks read. The split is rounded so + * no block is left without a step. E.g. K 2048 R 48 -> 3 x 4 blocks; K 6144 R 16 -> 1 x 12. */ struct ShPlan { int jt, ks, spb, nsteps; }; static ShPlan sh_plan(int64_t K, int64_t R) { ShPlan p; @@ -842,11 +824,11 @@ static int64_t sh_part_bytes(int64_t M, int64_t R, const ShPlan& p) { return p.ks > 1 ? (int64_t)p.ks * M * R * (int64_t)sizeof(float) : 0; } -/* HOW MANY BLOCKS ONE TILE'S PASSES SPREAD OVER. Decode with several adapters is a handful of - * blocks a pass, run one after another inside a block they would add up; spread over blockIdx.z - * they run at once. Only while the grid is small -- every z block of a tile that has fewer passes - * leaves after reading the slots, and on a prefill grid those would be thousands -- and never more - * than the passes a tile can have. Which block runs a pass is all this decides. */ +/* How many blocks one tile's passes spread over. Decode with several adapters is a handful of + * blocks a pass; run one after another inside a block they would add up, spread over blockIdx.z + * they run at once. Only while the grid is small (every z block of a tile with fewer passes leaves + * after reading the slots, and a prefill grid would have thousands), and never more than the + * passes a tile can have. Which block runs a pass is all this decides. */ static int z_fan(int64_t base, int64_t S, int64_t M, int64_t tile) { int64_t z = base >= kZGrid ? 1 : kZGrid / base; if (z > S) z = S; @@ -856,12 +838,12 @@ static int z_fan(int64_t base, int64_t S, int64_t M, int64_t tile) { return z < 1 ? 1 : (int)z; } -/* THE SPLIT'S ARRIVAL COUNTERS, one block a (device, `t`). They cannot live in the scratch: other +/* The split's arrival counters, one block a (device, `t`). They cannot live in the scratch: other * ops write the arena between two of ours and the counters must be zero at entry. Each lane's `t` * is its own buffer and the lora rows are ordered on their lane (not concurrent), so two launches - * that could overlap never share a block; the reducer leaves every counter zero. A block too - * small for a launch is replaced by a larger one and the old one is kept -- a recorded pass may - * still name it, and its own launches still fit it. */ + * that could overlap never share a block; the reducer leaves every counter zero. A block too small + * for a launch is replaced by a larger one and the old one is kept, since a recorded pass may + * still name it. */ static unsigned* shrink_ctr(const void* t, int64_t n, RadStream stream) { static std::mutex mu; static std::map, std::pair> blocks; @@ -936,8 +918,8 @@ int r4d_rad_lora_expand(const RadArgs* a, RadStream stream) { } /* The tiled shrink: lora_shrink_wmma (bf16 a) and lora_shrink_wmma_q (fp8 / i8 codes whose group - * is whole 32-wide steps) share this entry point. What the WMMA cannot hold exactly -- f16 and f32 - * activations, a scale group that ends inside a step -- goes to the v1 kernel, decided by the + * is whole 32-wide steps) share this entry point. What the WMMA cannot hold exactly (f16 and f32 + * activations, a scale group that ends inside a step) goes to the scalar kernel, decided by the * dtype and the stream's grid and never by M; the rows' bands do not send either here, and a * direct caller still gets the exact answer. */ int r4d_rad_lora_shrink_wmma(const RadArgs* a, RadStream stream) { @@ -982,7 +964,7 @@ int r4d_rad_lora_shrink_wmma(const RadArgs* a, RadStream stream) { } /* The K split's partials, sized at declare for the band's widest M (the core calls this with it). - * f16 / f32 activations run the v1 kernel and need none. */ + * f16 / f32 activations run the scalar kernel and need none. */ int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs* a) { using namespace r4d_lora; const int64_t M = rad_args_geti_or(a, "M", 0), K = rad_args_geti_or(a, "K", 0); diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 495596c1..2c117ed6 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -29,6 +29,8 @@ #include "rad_yarn.h" #include "r4d_fp8_wmma.h" +#include +#include #include #include @@ -198,22 +200,28 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel( // // Two passes over the row: n is 256 (a QK-norm head) or 5120 (the hidden state), so the row is in // L1 for the second pass, and one-pass Welford would only change the rounding. -template +// +// `TX` is the row's element: bf16, or f32 for a residual stream kept in f32 (a video decoder's), +// read as it is; the output is bf16 either way. +__device__ __forceinline__ float act_f32(uint16_t v) { return bf16_to_f32(v); } +__device__ __forceinline__ float act_f32(float v) { return v; } + +template __global__ __launch_bounds__(THR) void rmsnorm_kernel( - const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, + const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld) { __shared__ float lds[THR / kWave]; const uint32_t m = blockIdx.x; - const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + const TX* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; float ss = 0.0f; - for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf16_to_f32(xr[i]); ss += v * v; } + for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = act_f32(xr[i]); ss += v * v; } ss = block_sum(ss, lds); const float s = rsqrtf(ss / (float)n + eps); for (uint32_t i = threadIdx.x; i < n; i += THR) { const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); - yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult); + yr[i] = f32_to_bf16(act_f32(xr[i]) * s * (g + wadd) * mult); } } @@ -239,17 +247,67 @@ __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel( // ---------------------------------------------------------------------------- add / mul // ref_add / ref_mul with one broadcast rule: an operand of exactly n elements against an output of // rows*n broadcasts along rows; nothing else broadcasts, so shape bugs are not hidden. -// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op. +// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op. `div` (add +// only) divides the sum after its rounding and rounds again, the last step of a mean summed +// pairwise; 1 is the plain sum. __global__ __launch_bounds__(kThreads) void binary_kernel( const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y, - uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step) { + uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step, + float div) { const uint32_t m = blockIdx.x; const uint16_t* __restrict__ ar = a + (size_t)m * a_ld; const uint16_t* __restrict__ br = b + (size_t)m * b_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float u = bf16_to_f32(ar[i]), v = bf16_to_f32(br[i * b_step]); - yr[i] = f32_to_bf16(mul ? u * v : u + v); + float r = mul ? u * v : u + v; + if (div != 1.0f) r = bf16_to_f32(f32_to_bf16(r)) / div; + yr[i] = f32_to_bf16(r); + } +} + +// The f32 form (a video decoder's residual stream, a vocoder's branch mean), with the same +// broadcast rule and `div`. Flat over the M x n extent: a vocoder's last stages are a few channels +// over a million rows, which a workgroup a row would leave mostly idle. `y` may be `a` (an +// in-place residual): each element is read before it is written, by the same thread. +__global__ __launch_bounds__(kThreads) void binary_f32_kernel( + const float* __restrict__ a, const float* __restrict__ b, float* y, uint32_t n, + uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step, float div, + uint64_t total) { + for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total; + t += (uint64_t)gridDim.x * kThreads) { + const uint64_t m = t / n; + const uint32_t i = (uint32_t)(t - m * n); + const float u = a[m * a_ld + i], v = b[m * b_ld + (size_t)i * b_step]; + float r = mul ? u * v : u + v; + if (div != 1.0f) r = r / div; + y[m * y_ld + i] = r; + } +} + +// ref_mul_weight over an f32 weight (a layer scale kept f32): y = x * w, one row of n elements +// broadcast down the rows, or with `w_step` 0 one element for the whole op. +__global__ __launch_bounds__(kThreads) void mul_wf32_kernel( + const uint16_t* __restrict__ x, const float* __restrict__ w, uint16_t* __restrict__ y, + uint32_t n, uint32_t x_ld, uint32_t y_ld, uint32_t w_step) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * w[i * w_step]); +} + +// ref_mul_weight into an f32 output (a layer scale on a branch about to join an f32 residual): +// x bf16 or f32, the weight bf16 or f32, the product rounded once to f32. Flat, as the f32 binary. +template +__global__ __launch_bounds__(kThreads) void mul_weight_f32_kernel( + const TX* __restrict__ x, const TW* __restrict__ w, float* __restrict__ y, uint32_t n, + uint32_t x_ld, uint32_t y_ld, uint32_t w_step, uint64_t total) { + for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total; + t += (uint64_t)gridDim.x * kThreads) { + const uint64_t m = t / n; + const uint32_t i = (uint32_t)(t - m * n); + y[m * y_ld + i] = act_f32(x[m * x_ld + i]) * act_f32(w[(size_t)i * w_step]); } } @@ -400,7 +458,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj, float theta, float rscale, uint32_t row_pitch, - int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) { + int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn, RadLlama3 l3) { const uint32_t m = blockIdx.x; const uint32_t half = rot / 2; const float div = rscale != 0.0f ? rscale : 1.0f; @@ -421,6 +479,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c])); } inv = yarn.frequency(inv, (int)i); + inv = l3.frequency(inv); /* The proportional ladder rotates the whole head with every frequency past nfreq zero * (HF's _compute_proportional_rope_parameters): pair i is (i, i + head_dim/2), and pairs * past nfreq turn by 0 (cos 1, sin 0), returning the value exactly. */ @@ -679,7 +738,7 @@ extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, if (b_ld < 0) b_ld = 0; hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, (uint16_t*)y, (uint32_t)n, - (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step); + (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step, 1.0f); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -799,12 +858,13 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope } // The single launch of rope_kernel. `yarn` with factor 0 is the plain rotary (the YaRN blend -// returns the frequency unchanged and no magnitude is applied). `den` is the ladder width (`rot` +// returns the frequency unchanged and no magnitude is applied), and so is `l3` with factor 0 (Llama +// 3's scaling, after YaRN's, which no caller combines with it). `den` is the ladder width (`rot` // for `rotary`, `head_dim` for `head`); the plain entry passes `rot`. static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec, int plane, RadYarn yarn, long stream, - int nfreq = -1) { + int nfreq = -1, RadLlama3 l3 = RadLlama3{}) { if (!qkv || !pos) return -1; if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2; if (rot <= 0 || rot > head_dim || (rot & 1)) return -3; @@ -818,7 +878,7 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads (uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim, (uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta, rscale, - (uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn); + (uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -1187,16 +1247,39 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) { enum { RN_X = 0, RN_W, RN_Y }; +/* The norm over f32 rows into bf16 (a video decoder's f32 residual stream), at the bf16 form's + * width so the two fold a row's sum of squares alike. */ +static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int n, float eps, + float wadd, float mult, int w_f32, int x_ld, int y_ld, RadStream stream) { + const int thr = r4d_act_threads(M, n); +#define R4D_RNF_T(wf, T) \ + hipLaunchKernelGGL((rmsnorm_kernel), dim3((uint32_t)M), dim3(T), 0, \ + (hipStream_t)stream, x, w, y, (uint32_t)n, eps, wadd, mult, \ + (uint32_t)x_ld, (uint32_t)y_ld) +#define R4D_RNF(wf) \ + do { if (thr == 1024) R4D_RNF_T(wf, 1024); \ + else if (thr == 512) R4D_RNF_T(wf, 512); \ + else R4D_RNF_T(wf, 256); } while (0) + if (w_f32) R4D_RNF(true); + else R4D_RNF(false); +#undef R4D_RNF +#undef R4D_RNF_T + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, RN_X); const RadTensor* w = r4d_opt(a, RN_W); const RadTensor* y = r4d_opt(a, RN_Y); if (!x || !y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(dt_bf16(x)); + /* The row bf16, or f32 (read as it is); the output bf16. */ + if (x->dtype != RAD_BF16 && x->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); R4D_NEED(dt_bf16(y)); + const bool x_f32 = x->dtype == RAD_F32; /* An absent gain is one (Gemma 4's value norm, its multimodal embedder's pre-projection norm). * `wadd` without a gain is refused. */ if (!w) { + if (x_f32) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); if (r4d_getf(a, "wadd", 0.0) != 0.0) return R4D_NO(RAD_E_INVAL); @@ -1226,6 +1309,10 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); + if (x_f32) + return rmsnorm_x_f32((const float*)x->data, w->data, (uint16_t*)y->data, (int)M, (int)n, + eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld, + (int)y_ld, s); return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK @@ -1259,14 +1346,19 @@ extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) { enum { BI_A = 0, BI_B, BI_Y }; +/* Both rows of each op share this: every operand bf16, or (add_f32) every operand f32. */ static int binary(const RadArgs* a, int mul, RadStream s) { const RadTensor* A = r4d_opt(a, BI_A); const RadTensor* B = r4d_opt(a, BI_B); const RadTensor* Y = r4d_opt(a, BI_Y); if (!A || !B || !Y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(dt_bf16(A)); - R4D_NEED(dt_bf16(B)); - R4D_NEED(dt_bf16(Y)); + const bool f32 = Y->dtype == RAD_F32; + const uint32_t dt = f32 ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16; + if (A->dtype != dt || B->dtype != dt || Y->dtype != dt) return R4D_NO(RAD_E_DTYPE); + /* `div` is add's alone (mul's schema has none); 0 and non-finite values are refused, as libref + * refuses them. */ + const double div = mul ? 1.0 : r4d_getf(a, "div", 1.0); + if (!(div != 0.0) || !std::isfinite(div)) return R4D_NO(RAD_E_INVAL); const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); @@ -1289,6 +1381,22 @@ static int binary(const RadArgs* a, int mul, RadStream s) { if (b_ld == 0) return R4D_NO(RAD_E_STRIDE); /* 0 means broadcast; a real pitch cannot be 0 */ } + if (f32) { + const uint64_t total = (uint64_t)M * (uint64_t)n; + const uint64_t blocks = std::min((total + kThreads - 1) / kThreads, 65536u); + hipLaunchKernelGGL(binary_f32_kernel, dim3((uint32_t)blocks), dim3(kThreads), 0, + (hipStream_t)s, (const float*)A->data, (const float*)B->data, + (float*)Y->data, (uint32_t)n, (uint32_t)a_ld, (uint32_t)b_ld, + (uint32_t)y_ld, mul, 1u, (float)div, total); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } + if (div != 1.0) { + hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)s, + (const uint16_t*)A->data, (const uint16_t*)B->data, (uint16_t*)Y->data, + (uint32_t)n, (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, mul, 1u, + (float)div); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } return r4d_binary_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, mul, (int)a_ld, (int)b_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; @@ -1298,15 +1406,19 @@ extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0, extern "C" int r4d_rad_mul(const RadArgs* a, RadStream s) { return binary(a, 1, s); } /* mul_weight: y = x * w, `w` a bf16 weight of one element (pitch -1, a scalar) or one row (pitch - * 0, broadcast down the rows). */ + * 0, broadcast down the rows). The f32 row (mul_weight_f32) writes an f32 `y` from a bf16 or f32 + * `x`; the bf16 row a bf16 `y` from a bf16 `x`. */ extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) { const RadTensor* X = r4d_opt(a, 0); const RadTensor* W = r4d_opt(a, 1); const RadTensor* Y = r4d_opt(a, 2); if (!X || !W || !Y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(dt_bf16(X)); - R4D_NEED(dt_bf16(W)); - R4D_NEED(dt_bf16(Y)); + const bool y_f32 = Y->dtype == RAD_F32; + if (y_f32 ? (X->dtype != RAD_BF16 && X->dtype != RAD_F32) : X->dtype != RAD_BF16) + return R4D_NO(RAD_E_DTYPE); + /* The weight bf16 or f32 (a layer scale a model keeps f32; libref reads either). */ + if (W->dtype != RAD_BF16 && W->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!y_f32 && Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0, Mx = 0; @@ -1318,6 +1430,29 @@ extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) { if (r4d_numel(W) == 1) w_ld = -1; else if (r4d_numel(W) == n && r4d_contig(W)) w_ld = 0; else return R4D_NO(RAD_E_SHAPE); + if (y_f32) { + const uint64_t total = (uint64_t)M * (uint64_t)n; + const dim3 grid((uint32_t)std::min((total + kThreads - 1) / kThreads, 65536u)); + const uint32_t ws = w_ld < 0 ? 0u : 1u; + const bool xf = X->dtype == RAD_F32, wf = W->dtype == RAD_F32; +#define R4D_MWF(TX, TW) \ + hipLaunchKernelGGL((mul_weight_f32_kernel), grid, dim3(kThreads), 0, \ + (hipStream_t)s, (const TX*)X->data, (const TW*)W->data, \ + (float*)Y->data, (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, ws, \ + total) + if (xf && wf) R4D_MWF(float, float); + else if (xf) R4D_MWF(float, uint16_t); + else if (wf) R4D_MWF(uint16_t, float); + else R4D_MWF(uint16_t, uint16_t); +#undef R4D_MWF + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } + if (W->dtype == RAD_F32) { + hipLaunchKernelGGL(mul_wf32_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)s, + (const uint16_t*)X->data, (const float*)W->data, (uint16_t*)Y->data, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, w_ld < 0 ? 0u : 1u); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; + } return r4d_binary_bf16(r4d_addr(X), r4d_addr(W), r4d_addr(Y), (int)M, (int)n, 1, (int)x_ld, (int)w_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; @@ -1546,13 +1681,19 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL); /* No model uses YaRN with the axial vision rotary or a linear position divide. */ if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED); + /* Llama 3's scaling: one-component positions only, and never beside YaRN (libref refuses + * both alike). */ + const RadLlama3 l3 = rad_llama3_args(a); + if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) + return R4D_NO(RAD_E_INVAL); + if (l3.factor != 0.0f && (mc == 4 || multi)) return R4D_NO(RAD_E_UNSUPPORTED); /* The Q and K heads rotate; the trailing V heads do not. */ long long rot_l = rot, nfreq = rot / 2; if (den == head_dim && rot < head_dim && !multi && !gptj && mc == 0) rot_l = head_dim; return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim, (int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale, (int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s, - (int)nfreq) == 0 + (int)nfreq, l3) == 0 ? RAD_OK : RAD_E_DEVICE; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 45fba47c..3d6a36ce 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -135,9 +135,9 @@ int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream); int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream); int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream); int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream); -/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip): the v1 - * scalar rows, and the tiled rows -- WMMA shrink over row tiles with a K split fixed by K and R - * (its partials in the op's scratch), and an expand that stages B[s] in LDS for a tile of rows. */ +/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip): the scalar + * rows, and the tiled rows (a WMMA shrink over row tiles with a K split fixed by K and R, its + * partials in the op's scratch, and an expand that stages B[s] in LDS for a tile of rows). */ int r4d_rad_lora_shrink (const RadArgs*, RadStream); int r4d_rad_lora_expand (const RadArgs*, RadStream); int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream); @@ -170,6 +170,43 @@ int r4d_rad_s2d_avg_add (const RadArgs*, RadStream); int r4d_rad_to_rgba8 (const RadArgs*, RadStream); int r4d_rad_gelu_tanh (const RadArgs*, RadStream); int r4d_rad_scatter_add_rows (const RadArgs*, RadStream); +/* r4d_audio.hip */ +int r4d_rad_conv1d (const RadArgs*, RadStream); +int r4d_rad_conv_t1d (const RadArgs*, RadStream); +int r4d_rad_conv1d_f32 (const RadArgs*, RadStream); +int r4d_rad_conv_t1d_f32 (const RadArgs*, RadStream); +int r4d_rad_snake (const RadArgs*, RadStream); +int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream); +int r4d_rad_rvq_embed (const RadArgs*, RadStream); +int r4d_rad_frame_mix_store (const RadArgs*, RadStream); +int r4d_rad_end_status (const RadArgs*, RadStream); +int r4d_rad_frame_store (const RadArgs*, RadStream); +int r4d_rad_resample_nearest (const RadArgs*, RadStream); +int r4d_rad_fourier_embed (const RadArgs*, RadStream); +int r4d_rad_win_input (const RadArgs*, RadStream); +int r4d_rad_win_prep (const RadArgs*, RadStream); +int r4d_rad_win_finish (const RadArgs*, RadStream); +int r4d_rad_chan_split (const RadArgs*, RadStream); +int r4d_rad_interleave2 (const RadArgs*, RadStream); +int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream); +int r4d_rad_iota (const RadArgs*, RadStream); +int r4d_rad_cu_repeat (const RadArgs*, RadStream); +/* r4d_video.hip */ +int r4d_rad_rms_mod (const RadArgs*, RadStream); +int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream); +int r4d_rad_flow_x0_step (const RadArgs*, RadStream); +int r4d_rad_patch_unfold (const RadArgs*, RadStream); +int r4d_rad_vtile_gather (const RadArgs*, RadStream); +int r4d_rad_vtile_stitch (const RadArgs*, RadStream); +int r4d_rad_grid_pos3 (const RadArgs*, RadStream); +int r4d_rad_snake_aa (const RadArgs*, RadStream); +/* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */ +int r4d_rad_vsa_select (const RadArgs*, RadStream); +int64_t r4d_rad_vsa_select_scratch (const RadArgs*); +int r4d_rad_attn_vsa (const RadArgs*, RadStream); +/* r4d_quant_act_fp8.hip: E4M3 codes with a scale per column over every row (an attention's V). */ +int r4d_rad_quant_cols_fp8 (const RadArgs*, RadStream); +int64_t r4d_rad_quant_cols_fp8_scratch(const RadArgs*); /* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 and * MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify width (the * row's constraint value) is 8, against the gqa6 leg's 10. */ @@ -367,6 +404,7 @@ int r4d_rad_rope_table (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream); +int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs*, RadStream); int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*); int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_i8a8_m16 (const RadArgs*, RadStream); @@ -453,6 +491,34 @@ int r4d_rad_relayout_conv_tap(const RadParam*, int, int, const RadEncoding*, con const RadTensor*, int, void*, int64_t); int r4d_rad_unrelayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*, const void*, int64_t, const RadTensor*, int); +/* conv1d's weight, PyTorch's [cout][cin][k] stored [cout][k][cin], and conv_t1d's, PyTorch's + * [cin][cout][2s] stored [s][cout][2][cin] (r4d_layout.cpp). */ +int r4d_rad_layout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); +int r4d_rad_layout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); +/* The f32 rows' weights: conv1d's stored as bf16's, conv_t1d's [s][cout][ceil(k/s)][cin] with the + * taps past k zero (r4d_layout.cpp). */ +int r4d_rad_layout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); +int r4d_rad_layout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); +int r4d_rad_unrelayout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*, + const void*, int64_t, const RadTensor*, int); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, @@ -490,9 +556,11 @@ int r4d_rad_act_mul (const RadArgs*, RadStream); int r4d_rad_seg_mean (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope (const RadArgs*, RadStream); int r4d_rad_cast_widen (const RadArgs*, RadStream); +int r4d_rad_cast_f16 (const RadArgs*, RadStream); int r4d_rad_pool_rows (const RadArgs*, RadStream); int r4d_rad_relu (const RadArgs*, RadStream); int r4d_rad_silu (const RadArgs*, RadStream); +int r4d_rad_gelu (const RadArgs*, RadStream); int r4d_rad_clamp (const RadArgs*, RadStream); int r4d_rad_conv2d (const RadArgs*, RadStream); int r4d_rad_conv1d_dw (const RadArgs*, RadStream); @@ -511,6 +579,8 @@ int r4d_rad_layernorm (const RadArgs*, RadStream); int r4d_rad_grid_embed (const RadArgs*, RadStream); int r4d_rad_grid_embed_aa (const RadArgs*, RadStream); int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream); +/* gemm_nt_bias at f32 (r4d_gemm_f32_nt_bias.hip). */ +int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream); int r4d_rad_kv_store (const RadArgs*, RadStream); int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream); int r4d_rad_logits_gemm (const RadArgs*, RadStream); @@ -595,6 +665,7 @@ int r4d_shape_ar_gather_hc_write (const RadParam*, int, int operand, RadOpdDes int r4d_shape_gemm_nt (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gemm_nt_q (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_gemm_nt_q_bias (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gemm_nt_q_gated(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_dequant_w4 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_quant_act_fp8.hip b/libr4d/r4d_quant_act_fp8.hip index 985320d9..5804afca 100644 --- a/libr4d/r4d_quant_act_fp8.hip +++ b/libr4d/r4d_quant_act_fp8.hip @@ -188,3 +188,148 @@ extern "C" int r4d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) { extern "C" int r4d_rad_had_quant_act_i8g(const RadArgs* a, RadStream stream) { return rad_quant_act_fp8(a, stream, true, true); } + +// ============================================================== quant_cols_fp8 +// E4M3 codes with one scale per column over every row: an attention's V for its fp8 P.V. The +// formula is quant_act_fp8's (scale amax / 448, 1 for an all-zero column, codes of x / scale +// clamped to +-448) with the group running down a column. A column's scale needs every row, so +// two passes over the rows, split into kColChunks chunks: +// 1. column amax partials, a workgroup a block of columns and a chunk of rows, the bf16 +// magnitudes compared as integers (their order is the values'); +// 2. a workgroup the same block and chunk: the scales from the chunks' partials, then the codes, +// the chunk's rows walked from its end, which the first pass read last and the last-level +// cache still holds. +// A thread owns eight columns: one 16-byte load and one 8-byte store a row. +namespace { + +constexpr int kColChunks = 32; +constexpr int kColThreads = 128; + +typedef unsigned short r4d_u16x2 __attribute__((ext_vector_type(2))); + +__device__ __forceinline__ r4d_u16x2 col_mag(uint32_t w) { + return __builtin_bit_cast(r4d_u16x2, w & 0x7fff7fffu); +} + +__global__ __launch_bounds__(kColThreads) void quant_cols_amax_kernel( + const uint16_t* __restrict__ x, int M, int n, int x_ld, float* __restrict__ part) { + const int c8 = blockIdx.x * kColThreads + threadIdx.x; + if (c8 * 8 >= n) return; + const int r0 = (int)((long)M * blockIdx.y / kColChunks); + const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks); + const uint16_t* p = x + (long)c8 * 8; + r4d_u16x2 m[4] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; + int r = r0; + for (; r + 8 <= r1; r += 8) { + uint4 u[8]; + #pragma unroll + for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r + k) * x_ld); + #pragma unroll + for (int k = 0; k < 8; ++k) { + m[0] = __builtin_elementwise_max(m[0], col_mag(u[k].x)); + m[1] = __builtin_elementwise_max(m[1], col_mag(u[k].y)); + m[2] = __builtin_elementwise_max(m[2], col_mag(u[k].z)); + m[3] = __builtin_elementwise_max(m[3], col_mag(u[k].w)); + } + } + for (; r < r1; ++r) { + const uint4 u = *(const uint4*)(p + (long)r * x_ld); + m[0] = __builtin_elementwise_max(m[0], col_mag(u.x)); + m[1] = __builtin_elementwise_max(m[1], col_mag(u.y)); + m[2] = __builtin_elementwise_max(m[2], col_mag(u.z)); + m[3] = __builtin_elementwise_max(m[3], col_mag(u.w)); + } + float* d = part + (long)blockIdx.y * n + c8 * 8; + *(float4*)d = make_float4(bf16_to_f32(m[0].x), bf16_to_f32(m[0].y), bf16_to_f32(m[1].x), + bf16_to_f32(m[1].y)); + *(float4*)(d + 4) = make_float4(bf16_to_f32(m[2].x), bf16_to_f32(m[2].y), + bf16_to_f32(m[3].x), bf16_to_f32(m[3].y)); +} + +template +__device__ __forceinline__ int col_code2(float a, float b, float ia, float ib, int old) { + return __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(a * ia, -448.0f), 448.0f), + fminf(fmaxf(b * ib, -448.0f), 448.0f), old, HI); +} + +__global__ __launch_bounds__(kColThreads) void quant_cols_code_kernel( + const uint16_t* __restrict__ x, int M, int n, int x_ld, const float* __restrict__ part, + uint8_t* __restrict__ y, int y_ld, float* __restrict__ scale) { + const int c8 = blockIdx.x * kColThreads + threadIdx.x; + if (c8 * 8 >= n) return; + float am[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int ch = 0; ch < kColChunks; ++ch) { + const float4 a = *(const float4*)(part + (long)ch * n + c8 * 8); + const float4 b = *(const float4*)(part + (long)ch * n + c8 * 8 + 4); + am[0] = fmaxf(am[0], a.x); am[1] = fmaxf(am[1], a.y); + am[2] = fmaxf(am[2], a.z); am[3] = fmaxf(am[3], a.w); + am[4] = fmaxf(am[4], b.x); am[5] = fmaxf(am[5], b.y); + am[6] = fmaxf(am[6], b.z); am[7] = fmaxf(am[7], b.w); + } + float sc[8], inv[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) { + sc[e] = am[e] > 0.0f ? am[e] * (1.0f / 448.0f) : 1.0f; + inv[e] = 1.0f / sc[e]; + } + if (blockIdx.y == 0) { + *(float4*)(scale + c8 * 8) = make_float4(sc[0], sc[1], sc[2], sc[3]); + *(float4*)(scale + c8 * 8 + 4) = make_float4(sc[4], sc[5], sc[6], sc[7]); + } + const int r0 = (int)((long)M * blockIdx.y / kColChunks); + const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks); + const uint16_t* p = x + (long)c8 * 8; + uint8_t* q = y + (long)c8 * 8; + auto code = [&](uint4 u) { + int lo = col_code2(bf16w_lo(u.x), bf16w_hi(u.x), inv[0], inv[1], 0); + lo = col_code2(bf16w_lo(u.y), bf16w_hi(u.y), inv[2], inv[3], lo); + int hi = col_code2(bf16w_lo(u.z), bf16w_hi(u.z), inv[4], inv[5], 0); + hi = col_code2(bf16w_lo(u.w), bf16w_hi(u.w), inv[6], inv[7], hi); + return make_uint2((uint32_t)lo, (uint32_t)hi); + }; + int r = r1; + for (; r - 8 >= r0; r -= 8) { + uint4 u[8]; + #pragma unroll + for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r - 1 - k) * x_ld); + #pragma unroll + for (int k = 0; k < 8; ++k) *(uint2*)(q + (long)(r - 1 - k) * y_ld) = code(u[k]); + } + for (; r > r0; --r) + *(uint2*)(q + (long)(r - 1) * y_ld) = code(*(const uint4*)(p + (long)(r - 1) * x_ld)); +} + +} // namespace + +/* The partial maxima of every chunk, kColChunks rows of n floats. */ +extern "C" int64_t r4d_rad_quant_cols_fp8_scratch(const RadArgs* a) { + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + return (int64_t)kColChunks * n * (int64_t)sizeof(float); +} + +extern "C" int r4d_rad_quant_cols_fp8(const RadArgs* a, RadStream stream) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1), *sc = r4d_opt(a, 2); + if (!x || !y || !sc) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || y->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || n % 8) return R4D_NO(RAD_E_SHAPE); + long long M = 0, my = 0; + const long long xl = r4d_rows_pitch(x, n, &M), yl = r4d_rows_pitch(y, n, &my); + if (xl < 0 || yl < 0 || (xl & 7) || (yl & 7) || ((uintptr_t)x->data & 15) || + ((uintptr_t)y->data & 7) || !r4d_contig(sc) || ((uintptr_t)sc->data & 15)) + return R4D_NO(RAD_E_STRIDE); + if (my < M || r4d_numel(sc) < n || M > 0x7fffffffLL || n > 0x7fffffffLL) + return R4D_NO(RAD_E_SHAPE); + if (!a->scratch || ((uintptr_t)a->scratch & 15) || + a->scratch_bytes < (int64_t)kColChunks * n * (int64_t)sizeof(float)) + return R4D_NO(RAD_E_SCRATCH); + const dim3 grid((unsigned)((n / 8 + kColThreads - 1) / kColThreads), (unsigned)kColChunks); + hipLaunchKernelGGL(quant_cols_amax_kernel, grid, dim3(kColThreads), 0, (hipStream_t)stream, + (const uint16_t*)x->data, (int)M, (int)n, (int)xl, (float*)a->scratch); + hipLaunchKernelGGL(quant_cols_code_kernel, grid, dim3(kColThreads), 0, (hipStream_t)stream, + (const uint16_t*)x->data, (int)M, (int)n, (int)xl, + (const float*)a->scratch, (uint8_t*)y->data, (int)yl, (float*)sc->data); + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); +} diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 25ae530c..aab24411 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -172,6 +172,9 @@ static const RadParamSpec pAttnDense[] = { * start that attend only within themselves (a chunked encoder's windows). */ P_INTO("cu_div"), P_INTO("block"), + /* Non-causal only: the window's right side, key j visible when j - i < window_right; 0 is + * `window`'s (docs/OPS.md). */ + P_INTO("window_right"), }; static const RadOperandSpec oAttnDense[] = { { "q", RAD_OPD_IN, 0 }, @@ -679,6 +682,23 @@ static const RadOperandSpec oGemmNtQ[] = { { "a_sum", RAD_OPD_IN, 1 }, { "b_ref", RAD_OPD_WEIGHT, 1 }, }; +/* docs/OPS.md's `gemm_nt_q_bias`, ref's spelling: gemm_nt_q's first four operands, a per-column + * bias, then `y`. No parts and no aux operands. */ +static const RadParamSpec pGemmNtQBias[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "N", RAD_P_INT, RAD_REQUIRED }, + { "K", RAD_P_INT, RAD_REQUIRED }, + { "group", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oGemmNtQBias[] = { + { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "bias", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* docs/OPS.md's `dequant` is activation-shaped (`M`(range) `n` `group` `dtype`). libr4d's * dequant_w4_bf16 unpacks a weight from WMMA fragment order to row-major bf16, for the prefill @@ -1537,6 +1557,10 @@ static const RadOperandSpec oBinary[] = { { "b", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +/* `add`'s: `div` divides the rounded sum, rounded again (absent, 1: the plain sum). */ +static const RadParamSpec pAdd[] = { + P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div"), +}; static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype"), }; @@ -1559,11 +1583,13 @@ static const RadParamSpec pQkNormRope[] = { static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"), }; +/* `positions` may be absent at `rotary_dim` 0 (the norm alone), and an absent gain is a unit + * gain. */ static const RadOperandSpec oQkNormRope[] = { { "qkv", RAD_OPD_INOUT, 0 }, - { "positions", RAD_OPD_IN, 0 }, - { "q_w", RAD_OPD_WEIGHT, 0 }, - { "k_w", RAD_OPD_WEIGHT, 0 }, + { "positions", RAD_OPD_IN, 1 }, + { "q_w", RAD_OPD_WEIGHT, 1 }, + { "k_w", RAD_OPD_WEIGHT, 1 }, }; /* `scalar` 1 says `w` is one element rather than one row, for the shape description; the shim * reads it off the operand. */ @@ -1608,6 +1634,7 @@ static const RadOperandSpec oConv1dDw[] = { { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, }; static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype"), @@ -1695,6 +1722,11 @@ static const RadParamSpec pRope[] = { { "yarn_high", RAD_P_F64, RAD_OPTIONAL }, { "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL }, { "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */ + /* Llama 3's frequency scaling (abi/rad_yarn.h, RadLlama3). */ + { "llama3_factor", RAD_P_F64, RAD_OPTIONAL }, + { "llama3_low", RAD_P_F64, RAD_OPTIONAL }, + { "llama3_high", RAD_P_F64, RAD_OPTIONAL }, + { "llama3_orig", RAD_P_F64, RAD_OPTIONAL }, }; /* ---------------------------------------------------------------------- the vision tower */ @@ -2044,9 +2076,9 @@ static const RadOperandSpec oExpertScale[] = { /* ------------------------------------------------------------------------------- runtime LoRA * libref's schemas field for field (libref/ref_registry.cpp says what they mean): the loader - * refuses a library whose schema differs from the first declarer's. The pools are plain inputs -- - * the engine owns them as program buffers and fills a slot between steps -- and `dtype` is the - * tensor dtype name of `a` (shrink) or `y` (expand), which is what the rows below match on. */ + * refuses a library whose schema differs from the first declarer's. The pools are plain inputs + * (program buffers the engine fills between steps), and `dtype` is the tensor dtype name of `a` + * (shrink) or `y` (expand), which the rows below match on. */ static const RadParamSpec pLoraShrink[] = { P_INT("M"), P_INT("K"), @@ -2094,6 +2126,8 @@ static const RadOperandSpec oLnModQ[] = { { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 }, }; +/* `act` is the gate's activation, "tanh" (the default) or "none". */ +static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { { "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, @@ -2123,8 +2157,9 @@ static const RadOperandSpec oFlowEuler[] = { { "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 }, { "preview", RAD_OPD_INOUT, 1 }, }; +/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */ static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), - P_STR("mode"), P_STR("dtype") }; + P_STR("mode"), P_STR("dtype"), P_INTO("round") }; static const RadOperandSpec oGenUnary[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("stride"), P_STR("pad"), P_INT("up"), @@ -2146,12 +2181,187 @@ static const RadOperandSpec oScatterAdd[] = { static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), - P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk"), + P_STRO("pv") }; static const RadOperandSpec oAttnPS[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, - { "kv_cache", RAD_OPD_IN, 0 }, { "block_table", RAD_OPD_IN, 0 }, { "seqused", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_IN, 1 }, { "block_table", RAD_OPD_IN, 1 }, { "seqused", RAD_OPD_IN, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "k_descale", RAD_OPD_IN, 1 }, { "v_descale", RAD_OPD_IN, 1 }, { "k_i8", RAD_OPD_IN, 1 }, { "k_scale", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 }, + { "v_scale", RAD_OPD_IN, 1 }, +}; + +/* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */ +static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("dil"), P_STRO("act"), P_STR("dtype"), + P_INTO("causal") }; +static const RadOperandSpec oConv1d[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, { "b", RAD_OPD_WEIGHT, 1 }, +}; +static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"), + P_STR("dtype"), P_INTO("pad"), P_INTO("k") }; +static const RadOperandSpec oConvT1d[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pSnake[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("log") }; +static const RadOperandSpec oSnake[] = { + { "x", RAD_OPD_IN, 0 }, { "alpha", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, + { "beta", RAD_OPD_WEIGHT, 1 }, +}; +static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), + P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), + P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), + P_INTO("sup_hi"), P_F64O("penalty") }; +static const RadOperandSpec oCfgTopk[] = { + { "logits", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 }, + { "ids", RAD_OPD_OUT, 0 }, { "cfg", RAD_OPD_IN, 1 }, { "lane", RAD_OPD_IN, 1 }, + { "hist", RAD_OPD_INOUT, 1 }, +}; +static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), + P_INT("vocab"), P_INT("off0"), P_F64("scale"), + P_STR("dtype"), P_INTO("round") }; +static const RadOperandSpec oRvqEmbed[] = { + { "codes", RAD_OPD_IN, 0 }, { "t0", RAD_OPD_WEIGHT, 0 }, { "t1", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), + P_INTO("rep"), P_STR("dtype") }; +static const RadOperandSpec oFrameMix[] = { + { "hid", RAD_OPD_IN, 0 }, { "logits", RAD_OPD_WEIGHT, 0 }, { "scale", RAD_OPD_WEIGHT, 0 }, + { "lane", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 }, { "status", RAD_OPD_IN, 0 }, + { "dst", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") }; +static const RadOperandSpec oEndStatus[] = { + { "ids", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "status", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), + P_INTO("rep"), P_INTO("skip") }; +static const RadOperandSpec oFrameStore[] = { + { "codes", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 }, + { "status", RAD_OPD_IN, 0 }, { "dst", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pFourier[] = { P_INT("M"), P_INT("n"), P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oFourier[] = { + { "t", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pWinInput[] = { P_INT("M"), P_INT("n_lat"), P_INT("n_zero"), + P_INT("n_cond"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oWinInput[] = { + { "lat", RAD_OPD_IN, 0 }, { "cond", RAD_OPD_IN, 0 }, { "lat_cu", RAD_OPD_IN, 0 }, + { "win_lane", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pWinPrep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_INT("ov"), + P_STR("dtype") }; +static const RadOperandSpec oWinPrep[] = { + { "flags", RAD_OPD_IN, 0 }, { "t", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, + { "win_index", RAD_OPD_IN, 0 }, { "win_lane", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, + { "lat_cu", RAD_OPD_IN, 0 }, { "prev", RAD_OPD_IN, 0 }, { "noise", RAD_OPD_INOUT, 0 }, + { "lat", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pWinFinish[] = { P_INT("M"), P_INT("n"), P_INT("n_cond"), P_INT("stride"), + P_INT("ov"), P_STR("dtype") }; +static const RadOperandSpec oWinFinish[] = { + { "flags", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "win_lane", RAD_OPD_IN, 0 }, + { "lat_cu", RAD_OPD_IN, 0 }, { "cond", RAD_OPD_IN, 0 }, { "lat", RAD_OPD_INOUT, 0 }, + { "prev", RAD_OPD_INOUT, 0 }, { "prev_cond", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pChanSplit[] = { P_INT("M"), P_INT("n"), P_INT("parts"), P_STR("dtype") }; +static const RadParamSpec pInterleave[] = { P_INT("M"), P_STR("dtype") }; +static const RadOperandSpec oInterleave2[] = { + { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), + P_INTO("period") }; +static const RadOperandSpec oIota[] = { { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; +static const RadOperandSpec oCuRepeat[] = { { "len", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"), + P_INTO("log"), P_STR("dtype") }; +static const RadOperandSpec oSnakeAa[] = { + { "x", RAD_OPD_IN, 0 }, { "alpha", RAD_OPD_WEIGHT, 0 }, { "beta", RAD_OPD_WEIGHT, 0 }, + { "f_up", RAD_OPD_WEIGHT, 0 }, { "f_down", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; + +/* ---- video generation (r4d_video.hip); the same specs as libref's (ref_registry.cpp). `geom` is + * the request's latent geometry, i32 on the device. */ +static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), + P_STR("dtype") }; +static const RadOperandSpec oRmsMod[] = { + { "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, + { "z", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oRmsModQ[] = { + { "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, + { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 }, +}; +static const RadOperandSpec oFlowX0[] = { + { "v", RAD_OPD_IN, 0 }, { "t", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, + { "sigma_next", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, +}; +static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"), + P_INT("pw"), P_STR("mul"), P_STR("add"), + P_STR("dtype") }; +static const RadOperandSpec oPatchUnfold[] = { + { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pVtileGather[] = { P_INT("M"), P_INT("n"), P_INT("tile"), + P_INT("overlap"), P_INT("frames"), P_INT("period"), + P_INT("n_reg"), P_STR("dtype") }; +static const RadOperandSpec oVtileGather[] = { + { "x", RAD_OPD_IN, 0 }, { "reg", RAD_OPD_WEIGHT, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("scale"), P_INT("pt"), P_INT("skip"), + P_INT("keep"), P_INT("blend"), P_INT("period"), + P_STR("mean"), P_STR("std") }; +static const RadOperandSpec oVtileStitch[] = { + { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "prev", RAD_OPD_INOUT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), + P_INT("period"), P_F64("scale") }; +static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } }; + +/* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed + * rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is + * vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */ +static const RadParamSpec pVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale") }; +static const RadOperandSpec oVsaSelect[] = { + { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 1 }, + { "segs", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "sel", RAD_OPD_OUT, 0 }, { "coarse", RAD_OPD_OUT, 1 }, +}; +/* attn_vsa adds attn_prefix_self's int8 Q.K form at the end of the shared list: `qk` "i8" with + * `k_i8` [M, n_head head_dim] and `k_scale` [M, n_head], quant_act_i8g's codes and scales of k at + * group head_dim; and the fp8 P.V form: `pv` "fp8" with `v` as quant_cols_fp8's E4M3 codes and + * `v_scale` [n_head head_dim] their column scales. */ +static const RadParamSpec pAttnVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale"), P_STRO("qk"), + P_STRO("pv") }; +static const RadOperandSpec oAttnVsa[] = { + { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, + { "segs", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "sel", RAD_OPD_IN, 0 }, + { "coarse", RAD_OPD_IN, 1 }, { "gate", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 }, + { "k_i8", RAD_OPD_IN, 1 }, { "k_scale", RAD_OPD_IN, 1 }, { "v_scale", RAD_OPD_IN, 1 }, +}; + +/* quant_cols_fp8: E4M3 codes with one scale per column over every row (an attention's V for its + * fp8 P.V); the same spec as libref's. */ +static const RadParamSpec pQuantCols[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oQuantCols[] = { + { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, }; static const RadOpSchema kSchemas[] = { @@ -2163,9 +2373,10 @@ static const RadOpSchema kSchemas[] = { "attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the " "key with the k_norm gain in the same layer, which one op with a required gain cannot " "express."), - SCHEMA("add", pMnDtype, oBinary, + SCHEMA("add", pAdd, oBinary, "y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts " - "along rows, and nothing else broadcasts at all."), + "along rows, and nothing else broadcasts at all. With `div`, y = rd(rd(a + b) / div), " + "rd y's dtype."), SCHEMA("mul", pMnDtype, oBinary, "y = a * b, with the same one broadcast rule as `add`."), SCHEMA("mul_weight", pMulWeight, oMulWeight, "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " @@ -2187,13 +2398,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("qk_norm_rope", pQkNormRope, oQkNormRope, "In place over a fused [q | k | v] row: each q and k head RMS-normed against its gain " "(plus wadd) and rounded, then rotated (neox or gptj, rotary_dim of head_dim); with " - "v_norm each v head is RMS-normed with a unit gain and not rotated."), + "v_norm each v head is RMS-normed with a unit gain and not rotated. An absent gain is " + "a unit gain without wadd; rotary_dim 0 is the norm alone, positions then optional; " + "f32 positions are read as the values they hold."), SCHEMA("pool_rows", pPoolRows, oUnary, "Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded, then " "times `mult` and rounded again."), SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."), SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."), SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."), + SCHEMA("gelu", pMnDtype, oUnary, + "y = 0.5x(1 + erf(x/sqrt(2))). The exact erf form, not the tanh approximation."), SCHEMA("clamp", pMnDtype, oClamp, "y = min(max(x, lo), hi), lo and hi WEIGHTS of one element each: a clipped linear's range."), SCHEMA("conv2d", pConv2d, oConv2d, @@ -2445,6 +2660,8 @@ static const RadOpSchema kSchemas[] = { "C[M,N] = A[M,K] @ dequant(Bq)[N,K]^T. `dtype` names the operand COMBINATION, so one " "op covers w4a16 through mxfp4a8 and an architecture plugin that changes quant changes " "one string."), + SCHEMA("gemm_nt_q_bias", pGemmNtQBias, oGemmNtQBias, + "gemm_nt_q with a per-column bias added to the f32 product before its one rounding."), SCHEMA("dequant_w4", pDequantW4, oDequantW4, "a packed 4-bit fragment-ordered weight back to row-major bf16."), SCHEMA("scale_rows", pScaleRows, oScaleRows, @@ -2709,8 +2926,9 @@ static const RadOpSchema kSchemas[] = { SCHEMA("ln_mod_quant_fp8", pLnModQ, oLnModQ, "gated 1: x = bf16(x + bf16(bf16(tanh(g[seq])) * y)) first; then z = ln_mod(x) and " "(q, scale) = quant_act_fp8(z, group), z written when bound."), - SCHEMA("gate_add", pGenMn, oGateAdd, - "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate."), + SCHEMA("gate_add", pGateAdd, oGateAdd, + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; " + "with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."), SCHEMA("timestep_embed", pTimestep, oTimestep, "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2))."), SCHEMA("gather_rows2", pGenMn, oGather2, @@ -2722,7 +2940,8 @@ static const RadOpSchema kSchemas[] = { SCHEMA("flow_euler", pLane, oFlowEuler, "one Euler step of a flow-matching sampler per entry that moves a lane."), SCHEMA("chan_affine", pChanAffine, oGenUnary, - "a per-channel affine from two parameter lists of n values."), + "a per-channel affine from two parameter lists of n values; `round` 0 keeps the lists " + "and the arithmetic in f32, rounded once into y."), SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc, "an image convolution, channels innermost, the sizes read off the operands."), SCHEMA("l2norm_chan", pL2Norm, oL2Norm, @@ -2736,7 +2955,86 @@ static const RadOpSchema kSchemas[] = { "attention over a paged prefix and the step's own rows, causal over the own rows or not. " "`qk` \"i8\" with `k_i8` and `k_scale` selects the INT8 Q.K form: the own keys as quant_act_i8g " "codes and scales at group head_dim, the query and the prefix keys quantised the same " - "way inside the op, the score product exact in integers and P.V as in the bf16 form."), + "way inside the op, the score product exact in integers and P.V as in the bf16 form. " + "`pv` \"fp8\" with `v_scale` selects the fp8 P.V form (prefix-free only): `v` as " + "quant_cols_fp8's E4M3 codes and column scales, P as e4m3(448 p) against an exact " + "running max, o = (sum w v_code) v_scale / (448 sum p)."), + SCHEMA("conv1d", pConv1d, oConv1d, + "a 1-D convolution over the sequences cu_seqlens bounds, channels innermost, zeros outside " + "each; dilation `dil`, padding dil (k - 1) / 2 a side or, with `causal`, dil (k - 1) on " + "the left; `res` added after the bias, then `act`."), + SCHEMA("conv_t1d", pConvT1d, oConvT1d, + "a transposed 1-D convolution of kernel `k` (2 stride by default, or stride), padding " + "`pad` ((k - stride) / 2 by default, 0 the causal form): each sequence grows `stride` " + "times."), + SCHEMA("snake", pSnake, oSnake, + "x + sin(alpha x)^2 / (alpha + 1e-9) per channel, or with `beta` x + (1 / (beta + " + "1e-9)) sin(alpha x)^2; `log` reads both as logarithms."), + SCHEMA("cfg_topk_sample", pCfgTopk, oCfgTopk, + "a guided top-k pick a lane from `rep` branch rows, drawn with the frame's Philox stream; " + "per-lane guidance, a repetition penalty over the lane's history and suppressed ids " + "optional."), + SCHEMA("rvq_embed", pRvqEmbed, oRvqEmbed, + "a frame's embedding from code-major residual codes, the first codebook's table and the " + "others' stacked one, times `scale`; `round` 1 rounds the f32 sum once."), + SCHEMA("frame_mix_store", pFrameMix, oFrameMix, + "a frame's conditioning row (softmax-weighted planes times scale) into its lane."), + SCHEMA("end_status", pEndStatus, oEndStatus, + "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."), + SCHEMA("frame_store", pFrameStore, oFrameStore, + "a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] " + "= codes[k, rep i] when frame >= skip and status[lane] >= 0."), + SCHEMA("resample_nearest", pGenMn, oGenUnary, "rows resampled nearest-neighbour."), + SCHEMA("fourier_embed", pFourier, oFourier, "[cos | sin] of 2 pi t w for a trained w."), + SCHEMA("win_input", pWinInput, oWinInput, + "a denoiser's [lat | zeros | cond] rows from the window states."), + SCHEMA("win_prep", pWinPrep, oWinPrep, "a window step's noise and overlap binding."), + SCHEMA("win_finish", pWinFinish, oWinFinish, "a window's end and the overlap it hands on."), + SCHEMA("chan_split", pChanSplit, oGenUnary, "channel groups to sequences."), + SCHEMA("interleave2", pInterleave, oInterleave2, "two streams interleaved."), + SCHEMA("iota", pIota, oIota, "y[i] = start + i * step."), + SCHEMA("cu_repeat", pCuRepeat, oCuRepeat, "bounds of equal sequences, y[j] = j * len[0] * mult."), + SCHEMA("snake_aa", pSnakeAa, oSnakeAa, + "BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled " + "`ratio` times by `f_up`, SnakeBeta, filtered by `f_down` at stride `ratio`."), + SCHEMA("rms_mod", pRmsMod, oRmsMod, + "gated 1: x = bf16(x + bf16(g[seq] * y)) first (no tanh); then z = bf16(bf16(bf16(bf16(" + "x rsqrt(mean(x^2) + eps)) w) bf16(1 + scale[seq])) + shift[seq]), `s` holding " + "[shift | scale]."), + SCHEMA("rms_mod_quant_fp8", pRmsModQ, oRmsModQ, + "rms_mod with the chain in bf16, then (q, scale) = quant_act_fp8(z, group); z written " + "when bound."), + SCHEMA("flow_x0_step", pGenMn, oFlowX0, + "x = r x + (1 - r) (x + (1 - t) v), r = sigma_next / sigma, each step one f32 " + "rounding."), + SCHEMA("patch_unfold", pPatchUnfold, oPatchUnfold, + "patch rows unfolded to voxel rows and denormalised with f32 lists."), + SCHEMA("vtile_gather", pVtileGather, oVtileGather, + "a video decoder's tiles out of voxel rows, each followed by its register tokens and " + "zeros to the period."), + SCHEMA("vtile_stitch", pVtileStitch, oVtileStitch, + "a decoded chunk's tiles stitched into RGB bytes, blended with the previous chunk's " + "tail."), + SCHEMA("grid_pos3", pGridPos3, oGridPos3, + "a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."), + SCHEMA("vsa_select", pVsa, oVsaSelect, + "video sparse attention's selection over tiles of at most 64 rows (dense segments in " + "chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, " + "scores scale qp.kp, and for each video query tile the k = max(1, min(ceil((1 - " + "sparsity) V), V)) video tiles of largest score, ascending, ties to the lower tile; " + "with `coarse`, bf16(softmax over every tile of the scores, times the v means)."), + SCHEMA("attn_vsa", pAttnVsa, oAttnVsa, + "block-sparse attention over vsa_select's tiles: a prefix query tile sees every tile, a " + "video one the prefix tiles and its selected tiles; with `coarse` and `gate`, " + "bf16(bf16(o) + coarse[tile] gate). `qk` \"i8\" with `k_i8` and `k_scale` selects the " + "INT8 Q.K form: the keys as quant_act_i8g codes and scales at group head_dim, the query " + "quantised the same way inside the op, a score the exact integer product times both " + "scales, P.V as in the bf16 form. `pv` \"fp8\" with `v_scale` selects the fp8 P.V " + "form: `v` as quant_cols_fp8's E4M3 codes and column scales, P as e4m3(448 p) against " + "an exact running max, o = (sum w v_code) v_scale / (448 sum p)."), + SCHEMA("quant_cols_fp8", pQuantCols, oQuantCols, + "E4M3 codes with one scale per column over all M rows: scale = amax(|x[:, c]|) / 448 " + "(1 for an all-zero column), y = e4m3(clamp(x / scale, +-448)), round to nearest even."), }; /* ================================================================================ constraints @@ -3009,14 +3307,23 @@ static const RadConstraint cAttnLocalRel[] = { static const RadConstraint cCastWiden[] = { C_IN("from", "bf16"), C_IN("to", "f32"), }; +/* `cast` narrowing bf16 -> f16, rounded to nearest: the f16 activation of a 4-bit weight's skinny + * GEMM (w4a16_asym) where no rotation produces one. */ +static const RadConstraint cCastF16[] = { + C_IN("from", "bf16"), C_IN("to", "f16"), +}; /* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs * r4d_attn_dense_bf16.hip compiles. */ +/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */ static const RadConstraint cAttnDenseH64[] = { - C_EQ("head_dim", 64), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), + C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"), }; static const RadConstraint cAttnDenseH256G2[] = { C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; +static const RadConstraint cAttnDenseH256G4[] = { + C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; static const RadConstraint cAttnDenseH512G4[] = { C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; @@ -3184,9 +3491,8 @@ static const RadConstraint cExpertScale[] = { }; /* Runtime LoRA. Any M, K and N: the scalar kernels loop over whatever extents arrive, and the grid * is M blocks (shrink) or M strips of 256 columns (expand). R and S are bounded only by the shims' - * 32-bit index sanity. The dtype set is every activation the decode below reads -- an fp8 or i8 - * one with its scale stream -- and the three outputs a GEMM writes; anything else does not - * resolve here. */ + * 32-bit index sanity. The dtype set is every activation the decode reads (an fp8 or i8 one with + * its scale stream) and the three outputs a GEMM writes. */ static const RadConstraint cLoraShrink[] = { C_GE("R", 1), C_LE("R", 65536), C_GE("S", 1), C_LE("S", 1048576), C_IN("dtype", "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8"), @@ -3195,10 +3501,10 @@ static const RadConstraint cLoraExpand[] = { C_GE("R", 1), C_LE("R", 65536), C_GE("S", 1), C_LE("S", 1048576), C_IN("dtype", "bf16 f16 f32"), }; -/* The tiled rows (r4d_lora_bf16.hip, V2). Shrink is two rows because a constraint on an absent +/* The tiled rows (r4d_lora_bf16.hip). Shrink is two rows because a constraint on an absent * parameter does not hold: a bf16 activation has no `group`, and a coded one is the WMMA's only - * when its group is whole 32-wide steps (the scale is applied a step at a time). Anything else -- - * f16, f32, a coded activation with another group or none declared -- is the scalar row's. */ + * when its group is whole 32-wide steps (the scale is applied a step at a time). Anything else + * (f16, f32, a coded activation with another group or none declared) is the scalar row's. */ static const RadConstraint cLoraShrinkWmma[] = { C_GE("R", 1), C_LE("R", 65536), C_GE("S", 1), C_LE("S", 1048576), C_IN("dtype", "bf16"), }; @@ -3377,6 +3683,12 @@ static const RadConstraint cGemmNtFp8A8Tiled[] = { C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), }; +/* gemm_nt_q_bias on the narrow tile: the unbiased narrow row's band. The weight is the same + * fragment-order plane, so the same layout hooks serve it. */ +static const RadConstraint cGemmNtQBiasFp8A8M16[] = { + C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK), + C_IN("dtype", "fp8a8"), +}; /* The int8 twins: the same bands at dtype i8a8. */ static const RadConstraint cGemmNtI8A8M16[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK), @@ -3843,6 +4155,8 @@ static const RadConstraint cRopeRow[] = { C_GE("head_dim", 1), static const RadConstraint cLayernorm[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; static const RadConstraint cGridEmbed[] = { C_GE("n", 1), C_GE("side", 1), C_IN("dtype", "bf16") }; static const RadConstraint cGemmBias[] = { C_GE("M", 1), C_DIV("K", 8), C_IN("dtype", "bf16") }; +/* The f32 GEMM reads its rows a float at a time: any K. */ +static const RadConstraint cGemmBiasF32[] = { C_GE("M", 1), C_IN("dtype", "f32") }; static const RadConstraint cSampleVoc[] = { C_GE("n_vocab", 1) }; static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 4096) }; static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; @@ -3866,13 +4180,31 @@ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtyp /* Rows read 16 bytes at a time, so the widths are whole eights. */ static const RadConstraint cGenRows8[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) }; static const RadConstraint cGenBf16[] = { C_IN("dtype", "bf16") }; +/* A depth decoder's attention: a frame's handful of positions, one query head a key head. */ +static const RadConstraint cAttnDenseSmallH256[] = { + C_EQ("head_dim", 256), C_EQ("gqa", 1), C_IN("dtype", "bf16"), C_LE("max_seqlen", 32), +}; +static const RadConstraint cAudioAny[] = { C_IN("dtype", "bf16 f32") }; +/* ---- video generation (r4d_video.hip). The modulated norms keep a row's 8-wide chunks in + * registers, four a thread (n <= 8192), and read 16 bytes at a time; the lists are kernel + * arguments, 64 floats at most; the alias-free activation stages its filters in 32 floats of + * LDS. */ +static const RadConstraint cRmsMod[] = { C_IN("dtype", "bf16"), C_DIV("n", 8), C_LE("n", 8192) }; +static const RadConstraint cRmsModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192), + C_EQ("group", 128) }; +static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") }; +static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64) }; +static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") }; +static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) }; static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192), C_EQ("group", 128) }; /* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */ static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") }; /* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */ static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) }; +static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) }; static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cGenTimestepF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; /* The paged prefix at libr4d's block of 16, both caches bf16, up to eight query heads a KV head * (the shim takes 1, 2, 4 and 8). */ static const RadConstraint cAttnPrefixSelf[] = { @@ -3888,6 +4220,14 @@ static const RadConstraint cAttnDenseH768[] = { static const RadConstraint cAttnDenseH1152[] = { C_EQ("head_dim", 1152), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; +/* Video sparse attention: head_dim 128 over 4 x 4 x 4 tiles. The dtypes, the tile capacity and + * the optional pairs (v with coarse, coarse with gate) are the entry points' checks. */ +static const RadConstraint cVsa[] = { + C_EQ("head_dim", 128), C_EQ("tile_t", 4), C_EQ("tile_h", 4), C_EQ("tile_w", 4), + C_GE("patch", 1), +}; +/* A thread quantises eight columns: one 16-byte load and one 8-byte store a row. */ +static const RadConstraint cQuantCols[] = { C_DIV("n", 8), C_IN("dtype", "bf16") }; static const RadKernelInfo kKernels[] = { /* ---------------------------------- the small model ops (r4d_model_bf16.hip) ---------------- @@ -4007,6 +4347,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_cast_widen, nullptr, nullptr, nullptr, r4d_shape_cast }, +{ "cast_bf16_f16", "cast", "elem", + "y = x, bf16 narrowed to f16", + "any M and n; both row pitches are read off the operands", + "bf16 in, f16 out, rounded to nearest even (a value past f16's range becomes an infinity)", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cCastF16), NOTUNE, + nullptr, nullptr, r4d_rad_cast_f16, nullptr, nullptr, nullptr, + r4d_shape_cast }, + { "act_mul_bf16", "act_mul", "elem", "gated activation over two operands: act(a) rounded, times b", "any n; a, b and y each at their own row pitch, so both may be column slices of one buffer", @@ -4030,7 +4379,8 @@ static const RadKernelInfo kKernels[] = { "blocks at any even head_dim and section size (sections of 16 or a multiple of 32 pairs, each " "on a 32-channel slice, in registers; others a lane a pair); one workgroup a token and a wave " "a head, sin/cos computed once for all its heads", - "bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation", + "bf16 qkv, bf16 or f32 gains, i32 positions, f32 arithmetic, the norm rounded before the " + "rotation", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRope), NOTUNE, nullptr, nullptr, r4d_rad_qk_norm_rope }, @@ -4053,6 +4403,24 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_silu, nullptr, nullptr, nullptr, r4d_shape_unary }, +{ "silu_f32", "silu", "elem", + "x * sigmoid(x) over f32 rows, flat over the extent", + "any n; both row pitches read off the operands", + "f32 in, f32 out or bf16 rounded once", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_silu, nullptr, nullptr, nullptr, + r4d_shape_unary }, + +{ "gelu_bf16", "gelu", "elem", + "0.5 x (1 + erf(x / sqrt 2)), the exact form: libref's act_gelu", + "any n; both row pitches read off the operands", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_gelu, nullptr, nullptr, nullptr, + r4d_shape_unary }, + { "clamp_bf16", "clamp", "elem", "x clamped to two one-element weights: a clipped linear's range", "any n; bf16 or f32 bounds", @@ -4125,7 +4493,7 @@ static const RadKernelInfo kKernels[] = { { "rmsnorm_bf16", "rmsnorm", "norm", "root-mean-square norm with a gain, two passes over the row", "any n; the sum of squares accumulates in f32 and only the store narrows", - "bf16 x / gain / y, fp32 reduction", + "bf16 y, x bf16 or (with a gain) f32, bf16 or f32 gain, fp32 reduction", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr, @@ -4143,7 +4511,7 @@ static const RadKernelInfo kKernels[] = { { "layernorm_bf16", "layernorm", "norm", "layer norm with a gain and an optional bias, two passes over the row", "any n; mean and variance accumulate in f32 and only the store narrows", - "bf16 x / y, f32 or bf16 gain and bias", + "bf16 or f32 x, bf16 y, f32 or bf16 gain and bias", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cLayernorm), NOTUNE, nullptr, nullptr, r4d_rad_layernorm, nullptr, nullptr, nullptr, @@ -4168,8 +4536,9 @@ static const RadKernelInfo kKernels[] = { r4d_shape_grid_embed }, { "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm", - "biased GEMM C = res + act(A @ W^T + bias): eight waves over an LDS-staged 64-deep K tile, " - "the K tail staged as zeros, the activation and residual in the store", + "biased GEMM C = res + act(A @ W^T + bias) over 64-deep K tiles, the K tail staged as zeros, " + "the activation and residual in the store: from 32 blocks of 128x128 the weight read straight " + "into registers and the activation staged through LDS, below that both staged at 64x64", "any M, N; K a multiple of 8; A rows 16-byte aligned; `res` may be the output itself", "bf16 A / W / C / res, bf16 or f32 bias, fp32 accumulate, three RNE roundings in the store", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -4177,8 +4546,19 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_gemm_nt_bias, nullptr, nullptr, nullptr, r4d_shape_gemm_nt_bias }, +{ "gemm_f32_nt_bias", "gemm_nt_bias", "gemm", + "biased f32 GEMM C = res + act(A @ W^T + bias): a register-blocked FMA tile of 128 rows by 128, " + "96, 64 or 32 columns over LDS-staged 16-deep K slabs, the activation and residual in the store", + "any M, N and K; A and C at their own row pitches; `res` may be the output itself", + "f32 A / W, f32 or bf16 bias, f32 accumulate, C f32 or bf16 with res in C's dtype (each epilogue " + "step rounded to C's dtype)", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGemmBiasF32), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_f32_nt_bias, nullptr, nullptr, nullptr, + r4d_shape_gemm_nt_bias }, + { "add_bf16", "add", "elem", - "elementwise sum, with the one row-broadcast form", + "elementwise sum, with the one row-broadcast form; `div` divides the rounded sum", "any n; `b` with exactly n elements broadcasts along rows and nothing else does", "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -4186,6 +4566,16 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_add, nullptr, nullptr, nullptr, r4d_shape_binary }, +{ "add_f32", "add", "elem", + "elementwise f32 sum, the same broadcast rule and `div`, flat over the extent so a narrow row " + "over a million rows keeps every lane busy", + "any M and n; `y` may be `a` (an in-place residual)", + "f32 in and out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_add, nullptr, nullptr, nullptr, + r4d_shape_binary }, + { "mul_bf16", "mul", "elem", "elementwise product, with the one row-broadcast form", "any n; the same broadcast rule as add", @@ -4198,12 +4588,22 @@ static const RadKernelInfo kKernels[] = { { "mul_weight_bf16", "mul_weight", "elem", "activation times a learned scalar or one-row gain", "any n; the weight is one element or exactly n", - "bf16 in, weight and out, fp32 arithmetic", + "bf16 in and out, a bf16 or f32 weight, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cBf16Row), NOTUNE, nullptr, nullptr, r4d_rad_mul_weight, nullptr, nullptr, nullptr, r4d_shape_mul_weight }, +{ "mul_weight_f32", "mul_weight", "elem", + "activation times a learned scalar or one-row gain into an f32 output (a layer scale on a " + "branch joining an f32 residual)", + "any n; the weight is one element or exactly n", + "bf16 or f32 in, a bf16 or f32 weight, f32 out, the product rounded once", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_mul_weight, nullptr, nullptr, nullptr, + r4d_shape_mul_weight }, + { "fill_bf16", "fill", "elem", "constant fill, a row a workgroup", "any M, n; a row pitch is honoured", @@ -4915,8 +5315,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_attn_vit }, { "attn_dense_h64_bf16", "attn_dense", "attn", - "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window or " - "blocks", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or " + "blocks, or causal with an optional window behind", "head_dim 64, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a " "fused projection allowed)", "bf16 query / key / value / out, f16 operands, fp32 accumulate", @@ -4932,6 +5332,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDenseH256G2), NOTUNE, nullptr, nullptr, r4d_rad_attn_dense }, +{ "attn_dense_h256_gqa4_bf16", "attn_dense", "attn", + "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "head_dim 256, four query heads a KV head in one workgroup, the key range cut to the window", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH256G4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense }, + { "attn_dense_h512_gqa4_bf16", "attn_dense", "attn", "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", "head_dim 512 split across two waves, four query heads a KV head in one workgroup", @@ -5450,17 +5858,32 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, r4d_fuse_gemm_nt_q_gated }, { "gemm_fp8a8_tiled", "gemm_nt_q", "gemm", - "the same GEMM for prefill row counts: 128x128 tile, eight waves, one K tile prefetched in " - "registers, and the ACTIVATION on the A operand so the epilogue is a coalesced store", + "the same GEMM for prefill row counts: 128x128 tile, eight waves of 2 weight x 4 activation " + "tiles, the weight read straight into registers and the activation staged through LDS, one K " + "tile ahead; a lane stores eight consecutive columns of one row", "any M; K and N multiples of 128 -- the fold at the end of the K loop assumes a whole scale " "block, and the weight's block scale is read as one scalar for the block's 128 N rows", - "E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C", + "E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C; " + "each 128-K block's product folded into the f32 accumulator with one fma", RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED, ROW(cGemmNtFp8A8Tiled), NOTUNE, nullptr, nullptr, r4d_rad_gemm_fp8a8_tiled, nullptr, r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block }, +{ "gemm_fp8a8_bias_nt_m16", "gemm_nt_q_bias", "gemm", + "the narrow block-scaled FP8 W8A8 GEMM with a bias per output column in its store: the " + "unbiased narrow tile, never split, writing C at its own row pitch", + "M <= 64 (the narrow tile's NT of up to 4); K a multiple of 128 and N of 16, the unbiased " + "narrow row's band; C may be a column slice of a wider buffer", + "E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, a bf16 " + "bias added to the f32 accumulator before its one rounding, bf16 C", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGemmNtQBiasFp8A8M16), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_fp8a8_bias_m16, nullptr, + r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, + r4d_shape_gemm_nt_q_bias, r4d_rad_unrelayout_fp8_block }, + { "gemm_i8a8_nt_m16", "gemm_nt_q", "gemm", "gemm_fp8a8_nt_m16 at INT8 codes: the same narrow tile, staging and split-K, with the iu8 WMMA " "for the fp8 one and the weight's scale per row", @@ -5475,7 +5898,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, { "gemm_i8a8_tiled", "gemm_nt_q", "gemm", "gemm_fp8a8_tiled at INT8 codes: the same 128x128 prefill tile, the iu8 WMMA for the fp8 one and " - "the weight's scale per row, one a lane a tile in the fold", + "the weight's scale per row, eight a lane a tile in the fold", "the fp8 row's: any M; K and N multiples of 128", "i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per ROW per 128 K, bf16 C", RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED, @@ -6319,10 +6742,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cExpertScale), NOTUNE, nullptr, nullptr, r4d_rad_expert_scale_bf16 }, -/* Runtime LoRA, v1: scalar f32, correct first (r4d_lora_bf16.hip). NO opd_shape: libref describes - * both ops, so rad-kbench draws the same operands for this row as for the oracle -- `slot` in - * [0, S], S itself a base row. NOT CONCURRENT: see rad_kernel_concurrent below. Below the tiled - * rows, which serve the same ops for every dtype but f16/f32 activations (R4D_PRIO_LORA_TILED). */ +/* Runtime LoRA, the scalar f32 rows (r4d_lora_bf16.hip). No opd_shape: libref describes both ops, + * so rad-kbench draws the same operands for this row as for the oracle (`slot` in [0, S], S a base + * row). Not concurrent (rad_kernel_concurrent below). Below the tiled rows, which serve every dtype + * but f16/f32 activations (R4D_PRIO_LORA_TILED). */ { "lora_shrink_scalar", "lora_shrink", "gemm", "t = x A[slot]^T per row, base rows untouched: one block a row, one wave a column, the k of a " "lane in order and a fixed xor butterfly across the wave", @@ -6341,10 +6764,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_SCALAR, ROW(cLoraExpand), NOTUNE, nullptr, nullptr, r4d_rad_lora_expand }, -/* Runtime LoRA, v2: the tiled rows. The grid is row TILES, a tile of base rows leaves on one - * ballot, and a mixed tile runs one pass per distinct slot; shrink's summation order is fixed by K - * and R (sh_plan), expand's bytes are v1's. The shrink split keeps its partials in the op's - * scratch (the hook sizes it for the band) and its arrival counters in a block keyed on `t`. */ +/* Runtime LoRA, the tiled rows. The grid is row tiles, a tile of base rows leaves on one ballot, + * and a mixed tile runs one pass per distinct slot; shrink's summation order is fixed by K and R + * (sh_plan), and expand computes the scalar row's bytes. The shrink split keeps its partials in the + * op's scratch (the hook sizes it for the band) and its arrival counters in a block keyed on `t`. */ { "lora_shrink_wmma", "lora_shrink", "gemm", "t = x A[slot]^T per row, base rows untouched: WMMA bf16 over 16-row x 16-j tiles, K in 32-wide " "steps over 4 waves and a K split fixed by K and R, one pass a distinct slot of a tile", @@ -6365,7 +6788,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_lora_shrink_wmma, r4d_rad_lora_shrink_wmma_scratch }, { "lora_expand_tiled", "lora_expand", "gemm", "y += scale * (t B[slot]^T) per row, base rows neither read nor written: 32-row x 128-column " - "tiles, B[slot]'s slab staged in LDS once a tile, v1's j-ascending order a output", + "tiles, B[slot]'s slab staged in LDS once a tile, the scalar row's j-ascending order an output", "any M and N, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of t and y honoured", "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED, @@ -6374,8 +6797,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, { "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn", "attention over a paged prefix and the pass's own rows, causal over the own rows or not", "head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; " - "the int8 Q.K form (k_i8 / k_scale) at 1 only", - "bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate", + "the int8 Q.K form (k_i8 / k_scale) at 1 only; the fp8 P.V form (v_scale) at 1 without a " + "prefix", + "bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate; " + "or E4M3 V codes and P, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnPrefixSelf), NOTUNE, nullptr, nullptr, r4d_rad_attn_prefix_self }, @@ -6420,7 +6845,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_ln_mod }, { "gate_add_bf16", "gate_add", "elem", - "x += tanh(gate row) * y, the reference's three roundings", + "x += tanh(gate row) * y, the reference's three roundings; with `act` none the gate as it is", "any M, row pitches honoured", "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -6435,6 +6860,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenTimestep), NOTUNE, nullptr, nullptr, r4d_rad_timestep_embed }, +{ "timestep_embed_f32", "timestep_embed", "elem", + "sinusoidal timestep embedding into f32 rows (a timestep MLP kept in f32)", + "any M, row pitches honoured", + "f32 t and out, f32 angles", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenTimestepF32), NOTUNE, + nullptr, nullptr, r4d_rad_timestep_embed }, + { "gather_rows2_bf16", "gather_rows2", "elem", "rows from two sources by a signed index", "any M, row pitches honoured", @@ -6467,6 +6900,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenBf16), NOTUNE, nullptr, nullptr, r4d_rad_randn_lanes }, +{ "randn_lanes_f32", "randn_lanes", "elem", + "a lane's rows from its seed's Philox normal stream, kept in f32 (a sampler's f32 latents)", + "any M, row pitches honoured", + "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_randn_lanes }, + { "flow_euler_bf16", "flow_euler", "elem", "a flow-matching Euler step with guidance, preview and repaint", "any M, row pitches honoured", @@ -6476,13 +6917,21 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_flow_euler }, { "chan_affine_bf16", "chan_affine", "elem", - "a per-channel affine from parameter lists", + "a per-channel affine from parameter lists; `round` 0 keeps the lists and arithmetic f32", "any M, row pitches honoured", "bf16", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenAffine), NOTUNE, nullptr, nullptr, r4d_rad_chan_affine }, +{ "chan_affine_f32", "chan_affine", "elem", + "a per-channel affine from parameter lists over f32 rows (an f32 latent denormalised)", + "any M, row pitches honoured", + "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAffineF32), NOTUNE, + nullptr, nullptr, r4d_rad_chan_affine }, + { "l2norm_chan_bf16", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu: a wave a pixel", "any M, row pitches honoured", @@ -6539,6 +6988,242 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenBf16), NOTUNE, nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap, nullptr, r4d_rad_unrelayout_conv_tap }, + +/* -------------------------------------------------------------------------- audio generation */ +{ "conv1d_bf16", "conv1d", "conv", + "a 1-D convolution over sequences as an implicit GEMM over (tap, cin), the weight tap-major", + "128 rows x 64 or 128 output channels a block, 64 K a stage; cin % 8 != 0 or cout < 16 takes a " + "direct kernel", + "bf16 rows, weight, bias and residual, fp32 accumulate, one rounding; act none, tanh or clamp", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_conv1d, nullptr, r4d_rad_layout_conv1d_tap, + r4d_rad_relayout_conv1d_tap, nullptr, r4d_rad_unrelayout_conv1d_tap }, + +{ "conv1d_f32", "conv1d", "conv", + "a 1-D convolution over sequences in f32 (a vocoder kept in f32): an implicit GEMM over " + "(tap, cin) on the f32 FMA tile, the weight tap-major", + "128 rows x 128, 64 or 32 output channels a block, 16 K a slab; fewer than 16 output channels " + "take a direct kernel; `res` may be the output itself", + "f32 rows, weight, bias and residual, f32 accumulate; act none, tanh or clamp", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_conv1d_f32, nullptr, r4d_rad_layout_conv1d_tap_f32, + r4d_rad_relayout_conv1d_tap_f32, nullptr, r4d_rad_unrelayout_conv1d_tap_f32 }, + +{ "conv_t1d_bf16", "conv_t1d", "conv", + "a transposed 1-D convolution as one implicit GEMM a phase over its one or two taps, the " + "weight phase-major", + "128 input rows x 64 or 128 output channels a block, a grid slice a phase; cin % 8 == 0", + "bf16 rows, weight and bias, fp32 accumulate, one rounding", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_conv_t1d, nullptr, r4d_rad_layout_convt_phase, + r4d_rad_relayout_convt_phase, nullptr, r4d_rad_unrelayout_convt_phase }, + +{ "conv_t1d_f32", "conv_t1d", "conv", + "a transposed 1-D convolution in f32 as one implicit GEMM a phase over ceil(k / stride) taps, " + "the weight phase-major with the taps past k zero", + "any k of at least a stride and any padding; 128 input rows x 128, 64 or 32 output channels a " + "block, a grid slice a phase", + "f32 rows, weight and bias, f32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_conv_t1d_f32, nullptr, r4d_rad_layout_convt_phase_f32, + r4d_rad_relayout_convt_phase_f32, nullptr, r4d_rad_unrelayout_convt_phase_f32 }, + +{ "snake_bf16", "snake", "elem", + "the snake activation per channel", "any M, row pitches honoured", "bf16 rows, f32 alpha", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_snake }, + +{ "cfg_topk_sample", "cfg_topk_sample", "sample", + "a guided top-k pick a lane: radix selects for the conditional and the guided thresholds, ties " + "to the lower index, inverse CDF over the kept entries", + "a workgroup a lane, k <= 256, rep 1 or 2", "f32 or bf16 logits, i32 picks", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAudioAny), NOTUNE, + nullptr, nullptr, r4d_rad_cfg_topk_sample }, + +{ "rvq_embed_bf16", "rvq_embed", "elem", + "a frame's embedding from its residual codes", "a workgroup a row", "bf16 tables and rows", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_rvq_embed }, + +{ "frame_mix_store_bf16", "frame_mix_store", "elem", + "a frame's conditioning row into its lane", "a workgroup a lane, L <= 16", + "bf16 planes and rows, f32 logits and scale", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_frame_mix_store }, + +{ "end_status", "end_status", "elem", + "a frame's status from its first pick", "a thread a lane", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_end_status }, + +{ "frame_store", "frame_store", "elem", + "a frame's codes into its lane's history", "a thread a (lane, code); dst contiguous", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_frame_store }, + +{ "resample_nearest_bf16", "resample_nearest", "elem", + "rows resampled nearest-neighbour", "a workgroup an output row", "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_resample_nearest }, + +{ "fourier_embed_bf16", "fourier_embed", "elem", + "random Fourier features of a time", "a workgroup a row", "f32 time and w, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_fourier_embed }, + +{ "win_input_bf16", "win_input", "elem", + "a denoiser's input rows from the window states", "a workgroup a row", "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_win_input }, + +{ "win_prep_bf16", "win_prep", "elem", + "a window step's noise and overlap binding", "a grid slice an entry", "bf16 states, f32 t", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_win_prep }, + +{ "win_finish_bf16", "win_finish", "elem", + "a window's end and the overlap it hands on", "two kernels: the hand-on, then the join", + "bf16 states", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_win_finish }, + +{ "chan_split_bf16", "chan_split", "elem", + "channel groups to sequences", "any M, row pitches honoured", "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_chan_split }, + +{ "interleave2_bf16", "interleave2", "elem", + "two streams interleaved into stereo samples", "contiguous", "bf16 or f32 in, f32 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAudioAny), NOTUNE, + nullptr, nullptr, r4d_rad_interleave2 }, + +{ "iota", "iota", "elem", + "an arithmetic index sequence", "contiguous i32", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_iota }, + +{ "cu_repeat", "cu_repeat", "elem", + "bounds of equal sequences from a device length", "contiguous i32", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_cu_repeat }, + +{ "attn_dense_small_h256_bf16", "attn_dense", "attn", + "dense attention over short sequences, causal or not: a depth decoder's frame positions", + "head_dim 256, one query head a key head, sequences of at most 32 rows, a workgroup a (sequence, " + "head) with its keys and values in LDS", + "bf16 query / key / value / out, fp32 scores and accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseSmallH256), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_small_h256 }, + +{ "quant_cols_fp8_bf16", "quant_cols_fp8", "quant", + "E4M3 codes with one scale per column over every row: two passes, column maxima over 32 row " + "chunks then the codes", + "n a multiple of 8, a thread eight columns; the chunks' maxima in scratch", + "bf16 in, E4M3 out at its own pitch, f32 scale per column", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQuantCols), NOTUNE, + nullptr, nullptr, r4d_rad_quant_cols_fp8, r4d_rad_quant_cols_fp8_scratch }, + +{ "vsa_select_h128_bf16", "vsa_select", "attn", + "video sparse attention's tile selection: f32 tile means of q, k (and v), f32 tile scores, the " + "top k video tiles of each video query tile ascending, and the coarse softmax over the tiles " + "times the v means", + "head_dim 128, 4 x 4 x 4 tiles, at most 3072 tiles; the k and v means of a group of heads in " + "scratch, eight (four above 1536 tiles) query tiles a workgroup", + "bf16 q / k / v / coarse, i32 segs / geom / sel; f32 means, scores and softmax", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cVsa), NOTUNE, + nullptr, nullptr, r4d_rad_vsa_select, r4d_rad_vsa_select_scratch }, + +{ "attn_vsa_h128_bf16", "attn_vsa", "attn", + "block-sparse attention over the selected 64-row tiles, with the gated coarse term", + "head_dim 128, 4 x 4 x 4 tiles, a workgroup two query tiles of one head walking the merge of " + "their key tiles, each tile's rows computed from the geometry; the int8 Q.K form (k_i8 / " + "k_scale)", + "bf16 q / k / v / coarse / gate / out, i32 segs / geom / sel; bf16 operands, fp32 accumulate; " + "or i8 Q.K codes, i32 accumulate; or E4M3 V codes and P, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cVsa), NOTUNE, + nullptr, nullptr, r4d_rad_attn_vsa }, + +{ "rms_mod_bf16", "rms_mod", "norm", + "gated residual and modulated RMS norm in one pass: a workgroup a row", + "n % 8 == 0, n <= 8192; s a column slice at its own pitch", + "bf16 rows, gain and table, fp32 sum of squares", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRmsMod), NOTUNE, + nullptr, nullptr, r4d_rad_rms_mod }, + +{ "rms_mod_quant_fp8_bf16", "rms_mod_quant_fp8", "norm", + "gated residual, modulated RMS norm and quant_act_fp8 in one pass: a workgroup a row", + "n % 128 == 0, n <= 8192, group 128; s a column slice at its own pitch", + "bf16 rows, gain and table, E4M3 codes and f32 scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRmsModQ), NOTUNE, + nullptr, nullptr, r4d_rad_rms_mod_quant_fp8 }, + +{ "flow_x0_step_f32", "flow_x0_step", "elem", + "a sampler step toward the clean estimate", "any M, row pitches honoured", + "f32 state, f32 or bf16 velocity", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenF32), NOTUNE, + nullptr, nullptr, r4d_rad_flow_x0_step }, + +{ "patch_unfold_f32", "patch_unfold", "elem", + "patch rows to denormalised voxel rows, the geometry read on the device", + "C <= 64, row pitches honoured", "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cPatchUnfold), NOTUNE, + nullptr, nullptr, r4d_rad_patch_unfold }, + +{ "vtile_gather", "vtile_gather", "elem", + "a video decoder's tiles out of the latent, the tile layout from the device geometry: a " + "workgroup a tile row", + "row pitches honoured", "bf16 or f32 rows and registers", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_vtile_gather }, + +{ "vtile_stitch", "vtile_stitch", "elem", + "decoded tiles blended into frames and the chunk overlap: a thread a (pixel, colour) over the " + "chunk's frames", + "row pitches honoured", "bf16 or f32 tiles and overlap, u8 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_vtile_stitch }, + +{ "grid_pos3", "grid_pos3", "elem", + "a video decoder's rotary positions over its tiles", "a [3, M] view at its own pitch", "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_grid_pos3 }, + +{ "snake_aa_f32", "snake_aa", "elem", + "the alias-free SnakeBeta: a thread an output, its activations recomputed per output", + "k <= 32, row pitches honoured", "f32 rows, filters, alpha and beta", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cSnakeAa), NOTUNE, + nullptr, nullptr, r4d_rad_snake_aa }, }; /* ================================================================================== the exports */ @@ -6675,10 +7360,9 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { * at init, one per declared op and band). Concurrent launches never share these, so those three * rows are concurrent. A new row with stream-ordered state belongs in the list above. * - * lora_* no state of their own, and ordered ON PURPOSE: the core appends them - * behind the GEMM whose `y` they update and refills the pools they read - * between steps with its own copies, so they are kept out of the replay's - * overlap analysis rather than leaning on it. */ + * lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they + * update and refills the pools they read between steps with its own copies, + * so they stay out of the replay's overlap analysis. */ extern "C" int rad_kernel_concurrent(int i) { const RadKernelInfo* k = rad_kernel_at(i); if (!k) return 0; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index be81fcd2..26c2907c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -38,6 +38,9 @@ #include "r4d_hc_fp8.h" #include "r4d_fp8_frag.h" #include "r4d_fp8_lm.h" +#include "rad_encoding.h" +#include "rad_philox.h" +#include "rad_yarn.h" #include #include @@ -1052,10 +1055,10 @@ struct PartCut { /* An asymmetric grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16 * scale and a u8 zero point 0 .. 2^bits - 1 per 128 of K, drawn from st_mix32 of the * coordinates. */ -static Planes asym_planes(int bits, int64_t N, int64_t K) { +static Planes asym_planes(int bits, int64_t N, int64_t K, uint32_t zdt = RAD_U8) { Planes p; p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); - rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + rad_enc_add_plane(&p.enc, "zero", zdt, 1, 128); p.size(N, K); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic), G = K / 128; @@ -1067,12 +1070,18 @@ static Planes asym_planes(int bits, int64_t N, int64_t K) { for (int64_t g = 0; g < G; ++g) { const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); - p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) & top); + rad_store_code(p.data[(size_t)iz].data() + n * p.row_bytes(iz), zdt, g, + (int)((h >> 8) & top)); } } return p; } +/* Row n's zero point in group g of asym_planes' zero plane, whatever its width. */ +static double zero_at(const Planes& p, int iz, int64_t n, int64_t g) { + return rad_load_f32(p.data[(size_t)iz].data() + n * p.row_bytes(iz), p.enc.plane[iz].dtype, g); +} + /* The unnormalised Sylvester Walsh-Hadamard transform of `n` values, in place: (a + b) to the lower * index and (a - b) to the upper, the transform an "fwhtN" encoding names. H_n H_n = n I. */ static void h_fwht(float* v, int64_t n) { @@ -3945,26 +3954,27 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in } -/* ParoQuant's 5-bit skinny GEMM against the planes' meaning: u5 codes (a bit stream along K), an - * f16 scale and a zero point 0..31 per 128 of K, an f16 activation, the weight stored through the - * row's hooks. `pb1`/`pb2` give a partitioned weight. M past 64 runs the dispatcher's 64-row - * chunks. */ +/* The 5-bit skinny GEMM (ParoQuant's int5) and its 4-bit sibling w4a16_asym against the planes' + * meaning: u5 or u4 codes (a bit stream along K), an f16 scale and a zero point per 128 of K (of + * dtype `zdt`), an f16 activation, the weight stored through the row's hooks. `pb1`/`pb2` give a + * partitioned weight. M past 64 runs the dispatcher's 64-row chunks. */ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, - int64_t pb2 = 0) { - const char* row = "gemm_w5a16_nt_m64"; + int64_t pb2 = 0, int bits = 5, uint32_t zdt = RAD_U8) { + const char* row = bits == 5 ? "gemm_w5a16_nt_m64" : "gemm_w4a16_asym_nt_m64"; + const char* dtype = bits == 5 ? "w5a16" : "w4a16_asym"; if (!sel(row)) return; const PartCut cut(N, pb1, pb2); const int parts = cut.parts; char nm[160]; - std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, - (long long)N, (long long)K, parts); + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d zero %s", row, + (long long)M, (long long)N, (long long)K, parts, rad_dtype_name(zdt)); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - const Planes p = asym_planes(5, N, K); + const Planes p = asym_planes(bits, N, K, zdt); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); - std::vector lp = { PI("N", N), PI("K", K), PI("group", 128) }; + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", dtype) }; std::vector wq, ws; const int rw = stored(r, lp, 2, p, { "codes" }, &wq); const int rs = stored(r, lp, 3, p, { "scale", "zero" }, &ws); @@ -3998,7 +4008,7 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int }; absent(ts[1]); absent(ts[5]); absent(ts[6]); std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), - PS("dtype", "w5a16") }; + PS("dtype", dtype) }; if (pb1) ps.push_back(PI("pb1", pb1)); if (pb2) ps.push_back(PI("pb2", pb2)); RadArgs a; @@ -4016,8 +4026,9 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int const int pt = cut.part_of(n); double acc = 0; for (int64_t k = 0; k < K; ++k) { - const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, RAD_U5, k); - const double z = p.data[(size_t)iz][(size_t)(n * G + k / 128)]; + const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, + p.enc.plane[ic].dtype, k); + const double z = zero_at(p, iz, n, k / 128); const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + k / 128); acc += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z) * sc; } @@ -4121,18 +4132,18 @@ static void w5a16_perf(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t * scale and a u8 zero per 128 of K, an int8 activation with an f32 scale per (row, 128), parts * side by side. */ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, - int64_t pb2 = 0) { + int64_t pb2 = 0, uint32_t zdt = RAD_U8) { const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; if (!sel(row)) return; const PartCut cut(N, pb1, pb2); const int parts = cut.parts; char nm[160]; - std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, - (long long)N, (long long)K, parts); + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d zero %s", row, + (long long)M, (long long)N, (long long)K, parts, rad_dtype_name(zdt)); const RadKernelInfo* r = find(pl, row); if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } const int64_t G = K / 128; - const Planes p = asym_planes(bits, N, K); + const Planes p = asym_planes(bits, N, K, zdt); const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); const int64_t rb = p.row_bytes(ic); std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; @@ -4196,7 +4207,7 @@ static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int double acc = 0; for (int64_t g = 0; g < G; ++g) { double grp = 0; - const double z = p.data[(size_t)iz][(size_t)(n * G + g)]; + const double z = zero_at(p, iz, n, g); const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g); for (int64_t k = g * 128; k < (g + 1) * 128; ++k) { const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k); @@ -4409,6 +4420,96 @@ static void mxd_overlap_case(const Plugin& pl) { "rc=" + std::to_string(rc)); } +/* gemm_nt_bias at bf16 against an f64 product over the bf16 values the kernel reads, rounded as + * libref rounds: the biased product, the activation, the residual, each to bf16. The shapes reach + * the 128 x 128 kernel (32 blocks or more) through its edges: a K tail past whole 64-element tiles + * (or K below one tile), N past whole 128-row tiles and not a multiple of 8 (the per-element + * store), the residual read from the output it overwrites, and a bf16 bias. The tolerance is two + * bf16 steps of the element or of the product before its residual (the f32 accumulation order is + * the kernel's own) and a rel_l2 of 4e-3 over the tensor. */ +static void bias_gemm_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int act, + bool res, bool bias_f32) { + if (!sel("gemm_bf16_nt_bias_tiled")) return; + char nm[192]; + static const char* acts[] = { "none", "gelu", "gelu_tanh" }; + std::snprintf(nm, sizeof nm, "gemm_bf16_nt_bias_tiled numeric M=%lld N=%lld K=%lld act=%s%s%s", + (long long)M, (long long)N, (long long)K, acts[act], res ? " res=out" : "", + bias_f32 ? "" : " bias=bf16"); + const RadKernelInfo* r = find(pl, "gemm_bf16_nt_bias_tiled"); + if (!r) { ok(nm, false, "row absent"); return; } + std::vector ha((size_t)(M * K)), hw((size_t)(N * K)), hr((size_t)(M * N)); + for (size_t i = 0; i < ha.size(); ++i) ha[i] = st_rand_bf16((uint32_t)i); + for (size_t i = 0; i < hw.size(); ++i) hw[i] = h_to_bf16(0.25f * h_bf16(st_rand_bf16((uint32_t)i + 0x5bd1e995u))); + for (size_t i = 0; i < hr.size(); ++i) hr[i] = st_rand_bf16((uint32_t)i + 0x27d4eb2fu); + std::vector hb((size_t)N); + for (int64_t n = 0; n < N; ++n) hb[(size_t)n] = h_bf16(st_rand_bf16((uint32_t)n + 77u)); + std::vector hb16((size_t)N); + for (int64_t n = 0; n < N; ++n) hb16[(size_t)n] = h_to_bf16(hb[(size_t)n]); + + void* d_a = dalloc(ha.size() * 2); + void* d_w = dalloc(hw.size() * 2); + void* d_b = dalloc((size_t)N * 4); + void* d_y = dalloc((size_t)(M * N) * 2); + if (!d_a || !d_w || !d_b || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_a, ha.data(), ha.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_w, hw.data(), hw.size() * 2, hipMemcpyHostToDevice); + if (bias_f32) st_memcpy(d_b, hb.data(), (size_t)N * 4, hipMemcpyHostToDevice); + else st_memcpy(d_b, hb16.data(), (size_t)N * 2, hipMemcpyHostToDevice); + st_memcpy(d_y, hr.data(), hr.size() * 2, hipMemcpyHostToDevice); + + RadTensor tr = T(d_y, RAD_BF16, { M, N }); + if (!res) absent(tr); + std::vector ts = { T(d_a, RAD_BF16, { M, K }), T(d_w, RAD_BF16, { N, K }), + T(d_b, bias_f32 ? RAD_F32 : RAD_BF16, { N }), tr, + T(d_y, RAD_BF16, { M, N }) }; + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16"), + PS("act", acts[act]) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc " + std::to_string(rc)); return; } + std::vector got((size_t)(M * N)); + st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); + + std::vector af(ha.size()), wf(hw.size()); + for (size_t i = 0; i < ha.size(); ++i) af[i] = h_bf16(ha[i]); + for (size_t i = 0; i < hw.size(); ++i) wf[i] = h_bf16(hw[i]); + double e2 = 0.0, r2 = 0.0; + int64_t bad = 0; + std::string first; + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N; ++n) { + double s = 0.0; + const float* ar = &af[(size_t)(m * K)]; + const float* wr = &wf[(size_t)(n * K)]; + for (int64_t k = 0; k < K; ++k) s += (double)ar[k] * (double)wr[k]; + float t = h_bf16(h_to_bf16((float)s + hb[(size_t)n])); + if (act == 1) t = h_bf16(h_to_bf16((float)(0.5 * t * (1.0 + std::erf(t * 0.70710678118654752))))); + if (act == 2) t = h_bf16(h_to_bf16((float)(0.5 * t * (1.0 + std::tanh(0.7978845608028654 * + (t + 0.044715 * t * t * t)))))); + /* A step of the product before the residual add carries through it unchanged, so the + * bound scales with the larger of the two. */ + const float u = t; + if (res) t = h_bf16(h_to_bf16(h_bf16(hr[(size_t)(m * N + n)]) + t)); + const float g = h_bf16(got[(size_t)(m * N + n)]); + const double d = (double)g - (double)t; + e2 += d * d; + r2 += (double)t * t; + if (!(std::fabs(d) <= std::ldexp(std::max(std::fabs(t), std::fabs(u)), -6) + 1e-3)) { + if (!bad++) first = "m " + std::to_string(m) + " n " + std::to_string(n) + ": " + + std::to_string(g) + " vs " + std::to_string(t); + } + } + const double rel = std::sqrt(e2 / (r2 > 0 ? r2 : 1.0)); + ok(nm, bad == 0 && rel < 4e-3, + "rel_l2 " + std::to_string(rel) + ", " + std::to_string(bad) + " outside" + + (bad ? " (first " + first + ")" : std::string())); + dfree_all(); +} + /* The int8 trunk chain: quant_act_i8g on a bf16 activation, then an i8a8 GEMM on its output, * against the planes' meaning. The weight is i8 with a bf16 scale per row per 128 K (libquant's * `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's hooks. The reference uses @@ -4984,6 +5085,3032 @@ static int launch_row(const RadKernelInfo* r, std::vector ts, return st_stream_sync(nullptr) == hipSuccess ? RAD_OK : RAD_E_STATE; } +/* ---- the audio generator's ops and their optional forms, against libref's arithmetic ---------- + * + * Each case builds its operands on the host, runs the row, and compares with the host port of the + * libref function (libref/ref_audio.cpp, ref_elementwise.cpp, ref_attn.cpp) over the same bf16 + * inputs. Picks, ids and the history are compared exactly; a sum the kernel orders differently is + * held to a relative L2 against the answer rounded to bf16. */ +namespace au { + +uint64_t g_seed = 0xa0d10ull; +float rnd() { + g_seed = g_seed * 6364136223846793005ull + 1442695040888963407ull; + return (float)((int64_t)(g_seed >> 40) % 2001 - 1000) / 1000.0f; +} +std::vector randv(size_t n, float scale) { + std::vector v(n); + for (auto& x : v) x = rnd() * scale; + return v; +} +float bfr(float v) { return h_bf16(h_to_bf16(v)); } + +/* An operand allocated (zeroed): a launch refuses a null operand before reading its shape. */ +RadTensor TA(uint32_t dt, std::vector shape) { + RadTensor t = T(nullptr, dt, std::move(shape)); + t.data = alloc_for(t); + return t; +} + +/* bf16 on the device; the host copy is rounded in place to what the device holds. */ +void* up_bf16(std::vector& h) { + std::vector b(h.size()); + for (size_t i = 0; i < h.size(); ++i) { b[i] = h_to_bf16(h[i]); h[i] = h_bf16(b[i]); } + void* d = dalloc(b.size() * 2); + if (d) st_memcpy(d, b.data(), b.size() * 2, hipMemcpyHostToDevice); + return d; +} +void* up_f32(const std::vector& h) { + void* d = dalloc(h.size() * 4); + if (d) st_memcpy(d, h.data(), h.size() * 4, hipMemcpyHostToDevice); + return d; +} +void* up_i32(const std::vector& h) { + void* d = dalloc(h.size() * 4); + if (d) st_memcpy(d, h.data(), h.size() * 4, hipMemcpyHostToDevice); + return d; +} +std::vector down_bf16(void* d, size_t n) { + std::vector b(n); + st_memcpy(b.data(), d, n * 2, hipMemcpyDeviceToHost); + std::vector f(n); + for (size_t i = 0; i < n; ++i) f[i] = h_bf16(b[i]); + return f; +} +std::vector down_f32(void* d, size_t n) { + std::vector f(n); + st_memcpy(f.data(), d, n * 4, hipMemcpyDeviceToHost); + return f; +} +std::vector down_i32(void* d, size_t n) { + std::vector f(n); + st_memcpy(f.data(), d, n * 4, hipMemcpyDeviceToHost); + return f; +} +double rel(const std::vector& got, const std::vector& want) { + double e = 0, r = 0; + for (size_t i = 0; i < want.size(); ++i) { + const double w = bfr(want[i]); + e += (got[i] - w) * (got[i] - w); + r += w * w; + } + return r > 0 ? std::sqrt(e / r) : std::sqrt(e); +} +void check(const std::string& name, const std::vector& got, const std::vector& want, + double tol) { + const double r = rel(got, want); + ok(fmt("%s (rel_l2 %.3g, bound %.3g)", name.c_str(), r, tol).c_str(), r <= tol); +} +/* Elements that differ bit for bit. */ +template int64_t differ(const V& a, const V& b) { + int64_t n = 0; + for (size_t i = 0; i < a.size() && i < b.size(); ++i) + if (std::memcmp(&a[i], &b[i], sizeof(a[i])) != 0) ++n; + return n + (int64_t)(a.size() > b.size() ? a.size() - b.size() : b.size() - a.size()); +} +int launch(const RadKernelInfo* r, std::vector ts, std::vector ps) { + return launch_row(r, std::move(ts), std::move(ps)); +} + +/* A conv weight as the row stores it: through its relayout hook from PyTorch's layout. */ +void* stored_weight(const RadKernelInfo* r, const std::vector& lp, + const std::vector& w, int64_t rows, int64_t cols, const char* what) { + Planes p; + p.enc = rad_enc_plain(RAD_BF16); + p.rows = { rows }; + p.cols = { cols }; + p.data.assign(1, std::vector(w.size() * 2)); + for (size_t i = 0; i < w.size(); ++i) { + const uint16_t b = h_to_bf16(w[i]); + std::memcpy(p.data[0].data() + 2 * i, &b, 2); + } + std::vector blob; + const int rc = stored(r, lp, 1, p, { "codes" }, &blob); + if (rc != RAD_OK && rc != RAD_E_UNSUPPORTED) { + ok(what, false, "relayout rc " + std::to_string(rc)); + return nullptr; + } + void* d = dalloc(blob.size()); + if (d) st_memcpy(d, blob.data(), blob.size(), hipMemcpyHostToDevice); + return d; +} + +/* The sequence holding row r of `cu`. */ +int64_t seq_of(const std::vector& cu, int64_t r) { + int64_t s = 0; + while (s + 2 < (int64_t)cu.size() && cu[(size_t)s + 1] <= r) ++s; + return s; +} + +/* conv1d: the causal form beside the symmetric one, on the tiled and the direct kernels. */ +void conv1d_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv1d_bf16"); + if (!r) { ok("conv1d_bf16", false, "row absent"); return; } + struct C { int64_t cin, cout, k, dil; int causal, extras; }; + for (const C& c : { C{ 16, 32, 3, 2, 0, 0 }, C{ 16, 32, 3, 2, 1, 1 }, C{ 16, 128, 4, 1, 1, 0 }, + C{ 6, 3, 7, 3, 1, 1 }, C{ 6, 3, 2, 1, 1, 0 } }) { + const std::vector cu = { 0, 13, 30 }; + const int64_t M = 30; + std::vector x = randv((size_t)(M * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cout * c.cin * c.k), 0.3f); + std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f); + void* dx = up_bf16(x); + void* db = up_bf16(b); + void* dres = up_bf16(res); + for (auto& v : w) v = bfr(v); + std::vector ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout), + PI("k", c.k), PI("dil", c.dil), PS("act", c.extras ? "tanh" : "none"), + PS("dtype", "bf16"), PI("causal", c.causal) }; + const std::string nm = fmt("conv1d_bf16 cin %lld cout %lld k %lld dil %lld causal %d%s", + (long long)c.cin, (long long)c.cout, (long long)c.k, + (long long)c.dil, c.causal, c.extras ? " +bias+res+tanh" : ""); + void* dw = stored_weight(r, ps, w, c.cout, c.cin * c.k, nm.c_str()); + void* dcu = up_i32(cu); + void* dy = dalloc((size_t)(M * c.cout) * 2); + if (!dw) continue; + RadTensor tres = T(dres, RAD_BF16, { M, c.cout }), tb = T(db, RAD_BF16, { c.cout }); + if (!c.extras) { absent(tres); absent(tb); } + const int rc = launch(r, { T(dx, RAD_BF16, { M, c.cin }), T(dw, RAD_BF16, { c.cout, c.cin, c.k }), + T(dcu, RAD_I32, { 3 }), tres, T(dy, RAD_BF16, { M, c.cout }), tb }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t pad = c.causal ? c.dil * (c.k - 1) : c.dil * (c.k - 1) / 2; + std::vector want((size_t)(M * c.cout)); + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; + for (int64_t co = 0; co < c.cout; ++co) { + float acc = 0.0f; + for (int64_t kk = 0; kk < c.k; ++kk) { + const int64_t ir = row + kk * c.dil - pad; + if (ir < s0 || ir >= s1) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)]; + } + if (c.extras) { + acc += b[(size_t)co]; + acc += res[(size_t)(row * c.cout + co)]; + acc = std::tanh(acc); + } + want[(size_t)(row * c.cout + co)] = acc; + } + } + check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2); + } + /* An even kernel is causal only. */ + std::vector ps = { PI("M", 4), PI("cin", 8), PI("cout", 16), PI("k", 4), PI("dil", 1), + PS("dtype", "bf16") }; + const int rc = launch(r, { TA(RAD_BF16, { 4, 8 }), TA(RAD_BF16, { 16, 8, 4 }), + TI32({ 2 }, { 0, 4 }), TA(RAD_BF16, { 4, 16 }), + TA(RAD_BF16, { 4, 16 }), TA(RAD_BF16, { 16 }) }, + ps); + ok("conv1d_bf16 refuses an even symmetric kernel", rc == RAD_E_SHAPE, + "rc " + std::to_string(rc)); +} + +/* conv_t1d: kernel 2 stride or stride, any padding below stride, an odd stride. */ +void conv_t1d_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv_t1d_bf16"); + if (!r) { ok("conv_t1d_bf16", false, "row absent"); return; } + struct C { int64_t cin, cout, s, k, pad; }; /* pad -1: absent */ + for (const C& c : { C{ 16, 32, 2, 4, -1 }, C{ 16, 32, 8, 16, -1 }, C{ 16, 32, 5, 10, 0 }, + C{ 16, 128, 3, 6, 0 }, C{ 16, 32, 2, 2, 0 }, C{ 16, 32, 2, 2, -1 }, + C{ 16, 32, 4, 8, 1 } }) { + const std::vector cu = { 0, 5, 12 }; + const int64_t R = 12, O = R * c.s; + std::vector x = randv((size_t)(R * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cin * c.cout * c.k), 0.3f); + std::vector b = randv((size_t)c.cout, 0.5f); + void* dx = up_bf16(x); + void* db = up_bf16(b); + for (auto& v : w) v = bfr(v); + std::vector ps = { PI("M", R), PI("cin", c.cin), PI("cout", c.cout), + PI("stride", c.s), PS("dtype", "bf16"), PI("k", c.k) }; + if (c.pad >= 0) ps.push_back(PI("pad", c.pad)); + const std::string nm = fmt("conv_t1d_bf16 stride %lld k %lld pad %lld cout %lld", + (long long)c.s, (long long)c.k, (long long)c.pad, + (long long)c.cout); + void* dw = stored_weight(r, ps, w, c.cin, c.cout * c.k, nm.c_str()); + void* dcu = up_i32(cu); + void* dy = dalloc((size_t)(O * c.cout) * 2); + if (!dw) continue; + const int rc = launch(r, { T(dx, RAD_BF16, { R, c.cin }), T(dw, RAD_BF16, { c.cin, c.cout, c.k }), + T(db, RAD_BF16, { c.cout }), T(dcu, RAD_I32, { 3 }), + T(dy, RAD_BF16, { O, c.cout }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t P = c.pad >= 0 ? c.pad : (c.k - c.s) / 2, taps = c.k / c.s; + std::vector want((size_t)(O * c.cout)); + for (int64_t o = 0; o < O; ++o) { + const int64_t e = seq_of(cu, o / c.s), i0 = cu[(size_t)e], i1 = cu[(size_t)e + 1]; + const int64_t lo = o - i0 * c.s, q = (lo + P) / c.s, rr = (lo + P) % c.s; + for (int64_t co = 0; co < c.cout; ++co) { + float acc = b[(size_t)co]; + for (int64_t t = 0; t < taps; ++t) { + const int64_t qi = q - t, tap = rr + t * c.s; + if (qi < 0 || i0 + qi >= i1) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += w[(size_t)((ci * c.cout + co) * c.k + tap)] * + x[(size_t)((i0 + qi) * c.cin + ci)]; + } + want[(size_t)(o * c.cout + co)] = acc; + } + } + check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2); + } + /* A kernel neither stride nor 2 stride, a symmetric default the kernel cannot centre, a pad + * of a whole stride. */ + struct Bad { int64_t s, k, pad; }; + for (const Bad& c : { Bad{ 4, 12, 0 }, Bad{ 3, 6, -1 }, Bad{ 2, 4, 2 } }) { + std::vector ps = { PI("M", 4), PI("cin", 8), PI("cout", 16), PI("stride", c.s), + PS("dtype", "bf16"), PI("k", c.k) }; + if (c.pad >= 0) ps.push_back(PI("pad", c.pad)); + const int rc = launch(r, { TA(RAD_BF16, { 4, 8 }), TA(RAD_BF16, { 8, 16, c.k }), + TA(RAD_BF16, { 16 }), TI32({ 2 }, { 0, 4 }), + TA(RAD_BF16, { 4 * c.s, 16 }) }, + ps); + ok(fmt("conv_t1d_bf16 refuses stride %lld k %lld pad %lld", (long long)c.s, + (long long)c.k, (long long)c.pad).c_str(), rc == RAD_E_SHAPE, "rc " + std::to_string(rc)); + } +} + +/* snake: alpha alone, SnakeBeta, and both stored as logarithms. */ +void snake_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "snake_bf16"); + if (!r) { ok("snake_bf16", false, "row absent"); return; } + const int64_t M = 9, n = 192; + for (int form = 0; form < 3; ++form) { + std::vector x = randv((size_t)(M * n), 3.0f); + std::vector al(n), be(n); + for (int64_t c = 0; c < n; ++c) { + al[(size_t)c] = form == 2 ? rnd() * 0.7f : 0.2f + 0.8f * std::fabs(rnd()); + be[(size_t)c] = form == 2 ? rnd() * 0.7f : 0.2f + 0.8f * std::fabs(rnd()); + } + void* dx = up_bf16(x); + void* da = up_f32(al); + void* dbe = up_f32(be); + void* dy = dalloc((size_t)(M * n) * 2); + RadTensor tb = T(dbe, RAD_F32, { n }); + if (form == 0) absent(tb); + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") }; + if (form == 2) ps.push_back(PI("log", 1)); + const char* tag = form == 0 ? "alpha" : form == 1 ? "beta" : "log alpha, log beta"; + const int rc = launch(r, { T(dx, RAD_BF16, { M, n }), T(da, RAD_F32, { n }), + T(dy, RAD_BF16, { M, n }), tb }, ps); + if (rc != RAD_OK) { ok(fmt("snake_bf16 %s", tag).c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t rr = 0; rr < M; ++rr) + for (int64_t c = 0; c < n; ++c) { + const float v = x[(size_t)(rr * n + c)]; + const float a = form == 2 ? (float)std::exp((double)al[(size_t)c]) : al[(size_t)c]; + const float sn = (float)std::sin((double)(v * a)); + if (form == 0) { + want[(size_t)(rr * n + c)] = v + sn * sn / (a + 1e-9f); + } else { + const float bb = form == 2 ? (float)std::exp((double)be[(size_t)c]) : be[(size_t)c]; + want[(size_t)(rr * n + c)] = v + 1.0f / (bb + 1e-9f) * (sn * sn); + } + } + check(fmt("snake_bf16 %s numerics", tag), down_bf16(dy, want.size()), want, 3e-3); + } +} + +/* ref_cfg_topk_sample's rule on the host, for one lane, over f32 logits. */ +int ref_pick(const std::vector& lg, int64_t V, int64_t lane_row, int rep, float cfg, + int64_t K, int64_t cond_k, float temp, int64_t sup_lo, int64_t sup_hi, float pen, + std::vector* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream) { + std::vector c((size_t)V), g((size_t)V); + for (int64_t j = 0; j < V; ++j) c[(size_t)j] = lg[(size_t)(rep * lane_row * V + j)]; + if (rep == 2) { + for (int64_t j = 0; j < V; ++j) { + const float u = lg[(size_t)((rep * lane_row + 1) * V + j)]; + g[(size_t)j] = u + cfg * (c[(size_t)j] - u); + } + } else { + g = c; + } + if (hist && hb >= 0) { + if (frame == 0) + for (int64_t j = 0; j < V; ++j) (*hist)[(size_t)(hb + j)] = 0; + for (int64_t j = 0; j < V; ++j) + if ((*hist)[(size_t)(hb + j)] != 0) { + float& v = g[(size_t)j]; + v = v > 0.0f ? v / pen : v * pen; + } + } + std::vector idx; + auto open = [&](int64_t j) { return j < sup_lo || j >= sup_hi; }; + if (cond_k > 0) { + std::vector cc = c; + std::nth_element(cc.begin(), cc.begin() + (cond_k - 1), cc.end(), std::greater()); + const float thr = cc[(size_t)(cond_k - 1)]; + for (int64_t j = 0; j < V; ++j) + if (c[(size_t)j] >= thr && open(j)) idx.push_back(j); + } else { + for (int64_t j = 0; j < V; ++j) + if (open(j)) idx.push_back(j); + } + if (idx.empty()) return -1; + const int64_t kk = std::min(K, (int64_t)idx.size()); + std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int64_t p, int64_t q) { + return g[(size_t)p] > g[(size_t)q] || (g[(size_t)p] == g[(size_t)q] && p < q); + }); + const float m = g[(size_t)idx[0]] / temp; + double tot = 0; + std::vector e((size_t)kk); + for (int64_t t = 0; t < kk; ++t) { + e[(size_t)t] = std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)); + tot += e[(size_t)t]; + } + const double u = (double)rad_philox_uniform_s(seed, ((uint64_t)1 << 32) + (uint64_t)frame, + stream) * tot; + int64_t pick = idx[(size_t)(kk - 1)]; + double acc = 0; + for (int64_t t = 0; t < kk; ++t) { + acc += e[(size_t)t]; + if (u < acc) { pick = idx[(size_t)t]; break; } + } + if (hist && hb >= 0) (*hist)[(size_t)(hb + pick)] = 1; + return (int)pick; +} + +/* cfg_topk_sample with every optional form: per-lane guidance, the repetition penalty over a + * lane's history across three frames (the first clearing it), suppressed ids, a temperature that + * libref divides by. The picks and the history must equal the host rule's exactly. */ +void cfg_topk_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "cfg_topk_sample"); + if (!r) { ok("cfg_topk_sample", false, "row absent"); return; } + struct C { int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp; }; + for (const C& c : { C{ 2052, 2, true, true, 2048, 2051, 0, 0.9f }, + C{ 2051, 1, true, false, 2048, 2051, 0, 0.9f }, + C{ 2051, 2, false, true, 2048, 2051, 0, 0.9f }, + C{ 16385, 2, false, false, 0, 0, 50, 1.0f } }) { + const int64_t n = 3, lanes = 4, K = 50; + const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld", + (long long)c.V, c.rep, c.hist ? " hist" : "", + c.cfgs ? " per-lane cfg" : "", (long long)c.sup_lo, + (long long)c.sup_hi, (long long)c.cond_k); + std::vector lane = { 2, 0, 3 }; + std::vector cfgv = { 1.0f, 3.0f, 4.0f }; + std::vector seed = { 7u, 0u, 0x9e3779b9u, 1u, 0xdeadbeefu, 0x12345u }; + /* The history starts with stale marks, which frame 0 must clear. */ + std::vector hist((size_t)(lanes * c.V), 0); + for (size_t i = 0; i < hist.size(); i += 7) hist[i] = 1; + void* dlane = up_i32(lane); + void* dcfg = up_f32(cfgv); + void* dseed = dalloc(seed.size() * 4); + if (dseed) st_memcpy(dseed, seed.data(), seed.size() * 4, hipMemcpyHostToDevice); + void* dhist = up_i32(hist); + void* dids = dalloc((size_t)(c.rep * n) * 4); + int64_t wrong = 0, hist_wrong = 0; + /* Frames 1 and 2 over the stale history (every seventh id penalised), then frame 0, which + * clears it, then frame 1 over the picks since. */ + for (const int32_t f : { 1, 2, 0, 1 }) { + /* Logits with a spread wide enough that the penalty and the temperature move picks, + * and repeated values so that ties are cut by index. */ + std::vector lg((size_t)(c.rep * n * c.V)); + for (size_t i = 0; i < lg.size(); ++i) { + const float v = rnd() * 6.0f; + lg[i] = (i % 97 == 0) ? 5.95f : v; + } + void* dlg = up_f32(lg); + std::vector frame((size_t)n, f); + void* dfr = up_i32(frame); + RadTensor tcfg = T(dcfg, RAD_F32, { n }), tlane = T(dlane, RAD_I32, { n }); + RadTensor thist = T(dhist, RAD_I32, { lanes, c.V }); + if (!c.cfgs) absent(tcfg); + if (!c.hist) { absent(tlane); absent(thist); } + std::vector ps = { PI("M", c.rep * n), PI("n_vocab", c.V), PI("k", K), + PI("rep", c.rep), PI("cond_k", c.cond_k), PF("cfg", 1.5), + PF("temp", c.temp), PI("stream", 3), PS("dtype", "f32"), + PI("sup_lo", c.sup_lo), PI("sup_hi", c.sup_hi), + PF("penalty", 1.1) }; + const int rc = launch(r, { T(dlg, RAD_F32, { c.rep * n, c.V }), T(dseed, RAD_U32, { n, 2 }), + T(dfr, RAD_I32, { n }), T(dids, RAD_I32, { c.rep * n }), tcfg, + tlane, thist }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const std::vector got = down_i32(dids, (size_t)(c.rep * n)); + for (int64_t i = 0; i < n; ++i) { + const uint64_t sd = (uint64_t)seed[(size_t)(2 * i)] | + ((uint64_t)seed[(size_t)(2 * i + 1)] << 32); + const int want = ref_pick(lg, c.V, i, c.rep, c.cfgs ? cfgv[(size_t)i] : 1.5f, K, + c.cond_k, c.temp, c.sup_lo, c.sup_hi, 1.1f, + c.hist ? &hist : nullptr, + c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3); + for (int t = 0; t < c.rep; ++t) + if (got[(size_t)(c.rep * i + t)] != want) ++wrong; + } + if (c.hist) hist_wrong += differ(down_i32(dhist, hist.size()), hist); + } + ok((nm + " picks").c_str(), wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong, + (long long)(4 * c.rep * n))); + if (c.hist) + ok((nm + " history").c_str(), hist_wrong == 0, + fmt("%lld history entries differ", (long long)hist_wrong)); + } +} + +/* rvq_embed: libref's two roundings, the single rounding over bf16 and f32 tables into a bf16 or + * f32 row, codes read as a block of a wider frame-major history (strides other than the dense + * plane's), and a first code outside its table leaving the row unwritten. Exact. */ +void rvq_embed_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "rvq_embed_bf16"); + if (!r) { ok("rvq_embed_bf16", false, "row absent"); return; } + const int64_t D = 96, K = 5, voc = 11, off0 = 3, rows = 6, lanes = 2, stride = 9; + struct C { int round1; bool f32tab, f32y, block; }; + for (const C& c : { C{ 0, false, false, false }, C{ 1, false, false, false }, + C{ 1, true, true, true }, C{ 1, false, true, true } }) { + std::vector t0 = randv((size_t)((voc + off0) * D), 1.0f); + std::vector t1 = randv((size_t)((K - 1) * voc * D), 1.0f); + void* d0 = c.f32tab ? up_f32(t0) : up_bf16(t0); + void* d1 = c.f32tab ? up_f32(t1) : up_bf16(t1); + /* Codes [K, rows]: dense, or the rows' block of a [lanes * K, stride] history at lane 1, + * frames 2.. */ + std::vector plane; + RadTensor tc; + std::vector code((size_t)(K * rows)); + for (int64_t k = 0; k < K; ++k) + for (int64_t i = 0; i < rows; ++i) + code[(size_t)(k * rows + i)] = (int32_t)((k * 7 + i * 3 + 1) % voc); + code[(size_t)(2 * rows + 4)] = 3 * voc + 1; /* a later code past t1: adds nothing */ + code[(size_t)5] = -off0 - 1; /* the first code of row 5 outside t0 */ + if (c.block) { + plane.assign((size_t)(lanes * K * stride), 77); + for (int64_t k = 0; k < K; ++k) + for (int64_t i = 0; i < rows; ++i) + plane[(size_t)((K + k) * stride + 2 + i)] = code[(size_t)(k * rows + i)]; + void* dp = up_i32(plane); + tc = T(dp, RAD_I32, { K, rows }); + tc.data = (int32_t*)dp + K * stride + 2; + tc.stride[0] = stride; + tc.stride[1] = 1; + } else { + tc = T(up_i32(code), RAD_I32, { K, rows }); + } + const uint32_t ydt = c.f32y ? RAD_F32 : RAD_BF16; + std::vector sentinel((size_t)(rows * D), 0.25f); + void* dy = c.f32y ? up_f32(sentinel) : up_bf16(sentinel); + const float scale = 0.5f; + std::vector ps = { PI("M", rows), PI("n_embd", D), PI("n_codes", K), + PI("vocab", voc), PI("off0", off0), PF("scale", scale), + PS("dtype", c.f32y ? "f32" : "bf16"), PI("round", c.round1) }; + const std::string nm = fmt("rvq_embed_bf16 round %d %s tables -> %s%s", c.round1, + c.f32tab ? "f32" : "bf16", c.f32y ? "f32" : "bf16", + c.block ? ", codes a history block" : ""); + const int rc = launch(r, { tc, T(d0, c.f32tab ? RAD_F32 : RAD_BF16, { voc + off0, D }), + T(d1, c.f32tab ? RAD_F32 : RAD_BF16, { (K - 1) * voc, D }), + T(dy, ydt, { rows, D }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want = sentinel; + for (int64_t i = 0; i < rows; ++i) { + const int64_t c0 = code[(size_t)i] + off0; + if (c0 < 0 || c0 >= voc + off0) continue; + for (int64_t d = 0; d < D; ++d) { + const float e0 = t0[(size_t)(c0 * D + d)]; + float acc = c.round1 ? e0 : 0.0f; + for (int64_t k = 1; k < K; ++k) { + const int64_t ck = code[(size_t)(k * rows + i)] + (k - 1) * voc; + if (ck >= 0 && ck < (K - 1) * voc) acc += t1[(size_t)(ck * D + d)]; + } + const float s = c.round1 ? acc : bfr(e0 + bfr(acc)); + want[(size_t)(i * D + d)] = c.f32y ? s * scale : bfr(s * scale); + } + } + const std::vector got = c.f32y ? down_f32(dy, want.size()) : down_bf16(dy, want.size()); + const int64_t bad = differ(got, want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld of %lld elements differ", (long long)bad, + (long long)want.size())); + } +} + +/* frame_store: each lane's codes into its block of the history, frames before `skip` and lanes + * whose status ended the piece left alone. Exact. */ +void frame_store_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "frame_store"); + if (!r) { ok("frame_store", false, "row absent"); return; } + const int64_t K = 16, lanes = 4, stride = 12, n = 3, rep = 2; + for (const int64_t skip : { (int64_t)0, (int64_t)1 }) { + std::vector codes((size_t)(K * rep * n)); + for (size_t i = 0; i < codes.size(); ++i) codes[i] = (int32_t)(i * 37 % 2048); + std::vector lane = { 3, 1, 0 }, frame = { 0, 5, 11 }, status = { 4, -1, 9, 2 }; + std::vector dst((size_t)(lanes * K * stride), -7); + void* dc = up_i32(codes); + void* dl = up_i32(lane); + void* df = up_i32(frame); + void* ds = up_i32(status); + void* dd = up_i32(dst); + std::vector ps = { PI("M", n), PI("n_codes", K), PI("stride", stride), + PI("rep", rep), PI("skip", skip) }; + const int rc = launch(r, { T(dc, RAD_I32, { K, rep * n }), T(dl, RAD_I32, { n }), + T(df, RAD_I32, { n }), T(ds, RAD_I32, { lanes }), + T(dd, RAD_I32, { lanes * K, stride }) }, + ps); + const std::string nm = fmt("frame_store skip %lld", (long long)skip); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + for (int64_t i = 0; i < n; ++i) { + const int64_t L = lane[(size_t)i], f = frame[(size_t)i] - skip; + if (f < 0 || status[(size_t)L] < 0 || f >= stride) continue; + for (int64_t k = 0; k < K; ++k) + dst[(size_t)((L * K + k) * stride + f)] = codes[(size_t)(k * rep * n + rep * i)]; + } + const int64_t bad = differ(down_i32(dd, dst.size()), dst); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld entries differ", (long long)bad)); + } +} + +/* conv1d_dw with its optional bias, bf16 and f32. */ +void conv1d_dw_bias_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv1d_dw_bf16"); + if (!r) { ok("conv1d_dw_bf16", false, "row absent"); return; } + const int64_t M = 20, C = 1024, Kw = 7; + for (const bool f32b : { false, true }) { + std::vector x = randv((size_t)(M * C), 1.0f), w = randv((size_t)(C * Kw), 0.5f); + std::vector b = randv((size_t)C, 1.0f); + void* dx = up_bf16(x); + void* dw = up_bf16(w); + void* db = f32b ? up_f32(b) : up_bf16(b); + void* dy = dalloc((size_t)(M * C) * 2); + const std::vector cu = { 0, 7, 20 }; + const int rc = launch(r, { T(dx, RAD_BF16, { M, C }), T(dw, RAD_BF16, { C, 1, Kw }), + T(up_i32(cu), RAD_I32, { 3 }), T(dy, RAD_BF16, { M, C }), + T(db, f32b ? RAD_F32 : RAD_BF16, { C }) }, + { PI("M", M), PI("n", C), PI("k", Kw), PS("dtype", "bf16") }); + const std::string nm = fmt("conv1d_dw_bf16 with a %s bias", f32b ? "f32" : "bf16"); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * C)); + for (int64_t t = 0; t < M; ++t) { + const int64_t t0 = t < 7 ? 0 : 7; + for (int64_t c = 0; c < C; ++c) { + float acc = 0.0f; + for (int64_t j = 0; j < Kw; ++j) { + const int64_t tt = t - (Kw - 1) + j; + if (tt >= t0) acc += x[(size_t)(tt * C + c)] * w[(size_t)(c * Kw + j)]; + } + want[(size_t)(t * C + c)] = acc + b[(size_t)c]; + } + } + check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2); + } +} + +/* attn_dense with an asymmetric window over a fused [q|k|v] row: the encoder rows at h256 gqa 2 + * and 4, segments longer than the window, against libref's mask. And the refusals: a right side + * without a window, and the rows that read every key. */ +void attn_window_right_cases(const Plugin& pl, const char* name, int64_t nh, int64_t nkv, + int64_t window, int64_t wright) { + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t hd = 256, total = 330, wq = nh * hd, wkv = nkv * hd, width = wq + 2 * wkv; + const std::vector cu = { 0, 290, 330 }; + std::vector qkv = randv((size_t)(total * width), 1.0f); + void* d = up_bf16(qkv); + auto col = [&](int64_t first, int64_t w) { + RadTensor t = T(d, RAD_BF16, { total, w }); + t.data = (void*)((uint16_t*)d + first); + t.stride[0] = width; + return t; + }; + void* dout = dalloc((size_t)(total * wq) * 2); + const float scale = 0.0625f; + std::vector ps = { PI("M", total), PI("head_dim", hd), PI("gqa", nh / nkv), + PI("causal", 0), PS("dtype", "bf16"), PF("scale", scale), + PI("max_seqlen", 290), PI("window", window), + PI("window_right", wright) }; + const std::string nm = fmt("%s window %lld window_right %lld", name, (long long)window, + (long long)wright); + const int rc = launch(r, { col(0, wq), col(wq, wkv), col(wq + wkv, wkv), T(up_i32(cu), RAD_I32, { 3 }), + T(dout, RAD_BF16, { total, wq }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const int64_t wr = wright > 0 ? wright : window; + std::vector want((size_t)(total * wq)); + for (int64_t s = 0; s < 2; ++s) { + const int64_t b0 = cu[(size_t)s], b1 = cu[(size_t)s + 1]; + for (int64_t h = 0; h < nh; ++h) { + const int64_t kh = h / (nh / nkv); + for (int64_t i = b0; i < b1; ++i) { + const int64_t jb = std::max(b0, i - window + 1), je = std::min(b1, i + wr); + std::vector sc((size_t)(je - jb)); + double mx = -1e300; + for (int64_t j = jb; j < je; ++j) { + double dot = 0; + for (int64_t e = 0; e < hd; ++e) + dot += (double)qkv[(size_t)(i * width + h * hd + e)] * + qkv[(size_t)(j * width + wq + kh * hd + e)]; + sc[(size_t)(j - jb)] = dot * scale; + mx = std::max(mx, sc[(size_t)(j - jb)]); + } + double sum = 0; + for (double& v : sc) { v = std::exp(v - mx); sum += v; } + for (int64_t e = 0; e < hd; ++e) { + double a = 0; + for (int64_t j = jb; j < je; ++j) + a += sc[(size_t)(j - jb)] * qkv[(size_t)(j * width + wq + wkv + kh * hd + e)]; + want[(size_t)(i * wq + h * hd + e)] = (float)(a / sum); + } + } + } + } + check(nm + " numerics", down_bf16(dout, want.size()), want, 2e-2); +} + +void attn_refusal_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "attn_dense_h256_gqa2_bf16"); + if (r) { + std::vector ps = { PI("M", 8), PI("head_dim", 256), PI("gqa", 2), PI("causal", 0), + PS("dtype", "bf16"), PI("window_right", 4) }; + const int rc = launch(r, { TA(RAD_BF16, { 8, 1024 }), TA(RAD_BF16, { 8, 512 }), + TA(RAD_BF16, { 8, 512 }), TI32({ 2 }, { 0, 8 }), + TA(RAD_BF16, { 8, 1024 }) }, + ps); + ok("attn_dense refuses a right window without a window", rc == RAD_E_SHAPE, + "rc " + std::to_string(rc)); + } +} + +void attn_small_refusal_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "attn_dense_small_h256_bf16"); + if (!r) { ok("attn_dense_small_h256_bf16", false, "row absent"); return; } + for (const char* key : { "window", "block" }) { + std::vector ps = { PI("M", 8), PI("head_dim", 256), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PI(key, 4) }; + const int rc = launch(r, { TA(RAD_BF16, { 8, 256 }), TA(RAD_BF16, { 8, 256 }), + TA(RAD_BF16, { 8, 256 }), TI32({ 2 }, { 0, 8 }), + TA(RAD_BF16, { 8, 256 }) }, + ps); + ok(fmt("attn_dense_small_h256_bf16 refuses a %s", key).c_str(), rc == RAD_E_UNSUPPORTED, + "rc " + std::to_string(rc)); + } +} + +/* rope with Llama 3's frequency scaling at a depth decoder's geometry (positions 0..15, theta + * 5e5, factor 32 over an original length of 16), against an f32 mirror of the kernel; and its + * refusal beside YaRN. */ +void rope_llama3_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "rope_bf16"); + if (!r) { ok("rope_bf16 llama3", false, "row absent"); return; } + const int64_t M = 16, hd = 128, n_head = 8, nkv = 0, half = hd / 2; + const int64_t row = n_head * hd; + const float theta = 500000.0f; + RadLlama3 l3; + l3.factor = 32.0f; l3.low = 0.001953125f; l3.high = 0.0078125f; l3.orig = 16.0f; + std::vector x = randv((size_t)(M * row), 1.0f); + void* dq = up_bf16(x); + std::vector pos((size_t)M); + for (int64_t m = 0; m < M; ++m) pos[(size_t)m] = (int32_t)m; + void* dp = up_i32(pos); + std::vector ps = { PI("M", M), PI("head_dim", hd), PI("n_head", n_head), + PI("n_head_kv", nkv), PF("theta", (double)theta), PF("scale", 1.0), + PS("mode", "neox"), PF("llama3_factor", 32.0), + PF("llama3_low", 0.001953125), PF("llama3_high", 0.0078125), + PF("llama3_orig", 16.0) }; + const int rc = launch(r, { T(dq, RAD_BF16, { M, row }), T(dp, RAD_I32, { M }) }, ps); + if (rc != RAD_OK) { ok("rope_bf16 llama3", false, "rc " + std::to_string(rc)); return; } + std::vector want = x; + int64_t scaled = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t h = 0; h < n_head; ++h) + for (int64_t i = 0; i < half; ++i) { + const float inv0 = 1.0f / powf(theta, (float)(2 * i) / (float)hd); + const float inv = l3.frequency(inv0); + if (m == 0 && h == 0 && inv != inv0) ++scaled; + float s, c; + sincosf((float)pos[(size_t)m] * inv, &s, &c); + const size_t i0 = (size_t)(m * row + h * hd + i), i1 = i0 + (size_t)half; + want[i0] = x[i0] * c - x[i1] * s; + want[i1] = x[i0] * s + x[i1] * c; + } + const std::vector got = down_bf16(dq, want.size()); + const double rl = rel(got, want); + ok("rope_bf16 llama3 numerics", rl < 2e-3 && scaled > 0, + fmt("rel_l2 %.3g, %lld of %lld frequencies scaled", rl, (long long)scaled, (long long)half)); + ps.push_back(PF("yarn_factor", 2.0)); + ps.push_back(PF("yarn_low", 1.0)); + ps.push_back(PF("yarn_high", 4.0)); + const int rc2 = launch(r, { T(dq, RAD_BF16, { M, row }), T(dp, RAD_I32, { M }) }, ps); + ok("rope_bf16 refuses llama3 beside YaRN", rc2 == RAD_E_INVAL, "rc " + std::to_string(rc2)); +} + +/* attn_dense causal at head_dim 64 over a fused [rows, 3 * 16 * 64] row (a codec transformer's + * sliding layers), with a window behind and without, one sequence or two, against libref's mask. */ +void attn_causal_h64_case(const Plugin& pl, int64_t window, std::vector cu) { + const char* name = "attn_dense_h64_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t hd = 64, nh = 16, total = cu.back(), wq = nh * hd, width = 3 * wq; + std::vector qkv = randv((size_t)(total * width), 1.0f); + void* d = up_bf16(qkv); + auto col = [&](int64_t first, int64_t w) { + RadTensor t = T(d, RAD_BF16, { total, w }); + t.data = (void*)((uint16_t*)d + first); + t.stride[0] = width; + return t; + }; + void* dout = dalloc((size_t)(total * wq) * 2); + const float scale = 0.125f; + std::vector ps = { PI("M", total), PI("head_dim", hd), PI("gqa", 1), PI("causal", 1), + PS("dtype", "bf16"), PF("scale", scale), PI("max_seqlen", total) }; + if (window) ps.push_back(PI("window", window)); + const std::string nm = fmt("%s causal window %lld over %zu sequence(s) of %lld rows", name, + (long long)window, cu.size() - 1, (long long)total); + const int rc = launch(r, { col(0, wq), col(wq, wq), col(2 * wq, wq), + T(up_i32(cu), RAD_I32, { (int64_t)cu.size() }), + T(dout, RAD_BF16, { total, wq }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(total * wq)); + for (size_t s = 0; s + 1 < cu.size(); ++s) { + const int64_t b0 = cu[s], b1 = cu[s + 1]; + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = b0; i < b1; ++i) { + const int64_t jb = window ? std::max(b0, i - window + 1) : b0, je = i + 1; + std::vector sc((size_t)(je - jb)); + double mx = -1e300; + for (int64_t j = jb; j < je; ++j) { + double dot = 0; + for (int64_t e = 0; e < hd; ++e) + dot += (double)qkv[(size_t)(i * width + h * hd + e)] * + qkv[(size_t)(j * width + wq + h * hd + e)]; + sc[(size_t)(j - jb)] = dot * scale; + mx = std::max(mx, sc[(size_t)(j - jb)]); + } + double sum = 0; + for (double& v : sc) { v = std::exp(v - mx); sum += v; } + for (int64_t e = 0; e < hd; ++e) { + double a = 0; + for (int64_t j = jb; j < je; ++j) + a += sc[(size_t)(j - jb)] * qkv[(size_t)(j * width + 2 * wq + h * hd + e)]; + want[(size_t)(i * wq + h * hd + e)] = (float)(a / sum); + } + } + } + check(nm + " numerics", down_bf16(dout, want.size()), want, 2e-2); +} + +/* gelu, the exact erf form, against libref's act_gelu evaluated in double. */ +void gelu_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "gelu_bf16"); + if (!r) { ok("gelu_bf16", false, "row absent"); return; } + const int64_t M = 64, n = 4096; + std::vector x = randv((size_t)(M * n), 4.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("gelu_bf16", false, "rc " + std::to_string(rc)); return; } + std::vector want(x.size()); + for (size_t i = 0; i < x.size(); ++i) + want[i] = 0.5f * x[i] * (1.0f + (float)std::erf((double)(x[i] * 0.70710678118654752f))); + const std::vector got = down_bf16(dy, want.size()); + int64_t off = 0; + for (size_t i = 0; i < want.size(); ++i) + if (h_to_bf16(got[i]) != h_to_bf16(want[i])) ++off; + const double rl = rel(got, want); + ok(fmt("gelu_bf16 numerics (rel_l2 %.3g, %lld of %zu off libref's bf16)", rl, (long long)off, + want.size()).c_str(), rl < 2e-3); +} + +/* qk_norm_rope with f32 gains at a Gemma-style text encoder's geometry (head_dim 256, four query + * heads over one KV head, gain 1 + w): the same values as bf16 gains give the same bytes, and both + * follow libref's form (the norm rounded, then rotated). */ +void qk_norm_rope_f32_gain_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16"); + if (!r) { ok("qk_norm_rope_bf16 f32 gains", false, "row absent"); return; } + const int64_t M = 24, hd = 256, nh = 4, nkv = 1, width = (nh + 2 * nkv) * hd, half = hd / 2; + const float theta = 10000.0f, eps = 1e-6f; + std::vector x = randv((size_t)(M * width), 2.0f); + std::vector qg = randv((size_t)hd, 0.5f), kg = randv((size_t)hd, 0.5f); + for (auto& v : qg) v = bfr(v); + for (auto& v : kg) v = bfr(v); + std::vector pos((size_t)M); + for (int64_t m = 0; m < M; ++m) pos[(size_t)m] = (int32_t)(m * 3); + void* dp = up_i32(pos); + std::vector> outs; + for (const bool f32 : { false, true }) { + std::vector xx = x; + void* dq = up_bf16(xx); + std::vector a = qg, b = kg; + void* dqw = f32 ? up_f32(a) : up_bf16(a); + void* dkw = f32 ? up_f32(b) : up_bf16(b); + const uint32_t gdt = f32 ? RAD_F32 : RAD_BF16; + const int rc = launch(r, { T(dq, RAD_BF16, { M, width }), T(dp, RAD_I32, { M }), + T(dqw, gdt, { hd }), T(dkw, gdt, { hd }) }, + { PI("M", M), PI("head_dim", hd), PI("n_head", nh), PI("n_head_kv", nkv), + PF("theta", (double)theta), PF("eps", (double)eps), PS("mode", "neox"), + PF("wadd", 1.0) }); + if (rc != RAD_OK) { + ok("qk_norm_rope_bf16 f32 gains", false, fmt("%s gains rc %d", f32 ? "f32" : "bf16", rc)); + return; + } + outs.push_back(down_bf16(dq, (size_t)(M * width))); + if (!f32) x = xx; + } + const int64_t bad = differ(outs[0], outs[1]); + ok("qk_norm_rope_bf16 f32 gains give the bf16 gains' bytes", bad == 0, + fmt("%lld of %zu elements differ", (long long)bad, outs[0].size())); + std::vector want = x; + for (int64_t m = 0; m < M; ++m) + for (int64_t h = 0; h < nh + nkv; ++h) { + const std::vector& g = h < nh ? qg : kg; + const size_t base = (size_t)(m * width + h * hd); + double ss = 0; + for (int64_t e = 0; e < hd; ++e) ss += (double)x[base + (size_t)e] * x[base + (size_t)e]; + const float sc = 1.0f / std::sqrt((float)(ss / hd) + eps); + std::vector n((size_t)hd); + for (int64_t e = 0; e < hd; ++e) + n[(size_t)e] = bfr(x[base + (size_t)e] * sc * (g[(size_t)e] + 1.0f)); + for (int64_t i = 0; i < half; ++i) { + const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)hd); + float sn, cs; + sincosf((float)pos[(size_t)m] * inv, &sn, &cs); + want[base + (size_t)i] = n[(size_t)i] * cs - n[(size_t)(i + half)] * sn; + want[base + (size_t)(i + half)] = n[(size_t)i] * sn + n[(size_t)(i + half)] * cs; + } + } + check("qk_norm_rope_bf16 f32 gains numerics", outs[1], want, 1e-2); +} + +/* mul_weight over an f32 weight, a row and a scalar: one multiply, one rounding, exact. */ +void mul_weight_f32_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "mul_weight_bf16"); + if (!r) { ok("mul_weight_bf16 f32", false, "row absent"); return; } + const int64_t M = 7, n = 512; + for (const int64_t wn : { n, (int64_t)1 }) { + std::vector x = randv((size_t)(M * n), 3.0f), w = randv((size_t)wn, 0.01f); + void* dx = up_bf16(x); + void* dw = up_f32(w); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { M, n }), T(dw, RAD_F32, { wn }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + const std::string nm = fmt("mul_weight_bf16 f32 weight of %lld", (long long)wn); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(x.size()); + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) + want[(size_t)(m * n + i)] = bfr(x[(size_t)(m * n + i)] * w[(size_t)(wn == 1 ? 0 : i)]); + const int64_t bad = differ(down_bf16(dy, want.size()), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld elements differ", (long long)bad)); + } +} + +/* iota with and without a period. Exact. */ +void iota_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "iota"); + if (!r) { ok("iota", false, "row absent"); return; } + for (const int64_t period : { (int64_t)0, (int64_t)16 }) { + const int64_t n = 70; + void* dy = dalloc((size_t)n * 4); + std::vector ps = { PI("M", n), PI("start", 3), PI("step", 2) }; + if (period) ps.push_back(PI("period", period)); + const int rc = launch(r, { T(dy, RAD_I32, { n }) }, ps); + const std::string nm = fmt("iota period %lld", (long long)period); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)n); + for (int64_t i = 0; i < n; ++i) want[(size_t)i] = (int32_t)(3 + (period ? i % period : i) * 2); + const int64_t bad = differ(down_i32(dy, (size_t)n), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld entries differ", (long long)bad)); + } +} + +} /* namespace au */ + +/* ---- the video generator's ops, at MiniMax-H3's geometry ----------------------------------------- + * + * A request's latent geometry is a device operand the decoder's kernels read on the device. + * rad-kbench's index operands are constant-filled, which cannot express a (frames, H, W) whose + * values differ, so these cases build it by hand: a patch grid taller than it is wide, tiles that + * overlap unevenly, more tiles one way than the other, and every (first, last) pair of the stitch + * with the previous chunk's tail in `prev`. Each case compares with the host port of its libref + * function (libref/ref_video.cpp, ref_gen.cpp, ref_audio.cpp): bit for bit where the kernel keeps + * the reference's order, to a relative L2 where it sums in another order or calls the device's + * sin and exp. */ +namespace vid { + +using namespace au; + +/* libref's split_tiles. */ +bool split(int64_t len, int64_t tile, int64_t overlap, std::vector* st, + std::vector* ov) { + st->clear(); + ov->clear(); + if (tile >= len) { + st->push_back(0); + return len == tile; + } + int64_t n = (len + tile - 1) / tile; + while (tile * n - overlap * (n - 1) - len < 0) ++n; + ov->assign((size_t)(n - 1), overlap); + const int64_t rem = tile * n - overlap * (n - 1) - len; + for (int64_t i = 0; i < rem; ++i) (*ov)[(size_t)(i % (n - 1))] += 1; + st->push_back(0); + for (int64_t i = 0; i + 1 < n; ++i) st->push_back(st->back() + tile - (*ov)[(size_t)i]); + return true; +} + +std::string list_of(const std::vector& v) { + std::string s; + for (size_t i = 0; i < v.size(); ++i) s += fmt("%s%.9g", i ? " " : "", (double)v[i]); + return s; +} + +/* patch_unfold over a 3 x 4 x 5 patch grid, one and two frames a patch. */ +void patch_unfold_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "patch_unfold_f32"); + if (!r) { ok("patch_unfold_f32", false, "row absent"); return; } + const int64_t C = 24, F = 3, Hp = 4, Wp = 5, ph = 2, pw = 2; + std::vector mul = randv((size_t)C, 1.3f), add = randv((size_t)C, 0.7f); + const std::string smul = list_of(mul), sadd = list_of(add); + for (const int64_t pt : { (int64_t)1, (int64_t)2 }) { + const int64_t K = C * pt * ph * pw, rows = F * pt * Hp * ph * Wp * pw, M = rows + 5; + std::vector x = randv((size_t)(F * Hp * Wp * K), 2.0f); + void* dx = up_f32(x); + void* dy = dalloc((size_t)(M * C) * 4); + const std::string nm = fmt("patch_unfold_f32 pt %lld", (long long)pt); + const int rc = launch(r, { T(dx, RAD_F32, { F * Hp * Wp, K }), + TI32({ 3 }, { (int32_t)F, (int32_t)Hp, (int32_t)Wp }), + T(dy, RAD_F32, { M, C }) }, + { PI("M", M), PI("C", C), PI("pt", pt), PI("ph", ph), PI("pw", pw), + PS("mul", smul.c_str()), PS("add", sadd.c_str()), + PS("dtype", "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * C), 0.0f); + const int64_t Hv = Hp * ph, Wv = Wp * pw; + for (int64_t rr = 0; rr < rows; ++rr) { + const int64_t t = rr / (Hv * Wv), yy = (rr / Wv) % Hv, xx = rr % Wv; + const int64_t patch = ((t / pt) * Hp + yy / ph) * Wp + xx / pw; + const int64_t sub = ((t % pt) * ph + yy % ph) * pw + xx % pw; + for (int64_t c = 0; c < C; ++c) { + const float p = x[(size_t)(patch * K + c * pt * ph * pw + sub)] * mul[(size_t)c]; + want[(size_t)(rr * C + c)] = p + add[(size_t)c]; + } + } + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok((nm + " exact, rows past the geometry untouched").c_str(), bad == 0, + fmt("%lld values differ", (long long)bad)); + } +} + +/* vtile_gather: a 20 x 35 latent of 2 frames in tiles of 16 at least 4 apart (overlaps 12 down, + * 7 and 6 across), four registers and three zero rows a tile. */ +void vtile_gather_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vtile_gather"); + if (!r) { ok("vtile_gather", false, "row absent"); return; } + const int64_t frames = 2, H = 20, W = 35, tile = 16, ov = 4, n_reg = 4, n = 64; + const int64_t vox = frames * tile * tile, period = vox + n_reg + 3; + std::vector sy, sx, oy, ox; + split(H, tile, ov, &sy, &oy); + split(W, tile, ov, &sx, &ox); + const int64_t nw = (int64_t)sx.size(), rows = (int64_t)sy.size() * nw * period; + for (const bool bf : { false, true }) { + std::vector x = randv((size_t)(frames * H * W * n), 1.0f); + std::vector reg = randv((size_t)(n_reg * n), 1.0f); + void* dx = bf ? up_bf16(x) : up_f32(x); + void* dr = up_f32(reg); + const uint32_t dt = bf ? RAD_BF16 : RAD_F32; + void* dy = dalloc((size_t)(rows * n) * (bf ? 2 : 4)); + const std::string nm = fmt("vtile_gather %s 20 x 35 in 2 x 3 tiles", bf ? "bf16" : "f32"); + const int rc = launch(r, { T(dx, dt, { frames * H * W, n }), T(dr, RAD_F32, { n_reg, n }), + TI32({ 3 }, { (int32_t)frames, (int32_t)H, (int32_t)W }), + T(dy, dt, { rows, n }) }, + { PI("M", rows), PI("n", n), PI("tile", tile), PI("overlap", ov), + PI("frames", frames), PI("period", period), PI("n_reg", n_reg), + PS("dtype", bf ? "bf16" : "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(rows * n), 0.0f); + for (int64_t row = 0; row < rows; ++row) { + const int64_t k = row / period, p = row % period; + for (int64_t c = 0; c < n; ++c) { + float v = 0.0f; + if (p < vox) { + const int64_t t = p / (tile * tile), iy = (p / tile) % tile, ix = p % tile; + const int64_t src = (t * H + sy[(size_t)(k / nw)] + iy) * W + sx[(size_t)(k % nw)] + ix; + v = x[(size_t)(src * n + c)]; + } else if (p < vox + n_reg) { + v = bf ? bfr(reg[(size_t)((p - vox) * n + c)]) : reg[(size_t)((p - vox) * n + c)]; + } + want[(size_t)(row * n + c)] = v; + } + } + const std::vector got = bf ? down_bf16(dy, want.size()) : down_f32(dy, want.size()); + const int64_t bad = differ(got, want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld values differ", (long long)bad)); + } +} + +/* libref's ref_vtile_stitch on the host, over bf16 tiles and a bf16 `prev`, which it updates. */ +std::vector stitch_ref(const std::vector& x, std::vector* prev, + int64_t frames, int64_t H, int64_t W, bool first, bool last, + int64_t tile, int64_t ov, int64_t S, int64_t pt, int64_t skip, + int64_t keep, int64_t blend, int64_t period, const float* mean, + const float* stdv) { + (void)frames; + std::vector sy, sx, oy, ox; + split(H, tile, ov, &sy, &oy); + split(W, tile, ov, &sx, &ox); + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(), cols = 3 * pt * S * S; + const int64_t Hp = H * S, Wp = W * S, npx = Hp * Wp, fout = keep + (last ? blend : 0); + std::vector y((size_t)(fout * npx * 3), 0); + auto wb = [&](int64_t p, int64_t e) { return bfr((float)p / (float)e); }; + auto wa = [&](int64_t p, int64_t e) { return bfr(1.0f - bfr((float)p / (float)e)); }; + auto Tv = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t fc, int64_t c) { + const int64_t row = (i * nw + j) * period + ((fc / pt) * tile + ly / S) * tile + lx / S; + const int64_t col = ((c * pt + fc % pt) * S + ly % S) * S + lx % S; + return x[(size_t)(row * cols + col)]; + }; + for (int64_t px = 0; px < npx; ++px) { + const int64_t Y = px / Wp, X = px % Wp; + int64_t i = 0, j = 0; + while (i + 1 < nh && Y >= sy[(size_t)(i + 1)] * S) ++i; + while (j + 1 < nw && X >= sx[(size_t)(j + 1)] * S) ++j; + const int64_t ly = Y - sy[(size_t)i] * S, lx = X - sx[(size_t)j] * S; + auto stitch = [&](int64_t fc, int64_t c) { + float v = Tv(i, j, ly, lx, fc, c); + const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] * S : 0; + if (ly < ev) { + const float up = Tv(i - 1, j, ly + tile * S - ev, lx, fc, c); + v = bfr(bfr(up * wa(ly, ev)) + bfr(v * wb(ly, ev))); + } + const int64_t eh = j > 0 ? ox[(size_t)(j - 1)] * S : 0; + if (lx < eh) { + const float left = Tv(i, j - 1, ly, lx + tile * S - eh, fc, c); + v = bfr(bfr(left * wa(lx, eh)) + bfr(v * wb(lx, eh))); + } + return v; + }; + auto byte = [&](int64_t f, int64_t c, float v) { + float p = v * stdv[c]; + p = p + mean[c]; + p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p); + p = p * 255.0f; + const float q = p != p ? 0.0f : std::nearbyintf(p); + y[(size_t)((f * npx + px) * 3 + c)] = (uint8_t)(q < 0.0f ? 0.0f : (q > 255.0f ? 255.0f : q)); + }; + for (int64_t c = 0; c < 3; ++c) { + for (int64_t k = 0; k < keep; ++k) { + float v = stitch(skip + k, c); + if (!first && k < blend) { + const float pv = (*prev)[(size_t)((k * npx + px) * 3 + c)]; + v = bfr(bfr(pv * wa(k, blend)) + bfr(v * wb(k, blend))); + } + byte(k, c, v); + } + for (int64_t k = 0; k < blend; ++k) { + const float v = stitch(2 * skip + keep + k, c); + if (last) byte(keep + k, c, v); + (*prev)[(size_t)((k * npx + px) * 3 + c)] = bfr(v); + } + } + } + return y; +} + +/* vtile_stitch: a small geometry under every (first, last) pair, then MiniMax-H3's own parameters + * over a 20 x 35 latent (2 x 3 tiles, uneven overlaps) as a middle and a last chunk. */ +void vtile_stitch_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vtile_stitch"); + if (!r) { ok("vtile_stitch", false, "row absent"); return; } + static const float kMean[3] = { 0.485f, 0.456f, 0.406f }, kStd[3] = { 0.229f, 0.224f, 0.225f }; + struct G { int64_t frames, H, W, tile, ov, S, pt, skip, keep, blend; int first, last; }; + std::vector gs; + for (int fl = 0; fl < 4; ++fl) gs.push_back({ 4, 6, 9, 4, 1, 2, 2, 1, 3, 2, fl & 1, fl >> 1 }); + gs.push_back({ 7, 20, 35, 16, 4, 16, 4, 3, 17, 5, 0, 0 }); + gs.push_back({ 7, 20, 35, 16, 4, 16, 4, 3, 17, 5, 0, 1 }); + for (const G& g : gs) { + std::vector sy, sx, oy, ox; + split(g.H, g.tile, g.ov, &sy, &oy); + split(g.W, g.tile, g.ov, &sx, &ox); + const int64_t period = g.frames * g.tile * g.tile + 5, cols = 3 * g.pt * g.S * g.S; + const int64_t tiles = (int64_t)(sy.size() * sx.size()), npx = g.H * g.S * g.W * g.S; + const int64_t fout = g.keep + (g.last ? g.blend : 0); + std::vector x = randv((size_t)(tiles * period * cols), 2.5f); + std::vector prev = randv((size_t)(g.blend * npx * 3), 2.5f); + void* dx = up_bf16(x); + void* dp = up_bf16(prev); + void* dy = dalloc((size_t)(fout * npx * 3)); + const std::string nm = fmt("vtile_stitch %lld x %lld tile %lld first %d last %d", + (long long)g.H, (long long)g.W, (long long)g.tile, g.first, g.last); + const int rc = launch(r, { T(dx, RAD_BF16, { tiles * period, cols }), + TI32({ 5 }, { (int32_t)g.frames, (int32_t)g.H, (int32_t)g.W, + g.first, g.last }), + T(dp, RAD_BF16, { g.blend * npx, 3 }), + T(dy, RAD_U8, { fout * npx, 3 }) }, + { PI("M", fout * npx), PI("tile", g.tile), PI("overlap", g.ov), + PI("scale", g.S), PI("pt", g.pt), PI("skip", g.skip), + PI("keep", g.keep), PI("blend", g.blend), PI("period", period), + PS("mean", "0.485 0.456 0.406"), PS("std", "0.229 0.224 0.225") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector want = + stitch_ref(x, &prev, g.frames, g.H, g.W, g.first != 0, g.last != 0, g.tile, g.ov, g.S, + g.pt, g.skip, g.keep, g.blend, period, kMean, kStd); + std::vector got(want.size()); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + const int64_t bad = differ(got, want), badp = differ(down_bf16(dp, prev.size()), prev); + ok((nm + " bytes exact").c_str(), bad == 0, fmt("%lld bytes differ", (long long)bad)); + ok((nm + " handed-on tail exact").c_str(), badp == 0, + fmt("%lld values differ", (long long)badp)); + } +} + + +/* rms_mod and rms_mod_quant_fp8 at the DiT's width over three segments, the table and the gate a + * column slice of a wider row as the plugin reads them, gated and not. The residual is exact; the + * norm chain is held to a relative L2 (the sum of squares is a block sum on the device), and the + * codes are compared by their dequantised values. */ +void rms_mod_cases(const Plugin& pl, bool quant) { + const char* name = quant ? "rms_mod_quant_fp8_bf16" : "rms_mod_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t n = 5376, M = 7, segs = 3, pitch = 3 * n; + const std::vector cu = { 0, 2, 5, 7 }; + for (const int gated : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), y = randv((size_t)(M * n), 1.0f); + std::vector tab = randv((size_t)(segs * pitch), 0.5f), w = randv((size_t)n, 1.0f); + void* dx = up_bf16(x); + void* dyd = up_bf16(y); + void* dt = up_bf16(tab); + void* dw = up_bf16(w); + void* dcu = up_i32(cu); + /* s = columns [n, 3n) of the table (shift, scale), g = columns [0, n). */ + RadTensor ts = T((char*)dt + n * 2, RAD_BF16, { segs, 2 * n }); + ts.stride[0] = pitch; + RadTensor tg = T(dt, RAD_BF16, { segs, n }); + tg.stride[0] = pitch; + RadTensor ty = T(dyd, RAD_BF16, { M, n }); + if (!gated) { absent(ty); absent(tg); } + void* dz = dalloc((size_t)(M * n) * 2); + void* dq = dalloc((size_t)(M * n)); + void* dqs = dalloc((size_t)(M * n / 128) * 4); + std::vector args = { ty, tg, ts, T(dw, RAD_BF16, { n }), T(dcu, RAD_I32, { 4 }), + T(dx, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PF("eps", 1e-5), PI("gated", gated), + PS("dtype", "bf16") }; + if (quant) { + args.push_back(T(dq, RAD_F8E4M3, { M, n })); + args.push_back(T(dqs, RAD_F32, { M, n / 128 })); + ps.push_back(PI("group", 128)); + } + args.push_back(T(dz, RAD_BF16, { M, n })); + const std::string nm = fmt("%s gated %d", name, gated); + const int rc = launch(r, args, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector xr = x, want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row); + float* xv = xr.data() + row * n; + if (gated) + for (int64_t i = 0; i < n; ++i) + xv[i] = bfr(xv[i] + bfr(tab[(size_t)(e * pitch + i)] * y[(size_t)(row * n + i)])); + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) ss += xv[i] * xv[i]; + const float rs = 1.0f / std::sqrt(ss / (float)n + 1e-5f); + for (int64_t i = 0; i < n; ++i) { + const float n2 = bfr(bfr(xv[i] * rs) * w[(size_t)i]); + const float sc = bfr(1.0f + tab[(size_t)(e * pitch + 2 * n + i)]); + want[(size_t)(row * n + i)] = bfr(bfr(n2 * sc) + tab[(size_t)(e * pitch + n + i)]); + } + } + const int64_t badx = differ(down_bf16(dx, xr.size()), xr); + ok((nm + " residual exact").c_str(), badx == 0, fmt("%lld values differ", (long long)badx)); + check(nm + " norm", down_bf16(dz, want.size()), want, 4e-3); + if (quant) { + std::vector q((size_t)(M * n)); + st_memcpy(q.data(), dq, q.size(), hipMemcpyDeviceToHost); + const std::vector qs = down_f32(dqs, (size_t)(M * n / 128)); + std::vector deq((size_t)(M * n)); + for (size_t i = 0; i < deq.size(); ++i) + deq[i] = rad_fp8e4m3_to_f32(q[i]) * qs[i / 128]; + check(nm + " codes", deq, want, 4e-2); + } + } +} + +/* flow_x0_step: an f32 and a bf16 velocity, rows at a wider pitch; every value exact. */ +void flow_x0_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "flow_x0_step_f32"); + if (!r) { ok("flow_x0_step_f32", false, "row absent"); return; } + const int64_t M = 37, n = 96, ld = 100; + for (const bool bf : { false, true }) { + std::vector x = randv((size_t)(M * ld), 3.0f), v = randv((size_t)(M * n), 2.0f); + const std::vector t = { 0.3125f }, sg = { 0.6875f }, sgn = { 0.40625f }; + void* dx = up_f32(x); + void* dv = bf ? up_bf16(v) : up_f32(v); + RadTensor tx = T(dx, RAD_F32, { M, n }); + tx.stride[0] = ld; + const std::string nm = fmt("flow_x0_step_f32 %s velocity", bf ? "bf16" : "f32"); + const int rc = launch(r, { T(dv, bf ? RAD_BF16 : RAD_F32, { M, n }), + T(up_f32(t), RAD_F32, { 1 }), T(up_f32(sg), RAD_F32, { 1 }), + T(up_f32(sgn), RAD_F32, { 1 }), tx }, + { PI("M", M), PI("n", n), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want = x; + const float st = 1.0f - t[0], ra = sgn[0] / sg[0], omr = 1.0f - ra; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + const float xv = x[(size_t)(row * ld + c)]; + const float p = st * v[(size_t)(row * n + c)]; + const float d = xv + p; + const float a = ra * xv, b = omr * d; + want[(size_t)(row * ld + c)] = a + b; + } + const int64_t bad = differ(down_f32(dx, want.size()), want); + ok((nm + " exact, the pitch's gap untouched").c_str(), bad == 0, + fmt("%lld values differ", (long long)bad)); + } +} + +/* grid_pos3: MiniMax-H3's tile of 7 x 16 x 16 and its registers over two periods, written into a + * [3, M] view of a wider plane; exact. */ +void grid_pos3_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "grid_pos3"); + if (!r) { ok("grid_pos3", false, "row absent"); return; } + const int64_t T_ = 7, H = 16, W = 16, period = 1797, M = 2 * period, ld = M + 11; + const float scale = (float)6.283185307179586; + void* dy = dalloc((size_t)(3 * ld) * 4); + RadTensor ty = T(dy, RAD_F32, { 3, M }); + ty.stride[0] = ld; + const int rc = launch(r, { ty }, { PI("M", M), PI("T", T_), PI("H", H), PI("W", W), + PI("period", period), PF("scale", 6.283185307179586) }); + if (rc != RAD_OK) { ok("grid_pos3", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(3 * ld), 0.0f); + auto g = [](int64_t c, int64_t nn) { + const float q = ((float)c + 0.5f) / (float)nn; + const float d = 2.0f * q; + return d - 1.0f; + }; + for (int64_t m = 0; m < M; ++m) { + const int64_t k = m % period; + if (k >= T_ * H * W) continue; + want[(size_t)m] = scale * g(k / (H * W), T_); + want[(size_t)(ld + m)] = scale * g((k / W) % H, H); + want[(size_t)(2 * ld + m)] = scale * g(k % W, W); + } + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok("grid_pos3 7 x 16 x 16, two periods, exact", bad == 0, fmt("%lld values differ", (long long)bad)); +} + +/* snake_aa: BigVGAN's ratio 2 and 12-tap filters over a stereo pair of unequal sequences, alpha + * and beta as logarithms; and an odd filter at ratio 3. Against libref's arithmetic in f32 with + * the host's sin and exp. */ +void snake_aa_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "snake_aa_f32"); + if (!r) { ok("snake_aa_f32", false, "row absent"); return; } + struct C { int64_t R, k, lg; std::vector cu; }; + for (const C& c : { C{ 2, 12, 1, { 0, 23, 61 } }, C{ 3, 7, 0, { 0, 5, 9 } } }) { + const int64_t n = 40, M = c.cu.back(); + std::vector x = randv((size_t)(M * n), 2.0f), al(n), be(n); + for (int64_t i = 0; i < n; ++i) { + al[(size_t)i] = c.lg ? rnd() * 0.5f : 0.3f + std::fabs(rnd()); + be[(size_t)i] = c.lg ? rnd() * 0.5f : 0.3f + std::fabs(rnd()); + } + std::vector fu = randv((size_t)c.k, 0.4f), fd = randv((size_t)c.k, 0.4f); + void* dy = dalloc((size_t)(M * n) * 4); + const std::string nm = fmt("snake_aa_f32 ratio %lld k %lld%s", (long long)c.R, + (long long)c.k, c.lg ? " log" : ""); + const int rc = launch(r, { T(up_f32(x), RAD_F32, { M, n }), T(up_f32(al), RAD_F32, { n }), + T(up_f32(be), RAD_F32, { n }), T(up_f32(fu), RAD_F32, { 1, 1, c.k }), + T(up_f32(fd), RAD_F32, { 1, 1, c.k }), + T(up_i32(c.cu), RAD_I32, { (int64_t)c.cu.size() }), + T(dy, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PI("ratio", c.R), PI("k", c.k), + PI("log", c.lg), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + const int64_t R = c.R, k = c.k, P = k / R - 1, crop = P * R + (k - R) / 2; + const int64_t pad = k / 2 - (k % 2 == 0 ? 1 : 0); + for (size_t e = 0; e + 1 < c.cu.size(); ++e) { + const int64_t s0 = c.cu[e], L = c.cu[e + 1] - s0; + for (int64_t ch = 0; ch < n; ++ch) { + const float A = c.lg ? (float)std::exp((double)al[(size_t)ch]) : al[(size_t)ch]; + const float B = c.lg ? (float)std::exp((double)be[(size_t)ch]) : be[(size_t)ch]; + auto xp = [&](int64_t i) { + const int64_t q = std::min(std::max(i - P, 0), L - 1); + return x[(size_t)((s0 + q) * n + ch)]; + }; + std::vector act((size_t)(L * R)); + for (int64_t m = 0; m < L * R; ++m) { + const int64_t o = crop + m; + const int64_t lo = o < k ? 0 : (o - k) / R + 1, hi = std::min(o / R, L + 2 * P - 1); + float acc = 0.0f; + for (int64_t i = lo; i <= hi; ++i) acc += fu[(size_t)(o - i * R)] * xp(i); + const float u = (float)R * acc; + const float sn = (float)std::sin((double)(u * A)); + act[(size_t)m] = u + 1.0f / (B + 1e-9f) * (sn * sn); + } + for (int64_t o = 0; o < L; ++o) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int64_t m = std::min(std::max(o * R + j - pad, 0), L * R - 1); + acc += fd[(size_t)j] * act[(size_t)m]; + } + want[(size_t)((s0 + o) * n + ch)] = acc; + } + } + } + const std::vector got = down_f32(dy, want.size()); + double e2 = 0, r2 = 0; + for (size_t i = 0; i < want.size(); ++i) { + e2 += (double)(got[i] - want[i]) * (got[i] - want[i]); + r2 += (double)want[i] * want[i]; + } + const double rl = std::sqrt(e2 / r2); + ok(fmt("%s numerics (rel_l2 %.3g, bound 1e-5)", nm.c_str(), rl).c_str(), rl <= 1e-5); + } +} + +} /* namespace vid */ + +/* ---- a video generator's f32 forms, its biased GEMMs and its rotary, against libref's arithmetic + * + * A diffusion transformer's patch projections and heads, its timestep MLP and a video decoder's + * 1x1 projections are gemm_nt_bias at f32; its modulation projections gemm_nt_q_bias at fp8a8 into + * a column block of a wider table; its decoder's norms, layer scales and residual adds f32 forms of + * rmsnorm, layernorm, mul_weight and add; its vocoder f32 convolutions; its attention the axial + * qk_norm_rope over f32 positions. Each case compares with a host port of the libref function: + * an f32 output to a relative L2 of 2e-5 (rad-kbench's f32 GEMM bound), a bf16 one against the + * answer rounded to bf16, a copy or a single rounding exactly. */ +namespace vg { + +using namespace au; + +double rel_f32(const std::vector& got, const std::vector& want) { + double e = 0, r = 0; + for (size_t i = 0; i < want.size(); ++i) { + e += ((double)got[i] - want[i]) * ((double)got[i] - want[i]); + r += (double)want[i] * want[i]; + } + return r > 0 ? std::sqrt(e / r) : std::sqrt(e); +} +void check_f32(const std::string& name, const std::vector& got, + const std::vector& want, double tol) { + const double r = rel_f32(got, want); + ok(fmt("%s (rel_l2 %.3g, bound %.3g)", name.c_str(), r, tol).c_str(), r <= tol); +} +float gelu_erf(float x) { return 0.5f * x * (1.0f + (float)std::erf((double)(x * 0.70710678118654752f))); } +float gelu_tanh(float x) { + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + return 0.5f * x * (1.0f + (float)std::tanh((double)(k0 * (x + k1 * x * x * x)))); +} + +/* An f32 weight as an f32 row stores it, through its relayout hook from PyTorch's layout. */ +void* stored_weight_f32(const RadKernelInfo* r, const std::vector& lp, + const std::vector& w, int64_t rows, int64_t cols, const char* what) { + Planes p; + p.enc = rad_enc_plain(RAD_F32); + p.rows = { rows }; + p.cols = { cols }; + p.data.assign(1, std::vector(w.size() * 4)); + std::memcpy(p.data[0].data(), w.data(), w.size() * 4); + std::vector blob; + const int rc = stored(r, lp, 1, p, { "codes" }, &blob); + if (rc != RAD_OK) { + ok(what, false, "relayout rc " + std::to_string(rc)); + return nullptr; + } + std::string why; + ok(fmt("%s: the stored weight inverts to PyTorch's", what).c_str(), + restores(r, lp, 1, p, { "codes" }, blob, &why), why); + void* d = dalloc(blob.size()); + if (d) st_memcpy(d, blob.data(), blob.size(), hipMemcpyHostToDevice); + return d; +} + +/* gemm_nt_bias at f32 at the shapes a video generator issues, the bf16 output of its patch + * projections among them, and the epilogue's activation and residual (the residual once the + * output itself), with A and C at pitches wider than their rows. */ +void gemm_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "gemm_f32_nt_bias"); + if (!r) { ok("gemm_f32_nt_bias", false, "row absent"); return; } + struct G { int64_t M, N, K, apad, cpad; bool bf16; int act; int res; }; /* res 2: y itself */ + for (const G& g : { G{ 777, 5376, 96, 0, 0, true, 0, 0 }, G{ 300, 96, 5376, 0, 0, false, 0, 0 }, + G{ 200, 32, 5376, 0, 0, false, 0, 0 }, G{ 40, 2688, 5376, 0, 0, false, 0, 0 }, + G{ 70, 5376, 256, 0, 0, false, 0, 0 }, G{ 1000, 24, 24, 0, 0, false, 0, 0 }, + G{ 500, 2048, 24, 0, 0, false, 0, 0 }, G{ 33, 70, 37, 5, 6, true, 1, 2 }, + G{ 19, 130, 19, 0, 3, false, 2, 1 }, G{ 65, 64, 300, 3, 0, true, 0, 1 } }) { + const int64_t lda = g.K + g.apad, ldc = g.N + g.cpad; + std::vector a = randv((size_t)(g.M * lda), 1.0f), w = randv((size_t)(g.N * g.K), 0.1f); + std::vector b = randv((size_t)g.N, 0.5f), res = randv((size_t)(g.M * ldc), 1.0f); + const uint32_t ydt = g.bf16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32; + if (g.bf16) for (auto& v : res) v = bfr(v); + void* da = up_f32(a); + void* dw = up_f32(w); + void* db = up_f32(b); + /* The output starts as the residual where the residual is the output. */ + std::vector y0(res.size(), 0.0f); + if (g.res == 2) y0 = res; + void* dy = g.bf16 ? up_bf16(y0) : up_f32(y0); + std::vector rcopy = res; + void* dr = g.res == 1 ? (g.bf16 ? up_bf16(rcopy) : up_f32(rcopy)) : nullptr; + RadTensor ta = T(da, RAD_F32, { g.M, g.K }); + ta.stride[0] = lda; + RadTensor ty = T(dy, ydt, { g.M, g.N }); + ty.stride[0] = ldc; + RadTensor tr = g.res == 2 ? ty : T(dr, ydt, { g.M, g.N }); + if (g.res == 1) tr.stride[0] = ldc; + if (!g.res) absent(tr); + std::vector ps = { PI("M", g.M), PI("N", g.N), PI("K", g.K), PS("dtype", "f32") }; + if (g.act) ps.push_back(PS("act", g.act == 1 ? "gelu" : "gelu_tanh")); + const std::string nm = fmt("gemm_f32_nt_bias M %lld N %lld K %lld -> %s%s%s", + (long long)g.M, (long long)g.N, (long long)g.K, + g.bf16 ? "bf16" : "f32", g.act ? " +act" : "", + g.res == 2 ? " +res in place" : g.res ? " +res" : ""); + const int rc = launch(r, { ta, T(dw, RAD_F32, { g.N, g.K }), T(db, RAD_F32, { g.N }), tr, ty }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector all = g.bf16 ? down_bf16(dy, (size_t)(g.M * ldc)) + : down_f32(dy, (size_t)(g.M * ldc)); + std::vector got((size_t)(g.M * g.N)), want((size_t)(g.M * g.N)); + int64_t pad_moved = 0; + for (int64_t m = 0; m < g.M; ++m) { + for (int64_t n = 0; n < g.N; ++n) { + double acc = 0; + for (int64_t k = 0; k < g.K; ++k) + acc += (double)a[(size_t)(m * lda + k)] * w[(size_t)(n * g.K + k)]; + float t = (float)acc + b[(size_t)n]; + if (g.bf16) t = bfr(t); + if (g.act) { t = g.act == 1 ? gelu_erf(t) : gelu_tanh(t); if (g.bf16) t = bfr(t); } + if (g.res) { t = res[(size_t)(m * ldc + n)] + t; if (g.bf16) t = bfr(t); } + want[(size_t)(m * g.N + n)] = t; + got[(size_t)(m * g.N + n)] = all[(size_t)(m * ldc + n)]; + } + /* The columns past N keep what they held. */ + for (int64_t n = g.N; n < ldc; ++n) { + const float before = g.res == 2 ? res[(size_t)(m * ldc + n)] : 0.0f; + if (all[(size_t)(m * ldc + n)] != before) ++pad_moved; + } + } + if (g.bf16) check(nm + " numerics", got, want, 1e-2); + else check_f32(nm + " numerics", got, want, 2e-5); + if (g.cpad) ok((nm + " leaves the columns past N").c_str(), pad_moved == 0, + fmt("%lld written", (long long)pad_moved)); + } +} + +/* gemm_nt_q_bias at fp8a8 at a modulation projection's geometry (N 16128 of K 2688, up to 64 + * timesteps), into a column block of a table three blocks wide, and a small dense one. The host + * reads the same E4M3 codes and scales; only the summation order differs. */ +void gemm_q_bias_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "gemm_fp8a8_bias_nt_m16"); + if (!r) { ok("gemm_fp8a8_bias_nt_m16", false, "row absent"); return; } + struct G { int64_t M, N, K; bool slice; }; + for (const G& g : { G{ 1, 16128, 2688, true }, G{ 24, 16128, 2688, true }, + G{ 64, 16128, 2688, true }, G{ 5, 512, 640, false }, + G{ 40, 256, 384, true } }) { + const int64_t sn = (g.N + 127) / 128, sk = (g.K + 127) / 128; + std::vector wf((size_t)(g.N * g.K)); + for (int64_t i = 0; i < g.N * g.K; ++i) + wf[(size_t)i] = (float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) * 5e-5f * + (float)(1 + (i / g.K / 128) % 3); + const Planes p = fp8_block_planes(wf, g.N, g.K); + std::vector lp = { PI("N", g.N), PI("K", g.K), PI("group", 128) }; + std::vector wq, wsb; + const int rq = stored(r, lp, 2, p, { "codes" }, &wq); + const int rs = stored(r, lp, 3, p, { "scale" }, &wsb); + const std::string nm = fmt("gemm_fp8a8_bias_nt_m16 M %lld N %lld K %lld%s", (long long)g.M, + (long long)g.N, (long long)g.K, g.slice ? " into a column block" : ""); + if (rq != RAD_OK || rs != RAD_E_UNSUPPORTED) { + ok(nm.c_str(), false, fmt("layout rc %d / %d", rq, rs)); + continue; + } + std::vector xq((size_t)(g.M * g.K)); + for (size_t i = 0; i < xq.size(); ++i) xq[i] = st_rand_e4m3((uint32_t)i * 7u + 3u); + std::vector xs((size_t)(g.M * sk)); + for (size_t i = 0; i < xs.size(); ++i) xs[i] = 0.01f + 0.002f * (float)(st_mix32((uint32_t)i) % 50); + std::vector bias = randv((size_t)g.N, 0.5f); + void* dx = dalloc(xq.size()); + st_memcpy(dx, xq.data(), xq.size(), hipMemcpyHostToDevice); + void* dxs = up_f32(xs); + void* dw = dalloc(wq.size()); + st_memcpy(dw, wq.data(), wq.size(), hipMemcpyHostToDevice); + void* dws = dalloc(wsb.size()); + st_memcpy(dws, wsb.data(), wsb.size(), hipMemcpyHostToDevice); + void* db = up_bf16(bias); + const int64_t width = g.slice ? 3 * g.N : g.N, c0 = g.slice ? g.N : 0; + const uint16_t sentinel = 0x7f7f; + std::vector y0((size_t)(g.M * width), sentinel); + void* dy = dalloc(y0.size() * 2); + st_memcpy(dy, y0.data(), y0.size() * 2, hipMemcpyHostToDevice); + RadTensor ty = T((uint16_t*)dy + c0, RAD_BF16, { g.M, g.N }); + ty.stride[0] = width; + const int rc = launch(r, { T(dx, RAD_F8E4M3, { g.M, g.K }), T(dxs, RAD_F32, { g.M, sk }), + T(dw, RAD_F8E4M3, { g.N, g.K }), T(dws, RAD_BF16, { sn, sk }), + T(db, RAD_BF16, { g.N }), ty }, + { PI("M", g.M), PI("N", g.N), PI("K", g.K), PI("group", 128), + PS("dtype", "fp8a8") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector yo((size_t)(g.M * width)); + st_memcpy(yo.data(), dy, yo.size() * 2, hipMemcpyDeviceToHost); + /* Every row, a column in eleven past the first 64 (all of a small N), each operand + * decoded once. */ + std::vector xd((size_t)(g.M * g.K)), wrow((size_t)g.K); + for (int64_t m = 0; m < g.M; ++m) + for (int64_t k = 0; k < g.K; ++k) + xd[(size_t)(m * g.K + k)] = (double)h_e4m3(xq[(size_t)(m * g.K + k)]) * + xs[(size_t)(m * sk + k / 128)]; + std::vector got, want; + const uint8_t* wc = p.data[0].data(); + for (int64_t n = 0; n < g.N; ++n) { + if (n >= 64 && n % 11) continue; + for (int64_t k = 0; k < g.K; ++k) + wrow[(size_t)k] = (double)h_e4m3(wc[(size_t)(n * g.K + k)]) * + rad_load_f32(p.data[1].data(), RAD_BF16, (n / 128) * sk + k / 128); + for (int64_t m = 0; m < g.M; ++m) { + double acc = 0; + for (int64_t k = 0; k < g.K; ++k) acc += wrow[(size_t)k] * xd[(size_t)(m * g.K + k)]; + want.push_back((float)acc + bias[(size_t)n]); + got.push_back(h_bf16(yo[(size_t)(m * width + c0 + n)])); + } + } + check(nm + " numerics", got, want, 1e-2); + int64_t moved = 0; + for (int64_t m = 0; m < g.M; ++m) + for (int64_t c = 0; c < width; ++c) + if ((c < c0 || c >= c0 + g.N) && yo[(size_t)(m * width + c)] != sentinel) ++moved; + if (g.slice) ok((nm + " leaves the table's other columns").c_str(), moved == 0, + fmt("%lld written", (long long)moved)); + } +} + +/* The f32 elementwise rows and the f32 forms of the bf16 rows, as a video decoder and a vocoder + * issue them. */ +void add_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "add_f32"); + if (!r) { ok("add_f32", false, "row absent"); return; } + struct C { int64_t M, n; double div; int alias; bool bcast; }; + for (const C& c : { C{ 1000, 8, 3.0, 0, false }, C{ 70000, 8, 1.0, 1, false }, + C{ 37, 2048, 1.0, 1, false }, C{ 37, 33, 1.0, 0, true }, + C{ 64, 100, 3.0, 1, false } }) { + std::vector a = randv((size_t)(c.M * c.n), 2.0f); + std::vector b = randv((size_t)(c.bcast ? c.n : c.M * c.n), 2.0f); + void* da = up_f32(a); + void* db = up_f32(b); + void* dy = c.alias ? da : dalloc((size_t)(c.M * c.n) * 4); + std::vector ps = { PI("M", c.M), PI("n", c.n), PS("dtype", "f32") }; + if (c.div != 1.0) ps.push_back(PF("div", c.div)); + const std::string nm = fmt("add_f32 %lld x %lld%s%s%s", (long long)c.M, (long long)c.n, + c.div != 1.0 ? " div 3" : "", c.alias ? " in place" : "", + c.bcast ? " broadcast" : ""); + const int rc = launch(r, { T(da, RAD_F32, { c.M, c.n }), + T(db, RAD_F32, { c.bcast ? 1 : c.M, c.n }), + T(dy, RAD_F32, { c.M, c.n }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(a.size()); + for (int64_t m = 0; m < c.M; ++m) + for (int64_t i = 0; i < c.n; ++i) { + float s = a[(size_t)(m * c.n + i)] + b[(size_t)(c.bcast ? i : m * c.n + i)]; + if (c.div != 1.0) s = s / (float)c.div; + want[(size_t)(m * c.n + i)] = s; + } + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld elements differ", (long long)bad)); + } + /* div 0 is refused. */ + const int rc = launch(r, { TA(RAD_F32, { 4, 8 }), TA(RAD_F32, { 4, 8 }), TA(RAD_F32, { 4, 8 }) }, + { PI("M", 4), PI("n", 8), PS("dtype", "f32"), PF("div", 0.0) }); + ok("add_f32 refuses div 0", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); +} + +void add_bf16_div_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "add_bf16"); + if (!r) { ok("add_bf16 div", false, "row absent"); return; } + const int64_t M = 5, n = 300; + std::vector a = randv((size_t)(M * n), 2.0f), b = randv((size_t)(M * n), 2.0f); + void* da = up_bf16(a); + void* db = up_bf16(b); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(da, RAD_BF16, { M, n }), T(db, RAD_BF16, { M, n }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16"), PF("div", 3.0) }); + if (rc != RAD_OK) { ok("add_bf16 div 3", false, "rc " + std::to_string(rc)); return; } + std::vector want(a.size()); + for (size_t i = 0; i < a.size(); ++i) want[i] = bfr(bfr(a[i] + b[i]) / 3.0f); + const int64_t bad = differ(down_bf16(dy, want.size()), want); + ok("add_bf16 div 3 exact (rd(rd(a + b) / 3))", bad == 0, fmt("%lld elements differ", (long long)bad)); +} + +void mul_weight_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "mul_weight_f32"); + if (!r) { ok("mul_weight_f32", false, "row absent"); return; } + const int64_t M = 37, n = 2048; + for (const int xf : { 0, 1 }) + for (const int64_t wn : { n, (int64_t)1 }) { + std::vector x = randv((size_t)(M * n), 3.0f), w = randv((size_t)wn, 0.1f); + void* dx = xf ? up_f32(x) : up_bf16(x); + void* dw = up_f32(w); + void* dy = dalloc((size_t)(M * n) * 4); + const int rc = launch(r, { T(dx, xf ? RAD_F32 : RAD_BF16, { M, n }), T(dw, RAD_F32, { wn }), + T(dy, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "f32") }); + const std::string nm = fmt("mul_weight_f32 %s x, f32 weight of %lld", xf ? "f32" : "bf16", + (long long)wn); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(x.size()); + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) + want[(size_t)(m * n + i)] = x[(size_t)(m * n + i)] * w[(size_t)(wn == 1 ? 0 : i)]; + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld elements differ", (long long)bad)); + } +} + +void silu_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "silu_f32"); + if (!r) { ok("silu_f32", false, "row absent"); return; } + const int64_t M = 128, n = 5376; + std::vector x = randv((size_t)(M * n), 6.0f); + void* dx = up_f32(x); + for (const bool bf : { false, true }) { + void* dy = dalloc((size_t)(M * n) * (bf ? 2 : 4)); + const int rc = launch(r, { T(dx, RAD_F32, { M, n }), T(dy, bf ? RAD_BF16 : RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "f32") }); + const std::string nm = fmt("silu_f32 -> %s", bf ? "bf16" : "f32"); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(x.size()); + for (size_t i = 0; i < x.size(); ++i) + want[i] = x[i] * (1.0f / (1.0f + (float)std::exp(-(double)x[i]))); + if (bf) check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-3); + else check_f32(nm + " numerics", down_f32(dy, want.size()), want, 1e-6); + } +} + +void norm_f32_rows_cases(const Plugin& pl, bool layer) { + const char* name = layer ? "layernorm_bf16" : "rmsnorm_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t M = 9, n = 2048, ld = 2100; + const float eps = 1e-5f; + std::vector x = randv((size_t)(M * ld), 30.0f), w = randv((size_t)n, 1.0f), + b = randv((size_t)n, 0.5f); + for (size_t i = 0; i < x.size(); ++i) x[i] += 7.0f; /* a mean the layer norm must remove */ + void* dx = up_f32(x); + void* dw = up_f32(w); + void* db = up_f32(b); + void* dy = dalloc((size_t)(M * n) * 2); + RadTensor tx = T(dx, RAD_F32, { M, n }); + tx.stride[0] = ld; + std::vector ts = { tx, T(dw, RAD_F32, { n }) }; + if (layer) ts.push_back(T(db, RAD_F32, { n })); + ts.push_back(T(dy, RAD_BF16, { M, n })); + const int rc = launch(r, ts, { PI("M", M), PI("n", n), PF("eps", (double)eps), + PS("dtype", "bf16") }); + const std::string nm = fmt("%s over f32 rows", name); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + for (int64_t m = 0; m < M; ++m) { + const float* xr = x.data() + m * ld; + double mean = 0, ss = 0; + if (layer) { for (int64_t i = 0; i < n; ++i) mean += xr[i]; mean /= (double)n; } + for (int64_t i = 0; i < n; ++i) ss += ((double)xr[i] - mean) * ((double)xr[i] - mean); + const double s = 1.0 / std::sqrt(ss / (double)n + eps); + for (int64_t i = 0; i < n; ++i) + want[(size_t)(m * n + i)] = layer ? (float)(((double)xr[i] - mean) * s * w[(size_t)i] + b[(size_t)i]) + : (float)((double)xr[i] * s * w[(size_t)i]); + } + check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2); +} + +void timestep_f32_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "timestep_embed_f32"); + if (!r) { ok("timestep_embed_f32", false, "row absent"); return; } + const int64_t M = 64, n = 256, h = n / 2; + std::vector t((size_t)M); + for (int64_t m = 0; m < M; ++m) t[(size_t)m] = (float)m / (float)M; + void* dt = up_f32(t); + void* dy = dalloc((size_t)(M * n) * 4); + const int rc = launch(r, { T(dt, RAD_F32, { M }), T(dy, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PF("scale", 1.0), PF("max_period", 10000.0), + PS("dtype", "f32") }); + if (rc != RAD_OK) { ok("timestep_embed_f32", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + const float coef = (float)(-std::log(10000.0)); + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < h; ++i) { + const float f = (float)std::exp((double)(coef * (float)i / (float)h)); + const float arg = t[(size_t)m] * f; + want[(size_t)(m * n + i)] = (float)std::cos((double)arg); + want[(size_t)(m * n + h + i)] = (float)std::sin((double)arg); + } + check_f32("timestep_embed_f32 numerics", down_f32(dy, want.size()), want, 1e-6); +} + +void randn_f32_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "randn_lanes_f32"); + if (!r) { ok("randn_lanes_f32", false, "row absent"); return; } + /* Two lanes of 300 rows by 96; the entry draws into lane 1 (its first step), 250 rows. */ + const int64_t n = 96, stride = 300, len = 250; + const uint64_t seed = 0x1234567890abcdefull; + void* dd = dalloc((size_t)(2 * stride * n) * 4); + const int rc = launch(r, { TI32({ 1 }, { 1 }), + T(up_i32({ (int32_t)(uint32_t)seed, (int32_t)(uint32_t)(seed >> 32) }), + RAD_U32, { 2 }), + TI32({ 1 }, { 1 }), TI32({ 2 }, { 0, (int32_t)len }), + T(dd, RAD_F32, { 2 * stride, n }) }, + { PI("M", stride), PI("n", n), PI("stride", stride), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok("randn_lanes_f32", false, "rc " + std::to_string(rc)); return; } + const std::vector got = down_f32(dd, (size_t)(2 * stride * n)); + std::vector g1, want; + int64_t stray = 0; + for (int64_t k = 0; k < 2 * stride; ++k) + for (int64_t c = 0; c < n; ++c) { + const float v = got[(size_t)(k * n + c)]; + const int64_t lk = k - stride; + if (lk >= 0 && lk < len) { + g1.push_back(v); + want.push_back(rad_philox_normal(seed, (uint64_t)(lk * n + c))); + } else if (v != 0.0f) { + ++stray; + } + } + check_f32("randn_lanes_f32 against the host's Philox stream", g1, want, 1e-6); + ok("randn_lanes_f32 writes only its lane's rows", stray == 0, fmt("%lld stray", (long long)stray)); +} + +void interleave2_f32_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "interleave2_bf16"); + if (!r) { ok("interleave2 f32", false, "row absent"); return; } + const int64_t n = 70001; + std::vector s = randv((size_t)(2 * n), 1.0f); + void* ds = up_f32(s); + void* dy = dalloc((size_t)(2 * n) * 4); + const int rc = launch(r, { T(ds, RAD_F32, { n, 1 }), T((float*)ds + n, RAD_F32, { n, 1 }), + T(dy, RAD_F32, { n, 2 }) }, + { PI("M", n), PS("dtype", "f32") }); + if (rc != RAD_OK) { ok("interleave2 f32", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(2 * n)); + for (int64_t i = 0; i < n; ++i) { + want[(size_t)(2 * i)] = s[(size_t)i]; + want[(size_t)(2 * i + 1)] = s[(size_t)(n + i)]; + } + const int64_t bad = differ(down_f32(dy, want.size()), want); + ok("interleave2 f32 streams exact", bad == 0, fmt("%lld differ", (long long)bad)); +} + +void chan_affine_cases(const Plugin& pl, const char* row) { + const int64_t M = 1152, n = 32; + std::string mul, add; + std::vector mv((size_t)n), av((size_t)n); + for (int64_t c = 0; c < n; ++c) { + mv[(size_t)c] = 0.5 + 0.0371 * (double)c; + av[(size_t)c] = -0.3 + 0.0123 * (double)c; + mul += fmt("%s%.9g", c ? " " : "", mv[(size_t)c]); + add += fmt("%s%.9g", c ? " " : "", av[(size_t)c]); + } + for (const int rnd : { 0, 1 }) + for (const char* mode : { "fma", "inv" }) { + const RadKernelInfo* r = find(pl, row); + if (!r) { ok(row, false, "row absent"); return; } + const bool f32 = !std::strcmp(row, "chan_affine_f32"); + std::vector x = randv((size_t)(M * n), 3.0f); + void* dx = f32 ? up_f32(x) : up_bf16(x); + void* dy = dalloc((size_t)(M * n) * (f32 ? 4 : 2)); + const uint32_t dt = f32 ? RAD_F32 : RAD_BF16; + const int rc = launch(r, { T(dx, dt, { M, n }), T(dy, dt, { M, n }) }, + { PI("M", M), PI("n", n), PS("mul", mul.c_str()), + PS("add", add.c_str()), PS("mode", mode), + PS("dtype", f32 ? "f32" : "bf16"), PI("round", rnd) }); + const std::string nm = fmt("%s round %d %s", row, rnd, mode); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + auto rd = [&](float v) { return f32 ? v : bfr(v); }; + std::vector want(x.size()); + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < n; ++c) { + const float mu = rnd ? bfr((float)mv[(size_t)c]) : (float)mv[(size_t)c]; + const float ad = rnd ? bfr((float)av[(size_t)c]) : (float)av[(size_t)c]; + const float v = x[(size_t)(m * n + c)]; + const float t = std::strcmp(mode, "inv") ? v * mu : v - ad; + const float tr = rnd ? rd(t) : t; + want[(size_t)(m * n + c)] = rd(std::strcmp(mode, "inv") ? tr + ad : tr / mu); + } + const std::vector got = f32 ? down_f32(dy, want.size()) : down_bf16(dy, want.size()); + const int64_t bad = differ(got, want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld differ", (long long)bad)); + } +} + +void gate_add_none_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "gate_add_bf16"); + if (!r) { ok("gate_add_bf16 act none", false, "row absent"); return; } + const int64_t M = 30, n = 5376; + const std::vector cu = { 0, 7, 30 }; + std::vector y = randv((size_t)(M * n), 2.0f), g = randv((size_t)(2 * n), 1.5f), + x = randv((size_t)(M * n), 3.0f); + void* dy = up_bf16(y); + void* dg = up_bf16(g); + for (const char* act : { "none", "tanh" }) { + std::vector xx = x; + void* dxa = up_bf16(xx); + const int rc = launch(r, { T(dy, RAD_BF16, { M, n }), T(dg, RAD_BF16, { 2, n }), + T(up_i32(cu), RAD_I32, { 3 }), T(dxa, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16"), PS("act", act) }); + const std::string nm = fmt("gate_add_bf16 act %s", act); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(xx.size()); + for (int64_t m = 0; m < M; ++m) { + const int64_t e = m < 7 ? 0 : 1; + for (int64_t i = 0; i < n; ++i) { + const float gv = g[(size_t)(e * n + i)]; + const float t = std::strcmp(act, "none") ? bfr((float)std::tanh((double)gv)) : gv; + want[(size_t)(m * n + i)] = bfr(xx[(size_t)(m * n + i)] + bfr(t * y[(size_t)(m * n + i)])); + } + } + const std::vector got = down_bf16(dxa, want.size()); + if (std::strcmp(act, "none")) { + check(nm + " numerics", got, want, 1e-2); + } else { + const int64_t bad = differ(got, want); + ok((nm + " exact").c_str(), bad == 0, fmt("%lld differ", (long long)bad)); + } + } +} + +/* conv1d at f32 at a BigVGAN's geometries: conv_pre's 2048 -> 1024 over 7 taps, the AMP blocks' + * dilated 3/7/11 taps with the residual the output itself, the direct kernel's 8 channels and the + * final conv's one with its clamp. Two sequences, so a tap crossing a sequence's edge reads zero. */ +void conv1d_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv1d_f32"); + if (!r) { ok("conv1d_f32", false, "row absent"); return; } + struct C { int64_t cin, cout, k, dil, M0, M1; int act, bias, res; }; /* res 2: y itself */ + for (const C& c : { C{ 2048, 1024, 7, 1, 9, 15, 0, 1, 0 }, C{ 64, 128, 7, 1, 37, 60, 0, 1, 0 }, + C{ 32, 32, 11, 5, 70, 41, 0, 1, 2 }, C{ 16, 16, 3, 3, 50, 77, 0, 1, 1 }, + C{ 48, 40, 3, 1, 33, 30, 1, 1, 0 }, C{ 8, 8, 11, 5, 90, 64, 0, 1, 2 }, + C{ 8, 1, 7, 1, 100, 99, 2, 0, 0 }, C{ 64, 64, 11, 1, 200, 137, 2, 1, 2 } }) { + const std::vector cu = { 0, (int32_t)c.M0, (int32_t)(c.M0 + c.M1) }; + const int64_t M = c.M0 + c.M1; + std::vector x = randv((size_t)(M * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cout * c.cin * c.k), 1.0f / std::sqrt((float)(c.cin * c.k))); + std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f); + std::vector ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout), PI("k", c.k), + PI("dil", c.dil), + PS("act", c.act == 1 ? "tanh" : c.act == 2 ? "clamp" : "none"), + PS("dtype", "f32") }; + const std::string nm = fmt("conv1d_f32 cin %lld cout %lld k %lld dil %lld%s%s%s", (long long)c.cin, + (long long)c.cout, (long long)c.k, (long long)c.dil, + c.bias ? " +bias" : "", c.res == 2 ? " +res in place" : c.res ? " +res" : "", + c.act == 1 ? " tanh" : c.act == 2 ? " clamp" : ""); + void* dw = stored_weight_f32(r, ps, w, c.cout, c.cin * c.k, nm.c_str()); + if (!dw) continue; + void* dx = up_f32(x); + void* db = up_f32(b); + void* dy = up_f32(c.res == 2 ? res : std::vector((size_t)(M * c.cout), 0.0f)); + void* dr = up_f32(res); + RadTensor ty = T(dy, RAD_F32, { M, c.cout }); + RadTensor tr = c.res == 2 ? ty : T(dr, RAD_F32, { M, c.cout }); + RadTensor tb = T(db, RAD_F32, { c.cout }); + if (!c.res) absent(tr); + if (!c.bias) absent(tb); + const int rc = launch(r, { T(dx, RAD_F32, { M, c.cin }), + T(dw, RAD_F32, { c.cout, c.cin, c.k }), + T(up_i32(cu), RAD_I32, { 3 }), tr, ty, tb }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t pad = c.dil * (c.k - 1) / 2; + std::vector want((size_t)(M * c.cout)); + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; + for (int64_t co = 0; co < c.cout; ++co) { + double acc = 0; + for (int64_t kk = 0; kk < c.k; ++kk) { + const int64_t ir = row + kk * c.dil - pad; + if (ir < s0 || ir >= s1) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += (double)w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)]; + } + float v = (float)acc; + if (c.bias) v += b[(size_t)co]; + if (c.res) v += res[(size_t)(row * c.cout + co)]; + if (c.act == 1) v = (float)std::tanh((double)v); + if (c.act == 2) v = v < -1.0f ? -1.0f : (v > 1.0f ? 1.0f : v); + want[(size_t)(row * c.cout + co)] = v; + } + } + check_f32(nm + " numerics", down_f32(dy, want.size()), want, 2e-5); + } +} + +/* conv_t1d at f32 at BigVGAN's upsamplers (k 9 stride 5 pad 2, k 4 stride 2 pad 1), the symmetric + * default pad, a pad past a stride and a kernel of one stride, against libref's rule: output row o + * of a sequence sums its input rows i with 0 <= o + pad - i stride < k. */ +void conv_t1d_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv_t1d_f32"); + if (!r) { ok("conv_t1d_f32", false, "row absent"); return; } + struct C { int64_t cin, cout, s, k, pad; }; /* pad -1: absent */ + for (const C& c : { C{ 64, 32, 5, 9, 2 }, C{ 16, 8, 2, 4, 1 }, C{ 16, 32, 5, 9, -1 }, + C{ 16, 16, 4, 16, 5 }, C{ 24, 16, 3, 3, 0 }, C{ 128, 128, 2, 4, 1 }, + C{ 40, 72, 5, 9, 7 } }) { + const std::vector cu = { 0, 5, 12, 40 }; + const int64_t R = 40, O = R * c.s; + std::vector x = randv((size_t)(R * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cin * c.cout * c.k), 0.3f); + std::vector b = randv((size_t)c.cout, 0.5f); + std::vector ps = { PI("M", R), PI("cin", c.cin), PI("cout", c.cout), + PI("stride", c.s), PS("dtype", "f32"), PI("k", c.k) }; + if (c.pad >= 0) ps.push_back(PI("pad", c.pad)); + const std::string nm = fmt("conv_t1d_f32 cin %lld cout %lld stride %lld k %lld pad %lld", + (long long)c.cin, (long long)c.cout, (long long)c.s, (long long)c.k, + (long long)c.pad); + void* dw = stored_weight_f32(r, ps, w, c.cin, c.cout * c.k, nm.c_str()); + if (!dw) continue; + void* dx = up_f32(x); + void* db = up_f32(b); + void* dy = dalloc((size_t)(O * c.cout) * 4); + const int rc = launch(r, { T(dx, RAD_F32, { R, c.cin }), T(dw, RAD_F32, { c.cin, c.cout, c.k }), + T(db, RAD_F32, { c.cout }), T(up_i32(cu), RAD_I32, { 4 }), + T(dy, RAD_F32, { O, c.cout }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t P = c.pad >= 0 ? c.pad : (c.k - c.s) / 2; + std::vector want((size_t)(O * c.cout)); + for (size_t e = 0; e + 1 < cu.size(); ++e) { + const int64_t i0 = cu[e], L = cu[e + 1] - cu[e]; + for (int64_t o = 0; o < L * c.s; ++o) + for (int64_t co = 0; co < c.cout; ++co) { + double acc = b[(size_t)co]; + for (int64_t i = 0; i < L; ++i) { + const int64_t tap = o + P - i * c.s; + if (tap < 0 || tap >= c.k) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += (double)w[(size_t)((ci * c.cout + co) * c.k + tap)] * + x[(size_t)((i0 + i) * c.cin + ci)]; + } + want[(size_t)((i0 * c.s + o) * c.cout + co)] = (float)acc; + } + } + check_f32(nm + " numerics", down_f32(dy, want.size()), want, 2e-5); + } +} + +/* conv1d at bf16 with the clamp a vocoder's output takes. */ +void conv1d_bf16_clamp_case(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv1d_bf16"); + if (!r) { ok("conv1d_bf16 clamp", false, "row absent"); return; } + const int64_t cin = 16, cout = 32, k = 7, M = 40; + const std::vector cu = { 0, 17, 40 }; + std::vector x = randv((size_t)(M * cin), 2.0f), w = randv((size_t)(cout * cin * k), 0.4f); + void* dx = up_bf16(x); + for (auto& v : w) v = bfr(v); + std::vector ps = { PI("M", M), PI("cin", cin), PI("cout", cout), PI("k", k), PI("dil", 1), + PS("act", "clamp"), PS("dtype", "bf16") }; + void* dw = stored_weight(r, ps, w, cout, cin * k, "conv1d_bf16 clamp"); + if (!dw) return; + void* dy = dalloc((size_t)(M * cout) * 2); + RadTensor tr = TA(RAD_BF16, { M, cout }), tb = TA(RAD_BF16, { cout }); + absent(tr); + absent(tb); + const int rc = launch(r, { T(dx, RAD_BF16, { M, cin }), T(dw, RAD_BF16, { cout, cin, k }), + T(up_i32(cu), RAD_I32, { 3 }), tr, T(dy, RAD_BF16, { M, cout }), tb }, + ps); + if (rc != RAD_OK) { ok("conv1d_bf16 clamp", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * cout)); + int64_t clamped = 0; + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; + for (int64_t co = 0; co < cout; ++co) { + float acc = 0.0f; + for (int64_t kk = 0; kk < k; ++kk) { + const int64_t ir = row + kk - 3; + if (ir < s0 || ir >= s1) continue; + for (int64_t ci = 0; ci < cin; ++ci) + acc += w[(size_t)((co * cin + ci) * k + kk)] * x[(size_t)(ir * cin + ci)]; + } + if (acc < -1.0f || acc > 1.0f) ++clamped; + want[(size_t)(row * cout + co)] = acc < -1.0f ? -1.0f : (acc > 1.0f ? 1.0f : acc); + } + } + check("conv1d_bf16 clamp numerics", down_bf16(dy, want.size()), want, 1e-2); + ok("conv1d_bf16 clamp case clamps", clamped > 0, fmt("%lld clamped", (long long)clamped)); +} + +/* qk_norm_rope's axial mode, f32 positions, absent gains and rotary_dim 0, at a video + * transformer's geometry (head 128, 96 rotated in sections 16 16 16, bf16 gains, f32 (t, h, w) + * positions of a [3, max] plane) and a video decoder's (head 64, 48 rotated in 8 8 8, no gains), + * and the norm alone (a refiner's). A port of libref's ref_qk_norm_rope. */ +void qk_axial_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16"); + if (!r) { ok("qk_norm_rope_bf16 axial", false, "row absent"); return; } + struct C { int64_t hd, nh, rot; int sec; bool gains; int pos; double theta; }; /* pos 0 none, 1 f32 [3, max], 2 i32 [M] */ + for (const C& c : { C{ 128, 4, 96, 16, true, 1, 10000.0 }, C{ 64, 6, 48, 8, false, 1, 100.0 }, + C{ 128, 2, 0, 0, true, 0, 10000.0 }, C{ 128, 3, 96, 16, true, 2, 10000.0 }, + C{ 64, 2, 0, 0, false, 1, 100.0 } }) { + const int64_t M = 37, pmax = 50, width = 3 * c.nh * c.hd, half = c.rot / 2; + const float eps = 1e-5f; + std::vector x = randv((size_t)(M * width), 3.0f); + std::vector qg = randv((size_t)c.hd, 0.5f), kg = randv((size_t)c.hd, 0.5f); + for (auto& v : qg) v = bfr(1.0f + v); + for (auto& v : kg) v = bfr(1.0f + v); + std::vector pf((size_t)(3 * pmax)); + for (size_t i = 0; i < pf.size(); ++i) pf[i] = (float)(st_mix32((uint32_t)i) % 4001) * 0.01f - 20.0f; + std::vector pi32((size_t)M); + for (int64_t m = 0; m < M; ++m) pi32[(size_t)m] = (int32_t)(m * 7 + 3); + std::vector xx = x; + void* dq = up_bf16(xx); + x = xx; + RadTensor tp = c.pos == 1 ? T(up_f32(pf), RAD_F32, { 3, M }) : T(up_i32(pi32), RAD_I32, { M }); + if (c.pos == 1) tp.stride[0] = pmax; + if (c.pos == 0) absent(tp); + RadTensor tqw = T(up_bf16(qg), RAD_BF16, { c.hd }), tkw = T(up_bf16(kg), RAD_BF16, { c.hd }); + if (!c.gains) { absent(tqw); absent(tkw); } + std::vector ps = { PI("M", M), PI("head_dim", c.hd), PI("n_head", c.nh), + PI("n_head_kv", c.nh), PF("theta", c.theta), PF("eps", (double)eps), + PI("rotary_dim", c.rot) }; + std::string secs; + if (c.rot) { + secs = fmt("%d %d %d", c.sec, c.sec, c.sec); + ps.push_back(PS("mode", "axial")); + ps.push_back(PS("sections", secs.c_str())); + } + const std::string nm = fmt("qk_norm_rope_bf16 head %lld rot %lld%s%s", (long long)c.hd, + (long long)c.rot, c.gains ? " gains" : " no gains", + c.pos == 1 ? " f32 [3, M] positions" : c.pos == 2 ? " i32 [M] positions" + : " no positions"); + const int rc = launch(r, { T(dq, RAD_BF16, { M, width }), tp, tqw, tkw }, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want = x; + for (int64_t m = 0; m < M; ++m) + for (int64_t h = 0; h < 2 * c.nh; ++h) { + const size_t base = (size_t)(m * width + h * c.hd); + double ss = 0; + for (int64_t e = 0; e < c.hd; ++e) ss += (double)x[base + (size_t)e] * x[base + (size_t)e]; + const float sc = 1.0f / std::sqrt((float)(ss / (double)c.hd) + eps); + std::vector n((size_t)c.hd); + for (int64_t e = 0; e < c.hd; ++e) { + const float g = c.gains ? (h < c.nh ? qg : kg)[(size_t)e] : 1.0f; + n[(size_t)e] = bfr(c.gains ? x[base + (size_t)e] * sc * g : x[base + (size_t)e] * sc); + want[base + (size_t)e] = n[(size_t)e]; + } + for (int64_t i = 0; i < half; ++i) { + const int64_t sc_i = i / c.sec, j = i % c.sec; + const float p = c.pos == 1 ? pf[(size_t)(sc_i * pmax + m)] : (float)pi32[(size_t)m]; + const float inv = 1.0f / (float)std::pow((double)c.theta, + (double)((float)(2 * j) / (float)(2 * c.sec))); + const float ang = p * inv; + const float cs = (float)std::cos((double)ang), sn = (float)std::sin((double)ang); + want[base + (size_t)i] = n[(size_t)i] * cs - n[(size_t)(i + half)] * sn; + want[base + (size_t)(i + half)] = n[(size_t)i] * sn + n[(size_t)(i + half)] * cs; + } + } + check(nm + " numerics", down_bf16(dq, want.size()), want, 1e-2); + } + /* A rotation without positions is refused. */ + const int rc = launch(r, { TA(RAD_BF16, { 4, 3 * 2 * 128 }), RadTensor{}, TA(RAD_BF16, { 128 }), + TA(RAD_BF16, { 128 }) }, + { PI("M", 4), PI("head_dim", 128), PI("n_head", 2), PI("n_head_kv", 2), + PF("theta", 1e4), PF("eps", 1e-5), PI("rotary_dim", 96), + PS("mode", "axial"), PS("sections", "16 16 16") }); + ok("qk_norm_rope_bf16 refuses a rotation without positions", rc == RAD_E_INVAL, + "rc " + std::to_string(rc)); +} + +/* One host softmax-attention row for head `h` of query row `i`, keys [b0, b1), over a fused + * [rows, 3 nh hd] qkv row. */ +void attn_row_ref(const std::vector& qkv, int64_t width, int64_t nh, int64_t hd, int64_t i, + int64_t h, int64_t b0, int64_t b1, double scale, float* out) { + std::vector sc((size_t)(b1 - b0)); + double mx = -1e300; + for (int64_t j = b0; j < b1; ++j) { + double d = 0; + for (int64_t e = 0; e < hd; ++e) + d += (double)qkv[(size_t)(i * width + h * hd + e)] * qkv[(size_t)(j * width + nh * hd + h * hd + e)]; + sc[(size_t)(j - b0)] = d * scale; + mx = std::max(mx, sc[(size_t)(j - b0)]); + } + double sum = 0; + for (double& v : sc) { v = std::exp(v - mx); sum += v; } + for (int64_t e = 0; e < hd; ++e) { + double a = 0; + for (int64_t j = b0; j < b1; ++j) + a += sc[(size_t)(j - b0)] * qkv[(size_t)(j * width + 2 * nh * hd + h * hd + e)]; + out[e] = (float)(a / sum); + } +} + +/* attn_dense at head_dim 128, non-causal, over one long sequence (a video transformer's packed + * sequence), and at head_dim 64 over consecutive 1797-row documents (a video decoder's tiles), + * both reading q, k and v as column slices of one fused row. Every 29th query row is checked. */ +void attn_long_case(const Plugin& pl, const char* name, int64_t hd, int64_t nh, + std::vector cu) { + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t total = cu.back(), wq = nh * hd, width = 3 * wq; + std::vector qkv = randv((size_t)(total * width), 1.5f); + void* d = up_bf16(qkv); + auto col = [&](int64_t first) { + RadTensor t = T((uint16_t*)d + first, RAD_BF16, { total, wq }); + t.stride[0] = width; + return t; + }; + void* dout = dalloc((size_t)(total * wq) * 2); + const double scale = 1.0 / std::sqrt((double)hd); + int64_t msl = 0; + for (size_t s = 0; s + 1 < cu.size(); ++s) msl = std::max(msl, cu[s + 1] - cu[s]); + const std::string nm = fmt("%s non-causal over %zu sequence(s) of %lld rows, %lld heads", name, + cu.size() - 1, (long long)msl, (long long)nh); + const int rc = launch(r, { col(0), col(wq), col(2 * wq), T(up_i32(cu), RAD_I32, { (int64_t)cu.size() }), + T(dout, RAD_BF16, { total, wq }) }, + { PI("M", total), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PF("scale", scale), PI("max_seqlen", msl) }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const std::vector all = down_bf16(dout, (size_t)(total * wq)); + std::vector got, want; + std::vector row((size_t)hd); + for (int64_t i = 0; i < total; i += 29) { + int64_t s = 0; + while (s + 2 < (int64_t)cu.size() && cu[(size_t)s + 1] <= i) ++s; + for (int64_t h = 0; h < nh; ++h) { + attn_row_ref(qkv, width, nh, hd, i, h, cu[(size_t)s], cu[(size_t)s + 1], scale, row.data()); + for (int64_t e = 0; e < hd; ++e) { + want.push_back(row[(size_t)e]); + got.push_back(all[(size_t)(i * wq + h * hd + e)]); + } + } + } + check(nm + " numerics", got, want, 2e-2); +} + +} /* namespace vg */ + +/* ---- video sparse attention: vsa_select and attn_vsa against a host port of their contract + * + * The tiling, the f32 tile means (summed in each tile's raster), the f32 scores (each a sequential + * dot product), the top k with ties to the lower tile and the coarse softmax are plain loops here, + * in the order the op defines, so the selection compares exactly. The coarse output and the + * attention are held to a relative L2: the device's exp and its bf16 P are not these loops'. */ +namespace vsa { + +using namespace au; + +constexpr int64_t kHd = 128; + +/* The tiles of a packed sequence, each its rows in raster order: the dense segments in chunks of + * 64 rows, then the video grid in 4 x 4 x 4 boxes. */ +struct Geo { + int P = 0, V = 0, N = 0; + std::vector> rows; +}; + +Geo tiles(const std::vector& segs, int F, int Hp, int Wp) { + Geo g; + const size_t nd = segs.size() - 2; + for (size_t s = 0; s < nd; ++s) + for (int a = segs[s]; a < segs[s + 1]; a += 64) { + std::vector r; + for (int x = a; x < std::min(a + 64, (int)segs[s + 1]); ++x) r.push_back(x); + g.rows.push_back(r); + } + g.P = (int)g.rows.size(); + const int vb = segs[nd]; + for (int a = 0; a < F; a += 4) + for (int b = 0; b < Hp; b += 4) + for (int c = 0; c < Wp; c += 4) { + std::vector r; + for (int t = a; t < std::min(a + 4, F); ++t) + for (int h = b; h < std::min(b + 4, Hp); ++h) + for (int w = c; w < std::min(c + 4, Wp); ++w) + r.push_back(vb + (t * Hp + h) * Wp + w); + g.rows.push_back(r); + } + g.N = (int)g.rows.size(); + g.V = g.N - g.P; + return g; +} + +int topk(double sp, int V) { + return std::max(1, std::min((int)std::ceil((1.0 - sp) * (double)V), V)); +} + +/* One operand of a fused row buffer: column `col` of rows `ld` apart. */ +struct Opd { + const std::vector* x; + int64_t col, ld; + float at(int64_t r, int64_t h, int64_t d) const { return (*x)[(size_t)(r * ld + col + h * kHd + d)]; } +}; + +/* f32 tile means of every head, [nh][N][128]. */ +std::vector means(const Opd& o, const Geo& g, int64_t nh) { + std::vector m((size_t)(nh * g.N * kHd)); + for (int64_t h = 0; h < nh; ++h) + for (int i = 0; i < g.N; ++i) + for (int64_t d = 0; d < kHd; ++d) { + float s = 0.0f; + for (int r : g.rows[(size_t)i]) s = s + o.at(r, h, d); + m[(size_t)((h * g.N + i) * kHd + d)] = s / (float)g.rows[(size_t)i].size(); + } + return m; +} + +/* vsa_select's outputs: the scores [nh][N][N], the selection [nh][N][k] (video query tiles only) + * and the coarse rows [nh][N][128], rounded to bf16. */ +struct Ref { + int k = 0; + std::vector S; + std::vector sel; + std::vector coarse; +}; + +Ref select_ref(const Opd& q, const Opd& k, const Opd* v, const Geo& g, int64_t nh, double sp, + double scale) { + Ref f; + f.k = g.V > 0 ? topk(sp, g.V) : 0; + const std::vector qm = means(q, g, nh), km = means(k, g, nh); + const float sc = (float)scale; + const size_t N = (size_t)g.N; + f.S.assign((size_t)nh * N * N, 0.0f); + for (int64_t h = 0; h < nh; ++h) + for (size_t i = 0; i < N; ++i) + for (size_t j = 0; j < N; ++j) { + float s = 0.0f; + for (int64_t d = 0; d < kHd; ++d) + s = s + qm[(size_t)((h * N + i) * kHd + d)] * km[(size_t)((h * N + j) * kHd + d)]; + f.S[(h * N + i) * N + j] = s * sc; + } + f.sel.assign((size_t)nh * N * (size_t)std::max(f.k, 1), -1); + for (int64_t h = 0; h < nh; ++h) + for (int i = g.P; i < g.N; ++i) { + const float* s = &f.S[((size_t)h * N + (size_t)i) * N]; + std::vector idx; + for (int j = g.P; j < g.N; ++j) idx.push_back(j); + std::stable_sort(idx.begin(), idx.end(), [&](int a, int b) { return s[a] > s[b]; }); + idx.resize((size_t)f.k); + std::sort(idx.begin(), idx.end()); + std::copy(idx.begin(), idx.end(), f.sel.begin() + (long)(((size_t)h * N + (size_t)i) * f.k)); + } + if (!v) return f; + const std::vector vm = means(*v, g, nh); + f.coarse.assign((size_t)nh * N * kHd, 0.0f); + for (int64_t h = 0; h < nh; ++h) + for (size_t i = 0; i < N; ++i) { + const float* s = &f.S[((size_t)h * N + i) * N]; + float mx = -INFINITY, sum = 0.0f; + for (size_t j = 0; j < N; ++j) mx = std::max(mx, s[j]); + std::vector p(N); + for (size_t j = 0; j < N; ++j) { p[j] = std::exp(s[j] - mx); sum = sum + p[j]; } + for (size_t j = 0; j < N; ++j) p[j] = p[j] / sum; + for (int64_t d = 0; d < kHd; ++d) { + float a = 0.0f; + for (size_t j = 0; j < N; ++j) a = a + p[j] * vm[(size_t)((h * (int64_t)N + (int64_t)j) * kHd + d)]; + f.coarse[(size_t)((h * (int64_t)N + (int64_t)i) * kHd + d)] = bfr(a); + } + } + return f; +} + +/* quant_act_i8g's rule for one (row, head): the scale (amax / 127, 1 for an all-zero row) and the + * codes rint(clamp(x * (1 / scale), +-127)), in f32 as the device computes them. */ +float q8_row(const float* x, int64_t n, float* code) { + float am = 0.0f; + for (int64_t d = 0; d < n; ++d) am = std::max(am, std::fabs(x[d])); + const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t d = 0; d < n; ++d) code[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f)); + return sc; +} + +/* k in the int8 Q.K form: codes [R, n_head 128] at pitch `ld` and scales [R, n_head], on the host + * (codes as floats) and the device. */ +struct KQ8 { + int64_t ld = 0, nh = 0; + std::vector codes, scales; + void* dcode = nullptr; + void* dscale = nullptr; +}; + +KQ8 make_kq8(const Opd& k, int64_t R, int64_t nh) { + KQ8 z; + z.nh = nh; + z.ld = nh * kHd + 16; + z.codes.assign((size_t)(R * z.ld), 0.0f); + z.scales.assign((size_t)(R * nh), 0.0f); + std::vector c8((size_t)(R * z.ld), 0); + float x[kHd]; + for (int64_t r = 0; r < R; ++r) + for (int64_t h = 0; h < nh; ++h) { + for (int64_t d = 0; d < kHd; ++d) x[d] = k.at(r, h, d); + float* code = &z.codes[(size_t)(r * z.ld + h * kHd)]; + z.scales[(size_t)(r * nh + h)] = q8_row(x, kHd, code); + for (int64_t d = 0; d < kHd; ++d) c8[(size_t)(r * z.ld + h * kHd + d)] = (int8_t)code[d]; + } + z.dcode = dalloc(c8.size()); + if (z.dcode) st_memcpy(z.dcode, c8.data(), c8.size(), hipMemcpyHostToDevice); + z.dscale = up_f32(z.scales); + return z; +} + +/* quant_cols_fp8's rule for an [R, n] operand: a scale per column (amax / 448 in f32, 1 for an + * all-zero column) and the codes e4m3(clamp(x * (1 / scale), +-448)); the codes as bytes and as + * the values they decode to. */ +struct ColQ8 { + int64_t ld = 0, n = 0; + std::vector bytes; + std::vector codes, scales; + void* dcode = nullptr; + void* dscale = nullptr; +}; + +ColQ8 quant_cols(const Opd& x, int64_t R, int64_t n, int64_t ld) { + ColQ8 z; + z.ld = ld; + z.n = n; + z.bytes.assign((size_t)(R * ld), 0); + z.codes.assign((size_t)(R * ld), 0.0f); + z.scales.assign((size_t)n, 1.0f); + for (int64_t c = 0; c < n; ++c) { + float am = 0.0f; + for (int64_t r = 0; r < R; ++r) am = std::max(am, std::fabs(x.at(r, 0, c))); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc; + z.scales[(size_t)c] = sc; + for (int64_t r = 0; r < R; ++r) { + const float v = std::min(std::max(x.at(r, 0, c) * inv, -448.0f), 448.0f); + const uint8_t b = rad_f32_to_fp8e4m3(v); + z.bytes[(size_t)(r * ld + c)] = b; + z.codes[(size_t)(r * ld + c)] = rad_fp8e4m3_to_f32(b); + } + } + return z; +} + +/* The same codes and scales on the device, for an attention's v. */ +ColQ8 make_vq8(const Opd& v, int64_t R, int64_t W) { + ColQ8 z = quant_cols(v, R, W, W + 16); + z.dcode = dalloc(z.bytes.size()); + if (z.dcode) st_memcpy(z.dcode, z.bytes.data(), z.bytes.size(), hipMemcpyHostToDevice); + z.dscale = up_f32(z.scales); + return z; +} + +/* The fp8 P.V form against its port. Each w = e4m3(448 p) keeps 3 mantissa bits (~2.5% RMS a + * value), and the kernel rounds p against its running max where the port rounds it against the + * row's: two independent roundings. Over the random rows here the output is an average that + * nearly cancels, so that noise does not shrink with the key count and shows as 1.3-2.8% + * rel_l2; a wrong code or scale shows at tens of percent. */ +constexpr double kPv8Tol = 4e-2; + +/* One query row of one head over the given key rows, in double; with `kq` the scores are the + * int8 form's, (q codes . k codes) q_scale k_scale scale in f32 as libref forms them. With `vq` + * the fp8 P.V form: p = exp(s - max) in f32, w = e4m3(448 p), o = (sum w v_code) v_scale / + * (448 sum p). */ +void attn_ref(const Opd& q, const Opd& k, const Opd& v, const std::vector& keys, int64_t r, + int64_t h, double scale, float* out, const KQ8* kq = nullptr, + const ColQ8* vq = nullptr) { + std::vector sc(keys.size()); + double mx = -1e300; + float xq[kHd], cq[kHd], sq = 1.0f; + if (kq) { + for (int64_t e = 0; e < kHd; ++e) xq[e] = q.at(r, h, e); + sq = q8_row(xq, kHd, cq); + } + for (size_t j = 0; j < keys.size(); ++j) { + if (kq) { + const float* ck = &kq->codes[(size_t)(keys[j] * kq->ld + h * kHd)]; + float acc = 0.0f; + for (int64_t e = 0; e < kHd; ++e) acc += cq[e] * ck[e]; + sc[j] = (double)(acc * sq * kq->scales[(size_t)(keys[j] * kq->nh + h)] * (float)scale); + } else { + double d = 0; + for (int64_t e = 0; e < kHd; ++e) d += (double)q.at(r, h, e) * k.at(keys[j], h, e); + sc[j] = d * scale; + } + mx = std::max(mx, sc[j]); + } + if (vq) { + std::vector w(keys.size()); + double psum = 0; + for (size_t j = 0; j < keys.size(); ++j) { + const float pj = (float)std::exp(sc[j] - mx); + psum += pj; + w[j] = rad_fp8e4m3_to_f32(rad_f32_to_fp8e4m3(448.0f * pj)); + } + for (int64_t e = 0; e < kHd; ++e) { + double a = 0; + for (size_t j = 0; j < keys.size(); ++j) + a += w[j] * vq->codes[(size_t)(keys[j] * vq->ld + h * kHd + e)]; + out[e] = (float)(a * vq->scales[(size_t)(h * kHd + e)] / (448.0 * psum)); + } + return; + } + double sum = 0; + for (double& x : sc) { x = std::exp(x - mx); sum += x; } + for (int64_t e = 0; e < kHd; ++e) { + double a = 0; + for (size_t j = 0; j < keys.size(); ++j) a += sc[j] * v.at(keys[j], h, e); + out[e] = (float)(a / sum); + } +} + +/* A geometry: the dense segments' row counts and the video grid (latent sizes, patch 2). */ +struct Shape { + const char* what; + std::vector dense; + int F, Hp, Wp; +}; + +std::vector segs_of(const Shape& s) { + std::vector v = { 0 }; + for (int32_t d : s.dense) v.push_back(v.back() + d); + v.push_back(v.back() + s.F * s.Hp * s.Wp); + return v; +} + +std::vector params(int64_t R, double sp) { + return { PI("M", R), PI("head_dim", kHd), PI("tile_t", 4), PI("tile_h", 4), PI("tile_w", 4), + PI("patch", 2), PF("sparsity", sp), PF("scale", 1.0 / std::sqrt((double)kHd)) }; +} + +/* A launch with `scratch` bytes of scratch (the hook's answer when negative). */ +int run(const RadKernelInfo* r, std::vector ts, std::vector ps, + int64_t scratch = -1) { + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (scratch < 0 && r->scratch) scratch = r->scratch(&a); + if (scratch > 0) { a.scratch = dalloc((size_t)scratch); a.scratch_bytes = scratch; } + const int rc = r->launch(&a, (RadStream)nullptr); + if (rc != RAD_OK) return rc; + return st_stream_sync(nullptr) == hipSuccess ? RAD_OK : RAD_E_STATE; +} + +/* The operands of one pass: q, k and v as column slices of one fused row (pitch wider than the + * three), the geometry, and the case's host copies. */ +struct Pass { + Shape s; + int64_t nh = 0, W = 0, ld = 0, R = 0; + std::vector segs; + Geo g; + std::vector qkv; + void* d = nullptr; + RadTensor col(int64_t which) const { + RadTensor t = T((uint16_t*)d + which * W, RAD_BF16, { R, W }); + t.stride[0] = ld; + return t; + } + Opd opd(int64_t which) const { return Opd{ &qkv, which * W, ld }; } + RadTensor tsegs() const { return TI32({ (int64_t)segs.size() }, segs); } + RadTensor tgeom() const { + return TI32({ 16 }, { s.F, 2 * s.Hp, 2 * s.Wp, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + } +}; + +/* `kconst` sets every k value to 0.5, so every key tile's mean is the same and every score ties. */ +Pass make_pass(const Shape& s, int64_t nh, float amp, bool kconst = false) { + Pass p; + p.s = s; + p.nh = nh; + p.W = nh * kHd; + p.ld = 3 * p.W + 64; + p.segs = segs_of(s); + p.R = p.segs.back(); + p.g = tiles(p.segs, s.F, s.Hp, s.Wp); + p.qkv = randv((size_t)(p.R * p.ld), amp); + if (kconst) + for (int64_t r = 0; r < p.R; ++r) + for (int64_t c = 0; c < p.W; ++c) p.qkv[(size_t)(r * p.ld + p.W + c)] = 0.5f; + p.d = up_bf16(p.qkv); + return p; +} + +constexpr int32_t kUnwritten = -7; + +/* vsa_select against the port: the selection exactly (and nothing written outside the selected + * slots of video query tiles), the coarse rows to a relative L2. `heads_a_group` sizes the + * scratch for that many heads, so the entry runs several groups. */ +void select_case(const Plugin& pl, const Pass& p, double sp, bool coarse, int64_t tiles_cap, + int64_t k_cap, int64_t heads_a_group = 0, const char* note = "") { + const char* name = "vsa_select_h128_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const Geo& g = p.g; + const std::string nm = fmt("%s %s, %lld heads, sparsity %.1f, coarse %s%s", name, p.s.what, + (long long)p.nh, sp, coarse ? "yes" : "no", note); + const std::vector init((size_t)(p.nh * tiles_cap * k_cap), kUnwritten); + void* dsel = up_i32(init); + void* dco = dalloc((size_t)(p.nh * tiles_cap * kHd) * 2); + RadTensor tv = p.col(2), tco = T(dco, RAD_BF16, { p.nh, tiles_cap, kHd }); + if (!coarse) { absent(tv); absent(tco); } + const int64_t scratch = + heads_a_group > 0 ? heads_a_group * tiles_cap * (coarse ? 1536 : 1024) : -1; + const int rc = run(r, { p.col(0), p.col(1), tv, p.tsegs(), p.tgeom(), + T(dsel, RAD_I32, { p.nh, tiles_cap, k_cap }), tco }, + params(p.R, sp), scratch); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const Opd qo = p.opd(0), ko = p.opd(1), vo = p.opd(2); + const Ref f = select_ref(qo, ko, coarse ? &vo : nullptr, g, p.nh, sp, 1.0 / std::sqrt((double)kHd)); + const std::vector got = down_i32(dsel, init.size()); + int64_t bad = 0, stray = 0, tiles_off = 0, near = 0; + for (int64_t h = 0; h < p.nh; ++h) + for (int64_t i = 0; i < tiles_cap; ++i) { + const int32_t* gs = &got[(size_t)((h * tiles_cap + i) * k_cap)]; + const bool video = i >= g.P && i < g.N; + for (int64_t s = 0; s < k_cap; ++s) { + if (!video || s >= f.k) { stray += gs[s] != kUnwritten; continue; } + } + if (!video) continue; + const int* want = &f.sel[(size_t)((h * g.N + i) * f.k)]; + bool same = true; + for (int s = 0; s < f.k; ++s) same = same && gs[s] == want[s]; + if (same) continue; + ++tiles_off; + /* A selection may only differ where the k-th and (k+1)-th scores are within a few + * ulps: there the bisection and a sort can disagree only if a score does. */ + std::vector sc(&f.S[(size_t)((h * g.N + i) * g.N + g.P)], + &f.S[(size_t)((h * g.N + i) * g.N + g.N)]); + std::sort(sc.begin(), sc.end(), [](float x, float y) { return x > y; }); + const float a = sc[(size_t)f.k - 1], b = (size_t)f.k < sc.size() ? sc[(size_t)f.k] : -INFINITY; + if (std::fabs(a - b) <= 4e-7f * std::max(std::fabs(a), std::fabs(b))) ++near; + else ++bad; + } + ok(fmt("%s: selection (k %d of %d video tiles, %lld query tiles) exact", nm.c_str(), f.k, g.V, + (long long)(p.nh * g.V)).c_str(), + bad == 0 && tiles_off == near, + fmt("%lld query tiles differ, %lld of them at a near-tie", (long long)tiles_off, (long long)near)); + if (tiles_off) std::printf(" %lld query tile(s) differ, all at near-tied k-th scores\n", + (long long)tiles_off); + ok(fmt("%s: nothing written outside the selected slots", nm.c_str()).c_str(), stray == 0, + fmt("%lld slots written", (long long)stray)); + if (!coarse) return; + const std::vector co = down_bf16(dco, (size_t)(p.nh * tiles_cap * kHd)); + std::vector cg, cw; + int64_t past = 0; + for (int64_t h = 0; h < p.nh; ++h) + for (int64_t i = 0; i < tiles_cap; ++i) + for (int64_t d = 0; d < kHd; ++d) { + const float x = co[(size_t)((h * tiles_cap + i) * kHd + d)]; + if (i >= g.N) { past += x != 0.0f; continue; } + cg.push_back(x); + cw.push_back(f.coarse[(size_t)((h * g.N + i) * kHd + d)]); + } + check(nm + ": coarse", cg, cw, 2e-3); + ok(fmt("%s: no coarse row past the tiles", nm.c_str()).c_str(), past == 0); +} + +/* Every score ties: the selection is the k lowest video tiles. */ +void select_tie_case(const Plugin& pl, const Shape& s) { + const Pass p = make_pass(s, 2, 1.0f, true); + select_case(pl, p, 0.5, false, p.g.N, topk(0.5, p.g.V), 0, ", every score tied"); + const Ref f = select_ref(p.opd(0), p.opd(1), nullptr, p.g, p.nh, 0.5, 1.0 / std::sqrt(128.0)); + bool lowest = true; + for (int64_t h = 0; h < p.nh; ++h) + for (int i = p.g.P; i < p.g.N; ++i) + for (int x = 0; x < f.k; ++x) lowest = lowest && f.sel[(size_t)((h * p.g.N + i) * f.k + x)] == p.g.P + x; + ok("vsa_select_h128_bf16 tie port: the lowest tiles", lowest); +} + +/* The refusals: v without coarse, a tile capacity past the LDS budget, too little scratch. */ +void select_refusals(const Plugin& pl, const Pass& p) { + const RadKernelInfo* r = find(pl, "vsa_select_h128_bf16"); + if (!r) return; + void* dsel = dalloc((size_t)(p.nh * 4000 * 8) * 4); + void* dco = dalloc((size_t)(p.nh * 4000 * kHd) * 2); + RadTensor tco = T(dco, RAD_BF16, { p.nh, 64, kHd }), none = tco; + absent(none); + int rc = run(r, { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), + T(dsel, RAD_I32, { p.nh, 64, 8 }), none }, params(p.R, 0.8)); + ok("vsa_select_h128_bf16 refuses v without coarse", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); + rc = run(r, { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), + T(dsel, RAD_I32, { p.nh, 4000, 8 }), T(dco, RAD_BF16, { p.nh, 4000, kHd }) }, + params(p.R, 0.8)); + ok("vsa_select_h128_bf16 refuses 4000 tiles", rc == RAD_E_SHAPE, "rc " + std::to_string(rc)); + rc = run(r, { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), + T(dsel, RAD_I32, { p.nh, 64, 8 }), tco }, params(p.R, 0.8), 64 * 1024 - 16); + ok("vsa_select_h128_bf16 refuses scratch short of one head", rc == RAD_E_SCRATCH, + "rc " + std::to_string(rc)); +} + +/* attn_vsa against the port, with the port's selection as its input: rows `stride` apart (and + * every tile's first row) checked against the attention over their visible keys, then with the + * coarse term bf16(bf16(o) + coarse gate). At sparsity 0 every key is visible: dense attention. */ +void attn_case(const Plugin& pl, const Pass& p, double sp, bool coarse, int64_t stride, + bool i8 = false, bool pv8 = false) { + const char* name = "attn_vsa_h128_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const Geo& g = p.g; + const std::string nm = fmt("%s %s, %lld heads, sparsity %.1f, coarse %s%s%s", name, p.s.what, + (long long)p.nh, sp, coarse ? "yes" : "no", i8 ? ", qk i8" : "", + pv8 ? ", pv fp8" : ""); + const Ref f = select_ref(p.opd(0), p.opd(1), nullptr, g, p.nh, sp, 1.0 / std::sqrt((double)kHd)); + const int64_t tiles_cap = g.N + 3, k_cap = f.k + 2; + std::vector sel((size_t)(p.nh * tiles_cap * k_cap), kUnwritten); + for (int64_t h = 0; h < p.nh; ++h) + for (int i = g.P; i < g.N; ++i) + for (int x = 0; x < f.k; ++x) + sel[(size_t)((h * tiles_cap + i) * k_cap + x)] = f.sel[(size_t)((h * g.N + i) * f.k + x)]; + std::vector co = randv((size_t)(p.nh * tiles_cap * kHd), 0.5f); + const int64_t gld = p.W + 24; + std::vector gate = randv((size_t)(p.R * gld), 0.7f); + void* dco = up_bf16(co); + void* dg = up_bf16(gate); + const int64_t old = p.W + 40; + void* dout = dalloc((size_t)(p.R * old) * 2); + RadTensor tco = T(dco, RAD_BF16, { p.nh, tiles_cap, kHd }), tg = T(dg, RAD_BF16, { p.R, p.W }); + tg.stride[0] = gld; + RadTensor to = T(dout, RAD_BF16, { p.R, p.W }); + to.stride[0] = old; + if (!coarse) { absent(tco); absent(tg); } + const RadTensor tsel = T(up_i32(sel), RAD_I32, { p.nh, tiles_cap, k_cap }); + std::vector ts = { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), tsel, tco, + tg, to }; + std::vector ps = params(p.R, sp); + KQ8 kq; + if (i8) { + kq = make_kq8(p.opd(1), p.R, p.nh); + RadTensor tk8 = T(kq.dcode, RAD_I8, { p.R, p.W }); + tk8.stride[0] = kq.ld; + ts.push_back(tk8); + ts.push_back(T(kq.dscale, RAD_F32, { p.R, p.nh })); + ps.push_back(PS("qk", "i8")); + } + const std::vector ts_bf16 = ts; + ColQ8 vq; + if (pv8) { + vq = make_vq8(p.opd(2), p.R, p.W); + RadTensor tv8 = T(vq.dcode, RAD_F8E4M3, { p.R, p.W }); + tv8.stride[0] = vq.ld; + ts[2] = tv8; + if (!i8) { + RadTensor none = T(nullptr, RAD_I8, { 1 }); + absent(none); + ts.push_back(none); + ts.push_back(none); + } + ts.push_back(T(vq.dscale, RAD_F32, { p.W })); + ps.push_back(PS("pv", "fp8")); + } + const int rc = run(r, ts, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const std::vector out = down_bf16(dout, (size_t)(p.R * old)); + std::vector tile_of((size_t)p.R), first((size_t)p.R, 0); + for (int i = 0; i < g.N; ++i) { + for (int x : g.rows[(size_t)i]) tile_of[(size_t)x] = i; + first[(size_t)g.rows[(size_t)i][0]] = 1; + } + const Opd qo = p.opd(0), ko = p.opd(1), vo = p.opd(2); + std::vector got, want, row((size_t)kHd); + std::vector all; + for (int x = 0; x < p.R; ++x) all.push_back(x); + int64_t gap = 0; + for (int64_t x = 0; x < p.R; ++x) { + for (int64_t c = p.W; c < old; ++c) gap += out[(size_t)(x * old + c)] != 0.0f; + if (x % stride && !first[(size_t)x]) continue; + const int i = tile_of[(size_t)x]; + for (int64_t h = 0; h < p.nh; ++h) { + std::vector keys; + if (i < g.P) keys = all; + else { + for (int j = 0; j < g.P; ++j) keys.insert(keys.end(), g.rows[(size_t)j].begin(), g.rows[(size_t)j].end()); + for (int s = 0; s < f.k; ++s) { + const auto& rr = g.rows[(size_t)f.sel[(size_t)((h * g.N + i) * f.k + s)]]; + keys.insert(keys.end(), rr.begin(), rr.end()); + } + } + attn_ref(qo, ko, vo, keys, x, h, 1.0 / std::sqrt((double)kHd), row.data(), + i8 ? &kq : nullptr, pv8 ? &vq : nullptr); + for (int64_t e = 0; e < kHd; ++e) { + float w = row[(size_t)e]; + if (coarse) + w = bfr(bfr(w) + co[(size_t)((h * tiles_cap + i) * kHd + e)] * + gate[(size_t)(x * gld + h * kHd + e)]); + want.push_back(w); + got.push_back(out[(size_t)(x * old + h * kHd + e)]); + } + } + } + check(nm + fmt(": %zu values", got.size()), got, want, pv8 ? kPv8Tol : 2e-2); + ok(fmt("%s: the out pitch's gap untouched", nm.c_str()).c_str(), gap == 0); + if (!i8 && !pv8) return; + /* The same pass with bf16 P.V, and with bf16 scores too: how far each 8-bit form moves the + * output. */ + void* dout2 = dalloc((size_t)(p.R * old) * 2); + RadTensor to2 = to; + to2.data = dout2; + if (pv8) { + std::vector t2 = ts_bf16; + t2[8] = to2; + std::vector p2 = params(p.R, sp); + if (i8) p2.push_back(PS("qk", "i8")); + const int rc3 = run(r, t2, p2); + if (rc3 != RAD_OK) { ok((nm + ": the bf16 P.V form").c_str(), false, "rc " + std::to_string(rc3)); return; } + check(nm + ": against the bf16 P.V form", out, down_bf16(dout2, (size_t)(p.R * old)), 5e-2); + } + const int rc2 = run(r, { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), tsel, tco, tg, to2 }, + params(p.R, sp)); + if (rc2 != RAD_OK) { ok((nm + ": the bf16 form").c_str(), false, "rc " + std::to_string(rc2)); return; } + check(nm + ": against the bf16 form", out, down_bf16(dout2, (size_t)(p.R * old)), 5e-2); +} + +/* The fp8 P.V form's refusals: `pv` "fp8" without v_scale, v_scale without it, an unknown `pv`. */ +void attn_pv8_refusals(const Plugin& pl, const Pass& p) { + const RadKernelInfo* r = find(pl, "attn_vsa_h128_bf16"); + if (!r) return; + const Ref f = select_ref(p.opd(0), p.opd(1), nullptr, p.g, p.nh, 0.8, 1.0 / std::sqrt(128.0)); + std::vector sel((size_t)(p.nh * p.g.N * f.k), p.g.P); + const RadTensor tsel = T(up_i32(sel), RAD_I32, { p.nh, p.g.N, f.k }); + RadTensor none = T(nullptr, RAD_BF16, { 1 }); + absent(none); + const RadTensor to = T(dalloc((size_t)(p.R * p.W) * 2), RAD_BF16, { p.R, p.W }); + const ColQ8 vq = make_vq8(p.opd(2), p.R, p.W); + RadTensor tv8 = T(vq.dcode, RAD_F8E4M3, { p.R, p.W }); + tv8.stride[0] = vq.ld; + const RadTensor tvs = T(vq.dscale, RAD_F32, { p.W }); + std::vector p8 = params(p.R, 0.8), pbad = params(p.R, 0.8); + p8.push_back(PS("pv", "fp8")); + pbad.push_back(PS("pv", "fp16")); + const std::vector without = { p.col(0), p.col(1), tv8, p.tsegs(), p.tgeom(), tsel, + none, none, to }; + std::vector with = without; + with.push_back(none); + with.push_back(none); + with.push_back(tvs); + int rc = run(r, without, p8); + ok("attn_vsa_h128_bf16 refuses pv fp8 without v_scale", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); + rc = run(r, with, params(p.R, 0.8)); + ok("attn_vsa_h128_bf16 refuses v_scale without pv fp8", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); + rc = run(r, with, pbad); + ok("attn_vsa_h128_bf16 refuses pv fp16", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); +} + +/* quant_cols_fp8 against the port, scales and codes exactly: a column view of a wider row and a + * pitched output with a zero column and one large value; and the v columns of a 1344 x 768 + * pass's fused projection (38010 x 3584). */ +void quant_cols_case(const Plugin& pl, int64_t R, int64_t n, int64_t xld, int64_t yld, bool edge, + const char* what) { + const char* name = "quant_cols_fp8_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + std::vector x = randv((size_t)(R * xld), 2.0f); + if (edge) { + for (int64_t row = 0; row < R; ++row) x[(size_t)(row * xld + 5)] = 0.0f; + x[(size_t)(7 * xld + 9)] = 3.0e4f; + x[(size_t)(3 * xld + 11)] = -1.0e-30f; + } + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(R * yld)); + void* ds = dalloc((size_t)n * 4); + RadTensor tx = T(dx, RAD_BF16, { R, n }), ty = T(dy, RAD_F8E4M3, { R, n }); + tx.stride[0] = xld; + ty.stride[0] = yld; + const std::string nm = fmt("%s %s (%lld x %lld)", name, what, (long long)R, (long long)n); + const int rc = run(r, { tx, ty, T(ds, RAD_F32, { n }) }, + { PI("M", R), PI("n", n), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const ColQ8 z = quant_cols(Opd{ &x, 0, xld }, R, n, yld); + std::vector got((size_t)(R * yld)); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + int64_t bad = 0, gap = 0; + for (int64_t row = 0; row < R; ++row) + for (int64_t c = 0; c < yld; ++c) { + const size_t at = (size_t)(row * yld + c); + if (c >= n) gap += got[at] != 0; + else bad += got[at] != z.bytes[at]; + } + const int64_t sbad = differ(down_f32(ds, (size_t)n), z.scales); + ok((nm + ": scales exact").c_str(), sbad == 0, fmt("%lld differ", (long long)sbad)); + ok((nm + ": codes exact, the pitch's gap untouched").c_str(), bad == 0 && gap == 0, + fmt("%lld codes differ, %lld gap bytes written", (long long)bad, (long long)gap)); +} + +void quant_cols_cases(const Plugin& pl) { + quant_cols_case(pl, 37, 72, 88, 80, true, "edge columns"); + quant_cols_case(pl, 5, 8, 8, 8, false, "five rows"); + quant_cols_case(pl, 38010, 3584, 3584 + 64, 3584, false, "1344 x 768 v"); +} + +/* attn_prefix_self without a prefix (self attention over cu_seqlens sequences) against the port, + * at bf16 and int8 scores and bf16 and fp8 P.V: two sequences of 1000 and 1333 rows, causal and + * not, every third row; and one 38010-row sequence (the 1344 x 768 pass) every 397th row. q, k + * and v are columns of one fused row. */ +void dense_case(const Plugin& pl, std::vector cu, int64_t nh, int causal, int64_t stride, + bool i8, bool pv8) { + const char* name = "attn_prefix_self_h128_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t R = cu.back(), W = nh * kHd, ld = 3 * W + 64; + std::vector qkv = randv((size_t)(R * ld), 1.5f); + void* d = up_bf16(qkv); + auto col = [&](int64_t which) { + RadTensor t = T((uint16_t*)d + which * W, RAD_BF16, { R, W }); + t.stride[0] = ld; + return t; + }; + const Opd qo{ &qkv, 0, ld }, ko{ &qkv, W, ld }, vo{ &qkv, 2 * W, ld }; + void* dout = dalloc((size_t)(R * W) * 2); + RadTensor none = T(nullptr, RAD_BF16, { 1 }); + absent(none); + std::vector ts = { col(0), col(1), col(2), none, none, none, + T(up_i32(cu), RAD_I32, { (int64_t)cu.size() }), none, none, none, + none, T(dout, RAD_BF16, { R, W }) }; + std::vector ps = { PI("q_len", R), PI("head_dim", kHd), PI("gqa", 1), + PI("block_size", 16), PI("causal", causal), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PF("scale", 1.0 / std::sqrt(128.0)), + PI("max_ctx", 0), PI("n_head", nh), PI("max_seqs", 4) }; + KQ8 kq; + if (i8) { + kq = make_kq8(ko, R, nh); + RadTensor tk8 = T(kq.dcode, RAD_I8, { R, W }); + tk8.stride[0] = kq.ld; + ts[9] = tk8; + ts[10] = T(kq.dscale, RAD_F32, { R, nh }); + ps.push_back(PS("qk", "i8")); + } + const std::vector ts_bf16 = ts; + const std::vector ps_bf16 = ps; + ColQ8 vq; + if (pv8) { + vq = make_vq8(vo, R, W); + RadTensor tv8 = T(vq.dcode, RAD_F8E4M3, { R, W }); + tv8.stride[0] = vq.ld; + ts[2] = tv8; + ts.push_back(T(vq.dscale, RAD_F32, { W })); + ps.push_back(PS("pv", "fp8")); + } + int64_t msl = 0; + for (size_t sq = 0; sq + 1 < cu.size(); ++sq) msl = std::max(msl, cu[sq + 1] - cu[sq]); + const std::string nm = fmt("%s %zu sequence(s) of up to %lld rows, %lld heads, causal %d, qk %s, " + "pv %s", name, cu.size() - 1, (long long)msl, (long long)nh, causal, + i8 ? "i8" : "bf16", pv8 ? "fp8" : "bf16"); + const int rc = run(r, ts, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; } + const std::vector out = down_bf16(dout, (size_t)(R * W)); + std::vector got, want, row((size_t)kHd); + for (int64_t x = 0; x < R; x += stride) { + int64_t sq = 0; + while (sq + 2 < (int64_t)cu.size() && cu[(size_t)sq + 1] <= x) ++sq; + std::vector keys; + const int64_t kend = causal ? x + 1 : cu[(size_t)sq + 1]; + for (int64_t j = cu[(size_t)sq]; j < kend; ++j) keys.push_back((int)j); + for (int64_t h = 0; h < nh; ++h) { + attn_ref(qo, ko, vo, keys, x, h, 1.0 / std::sqrt(128.0), row.data(), i8 ? &kq : nullptr, + pv8 ? &vq : nullptr); + for (int64_t e = 0; e < kHd; ++e) { + want.push_back(row[(size_t)e]); + got.push_back(out[(size_t)(x * W + h * kHd + e)]); + } + } + } + check(nm + fmt(": %zu values", got.size()), got, want, pv8 ? kPv8Tol : 2e-2); + if (!pv8) return; + void* dout2 = dalloc((size_t)(R * W) * 2); + std::vector t2 = ts_bf16; + t2[11] = T(dout2, RAD_BF16, { R, W }); + const int rc2 = run(r, t2, ps_bf16); + if (rc2 != RAD_OK) { ok((nm + ": the bf16 P.V form").c_str(), false, "rc " + std::to_string(rc2)); return; } + check(nm + ": against the bf16 P.V form", out, down_bf16(dout2, (size_t)(R * W)), 5e-2); +} + +/* The dense fp8 P.V form's refusals: with a paged prefix, and `pv` "fp8" without v_scale. */ +void dense_pv8_refusals(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "attn_prefix_self_h128_bf16"); + if (!r) return; + const int64_t R = 64, W = kHd; + std::vector qkv = randv((size_t)(R * 3 * W), 1.0f); + void* d = up_bf16(qkv); + const Opd vo{ &qkv, 2 * W, 3 * W }; + const ColQ8 vq = make_vq8(vo, R, W); + RadTensor tq = T(d, RAD_BF16, { R, W }), tk = T((uint16_t*)d + W, RAD_BF16, { R, W }); + tq.stride[0] = tk.stride[0] = 3 * W; + RadTensor tv8 = T(vq.dcode, RAD_F8E4M3, { R, W }); + tv8.stride[0] = vq.ld; + RadTensor none = T(nullptr, RAD_BF16, { 1 }); + absent(none); + const RadTensor cu = TI32({ 2 }, { 0, (int32_t)R }); + const RadTensor to = T(dalloc((size_t)(R * W) * 2), RAD_BF16, { R, W }); + const RadTensor cache = T(dalloc((size_t)(4 * 16 * 2 * W) * 2), RAD_BF16, { 4, 1, 16, 2 * W }); + std::vector ps = { PI("q_len", R), PI("head_dim", kHd), PI("gqa", 1), + PI("block_size", 16), PI("causal", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PF("scale", 1.0 / std::sqrt(128.0)), + PI("max_ctx", 64), PI("n_head", 1), PI("max_seqs", 1), + PS("pv", "fp8") }; + int rc = run(r, { tq, tk, tv8, cache, TI32({ 1, 4 }, { 0, 1, 2, 3 }), TI32({ 1 }, { 16 }), cu, + none, none, none, none, to, T(vq.dscale, RAD_F32, { W }) }, ps); + ok("attn_prefix_self_h128_bf16 refuses pv fp8 with a prefix", rc == RAD_E_UNSUPPORTED, + "rc " + std::to_string(rc)); + rc = run(r, { tq, tk, tv8, none, none, none, cu, none, none, none, none, to }, ps); + ok("attn_prefix_self_h128_bf16 refuses pv fp8 without v_scale", rc == RAD_E_INVAL, + "rc " + std::to_string(rc)); +} + +void dense_cases(const Plugin& pl) { + for (const bool i8 : { false, true }) + for (const bool pv8 : { false, true }) { + dense_case(pl, { 0, 1000, 2333 }, 2, 0, 3, i8, pv8); + dense_case(pl, { 0, 1000, 2333 }, 2, 1, 3, i8, pv8); + } + dense_pv8_refusals(pl); + dense_case(pl, { 0, 38010 }, 2, 0, 397, true, true); + dense_case(pl, { 0, 38010 }, 2, 0, 397, false, true); +} + +/* The int8 form's refusals: `qk` "i8" without the codes, the codes without it, an unknown `qk`. */ +void attn_i8_refusals(const Plugin& pl, const Pass& p) { + const RadKernelInfo* r = find(pl, "attn_vsa_h128_bf16"); + if (!r) return; + const Ref f = select_ref(p.opd(0), p.opd(1), nullptr, p.g, p.nh, 0.8, 1.0 / std::sqrt(128.0)); + std::vector sel((size_t)(p.nh * p.g.N * f.k), p.g.P); + const RadTensor tsel = T(up_i32(sel), RAD_I32, { p.nh, p.g.N, f.k }); + RadTensor none = T(nullptr, RAD_BF16, { 1 }); + absent(none); + const RadTensor to = T(dalloc((size_t)(p.R * p.W) * 2), RAD_BF16, { p.R, p.W }); + const KQ8 kq = make_kq8(p.opd(1), p.R, p.nh); + RadTensor tk8 = T(kq.dcode, RAD_I8, { p.R, p.W }); + tk8.stride[0] = kq.ld; + const RadTensor tks = T(kq.dscale, RAD_F32, { p.R, p.nh }); + const std::vector base = { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), tsel, + none, none, to }; + std::vector pi8 = params(p.R, 0.8), pbad = params(p.R, 0.8); + pi8.push_back(PS("qk", "i8")); + pbad.push_back(PS("qk", "fp8")); + std::vector with = base; + with.push_back(tk8); + with.push_back(tks); + int rc = run(r, base, pi8); + ok("attn_vsa_h128_bf16 refuses qk i8 without k_i8 / k_scale", rc == RAD_E_INVAL, + "rc " + std::to_string(rc)); + rc = run(r, with, params(p.R, 0.8)); + ok("attn_vsa_h128_bf16 refuses k_i8 / k_scale without qk i8", rc == RAD_E_INVAL, + "rc " + std::to_string(rc)); + rc = run(r, with, pbad); + ok("attn_vsa_h128_bf16 refuses qk fp8", rc == RAD_E_INVAL, "rc " + std::to_string(rc)); +} + +/* attn_vsa at sparsity 0 against attn_dense_h128_bf16 on the same rows: two kernels computing + * one dense attention, held to the spread between them. */ +void attn_vs_dense_case(const Plugin& pl, const Pass& p) { + const RadKernelInfo* r = find(pl, "attn_vsa_h128_bf16"); + const RadKernelInfo* rd = find(pl, "attn_dense_h128_bf16"); + if (!r || !rd) { ok("attn_vsa_h128_bf16 vs attn_dense_h128_bf16", false, "row absent"); return; } + const Geo& g = p.g; + const int k = topk(0.0, g.V); + std::vector sel((size_t)(p.nh * g.N * k)); + for (int64_t h = 0; h < p.nh; ++h) + for (int i = 0; i < g.N; ++i) + for (int x = 0; x < k; ++x) sel[(size_t)((h * g.N + i) * k + x)] = g.P + x; + void* da = dalloc((size_t)(p.R * p.W) * 2); + void* db = dalloc((size_t)(p.R * p.W) * 2); + RadTensor tn = T(nullptr, RAD_BF16, { 1 }); + absent(tn); + int rc = run(r, { p.col(0), p.col(1), p.col(2), p.tsegs(), p.tgeom(), + T(up_i32(sel), RAD_I32, { p.nh, g.N, k }), tn, tn, T(da, RAD_BF16, { p.R, p.W }) }, + params(p.R, 0.0)); + const int rc2 = launch(rd, { p.col(0), p.col(1), p.col(2), TI32({ 2 }, { 0, (int32_t)p.R }), + T(db, RAD_BF16, { p.R, p.W }) }, + { PI("M", p.R), PI("head_dim", kHd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PF("scale", 1.0 / std::sqrt(128.0)), + PI("max_seqlen", p.R) }); + const std::string nm = fmt("attn_vsa_h128_bf16 %s sparsity 0.0 vs attn_dense_h128_bf16", p.s.what); + if (rc != RAD_OK || rc2 != RAD_OK) { ok(nm.c_str(), false, fmt("rc %d / %d", rc, rc2)); return; } + check(nm, down_bf16(da, (size_t)(p.R * p.W)), down_bf16(db, (size_t)(p.R * p.W)), 1e-2); +} + +/* The small geometry with every edge: dense segments of 13 and 14 rows, a 6 x 5 x 7 grid (edge + * boxes along all three axes); the same with an empty segment between; and the 1344 x 768 pass + * (text 300, a soundtrack of 2 x 207, 37 x 24 x 42). */ +const Shape kSmall = { "13 | 14 | 6 x 5 x 7", { 13, 14 }, 6, 5, 7 }; +const Shape kSmallEmpty = { "13 | 0 | 14 | 6 x 5 x 7", { 13, 0, 14 }, 6, 5, 7 }; +const Shape k768 = { "1344 x 768", { 300, 207, 207 }, 37, 24, 42 }; + +void select_cases(const Plugin& pl) { + const Pass s = make_pass(kSmall, 3, 1.5f); + select_case(pl, s, 0.8, true, s.g.N + 5, topk(0.8, s.g.V) + 3); + select_case(pl, s, 0.8, false, s.g.N + 5, topk(0.8, s.g.V) + 3, 1, ", one head a group"); + select_case(pl, s, 0.0, true, s.g.N, s.g.V, 2, ", two heads a group"); + select_case(pl, s, 0.8, true, 2000, 16, 3, ", 2000-tile capacity"); + const Pass e = make_pass(kSmallEmpty, 2, 1.5f); + select_case(pl, e, 0.8, true, e.g.N, topk(0.8, e.g.V)); + select_tie_case(pl, kSmall); + select_refusals(pl, s); + const Pass b = make_pass(k768, 3, 1.5f); + select_case(pl, b, 0.8, true, 1500, 300); +} + +void attn_cases(const Plugin& pl) { + const Pass s = make_pass(kSmall, 3, 1.5f); + attn_case(pl, s, 0.8, true, 1); + attn_case(pl, s, 0.8, false, 1); + attn_case(pl, s, 0.0, false, 1); + attn_case(pl, s, 0.0, true, 1); + const Pass e = make_pass(kSmallEmpty, 2, 1.5f); + attn_case(pl, e, 0.8, true, 1); + attn_vs_dense_case(pl, s); + attn_case(pl, s, 0.8, true, 1, true); + attn_case(pl, s, 0.0, false, 1, true); + attn_case(pl, e, 0.8, false, 1, true); + attn_i8_refusals(pl, s); + attn_case(pl, s, 0.8, true, 1, true, true); + attn_case(pl, s, 0.8, false, 1, false, true); + attn_case(pl, s, 0.0, true, 1, true, true); + attn_case(pl, e, 0.8, false, 1, true, true); + attn_pv8_refusals(pl, s); + const Pass b = make_pass(k768, 2, 1.5f); + attn_case(pl, b, 0.8, true, 61); + attn_case(pl, b, 0.8, true, 61, true); + attn_case(pl, b, 0.8, true, 61, true, true); + attn_case(pl, b, 0.8, false, 61, false, true); + attn_vs_dense_case(pl, b); +} + +} /* namespace vsa */ + static void fused_quant_fp8_numeric(const Plugin& pl) { const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); const RadKernelInfo* smu = find(pl, "silu_mul_bf16"); @@ -7311,6 +10438,701 @@ static void w2_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters tp.label.c_str()); } } +/* ------------------------------------------------------------------ video sparse attention, timed + * + * vsa_select and attn_vsa at FastH3's 1344 x 768 pass (text 300 rows, a soundtrack of 2 x 207, a + * 37 x 24 x 42 grid: 38010 rows, 675 tiles) at a TP2 rank's 28 heads, and attn_dense over the + * same rows in the same run. q, k and v are column slices of one fused row, as the transformer + * writes them, every value distinct (an avalanche hash of its index), so no two tiles share a + * mean. attn_vsa's rate counts the work it does: 4 head_dim (query rows x visible key rows) over + * every (query tile, head), from the selection read back. Warm, back to back. */ +static void vsa_perf(const Plugin& pl, int iters, bool local) { + using namespace vsa; + if (iters <= 0) iters = 5; + const RadKernelInfo* rs = find(pl, "vsa_select_h128_bf16"); + const RadKernelInfo* ra = find(pl, "attn_vsa_h128_bf16"); + const RadKernelInfo* rd = find(pl, "attn_dense_h128_bf16"); + if (!rs || !ra || !rd) { std::printf("--perfvsa: rows absent\n"); return; } + const Shape s = k768; + const std::vector segs = segs_of(s); + const int64_t R = segs.back(), nh = 28, W = nh * kHd, ld = 3 * W; + const Geo g = tiles(segs, s.F, s.Hp, s.Wp); + const int64_t tiles_cap = 1500, k_cap = 704; + void* dq = dalloc((size_t)(R * ld) * 2); + void* dg = dalloc((size_t)(R * W) * 2); + void* dout = dalloc((size_t)(R * W) * 2); + void* dsel = dalloc((size_t)(nh * tiles_cap * k_cap) * 4); + void* dco = dalloc((size_t)(nh * tiles_cap * kHd) * 2); + if (!dq || !dg || !dout || !dsel || !dco) { std::printf("--perfvsa: hipMalloc failed\n"); return; } + auto fill = [](void* d, int64_t n, uint32_t salt) { + const int64_t chunk = (int64_t)8 << 20; + std::vector h((size_t)std::min(chunk, n)); + for (int64_t off = 0; off < n; off += chunk) { + const int64_t m = std::min(chunk, n - off); + for (int64_t i = 0; i < m; ++i) h[(size_t)i] = st_rand_bf16((uint32_t)(off + i) ^ salt); + st_memcpy((uint16_t*)d + off, h.data(), (size_t)m * 2, hipMemcpyHostToDevice); + } + }; + fill(dq, R * ld, 0u); + if (local) { + /* q and k of a video row: half random, half (cos, sin) pairs of its position along one + * axis at wavelengths of 6 to 48 rows, so a score falls with the distance between two + * tiles and a query tile selects its neighbourhood. */ + static const double kWave[7] = { 48, 32, 24, 16, 12, 8, 6 }; + const int64_t vb = segs[segs.size() - 2], rows = 512; + std::vector h((size_t)(rows * ld)); + for (int64_t r0 = vb; r0 < R; r0 += rows) { + const int64_t n = std::min(rows, R - r0); + for (int64_t r = r0; r < r0 + n; ++r) { + uint16_t* hr = h.data() + (r - r0) * ld; + const int x = (int)(r - vb), p3[3] = { x / (s.Hp * s.Wp), (x / s.Wp) % s.Hp, x % s.Wp }; + for (int64_t c = 0; c < ld; ++c) { + const float u = h_bf16(st_rand_bf16((uint32_t)(r * ld + c))); + if (c >= 2 * W) { hr[c] = h_to_bf16(u); continue; } + const int d = (int)(c % kHd), m = d / 2; + const double ph = 2.0 * M_PI * p3[m % 3] / kWave[(m / 3) % 7]; + hr[c] = h_to_bf16(0.5f * u + 0.5f * (float)(d & 1 ? std::sin(ph) : std::cos(ph))); + } + } + st_memcpy((uint16_t*)dq + r0 * ld, h.data(), (size_t)(n * ld) * 2, hipMemcpyHostToDevice); + } + } + fill(dg, R * W, 0x5bd1e995u); + auto col = [&](int64_t which) { + RadTensor t = T((uint16_t*)dq + which * W, RAD_BF16, { R, W }); + t.stride[0] = ld; + return t; + }; + const RadTensor tsegs = TI32({ (int64_t)segs.size() }, segs); + const RadTensor tgeom = TI32({ 16 }, { s.F, 2 * s.Hp, 2 * s.Wp, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0 }); + const RadTensor tsel = T(dsel, RAD_I32, { nh, tiles_cap, k_cap }); + RadTensor tco = T(dco, RAD_BF16, { nh, tiles_cap, kHd }), tgate = T(dg, RAD_BF16, { R, W }); + RadTensor none = tco; + absent(none); + const RadTensor tout = T(dout, RAD_BF16, { R, W }); + + RadArgs probe; + std::memset(&probe, 0, sizeof(probe)); + std::vector pp = params(R, 0.8); + probe.p = pp.data(); probe.n_p = (int)pp.size(); + const int64_t sb = rs->scratch(&probe); + void* scr = dalloc((size_t)sb); + auto time = [&](const RadKernelInfo* r, std::vector ts, std::vector ps, + int it) -> double { + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + a.scratch = scr; a.scratch_bytes = sb; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK) return (double)rc; + if (st_stream_sync(nullptr) != hipSuccess) return -1000.0; + return st_time_us([&](int) { r->launch(&a, nullptr); }, it, nullptr); + }; + /* The work attn_vsa does for the selection in `dsel`, in FLOPs. */ + auto work = [&](double sp) { + const std::vector sel = down_i32(dsel, (size_t)(nh * tiles_cap * k_cap)); + const int k = topk(sp, g.V); + double pre = 0, f = 0; + for (int j = 0; j < g.P; ++j) pre += (double)g.rows[(size_t)j].size(); + for (int64_t h = 0; h < nh; ++h) + for (int i = 0; i < g.N; ++i) { + double keys = i < g.P ? (double)R : pre; + if (i >= g.P) + for (int x = 0; x < k; ++x) + keys += (double)g.rows[(size_t)sel[(size_t)((h * tiles_cap + i) * k_cap + x)]].size(); + f += 4.0 * kHd * (double)g.rows[(size_t)i].size() * keys; + } + return f; + }; + /* Key tiles staged a query tile when `group` consecutive query tiles walk the union of + * their lists. */ + auto staged = [&](double sp, int group) { + const std::vector sel = down_i32(dsel, (size_t)(nh * tiles_cap * k_cap)); + const int k = topk(sp, g.V); + double n = 0; + for (int64_t h = 0; h < nh; ++h) + for (int i0 = 0; i0 < g.N; i0 += group) { + std::vector in((size_t)g.N, 0); + for (int i = i0; i < std::min(i0 + group, g.N); ++i) { + if (i < g.P) { std::fill(in.begin(), in.end(), 1); break; } + for (int j = 0; j < g.P; ++j) in[(size_t)j] = 1; + for (int x = 0; x < k; ++x) in[(size_t)sel[(size_t)((h * tiles_cap + i) * k_cap + x)]] = 1; + } + for (char b : in) n += b; + } + return n / (double)(nh * g.N); + }; + const double dense = 4.0 * (double)R * (double)R * kHd * nh; + + std::printf("1344 x 768: %lld rows, %d tiles (%d prefix, %d video), %lld heads, %s q and k, " + "%d launches each\n", (long long)R, g.N, g.P, g.V, (long long)nh, + local ? "position-structured" : "random", iters); + std::printf("\nvsa_select (vsa_select_h128_bf16), %.1f MiB of scratch\n", (double)sb / 1048576.0); + for (const double sp : { 0.8, 0.0 }) { + for (const bool c : { true, false }) { + const double us = time(rs, { col(0), col(1), c ? col(2) : none, tsegs, tgeom, tsel, + c ? tco : none }, params(R, sp), iters * 2); + if (us < 0) std::printf(" sparsity %.1f coarse %-3s rc %d\n", sp, c ? "yes" : "no", (int)us); + else std::printf(" sparsity %.1f coarse %-3s %9.1f us\n", sp, c ? "yes" : "no", us); + } + } + std::printf("\nattn_vsa (attn_vsa_h128_bf16)\n"); + for (const double sp : { 0.8, 0.0 }) { + /* The selection this sparsity reads, from vsa_select. */ + time(rs, { col(0), col(1), col(2), tsegs, tgeom, tsel, tco }, params(R, sp), 0); + const double f = work(sp); + std::printf(" sparsity %.1f: key tiles staged a query tile, alone %.1f, in pairs %.1f, in " + "fours %.1f\n", sp, staged(sp, 1), staged(sp, 2), staged(sp, 4)); + for (const bool c : { true, false }) { + if (!c && sp == 0.0) continue; + const double us = time(ra, { col(0), col(1), col(2), tsegs, tgeom, tsel, + c ? tco : none, c ? tgate : none, tout }, + params(R, sp), iters); + if (us < 0) std::printf(" sparsity %.1f coarse %-3s rc %d\n", sp, c ? "yes" : "no", (int)us); + else std::printf(" sparsity %.1f coarse %-3s %9.1f us %6.1f TFLOP/s (%.0f GFLOP, %.1f%% " + "of dense)\n", sp, c ? "yes" : "no", us, f / (us * 1e6), f / 1e9, + 100.0 * f / dense); + } + } + /* The int8 Q.K form: k's codes and scales from the device's k (quant_act_i8g's rule), timed + * at sparsity 0.8 on the selection vsa_select writes, and its output against the bf16 + * form's. */ + { + std::vector kh((size_t)(R * W)); + st_memcpy2d(kh.data(), (size_t)W * 2, (uint16_t*)dq + W, (size_t)ld * 2, (size_t)W * 2, + (size_t)R, hipMemcpyDeviceToHost); + std::vector c8((size_t)(R * W)); + std::vector sc((size_t)(R * nh)); + float x[kHd], code[kHd]; + for (int64_t r = 0; r < R; ++r) + for (int64_t h = 0; h < nh; ++h) { + for (int64_t d = 0; d < kHd; ++d) x[d] = h_bf16(kh[(size_t)(r * W + h * kHd + d)]); + sc[(size_t)(r * nh + h)] = q8_row(x, kHd, code); + for (int64_t d = 0; d < kHd; ++d) c8[(size_t)(r * W + h * kHd + d)] = (int8_t)code[d]; + } + void* dk8 = dalloc(c8.size()); + void* dks = up_f32(sc); + void* dref = dalloc((size_t)(R * W) * 2); + if (!dk8 || !dks || !dref) { std::printf("--perfvsa: hipMalloc failed\n"); return; } + st_memcpy(dk8, c8.data(), c8.size(), hipMemcpyHostToDevice); + const RadTensor tk8 = T(dk8, RAD_I8, { R, W }), tks = T(dks, RAD_F32, { R, nh }); + time(rs, { col(0), col(1), col(2), tsegs, tgeom, tsel, tco }, params(R, 0.8), 0); + const double f = work(0.8); + std::vector pi8 = params(R, 0.8); + pi8.push_back(PS("qk", "i8")); + std::printf("\nattn_vsa, qk i8 (k_i8 / k_scale)\n"); + for (const bool c : { true, false }) { + const double us = time(ra, { col(0), col(1), col(2), tsegs, tgeom, tsel, c ? tco : none, + c ? tgate : none, tout, tk8, tks }, pi8, iters); + if (us < 0) std::printf(" sparsity 0.8 coarse %-3s rc %d\n", c ? "yes" : "no", (int)us); + else std::printf(" sparsity 0.8 coarse %-3s %9.1f us %6.1f TFLOP/s\n", c ? "yes" : "no", + us, f / (us * 1e6)); + } + const RadTensor tref = T(dref, RAD_BF16, { R, W }); + time(ra, { col(0), col(1), col(2), tsegs, tgeom, tsel, none, none, tref }, params(R, 0.8), 0); + time(ra, { col(0), col(1), col(2), tsegs, tgeom, tsel, none, none, tout, tk8, tks }, pi8, 0); + const std::vector a = down_bf16(dout, (size_t)(R * W)), b = down_bf16(dref, (size_t)(R * W)); + std::printf(" output against the bf16 form: rel_l2 %.3g\n", rel(a, b)); + + /* The fp8 P.V form: v's codes and column scales from quant_cols_fp8 (timed, with the + * bytes it moves: v read twice, the codes written once), then attn_vsa at int8 and at + * bf16 scores, and its output against the bf16 P.V form at int8 scores and against the + * bf16 form. */ + void* dv8 = dalloc((size_t)(R * W)); + void* dvs = dalloc((size_t)W * 4); + void* dref8 = dalloc((size_t)(R * W) * 2); + if (!dv8 || !dvs || !dref8) { std::printf("--perfvsa: hipMalloc failed\n"); return; } + const RadTensor tv8 = T(dv8, RAD_F8E4M3, { R, W }), tvs = T(dvs, RAD_F32, { W }); + if (const RadKernelInfo* rq = find(pl, "quant_cols_fp8_bf16")) { + const double uq = time(rq, { col(2), tv8, tvs }, { PI("M", R), PI("n", W), + PS("dtype", "bf16") }, iters * 4); + if (uq < 0) std::printf("\nquant_cols_fp8 rc %d\n", (int)uq); + else std::printf("\nquant_cols_fp8 (quant_cols_fp8_bf16), v: %lld x %lld %9.1f us " + "%6.0f GB/s\n", (long long)R, (long long)W, uq, + (double)(R * W) * 5.0 / (uq * 1e3)); + } else { + std::printf("\nquant_cols_fp8: row absent\n"); + return; + } + RadTensor ni8 = T(nullptr, RAD_I8, { 1 }); + absent(ni8); + std::vector p88 = pi8, pb8 = params(R, 0.8); + p88.push_back(PS("pv", "fp8")); + pb8.push_back(PS("pv", "fp8")); + std::printf("attn_vsa, pv fp8 (v as E4M3 codes, v_scale)\n"); + for (const bool i8f : { true, false }) + for (const bool c : { true, false }) { + const double us = time(ra, { col(0), col(1), tv8, tsegs, tgeom, tsel, c ? tco : none, + c ? tgate : none, tout, i8f ? tk8 : ni8, i8f ? tks : ni8, + tvs }, i8f ? p88 : pb8, iters); + if (us < 0) std::printf(" qk %-4s sparsity 0.8 coarse %-3s rc %d\n", i8f ? "i8" : "bf16", + c ? "yes" : "no", (int)us); + else std::printf(" qk %-4s sparsity 0.8 coarse %-3s %9.1f us %6.1f TFLOP/s\n", + i8f ? "i8" : "bf16", c ? "yes" : "no", us, f / (us * 1e6)); + } + const RadTensor tref8 = T(dref8, RAD_BF16, { R, W }); + time(ra, { col(0), col(1), col(2), tsegs, tgeom, tsel, none, none, tref8, tk8, tks }, pi8, 0); + time(ra, { col(0), col(1), tv8, tsegs, tgeom, tsel, none, none, tout, tk8, tks, tvs }, p88, 0); + const std::vector a8 = down_bf16(dout, (size_t)(R * W)); + std::printf(" qk i8 pv fp8 output against qk i8 pv bf16: rel_l2 %.3g, against the bf16 " + "form: rel_l2 %.3g\n", rel(a8, down_bf16(dref8, (size_t)(R * W))), rel(a8, b)); + } + + std::printf("\nattn_dense (attn_dense_h128_bf16), the same rows as one sequence\n"); + const double us = time(rd, { col(0), col(1), col(2), TI32({ 2 }, { 0, (int32_t)R }), tout }, + { PI("M", R), PI("head_dim", kHd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PF("scale", 1.0 / std::sqrt(128.0)), + PI("max_seqlen", R) }, iters); + if (us < 0) std::printf(" rc %d\n", (int)us); + else std::printf(" %9.1f us %6.1f TFLOP/s (%.0f GFLOP)\n", us, dense / (us * 1e6), dense / 1e9); +} + +/* ------------------------------------------------------------------ a video generator, timed + * + * The ops of a video transformer's step and its decoder that dense attention does not dominate, + * at their shapes: the f32 GEMMs (the patch projections over the longest video, the heads over a + * 16384-row part, the timestep MLP, a video decoder's 1x1 projections), the fp8 modulation + * projection into its table, and the dense attention itself over one packed sequence of 3K to 106K + * rows at a TP2 rank's 28 heads, with the rate it reaches (4 M^2 head_dim heads FLOPs), and a + * decoder pass's per-tile attention. Warm: one set of operands, launched back to back; contents + * are bounded random values, so the softmax takes its rescale path as real data does. */ +/* --perfattn M HEADS [iters]: one long non-causal sequence of M rows through the head-128 dense + * attention at HEADS heads -- attn_dense, and attn_prefix_self without a prefix at bf16 and int8 + * scores -- with q, k and v as columns of one fused projection, as a DiT step issues them. */ +static void attn_perf(const Plugin& pl, int64_t M, int64_t H, int iters) { + if (iters <= 0) iters = 5; + const int64_t W = H * 128; + void* dqkv = dalloc((size_t)(M * 3 * W) * 2); + void* dk8 = dalloc((size_t)(M * W)); + void* dks = dalloc((size_t)(M * H) * 4); + void* dout = dalloc((size_t)(M * W) * 2); + if (!dqkv || !dk8 || !dks || !dout) { std::printf("--perfattn: hipMalloc failed\n"); dfree_all(); return; } + { + std::vector h((size_t)(M * 3 * W)); + for (size_t i = 0; i < h.size(); ++i) h[i] = st_rand_bf16((uint32_t)i); + st_memcpy(dqkv, h.data(), h.size() * 2, hipMemcpyHostToDevice); + std::vector c((size_t)(M * W)); + for (size_t i = 0; i < c.size(); ++i) c[i] = (int8_t)((int)((i * 2654435761u) >> 24) % 255 - 127); + st_memcpy(dk8, c.data(), c.size(), hipMemcpyHostToDevice); + std::vector s((size_t)(M * H)); + for (size_t i = 0; i < s.size(); ++i) s[i] = 0.004f + 0.0005f * (float)(i % 7); + st_memcpy(dks, s.data(), s.size() * 4, hipMemcpyHostToDevice); + } + auto col = [&](int64_t c0) { + RadTensor t = T((uint16_t*)dqkv + c0, RAD_BF16, { M, W }); + t.stride[0] = 3 * W; + return t; + }; + RadTensor none = T(nullptr, RAD_BF16, { 1 }); + absent(none); + const RadTensor cu = TI32({ 2 }, { 0, (int32_t)M }); + const double flop = 4.0 * (double)M * (double)M * 128.0 * (double)H; + const int64_t sb = 32 * W * 4; + void* scr = dalloc((size_t)sb); + auto run = [&](const char* row, std::vector ts, std::vector ps) { + const RadKernelInfo* r = find(pl, row); + if (!r) { std::printf(" %-34s absent\n", row); return; } + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + a.scratch = scr; a.scratch_bytes = sb; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + std::printf(" %-34s rc %d\n", row, rc); + return; + } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + const char *qk = "", *pv = ""; + for (const RadParam& p : ps) { + if (!std::strcmp(p.key, "qk")) qk = p.sval; + if (!std::strcmp(p.key, "pv")) pv = p.sval; + } + if (!std::strcmp(row, "quant_cols_fp8_bf16")) + std::printf(" %-26s %-9s %9.2f ms %7.0f GB/s\n", row, "v", us / 1000.0, + (double)(M * W) * 5.0 / (us * 1e3)); + else + std::printf(" %-26s %-4s %-4s %9.2f ms %7.1f TFLOP/s\n", row, qk, pv, us / 1000.0, + flop / (us * 1e6)); + }; + std::printf("dense attention, %lld rows x %lld heads x 128, %d launches each\n", (long long)M, + (long long)H, iters); + run("attn_dense_h128_bf16", { col(0), col(W), col(2 * W), cu, T(dout, RAD_BF16, { M, W }) }, + { PI("M", M), PI("head_dim", 128), PI("gqa", 1), PI("causal", 0), PS("dtype", "bf16"), + PF("scale", 1.0 / std::sqrt(128.0)), PI("max_seqlen", M) }); + for (const char* qk : { "bf16", "i8" }) { + const bool i8 = !std::strcmp(qk, "i8"); + RadTensor k8 = T(dk8, RAD_I8, { M, W }), ks = T(dks, RAD_F32, { M, H }); + if (!i8) { absent(k8); absent(ks); } + run("attn_prefix_self_h128_bf16", + { col(0), col(W), col(2 * W), none, none, none, cu, none, none, k8, ks, + T(dout, RAD_BF16, { M, W }) }, + { PI("q_len", M), PI("head_dim", 128), PI("gqa", 1), PI("block_size", 16), + PI("causal", 0), PS("q_dtype", "bf16"), PS("kv_dtype", "bf16"), + PF("scale", 1.0 / std::sqrt(128.0)), PI("max_ctx", 0), PI("n_head", H), + PI("max_seqs", 1), PS("qk", qk) }); + } + /* The fp8 P.V form, v's codes and column scales written by quant_cols_fp8 (timed too). */ + void* dv8 = dalloc((size_t)(M * W)); + void* dvs = dalloc((size_t)W * 4); + if (!dv8 || !dvs || !scr) { std::printf("--perfattn: hipMalloc failed\n"); dfree_all(); return; } + const RadTensor tv8 = T(dv8, RAD_F8E4M3, { M, W }), tvs = T(dvs, RAD_F32, { W }); + run("quant_cols_fp8_bf16", { col(2 * W), tv8, tvs }, + { PI("M", M), PI("n", W), PS("dtype", "bf16") }); + for (const char* qk : { "bf16", "i8" }) { + const bool i8 = !std::strcmp(qk, "i8"); + RadTensor k8 = T(dk8, RAD_I8, { M, W }), ks = T(dks, RAD_F32, { M, H }); + if (!i8) { absent(k8); absent(ks); } + run("attn_prefix_self_h128_bf16", + { col(0), col(W), tv8, none, none, none, cu, none, none, k8, ks, + T(dout, RAD_BF16, { M, W }), tvs }, + { PI("q_len", M), PI("head_dim", 128), PI("gqa", 1), PI("block_size", 16), + PI("causal", 0), PS("q_dtype", "bf16"), PS("kv_dtype", "bf16"), + PF("scale", 1.0 / std::sqrt(128.0)), PI("max_ctx", 0), PI("n_head", H), + PI("max_seqs", 1), PS("qk", qk), PS("pv", "fp8") }); + } + dfree_all(); +} + +static void video_perf(const Plugin& pl, int iters, const char* only) { + if (iters <= 0) iters = 10; + /* One section by name, or every one. */ + auto want = [&](const char* sec) { return !only || !std::strcmp(only, sec); }; + /* Device memory filled with bounded random bf16, a 16 MiB pattern repeated. */ + auto rand_fill = [](void* d, size_t bytes) { + const size_t chunk = std::min(bytes, (size_t)16 << 20); + std::vector h(chunk / 2); + for (size_t i = 0; i < h.size(); ++i) h[i] = st_rand_bf16((uint32_t)i); + for (size_t off = 0; off < bytes; off += chunk) + st_memcpy((uint8_t*)d + off, h.data(), std::min(chunk, bytes - off), hipMemcpyHostToDevice); + }; + auto time_row = [&](const RadKernelInfo* r, std::vector ts, std::vector ps, + int it) -> double { + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + const int rc = r->launch(&a, nullptr); + /* A refusal or a fault comes back negative: the launch's code, or -1000. */ + if (rc != RAD_OK) return (double)rc; + if (st_stream_sync(nullptr) != hipSuccess) return -1000.0; + return st_time_us([&](int) { r->launch(&a, nullptr); }, it, nullptr); + }; + + /* Random E4M3 codes over the whole range but the two NaN codes, as a quantiser with an amax + * scale writes them; at a power limit the time depends on how many bits switch. */ + auto rand_fill_e4m3 = [](void* d, size_t bytes) { + const size_t chunk = std::min(bytes, (size_t)16 << 20); + std::vector h(chunk); + for (size_t i = 0; i < h.size(); ++i) { + const uint8_t b = (uint8_t)(st_mix32((uint32_t)i) >> 7); + h[i] = (b & 0x7Fu) == 0x7Fu ? (uint8_t)(b ^ 1u) : b; + } + for (size_t off = 0; off < bytes; off += chunk) + st_memcpy((uint8_t*)d + off, h.data(), std::min(chunk, bytes - off), hipMemcpyHostToDevice); + }; + + if (want("trunk")) { + std::printf("gemm_nt_q at fp8a8 (gemm_fp8a8_tiled): the DiT's linears on one of two ranks, at " + "a short clip's rows, half a step's and a whole step's, %d launches each\n", + iters); + const RadKernelInfo* gq = find(pl, "gemm_fp8a8_tiled"); + struct L { const char* what; int64_t N, K; }; + for (const int64_t M : { (int64_t)1412, (int64_t)18648, (int64_t)37774 }) { + for (const L& g : { L{ "qkv", 10752, 5376 }, L{ "qkv + gate (FastH3)", 14336, 5376 }, + L{ "o", 5376, 3584 }, L{ "gate_up", 14336, 5376 }, + L{ "down", 5376, 7168 } }) { + if (!gq) { std::printf(" row absent\n"); break; } + const int64_t sk = g.K / 128, sn = g.N / 128; + void* dx = dalloc((size_t)(M * g.K)); + void* dxs = dalloc((size_t)(M * sk) * 4); + void* dw = dalloc((size_t)(g.N * g.K)); + void* dws = dalloc((size_t)(sn * sk) * 2); + void* dy = dalloc((size_t)(M * g.N) * 2); + if (!dx || !dxs || !dw || !dws || !dy) { std::printf(" hipMalloc failed\n"); dfree_all(); continue; } + rand_fill_e4m3(dx, (size_t)(M * g.K)); + rand_fill_e4m3(dw, (size_t)(g.N * g.K)); + { + std::vector xs((size_t)(M * sk)); + for (size_t i = 0; i < xs.size(); ++i) + xs[i] = (1.0f + (float)(st_mix32((uint32_t)i) & 1023u) / 1024.0f) * 2.0e-3f; + st_memcpy(dxs, xs.data(), xs.size() * 4, hipMemcpyHostToDevice); + std::vector ws((size_t)(sn * sk)); + for (size_t i = 0; i < ws.size(); ++i) + ws[i] = h_to_bf16((1.0f + (float)(st_mix32((uint32_t)i + 7u) & 1023u) / 1024.0f) * 3.0e-4f); + st_memcpy(dws, ws.data(), ws.size() * 2, hipMemcpyHostToDevice); + } + RadTensor t5 = T(nullptr, RAD_F32, { 1 }), t6 = T(nullptr, RAD_U8, { 1 }); + absent(t5); + absent(t6); + const int it = M > 20000 ? std::max(2, iters / 2) : iters; + const double us = time_row(gq, { T(dx, RAD_F8E4M3, { M, g.K }), T(dxs, RAD_F32, { M, sk }), + T(dw, RAD_F8E4M3, { g.N, g.K }), T(dws, RAD_BF16, { sn, sk }), + T(dy, RAD_BF16, { M, g.N }), t5, t6 }, + { PI("M", M), PI("N", g.N), PI("K", g.K), PI("group", 128), + PS("dtype", "fp8a8") }, + it); + if (us < 0) std::printf(" %-20s M %6lld: rc %d\n", g.what, (long long)M, (int)us); + else std::printf(" %-20s M %6lld N %5lld K %5lld %9.1f us %6.1f TFLOP/s\n", g.what, + (long long)M, (long long)g.N, (long long)g.K, us, + 2.0 * (double)M * g.N * g.K / (us * 1e6)); + dfree_all(); + } + } + } + + if (want("decoder")) { + std::printf("\ngemm_nt_bias at bf16 (gemm_bf16_nt_bias_tiled): the video decoder's linears " + "over 14 tiles of 1797 rows, f32 bias, %d launches each\n", iters); + const RadKernelInfo* gb = find(pl, "gemm_bf16_nt_bias_tiled"); + struct L { const char* what; int64_t N, K; }; + const int64_t M = 14 * 1797; + for (const L& g : { L{ "qkv", 6144, 2048 }, L{ "o", 2048, 2048 }, L{ "up", 16384, 2048 }, + L{ "down", 2048, 8192 } }) { + if (!gb) { std::printf(" row absent\n"); break; } + void* da = dalloc((size_t)(M * g.K) * 2); + void* dw = dalloc((size_t)(g.N * g.K) * 2); + void* db = dalloc((size_t)g.N * 4); + void* dy = dalloc((size_t)(M * g.N) * 2); + if (!da || !dw || !db || !dy) { std::printf(" hipMalloc failed\n"); dfree_all(); continue; } + rand_fill(da, (size_t)(M * g.K) * 2); + rand_fill(dw, (size_t)(g.N * g.K) * 2); + RadTensor tr = T(nullptr, RAD_BF16, { 1 }); + absent(tr); + const double us = time_row(gb, { T(da, RAD_BF16, { M, g.K }), T(dw, RAD_BF16, { g.N, g.K }), + T(db, RAD_F32, { g.N }), tr, T(dy, RAD_BF16, { M, g.N }) }, + { PI("M", M), PI("N", g.N), PI("K", g.K), PS("dtype", "bf16") }, + iters); + if (us < 0) std::printf(" %-6s rc %d\n", g.what, (int)us); + else std::printf(" %-6s M %6lld N %5lld K %5lld %9.1f us %6.1f TFLOP/s\n", g.what, + (long long)M, (long long)g.N, (long long)g.K, us, + 2.0 * (double)M * g.N * g.K / (us * 1e6)); + dfree_all(); + } + + /* The elementwise ops that follow those GEMMs in a decoder layer: o and down each feed a + * layer scale into the f32 residual, up feeds the SwiGLU. What an epilogue fusion would + * absorb. */ + std::printf(" the elementwise ops after them, %d launches each\n", iters); + const int64_t dim = 2048, ff = 8192; + void* dx = dalloc((size_t)(M * 2 * ff) * 2); + void* dt = dalloc((size_t)(M * dim) * 4); + void* dr = dalloc((size_t)(M * dim) * 4); + void* dsc = dalloc((size_t)dim * 4); + void* dact = dalloc((size_t)(M * ff) * 2); + if (!dx || !dt || !dr || !dsc || !dact) { std::printf(" hipMalloc failed\n"); dfree_all(); } + else { + rand_fill(dx, (size_t)(M * 2 * ff) * 2); + rand_fill(dr, (size_t)(M * dim) * 4); + struct E { const char* what; const char* row; std::vector ts; + std::vector ps; double bytes; }; + for (const E& e : { + E{ "layer scale (mul_weight_f32), bf16 -> f32", "mul_weight_f32", + { T(dx, RAD_BF16, { M, dim }), T(dsc, RAD_F32, { dim }), T(dt, RAD_F32, { M, dim }) }, + { PI("M", M), PI("n", dim), PS("dtype", "f32") }, (double)M * dim * 6 }, + E{ "residual (add_f32), in place", "add_f32", + { T(dr, RAD_F32, { M, dim }), T(dt, RAD_F32, { M, dim }), T(dr, RAD_F32, { M, dim }) }, + { PI("M", M), PI("n", dim), PS("dtype", "f32") }, (double)M * dim * 12 }, + E{ "SwiGLU (silu_mul_bf16)", "silu_mul_bf16", + { T(dx, RAD_BF16, { M, 2 * ff }), T(dact, RAD_BF16, { M, ff }) }, + { PI("M", M), PI("n", ff), PS("dtype", "bf16") }, (double)M * ff * 6 } }) { + const RadKernelInfo* r = find(pl, e.row); + if (!r) { std::printf(" %s: row absent\n", e.row); continue; } + const double us = time_row(r, e.ts, e.ps, iters); + if (us < 0) std::printf(" %-44s rc %d\n", e.what, (int)us); + else std::printf(" %-44s %9.1f us %6.1f GB/s\n", e.what, us, e.bytes / (us * 1e3)); + } + dfree_all(); + } + } + + if (want("f32")) { + std::printf("\ngemm_nt_bias at f32 (gemm_f32_nt_bias), %d launches each\n", iters); + const RadKernelInfo* gf = find(pl, "gemm_f32_nt_bias"); + struct G { const char* what; int64_t M, N, K; bool bf16; }; + for (const G& g : { G{ "video patch projection (102816 rows)", 102816, 5376, 96, true }, + G{ "soundtrack projection (1152 rows)", 1152, 5376, 32, true }, + G{ "video head, one 16384-row part", 16384, 96, 5376, false }, + G{ "soundtrack head (1152 rows)", 1152, 32, 5376, false }, + G{ "timestep MLP 1 (128 rows)", 128, 5376, 256, false }, + G{ "timestep MLP 2 (128 rows)", 128, 2688, 5376, false }, + G{ "decoder post_quant_conv", 28224, 24, 24, false }, + G{ "decoder proj_in", 28224, 2048, 24, false } }) { + if (!gf) { std::printf(" row absent\n"); break; } + void* da = dalloc((size_t)(g.M * g.K) * 4); + void* dw = dalloc((size_t)(g.N * g.K) * 4); + void* db = dalloc((size_t)g.N * 4); + void* dy = dalloc((size_t)(g.M * g.N) * (g.bf16 ? 2 : 4)); + if (!da || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", g.what); dfree_all(); continue; } + rand_fill(da, (size_t)(g.M * g.K) * 4); + rand_fill(dw, (size_t)(g.N * g.K) * 4); + RadTensor tr = T(nullptr, g.bf16 ? RAD_BF16 : RAD_F32, { 1 }); + absent(tr); + const double us = time_row(gf, { T(da, RAD_F32, { g.M, g.K }), T(dw, RAD_F32, { g.N, g.K }), + T(db, RAD_F32, { g.N }), tr, + T(dy, g.bf16 ? RAD_BF16 : RAD_F32, { g.M, g.N }) }, + { PI("M", g.M), PI("N", g.N), PI("K", g.K), PS("dtype", "f32") }, + iters); + if (us < 0) std::printf(" %-40s rc %d\n", g.what, (int)us); + else std::printf(" %-40s M %6lld N %5lld K %5lld -> %s %9.1f us %6.2f TFLOP/s\n", g.what, + (long long)g.M, (long long)g.N, (long long)g.K, g.bf16 ? "bf16" : "f32 ", + us, 2.0 * (double)g.M * g.N * g.K / (us * 1e6)); + dfree_all(); + } + } + + if (want("conv")) { + std::printf("\nconv1d and conv_t1d at f32 (conv1d_f32, conv_t1d_f32): a BigVGAN's stages over " + "the longest soundtrack's two channels\n"); + { + const RadKernelInfo* c1 = find(pl, "conv1d_f32"); + const RadKernelInfo* ct = find(pl, "conv_t1d_f32"); + struct C { const char* what; bool t; int64_t rows, cin, cout, k, dil, s; }; + for (const C& c : { C{ "conv_pre", false, 1152, 2048, 1024, 7, 1, 1 }, + C{ "stage 0 upsample", true, 1152, 1024, 512, 9, 1, 5 }, + C{ "stage 0 AMP conv k11 dil 5", false, 5760, 512, 512, 11, 5, 1 }, + C{ "stage 1 AMP conv k11 dil 5", false, 28800, 256, 256, 11, 5, 1 }, + C{ "stage 2 AMP conv k11 dil 5", false, 57600, 128, 128, 11, 5, 1 }, + C{ "stage 4 AMP conv k11 dil 5", false, 230400, 32, 32, 11, 5, 1 }, + C{ "stage 6 AMP conv k11 dil 5", false, 921600, 8, 8, 11, 5, 1 }, + C{ "conv_post", false, 921600, 8, 1, 7, 1, 1 } }) { + const RadKernelInfo* r = c.t ? ct : c1; + if (!r) { std::printf(" row absent\n"); break; } + const int64_t orows = c.rows * c.s, taps = (c.k + c.s - 1) / c.s; + void* dx = dalloc((size_t)(c.rows * c.cin) * 4); + void* dw = dalloc((size_t)(c.s * c.cout * taps * c.cin) * 4); + void* db = dalloc((size_t)c.cout * 4); + void* dy = dalloc((size_t)(orows * c.cout) * 4); + if (!dx || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", c.what); dfree_all(); continue; } + rand_fill(dx, (size_t)(c.rows * c.cin) * 4); + rand_fill(dw, (size_t)(c.s * c.cout * taps * c.cin) * 4); + const int32_t half = (int32_t)(c.rows / 2); + std::vector ts; + std::vector ps = { PI("M", c.rows), PI("cin", c.cin), PI("cout", c.cout), + PI("k", c.k), PS("dtype", "f32") }; + if (c.t) { + ts = { T(dx, RAD_F32, { c.rows, c.cin }), T(dw, RAD_F32, { c.cin, c.cout, c.k }), + T(db, RAD_F32, { c.cout }), TI32({ 3 }, { 0, half, (int32_t)c.rows }), + T(dy, RAD_F32, { orows, c.cout }) }; + ps.push_back(PI("stride", c.s)); + ps.push_back(PI("pad", (c.k - c.s) / 2)); + } else { + RadTensor tr = T(nullptr, RAD_F32, { 1 }); + absent(tr); + ts = { T(dx, RAD_F32, { c.rows, c.cin }), T(dw, RAD_F32, { c.cout, c.cin, c.k }), + TI32({ 3 }, { 0, half, (int32_t)c.rows }), tr, + T(dy, RAD_F32, { c.rows, c.cout }), T(db, RAD_F32, { c.cout }) }; + ps.push_back(PI("dil", c.dil)); + } + const double us = time_row(r, ts, ps, iters); + if (us < 0) std::printf(" %-28s rc %d\n", c.what, (int)us); + else std::printf(" %-28s rows %7lld cin %4lld cout %4lld k %2lld %9.1f us %6.2f TFLOP/s\n", + c.what, (long long)orows, (long long)c.cin, (long long)c.cout, + (long long)c.k, us, + 2.0 * (double)orows * c.cout * c.cin * (double)c.k / c.s / (us * 1e6)); + dfree_all(); + } + } + } + + if (want("mod")) { + std::printf("\ngemm_nt_q_bias at fp8a8 (gemm_fp8a8_bias_nt_m16): a modulation projection, its " + "50 timesteps into a column block of the table\n"); + if (const RadKernelInfo* gq = find(pl, "gemm_fp8a8_bias_nt_m16")) { + for (const int64_t N : { (int64_t)16128, (int64_t)32256 }) { + const int64_t M = 50, K = 2688, sk = K / 128, sn = (N + 127) / 128, width = 3 * N; + void* dx = dalloc((size_t)(M * K)); + void* dxs = dalloc((size_t)(M * sk) * 4); + void* dw = dalloc((size_t)(N * K)); + void* dws = dalloc((size_t)(sn * sk) * 2); + void* db = dalloc((size_t)N * 2); + void* dy = dalloc((size_t)(M * width) * 2); + if (!dx || !dxs || !dw || !dws || !db || !dy) { std::printf(" hipMalloc failed\n"); break; } + RadTensor ty = T(dy, RAD_BF16, { M, N }); + ty.stride[0] = width; + const double us = time_row(gq, { T(dx, RAD_F8E4M3, { M, K }), T(dxs, RAD_F32, { M, sk }), + T(dw, RAD_F8E4M3, { N, K }), T(dws, RAD_BF16, { sn, sk }), + T(db, RAD_BF16, { N }), ty }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8") }, + iters); + if (us < 0) std::printf(" N %lld: rc %d\n", (long long)N, (int)us); + else std::printf(" M %lld N %6lld K %lld %9.1f us %6.1f GB/s of weight (warm)\n", + (long long)M, (long long)N, (long long)K, us, + (double)(N * K) / (us * 1e3)); + dfree_all(); + } + } + } + + if (want("attn")) { + std::printf("\nattn_dense at head_dim 128, non-causal, one sequence, 28 heads " + "(attn_dense_h128_bf16)\n"); + if (const RadKernelInfo* ra = find(pl, "attn_dense_h128_bf16")) { + for (const int64_t M : { (int64_t)3072, (int64_t)16384, (int64_t)38016, (int64_t)73000, + (int64_t)106000 }) { + const int64_t nh = 28, hd = 128, wq = nh * hd, width = 3 * wq; + void* dq = dalloc((size_t)(M * width) * 2); + void* dout = dalloc((size_t)(M * wq) * 2); + if (!dq || !dout) { std::printf(" M %lld: hipMalloc failed\n", (long long)M); dfree_all(); continue; } + rand_fill(dq, (size_t)(M * width) * 2); + auto col = [&](int64_t first) { + RadTensor t = T((uint16_t*)dq + first, RAD_BF16, { M, wq }); + t.stride[0] = width; + return t; + }; + const int it = M > 40000 ? 2 : M > 10000 ? 3 : iters; + const double us = time_row(ra, { col(0), col(wq), col(2 * wq), + TI32({ 2 }, { 0, (int32_t)M }), T(dout, RAD_BF16, { M, wq }) }, + { PI("M", M), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PF("scale", 1.0 / std::sqrt(128.0)), + PI("max_seqlen", M) }, + it); + if (us < 0) std::printf(" M %6lld: rc %d\n", (long long)M, (int)us); + else std::printf(" M %6lld %11.1f us %6.1f TFLOP/s\n", (long long)M, us, + 4.0 * (double)M * (double)M * hd * nh / (us * 1e6)); + dfree_all(); + } + } + } + + if (want("attn64")) { + std::printf("\nattn_dense at head_dim 64 over 14 decoder tiles of 1797 rows, 32 heads " + "(attn_dense_h64_bf16)\n"); + if (const RadKernelInfo* ra = find(pl, "attn_dense_h64_bf16")) { + const int64_t tiles = 14, period = 1797, M = tiles * period, nh = 32, hd = 64; + const int64_t wq = nh * hd, width = 3 * wq; + void* dq = dalloc((size_t)(M * width) * 2); + void* dout = dalloc((size_t)(M * wq) * 2); + if (dq && dout) { + rand_fill(dq, (size_t)(M * width) * 2); + std::vector cu((size_t)tiles + 1); + for (int64_t t = 0; t <= tiles; ++t) cu[(size_t)t] = (int32_t)(t * period); + auto col = [&](int64_t first) { + RadTensor t = T((uint16_t*)dq + first, RAD_BF16, { M, wq }); + t.stride[0] = width; + return t; + }; + const double us = time_row(ra, { col(0), col(wq), col(2 * wq), TI32({ tiles + 1 }, cu), + T(dout, RAD_BF16, { M, wq }) }, + { PI("M", M), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16"), PF("scale", 0.125), + PI("max_seqlen", period) }, + iters); + if (us < 0) std::printf(" rc %d\n", (int)us); + else std::printf(" %lld rows %9.1f us %6.1f TFLOP/s\n", (long long)M, us, + 4.0 * (double)period * period * hd * nh * tiles / (us * 1e6)); + } + dfree_all(); + } + } +} + static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { if (N % 128 || K % 128 || M < 1) { std::printf("--perf: N and K must be 128-aligned and M >= 1\n"); @@ -12472,23 +16294,23 @@ static void ngram_ahead_case(const Plugin& pl) { ok("ngram_ids_i32 ahead: the ids ahead are the ones the next step computes", ahd1 == ids2); } -/* ---- RUNTIME LoRA: a lora_shrink row then a lora_expand row, as the engine issues them, against an +/* ---- Runtime LoRA: a lora_shrink row then a lora_expand row, as the engine issues them, against an * f64 host sum and libref's bytes. * - * Both halves in one case, because expand reads the `t` shrink wrote. A base row (slot -1, S, - * -5) keeps the 0xFF fill of `t` and every byte of `y` (a -0 included), and the column slices' + * Both halves in one case, because expand reads the `t` shrink wrote. A base row (slot -1, S, -5) + * keeps the 0xFF fill of `t` and every byte of `y` (a -0 included), and the column slices' * neighbours are untouched. Adapter rows: shrink within (K + 2) 2^-24 sum|terms| of the f64 sum * (an f32 dot's worst case in any order); expand exactly the bytes of libref's f32 order (j - * ascending, sum then scale then add, one RTNE) over the `t` the device wrote. The v1 pair runs - * its four small shapes and two real ones; the tiled pairs run the real shapes -- M 1 / 8 / 2048, - * K 2048 / 5120 / 6144 / 17408, N 2560 / 12288 / 17408, R 16 / 48 / 64 / 192 -- with slots in - * runs the way a prefill chunk holds several requests and base rows, plus: + * ascending, sum then scale then add, one RTNE) over the `t` the device wrote. The scalar pair + * runs four small shapes and two real ones; the tiled pairs run the real shapes (M 1 / 8 / 2048, + * K 2048 / 5120 / 6144 / 17408, N 2560 / 12288 / 17408, R 16 / 48 / 64 / 192) with slots in runs + * the way a prefill chunk holds several requests and base rows, plus: * - * * BATCH INVARIANCE ON THE CARD: rows computed alone (M = 1) and inside batches of 8, 37 and - * 2048 with other slots and base rows around them give the same t and y bits. This is the - * check the emulator cannot make -- that the WMMA unit's answer for a row does not depend on - * the tile position it lands in or on the rows beside it. - * * A LAUNCH OF BASE ROWS ONLY touches no byte of t or y. */ + * - Batch invariance on the card: rows computed alone (M = 1) and inside batches of 8, 37 and + * 2048 with other slots and base rows around them give the same t and y bits, which the + * emulator cannot check (the WMMA unit's answer for a row must not depend on its tile + * position or the rows beside it). + * - A launch of base rows only touches no byte of t or y. */ struct LoraProb { int M = 0, K = 0, N = 0, R = 0, S = 4; bool fp8 = false; @@ -12727,9 +16549,9 @@ static void lora_pair_case(const Plugin& pl, const char* sname, const char* enam (long long)bad_y)); } -/* BATCH INVARIANCE ON THE CARD. For each of `n_tgt` target rows of a batch (several slots, at - * tile starts, ends and middles), the same row alone -- its x, scales, slot and y, the same pools - * -- must come back with the same t and y bits. */ +/* Batch invariance on the card. For each of `n_tgt` target rows of a batch (several slots, at tile + * starts, ends and middles), the same row alone (its x, scales, slot and y, the same pools) must + * come back with the same t and y bits. */ static void lora_invariance_case(const Plugin& pl, const char* sname, const char* ename, int K, int N, int R, bool fp8, uint32_t ydt) { const RadKernelInfo* rs = find(pl, sname); @@ -12834,8 +16656,8 @@ static void lora_case(const Plugin& pl) { } } -/* ---- --perflora M K N R S PATTERN [iters]: every lora_shrink row, then every lora_expand row, - * at one shape, warm (or cold with --cold). The pattern lays the slots out: +/* ---- --perflora M K N R S PATTERN [iters] [a=DT] [y=DT]: every lora_shrink row, then every + * lora_expand row, at one shape, warm (or cold with --cold). The pattern lays the slots out: * * base every row a base row -- what a base request pays for the adapter ops being there * one every row adapter 0 -- one request, or a prefill chunk of one @@ -12843,22 +16665,17 @@ static void lora_case(const Plugin& pl) { * mix row m on adapter m % S -- every adapter in every tile, the most passes a tile has * runs contiguous runs of ceil(M / S) rows a slot -- a chunk holding S requests * - * `a` is bf16, or E4M3 with a scale every 128 when R4D_PERFLORA_A=fp8_e4m3; `y` bf16, or the - * dtype R4D_PERFLORA_Y names (f16, f32). Rows that do not serve the dtype say so. Each shrink row's - * t is compared with the first row's (max |diff| over max |t|), and each expand row's y bytes with - * the first's over the same t -- equal bytes is the claim the tiled expand makes. The GB/s column - * is the bytes the op cannot avoid (each active adapter's pool once, x or y once) over the time. */ + * `a` is bf16, or E4M3 with a scale every 128 (`a=fp8_e4m3`); `y` is bf16, f16 or f32 (`y=`). + * Rows that do not serve the dtype say so. Each shrink row's t is compared with the first row's + * (max |diff| over max |t|), and each expand row's y bytes with the first's over the same t, since + * the tiled expand claims equal bytes. The GB/s column is the bytes the op cannot avoid (each + * active adapter's pool once, x or y once) over the time. */ static void lora_perf(const Plugin& pl, int64_t M, int64_t K, int64_t N, int64_t R, int64_t S, - const char* pat, int iters) { + const char* pat, int iters, bool fp8, uint32_t ydt) { if (M < 1 || K < 1 || N < 1 || R < 1 || S < 1 || iters < 1) { std::printf("--perflora: M K N R S must be >= 1\n"); return; } - const char* ae = std::getenv("R4D_PERFLORA_A"); - const char* ye = std::getenv("R4D_PERFLORA_Y"); - const bool fp8 = ae && !std::strcmp(ae, "fp8_e4m3"); - const uint32_t ydt = ye && !std::strcmp(ye, "f32") ? RAD_F32 - : (ye && !std::strcmp(ye, "f16") ? RAD_F16 : RAD_BF16); std::vector slot((size_t)M); const int64_t run = (M + S - 1) / S; for (int64_t m = 0; m < M; ++m) { @@ -13148,6 +16965,7 @@ static void device_phase(const Plugin& pl) { struct G { const char* name; int64_t hd, nh, nkv; }; for (const G& g : { G{ "attn_dense_h64_bf16", 64, 4, 4 }, G{ "attn_dense_h256_gqa2_bf16", 256, 4, 2 }, + G{ "attn_dense_h256_gqa4_bf16", 256, 4, 1 }, G{ "attn_dense_h512_gqa4_bf16", 512, 4, 1 } }) { if (!sel(g.name)) continue; const RadKernelInfo* r = find(pl, g.name); @@ -13742,6 +17560,59 @@ static void device_phase(const Plugin& pl) { check("attn_local_rel_bf16 numerics", down(dout, want.size()), want, 1e-2); } } + if (sel("cast_bf16_f16")) { + /* Every value against rad_f32_to_f16 of the bf16 value, bit for bit: f16's normal range + * (kept exactly), its subnormals (rounded to nearest even) and past 65504 (an infinity), + * over rows of a column slice so both pitches are read. */ + const RadKernelInfo* r = find(pl, "cast_bf16_f16"); + if (!r) ok("cast_bf16_f16", false, "row absent"); + else { + const int64_t M = 5, n = 1000, ldx = 1024; + std::vector hx((size_t)(M * ldx), 0x7fc0); + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) { + const uint32_t h = st_mix32((uint32_t)(m * 4096 + i) ^ 0xc457u); + /* exponents from 2^-30 to 2^20 and both signs */ + const float v = std::ldexp(1.0f + (float)(h & 0x7f) / 128.0f, + (int)((h >> 8) % 51) - 30) * ((h >> 16) & 1 ? -1.0f : 1.0f); + hx[(size_t)(m * ldx + i)] = rad_f32_to_bf16(v); + } + void* d_x = dalloc(hx.size() * 2); + void* d_y = dalloc((size_t)(M * n * 2)); + if (!d_x || !d_y) ok("cast_bf16_f16", false, "hipMalloc failed"); + else { + st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); + RadTensor tx = T(d_x, RAD_BF16, { M, n }); + tx.stride[0] = ldx; + std::vector ts = { tx, T(d_y, RAD_F16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PS("from", "bf16"), + PS("to", "f16") }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + const int rc = r->launch(&a, (RadStream) nullptr); + std::vector hy((size_t)(M * n), 0); + if (rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess) + st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); + int64_t bad = 0, inf = 0, sub = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < n; ++i) { + const uint16_t want = + rad_f32_to_f16(rad_bf16_to_f32(hx[(size_t)(m * ldx + i)])); + bad += hy[(size_t)(m * n + i)] != want; + inf += (want & 0x7fff) == 0x7c00; + sub += (want & 0x7c00) == 0 && (want & 0x3ff) != 0; + } + char d[96]; + std::snprintf(d, sizeof d, "rc=%d, %lld of %lld differ (%lld inf, %lld subnormal)", + rc, (long long)bad, (long long)(M * n), (long long)inf, (long long)sub); + ok("cast_bf16_f16 rounds as rad_f32_to_f16", rc == RAD_OK && bad == 0 && inf > 0 && + sub > 0, d); + } + } + } if (sel("cast_bf16_f32")) { const RadKernelInfo* r = find(pl, "cast_bf16_f32"); if (!r) ok("cast_bf16_f32", false, "row absent"); @@ -14230,6 +18101,12 @@ static void device_phase(const Plugin& pl) { i8a8_numeric(pl, "gemm_i8a8_nt_m16", 64, 512, 640); i8a8_numeric(pl, "gemm_i8a8_tiled", 200, 256, 640); i8a8_numeric(pl, "gemm_i8a8_tiled", 2048, 512, 2560); + /* The bias GEMM: three shapes on the 128 x 128 kernel (ragged N with an unaligned pitch; + * an aligned ragged N with a K tail; K below one tile) and one on the 64 x 64 kernel. */ + bias_gemm_numeric(pl, 1100, 1001, 200, 1, true, false); + bias_gemm_numeric(pl, 520, 1040, 1104, 0, true, true); + bias_gemm_numeric(pl, 2050, 600, 40, 2, false, true); + bias_gemm_numeric(pl, 200, 300, 136, 2, true, false); w8a16_numeric(pl, "gemm_w8a16_nt_m64", 5, 272, 384, RAD_F16); w8a16_numeric(pl, "gemm_w8a16_nt_m64", 64, 2560, 6144, RAD_F16); gemm_case(pl, "gemm_w4a8_nt_m64", "w4a8", M, N, K, RAD_I8, 1, 0, 0, N*K/2, N*(K/128)*4); @@ -14588,6 +18465,77 @@ static void device_phase(const Plugin& pl) { rope_ladder_case(pl); } + /* The audio generator's ops and the optional forms a speech model adds, each against libref's + * arithmetic. */ + if (sel("conv1d_bf16")) au::conv1d_cases(pl); + if (sel("conv_t1d_bf16")) au::conv_t1d_cases(pl); + if (sel("snake_bf16")) au::snake_cases(pl); + if (sel("cfg_topk_sample")) au::cfg_topk_cases(pl); + if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl); + if (sel("frame_store")) au::frame_store_cases(pl); + if (sel("iota")) au::iota_cases(pl); + if (sel("gelu_bf16")) au::gelu_case(pl); + if (sel("mul_weight_bf16")) au::mul_weight_f32_case(pl); + if (sel("qk_norm_rope_bf16")) au::qk_norm_rope_f32_gain_case(pl); + if (sel("attn_dense_h64_bf16")) { + au::attn_causal_h64_case(pl, 72, { 0, 89 }); + au::attn_causal_h64_case(pl, 0, { 0, 89 }); + au::attn_causal_h64_case(pl, 72, { 0, 13, 89 }); + au::attn_causal_h64_case(pl, 9, { 0, 40, 200 }); + } + if (sel("conv1d_dw_bf16")) au::conv1d_dw_bias_cases(pl); + if (sel("attn_dense_h256_gqa4_bf16")) { + au::attn_window_right_cases(pl, "attn_dense_h256_gqa4_bf16", 4, 1, 256, 257); + au::attn_window_right_cases(pl, "attn_dense_h256_gqa4_bf16", 4, 1, 9, 0); + } + if (sel("attn_dense_h256_gqa2_bf16")) { + au::attn_window_right_cases(pl, "attn_dense_h256_gqa2_bf16", 4, 2, 9, 5); + au::attn_window_right_cases(pl, "attn_dense_h256_gqa2_bf16", 4, 2, 9, 0); + au::attn_refusal_cases(pl); + } + if (sel("attn_dense_small_h256_bf16")) au::attn_small_refusal_case(pl); + /* The video generator's ops, the decoder's at a geometry rad-kbench cannot fill. */ + if (sel("patch_unfold_f32")) vid::patch_unfold_cases(pl); + if (sel("vtile_gather")) vid::vtile_gather_cases(pl); + if (sel("vtile_stitch")) vid::vtile_stitch_cases(pl); + if (sel("rms_mod_bf16")) vid::rms_mod_cases(pl, false); + if (sel("rms_mod_quant_fp8_bf16")) vid::rms_mod_cases(pl, true); + if (sel("flow_x0_step_f32")) vid::flow_x0_cases(pl); + if (sel("grid_pos3")) vid::grid_pos3_cases(pl); + if (sel("snake_aa_f32")) vid::snake_aa_cases(pl); + if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl); + if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl); + if (sel("quant_cols_fp8_bf16")) vsa::quant_cols_cases(pl); + if (sel("attn_prefix_self_h128_bf16")) vsa::dense_cases(pl); + if (sel("rope_bf16")) au::rope_llama3_case(pl); + + /* A video generator's f32 forms, its biased GEMMs, its axial rotary and its two dense + * attentions, each against libref's arithmetic. */ + if (sel("gemm_f32_nt_bias")) vg::gemm_f32_cases(pl); + if (sel("gemm_fp8a8_bias_nt_m16")) vg::gemm_q_bias_cases(pl); + if (sel("add_f32")) vg::add_f32_cases(pl); + if (sel("add_bf16")) vg::add_bf16_div_case(pl); + if (sel("mul_weight_f32")) vg::mul_weight_f32_cases(pl); + if (sel("silu_f32")) vg::silu_f32_cases(pl); + if (sel("rmsnorm_bf16")) vg::norm_f32_rows_cases(pl, false); + if (sel("layernorm_bf16")) vg::norm_f32_rows_cases(pl, true); + if (sel("timestep_embed_f32")) vg::timestep_f32_case(pl); + if (sel("randn_lanes_f32")) vg::randn_f32_case(pl); + if (sel("interleave2_bf16")) vg::interleave2_f32_case(pl); + if (sel("chan_affine_f32")) vg::chan_affine_cases(pl, "chan_affine_f32"); + if (sel("chan_affine_bf16")) vg::chan_affine_cases(pl, "chan_affine_bf16"); + if (sel("gate_add_bf16")) vg::gate_add_none_case(pl); + if (sel("conv1d_f32")) vg::conv1d_f32_cases(pl); + if (sel("conv_t1d_f32")) vg::conv_t1d_f32_cases(pl); + if (sel("conv1d_bf16")) vg::conv1d_bf16_clamp_case(pl); + if (sel("qk_norm_rope_bf16")) vg::qk_axial_cases(pl); + if (sel("attn_dense_h128_bf16")) { + vg::attn_long_case(pl, "attn_dense_h128_bf16", 128, 2, { 0, 3001 }); + vg::attn_long_case(pl, "attn_dense_h128_bf16", 128, 3, { 0, 1000, 2333 }); + } + if (sel("attn_dense_h64_bf16")) + vg::attn_long_case(pl, "attn_dense_h64_bf16", 64, 4, { 0, 1797, 3594, 5391, 7188 }); + /* Each row needs a case under its own name: a child runs per row and `sel` matches only that * name, so a case nested in another row's block would never run. */ if (sel("moe_gemm_w4a8")) { @@ -14723,6 +18671,33 @@ static void device_phase(const Plugin& pl) { wpa8i8_numeric(pl, bits, 2100, 34816, 5120, 17408); wpa8i8_numeric(pl, bits, 2048, 17408, 5120); wpa8i8_numeric(pl, bits, 2048, 5120, 17408); + if (bits == 4) { + /* An int4 W4A16 release imported with a u4 zero plane and no rotation: five groups + * a row, so each zero row ends in a pad nibble; then the delta net's qkv|z, the MLP's + * gate|up and down at a prefill chunk. */ + wpa8i8_numeric(pl, 4, 300, 400, 640, 0, 0, RAD_U4); + wpa8i8_numeric(pl, 4, 2048, 16384, 5120, 0, 0, RAD_U4); + wpa8i8_numeric(pl, 4, 2048, 34816, 5120, 0, 0, RAD_U4); + wpa8i8_numeric(pl, 4, 2048, 5120, 17408, 0, 0, RAD_U4); + } + } + + if (sel("gemm_w4a16_asym_nt_m64")) { + if (!g_case) std::printf("\nthe 4-bit asymmetric f16 GEMM, against the planes' meaning\n"); + /* z-lab's ParoQuant int4 (u8 zero, parts) and an int4 W4A16 release imported with a u4 + * zero plane: five groups a row (a pad nibble ends each zero row), then decode and verify + * rows at the 27B's shapes. */ + w5a16_numeric(pl, 8, 272, 640, 0, 0, 4); + w5a16_numeric(pl, 5, 400, 640, 144, 0, 4); + w5a16_numeric(pl, 40, 512, 2560, 128, 384, 4); + w5a16_numeric(pl, 8, 272, 640, 0, 0, 4, RAD_U4); + for (const int64_t M : { 1, 4, 16, 64 }) { + w5a16_numeric(pl, M, 16384, 5120, 0, 0, 4, RAD_U4); + w5a16_numeric(pl, M, 34816, 5120, 0, 0, 4, RAD_U4); + w5a16_numeric(pl, M, 5120, 17408, 0, 0, 4, RAD_U4); + w5a16_numeric(pl, M, 1024, 5120, 0, 0, 4, RAD_U4); + } + w5a16_numeric(pl, 150, 5120, 17408, 0, 0, 4, RAD_U4); } if (sel("gemm_w5a16_nt_m64")) { @@ -15068,11 +19043,25 @@ static void usage(void) { " default), every form compared with the first; `distinct` weight\n" " planes back the table, and fewer than the experts is a cache-resident\n" " floor rather than the real traffic.\n" - " --perflora M K N R S PATTERN [iters]: every lora_shrink row, then every\n" - " lora_expand row, at one shape; PATTERN lays the slots out: base, one,\n" - " half (even rows adapter 0, odd base), mix (row m on m %% S) or runs\n" - " (S contiguous runs). R4D_PERFLORA_A=fp8_e4m3 for a coded `a` (scale\n" - " every 128), R4D_PERFLORA_Y=f16|f32 for `y`. Each row's t and y are\n" + " --perfattn M HEADS [iters]: the head-128 dense attention over one M-row\n" + " sequence: attn_dense and attn_prefix_self without a prefix at\n" + " bf16 and int8 scores, bf16 and fp8 P.V, and quant_cols_fp8\n" + " on its v.\n" + " --perfvideo [iters] [section]: a video generator's GEMMs and attention\n" + " (TFLOP/s): trunk (the DiT's fp8 linears at a rank's width), decoder\n" + " (the video decoder's bf16 linears), f32 (the f32 GEMMs), conv (the\n" + " audio decoder's convolutions), mod (the fp8 modulation projection),\n" + " attn and attn64 (dense attention at 3K to 106K rows, and over the\n" + " decoder's tiles); every section without one.\n" + " --perfvsa [iters] [local]: vsa_select and attn_vsa at 1344 x 768 (38010\n" + " rows, 28 heads), sparsity 0.8 and 0, beside attn_dense over the same\n" + " rows. `local` gives q and k features of the row's grid position, so a\n" + " query tile selects its neighbourhood rather than random tiles.\n" + " --perflora M K N R S PATTERN [iters] [a=DT] [y=DT]: every lora_shrink row,\n" + " then every lora_expand row, at one shape; PATTERN lays the slots out:\n" + " base, one, half (even rows adapter 0, odd base), mix (row m on m %% S)\n" + " or runs (S contiguous runs). a=bf16 (default) or a=fp8_e4m3 (scale\n" + " every 128); y=bf16 (default), y=f16 or y=f32. Each row's t and y are\n" " compared with the first row's; --cold applies.\n" " --perfqsa CTX [M] [iters]: the QSA indexer at a real context length. It is\n" " the only decode op that grows with context, and at 200K it is\n" @@ -15099,9 +19088,17 @@ int main(int argc, char** argv) { int moe_it = 20; long long m16_m = 0, m16_e = 256, m16_k = 10, m16_d = 0; int m16_it = 20; + int video_it = 0; + long long attn_m = 0, attn_h = 0; + int attn_it = 5; + int vsa_it = 0; + bool vsa_local = false; + const char* video_sec = nullptr; long long lo_m = 0, lo_k = 0, lo_n = 0, lo_r = 0, lo_s = 0; const char* lo_pat = nullptr; int lo_it = 200; + bool lo_fp8 = false; + uint32_t lo_ydt = RAD_BF16; for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "--real")) { if (i + 5 >= argc) { usage(); return 2; } @@ -15173,12 +19170,41 @@ int main(int argc, char** argv) { lo_r = std::strtoll(argv[++i], nullptr, 0); lo_s = std::strtoll(argv[++i], nullptr, 0); lo_pat = argv[++i]; - if (i + 1 < argc && argv[i + 1][0] != 0x2d) lo_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] >= '0' && argv[i + 1][0] <= '9') + lo_it = (int)std::strtol(argv[++i], nullptr, 0); + while (i + 1 < argc && (!std::strncmp(argv[i + 1], "a=", 2) || + !std::strncmp(argv[i + 1], "y=", 2))) { + const char* v = argv[++i] + 2; + if (argv[i][0] == 'a' && !std::strcmp(v, "bf16")) lo_fp8 = false; + else if (argv[i][0] == 'a' && !std::strcmp(v, "fp8_e4m3")) lo_fp8 = true; + else if (argv[i][0] == 'y' && !std::strcmp(v, "bf16")) lo_ydt = RAD_BF16; + else if (argv[i][0] == 'y' && !std::strcmp(v, "f16")) lo_ydt = RAD_F16; + else if (argv[i][0] == 'y' && !std::strcmp(v, "f32")) lo_ydt = RAD_F32; + else { + std::fprintf(stderr, "--perflora: %s is not a=bf16|fp8_e4m3 or y=bf16|f16|f32\n", + argv[i]); + return 2; + } + } } else if (!std::strcmp(argv[i], "--perfhc")) { /* The gated residual's read at M rows. */ if (i + 1 >= argc) { usage(); return 2; } hc_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) hc_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfattn")) { + if (i + 2 >= argc) { usage(); return 2; } + attn_m = std::strtoll(argv[++i], nullptr, 0); + attn_h = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') attn_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfvideo")) { + video_it = 10; + if (i + 1 < argc && argv[i + 1][0] != '-') video_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') video_sec = argv[++i]; + } else if (!std::strcmp(argv[i], "--perfvsa")) { + vsa_it = 5; + if (i + 1 < argc && argv[i + 1][0] != '-' && std::strcmp(argv[i + 1], "local")) + vsa_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && !std::strcmp(argv[i + 1], "local")) { vsa_local = true; ++i; } } else if (!std::strcmp(argv[i], "--perfops")) { /* The elementwise ops at a decode shape: launch cost, not GEMM bandwidth. */ if (i + 2 >= argc) { usage(); return 2; } @@ -15203,6 +19229,35 @@ int main(int argc, char** argv) { Plugin pl; /* Timing modes run alone, without the catalogue. */ + if (attn_m > 0 && attn_h > 0) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + attn_perf(pl, attn_m, attn_h, attn_it); +#else + skip("attention timing", "built without HIP"); +#endif + return 0; + } + if (video_it) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + video_perf(pl, video_it, video_sec); + dfree_all(); +#else + skip("video generator timing", "built without HIP"); +#endif + return 0; + } + if (vsa_it) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + vsa_perf(pl, vsa_it, vsa_local); + dfree_all(); +#else + skip("video sparse attention timing", "built without HIP"); +#endif + return 0; + } if (hc_m) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP @@ -15216,7 +19271,7 @@ int main(int argc, char** argv) { if (lo_pat) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - lora_perf(pl, lo_m, lo_k, lo_n, lo_r, lo_s, lo_pat, lo_it); + lora_perf(pl, lo_m, lo_k, lo_n, lo_r, lo_s, lo_pat, lo_it, lo_fp8, lo_ydt); dfree_all(); #else skip("runtime LoRA timing", "built without HIP"); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 3e6db2ab..91505e41 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -315,10 +315,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); - /* Two rows serve the op, bf16 -> bf16 (a strided row copy) and bf16 -> f32, and the shims - * refuse any other pair, so another pair is declined here. */ + /* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16, + * and the shims refuse any other pair, so another pair is declined here. */ const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to"); - if (f != (uint32_t)RAD_BF16 || (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32)) + if (f != (uint32_t)RAD_BF16 || + (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16)) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) }; R4D_PICK(l); @@ -1061,6 +1062,29 @@ extern "C" int r4d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* gemm_nt_q_bias at fp8a8: gemm_nt_q's fp8 operands, a bf16 bias per output column, then y. The + * libref description matches it (ref_gemm_nt_q_bias_shape). */ +extern "C" int r4d_shape_gemm_nt_q_bias(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t N = pi(p, n_p, "N"); + const int64_t K = pi(p, n_p, "K"); + const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); + const char* q = r4d_pgets(p, n_p, "dtype"); + if (!q || std::strcmp(q, "fp8a8") || g != R4D_FP8_BLOCK || K <= 0 || N <= 0) + return RAD_E_UNSUPPORTED; + const int64_t kb = (K + g - 1) / g, nb = (N + g - 1) / g; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_F8E4M3, M, K), + opd((uint32_t)RAD_F32, M, kb), + opd((uint32_t)RAD_F8E4M3, N, K), + opd((uint32_t)RAD_BF16, nb, kb), + opd((uint32_t)RAD_BF16, N), + opd((uint32_t)RAD_BF16, M, N), + }; + R4D_PICK(l); +} + /* The same GEMM with the SwiGLU and the quantiser in its epilogue. `N` is the weight's rows, gate * then up, so the quantiser's outputs are N/2 wide (hence a schema of its own). */ extern "C" int r4d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, diff --git a/libr4d/r4d_video.hip b/libr4d/r4d_video.hip new file mode 100644 index 00000000..c1134cc6 --- /dev/null +++ b/libr4d/r4d_video.hip @@ -0,0 +1,654 @@ +// R4D -- the video generator's ops (docs/OPS.md, "Video generation"): a diffusion transformer's +// modulated RMS norm and its sampler step, the video decoder's patch unfold, the tiles it runs +// over, their stitch back into frames and their rotary positions; and its soundtrack decoder's +// alias-free SnakeBeta (docs/OPS.md, "Audio generation"). +// +// Each kernel rounds where its libref function does (libref/ref_gen.cpp, libref/ref_video.cpp, +// libref/ref_audio.cpp), under the library's -ffp-contract=off. The norm's sum of squares is a +// block sum here and a sequential one there, so a norm output can land one bf16 step apart, and +// sin and exp are the device's; every other value is the reference's arithmetic in its order. +// +// A request's latent geometry is a device operand (`geom`), never a parameter, so the decoder's +// kernels read it on the device and recompute an axis's tile layout from its length there. Rows +// past what the geometry writes are left alone. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" +#include "r4d_q8.h" + +#include +#include +#include + +namespace { + +constexpr int kT = 256; + +__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); } + +__device__ __forceinline__ void ld8(const uint16_t* p, float* f) { + const uint4 u = *(const uint4*)p; + f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y); + f[4] = bf16w_lo(u.z); f[5] = bf16w_hi(u.z); f[6] = bf16w_lo(u.w); f[7] = bf16w_hi(u.w); +} +__device__ __forceinline__ void st8(uint16_t* p, const float* f) { + uint4 u; + u.x = (uint32_t)f32_to_bf16(f[0]) | ((uint32_t)f32_to_bf16(f[1]) << 16); + u.y = (uint32_t)f32_to_bf16(f[2]) | ((uint32_t)f32_to_bf16(f[3]) << 16); + u.z = (uint32_t)f32_to_bf16(f[4]) | ((uint32_t)f32_to_bf16(f[5]) << 16); + u.w = (uint32_t)f32_to_bf16(f[6]) | ((uint32_t)f32_to_bf16(f[7]) << 16); + *(uint4*)p = u; +} + +// The entry that owns row r of a cu_seqlens partition: linear, because a step has three +// segments and a vocoder pass two channels. +__device__ __forceinline__ int seq_of(const int* cu, int n_seq, int r) { + int s = 0; + while (s + 1 < n_seq && cu[s + 1] <= r) ++s; + return s; +} + +// A sum over the 256 threads, every thread receiving it. `sh` is 8 floats of LDS. +__device__ __forceinline__ float block_sum(float v, float* sh) { + v = r4d_wave_sum(v); + __syncthreads(); + if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = v; + __syncthreads(); + float t = 0.0f; + #pragma unroll + for (int i = 0; i < kT / 32; ++i) t += sh[i]; + return t; +} + +// A value of a bf16 or f32 operand, and a store rounded to it. +__device__ __forceinline__ float ldv(const uint16_t* p, int64_t i) { return bf2f(p[i]); } +__device__ __forceinline__ float ldv(const float* p, int64_t i) { return p[i]; } +__device__ __forceinline__ void stv(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); } +__device__ __forceinline__ void stv(float* p, int64_t i, float v) { p[i] = v; } +__device__ __forceinline__ float rdv(const uint16_t*, float v) { return bfr(v); } +__device__ __forceinline__ float rdv(const float*, float v) { return v; } + +// ---------------------------------------------------------------------------- rms_mod +// The gated residual of the branch before, then the RMS norm with a gain and the entry's shift and +// scale, a workgroup a row: libref's rms_mod_row with the residual and the chain rounded to bf16. +// With QUANT the chain feeds quant_act_fp8 as ln_mod_quant_fp8 does (r4d_gen.hip): a 128-column +// group is sixteen consecutive lanes, so its amax is a half-wave reduction, and the codes are +// r4d_q8.h's. `s` is a column slice of the modulation table, [shift | scale] in each entry's row. +constexpr int kRmChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192 + +template +__global__ __launch_bounds__(kT) void rms_mod_kernel( + const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s, + const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x, + uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq, + float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) { + __shared__ float sh[kT / 32]; + const int r = blockIdx.x; + const int e = seq_of(cu, n_seq, r); + uint16_t* xr = x + (size_t)r * x_ld; + float v[kRmChunks][8]; + float ss = 0.0f; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + float f[8]; + ld8(xr + i, f); + if (GATED) { + float a[8], b[8]; + ld8(yd + (size_t)r * y_ld + i, a); + ld8(g + (size_t)e * g_ld + i, b); + #pragma unroll + for (int j = 0; j < 8; ++j) f[j] = f[j] + bfr(b[j] * a[j]); + st8(xr + i, f); + #pragma unroll + for (int j = 0; j < 8; ++j) f[j] = bfr(f[j]); + } + #pragma unroll + for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; } + } + } + const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps); + const uint16_t* sr = s + (size_t)e * s_ld; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i >= n) break; + float shf[8], scf[8], wf[8], o[8]; + ld8(sr + i, shf); + ld8(sr + n + i, scf); + ld8(w + i, wf); + #pragma unroll + for (int j = 0; j < 8; ++j) { + const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]); + o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]); + } + if (z) st8(z + (size_t)r * z_ld + i, o); + if (QUANT) { + float m = 0.0f; + #pragma unroll + for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j])); + m = fmaxf(m, r4d_xor_lane<8>(m)); + m = fmaxf(m, r4d_xor_lane<4>(m)); + m = fmaxf(m, r4d_xor_lane<2>(m)); + m = fmaxf(m, r4d_xor_lane<1>(m)); + const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc; + *(uint2*)(q + (size_t)r * q_ld + i) = + make_uint2(q8_pack4(o[0], o[1], o[2], o[3], inv), + q8_pack4(o[4], o[5], o[6], o[7], inv)); + } + } +} + +// ---------------------------------------------------------------------------- flow_x0_step +// One sampler step a lane value: the clean estimate d = x + (1 - t) v, then x' = r x + (1 - r) d +// with r = sigma_next / sigma, every product and sum one f32 rounding. +template +__global__ __launch_bounds__(kT) void flow_x0_kernel( + const TV* __restrict__ v, const float* __restrict__ t, const float* __restrict__ sg, + const float* __restrict__ sgn, float* __restrict__ x, int n, int v_ld, int x_ld, int64_t total) { + const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x; + if (id >= total) return; + const int64_t r = id / n; + const int c = (int)(id % n); + const float st = 1.0f - t[0]; + const float ra = sgn[0] / sg[0]; + const float omr = 1.0f - ra; + float* xp = x + r * x_ld + c; + const float xv = *xp; + const float d = xv + st * ldv(v, r * v_ld + c); + *xp = ra * xv + omr * d; +} + +// ---------------------------------------------------------------------------- patch_unfold +// The two parameter lists of the latent's statistics, f32 kernel arguments. +constexpr int kMaxChan = 64; +struct ChanList { float v[kMaxChan]; }; + +// A thread a voxel channel: y[(t, yy, xx), c] = f32(f32(x[patch, (c, sub)] * mul[c]) + add[c]). +__global__ __launch_bounds__(kT) void patch_unfold_kernel( + const float* __restrict__ x, const int* __restrict__ geom, float* __restrict__ y, ChanList mul, + ChanList add, int C, int pt, int ph, int pw, int x_ld, int y_ld, int64_t cap, int64_t x_rows) { + const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x; + const int F = geom[0], Hp = geom[1], Wp = geom[2]; + const int64_t Hv = (int64_t)Hp * ph, Wv = (int64_t)Wp * pw; + const int64_t rows = (int64_t)F * pt * Hv * Wv; + if (id >= cap || id >= rows * C || (int64_t)F * Hp * Wp > x_rows) return; + const int64_t r = id / C; + const int c = (int)(id % C); + const int64_t tt = r / (Hv * Wv), yy = (r / Wv) % Hv, xx = r % Wv; + const int64_t patch = ((tt / pt) * Hp + yy / ph) * Wp + xx / pw; + const int64_t sub = ((tt % pt) * ph + yy % ph) * pw + xx % pw; + y[r * y_ld + c] = x[patch * x_ld + c * pt * ph * pw + sub] * mul.v[c] + add.v[c]; +} + +// ---------------------------------------------------------------------------- the tile layout +// diffusers' _split_tiles in latent units (libref's split_tiles), in closed form: the tile count +// is the fewest whose overlaps are all at least `overlap`; the slack tile n - overlap (n - 1) - len +// goes to the overlaps one unit at a time from the first, so overlap i is overlap + q + (i < rr) +// with q, rr the slack's quotient and remainder by n - 1. A tile at least as long as the axis is +// one tile, a layout only when it is exactly as long. +struct Tiles { + int n = 0, q = 0, rr = 0, tile = 0, overlap = 0; + __device__ int ov(int i) const { return overlap + q + (i < rr ? 1 : 0); } + __device__ int start(int i) const { return i * (tile - overlap - q) - min(i, rr); } +}; + +__device__ __forceinline__ Tiles split_tiles(int len, int tile, int overlap) { + Tiles t; + t.tile = tile; + t.overlap = overlap; + if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return t; + if (tile >= len) { + t.n = len == tile ? 1 : 0; + return t; + } + int n = (len + tile - 1) / tile; + while (tile * n - overlap * (n - 1) < len) ++n; + const int rem = tile * n - overlap * (n - 1) - len; + t.n = n; + t.q = rem / (n - 1); + t.rr = rem % (n - 1); + return t; +} + +// ---------------------------------------------------------------------------- vtile_gather +// A workgroup a tile row: its voxel from x, a register token from `reg`, or zeros. +template +__global__ __launch_bounds__(kT) void vtile_gather_kernel( + const TX* __restrict__ x, const TR* __restrict__ reg, const int* __restrict__ geom, + TY* __restrict__ y, int n, int tile, int overlap, int frames, int period, int n_reg, int x_ld, + int reg_ld, int y_ld, int64_t x_rows) { + const int row = blockIdx.x; + const int H = geom[1], W = geom[2]; + if (geom[0] != frames || (int64_t)frames * H * W > x_rows) return; + const Tiles ty = split_tiles(H, tile, overlap), tx = split_tiles(W, tile, overlap); + if (ty.n == 0 || tx.n == 0 || row >= ty.n * tx.n * period) return; + const int k = row / period, p = row % period; + const int vox = frames * tile * tile; + TY* yr = y + (size_t)row * y_ld; + if (p < vox) { + const int t = p / (tile * tile), iy = (p / tile) % tile, ix = p % tile; + const int64_t src = ((int64_t)t * H + ty.start(k / tx.n) + iy) * W + tx.start(k % tx.n) + ix; + const TX* xr = x + src * x_ld; + for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, ldv(xr, c)); + } else if (p < vox + n_reg) { + const TR* rr = reg + (size_t)(p - vox) * reg_ld; + for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, ldv(rr, c)); + } else { + for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, 0.0f); + } +} + +// ---------------------------------------------------------------------------- vtile_stitch +// A thread a (pixel, colour) over every frame the chunk writes, so a pixel's reads of `prev` +// precede its writes of it in one thread: the kept frames, blended with the previous chunk's +// tail unless first, then the tail handed on (and written when last). The blends round to x's +// dtype and the tail is stored at prev's, as libref's ref_vtile_stitch. +struct PixList { float mean[3], stdv[3]; }; + +template +__global__ __launch_bounds__(kT) void vtile_stitch_kernel( + const TX* __restrict__ x, const int* __restrict__ geom, TP* __restrict__ prev, + uint8_t* __restrict__ y, PixList pl, int tile, int overlap, int S, int pt, int skip, int keep, + int blend, int period, int x_ld, int p_ld, int y_ld, int64_t cap, int64_t x_rows, + int64_t p_rows) { + const int frames = geom[0], H = geom[1], W = geom[2]; + const bool first = geom[3] != 0, last = geom[4] != 0; + const int64_t Hp = (int64_t)H * S, Wp = (int64_t)W * S, npx = Hp * Wp; + const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x; + if (id >= npx * 3 || 2 * skip + keep + blend > frames * pt || period < frames * tile * tile) + return; + const int64_t fout = keep + (last ? blend : 0); + if (fout * npx > cap) return; + const Tiles ty = split_tiles(H, tile, overlap), tx = split_tiles(W, tile, overlap); + if (ty.n == 0 || tx.n == 0 || (int64_t)ty.n * tx.n * period > x_rows || + (int64_t)blend * npx > p_rows) + return; + const int c = (int)(id / npx); + const int64_t px = id % npx; + const int Y = (int)(px / Wp), X = (int)(px % Wp); + // The owner tile of the pixel's row and column, and its offset in it. + int i = 0, j = 0; + while (i + 1 < ty.n && Y >= ty.start(i + 1) * S) ++i; + while (j + 1 < tx.n && X >= tx.start(j + 1) * S) ++j; + const int ly = Y - ty.start(i) * S, lx = X - tx.start(j) * S; + const int ev = i > 0 ? ty.ov(i - 1) * S : 0, eh = j > 0 ? tx.ov(j - 1) * S : 0; + auto rd = [&](float v) { return rdv(x, v); }; + auto wb = [&](int p, int e) { return rd((float)p / (float)e); }; + auto wa = [&](int p, int e) { return rd(1.0f - rd((float)p / (float)e)); }; + auto T = [&](int ti, int tj, int ay, int ax, int fc) { + const int64_t row = (int64_t)(ti * tx.n + tj) * period + + ((fc / pt) * tile + ay / S) * tile + ax / S; + const int col = ((c * pt + fc % pt) * S + ay % S) * S + ax % S; + return ldv(x, row * x_ld + col); + }; + auto stitch = [&](int fc) { + float v = T(i, j, ly, lx, fc); + if (ly < ev) { + const float up = T(i - 1, j, ly + tile * S - ev, lx, fc); + v = rd(rd(up * wa(ly, ev)) + rd(v * wb(ly, ev))); + } + if (lx < eh) { + const float left = T(i, j - 1, ly, lx + tile * S - eh, fc); + v = rd(rd(left * wa(lx, eh)) + rd(v * wb(lx, eh))); + } + return v; + }; + auto byte = [&](int f, float v) { + float p = v * pl.stdv[c] + pl.mean[c]; + p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p); + p = p * 255.0f; + float r = p != p ? 0.0f : rintf(p); + r = r < 0.0f ? 0.0f : (r > 255.0f ? 255.0f : r); + y[(f * npx + px) * y_ld + c] = (uint8_t)r; + }; + for (int k = 0; k < keep; ++k) { + float v = stitch(skip + k); + if (!first && k < blend) { + const float pv = ldv(prev, (k * npx + px) * p_ld + c); + v = rd(rd(pv * wa(k, blend)) + rd(v * wb(k, blend))); + } + byte(k, v); + } + for (int k = 0; k < blend; ++k) { + const float v = stitch(2 * skip + keep + k); + if (last) byte(keep + k, v); + stv(prev, (k * npx + px) * p_ld + c, v); + } +} + +// ---------------------------------------------------------------------------- grid_pos3 +// A thread a row: its token's three centred, scaled coordinates, or zeros past the tile's tokens. +__global__ __launch_bounds__(kT) void grid_pos3_kernel( + float* __restrict__ y, int T, int H, int W, int period, float scale, int M, int rs, int cs) { + const int m = blockIdx.x * kT + threadIdx.x; + if (m >= M) return; + const int k = m % period; + float p[3] = { 0.0f, 0.0f, 0.0f }; + if (k < T * H * W) { + const int cc[3] = { k / (H * W), (k / W) % H, k % W }, nn[3] = { T, H, W }; + #pragma unroll + for (int a = 0; a < 3; ++a) { + const float qq = ((float)cc[a] + 0.5f) / (float)nn[a]; + p[a] = scale * (2.0f * qq - 1.0f); + } + } + #pragma unroll + for (int a = 0; a < 3; ++a) y[(size_t)a * rs + (size_t)m * cs] = p[a]; +} + +// ---------------------------------------------------------------------------- snake_aa +// A thread an output (row, channel) of a sequence: the `k` activations its low-pass filter reads, +// each the upsampled value at that position through SnakeBeta, recomputed per output rather than +// staged (an activation is read by k / ratio outputs). Indices and orders are libref's +// ref_snake_aa: the replicate pad P = k / ratio - 1, the upsampler's crop, the low-pass's left pad +// k / 2 (one less for an even k), each sum in ascending tap. +constexpr int kMaxTaps = 32; + +__global__ __launch_bounds__(kT) void snake_aa_kernel( + const float* __restrict__ x, const float* __restrict__ al, const float* __restrict__ be, + const float* __restrict__ fu, const float* __restrict__ fd, const int* __restrict__ cu, + float* __restrict__ y, int n, int R, int k, int lg, int n_seq, int x_ld, int y_ld, + int64_t cap) { + __shared__ float sfu[kMaxTaps], sfd[kMaxTaps]; + if ((int)threadIdx.x < k) { + sfu[threadIdx.x] = fu[threadIdx.x]; + sfd[threadIdx.x] = fd[threadIdx.x]; + } + __syncthreads(); + const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x; + const int r0 = cu[0], r1 = cu[n_seq]; + if (id >= cap || id >= (int64_t)(r1 - r0) * n) return; + const int row = r0 + (int)(id / n), c = (int)(id % n); + const int e = seq_of(cu, n_seq, row); + const int s0 = cu[e], L = cu[e + 1] - s0, o = row - s0; + const int P = k / R - 1, crop = P * R + (k - R) / 2, pad = k / 2 - (k % 2 == 0 ? 1 : 0); + const float A = lg ? expf(al[c]) : al[c]; + const float B = lg ? expf(be[c]) : be[c]; + const float ib = 1.0f / (B + 1e-9f); + const int LR = L * R; + float acc = 0.0f; + for (int jt = 0; jt < k; ++jt) { + const int m = min(max(o * R + jt - pad, 0), LR - 1); + const int oo = crop + m; + const int i_lo = oo < k ? 0 : (oo - k) / R + 1; + const int i_hi = min(oo / R, L + 2 * P - 1); + float u = 0.0f; + for (int ii = i_lo; ii <= i_hi; ++ii) { + const int qrow = min(max(ii - P, 0), L - 1); + u += sfu[oo - ii * R] * x[(size_t)(s0 + qrow) * x_ld + c]; + } + u = (float)R * u; + const float sn = sinf(u * A); + acc += sfd[jt] * (u + ib * (sn * sn)); + } + y[(size_t)row * y_ld + c] = acc; +} + +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } + +inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); } + +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } +inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; } + +// A row-major operand's row count and pitch, with the pitch a multiple of eight elements so a row +// is read 16 bytes at a time. +inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* ld) { + if (!t || n <= 0 || (n & 7)) return false; + *ld = r4d_rows_pitch(t, n, rows); + return *ld >= 0 && !(*ld & 7) && !((uintptr_t)t->data & 15); +} + +// A space-separated list of floats kept in f32, as libref's parse_f32_list. +int parse_f32_list(const char* s, float* out, int max) { + int n = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (n == max) return max + 1; + out[n++] = (float)v; + s = end; + } + return n; +} + +} // namespace + +// ============================================================== the plugin ABI entry points + +// rms_mod (QUANT false: y, g, s, w, cu, x, z) and rms_mod_quant_fp8 (y, g, s, w, cu, x, q, scale, +// z), one shim. +static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { + const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2); + const RadTensor *w = r4d_opt(a, 3), *cu = r4d_opt(a, 4), *x = r4d_opt(a, 5); + const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr; + const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr; + const RadTensor* z = r4d_opt(a, quant ? 8 : 6); + if (!sc || !w || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); + const bool gated = r4d_geti_or(a, "gated", 0) != 0; + if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) || + (gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) || + (quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32))) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || (n & 7) || n > (long long)kT * 8 * kRmChunks || + (quant && (n % 128 || r4d_geti_or(a, "group", 0) != 128))) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0; + long long rq = 0, rqs = 0, ql = 0, qsl = 0; + if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) || + !r4d_contig(w) || ((uintptr_t)w->data & 15) || + (gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) || + (z && !rows8(z, n, &rz, &zl))) + return R4D_NO(RAD_E_STRIDE); + if (quant) { + ql = r4d_rows_pitch(q, n, &rq); + qsl = r4d_rows_pitch(qs, n / 128, &rqs); + if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE); + } + const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz; + if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n || + (quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows)) + return R4D_NO(RAD_E_SHAPE); + const float eps = (float)r4d_getf(a, "eps", 1e-6); +#define R4D_RMQ(G, Q) \ + hipLaunchKernelGGL((rms_mod_kernel), dim3((unsigned)rows), dim3(kT), 0, \ + (hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \ + G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \ + (const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \ + Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \ + z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \ + (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl) + if (quant) { + if (gated) R4D_RMQ(true, true); + else R4D_RMQ(false, true); + } else { + if (gated) R4D_RMQ(true, false); + else R4D_RMQ(false, false); + } +#undef R4D_RMQ + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_rms_mod(const RadArgs* a, RadStream s) { return rms_mod_launch(a, s, false); } + +extern "C" int r4d_rad_rms_mod_quant_fp8(const RadArgs* a, RadStream s) { + return rms_mod_launch(a, s, true); +} + +extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) { + const RadTensor *v = r4d_opt(a, 0), *t = r4d_opt(a, 1), *sg = r4d_opt(a, 2); + const RadTensor *sgn = r4d_opt(a, 3), *x = r4d_opt(a, 4); + if (!v || !t || !sg || !sgn || !x) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(t) || !is_f32(sg) || !is_f32(sgn) || (!is_f32(v) && !is_bf16(v))) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, rv = 0; + const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1; + const long long vl = n > 0 ? r4d_rows_pitch(v, n, &rv) : -1; + if (xl < 0 || vl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || rv < rx || r4d_numel(t) < 1 || r4d_numel(sg) < 1 || r4d_numel(sgn) < 1) + return R4D_NO(RAD_E_SHAPE); + const int64_t total = (int64_t)rx * n; +#define R4D_FX0(TV) \ + hipLaunchKernelGGL(flow_x0_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, \ + (const TV*)v->data, (const float*)t->data, (const float*)sg->data, \ + (const float*)sgn->data, (float*)x->data, (int)n, (int)vl, (int)xl, total) + if (is_f32(v)) R4D_FX0(float); + else R4D_FX0(uint16_t); +#undef R4D_FX0 + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_patch_unfold(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(y) || !is_i32(geom)) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), pt = r4d_geti_or(a, "pt", 0); + const long long ph = r4d_geti_or(a, "ph", 0), pw = r4d_geti_or(a, "pw", 0); + ChanList mul{}, add{}; + if (C <= 0 || C > kMaxChan || pt <= 0 || ph <= 0 || pw <= 0 || + parse_f32_list(r4d_gets(a, "mul"), mul.v, kMaxChan) != C || + parse_f32_list(r4d_gets(a, "add"), add.v, kMaxChan) != C || r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C * pt * ph * pw, &rx), yl = r4d_rows_pitch(y, C, &ry); + if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx <= 0) return R4D_NO(RAD_E_SHAPE); + const int64_t cap = (int64_t)ry * C; + hipLaunchKernelGGL(patch_unfold_kernel, dim3(blocks_for(cap)), dim3(kT), 0, (hipStream_t)s, + (const float*)x->data, (const int*)geom->data, (float*)y->data, mul, add, + (int)C, (int)pt, (int)ph, (int)pw, (int)xl, (int)yl, cap, (int64_t)rx); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vtile_gather(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *reg = r4d_opt(a, 1), *geom = r4d_opt(a, 2); + const RadTensor* y = r4d_opt(a, 3); + if (!x || !reg || !geom || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_f32(x) && !is_bf16(x)) || (!is_f32(reg) && !is_bf16(reg)) || + (!is_f32(y) && !is_bf16(y)) || !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), tile = r4d_geti_or(a, "tile", 0); + const long long overlap = r4d_geti_or(a, "overlap", 0), frames = r4d_geti_or(a, "frames", 0); + const long long period = r4d_geti_or(a, "period", 0), n_reg = r4d_geti_or(a, "n_reg", 0); + if (n <= 0 || tile <= 0 || frames <= 0 || n_reg < 0 || overlap < 0 || overlap >= tile || + period < frames * tile * tile + n_reg || r4d_numel(geom) < 3) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, rr = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, n, &rx), rl = r4d_rows_pitch(reg, n, &rr); + const long long yl = r4d_rows_pitch(y, n, &ry); + if (xl < 0 || rl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rr < n_reg) return R4D_NO(RAD_E_SHAPE); +#define R4D_VTG(TX, TR, TY) \ + hipLaunchKernelGGL((vtile_gather_kernel), dim3((unsigned)ry), dim3(kT), 0, \ + (hipStream_t)s, (const TX*)x->data, (const TR*)reg->data, \ + (const int*)geom->data, (TY*)y->data, (int)n, (int)tile, (int)overlap, \ + (int)frames, (int)period, (int)n_reg, (int)xl, (int)rl, (int)yl, \ + (int64_t)rx) +#define R4D_VTG_Y(TX, TR) \ + do { if (is_f32(y)) R4D_VTG(TX, TR, float); else R4D_VTG(TX, TR, uint16_t); } while (0) +#define R4D_VTG_R(TX) \ + do { if (is_f32(reg)) R4D_VTG_Y(TX, float); else R4D_VTG_Y(TX, uint16_t); } while (0) + if (is_f32(x)) R4D_VTG_R(float); + else R4D_VTG_R(uint16_t); +#undef R4D_VTG_R +#undef R4D_VTG_Y +#undef R4D_VTG + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vtile_stitch(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *prev = r4d_opt(a, 2); + const RadTensor* y = r4d_opt(a, 3); + if (!x || !geom || !prev || !y) return R4D_NO(RAD_E_INVAL); + if ((!is_f32(x) && !is_bf16(x)) || (!is_f32(prev) && !is_bf16(prev)) || y->dtype != RAD_U8 || + !is_i32(geom)) + return R4D_NO(RAD_E_DTYPE); + const long long tile = r4d_geti_or(a, "tile", 0), overlap = r4d_geti_or(a, "overlap", 0); + const long long S = r4d_geti_or(a, "scale", 0), pt = r4d_geti_or(a, "pt", 0); + const long long skip = r4d_geti_or(a, "skip", 0), keep = r4d_geti_or(a, "keep", 0); + const long long blend = r4d_geti_or(a, "blend", 0), period = r4d_geti_or(a, "period", 0); + PixList pl{}; + if (tile <= 0 || overlap < 0 || overlap >= tile || S <= 0 || pt <= 0 || skip < 0 || + keep <= 0 || blend < 0 || blend > keep || period <= 0 || + parse_f32_list(r4d_gets(a, "mean"), pl.mean, 3) != 3 || + parse_f32_list(r4d_gets(a, "std"), pl.stdv, 3) != 3 || r4d_numel(geom) < 5) + return R4D_NO(RAD_E_SHAPE); + const long long cols = 3 * pt * S * S; + long long rx = 0, rp = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, cols, &rx), pl_ld = r4d_rows_pitch(prev, 3, &rp); + const long long yl = r4d_rows_pitch(y, 3, &ry); + if (xl < 0 || pl_ld < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < period) return R4D_NO(RAD_E_SHAPE); + // A thread a (pixel, colour) of the largest frame the output holds; the kernel bounds the rest + // by the device geometry. + const int64_t npx_cap = ry / keep, total = npx_cap * 3; +#define R4D_VTS(TX, TP) \ + hipLaunchKernelGGL((vtile_stitch_kernel), dim3(blocks_for(total)), dim3(kT), 0, \ + (hipStream_t)s, (const TX*)x->data, (const int*)geom->data, \ + (TP*)prev->data, (uint8_t*)y->data, pl, (int)tile, (int)overlap, (int)S, \ + (int)pt, (int)skip, (int)keep, (int)blend, (int)period, (int)xl, \ + (int)pl_ld, (int)yl, (int64_t)ry, (int64_t)rx, (int64_t)rp) +#define R4D_VTS_P(TX) \ + do { if (is_f32(prev)) R4D_VTS(TX, float); else R4D_VTS(TX, uint16_t); } while (0) + if (is_f32(x)) R4D_VTS_P(float); + else R4D_VTS_P(uint16_t); +#undef R4D_VTS_P +#undef R4D_VTS + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_grid_pos3(const RadArgs* a, RadStream s) { + const RadTensor* y = r4d_opt(a, 0); + if (!y) return R4D_NO(RAD_E_INVAL); + if (!is_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long T = r4d_geti_or(a, "T", 0), H = r4d_geti_or(a, "H", 0); + const long long W = r4d_geti_or(a, "W", 0), period = r4d_geti_or(a, "period", 0); + if (T <= 0 || H <= 0 || W <= 0 || period < T * H * W || y->rank != 2 || y->shape[0] < 3) + return R4D_NO(RAD_E_SHAPE); + const long long M = y->shape[1]; + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(grid_pos3_kernel, dim3(blocks_for(M)), dim3(kT), 0, (hipStream_t)s, + (float*)y->data, (int)T, (int)H, (int)W, (int)period, + (float)r4d_getf(a, "scale", 1.0), (int)M, (int)y->stride[0], + (int)y->stride[1]); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_snake_aa(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *al = r4d_opt(a, 1), *be = r4d_opt(a, 2); + const RadTensor *fu = r4d_opt(a, 3), *fd = r4d_opt(a, 4), *cu = r4d_opt(a, 5); + const RadTensor* y = r4d_opt(a, 6); + if (!x || !al || !be || !fu || !fd || !cu || !y) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(y) || !is_f32(al) || !is_f32(be) || !is_f32(fu) || !is_f32(fd) || + !is_i32(cu)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), R = r4d_geti_or(a, "ratio", 0); + const long long k = r4d_geti_or(a, "k", 0), lg = r4d_geti_or(a, "log", 0); + if (n <= 0 || R <= 0 || k < R || k > kMaxTaps || lg < 0 || lg > 1 || r4d_numel(al) < n || + r4d_numel(be) < n || r4d_numel(fu) < k || r4d_numel(fd) < k) + return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(al) || !r4d_contig(be) || !r4d_contig(fu) || !r4d_contig(fd) || !r4d_contig(cu)) + return R4D_NO(RAD_E_STRIDE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n_seq <= 0 || ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE); + const int64_t cap = (int64_t)ry * n; + hipLaunchKernelGGL(snake_aa_kernel, dim3(blocks_for(cap)), dim3(kT), 0, (hipStream_t)s, + (const float*)x->data, (const float*)al->data, (const float*)be->data, + (const float*)fu->data, (const float*)fd->data, (const int*)cu->data, + (float*)y->data, (int)n, (int)R, (int)k, (int)lg, (int)n_seq, (int)xl, + (int)yl, cap); + return st_of(hipGetLastError()); +} diff --git a/libr4d/r4d_vit_bf16.hip b/libr4d/r4d_vit_bf16.hip index 54ac40c1..e4498165 100644 --- a/libr4d/r4d_vit_bf16.hip +++ b/libr4d/r4d_vit_bf16.hip @@ -6,9 +6,10 @@ // activation and after the residual, as the unfused chain would. // // Not gemm_bf16_nt_tiled: that kernel needs K in whole 64-element tiles (a tower MLP's 4304 is 16 -// past one) and has no bias. This uses the same block shape (eight waves over an LDS-staged 64-deep -// K tile, next tile prefetched into registers) with a zero-staged K tail, no split-K, and the -// epilogue in the store. Meant for tall activations (thousands of patches). +// past one) and has no bias. Two kernels, both with a zero-staged K tail, no split-K, and the +// epilogue in the store: a 64 x 64 tile with both operands staged through LDS for small grids, and +// for large ones (tall activations, thousands of patches) a 128 x 128 tile that reads the weight +// straight into registers and stages only the activation. #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -50,26 +51,30 @@ __device__ __forceinline__ float ldw(const void* p, uint32_t i) { // ---------------------------------------------------------------------------- layernorm // ref_layernorm: y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, two passes (mean, then // squared deviations); one-pass E[x^2] - E[x]^2 cancels badly when the mean is large relative to -// the spread. One block per row. -template +// the spread. One block per row. `TX` is the row's element: bf16, or f32 for a residual stream kept +// in f32 (a video decoder's), read as it is; the output is bf16 either way. +__device__ __forceinline__ float ldx(const unsigned short* p, uint32_t i) { return bf2f(p[i]); } +__device__ __forceinline__ float ldx(const float* p, uint32_t i) { return p[i]; } + +template __global__ __launch_bounds__(kThr) void layernorm_kernel( - const unsigned short* __restrict__ x, const void* __restrict__ w, const void* __restrict__ b, + const TX* __restrict__ x, const void* __restrict__ w, const void* __restrict__ b, unsigned short* __restrict__ y, uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) { __shared__ float lds[kThr / 32]; const uint32_t m = blockIdx.x; - const unsigned short* __restrict__ xr = x + (size_t)m * x_ld; + const TX* __restrict__ xr = x + (size_t)m * x_ld; unsigned short* __restrict__ yr = y + (size_t)m * y_ld; float s = 0.0f; - for (uint32_t i = threadIdx.x; i < n; i += kThr) s += bf2f(xr[i]); + for (uint32_t i = threadIdx.x; i < n; i += kThr) s += ldx(xr, i); const float mean = block_sum(s, lds) / (float)n; float ss = 0.0f; for (uint32_t i = threadIdx.x; i < n; i += kThr) { - const float d = bf2f(xr[i]) - mean; + const float d = ldx(xr, i) - mean; ss += d * d; } const float r = rsqrtf(block_sum(ss, lds) / (float)n + eps); for (uint32_t i = threadIdx.x; i < n; i += kThr) { - float v = (bf2f(xr[i]) - mean) * r * ldw(w, i); + float v = (ldx(xr, i) - mean) * r * ldw(w, i); if (b) v += ldw(b, i); yr[i] = f32_to_bf16(v); } @@ -170,7 +175,8 @@ __global__ __launch_bounds__(kThr) void grid_embed_aa_kernel( #define VB_PITCH (VB_BK + 8) // 144-byte LDS rows, as in gemm_bf16_nt_tiled (bank spread) // TM x TN WMMA tiles per wave, eight waves as 2 x 4: BM = 2*TM*16, BN = 4*TN*16. ACT: 0 none, -// 1 exact GELU, 2 tanh GELU. +// 1 exact GELU, 2 tanh GELU. Serves grids under 32 blocks of 128 x 128 at TM 2, TN 1 (64 x 64); +// larger grids take vit_gemm_wa_kernel below. template __global__ __launch_bounds__(256) void vit_gemm_kernel( const unsigned short* __restrict__ A, unsigned lda, const unsigned short* __restrict__ W, @@ -282,6 +288,236 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( } } + +// ---------------------------------------------------------------------------- gemm_nt_bias, large grids +// +// 128 weight rows x 128 activation rows a block, eight waves as kVWW (weight) x kVWA +// (activation), a wave kVTW weight tiles x kVTA activation tiles. The weight is the WMMA A operand, +// read from global straight into registers; the activation is the B operand, staged through LDS +// and read by the four waves that share its rows. A lane's accumulator is then eight consecutive +// weight rows of one activation row, so the bias is eight consecutive values and the store (with +// its residual read) is one 16-byte access. +// +// Staging both operands through LDS with a 4 x 2 tile a wave (the kernel above at 128 x 128, which +// this replaces) costs 384 bytes of fragment reads and 128 of stores per bf16 WMMA: all of gfx1201's +// LDS bandwidth, 64 bytes a clock per CU against one bf16 WMMA every 16 clocks per SIMD +// (libr4d/isa/wmmamix.hip). Here it is 256 and 64, and the weight's 128 bytes come through the +// vector cache. +// +// K is relabelled inside a staged tile so that a lane's operand bytes are contiguous: lane half h, +// k step s and element e hold k = 32h + 8s + e of the tile, for both operands alike. That is a +// permutation of K applied to A and B together, so the product is the same sum; its rounding inside +// the WMMA differs from the canonical order in the last bit (rel_l2 ~4e-5 against it, well inside a +// bf16 output). It makes a lane's weight fragments for the tile one 64-byte run of its row, four +// 16-byte loads, and its activation fragment one 16-byte LDS read. +// +// A weight row stride that is a multiple of 8 KiB (K = 4096 or 8192) puts all sixteen rows a +// fragment load touches in one vector-cache set, and every load refetches them. The block's first K +// tile is therefore rotated by its grid position, which spreads the blocks resident at once over +// the K columns: +5% at K 8192, -1% at K 2048 (noise-level), the summation order changing with it. +// The real fix is a weight layout without the stride (a padded row reached 139 TFLOP/s at K 8192 +// against 115 here), which needs a layout hook. +// +// Measured at the video decoder's shapes (M 25158, 300 W; the kernel above 93-98 TFLOP/s): this +// tile 133-137 at K 2048, 115 at K 8192. Rejected: 2 x 4 waves of 4 weight x 2 activation tiles +// (spills, -20%); 2 x 2 waves of 4 x 4 tiles at a 32-wide K tile (-22%: half-line weight loads, +// twice the barriers); 4 x 1 waves of 2 x 8 at a 32-wide K tile (-8%); eight waves a SIMD at a +// 32-wide K tile (-4%). kVGroup 1, 2, 4 and 16 are within 2% of 8 except at N 16384 (-9, -5, -3 +// and -3%); 32 is 5-15% slower. The kernel above with the grouped raster: +3% at N 16384, -2% at +// K 8192. A uniform block base and 32-bit lane offsets for the loads: neutral. The weight through +// raw buffer loads: +1% at K 2048 and +4% at K 8192, but the same loads cost the fp8 prefill tile +// 20%, so neither tile uses them. The weight's loads nontemporal: -25..-50%. +constexpr uint32_t kVTW = 2, kVTA = 4, kVWW = 4, kVWA = 2; +constexpr uint32_t kVBN = kVWW * kVTW * 16, kVBM = kVWA * kVTA * 16; // weight x activation rows +constexpr uint32_t kVThreads = kVWW * kVWA * 32; +constexpr uint32_t kVFK = 64; // K elements a staged tile +constexpr uint32_t kVPB = kVFK * 2 + 16; // LDS row pitch, bytes +constexpr uint32_t kVCPR = kVFK * 2 / 16; // 16-byte chunks a row +constexpr uint32_t kVSPT = kVBM * kVCPR / kVThreads; // chunks a thread stages +constexpr uint32_t kVWC = kVFK / 16; // a lane's weight chunks a tile +// Activation bands per raster group; see gemm_8a8_prefill_kernel (r4d_gemm_fp8a8.hip). +constexpr uint32_t kVGroup = 8; +static_assert(kVBM * kVCPR % kVThreads == 0, "whole chunks a thread"); + +// The store's three roundings, libref's order: the biased product, the activation, the residual. +template +__device__ __forceinline__ unsigned short vit_finish(float acc, float bv, unsigned short r) { + unsigned short t = f32_to_bf16(acc + bv); + if constexpr (ACT == 1) t = f32_to_bf16(gelu_erf(bf2f(t))); + if constexpr (ACT == 2) t = f32_to_bf16(gelu_tanh(bf2f(t))); + if constexpr (RES) t = f32_to_bf16(bf2f(r) + bf2f(t)); + return t; +} + +/* `vec` (host-checked): C, R and the bias take 16-byte accesses at every eight-column boundary. */ +template +__global__ __launch_bounds__(kVThreads) R4D_WAVES(6) void vit_gemm_wa_kernel( + const unsigned short* __restrict__ A, unsigned lda, const unsigned short* __restrict__ W, + unsigned ldw_, const void* __restrict__ bias, const unsigned short* R, unsigned ldr, + unsigned short* C, unsigned ldc, int M, int K, int N, unsigned vec) { + typedef r4d_u32x4 U4; + // Double-buffered: one barrier a staged tile, which publishes it. + __shared__ __attribute__((aligned(16))) unsigned char s_a[2][kVBM * kVPB]; + + const uint32_t tid = threadIdx.x, lane = tid & 31u; + // Uniform per wave, and through readfirstlane known so, so what derives from it stays scalar. + const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5); + const uint32_t ww = wave % kVWW, wa = wave / kVWW; + + // Grouped raster, as in gemm_8a8_prefill_kernel: kVGroup activation bands sweep N together. + uint32_t bm = blockIdx.x, bn = blockIdx.y; + if (gridDim.x > kVGroup) { + const uint32_t per = kVGroup * gridDim.y; + const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t first = (lin / per) * kVGroup, r = lin % per; + const uint32_t gm = min(gridDim.x - first, kVGroup); + bm = first + r % gm; + bn = r / gm; + } + const uint32_t m0 = bm * kVBM, n0 = bn * kVBN; + + // Staging: eight consecutive threads cover a row's 128 bytes, so a load is whole cachelines. + // Rows past M re-read row M-1; nothing past M is stored. + const unsigned char* asrc[kVSPT]; + uint32_t adst[kVSPT], aoff[kVSPT]; +#pragma unroll + for (uint32_t i = 0; i < kVSPT; ++i) { + const uint32_t c = tid + kVThreads * i, r = c / kVCPR, ch = c % kVCPR; + asrc[i] = (const unsigned char*)(A + (size_t)min(m0 + r, (uint32_t)M - 1u) * lda); + aoff[i] = ch * 8u; // elements into the tile + adst[i] = r * kVPB + ch * 16u; + } + // Weight: lane row (l & 15) of each tile, elements [32h, 32h + 32) of the staged tile. Rows past + // N re-read row N-1; nothing past N is stored. + const unsigned short* wsrc[kVTW]; +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) + wsrc[i] = W + (size_t)min(n0 + (ww * kVTW + i) * 16u + (lane & 15u), (uint32_t)N - 1u) * ldw_ + + (lane >> 4) * (kVFK / 2u); + // This lane's activation fragment row and half in the staged tile. + const uint32_t frow = (wa * kVTA * 16u + (lane & 15u)) * kVPB + (lane >> 4) * kVFK; + + v8f acc[kVTW][kVTA]; +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kVTA; ++j) acc[i][j] = (v8f)(0.f); + + /* Four k steps of one staged tile: the weight from `cur`, the activation from LDS. */ + auto mma_tile = [&](const unsigned char* sa, const U4 (&cur)[kVTW][kVWC]) { +#pragma unroll + for (uint32_t s = 0; s < kVWC; ++s) { + v8bf bfr[kVTA]; +#pragma unroll + for (uint32_t j = 0; j < kVTA; ++j) + bfr[j] = __builtin_bit_cast(v8bf, *(const U4*)(sa + frow + j * 16u * kVPB + s * 16u)); +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) { + const v8bf af = __builtin_bit_cast(v8bf, cur[i][s]); +#pragma unroll + for (uint32_t j = 0; j < kVTA; ++j) acc[i][j] = mma(af, bfr[j], acc[i][j]); + } + } + }; + + // Whole tiles in a rotated order, then the K tail (K is a multiple of 8, so a 16-byte chunk + // is wholly inside or wholly past K) staged with zeros. + const uint32_t nfull = (uint32_t)K / kVFK; + if (nfull > 0u) { + const uint32_t t0 = (bm + bn) % nfull; + auto kt = [&](uint32_t t) { const uint32_t u = t0 + t; return (u >= nfull ? u - nfull : u) * kVFK; }; + U4 pa[kVSPT], w0[kVTW][kVWC], w1[kVTW][kVWC]; + /* Every load is issued unconditionally (the last tile's prefetch re-reads the last tile), + * so the loop has no branch and its waits count exactly. */ + auto load = [&](uint32_t k0, U4 (&w)[kVTW][kVWC]) { +#pragma unroll + for (uint32_t i = 0; i < kVSPT; ++i) pa[i] = *(const U4*)(asrc[i] + (size_t)(k0 + aoff[i]) * 2u); +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) +#pragma unroll + for (uint32_t c = 0; c < kVWC; ++c) w[i][c] = *(const U4*)(wsrc[i] + k0 + c * 8u); + }; + auto tile = [&](uint32_t t, uint32_t buf, U4 (&cur)[kVTW][kVWC], U4 (&nxt)[kVTW][kVWC]) { +#pragma unroll + for (uint32_t i = 0; i < kVSPT; ++i) *(U4*)(s_a[buf] + adst[i]) = pa[i]; + lds_barrier(); + load(kt(min(t + 1u, nfull - 1u)), nxt); + mma_tile(s_a[buf], cur); + }; + load(kt(0), w0); + uint32_t t = 0; + for (; t + 1u < nfull; t += 2u) { + tile(t, 0, w0, w1); + tile(t + 1u, 1, w1, w0); + } + if (t < nfull) tile(t, 0, w0, w1); + } + if ((uint32_t)K % kVFK) { + // The buffer the last whole tile did not use, last read two tiles back. + unsigned char* const sa = s_a[nfull % 2u]; + const uint32_t k0 = nfull * kVFK; + const U4 zero = (U4)(0u); +#pragma unroll + for (uint32_t i = 0; i < kVSPT; ++i) + *(U4*)(sa + adst[i]) = k0 + aoff[i] < (uint32_t)K + ? *(const U4*)(asrc[i] + (size_t)(k0 + aoff[i]) * 2u) : zero; + U4 w[kVTW][kVWC]; +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) +#pragma unroll + for (uint32_t c = 0; c < kVWC; ++c) + w[i][c] = k0 + (lane >> 4) * (kVFK / 2u) + c * 8u < (uint32_t)K + ? *(const U4*)(wsrc[i] + k0 + c * 8u) : zero; + lds_barrier(); + mma_tile(sa, w); + } + + // D is [weight row][activation row]: eight consecutive columns of one C row a lane a tile. + // The residual is read by the thread that stores the same element, so R may alias C. +#pragma unroll + for (uint32_t i = 0; i < kVTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kVTA; ++j) { + const uint32_t m = m0 + (wa * kVTA + j) * 16u + (lane & 15u); + const uint32_t n = n0 + (ww * kVTW + i) * 16u + (lane >> 4) * 8u; + if (m >= (uint32_t)M) continue; + const v8f v = acc[i][j]; + if (vec && n + 8u <= (uint32_t)N) { + float bv[8]; + if constexpr (BF32) { + const float4 b0 = *(const float4*)((const float*)bias + n); + const float4 b1 = *(const float4*)((const float*)bias + n + 4); + bv[0] = b0.x; bv[1] = b0.y; bv[2] = b0.z; bv[3] = b0.w; + bv[4] = b1.x; bv[5] = b1.y; bv[6] = b1.z; bv[7] = b1.w; + } else { + const uint4 b = *(const uint4*)((const unsigned short*)bias + n); + const uint32_t d[4] = { b.x, b.y, b.z, b.w }; +#pragma unroll + for (uint32_t e = 0; e < 8; ++e) bv[e] = bf2f((unsigned short)(d[e / 2] >> (16 * (e % 2)))); + } + uint32_t rr[4] = { 0u, 0u, 0u, 0u }; + if constexpr (RES) { + const uint4 r4 = *(const uint4*)(R + (size_t)m * ldr + n); + rr[0] = r4.x; rr[1] = r4.y; rr[2] = r4.z; rr[3] = r4.w; + } + uint32_t o[4]; +#pragma unroll + for (uint32_t e = 0; e < 8; e += 2) + o[e / 2] = (uint32_t)vit_finish(v[e], bv[e], (unsigned short)rr[e / 2]) | + ((uint32_t)vit_finish(v[e + 1], bv[e + 1], + (unsigned short)(rr[e / 2] >> 16)) << 16); + *(uint4*)(C + (size_t)m * ldc + n) = make_uint4(o[0], o[1], o[2], o[3]); + } else { +#pragma unroll + for (uint32_t e = 0; e < 8; ++e) { + if (n + e >= (uint32_t)N) continue; + const unsigned short r = RES ? R[(size_t)m * ldr + n + e] : (unsigned short)0; + C[(size_t)m * ldc + n + e] = vit_finish(v[e], ldw(bias, n + e), r); + } + } + } +} + } // namespace // ============================================================== the plugin ABI entry points @@ -295,7 +531,9 @@ extern "C" int r4d_rad_layernorm(const RadArgs* a, RadStream stream) { const RadTensor* b = r4d_opt(a, LN_B); const RadTensor* y = r4d_opt(a, LN_Y); if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); - if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + /* The row bf16 or f32, the output bf16. */ + if ((x->dtype != RAD_BF16 && x->dtype != RAD_F32) || y->dtype != RAD_BF16) + return R4D_NO(RAD_E_DTYPE); /* Gain and bias share one dtype, f32 or bf16. */ if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (b && b->dtype != w->dtype) return R4D_NO(RAD_E_DTYPE); @@ -309,14 +547,17 @@ extern "C" int r4d_rad_layernorm(const RadArgs* a, RadStream stream) { if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-5); - if (w->dtype == RAD_F32) - return R4D_EMIT(stream, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, - (const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b), - (unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld, - (uint32_t)y_ld); - return R4D_EMIT(stream, layernorm_kernel, dim3((uint32_t)M), dim3(kThr), 0, - (const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b), - (unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld); +#define R4D_LN(WF, TX) \ + return R4D_EMIT(stream, (layernorm_kernel), dim3((uint32_t)M), dim3(kThr), 0, \ + (const TX*)r4d_p(x), r4d_p(w), r4d_p(b), (unsigned short*)r4d_wp(y), \ + (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld) + if (x->dtype == RAD_F32) { + if (w->dtype == RAD_F32) R4D_LN(true, float); + R4D_LN(false, float); + } + if (w->dtype == RAD_F32) R4D_LN(true, unsigned short); + R4D_LN(false, unsigned short); +#undef R4D_LN } /* ------------------------------------------------------------------ grid_embed */ @@ -421,32 +662,53 @@ extern "C" int r4d_rad_gemm_nt_bias(const RadArgs* a, RadStream stream) { } const bool res = R != nullptr, bf32 = B->dtype == RAD_F32; - /* The large tile once its grid reaches 32 workgroups, as gemm_bf16_nt_tiled chooses. */ + /* The 128 x 128 kernel once its grid reaches 32 workgroups, as gemm_bf16_nt_tiled chooses; + * below that the 64 x 64 tile, whose four times the blocks fill more of the card. */ const long long g128 = ((N + 127) / 128) * ((M + 127) / 128); const bool big = g128 >= 32; - const int bt = big ? 128 : 64; - const dim3 grid((unsigned)((N + bt - 1) / bt), (unsigned)((M + bt - 1) / bt)), block(256); auto Ap = (const unsigned short*)r4d_p(A); auto Wp = (const unsigned short*)r4d_p(W); auto Rp = (const unsigned short*)r4d_p(R); auto Cp = (unsigned short*)r4d_wp(Y); const void* Bp = r4d_p(B); -#define VB_L(TM, TN, AC, RS, BF) \ - return R4D_EMIT(stream, (vit_gemm_kernel), grid, block, 0, Ap, \ + if (big) { + /* Sixteen-byte stores, residual reads and bias reads at every eight-column boundary. */ + const unsigned vec = (ldc % 8) == 0 && r4d_aligned(Cp, 16) && r4d_aligned(Bp, 16) && + (!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16))); + const dim3 grid((unsigned)((M + kVBM - 1) / kVBM), (unsigned)((N + kVBN - 1) / kVBN)); +#define VB_L(AC, RS, BF) \ + return R4D_EMIT(stream, (vit_gemm_wa_kernel), grid, dim3(kVThreads), 0, Ap, \ + (unsigned)lda, Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, \ + (int)M, (int)K, (int)N, vec) +#define VB_ACT(RS, BF) \ + do { \ + if (act == 1) VB_L(1, RS, BF); \ + if (act == 2) VB_L(2, RS, BF); \ + VB_L(0, RS, BF); \ + } while (0) +#define VB_RES(BF) \ + do { if (res) VB_ACT(true, BF); VB_ACT(false, BF); } while (0) + if (bf32) VB_RES(true); + VB_RES(false); +#undef VB_RES +#undef VB_ACT +#undef VB_L + } + const dim3 grid((unsigned)((N + 63) / 64), (unsigned)((M + 63) / 64)), block(256); +#define VB_L(AC, RS, BF) \ + return R4D_EMIT(stream, (vit_gemm_kernel<2, 1, AC, RS, BF>), grid, block, 0, Ap, \ (unsigned)lda, Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, \ - (int)M, (int)K, \ - (int)N) -#define VB_ACT(TM, TN, RS, BF) \ + (int)M, (int)K, (int)N) +#define VB_ACT(RS, BF) \ do { \ - if (act == 1) VB_L(TM, TN, 1, RS, BF); \ - if (act == 2) VB_L(TM, TN, 2, RS, BF); \ - VB_L(TM, TN, 0, RS, BF); \ + if (act == 1) VB_L(1, RS, BF); \ + if (act == 2) VB_L(2, RS, BF); \ + VB_L(0, RS, BF); \ } while (0) -#define VB_RES(TM, TN, BF) \ - do { if (res) VB_ACT(TM, TN, true, BF); VB_ACT(TM, TN, false, BF); } while (0) - if (big) { if (bf32) VB_RES(4, 2, true); VB_RES(4, 2, false); } - if (bf32) VB_RES(2, 1, true); - VB_RES(2, 1, false); +#define VB_RES(BF) \ + do { if (res) VB_ACT(true, BF); VB_ACT(false, BF); } while (0) + if (bf32) VB_RES(true); + VB_RES(false); #undef VB_RES #undef VB_ACT #undef VB_L diff --git a/libr4d/r4d_vsa.hip b/libr4d/r4d_vsa.hip new file mode 100644 index 00000000..75ea1bc4 --- /dev/null +++ b/libr4d/r4d_vsa.hip @@ -0,0 +1,1197 @@ +// R4D video sparse attention (docs/OPS.md, "Video generation"): `vsa_select`, the per-head tile +// selection of a distilled video transformer, and `attn_vsa`, the block-sparse attention that reads +// it, both at head_dim 128 over 4 x 4 x 4 tiles. +// +// The packed sequence is dense segments (text, a soundtrack's channels) and one video grid of +// F x Hp x Wp rows. Each dense segment is cut on its own into chunks of 64 rows, the prefix tiles; +// the grid into 4 x 4 x 4 boxes, the video tiles. A tile's rows are found from its number in +// closed form (vsa_tile, vsa_row), so neither op permutes rows. The geometry is a device operand, +// read by every workgroup: a video grid that does not fit the operand's rows has no tiles, and the +// tile count is cut to the selection's capacity, so no value of `segs` or `geom` reaches outside +// an operand. +// +// vsa_select, two steps a group of heads (the scratch holds the means of as many heads as fit): +// pool the f32 means of q, k (and v) over each tile, summed in the tile's (t, h, w) raster; +// select a workgroup a few query tiles: their q means, the f32 scores against every tile's k +// mean (each a sequential 128-term dot product, so a score is the reference's to the +// bit), the top k video tiles by a bisection on the scores' 32 bits with ties to the +// lower tile, written ascending, and with `coarse` the softmax over every tile times +// the v means, rounded once. +// +// attn_vsa: r4d_attn_gen.hip's S^T = K.Q^T flash attention (a lane owns a query row; P stays in +// registers, truncated to bf16 with the row sum taken from the truncated values), a workgroup two +// query tiles of one head walking the merge of their visible key tiles: every tile for a prefix +// query tile, the prefix tiles and its selected tiles for a video one. With `coarse` the output +// is bf16(bf16(o) + coarse * gate). +// +// attn_vsa's int8 Q.K form (`qk` "i8", operands `k_i8` and `k_scale`), attn_prefix_self's: the +// keys as quant_act_i8g codes and scales at group head_dim (per (row, head) scale amax / 127, 1 +// for an all-zero row, code rint(x / scale) clamped to +-127), the query quantised the same way +// here, a score the exact integer dot product times both scales on v_wmma_i32_16x16x16_iu8 (half +// the cycles of bf16), P.V in bf16 as above. The K stream halves (8 KiB a tile instead of 16). +// +// The fp8 P.V form (`pv` "fp8"): `v` as E4M3 codes with a scale per column (quant_cols_fp8's), +// P.V on v_wmma_f32_16x16x16_fp8_fp8 with P as E4M3 codes of 448 p. The softmax keeps an exact +// running max (every p at most 1, E4M3 ending at 448), the row sum takes the unrounded 448 p, +// and the epilogue multiplies by the column scale. The V stream halves too. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_dt16.h" + +#include +#include +#include + +namespace { + +constexpr int kHd = 128; // head_dim +constexpr int kTile = 64; // rows a tile at most: 4 x 4 x 4, and a prefix chunk + +__device__ __forceinline__ int vsa_clamp(int x, int lo, int hi) { + return x < lo ? lo : (x > hi ? hi : x); +} + +// The tiling of one pass, the same in every workgroup. +struct VsaGeom { + int nd; // dense segments + int P, V, N; // prefix, video and all tiles + int F, Hp, Wp; // the video grid + int nb, nc; // boxes along h and w + unsigned mb, mc; // ceil(2^32 / nb), ceil(2^32 / nc): x / n = mulhi(x, m) for x < 2^16 + int vbase; // the grid's first row + int k; // video tiles a video query tile selects +}; + +__device__ __forceinline__ VsaGeom vsa_geom(const int* __restrict__ segs, int n_seg, + const int* __restrict__ geom, int patch, int R, + int tiles_cap, double sparsity) { + VsaGeom g; + g.nd = n_seg - 1; + int P = 0; + for (int s = 0; s < g.nd; ++s) { + const int a = vsa_clamp(segs[s], 0, R), b = vsa_clamp(segs[s + 1], a, R); + P += (b - a + kTile - 1) / kTile; + } + g.vbase = vsa_clamp(segs[g.nd], 0, R); + int F = geom[0], Hp = geom[1] / patch, Wp = geom[2] / patch; + // A grid that does not fit the rows after its first is no grid: every row index below stays + // under R in 32 bits. + bool fits = F > 0 && Hp > 0 && Wp > 0 && F <= R && Hp <= R && Wp <= R; + if (fits) { + const long long fh = (long long)F * Hp; + fits = fh <= R && fh * Wp <= (long long)(R - g.vbase); + } + if (!fits) F = Hp = Wp = 0; + g.F = F; g.Hp = Hp; g.Wp = Wp; + g.nb = (Hp + 3) >> 2; + g.nc = (Wp + 3) >> 2; + g.mb = g.nb > 1 ? 0xffffffffu / (unsigned)g.nb + 1u : 0u; + g.mc = g.nc > 1 ? 0xffffffffu / (unsigned)g.nc + 1u : 0u; + int V = ((F + 3) >> 2) * g.nb * g.nc; + P = min(P, tiles_cap); + V = min(V, tiles_cap - P); + g.P = P; g.V = V; g.N = P + V; + g.k = 0; + if (V > 0) { + const double keep = (1.0 - sparsity) * (double)V; + g.k = max(1, min((int)ceil(keep), V)); + } + return g; +} + +// A tile's rows: local index kk (its raster, w fastest) is row base + dt sT + dh sH + dw, with +// (dt, dh, dw) from kk by two divisions by extents of at most 4, done as (x * m) >> 8 with +// m = ceil(256 / n), exact for x < 64. A prefix tile is one run (nw 64, so dt = dh = 0). +struct VsaTile { + int base, sT, sH, nw, nh, mw, mh, size; +}; + +__device__ __forceinline__ int vsa_magic(int n) { return (256 + n - 1) / n; } + +__device__ __forceinline__ VsaTile vsa_tile(const VsaGeom& g, const int* __restrict__ segs, + int R, int j) { + VsaTile d; + if (j < g.P) { + d.base = 0; + d.size = 1; + for (int s = 0, jj = j; s < g.nd; ++s) { + const int a = vsa_clamp(segs[s], 0, R), b = vsa_clamp(segs[s + 1], a, R); + const int nt = (b - a + kTile - 1) / kTile; + if (jj < nt) { + d.base = a + jj * kTile; + d.size = min(kTile, b - d.base); + break; + } + jj -= nt; + } + d.sT = 0; d.sH = 0; d.nw = kTile; d.nh = 1; d.mw = 4; d.mh = 256; + return d; + } + // Tile numbers are below 2^16 (the capacity is), where the multiply-high is the quotient; a + // divisor of 1 has no 32-bit reciprocal and is the identity. + const int v = j - g.P; + const int ab = g.nc > 1 ? (int)__umulhi((unsigned)v, g.mc) : v, c = v - ab * g.nc; + const int a = g.nb > 1 ? (int)__umulhi((unsigned)ab, g.mb) : ab, b = ab - a * g.nb; + const int t0 = 4 * a, h0 = 4 * b, w0 = 4 * c; + const int nt = min(4, g.F - t0), nh = min(4, g.Hp - h0), nw = min(4, g.Wp - w0); + d.base = g.vbase + (t0 * g.Hp + h0) * g.Wp + w0; + d.sT = g.Hp * g.Wp; + d.sH = g.Wp; + d.nw = nw; d.nh = nh; + d.mw = vsa_magic(nw); d.mh = vsa_magic(nh); + d.size = nt * nh * nw; + return d; +} + +__device__ __forceinline__ int vsa_row(const VsaTile& d, int kk) { + const int q1 = (kk * d.mw) >> 8, dw = kk - q1 * d.nw; + const int dt = (q1 * d.mh) >> 8, dh = q1 - dt * d.nh; + return d.base + dt * d.sT + dh * d.sH + dw; +} + +// Four bf16 (one uint2) added in order to four f32 sums. +__device__ __forceinline__ void vsa_acc4(float4& s, uint2 u) { + s.x = s.x + bf16w_lo(u.x); s.y = s.y + bf16w_hi(u.x); + s.z = s.z + bf16w_lo(u.y); s.w = s.w + bf16w_hi(u.y); +} + +// The sums of q, k and (when `xv` is given) v over a tile's rows, one head's four dims each, in the +// tile's raster: the three share each row's address, and a batch of four rows' loads is issued +// before its adds, which stay in row order. +__device__ __forceinline__ void vsa_tile_sum3(const uint16_t* __restrict__ xq, int q_ld, + const uint16_t* __restrict__ xk, int k_ld, + const uint16_t* __restrict__ xv, int v_ld, + const VsaTile& d, float4& sq, float4& sk, + float4& sv) { + sq = sk = sv = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + int kk = 0; + for (; kk + 4 <= d.size; kk += 4) { + uint2 uq[4], uk[4], uv[4]; + #pragma unroll + for (int r = 0; r < 4; ++r) { + const long row = vsa_row(d, kk + r); + uq[r] = *(const uint2*)(xq + row * q_ld); + uk[r] = *(const uint2*)(xk + row * k_ld); + if (xv) uv[r] = *(const uint2*)(xv + row * v_ld); + } + #pragma unroll + for (int r = 0; r < 4; ++r) { + vsa_acc4(sq, uq[r]); + vsa_acc4(sk, uk[r]); + if (xv) vsa_acc4(sv, uv[r]); + } + } + for (; kk < d.size; ++kk) { + const long row = vsa_row(d, kk); + vsa_acc4(sq, *(const uint2*)(xq + row * q_ld)); + vsa_acc4(sk, *(const uint2*)(xk + row * k_ld)); + if (xv) vsa_acc4(sv, *(const uint2*)(xv + row * v_ld)); + } +} + +// A score as an unsigned key that orders like the float, -0 folded onto +0 first so that the two +// zeros tie as they do as floats. +__device__ __forceinline__ uint32_t vsa_key(float s) { + const uint32_t u = __float_as_uint(s + 0.0f); + return (u & 0x80000000u) ? ~u : (u | 0x80000000u); +} +__device__ __forceinline__ float vsa_unkey(uint32_t k) { + return __uint_as_float((k & 0x80000000u) ? (k & 0x7fffffffu) : ~k); +} + +__device__ __forceinline__ int vsa_wave_count(int c) { return (int)r4d_wave_sum((float)c); } + +// ---------------------------------------------------------------------------- vsa_select: pool +// The q, k (and v) means of every tile of G heads into the scratch: k as [G][32][tiles_cap] +// float4, the dims in groups of four outermost, so the score loop's lanes (consecutive tiles) read +// 512 contiguous bytes; q and v as [G][tiles_cap][128] f32 rows, read by a wave a tile and by the +// coarse product's lanes (consecutive dims). A workgroup a tile and four heads, a lane four dims +// of one head. The sums are a dependent chain a lane, so they run here, at this kernel's +// occupancy, rather than in the select kernel's. +__global__ __launch_bounds__(128) void vsa_pool_kernel( + const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, + const uint16_t* __restrict__ gv, int q_ld, int k_ld, int v_ld, + const int* __restrict__ segs, int n_seg, const int* __restrict__ geom, int patch, int R, + int tiles_cap, int h0, int G, float4* __restrict__ kpT, float4* __restrict__ qp, + float4* __restrict__ vp) { + const VsaGeom g = vsa_geom(segs, n_seg, geom, patch, R, tiles_cap, 0.0); + const int j = blockIdx.x; + const int gh = blockIdx.y * 4 + (threadIdx.x >> 5), d4 = threadIdx.x & 31; + if (j >= g.N || gh >= G) return; + const VsaTile d = vsa_tile(g, segs, R, j); + const long col = (long)(h0 + gh) * kHd + 4 * d4; + const float n = (float)d.size; + float4 sq, sk, sv; + vsa_tile_sum3(gq + col, q_ld, gk + col, k_ld, vp ? gv + col : nullptr, v_ld, d, sq, sk, sv); + const long rw = ((long)gh * tiles_cap + j) * 32 + d4; + kpT[((long)gh * 32 + d4) * tiles_cap + j] = make_float4(sk.x / n, sk.y / n, sk.z / n, sk.w / n); + qp[rw] = make_float4(sq.x / n, sq.y / n, sq.z / n, sq.w / n); + if (vp) vp[rw] = make_float4(sv.x / n, sv.y / n, sv.z / n, sv.w / n); +} + +// ---------------------------------------------------------------------------- vsa_select: select +// QT query tiles of one head a workgroup of eight waves; NMAX bounds the tile count (the scores +// of every tile for each query tile are kept in LDS, as order keys, then as softmax weights). +// +// 1. q means of the QT tiles from the scratch into LDS. +// 2. Scores: a thread a key tile and all QT query tiles, the k mean read four dims at a time +// from the transposed scratch (eight loads in flight), each dot product summed over the +// dims in order. +// 3. Selection, a wave a query tile: the k-th largest key by bisection on its 32 bits (T is the +// largest value with at least k keys >= T), then one ascending pass taking the keys above T +// and the first (k - #above) keys equal to it, compacted by ballots. +// 4. Coarse: the wave's softmax over every tile (max-subtracted, f32) into the same LDS row, +// then p times the v means summed over the tiles, a thread a dim and every query tile of +// the group over half of them, eight tiles' loads in flight. +template +__global__ __launch_bounds__(256) void vsa_select_kernel( + const int* __restrict__ segs, int n_seg, const int* __restrict__ geom, int patch, int R, + int tiles_cap, double sparsity, float scale, int h0, const float4* __restrict__ kpT, + const float4* __restrict__ qp, const float* __restrict__ vp, int* __restrict__ sel, + long long sel_hs, long long sel_ts, int k_cap, uint16_t* __restrict__ coarse, + long long c_hs, long long c_ts) { + static_assert(QT <= 8, "a wave a query tile"); + __shared__ uint32_t sS[QT * NMAX]; + __shared__ float4 sQ[QT * 32]; + + const VsaGeom g = vsa_geom(segs, n_seg, geom, patch, R, tiles_cap, sparsity); + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int i0 = blockIdx.x * QT, gh = blockIdx.y, hq = h0 + gh; + if (i0 >= g.N) return; + + // 1. the q means + if (wave < QT) { + const int i = i0 + wave; + sQ[wave * 32 + lane] = i < g.N ? qp[((long)gh * tiles_cap + i) * 32 + lane] + : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } + __syncthreads(); + + // 2. the scores + const float4* kb = kpT + (long)gh * 32 * tiles_cap; + for (int j0 = 0; j0 < g.N; j0 += 256) { + const int j = j0 + tid, jc = min(j, g.N - 1); + float acc[QT]; + #pragma unroll + for (int q = 0; q < QT; ++q) acc[q] = 0.0f; + #pragma unroll 1 + for (int d0 = 0; d0 < 32; d0 += 8) { + float4 kv[8]; + #pragma unroll + for (int u = 0; u < 8; ++u) kv[u] = kb[(long)(d0 + u) * tiles_cap + jc]; + // A fence a step: the eight loads above are what is hoisted, not the LDS reads of + // every step (eight query tiles' worth each). + #pragma unroll + for (int u = 0; u < 8; ++u) { + #pragma unroll + for (int q = 0; q < QT; ++q) { + const float4 qv = sQ[q * 32 + d0 + u]; + acc[q] = acc[q] + qv.x * kv[u].x; + acc[q] = acc[q] + qv.y * kv[u].y; + acc[q] = acc[q] + qv.z * kv[u].z; + acc[q] = acc[q] + qv.w * kv[u].w; + } + sched_barrier(); + } + } + if (j < g.N) { + #pragma unroll + for (int q = 0; q < QT; ++q) sS[q * NMAX + j] = vsa_key(acc[q] * scale); + } + } + __syncthreads(); + + // 3. the selection + const int i = i0 + wave; + uint32_t* row = sS + wave * NMAX; + if (wave < QT && i < g.N && i >= g.P && g.V > 0) { + const int k = g.k; + uint32_t T = 0; + for (int b = 31; b >= 0; --b) { + const uint32_t cand = T | (1u << b); + int c = 0; + for (int j = g.P + lane; j < g.N; j += 32) c += row[j] >= cand ? 1 : 0; + if (vsa_wave_count(c) >= k) T = cand; + } + int c = 0; + for (int j = g.P + lane; j < g.N; j += 32) c += row[j] > T ? 1 : 0; + const int need = k - vsa_wave_count(c); + int* out = sel + (long long)hq * sel_hs + (long long)i * sel_ts; + const int kw = min(k, k_cap); + const uint32_t below = (1u << lane) - 1u; + int eq_seen = 0, written = 0; + for (int j0 = g.P; j0 < g.N && written < kw; j0 += 32) { + const int j = j0 + lane; + const uint32_t key = j < g.N ? row[j] : 0u; + const bool gt = j < g.N && key > T, eq = j < g.N && key == T; + const uint32_t em = (uint32_t)__builtin_amdgcn_ballot_w32(eq); + const bool take = gt || (eq && eq_seen + (int)__popc(em & below) < need); + const uint32_t tm = (uint32_t)__builtin_amdgcn_ballot_w32(take); + const int pos = written + (int)__popc(tm & below); + if (take && pos < kw) out[pos] = j; + written += (int)__popc(tm); + eq_seen += (int)__popc(em); + } + } + if (!coarse) return; + + // 4. the coarse branch + if (wave < QT && i < g.N) { + float mx = -INFINITY; + for (int j = lane; j < g.N; j += 32) mx = fmaxf(mx, vsa_unkey(row[j])); + mx = r4d_wave_max(mx); + float sum = 0.0f; + for (int j = lane; j < g.N; j += 32) { + const float e = expf(vsa_unkey(row[j]) - mx); + row[j] = __float_as_uint(e); + sum += e; + } + sum = r4d_wave_sum(sum); + for (int j = lane; j < g.N; j += 32) + row[j] = __float_as_uint(__uint_as_float(row[j]) / sum); + } + __syncthreads(); + // A thread a dim and every query tile of the group over half the tiles, so each v load feeds + // QT products; the second half's sums meet the first's through LDS (sQ is free once the + // scores are done). + const int dim = tid & (kHd - 1), half = tid >> 7; + const int jm = (g.N + 1) / 2, j1 = half ? g.N : jm; + float acc[QT]; + #pragma unroll + for (int q = 0; q < QT; ++q) acc[q] = 0.0f; + const float* vb = vp + (long)gh * tiles_cap * kHd + dim; + int j = half ? jm : 0; + for (; j + 8 <= j1; j += 8) { + float vv[8]; + #pragma unroll + for (int u = 0; u < 8; ++u) vv[u] = vb[(long)(j + u) * kHd]; + #pragma unroll + for (int u = 0; u < 8; ++u) { + #pragma unroll + for (int q = 0; q < QT; ++q) + acc[q] = acc[q] + __uint_as_float(sS[q * NMAX + j + u]) * vv[u]; + sched_barrier(); + } + } + for (; j < j1; ++j) { + const float vv = vb[(long)j * kHd]; + #pragma unroll + for (int q = 0; q < QT; ++q) acc[q] = acc[q] + __uint_as_float(sS[q * NMAX + j]) * vv; + } + float* part = (float*)sQ; + if (half) { + #pragma unroll + for (int q = 0; q < QT; ++q) part[q * kHd + dim] = acc[q]; + } + __syncthreads(); + if (half) return; + #pragma unroll + for (int q = 0; q < QT; ++q) { + const int iq = i0 + q; + if (iq < g.N) + coarse[(long long)hq * c_hs + (long long)iq * c_ts + dim] = + f32_to_bf16(acc[q] + part[q * kHd + dim]); + } +} + +// ---------------------------------------------------------------------------- attn_vsa +// A workgroup NQT query tiles of one head, four waves of 16 query rows each (a tile's raster). +// Each query tile's visible key tiles are ascending (the prefix tiles, then its selection, which +// vsa_select writes ascending; every tile for a prefix query tile), so the workgroup walks their +// merge: a key tile is staged once for every query tile of the group that sees it, and the waves +// of the others skip its arithmetic. +// +// The kernel is bound by the stream of staged K/V tiles, which a random selection draws from the +// whole head (19 MB at 1344 x 768, past the 8 MB L2): two query tiles a workgroup stage 17% +// fewer tiles than one at random selections and a third fewer where neighbouring tiles select +// alike, and four lose more to idle waves than they save. Staging is r4d_attn_ps_kernel's (K +// rows into LDS, V through the transposing load into V^T), one tile ahead: the next tile's loads +// are issued into registers before the current tile's arithmetic and land in LDS after it. A key +// past its tile's size reads the tile's last row and is masked; 16-key blocks wholly past it are +// skipped, and full tiles take the unmasked arithmetic. LDS rows are not padded: 16-byte chunk c +// of row r is stored at c ^ (r & 7), so the eight lanes of a 16-byte access reach eight +// different bank groups, and the two tiles take 32 KiB (four workgroups a WGP). +constexpr int kNone = 0x7fffffff; + +// log2(448) less 2^-16: exp2 of it is 448 (1 - 1.1e-5), under 448 with room for the hardware +// exp2's error, and still the E4M3 code of 448. +constexpr float kLog448 = 8.8073397f; + +typedef int v2i_vsa __attribute__((ext_vector_type(2))); +typedef int v8i_vsa __attribute__((ext_vector_type(8))); + +// quant_act_i8g codes for four values against `inv` = 1 / scale, packed into one dword. +__device__ __forceinline__ uint32_t vsa_q8x4(float a, float b, float c, float d, float inv) { + auto q = [inv](float x) { + return (uint32_t)((int)rintf(fminf(fmaxf(x * inv, -127.0f), 127.0f)) & 0xff); + }; + return q(a) | (q(b) << 8) | (q(c) << 16) | (q(d) << 24); +} +__device__ __forceinline__ float vsa_amax8(uint4 u) { + return fmaxf(fmaxf(fmaxf(fabsf(bf16w_lo(u.x)), fabsf(bf16w_hi(u.x))), + fmaxf(fabsf(bf16w_lo(u.y)), fabsf(bf16w_hi(u.y)))), + fmaxf(fmaxf(fabsf(bf16w_lo(u.z)), fabsf(bf16w_hi(u.z))), + fmaxf(fabsf(bf16w_lo(u.w)), fabsf(bf16w_hi(u.w))))); +} +__device__ __forceinline__ v2i_vsa vsa_q8x8(uint4 u, float inv) { + const uint32_t a = vsa_q8x4(bf16w_lo(u.x), bf16w_hi(u.x), bf16w_lo(u.y), bf16w_hi(u.y), inv); + const uint32_t b = vsa_q8x4(bf16w_lo(u.z), bf16w_hi(u.z), bf16w_lo(u.w), bf16w_hi(u.w), inv); + return (v2i_vsa){ (int)a, (int)b }; +} + +__device__ __forceinline__ int vsa_sw(int r, int c) { return c ^ (r & 7); } + +// The int8 + fp8 form is held to 192 VGPRs (eight waves a SIMD, four workgroups a WGP): it lands +// a few over without the target, which costs a workgroup a WGP. The bf16 + fp8 form spills +// under it and stays without. +template +__global__ __launch_bounds__(NQT * 128) __attribute__((amdgpu_waves_per_eu(I8 && PV8 ? 8 : 1))) +void vsa_attn_kernel( + const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, + const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, + const uint16_t* __restrict__ gc, const uint16_t* __restrict__ gg, + const int* __restrict__ segs, int n_seg, const int* __restrict__ geom, int patch, int R, + int tiles_cap, double sparsity, const int* __restrict__ sel, long long sel_hs, + long long sel_ts, int k_cap, long long c_hs, long long c_ts, float scale, int q_ld, int k_ld, + int v_ld, int g_ld, int o_ld, const int8_t* __restrict__ gk8, const float* __restrict__ gks, + int k8_ld, int ks_ld, const float* __restrict__ gvs) { + typedef DT16<0> D; + typedef D::frag frag16; + typedef typename std::conditional::type qfrag; + + constexpr int HD = kHd; + constexpr int TILE = kTile; + constexpr int NTHR = NQT * 128; + constexpr int NKS = HD / 16; + constexpr int DG = HD / 8; // 16-byte chunks of a K row + constexpr int KP = TILE * DG / NTHR; // 16-byte K units a thread, and V units + constexpr int VP = KP; + constexpr int VP8 = VP / 2; // the same at E4M3: 16 dims of 8 keys a unit + constexpr int MT = TILE / 16; + constexpr float GROW = D::GROW; + + // The int8 key tile is r4d_attn_ps_kernel's: HD bytes a row padded by 8, so a fragment read's + // sixteen rows hit distinct bank pairs, written as 8-byte halves (odd rows are 8-byte + // aligned), and a scale a key. + constexpr int KSTR8 = HD + 8; + // The E4M3 V^T tile: HD rows of TILE key bytes padded by 8, so the sixteen rows of a fragment + // read (8 bytes a lane) fall on distinct bank pairs. + constexpr int VSTR8 = TILE + 8; + __shared__ __align__(16) uint16_t sK[I8 ? 8 : TILE * HD]; + __shared__ __align__(16) int8_t sK8[I8 ? TILE * KSTR8 : 16]; + __shared__ __align__(16) float sKs[I8 ? TILE : 4]; + __shared__ __align__(16) uint16_t sV[PV8 ? 8 : HD * TILE]; + __shared__ __align__(16) uint8_t sV8[PV8 ? HD * VSTR8 : 16]; + + const VsaGeom g = vsa_geom(segs, n_seg, geom, patch, R, tiles_cap, sparsity); + const int i0 = blockIdx.x * NQT, hq = blockIdx.y; + if (i0 >= g.N) return; + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int c = lane & 15, h = lane >> 4, swz = c & 7; + const int qt = warp >> 2, wq = warp & 3; + const int i = i0 + qt; + const bool tval = i < g.N; + const VsaTile qd = vsa_tile(g, segs, R, tval ? i : i0); + const int qpos = wq * 16 + c; + const bool live = tval && qpos < qd.size; + const bool wlive = tval && wq * 16 < qd.size; + const int qrow = vsa_row(qd, qpos < qd.size ? qpos : qd.size - 1); + + // The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against the + // row's absmax (a lane holds half the head's dims, lane + 16 the other half) with the scale + // in `qs`, applied to the integer score. + const float mul = scale * 1.44269504089f; + qfrag qf[NKS]; + float qs = mul; + { + const uint16_t* qp = gq + (long)qrow * q_ld + (long)hq * HD; + if constexpr (I8) { + uint4 qu[NKS]; + float am = 0.0f; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + qu[t] = *(const uint4*)(qp + 16 * t + 8 * h); + am = fmaxf(am, vsa_amax8(qu[t])); + } + am = fmaxf(am, swap16(am)); + const float sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; + const float inv = 1.0f / sq; + qs = sq * mul; + #pragma unroll + for (int t = 0; t < NKS; ++t) qf[t] = vsa_q8x8(qu[t], inv); + } else { + #pragma unroll + for (int t = 0; t < NKS; ++t) { + const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h); + auto cv = [&](uint32_t w) { + return D::pk(__builtin_bit_cast(float, w << 16) * mul, + __builtin_bit_cast(float, w & 0xffff0000u) * mul); + }; + qf[t] = D::mk(make_uint2(cv(u.x), cv(u.y)), make_uint2(cv(u.z), cv(u.w))); + } + } + } + + float m_ref = -3.0e38f, soff = 3.0e38f, l_i = 0.0f; + v8f acc[NKS]; + #pragma unroll + for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + + // The key-tile lists: query tile q of the group sees its entries e < len[q], entry e being e + // itself while e < P or the query tile is a prefix tile, else its selection's slot e - P. + const int ks = min(g.k, k_cap); + int len[NQT], pos[NQT], cur[NQT]; + const int* srow[NQT]; + #pragma unroll + for (int q = 0; q < NQT; ++q) { + const int iq = i0 + q; + len[q] = iq >= g.N ? 0 : iq < g.P ? g.N : g.P + ks; + srow[q] = sel + (long long)hq * sel_hs + (long long)(iq < g.N ? iq : 0) * sel_ts; + pos[q] = 0; + } + auto entry = [&](int q, int e) -> int { + if (e >= len[q]) return kNone; + if (e < g.P || i0 + q < g.P) return e; + return vsa_clamp(srow[q][e - g.P], 0, g.N - 1); + }; + #pragma unroll + for (int q = 0; q < NQT; ++q) cur[q] = entry(q, 0); + // The next tile of the merge and the query tiles that see it, as a bit mask. + auto advance = [&](int& j, int& m) { + j = kNone; + #pragma unroll + for (int q = 0; q < NQT; ++q) j = min(j, cur[q]); + m = 0; + if (j == kNone) return; + #pragma unroll + for (int q = 0; q < NQT; ++q) + if (cur[q] == j) { m |= 1 << q; cur[q] = entry(q, ++pos[q]); } + }; + + // Staging: wave w stages keys KW w .. KW w + KW - 1, their K rows and V rows. Lane l decodes + // the row of key KW w + l % KW once. Its V units read that key: eight-lane group g of the + // wave takes key group g % (KW / 8) and dim groups g / (KW / 8) + (32 / KW) r, the eight + // lanes of a group the group's eight keys, as the transposing load wants. Its K units take + // keys KW w + l / 16 + 2 p at dims 8 (l % 16), the row from lane l / 16 + 2 p by a permute. + // So a wave reads whole rows, and a row is decoded once a tile (decoding it per unit cost a + // tenth of the kernel). An int8 K row is eight 16-byte units: keys KW w + l / 8 + 4 p, the + // row from lane l / 8 + 4 p, and lane l < KW reads its key's scale. An E4M3 V unit is the same + // transposing load over pairs of codes (16 dims of the group's 8 keys): lane j receives dims + // 2j and 2j + 1 interleaved, and four byte permutes split them into two V^T rows of 8 keys. + constexpr int NW = NTHR / 32; + constexpr int KW = TILE / NW; + constexpr int K8P = KW / 4; + static_assert(KW == 2 * KP && VP == KW / 2 && (KW == 8 || KW == 16), "a wave's keys"); + const int kw0 = KW * warp, lg = lane >> 3, vj = lane & 7; + const int vkg = kw0 / 8 + lg % (KW / 8), vdg = lg / (KW / 8); + const uint16_t* kbase = gk + (long)hq * HD + (lane & 15) * 8; + const int8_t* k8base = I8 ? gk8 + (long)hq * HD + (lane & 7) * 16 : nullptr; + const uint16_t* vbase = gv + (long)hq * HD; + const uint8_t* vbase8 = (const uint8_t*)gv + (long)hq * HD; + // ext_vector_type staging registers: an array of HIP's uint4 carried across the loop is kept + // in scratch (r4d_common.h). + r4d_u32x4 kr[I8 ? K8P : KP], vr[PV8 ? VP8 : VP]; + float ksr = 0.0f; + auto load = [&](const VsaTile& kd) { + const int kk = kw0 + lane % KW; + const int row = vsa_row(kd, kk < kd.size ? kk : kd.size - 1); + if constexpr (PV8) { + const uint8_t* v0 = vbase8 + (long)row * v_ld; + #pragma unroll + for (int r = 0; r < VP8; ++r) + vr[r] = __builtin_bit_cast(r4d_u32x4, + load_tr_b128(v0 + (vdg + (32 / KW) * r) * 16)); + } else { + const uint16_t* v0 = vbase + (long)row * v_ld; + #pragma unroll + for (int r = 0; r < VP; ++r) + vr[r] = __builtin_bit_cast(r4d_u32x4, load_tr_b128(v0 + (vdg + (32 / KW) * r) * 8)); + } + if constexpr (I8) { + #pragma unroll + for (int p = 0; p < K8P; ++p) { + const int krow = __shfl(row, (lane >> 3) + 4 * p); + kr[p] = *(const r4d_u32x4*)(k8base + (long)krow * k8_ld); + } + if (lane < KW) ksr = gks[(long)row * ks_ld + hq]; + } else { + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int krow = __shfl(row, (lane >> 4) + 2 * p); + kr[p] = *(const r4d_u32x4*)(kbase + (long)krow * k_ld); + } + } + }; + auto store = [&]() { + if constexpr (PV8) { + #pragma unroll + for (int r = 0; r < VP8; ++r) { + const int row = (vdg + (32 / KW) * r) * 16 + 2 * vj; + const r4d_u32x4 w = vr[r]; + *(uint2*)&sV8[row * VSTR8 + vkg * 8] = + make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x06040200u), + __builtin_amdgcn_perm(w.w, w.z, 0x06040200u)); + *(uint2*)&sV8[(row + 1) * VSTR8 + vkg * 8] = + make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x07050301u), + __builtin_amdgcn_perm(w.w, w.z, 0x07050301u)); + } + } else { + #pragma unroll + for (int r = 0; r < VP; ++r) { + const int row = (vdg + (32 / KW) * r) * 8 + vj; + *(r4d_u32x4*)&sV[row * TILE + vsa_sw(row, vkg) * 8] = vr[r]; + } + } + if constexpr (I8) { + #pragma unroll + for (int p = 0; p < K8P; ++p) { + int8_t* d = &sK8[(kw0 + (lane >> 3) + 4 * p) * KSTR8 + (lane & 7) * 16]; + *(uint2*)d = make_uint2(kr[p].x, kr[p].y); + *(uint2*)(d + 8) = make_uint2(kr[p].z, kr[p].w); + } + if (lane < KW) sKs[kw0 + lane] = ksr; + } else { + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int key = kw0 + (lane >> 4) + 2 * p; + *(r4d_u32x4*)&sK[key * HD + vsa_sw(key, lane & 15) * 8] = kr[p]; + } + } + }; + + // A lane reads K row mt * 16 + c and V^T rows t * 16 + c, both at swizzle c & 7: the K + // chunk of dims 16 t + 8 h is (2 t + h) ^ swz = 2 t ^ (h ^ swz). + int koff[NKS]; + #pragma unroll + for (int t = 0; t < NKS; ++t) koff[t] = c * HD + ((2 * t) ^ (h ^ swz)) * 8; + + // Scores of keys mt * 16 + 8 h .. + 8 for the lane's query, in log2 units once multiplied by + // `qs` (int8 only; the bf16 query already carries the scale). + auto score = [&](int mt, float (&sc)[8]) { + if constexpr (I8) { + v8i_vsa si = (v8i_vsa){0, 0, 0, 0, 0, 0, 0, 0}; + const int8_t* kr2 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_vsa kf[4]; + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const uint2 u = *(const uint2*)(kr2 + 16 * (t0 + jj)); + kf[jj] = (v2i_vsa){ (int)u.x, (int)u.y }; + } + sched_barrier(); + #pragma unroll + for (int jj = 0; jj < 4; ++jj) + si = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, kf[jj], true, qf[t0 + jj], si, false); + } + const float4 ka = *(const float4*)&sKs[mt * 16 + 8 * h]; + const float4 kb = *(const float4*)&sKs[mt * 16 + 8 * h + 4]; + const float kss[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = (float)si[e] * kss[e]; + } else { + v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + const uint16_t* kr2 = &sK[mt * 16 * HD]; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 kf[4]; + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const uint4 u = *(const uint4*)(kr2 + koff[t0 + jj]); + kf[jj] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); + } + sched_barrier(); + #pragma unroll + for (int jj = 0; jj < 4; ++jj) s = D::wmma(kf[jj], qf[t0 + jj], s); + } + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = s[e]; + } + }; + + // MASK is the edge tiles' form; a full tile's keys are all valid. + auto compute = [&](int klim, auto maskc) { + constexpr bool mask = decltype(maskc)::value; + const int mte = mask ? (klim + 15) >> 4 : TILE / 16; + #pragma unroll 1 + for (int mt = 0; mt < mte; ++mt) { + float sc[8]; + score(mt, sc); + if constexpr (mask) { + const int kq0 = mt * 16 + 8 * h; + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = kq0 + e < klim ? sc[e] : -INFINITY; + } + + // qs > 0, so the max of the scaled scores is the scaled max. + float smax = sc[0]; + #pragma unroll + for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); + if (I8) smax *= qs; + if (wave_any(smax > m_ref + GROW)) { + const float rmax = fmaxf(smax, swap16(smax)); + const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f); + const float alpha = ex2(m_ref - mnew); + #pragma unroll + for (int t = 0; t < NKS; ++t) + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= alpha; + l_i *= alpha; + m_ref = mnew; + soff = -mnew; + } + + // P to bf16 by truncation, the row sum from the same truncated values (see + // r4d_attn_ps_kernel). + uint32_t pw[4]; + #pragma unroll + for (int e = 0; e < 8; e += 2) { + const float a0 = I8 ? __builtin_fmaf(sc[e], qs, soff) : sc[e] + soff; + const float a1 = I8 ? __builtin_fmaf(sc[e + 1], qs, soff) : sc[e + 1] + soff; + const uint32_t lo = __builtin_bit_cast(uint32_t, ex2(a0)); + const uint32_t hi = __builtin_bit_cast(uint32_t, ex2(a1)); + pw[e >> 1] = __builtin_amdgcn_perm(hi, lo, 0x07060302u); + } + #pragma unroll + for (int e = 0; e < 4; ++e) + l_i += __builtin_bit_cast(float, pw[e] << 16) + + __builtin_bit_cast(float, pw[e] & 0xffff0000u); + const frag16 p16 = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3])); + + const uint16_t* vr2 = &sV[c * TILE + (((2 * mt) ^ (h ^ swz)) * 8)]; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 vf[4]; + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const uint4 u = *(const uint4*)(vr2 + (t0 + jj) * 16 * TILE); + vf[jj] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)); + } + sched_barrier(); + #pragma unroll + for (int jj = 0; jj < 4; ++jj) acc[t0 + jj] = D::wmma(vf[jj], p16, acc[t0 + jj]); + } + } + }; + + // The fp8 P.V form, a tile at a time: the scores of all its 16-key blocks, one exact running + // max over them (one rescale test a tile rather than a block), P as E4M3 codes of 448 p, then + // the blocks' fp8 WMMAs. The max is kept in the scores' own units (the int8 form's are + // unscaled, `qs` being one positive factor a row), so s - max is at most 0 exactly, and + // x = exp2((s - max) qs + kLog448) cannot pass exp2(kLog448) < 448, where v_cvt_pk_fp8_f32 + // would give NaN. x is 448 p up to a factor common to every key, which the row sum shares. + auto compute8 = [&](int klim, auto maskc) { + constexpr bool mask = decltype(maskc)::value; + const int mte = mask ? (klim + 15) >> 4 : MT; + float sc[MT][8]; + auto score_all = [&]() { + #pragma unroll + for (int mt = 0; mt < MT; ++mt) { + if (mask && mt >= mte) { + #pragma unroll + for (int e = 0; e < 8; ++e) sc[mt][e] = -INFINITY; + continue; + } + score(mt, sc[mt]); + if constexpr (mask) { + const int kq0 = mt * 16 + 8 * h; + #pragma unroll + for (int e = 0; e < 8; ++e) sc[mt][e] = kq0 + e < klim ? sc[mt][e] : -INFINITY; + } + } + }; + bool scored = false; + if constexpr (I8) { + if constexpr (!mask) { + // Two blocks' int8 chains interleaved: each WMMA waits on the one two back. + #pragma unroll + for (int mt = 0; mt < MT; mt += 2) { + v8i_vsa s0 = (v8i_vsa){0, 0, 0, 0, 0, 0, 0, 0}, s1 = s0; + const int8_t* r0 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h; + const int8_t* r1 = r0 + 16 * KSTR8; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_vsa k0[4], k1[4]; + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const uint2 u0 = *(const uint2*)(r0 + 16 * (t0 + jj)); + const uint2 u1 = *(const uint2*)(r1 + 16 * (t0 + jj)); + k0[jj] = (v2i_vsa){ (int)u0.x, (int)u0.y }; + k1[jj] = (v2i_vsa){ (int)u1.x, (int)u1.y }; + } + sched_barrier(); + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + s0 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, k0[jj], true, qf[t0 + jj], s0, false); + s1 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12( + true, k1[jj], true, qf[t0 + jj], s1, false); + } + } + #pragma unroll + for (int b = 0; b < 2; ++b) { + const float4 ka = *(const float4*)&sKs[(mt + b) * 16 + 8 * h]; + const float4 kb = *(const float4*)&sKs[(mt + b) * 16 + 8 * h + 4]; + const float kss[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) + sc[mt + b][e] = (float)(b ? s1[e] : s0[e]) * kss[e]; + } + } + scored = true; + } + } + if (!scored) score_all(); + float smax = sc[0][0]; + #pragma unroll + for (int mt = 0; mt < MT; ++mt) + #pragma unroll + for (int e = 0; e < 8; ++e) smax = fmaxf(smax, sc[mt][e]); + if (wave_any(smax > m_ref)) { + const float rmax = fmaxf(smax, swap16(smax)); + const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f); + const float alpha = ex2(I8 ? (m_ref - mnew) * qs : m_ref - mnew); + #pragma unroll + for (int t = 0; t < NKS; ++t) + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= alpha; + l_i *= alpha; + m_ref = mnew; + } + v2i_vsa p8[MT]; + #pragma unroll + for (int mt = 0; mt < MT; ++mt) { + float x[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) { + const float d = sc[mt][e] - m_ref; + x[e] = ex2(I8 ? __builtin_fmaf(d, qs, kLog448) : d + kLog448); + } + l_i += ((x[0] + x[1]) + (x[2] + x[3])) + ((x[4] + x[5]) + (x[6] + x[7])); + // The first conversion's high half is dead (the second writes it), so any live + // register serves as its old value: no zeroing moves. + int w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[0], x[1], __builtin_bit_cast(int, x[0]), + false); + w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[2], x[3], w0, true); + int w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[4], x[5], __builtin_bit_cast(int, x[4]), + false); + w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[6], x[7], w1, true); + p8[mt] = (v2i_vsa){ w0, w1 }; + } + #pragma unroll + for (int mt = 0; mt < MT; ++mt) { + if (mask && mt >= mte) break; + const uint8_t* vr2 = &sV8[c * VSTR8 + mt * 16 + 8 * h]; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + v2i_vsa vf[4]; + #pragma unroll + for (int jj = 0; jj < 4; ++jj) { + const uint2 u = *(const uint2*)(vr2 + (t0 + jj) * 16 * VSTR8); + vf[jj] = (v2i_vsa){ (int)u.x, (int)u.y }; + } + sched_barrier(); + #pragma unroll + for (int jj = 0; jj < 4; ++jj) + acc[t0 + jj] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12( + vf[jj], p8[mt], acc[t0 + jj]); + } + } + }; + + // The walk: the staged tile (jc, the query tiles mc that see it) goes to LDS, the next one's + // loads are issued, then the staged tile's arithmetic. + int jc, mc; + advance(jc, mc); + VsaTile kdc = qd; + if (jc != kNone) { + kdc = vsa_tile(g, segs, R, jc); + load(kdc); + } + while (jc != kNone) { + int jn, mn; + advance(jn, mn); + lds_barrier(); + store(); + lds_barrier(); + VsaTile kdn = kdc; + if (jn != kNone) { + kdn = vsa_tile(g, segs, R, jn); + load(kdn); + } + if (wlive && ((mc >> qt) & 1)) { + if constexpr (PV8) { + if (kdc.size == TILE) compute8(kdc.size, std::false_type{}); + else compute8(kdc.size, std::true_type{}); + } else { + if (kdc.size == TILE) compute(kdc.size, std::false_type{}); + else compute(kdc.size, std::true_type{}); + } + } + jc = jn; + mc = mn; + kdc = kdn; + } + + if (!live) return; + const float ls = l_i + swap16(l_i); + const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f; + uint16_t* op = go + (long)qrow * o_ld + (long)hq * HD; + const uint16_t* cp = gc ? gc + (long long)hq * c_hs + (long long)i * c_ts : nullptr; + const uint16_t* gp = gg ? gg + (long)qrow * g_ld + (long)hq * HD : nullptr; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + uint32_t tw[4]; + if constexpr (PV8) { + // The column scales of the lane's eight dims. + const float4 sa = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h); + const float4 sb = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h + 4); + const float vs[8] = { sa.x, sa.y, sa.z, sa.w, sb.x, sb.y, sb.z, sb.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) acc[t][e] *= vs[e]; + } + if (cp) { + // The epilogue's addcmul: o rounded to bf16, plus coarse * gate (exact in f32), one + // rounding. + const uint4 cu = *(const uint4*)(cp + t * 16 + 8 * h); + const uint4 gu = *(const uint4*)(gp + t * 16 + 8 * h); + const uint32_t cw[4] = { cu.x, cu.y, cu.z, cu.w }, gw[4] = { gu.x, gu.y, gu.z, gu.w }; + #pragma unroll + for (int e = 0; e < 8; e += 2) { + const float o0 = bf16_to_f32(f32_to_bf16(acc[t][e] * inv)); + const float o1 = bf16_to_f32(f32_to_bf16(acc[t][e + 1] * inv)); + const float r0 = o0 + bf16w_lo(cw[e >> 1]) * bf16w_lo(gw[e >> 1]); + const float r1 = o1 + bf16w_hi(cw[e >> 1]) * bf16w_hi(gw[e >> 1]); + tw[e >> 1] = (uint32_t)f32_to_bf16(r0) | ((uint32_t)f32_to_bf16(r1) << 16); + } + } else { + #pragma unroll + for (int e = 0; e < 8; e += 2) + tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv) + | ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16); + } + *(uint4*)(op + t * 16 + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]); + } +} + +// ---------------------------------------------------------------------------- shared checks +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; } +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } + +// What both ops read alike: the geometry parameters and the device geometry operands. +struct VsaCommon { + long long R, nh, q_ld, k_ld; + int n_seg, patch; + double sparsity; + float scale; +}; + +int vsa_common(const RadArgs* a, const RadTensor* q, const RadTensor* k, const RadTensor* segs, + const RadTensor* geom, VsaCommon* c) { + if (!is_bf16(q) || !is_bf16(k) || !is_i32(segs) || !is_i32(geom)) return R4D_NO(RAD_E_DTYPE); + if (r4d_geti_or(a, "head_dim", 0) != kHd || r4d_geti_or(a, "tile_t", 0) != 4 || + r4d_geti_or(a, "tile_h", 0) != 4 || r4d_geti_or(a, "tile_w", 0) != 4) + return R4D_NO(RAD_E_SHAPE); + const long long patch = r4d_geti_or(a, "patch", 0); + const double sp = r4d_getf(a, "sparsity", -1.0); + if (patch < 1 || !(sp >= 0.0 && sp < 1.0)) return R4D_NO(RAD_E_INVAL); + long long tk = 0, hk = 0; + if (!r4d_head_rows(q, kHd, &c->R, &c->nh, &c->q_ld) || + !r4d_head_rows(k, kHd, &tk, &hk, &c->k_ld) || + ((c->q_ld | c->k_ld) & 7) || ((uintptr_t)q->data & 15) || ((uintptr_t)k->data & 15)) + return R4D_NO(RAD_E_STRIDE); + if (hk != c->nh || tk < c->R || c->R <= 0 || c->R > 0x7fffffffLL) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(segs) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + const long long ns = r4d_numel(segs) - 1; + if (ns < 1 || ns > 4096 || r4d_numel(geom) < 3) return R4D_NO(RAD_E_SHAPE); + c->n_seg = (int)ns; + c->patch = (int)patch; + c->sparsity = sp; + c->scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)kHd)); + return RAD_OK; +} + +// An operand of R rows of nh heads at its own pitch, 16-byte aligned. +bool vsa_rows(const RadTensor* t, long long R, long long nh, long long* ld) { + long long rows = 0, heads = 0; + return is_bf16(t) && r4d_head_rows(t, kHd, &rows, &heads, ld) && !(*ld & 7) && + !((uintptr_t)t->data & 15) && heads == nh && rows >= R; +} + +// sel [>= nh, tiles_cap, k_cap] i32 with unit stride on the last axis, and coarse +// [>= nh, >= tiles_cap, 128] bf16 likewise. +int vsa_sel(const RadTensor* sel, const RadTensor* coarse, long long nh, long long* tiles_cap, + long long* k_cap) { + if (!is_i32(sel) || (coarse && !is_bf16(coarse))) return R4D_NO(RAD_E_DTYPE); + if (sel->rank != 3 || sel->stride[2] != 1 || + (coarse && (coarse->rank != 3 || coarse->stride[2] != 1))) + return R4D_NO(RAD_E_STRIDE); + *tiles_cap = sel->shape[1]; + *k_cap = sel->shape[2]; + /* Tile numbers stay below 2^16 (the tile decode's multiply-high division). */ + if (sel->shape[0] < nh || *tiles_cap < 1 || *k_cap < 1 || *tiles_cap > 65536 || + *k_cap > 0x7fffffffLL) + return R4D_NO(RAD_E_SHAPE); + if (coarse && (coarse->shape[0] < nh || coarse->shape[1] < *tiles_cap || + coarse->shape[2] != kHd || ((uintptr_t)coarse->data & 15) || + (coarse->stride[1] & 7) || (coarse->stride[0] & 7))) + return R4D_NO(RAD_E_SHAPE); + return RAD_OK; +} + +} // namespace + +// ============================================================== the plugin ABI entry points +enum { VS_Q = 0, VS_K, VS_V, VS_SEGS, VS_GEOM, VS_SEL, VS_COARSE }; + +/* The scratch holds the q, k and v means of a group of heads, 1.5 KiB a (tile, head) at the + * layouts the select kernel reads. The hook sees neither the head count nor the selection's tile + * capacity, so it sizes for M / 4 (tile, head) slots; the entry point takes as many heads a group + * as fit (tiles_cap slots each) and refuses only when one does not. At 1344 x 768 (M 37.7K, + * tiles_cap up to ~1500) that is six heads a group. */ +extern "C" int64_t r4d_rad_vsa_select_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + return M * 384; +} + +extern "C" int r4d_rad_vsa_select(const RadArgs* a, RadStream s) { + const RadTensor *q = r4d_opt(a, VS_Q), *k = r4d_opt(a, VS_K), *v = r4d_opt(a, VS_V); + const RadTensor *segs = r4d_opt(a, VS_SEGS), *geom = r4d_opt(a, VS_GEOM); + const RadTensor *sel = r4d_opt(a, VS_SEL), *coarse = r4d_opt(a, VS_COARSE); + if (!q || !k || !segs || !geom || !sel) return R4D_NO(RAD_E_INVAL); + /* v is read only for the coarse branch: both or neither. */ + if ((v != nullptr) != (coarse != nullptr)) return R4D_NO(RAD_E_INVAL); + VsaCommon c; + int rc = vsa_common(a, q, k, segs, geom, &c); + if (rc != RAD_OK) return rc; + long long v_ld = 0, tiles_cap = 0, k_cap = 0; + if (v && !vsa_rows(v, c.R, c.nh, &v_ld)) return R4D_NO(RAD_E_STRIDE); + rc = vsa_sel(sel, coarse, c.nh, &tiles_cap, &k_cap); + if (rc != RAD_OK) return rc; + /* Two LDS budgets: eight query tiles a workgroup up to 1536 tiles, four up to 3072. */ + if (tiles_cap > 3072) return R4D_NO(RAD_E_SHAPE); + const long long per = tiles_cap * (coarse ? 1536 : 1024); + long long G = a->scratch && !((uintptr_t)a->scratch & 15) + ? std::min(c.nh, a->scratch_bytes / per) : 0; + if (G < 1) return R4D_NO(RAD_E_SCRATCH); + /* As many groups as the scratch needs, the heads spread evenly over them: a last group of a + * head or two would leave most of the card idle for its two launches. */ + const long long rounds = (c.nh + G - 1) / G; + G = (c.nh + rounds - 1) / rounds; + float4* kpT = (float4*)a->scratch; + float4* qp4 = (float4*)((char*)a->scratch + G * tiles_cap * 512); + float4* vp4 = coarse ? (float4*)((char*)a->scratch + G * tiles_cap * 1024) : nullptr; + const hipStream_t st = (hipStream_t)s; + for (long long h0 = 0; h0 < c.nh; h0 += G) { + const int g = (int)std::min(G, c.nh - h0); + hipLaunchKernelGGL(vsa_pool_kernel, dim3((unsigned)tiles_cap, (unsigned)((g + 3) / 4)), + dim3(128), 0, st, (const uint16_t*)q->data, (const uint16_t*)k->data, + v ? (const uint16_t*)v->data : nullptr, (int)c.q_ld, (int)c.k_ld, + (int)v_ld, (const int*)segs->data, c.n_seg, (const int*)geom->data, + c.patch, (int)c.R, (int)tiles_cap, (int)h0, g, kpT, qp4, vp4); +#define R4D_VSEL(QT, NMAX) \ + hipLaunchKernelGGL((vsa_select_kernel), \ + dim3((unsigned)((tiles_cap + QT - 1) / QT), (unsigned)g), dim3(256), 0, \ + st, (const int*)segs->data, c.n_seg, (const int*)geom->data, \ + c.patch, (int)c.R, (int)tiles_cap, c.sparsity, c.scale, (int)h0, \ + (const float4*)kpT, (const float4*)qp4, (const float*)vp4, \ + (int*)sel->data, (long long)sel->stride[0], \ + (long long)sel->stride[1], (int)k_cap, \ + coarse ? (uint16_t*)coarse->data : nullptr, \ + coarse ? (long long)coarse->stride[0] : 0LL, \ + coarse ? (long long)coarse->stride[1] : 0LL) + if (tiles_cap <= 1536) R4D_VSEL(8, 1536); + else R4D_VSEL(4, 3072); +#undef R4D_VSEL + const hipError_t e = hipGetLastError(); + if (e != hipSuccess) return st_of(e); + } + return RAD_OK; +} + +enum { VA_Q = 0, VA_K, VA_V, VA_SEGS, VA_GEOM, VA_SEL, VA_COARSE, VA_GATE, VA_OUT, VA_K8, VA_KS, + VA_VS }; + +extern "C" int r4d_rad_attn_vsa(const RadArgs* a, RadStream s) { + const RadTensor *q = r4d_opt(a, VA_Q), *k = r4d_opt(a, VA_K), *v = r4d_opt(a, VA_V); + const RadTensor *segs = r4d_opt(a, VA_SEGS), *geom = r4d_opt(a, VA_GEOM); + const RadTensor *sel = r4d_opt(a, VA_SEL), *coarse = r4d_opt(a, VA_COARSE); + const RadTensor *gate = r4d_opt(a, VA_GATE), *o = r4d_opt(a, VA_OUT); + if (!q || !k || !v || !segs || !geom || !sel || !o) return R4D_NO(RAD_E_INVAL); + /* The gated coarse term takes both. */ + if ((coarse != nullptr) != (gate != nullptr)) return R4D_NO(RAD_E_INVAL); + VsaCommon c; + int rc = vsa_common(a, q, k, segs, geom, &c); + if (rc != RAD_OK) return rc; + /* The fp8 P.V form (`pv` "fp8"): `v` as E4M3 codes [M, n_head * head_dim] and their column + * scales `v_scale` [n_head * head_dim], as quant_cols_fp8 writes them. */ + const RadTensor* vs = r4d_opt(a, VA_VS); + const char* pvs = r4d_gets(a, "pv"); + const bool pv8 = pvs && !std::strcmp(pvs, "fp8"); + if (pvs && !pv8 && std::strcmp(pvs, "bf16")) return R4D_NO(RAD_E_INVAL); + if (pv8 != (vs != nullptr)) return R4D_NO(RAD_E_INVAL); + long long v_ld = 0, o_ld = 0, g_ld = 0, tiles_cap = 0, k_cap = 0; + if (pv8) { + long long tv = 0, hv = 0; + if (v->dtype != RAD_F8E4M3 || vs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!r4d_head_rows(v, kHd, &tv, &hv, &v_ld) || (v_ld & 15) || ((uintptr_t)v->data & 15) || + !r4d_contig(vs) || ((uintptr_t)vs->data & 15)) + return R4D_NO(RAD_E_STRIDE); + if (hv != c.nh || tv < c.R || r4d_numel(vs) < c.nh * kHd) return R4D_NO(RAD_E_SHAPE); + } else if (!vsa_rows(v, c.R, c.nh, &v_ld)) { + return R4D_NO(RAD_E_STRIDE); + } + if (!vsa_rows(o, c.R, c.nh, &o_ld) || (gate && !vsa_rows(gate, c.R, c.nh, &g_ld))) + return R4D_NO(RAD_E_STRIDE); + rc = vsa_sel(sel, coarse, c.nh, &tiles_cap, &k_cap); + if (rc != RAD_OK) return rc; + /* The int8 Q.K form (`qk` "i8"): the key codes [R, n_head * head_dim] and their scales + * [R, n_head], as quant_act_i8g writes them at group head_dim. */ + const RadTensor *k8 = r4d_opt(a, VA_K8), *ks = r4d_opt(a, VA_KS); + const char* qk = r4d_gets(a, "qk"); + const bool i8 = qk && !std::strcmp(qk, "i8"); + if (qk && !i8 && std::strcmp(qk, "bf16")) return R4D_NO(RAD_E_INVAL); + if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return R4D_NO(RAD_E_INVAL); + long long k8_ld = 0, ks_ld = 0; + if (i8) { + if (k8->dtype != RAD_I8 || ks->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + long long t8 = 0, h8 = 0, ts = 0; + if (!r4d_head_rows(k8, kHd, &t8, &h8, &k8_ld) || (k8_ld & 15) || ((uintptr_t)k8->data & 15)) + return R4D_NO(RAD_E_STRIDE); + ks_ld = r4d_rows_pitch(ks, c.nh, &ts); + if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (h8 != c.nh || t8 < c.R || ts < c.R) return R4D_NO(RAD_E_SHAPE); + } + /* Two query tiles a workgroup (see vsa_attn_kernel). */ + constexpr int NQT = 2; +#define R4D_VATT(I8, PV8) \ + hipLaunchKernelGGL((vsa_attn_kernel), \ + dim3((unsigned)((tiles_cap + NQT - 1) / NQT), (unsigned)c.nh), \ + dim3(NQT * 128), 0, (hipStream_t)s, (const uint16_t*)q->data, \ + (const uint16_t*)k->data, (const uint16_t*)v->data, (uint16_t*)o->data, \ + coarse ? (const uint16_t*)coarse->data : nullptr, \ + gate ? (const uint16_t*)gate->data : nullptr, (const int*)segs->data, \ + c.n_seg, (const int*)geom->data, c.patch, (int)c.R, (int)tiles_cap, \ + c.sparsity, (const int*)sel->data, (long long)sel->stride[0], \ + (long long)sel->stride[1], (int)k_cap, \ + coarse ? (long long)coarse->stride[0] : 0LL, \ + coarse ? (long long)coarse->stride[1] : 0LL, c.scale, (int)c.q_ld, \ + (int)c.k_ld, (int)v_ld, (int)g_ld, (int)o_ld, \ + i8 ? (const int8_t*)k8->data : nullptr, \ + i8 ? (const float*)ks->data : nullptr, (int)k8_ld, (int)ks_ld, \ + pv8 ? (const float*)vs->data : nullptr) + if (i8) { + if (pv8) R4D_VATT(true, true); + else R4D_VATT(true, false); + } else { + if (pv8) R4D_VATT(false, true); + else R4D_VATT(false, false); + } +#undef R4D_VATT + return st_of(hipGetLastError()); +} diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index baa88781..b8fed97e 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -264,9 +264,15 @@ int ref_attn_dense(const RadArgs* a, RadStream) { * itself (a chunked encoder's windows). `cu_div` reads cu_seqlens in units of that many rows: * a segment is rows [cu[s] / cu_div, cu[s+1] / cu_div). */ const int64_t window = p_int(a, "window", 0); + /* Non-causal only: the window's right side, key j visible when j - i < window_right; 0 is + * `window`'s. A sliding encoder layer that sees `l` keys behind and `r` ahead is window l + 1, + * window_right r + 1. */ + const int64_t wright = p_int(a, "window_right", 0); const int64_t block = p_int(a, "block", 0); const int64_t cdiv = p_int(a, "cu_div", 1); - if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE; + if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0 || wright < 0 || + (wright > 0 && (causal || window == 0))) + return RAD_E_SHAPE; if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED; /* [tokens, heads, head_dim], or [tokens, heads * head_dim] as a column slice of a fused @@ -308,7 +314,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) { int64_t jbeg = b0, jend = causal ? (i + 1) : b1; if (window > 0) { jbeg = std::max(b0, i - window + 1); - if (!causal) jend = std::min(b1, i + window); + if (!causal) jend = std::min(b1, i + (wright > 0 ? wright : window)); } if (block > 0) { const int64_t blk = b0 + (i - b0) / block * block; @@ -477,6 +483,15 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, } } +/* A position as the rotation reads it, divided by the position scale in f32: an integer operand's + * value, or a float operand's own value (a fractional coordinate, such as a video decoder's + * normalised grid already multiplied by 2 pi). */ +static inline float rope_pos(const RadTensor* pos, int64_t off, float div) { + const uint32_t dt = pos->dtype; + const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16; + return (flt ? ld_dt(dt, pos->data, off) : (float)ld_int(dt, pos->data, off)) / div; +} + /* "11 11 10" -> {11, 11, 10}. Absent is no sections. */ static int rope_sections(const RadArgs* a, int64_t* sec) { const char* v = p_str(a, "sections", nullptr); @@ -551,6 +566,12 @@ int ref_rope(const RadArgs* a, RadStream) { if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED; for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i); } + const RadLlama3 l3 = rad_llama3_args(a); + if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL; + if (l3.factor != 0.0f) { + if (mode == ROPE_AXIAL || multi) return RAD_E_UNSUPPORTED; + for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = l3.frequency(f.inv[i]); + } for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f; const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; @@ -564,10 +585,9 @@ int ref_rope(const RadArgs* a, RadStream) { float p[8]; const float div = rscale != 0.0f ? rscale : 1.0f; if (multi) { - for (int64_t c = 0; c < n_comp; ++c) - p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div; + for (int64_t c = 0; c < n_comp; ++c) p[c] = rope_pos(pos, c * pcs + m * pms, div); } else { - const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div; + const float one = rope_pos(pos, offlin(pos, m), div); for (int c = 0; c < 8; ++c) p[c] = one; } const int64_t row = m * rs; @@ -581,14 +601,16 @@ int ref_rope(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ qk_norm_rope */ /* QK-norm and rotation in one op: an RMS norm over each head_dim-wide q and k head against its own * gain vector, then RoPE. `v_norm` 1 also RMS-norms each v head with unit gain and no rotation - * (Gemma 4's weightless value norm); otherwise v heads are untouched. + * (Gemma 4's weightless value norm); otherwise v heads are untouched. An absent gain is a unit + * gain, without `wadd` (a video decoder's weightless q and k norms); `rotary_dim` 0 is the norm + * alone, and then `positions` may be absent. * * The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does; * libr4d's r4d_qk_norm_rope_gate matches this. A fused kernel keeping f32 across the seam would be * half a ULP better and fail the comparison. */ int ref_qk_norm_rope(const RadArgs* a, RadStream) { - if (!have(a, 4)) return RAD_E_INVAL; - const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3]; + if (a->n_t < 4 || !t_in(a, 0)) return RAD_E_INVAL; + const RadTensor *qkv = &a->t[0], *pos = t_in(a, 1), *qw = t_in(a, 2), *kw = t_in(a, 3); const int64_t head_dim = p_int(a, "head_dim", 0); const int64_t n_head = p_int(a, "n_head", 0); @@ -600,16 +622,21 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const int v_norm = (int)p_int(a, "v_norm", 0); /* `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j, start + 2j + 1): * the complex-number form of Qwen-Image's 3-axis rotary. `imrope` is `rope`'s interleaved - * M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). */ - static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" }; - const int mode = p_enum(a, "mode", kModes, 5, 0); + * M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). `axial` is `rope`'s axial + * form (a 3-axis video rotary over NeoX pairs), its section ladders applied with rank-1 + * positions too, every component then being that one position. */ + static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" }; + const int mode = p_enum(a, "mode", kModes, 6, 0); if (mode < 0) return RAD_E_UNSUPPORTED; const bool blocks = mode == 2 || mode == 3; const bool adjacent = mode == 3; const bool im = mode == 4; + const bool axial = mode == 5; int64_t rot = p_int(a, "rotary_dim", head_dim); - if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; - if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE; + if (head_dim <= 0 || n_head <= 0 || rot < 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; + if ((qw && numel(qw) < head_dim) || (kw && numel(kw) < head_dim)) return RAD_E_SHAPE; + const bool turn = rot > 0; + if (turn && !pos) return RAD_E_INVAL; /* Blocks: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired * (start + j, start + sec[c] + j) and turned by position component comps[c] at @@ -617,11 +644,11 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { * rotated prefix exactly. Positions are [C, M], component-major. */ int64_t sec[8] = {}, comp[8] = {}; int n_sec = 0; - if (im) { + if (turn && (im || axial)) { n_sec = rope_sections(a, sec); - if (n_sec < 3) return RAD_E_SHAPE; + if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE; } - if (blocks) { + if (turn && blocks) { n_sec = rope_sections(a, sec); if (n_sec <= 0) return RAD_E_SHAPE; int64_t total = 0; @@ -639,23 +666,31 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { if (k != n_sec) return RAD_E_SHAPE; } } - const bool multi = pos->rank >= 2; + const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; + const bool multi = pos && pos->rank >= 2; const int64_t n_comp = multi ? pos->shape[0] : 1; - const int64_t M = multi ? pos->shape[1] : numel(pos); - if (multi && !blocks && !im) return RAD_E_SHAPE; - if (multi && im && n_comp < 3) return RAD_E_SHAPE; - for (int c = 0; blocks && c < n_sec; ++c) - if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE; + const int64_t M = !pos ? rows_of(qkv, stride_row) : multi ? pos->shape[1] : numel(pos); + if (turn) { + if (multi && !blocks && !im && !axial) return RAD_E_SHAPE; + if (multi && im && n_comp < 3) return RAD_E_SHAPE; + if (multi && axial && n_comp < n_sec) return RAD_E_SHAPE; + for (int c = 0; blocks && c < n_sec; ++c) + if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE; + } const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; - const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; const int64_t rs = row_stride(qkv, stride_row); const int64_t ds = laststride(qkv); RopeFreq f; /* No `ladder` parameter here: the fused norm+rope measures by `rot`. */ - if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f)); - else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f)); + if (turn && im) + RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f)); + else if (turn && axial) + RAD_REF_TRY(rope_freqs(ROPE_AXIAL, rot, rot, theta, sec, n_sec, &f)); + else if (turn) + RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f)); + const int pair_mode = im ? (int)ROPE_IMROPE : axial ? (int)ROPE_AXIAL : mode; /* RMS-norms one head in place, against gain `w` (+ wadd), or unit gain without one. */ auto norm_head = [&](int64_t base, const RadTensor* w) { @@ -675,19 +710,20 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { for (int64_t m = 0; m < M; ++m) { float p[8]; const float div = rscale != 0.0f ? rscale : 1.0f; - if (multi) { + if (turn && multi) { for (int64_t c = 0; c < n_comp && c < 8; ++c) - p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div; - } else { - const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div; + p[c] = rope_pos(pos, c * pcs + m * pms, div); + } else if (turn) { + const float one = rope_pos(pos, offlin(pos, m), div); for (int c = 0; c < 8; ++c) p[c] = one; } const int64_t row = m * rs; for (int64_t h = 0; h < n_head + n_head_kv; ++h) { const int64_t base = row + h * head_dim * ds; norm_head(base, h < n_head ? qw : kw); + if (!turn) continue; if (!blocks) { - rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p); + rope_head(qkv, base, ds, rot, pair_mode, f, p); continue; } int64_t start = 0; diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp new file mode 100644 index 00000000..c4d4357c --- /dev/null +++ b/libref/ref_audio.cpp @@ -0,0 +1,728 @@ +/* ref_audio.cpp -- the audio generator's ops (docs/OPS.md, "Audio generation"). + * + * An audio generator writes a piece frame by frame with a language model and a depth decoder over + * residual codebooks, sampled with guidance between branches; a denoiser turns runs of frames + * (windows) into latents; a vocoder of 1-D convolutions plays them. These are the ops that are not + * already a language model's or an image generator's. + * + * Rounding follows the reference models, which run in bf16 and round every tensor they + * materialise; where an op stands for several reference tensors, the libref function says which + * roundings it keeps. Per-pass extents (a window's latents, a sequence's rows) come from the + * operands; parameters are fixed at declare. + */ +#include "ref_common.h" +#include "ref_ops.h" +#include "rad_philox.h" + +#include +#include +#include +#include + +using namespace ref; + +namespace { + +/* A window entry's flags (RadAudioGenBatch, RAD_AGEN_F_*), restated because a kernel library + * compiles against rad_abi.h, not the run phase's header. */ +enum { kFirst = 1, kLast = 8, kJoin = 16 }; + +inline float rbf(float v) { return round_dt(RAD_BF16, v); } + +/* The Philox stream an audio window's noise is drawn from, and the one a frame's picks are. */ +inline uint64_t window_stream(int64_t k) { return 1 + (uint64_t)k; } +inline uint64_t frame_stream(int64_t f) { return ((uint64_t)1 << 32) + (uint64_t)f; } + +inline uint64_t seed_at(const RadTensor* s, int64_t i) { + return (uint64_t)(uint32_t)ld_int(s->dtype, s->data, offlin(s, 2 * i)) | + ((uint64_t)(uint32_t)ld_int(s->dtype, s->data, offlin(s, 2 * i + 1)) << 32); +} + +inline int64_t ldi(const RadTensor* t, int64_t i) { + return ld_int(t->dtype, t->data, offlin(t, i)); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ conv1d */ +/* A 1-D convolution over sequences of rows, channels innermost: x [rows, cin], y [rows, cout], + * `cu_seqlens` bounding each sequence (row indices of both operands, as every sequenced op reads + * them), outside of which the input reads zero (each sequence is padded on its own). w is + * PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding + * dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it, + * dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none, + * tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */ +int ref_conv1d(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2]; + const RadTensor *res = t_in(a, 3), *y = &a->t[4], *b = t_in(a, 5); + if (!y->data) return RAD_E_INVAL; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0); + const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0); + const char* act = p_str(a, "act", "none"); + const bool tanh_out = act && !std::strcmp(act, "tanh"); + const bool clamp_out = act && !std::strcmp(act, "clamp"); + if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL; + if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || + causal < 0 || causal > 1) + return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE; + if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE; + if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE; + const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2; + REF_PAR_FOR((r1 - r0) * cout * cin * k) + for (int64_t r = r0; r < r1; ++r) { + const int64_t e = seq_of(cu, n_seq, r); + const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1); + const int64_t yb = rowoff(y, r, cout), ys = laststride(y); + for (int64_t co = 0; co < cout; ++co) { + float acc = 0.0f; + for (int64_t kk = 0; kk < k; ++kk) { + const int64_t ir = r + kk * dil - pad; + if (ir < s0 || ir >= s1) continue; + const int64_t xb = rowoff(x, ir, cin), xs = laststride(x); + for (int64_t ci = 0; ci < cin; ++ci) + acc += ldt(w, (co * cin + ci) * k + kk) * ldt(x, xb + ci * xs); + } + if (b) acc += ldt(b, co); + if (res) acc += ldt(res, rowoff(res, r, cout) + co * laststride(res)); + if (tanh_out) acc = ref_tanh(acc); + if (clamp_out) acc = acc < -1.0f ? -1.0f : (acc > 1.0f ? 1.0f : acc); + stt(y, yb + co * ys, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv_t1d */ +/* A transposed 1-D convolution of kernel `k` >= stride (2 stride by default) and padding `pad` + * ((k - stride) / 2 by default, which needs k - stride even; 0 is the causal form, the full + * output's last k - stride rows dropped), so each sequence grows exactly `stride` times: x + * [rows, cin] in sequences `cu_seqlens`, y [rows * stride, cout] in the same sequences scaled. w + * is PyTorch's ConvTranspose1d weight [cin, cout, k], b [cout]; sequence e is input rows + * [cu[e], cu[e+1]) and output rows [stride cu[e], stride cu[e+1]). Output row o of a sequence + * reads every input row i of the same sequence with 0 <= (o + pad) - i stride < k: with + * q = (o + pad) / stride and r = (o + pad) % stride, the taps t = 0, 1, .. while r + t stride < k, + * y[o] = b + sum_t x[q - t] w[:, :, r + t stride], in that order. f32 accumulation, one + * rounding. */ +int ref_conv_t1d(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *cu = &a->t[3], *y = &a->t[4]; + const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), s = p_int(a, "stride", 0); + /* Without `pad`, the symmetric (k - stride) / 2, which needs k - stride even. */ + const int64_t K = p_int(a, "k", 2 * s), pad = p_int(a, "pad", -1); + const int64_t P = pad >= 0 ? pad : (K - s) / 2; + if (cin <= 0 || cout <= 0 || s <= 0 || K < s || (pad < 0 && ((K - s) & 1))) return RAD_E_SHAPE; + const int64_t taps = (K + s - 1) / s; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(x, cin) < r1 || rows_of(y, cout) < r1 * s) return RAD_E_SHAPE; + if (numel(w) < cin * cout * K || numel(b) < cout) return RAD_E_SHAPE; + REF_PAR_FOR((r1 - r0) * s * cout * cin * taps) + for (int64_t o = r0 * s; o < r1 * s; ++o) { + const int64_t e = seq_of(cu, n_seq, o / s); + const int64_t i0 = cu_at(cu, e), i1 = cu_at(cu, e + 1); + const int64_t lo = o - i0 * s; /* the output row within its sequence */ + const int64_t q = (lo + P) / s, rr = (lo + P) % s; + const int64_t yb = rowoff(y, o, cout), ys = laststride(y); + for (int64_t co = 0; co < cout; ++co) { + float acc = ldt(b, co); + for (int64_t t = 0; rr + t * s < K; ++t) { + const int64_t qi = q - t, tap = rr + t * s; + if (qi < 0 || i0 + qi >= i1) continue; + const int64_t xb = rowoff(x, i0 + qi, cin), xs = laststride(x); + for (int64_t ci = 0; ci < cin; ++ci) + acc += ldt(w, (ci * cout + co) * K + tap) * ldt(x, xb + ci * xs); + } + stt(y, yb + co * ys, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ snake */ +/* Snake, per channel: y = x + sin(alpha x)^2 / (alpha + 1e-9), alpha [n]. With `beta` [n], the + * SnakeBeta form y = x + (1 / (beta + 1e-9)) sin(alpha x)^2. With `log` 1 both are stored as their + * logarithms and exponentiated first, as the reference does each pass. f32, one rounding. */ +int ref_snake(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *al = &a->t[1], *y = &a->t[2], *be = t_in(a, 3); + const int64_t n = p_int(a, "n", 0), lg = p_int(a, "log", 0); + if (n <= 0 || numel(al) < n || (be && numel(be) < n) || lg < 0 || lg > 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) { + const float v = ldt(x, xb + c * xs); + const float al_c = lg ? ref_exp(ldt(al, c)) : ldt(al, c); + const float sn = ref_sin(v * al_c); + if (be) { + const float b_c = lg ? ref_exp(ldt(be, c)) : ldt(be, c); + stt(y, yb + c * ys, v + 1.0f / (b_c + 1e-9f) * (sn * sn)); + } else { + stt(y, yb + c * ys, v + sn * sn / (al_c + 1e-9f)); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ snake_aa */ +/* BigVGAN's alias-free SnakeBeta over each sequence (diffusers' MiniMaxH3AudioActivation1d: + * UpSample1d, SnakeBeta, DownSample1d), rows samples and channels innermost, all in f32. Per + * channel c of a sequence of L rows: + * + * xp the sequence replicate-padded by P = k / ratio - 1 rows on each side + * u ratio * conv_transpose1d(xp, f_up, stride ratio), cropped by P ratio + (k - ratio) / 2 + * rows at the start and P ratio + (k - ratio + 1) / 2 at the end, so L ratio rows remain: + * u_full[o] = sum over input rows i with 0 <= o - i ratio < k of f_up[o - i ratio] xp[i], + * in ascending i + * a u + (1 / (B + 1e-9)) sin(A u)^2, A = exp(alpha[c]) and B = exp(beta[c]) with `log` 1 + * (alpha[c] and beta[c] themselves otherwise), as `snake` evaluates it + * y[o] sum over j < k of f_down[j] ap[o ratio + j] in ascending j, ap being a replicate-padded + * by k / 2 rows on the right and k / 2 on the left less one for an even k + * + * so a sequence keeps its length. f_up and f_down are the checkpoint's [1, 1, k] Kaiser filters, + * read for every channel. */ +int ref_snake_aa(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *al = &a->t[1], *be = &a->t[2], *fu = &a->t[3]; + const RadTensor *fd = &a->t[4], *cu = &a->t[5], *y = &a->t[6]; + const int64_t n = p_int(a, "n", 0), R = p_int(a, "ratio", 0), k = p_int(a, "k", 0); + const int64_t lg = p_int(a, "log", 0); + if (n <= 0 || R <= 0 || k < R || lg < 0 || lg > 1) return RAD_E_SHAPE; + if (numel(al) < n || numel(be) < n || numel(fu) < k || numel(fd) < k) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); + if (r0 < 0 || r1 <= r0 || rows_of(x, n) < r1 || rows_of(y, n) < r1) return RAD_E_SHAPE; + const int64_t P = k / R - 1, crop = P * R + (k - R) / 2, pl = k / 2 - (k % 2 == 0 ? 1 : 0); + std::vector fup((size_t)k), fdn((size_t)k); + for (int64_t j = 0; j < k; ++j) { + fup[(size_t)j] = ldt(fu, offlin(fu, j)); + fdn[(size_t)j] = ldt(fd, offlin(fd, j)); + } + REF_PAR_FOR_DYN((r1 - r0) * n * k * 4) + for (int64_t ec = 0; ec < n_seq * n; ++ec) { + const int64_t e = ec / n, c = ec % n; + const int64_t s0 = cu_at(cu, e), L = cu_at(cu, e + 1) - s0; + if (L <= 0) continue; + const float A = lg ? ref_exp(ldt(al, c)) : ldt(al, c); + const float B = lg ? ref_exp(ldt(be, c)) : ldt(be, c); + /* Row i of the padded sequence. */ + auto xp = [&](int64_t i) { + const int64_t q = std::min(std::max(i - P, 0), L - 1); + return ldt(x, rowoff(x, s0 + q, n) + c * laststride(x)); + }; + std::vector act((size_t)(L * R)); + for (int64_t m = 0; m < L * R; ++m) { + const int64_t o = crop + m; + const int64_t i_lo = o < k ? 0 : (o - k) / R + 1; + const int64_t i_hi = std::min(o / R, L + 2 * P - 1); + float acc = 0.0f; + for (int64_t i = i_lo; i <= i_hi; ++i) acc += fup[(size_t)(o - i * R)] * xp(i); + const float u = (float)R * acc; + const float sn = ref_sin(u * A); + act[(size_t)m] = u + 1.0f / (B + 1e-9f) * (sn * sn); + } + for (int64_t o = 0; o < L; ++o) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const int64_t m = std::min(std::max(o * R + j - pl, 0), L * R - 1); + acc += fdn[(size_t)j] * act[(size_t)m]; + } + stt(y, rowoff(y, s0 + o, n) + c * laststride(y), acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ cfg_topk_sample */ +/* One pick per lane from `rep` branch rows of logits (rows rep i .. rep i + rep - 1 are lane i's + * branches, the conditional first), with guidance: g = u + cfg (c - u) between the first two + * branches, or c alone when rep is 1; `cfg` [n] f32, when bound, is each lane's guidance in place + * of the parameter. With `penalty` (the repetition penalty) and a lane's history `hist` + * [lanes, n_vocab] i32 (`lane` [n] naming the row), every id the history holds has its g divided + * by the penalty when positive and multiplied by it otherwise; frame 0 clears the lane's row + * first, and the pick is recorded in it. Ids in [sup_lo, sup_hi) are never candidates. With + * `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates + * the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and + * drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream). + * The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or + * bf16; seed [n, 2]; frame [n]. */ +int ref_cfg_topk_sample(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *lg = &a->t[0], *seed = &a->t[1], *fr = &a->t[2], *ids = &a->t[3]; + const RadTensor *cfgs = t_in(a, 4), *lane = t_in(a, 5), *hist = t_in(a, 6); + const int64_t V = p_int(a, "n_vocab", 0), K = p_int(a, "k", 0), rep = p_int(a, "rep", 1); + const int64_t ck = p_int(a, "cond_k", 0), stream = p_int(a, "stream", 0); + const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0); + const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f); + const float pen = p_f32(a, "penalty", 1.0f); + if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) || + sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane)) + return RAD_E_SHAPE; + const int64_t n = numel(ids) / rep; + if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n || + (cfgs && numel(cfgs) < n) || (lane && numel(lane) < n)) + return RAD_E_SHAPE; + std::vector g((size_t)V), c((size_t)V); + std::vector idx((size_t)V); + for (int64_t i = 0; i < n; ++i) { + const int64_t cb = rowoff(lg, rep * i, V), cs = laststride(lg); + for (int64_t j = 0; j < V; ++j) c[(size_t)j] = ldt(lg, cb + j * cs); + if (rep == 2) { + const float gi = cfgs ? ldt(cfgs, offlin(cfgs, i)) : cfg; + const int64_t ub = rowoff(lg, rep * i + 1, V); + for (int64_t j = 0; j < V; ++j) { + const float u = ldt(lg, ub + j * cs); + g[(size_t)j] = u + gi * (c[(size_t)j] - u); + } + } else { + g = c; + } + /* The lane's history: cleared at its first frame, then each id it holds penalised. */ + int64_t hb = -1; + if (hist) { + const int64_t L = ldi(lane, i); + if (L < 0 || (L + 1) * V > numel(hist)) return RAD_E_SHAPE; + hb = L * V; + if (ldi(fr, i) == 0) + for (int64_t j = 0; j < V; ++j) + st_int(hist->dtype, hist->data, offlin(hist, hb + j), 0); + for (int64_t j = 0; j < V; ++j) + if (ldi(hist, hb + j) != 0) { + float& v = g[(size_t)j]; + v = v > 0.0f ? v / pen : v * pen; + } + } + /* The candidates: every entry outside the suppressed range, or those at or above the + * conditional's ck-th largest. */ + int64_t nc = 0; + auto open = [&](int64_t j) { return j < sup_lo || j >= sup_hi; }; + if (ck > 0) { + std::vector cc = c; + std::nth_element(cc.begin(), cc.begin() + (ck - 1), cc.end(), std::greater()); + const float thr = cc[(size_t)(ck - 1)]; + for (int64_t j = 0; j < V; ++j) + if (c[(size_t)j] >= thr && open(j)) idx[(size_t)nc++] = j; + } else { + for (int64_t j = 0; j < V; ++j) + if (open(j)) idx[(size_t)nc++] = j; + } + if (nc == 0) return RAD_E_SHAPE; + const int64_t kk = std::min(K, nc); + std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc, + [&](int64_t p, int64_t q) { + return g[(size_t)p] > g[(size_t)q] || + (g[(size_t)p] == g[(size_t)q] && p < q); + }); + const float m = g[(size_t)idx[0]] / temp; + double tot = 0; + std::vector e((size_t)kk); + for (int64_t t = 0; t < kk; ++t) { + e[(size_t)t] = std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)); + tot += e[(size_t)t]; + } + const double u = (double)rad_philox_uniform_s(seed_at(seed, i), frame_stream(ldi(fr, i)), + (uint64_t)stream) * tot; + int64_t pick = idx[(size_t)(kk - 1)]; + double acc = 0; + for (int64_t t = 0; t < kk; ++t) { + acc += e[(size_t)t]; + if (u < acc) { pick = idx[(size_t)t]; break; } + } + for (int64_t r = 0; r < rep; ++r) + st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick); + if (hist) st_int(hist->dtype, hist->data, offlin(hist, hb + pick), 1); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ rvq_embed */ +/* A frame's embedding from its residual codes: codes [n_codes, rows] (code-major, so each + * codebook's picks are one dense row), t0 the first codebook's table read at code + off0, t1 the + * other codebooks' stacked tables, codebook k (k >= 1) at code + (k - 1) vocab. As the reference + * rounds its tensors: y = bf16(bf16(t0[.] + bf16(sum_k t1[.])) * scale); with `round` 1 the whole + * sum is one f32 accumulation in codebook order, times scale, rounded once to y's dtype (a sum of + * every codebook's embedding, as torch's sum over the codebook axis rounds). A first code outside + * t0 leaves its row unwritten; a later code outside t1 adds nothing. */ +int ref_rvq_embed(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *codes = &a->t[0], *t0 = &a->t[1], *t1 = &a->t[2], *y = &a->t[3]; + const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0); + const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0); + const float scale = p_f32(a, "scale", 1.0f); + const int64_t round1 = p_int(a, "round", 0); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, D); + if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE; + const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D); + /* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */ + const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows; + const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + REF_PAR_FOR(rows * D * K) + for (int64_t r = 0; r < rows; ++r) { + const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0; + if (c0 < 0 || c0 >= r0) continue; + std::vector acc((size_t)D, 0.0f); + const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D); + if (round1) + for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0)); + for (int64_t k = 1; k < K; ++k) { + const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc; + if (ck < 0 || ck >= r1) continue; + const int64_t tb = rowoff(t1, ck, D); + for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1)); + } + for (int64_t d = 0; d < D; ++d) { + const float s = round1 ? acc[(size_t)d] + : rbf(ldt(t0, b0 + d * laststride(t0)) + rbf(acc[(size_t)d])); + stt(y, yb + d * laststride(y), s * scale); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ frame_mix_store */ +/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale)) + * with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row + * rep i of each plane belonging to lane[i]'s frame[i] (a plane holds every branch's row, the + * conditional first). Stored at dst[lane * stride + frame - 1] when frame >= 1 and + * status[lane] >= 0 (frame 0 only moves past the prompt; a negative status ended the piece). */ +int ref_frame_mix_store(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + const RadTensor *hid = &a->t[0], *lw = &a->t[1], *sc = &a->t[2], *lane = &a->t[3]; + const RadTensor *fr = &a->t[4], *st = &a->t[5], *dst = &a->t[6]; + const int64_t D = p_int(a, "n_embd", 0), L = p_int(a, "L", 0), stride = p_int(a, "stride", 0); + const int64_t rep = p_int(a, "rep", 1); + if (D <= 0 || L <= 0 || stride <= 0 || rep < 1 || numel(lw) < L || numel(sc) < 1) + return RAD_E_SHAPE; + const int64_t n = numel(lane), plane = rows_of(hid, D) / L; + if (n <= 0 || plane < rep * n || numel(fr) < n) return RAD_E_SHAPE; + std::vector wl((size_t)L); + float mx = -INFINITY; + for (int64_t l = 0; l < L; ++l) { + wl[(size_t)l] = rbf(ldt(lw, l)); + mx = std::max(mx, wl[(size_t)l]); + } + double tot = 0; + for (int64_t l = 0; l < L; ++l) tot += std::exp((double)(wl[(size_t)l] - mx)); + for (int64_t l = 0; l < L; ++l) + wl[(size_t)l] = rbf((float)(std::exp((double)(wl[(size_t)l] - mx)) / tot)); + const float scale = rbf(ldt(sc, 0)); + const int64_t drows = rows_of(dst, D); + for (int64_t i = 0; i < n; ++i) { + const int64_t ln = ldi(lane, i), f = ldi(fr, i); + if (f < 1 || ln < 0 || ln >= numel(st) || ldi(st, ln) < 0) continue; + const int64_t row = ln * stride + f - 1; + if (f > stride || row >= drows) return RAD_E_SHAPE; + const int64_t yb = rowoff(dst, row, D); + for (int64_t d = 0; d < D; ++d) { + float acc = 0.0f; + for (int64_t l = 0; l < L; ++l) + acc += wl[(size_t)l] * + ldt(hid, rowoff(hid, l * plane + rep * i, D) + d * laststride(hid)); + stt(dst, yb + d * laststride(dst), rbf(acc) * scale); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ end_status */ +/* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end` + * (the model ended the piece), else the pick. */ +int ref_end_status(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *ids = &a->t[0], *lane = &a->t[1], *st = &a->t[2]; + const int64_t end = p_int(a, "end", -1), rep = p_int(a, "rep", 1); + const int64_t n = numel(lane); + if (n <= 0 || rep < 1 || numel(ids) < rep * n) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t ln = ldi(lane, i), v = ldi(ids, rep * i); + if (ln < 0 || ln >= numel(st)) return RAD_E_SHAPE; + st_int(st->dtype, st->data, offlin(st, ln), v == end ? -1 : v); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ frame_store */ +/* A frame's codes into its lane's history: dst[(lane[i] n_codes + k) stride + frame[i] - skip] = + * codes[k, rep i] for every k, when frame[i] >= skip and status[lane[i]] >= 0. codes is code-major + * [n_codes, rows] (a codebook's picks one row, each lane's `rep` times); dst [lanes * n_codes, + * stride] holds each lane's codebooks as rows over its frames, so a run of frames is a block. */ +int ref_frame_store(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *codes = &a->t[0], *lane = &a->t[1], *fr = &a->t[2], *st = &a->t[3]; + const RadTensor *dst = &a->t[4]; + const int64_t K = p_int(a, "n_codes", 0), stride = p_int(a, "stride", 0); + const int64_t rep = p_int(a, "rep", 1), skip = p_int(a, "skip", 0); + if (K <= 0 || stride <= 0 || rep < 1 || skip < 0) return RAD_E_SHAPE; + const int64_t n = numel(lane); + if (n <= 0 || numel(fr) < n || numel(codes) < K * rep * n) return RAD_E_SHAPE; + const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rep * n; + const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + for (int64_t i = 0; i < n; ++i) { + const int64_t L = ldi(lane, i), f = ldi(fr, i) - skip; + if (L < 0 || L >= numel(st)) return RAD_E_SHAPE; + if (f < 0 || ldi(st, L) < 0) continue; + if (f >= stride || (L + 1) * K * stride > numel(dst)) return RAD_E_SHAPE; + for (int64_t k = 0; k < K; ++k) + st_int(dst->dtype, dst->data, offlin(dst, (L * K + k) * stride + f), + ld_int(codes->dtype, codes->data, k * kp + rep * i * rp)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ resample_nearest */ +/* Rows resampled nearest-neighbour as torch's interpolate(mode="nearest") does, in f32: output row + * j reads input row min(floor(j * (in / out)), in - 1), `in` and `out` the operands' row counts. */ +int ref_resample_nearest(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t in = rows_of(x, n), out = rows_of(y, n); + if (in <= 0 || out <= 0) return RAD_E_SHAPE; + const float scale = (float)in / (float)out; + for (int64_t j = 0; j < out; ++j) { + const int64_t src = std::min((int64_t)std::floor((float)j * scale), in - 1); + const int64_t xb = rowoff(x, src, n), yb = rowoff(y, j, n); + for (int64_t c = 0; c < n; ++c) + stt(y, yb + c * laststride(y), ldt(x, xb + c * laststride(x))); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ fourier_embed */ +/* Random Fourier features of a time in [0, 1]: y = [cos(2 pi t w) | sin(2 pi t w)], w [n / 2] + * (a trained projection). With `round` 1 every tensor the bf16 reference holds is rounded: t, then + * bf16(2 pi t), then the product with w, then each cosine and sine. t is f32 [M]. */ +int ref_fourier_embed(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *t = &a->t[0], *w = &a->t[1], *y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + const bool rnd = p_int(a, "round", 0) != 0; + if (n <= 0 || (n & 1) || numel(w) < n / 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE; + const float two_pi = 6.28318530717958647692f; + for (int64_t r = 0; r < rows; ++r) { + float tv = ldt(t, offlin(t, r)); + if (rnd) tv = rbf(rbf(tv) * two_pi); + else tv *= two_pi; + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t i = 0; i < n / 2; ++i) { + float ang = tv * ldt(w, i); + if (rnd) ang = rbf(ang); + stt(y, yb + i * ys, ref_cos(ang)); + stt(y, yb + (n / 2 + i) * ys, ref_sin(ang)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_input */ +/* A denoiser's input rows for its window entries: entry e's latent rows (lat_cu) are + * [lat | zeros | cond] from lane win_lane[e] of the latent state `lat` [lanes * stride, n_lat] and + * of the window conditioning `cond` [lanes * stride, n_cond], `stride` rows a lane. An entry + * that is an unconditional branch (pair -2) takes zeros for its conditioning. + * y [rows, n_lat + n_zero + n_cond]. */ +int ref_win_input(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *lat = &a->t[0], *cond = &a->t[1], *lcu = &a->t[2], *wl = &a->t[3]; + const RadTensor *pair = &a->t[4], *y = &a->t[5]; + const int64_t C = p_int(a, "n_lat", 0), Z = p_int(a, "n_zero", 0), D = p_int(a, "n_cond", 0); + const int64_t stride = p_int(a, "stride", 0), W = C + Z + D; + if (C <= 0 || Z < 0 || D <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(wl) < S || numel(pair) < S) return RAD_E_SHAPE; + if (rows_of(y, W) < cu_at(lcu, S)) return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + const int64_t L = ldi(wl, e), neg = ldi(pair, e) == -2; + const int64_t b0 = cu_at(lcu, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, C) || + (len > 0 && (b0 < 0 || b0 + len > rows_of(y, W))) || + (len > 0 && !neg && (L + 1) * stride > rows_of(cond, D))) + return RAD_E_SHAPE; + for (int64_t k = 0; k < len; ++k) { + const int64_t yb = rowoff(y, b0 + k, W), ys = laststride(y); + const int64_t lb = rowoff(lat, L * stride + k, C); + for (int64_t c = 0; c < C; ++c) stt(y, yb + c * ys, ldt(lat, lb + c * laststride(lat))); + for (int64_t c = 0; c < Z; ++c) stt(y, yb + (C + c) * ys, 0.0f); + const int64_t cb = rowoff(cond, L * stride + k, D); + for (int64_t c = 0; c < D; ++c) + stt(y, yb + (C + Z + c) * ys, neg ? 0.0f : ldt(cond, cb + c * laststride(cond))); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_prep */ +/* A window step's start, for each entry that moves its lane (pair != -2): + * FIRST the lane's latent rows become the window's noise, element (k, c) of + * rad_philox_normal_s(seed, 1 + win_index, k n + c) as bf16, and with JOIN the first `ov` + * rows are kept in `noise`; + * JOIN the first min(ov, rows) rows are bound to the previous window's end: + * bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev)), t = bf16(t[e]). + * `lat` [lanes * stride, n], `prev` and `noise` [lanes * ov, n]. */ +int ref_win_prep(const RadArgs* a, RadStream) { + if (!have(a, 10)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *t = &a->t[1], *seed = &a->t[2], *widx = &a->t[3]; + const RadTensor *wl = &a->t[4], *pair = &a->t[5], *lcu = &a->t[6], *prev = &a->t[7]; + const RadTensor *noise = &a->t[8], *lat = &a->t[9]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0); + if (n <= 0 || stride <= 0 || ov < 0 || ov > stride) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(fl) < S || numel(t) < S || numel(widx) < S || numel(wl) < S || + numel(pair) < S) + return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + if (ldi(pair, e) == -2) continue; + const int64_t f = ldi(fl, e), L = ldi(wl, e); + const int64_t len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) || + (ov && (L + 1) * ov > rows_of(noise, n)) || + ((f & kFirst) && numel(seed) < 2 * (e + 1)) || + ((f & kJoin) && ov && len > 0 && (L + 1) * ov > rows_of(prev, n))) + return RAD_E_SHAPE; + if (f & kFirst) { + const uint64_t sd = seed_at(seed, e), sm = window_stream(ldi(widx, e)); + for (int64_t k = 0; k < len; ++k) + for (int64_t c = 0; c < n; ++c) { + const float v = rbf(rad_philox_normal_s(sd, sm, (uint64_t)(k * n + c))); + stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat), v); + if ((f & kJoin) && k < ov) + stt(noise, rowoff(noise, L * ov + k, n) + c * laststride(noise), v); + } + } + if (f & kJoin) { + const float tb = rbf(ldt(t, offlin(t, e))); + const float wn = rbf(1.0f - rbf((1.0f - 1e-6f) * tb)); + const int64_t m = std::min(ov, len); + for (int64_t k = 0; k < m; ++k) + for (int64_t c = 0; c < n; ++c) { + const float nz = + ldt(noise, rowoff(noise, L * ov + k, n) + c * laststride(noise)); + const float pv = ldt(prev, rowoff(prev, L * ov + k, n) + c * laststride(prev)); + stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat), + rbf(rbf(wn * nz) + rbf(tb * pv))); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ win_finish */ +/* A window's end, for each entry that moves its lane and carries LAST: with JOIN its first + * min(ov, rows) rows become the previous window's end exactly; then the rows + * [max(0, rows - 2 ov), max(that, rows - ov)) of the latent and of the conditioning are kept as + * the next window's `prev` and `prev_cond`. `lat` [lanes * stride, n], `cond` [lanes * stride, + * n_cond], `prev` [lanes * ov, n], `prev_cond` [lanes * ov, n_cond]. */ +int ref_win_finish(const RadArgs* a, RadStream) { + if (!have(a, 8)) return RAD_E_INVAL; + const RadTensor *fl = &a->t[0], *pair = &a->t[1], *wl = &a->t[2], *lcu = &a->t[3]; + const RadTensor *cond = &a->t[4], *lat = &a->t[5], *prev = &a->t[6], *pc = &a->t[7]; + const int64_t n = p_int(a, "n", 0), D = p_int(a, "n_cond", 0); + const int64_t stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0); + if (n <= 0 || D <= 0 || stride <= 0 || ov <= 0 || ov > stride) return RAD_E_SHAPE; + const int64_t S = numel(lcu) - 1; + if (S <= 0 || numel(fl) < S || numel(wl) < S || numel(pair) < S) return RAD_E_SHAPE; + for (int64_t e = 0; e < S; ++e) { + const int64_t f = ldi(fl, e); + if (ldi(pair, e) == -2 || !(f & kLast)) continue; + const int64_t L = ldi(wl, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e); + if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) || + (L + 1) * ov > rows_of(prev, n) || (L + 1) * ov > rows_of(pc, D) || + (len > ov && (L + 1) * stride > rows_of(cond, D))) + return RAD_E_SHAPE; + if (f & kJoin) + for (int64_t k = 0; k < std::min(ov, len); ++k) + for (int64_t c = 0; c < n; ++c) + stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat), + ldt(prev, rowoff(prev, L * ov + k, n) + c * laststride(prev))); + const int64_t s0 = std::max(0, len - 2 * ov); + const int64_t s1 = std::max(s0, len - ov); + for (int64_t k = s0; k < s1; ++k) { + for (int64_t c = 0; c < n; ++c) + stt(prev, rowoff(prev, L * ov + k - s0, n) + c * laststride(prev), + ldt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat))); + for (int64_t c = 0; c < D; ++c) + stt(pc, rowoff(pc, L * ov + k - s0, D) + c * laststride(pc), + ldt(cond, rowoff(cond, L * stride + k, D) + c * laststride(cond))); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_split */ +/* Channel groups to sequences: x [rows, parts * n] becomes y [parts * rows, n], y[p rows + r] = + * x[r, p n .. p n + n): a stereo latent's two halves as two streams for a vocoder. */ +int ref_chan_split(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), P = p_int(a, "parts", 0); + if (n <= 0 || P <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n) / P; + if (rows <= 0 || rows_of(x, P * n) < rows) return RAD_E_SHAPE; + for (int64_t p = 0; p < P; ++p) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, P * n), yb = rowoff(y, p * rows + r, n); + for (int64_t c = 0; c < n; ++c) + stt(y, yb + c * laststride(y), ldt(x, xb + (p * n + c) * laststride(x))); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ interleave2 */ +/* Two streams of samples interleaved, y [rows, 2] = (a[r], b[r]): a vocoder's left and right + * outputs as a stereo buffer. */ +int ref_interleave2(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x0 = &a->t[0], *x1 = &a->t[1], *y = &a->t[2]; + const int64_t rows = rows_of(y, 2); + if (rows <= 0 || numel(x0) < rows || numel(x1) < rows) return RAD_E_SHAPE; + for (int64_t r = 0; r < rows; ++r) { + stt(y, rowoff(y, r, 2), ldt(x0, offlin(x0, r))); + stt(y, rowoff(y, r, 2) + laststride(y), ldt(x1, offlin(x1, r))); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ iota */ +/* y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`: row + * indices a model's fixed layout names (a depth decoder's position p in every sequence of its + * frame), or the positions of equal sequences laid end to end. */ +int ref_iota(const RadArgs* a, RadStream) { + if (!have(a, 1)) return RAD_E_INVAL; + const RadTensor* y = &a->t[0]; + const int64_t start = p_int(a, "start", 0), step = p_int(a, "step", 1); + const int64_t period = p_int(a, "period", 0); + const int64_t n = numel(y); + if (n <= 0 || period < 0) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) + st_int(y->dtype, y->data, offlin(y, i), start + (period ? i % period : i) * step); + return RAD_OK; +} + +/* ------------------------------------------------------------------ cu_repeat */ +/* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's + * lengths live on the device (a window's frames, the latents a vocoder decodes per channel group), + * so a model's derived bounds are made there too. */ +int ref_cu_repeat(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *len = &a->t[0], *y = &a->t[1]; + const int64_t mult = p_int(a, "mult", 1); + const int64_t n = numel(y); + if (n <= 0 || numel(len) < 1 || mult <= 0) return RAD_E_SHAPE; + const int64_t l = ldi(len, 0); + for (int64_t j = 0; j < n; ++j) st_int(y->dtype, y->data, offlin(y, j), j * l * mult); + return RAD_OK; +} diff --git a/libref/ref_common.h b/libref/ref_common.h index 6dc82a7d..21c12e40 100644 --- a/libref/ref_common.h +++ b/libref/ref_common.h @@ -426,6 +426,10 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam * without doing the work. */ #define RAD_REF_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0) +/* quant_act_i8g's rule for one row of `n` (ref_gen.cpp): returns the scale (amax/127, 1 for an + * all-zero row) and writes the codes rint(clamp(x * (1/scale), +-127)) to `code`, which may be `x`. */ +float ref_q8_row(const float* x, int64_t n, float* code); + static inline const RadTensor* t_in(const RadArgs* a, int i) { return rad_arg_in(a, i); } static inline bool have(const RadArgs* a, int n) { return rad_args_have(a, n) != 0; } diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index c88b5240..8f3712e6 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -251,11 +251,14 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ add / mul */ /* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which * broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a - * plausible number. */ + * plausible number. `add` with `div` stores rd(rd(a + b) / div), rd y's dtype: the last step of a + * mean summed pairwise, (b0 + b1 + b2) / 3 as a vocoder averages its residual blocks. */ static int elementwise2(const RadArgs* a, bool mul) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2]; const int64_t n = p_int(a, "n", numel(Y)); + const float div = mul ? 1.0f : p_f32(a, "div", 1.0f); + if (!(div != 0.0f) || !std::isfinite(div)) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; const int64_t rows = rows_of(Y, n); if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE; @@ -269,7 +272,9 @@ static int elementwise2(const RadArgs* a, bool mul) { const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y); for (int64_t i = 0; i < n; ++i) { float u = ldt(A, ab + i * as), v = ldt(B, bb + i * bs); - stt(Y, yb + i * ys, mul ? u * v : u + v); + float s = mul ? u * v : u + v; + if (div != 1.0f) s = round_dt(Y->dtype, s) / div; + stt(Y, yb + i * ys, s); } } return RAD_OK; @@ -652,13 +657,15 @@ int ref_conv2d_unfold(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ conv1d_dw */ /* A causal depthwise convolution over time: y[t, c] = sum_j w[c, j] * x[t - (k-1) + j, c], the - * rows before the segment's start (cu[s] / cu_div) read as zeros. `w` is PyTorch's depthwise - * [C, 1, k]. f32 accumulation, one rounding. */ + * rows before the segment's start (cu[s] / cu_div) read as zeros, plus `b` [C] when bound. `w` is + * PyTorch's depthwise [C, 1, k]. f32 accumulation, one rounding. */ int ref_conv1d_dw(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3]; + const RadTensor *B = t_in(a, 4); const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1); - if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE; + if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K || (B && numel(B) < C)) + return RAD_E_SHAPE; const int64_t S = numel(cu) - 1; if (S <= 0) return RAD_E_SHAPE; const int64_t Mx = rows_of(X, C), My = rows_of(Y, C); @@ -681,6 +688,7 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) { if (tt < t0) continue; acc += ldt(X, rowoff(X, tt, C) + c * xs) * ldt(Wt, c * K + j); } + if (B) acc += ldt(B, c); stt(Y, yb + c * ys, acc); } } diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index b2e7bccb..4246cc3f 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -26,14 +26,15 @@ enum { kFirst = 1, kInpaint = 2, kPreview = 4 }; inline float rbf(float v) { return round_dt(RAD_BF16, v); } -/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it. */ -int parse_list(const char* s, std::vector* out) { +/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it, or + * kept in f32 with `bf16` false. */ +int parse_list(const char* s, std::vector* out, bool bf16 = true) { out->clear(); while (s && *s) { char* end = nullptr; const double v = std::strtod(s, &end); if (end == s) break; - out->push_back(rbf((float)v)); + out->push_back(bf16 ? rbf((float)v) : (float)v); s = end; } return (int)out->size(); @@ -78,11 +79,15 @@ int ref_ln_mod(const RadArgs* a, RadStream) { } /* ------------------------------------------------------------------ gate_add */ -/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ): a residual added through its sequence's gate. */ +/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ): a residual added through its sequence's gate. + * With `act` none the gate is g itself, unrounded: x = bf16(x + bf16(g[seq] * y)). */ int ref_gate_add(const RadArgs* a, RadStream) { if (!have(a, 4)) return RAD_E_INVAL; const RadTensor *y = &a->t[0], *g = &a->t[1], *cu = &a->t[2], *x = &a->t[3]; const int64_t n = p_int(a, "n", 0); + static const char* kActs[] = { "tanh", "none" }; + const int act = p_enum(a, "act", kActs, 2, 0); + if (act < 0 || act > 1) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1; if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; @@ -93,7 +98,8 @@ int ref_gate_add(const RadArgs* a, RadStream) { const int64_t yb = rowoff(y, r, n), ys = laststride(y); const int64_t xb = rowoff(x, r, n), xs = laststride(x); for (int64_t i = 0; i < n; ++i) { - const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs))); + const float gv = ldt(g, e * g_rs + i * g_cs); + const float t = act ? gv : round_dt(x->dtype, ref_tanh(gv)); const float p = round_dt(x->dtype, t * ldt(y, yb + i * ys)); stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); } @@ -156,6 +162,108 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */ +/* The checks both forms share: `s` holds [shift | scale] in each of its n_seq rows, `g` a gate + * row per sequence when `gated`, and every row operand at least `rows` rows. */ +static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor* s, + const RadTensor* w, const RadTensor* x, int64_t n, int64_t n_seq, + int64_t rows, bool gated) { + if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(w) < n || + numel(s) < n_seq * 2 * n) + return RAD_E_SHAPE; + if (gated && (rows_of(y, n) < rows || numel(g) < n_seq * n)) return RAD_E_SHAPE; + return RAD_OK; +} + +/* Row r of sequence e into o[0, n). With `gated` the branch is added first through the gate row, + * x = bf16(x + bf16(g[e] * y[r])) (no tanh), and stored; then an RMS norm with a gain and the + * sequence's shift and scale, each step a tensor the upstream bf16 model stores: + * + * n1 = bf16(x * rsqrt(mean(x^2) + eps)) n2 = bf16(n1 * w) + * m = bf16(n2 * bf16(1 + scale[e])) z = bf16(m + shift[e]) + * + * The sum of squares is f32 in ascending order, read from the stored residual. `s` is + * [n_seq, >= 2n] at its own row pitch, shift = s[e, 0:n] and scale = s[e, n:2n] (a column slice + * of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`. */ +static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* s, + const RadTensor* w, const RadTensor* x, int64_t r, int64_t e, int64_t n, + float eps, bool gated, uint32_t dt, float* o) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + if (gated) { + const int64_t g_rs = row_stride(g, n), g_cs = laststride(g); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t i = 0; i < n; ++i) { + const float p = round_dt(x->dtype, ldt(g, e * g_rs + i * g_cs) * ldt(y, yb + i * ys)); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); + } + } + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) { const float v = ldt(x, xb + i * xs); ss += v * v; } + const float rs = 1.0f / std::sqrt(ss / (float)n + eps); + const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = laststride(w); + for (int64_t i = 0; i < n; ++i) { + const float n1 = round_dt(dt, ldt(x, xb + i * xs) * rs); + const float n2 = round_dt(dt, n1 * ldt(w, i * ws)); + const float sc = round_dt(dt, 1.0f + ldt(s, e * s_rs + (n + i) * s_cs)); + const float m = round_dt(dt, n2 * sc); + o[i] = round_dt(dt, m + ldt(s, e * s_rs + i * s_cs)); + } +} + +/* A diffusion transformer's adaptive RMS norm with a shift (MiniMax-H3's + * `norm(h) * (1 + scale) + shift`), the gated residual of the branch before it optionally first; + * the norm chain rounds to z's dtype. */ +int ref_rms_mod(const RadArgs* a, RadStream) { + if (a->n_t < 7) return RAD_E_INVAL; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6]; + const int64_t n = p_int(a, "n", 0); + const bool gated = p_int(a, "gated", 0) != 0; + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0 || (gated && (!y || !g))) return RAD_E_SHAPE; + const int64_t rows = rows_of(z, n), n_seq = numel(cu) - 1; + RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + std::vector o((size_t)n); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data()); + const int64_t zb = rowoff(z, r, n), zs = laststride(z); + for (int64_t i = 0; i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); + } + return RAD_OK; +} + +/* rms_mod in front of a quantised linear: the norm chain in bf16, then the codes and scales as + * ref_quant_act_fp8 writes them over that bf16 row (ln_mod_quant_fp8's rule), z written when + * bound. */ +int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { + if (a->n_t < 9) return RAD_E_INVAL; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8); + const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); + const bool gated = p_int(a, "gated", 0) != 0; + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; + const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; + RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); + if (numel(sc) < rows * ngrp || (z && rows_of(z, n) < rows)) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + std::vector o((size_t)n); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data()); + const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0; + for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); + const int64_t qb = rowoff(q, r, n), qs = laststride(q); + for (int64_t gi = 0; gi < ngrp; ++gi) { + const float* og = o.data() + gi * grp; + const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q, + qb + gi * grp * qs, qs); + stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ timestep_embed */ /* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where * f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value @@ -298,12 +406,13 @@ int ref_randn_lanes(const RadArgs* a, RadStream) { * noise the image's own stream (randn_lanes). At the last step sigma_next is 0 and the kept * region is the picture's latent exactly. */ int ref_flow_euler(const RadArgs* a, RadStream) { - if (!have(a, 13)) return RAD_E_INVAL; + /* inp, mask and preview are optional: a sampler without repaint or previews passes none. */ + if (!have(a, 9) || !t_in(a, 11)) return RAD_E_INVAL; const RadTensor *v = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3]; const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7]; const RadTensor *cu = &a->t[8]; const RadTensor *inp = t_in(a, 9), *mask = t_in(a, 10); - const RadTensor *st = &a->t[11]; + const RadTensor *st = t_in(a, 11); const RadTensor *pv = t_in(a, 12); const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; @@ -357,31 +466,71 @@ int ref_flow_euler(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ flow_x0_step */ +/* One sampler step over a lane's rows in f32, as diffusers' MiniMaxH3Scheduler.step takes it: the + * velocity points toward the data, so the clean estimate is d = x + (1 - t) v, and the step blends + * the sample toward it by the schedule's ratio. Each product and sum is one f32 rounding: + * + * st = f32(1 - t) d = f32(x + f32(st * v)) r = f32(sigma_next / sigma) + * x' = f32(f32(r * x) + f32(f32(1 - r) * d)) + * + * t, sigma and sigma_next are one value each: t the timestep the transformer was conditioned on, + * sigma and sigma_next the schedule's entries, kept apart because 1 - (1 - sigma) is not exact in + * f32. x' is stored at x's dtype. */ +int ref_flow_x0_step(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *v = &a->t[0], *t = &a->t[1], *sg = &a->t[2], *sgn = &a->t[3], *x = &a->t[4]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || rows_of(v, n) < rows || numel(t) < 1 || numel(sg) < 1 || numel(sgn) < 1) + return RAD_E_SHAPE; + const float st = 1.0f - ldt(t, offlin(t, 0)); + const float r = ldt(sgn, offlin(sgn, 0)) / ldt(sg, offlin(sg, 0)); + const float omr = 1.0f - r; + REF_PAR_FOR(rows * n) + for (int64_t k = 0; k < rows; ++k) { + const int64_t vb = rowoff(v, k, n), vs = laststride(v); + const int64_t xb = rowoff(x, k, n), xs = laststride(x); + for (int64_t c = 0; c < n; ++c) { + const float xv = ldt(x, xb + c * xs); + const float d = xv + st * ldt(v, vb + c * vs); + stt(x, xb + c * xs, r * xv + omr * d); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ chan_affine */ /* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration, * not weights), each value rounded to bf16 as upstream holds it: mode `fma` is - * bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */ + * bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). With `round` 0 the lists stay + * f32 and so does the arithmetic, rounded once into y: rd(f32(x * mul) + add) and + * rd(f32(x - add) / mul), as an f32 model denormalises an f32 latent. */ int ref_chan_affine(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *y = &a->t[1]; - const int64_t n = p_int(a, "n", 0); + const int64_t n = p_int(a, "n", 0), rnd = p_int(a, "round", 1); + if (rnd < 0 || rnd > 1) return RAD_E_INVAL; std::vector mul, add; - if (n <= 0 || parse_list(p_str(a, "mul", ""), &mul) != n || - parse_list(p_str(a, "add", ""), &add) != n) + if (n <= 0 || parse_list(p_str(a, "mul", ""), &mul, rnd) != n || + parse_list(p_str(a, "add", ""), &add, rnd) != n) return RAD_E_SHAPE; const char* mode = p_str(a, "mode", "fma"); const bool inv = mode && !std::strcmp(mode, "inv"); if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL; const int64_t rows = rows_of(y, n); if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + /* The inner product's or difference's rounding: y's dtype, or none. */ + const uint32_t mid = rnd ? y->dtype : (uint32_t)RAD_F32; REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); const int64_t yb = rowoff(y, r, n), ys = laststride(y); for (int64_t c = 0; c < n; ++c) { const float v = ldt(x, xb + c * xs); - stt(y, yb + c * ys, inv ? round_dt(y->dtype, v - add[c]) / mul[c] - : round_dt(y->dtype, v * mul[c]) + add[c]); + stt(y, yb + c * ys, inv ? round_dt(mid, v - add[c]) / mul[c] + : round_dt(mid, v * mul[c]) + add[c]); } } return RAD_OK; @@ -607,7 +756,7 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) { /* quant_act_i8g's rule for one row of `n`: the scale (amax/127, 1 for an all-zero row) and the * codes rint(clamp(x * (1/scale), +-127)), in f32 as the device computes them. `code` may be `x`: * each code is written after its value is read. */ -static float ref_q8_row(const float* x, int64_t n, float* code) { +float ref::ref_q8_row(const float* x, int64_t n, float* code) { float am = 0.0f; for (int64_t d = 0; d < n; ++d) am = std::max(am, std::fabs(x[d])); const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f; @@ -619,8 +768,11 @@ static float ref_q8_row(const float* x, int64_t n, float* code) { int ref_attn_prefix_self(const RadArgs* a, RadStream) { if (a->n_t < 12) return RAD_E_INVAL; - const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *kv = &a->t[3]; - const RadTensor *bt = &a->t[4], *su = &a->t[5], *cu = &a->t[6], *o = &a->t[11]; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[6], *o = &a->t[11]; + /* The paged prefix (cache, block table, per-sequence prefix lengths), all three or none: with + * none every sequence's prefix is empty. */ + const RadTensor *kv = t_in(a, 3), *bt = t_in(a, 4), *su = t_in(a, 5); + if ((kv == nullptr) != (bt == nullptr) || (kv == nullptr) != (su == nullptr)) return RAD_E_INVAL; const RadTensor *kdes = t_in(a, 7), *vdes = t_in(a, 8); /* The int8 Q.K form: own keys' codes and scales are given; everything else is quantised here. */ const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10); @@ -628,38 +780,50 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { const bool i8 = std::strcmp(qk, "i8") == 0; if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return RAD_E_INVAL; if (i8 && (kdes || vdes)) return RAD_E_UNSUPPORTED; + /* The fp8 P.V form: `v` E4M3 codes with a scale per column in `v_scale` (quant_cols_fp8), each + * weight exp(s - max) taken to E4M3 at 448 times its value, o = sum(w v) v_scale / + * (448 sum exp(s - max)); prefix-free only. */ + const RadTensor* vsc = a->n_t > 12 ? t_in(a, 12) : nullptr; + const char* pv = p_str(a, "pv", "bf16"); + const bool pv8 = std::strcmp(pv, "fp8") == 0; + if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL; + if (pv8 && (kv || kdes || vdes)) return RAD_E_UNSUPPORTED; const int64_t head_dim = p_int(a, "head_dim", 0), gqa = p_int(a, "gqa", 1); const int causal = (int)p_int(a, "causal", 0); - const int64_t block_size = kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0); + const int64_t block_size = !kv ? 1 : kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0); /* The widest head held in the stack rows below. */ constexpr int64_t kHdMax = 1024; if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE; if (head_dim > kHdMax) return RAD_E_UNSUPPORTED; - const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0; + /* Without a cache the key heads are the own keys' width over head_dim. */ + const int64_t kv_heads = kv ? (kv->rank == 4 ? kv->shape[1] : 0) + : k->rank >= 3 ? k->shape[k->rank - 2] + : k->rank == 2 ? k->shape[1] / head_dim : 0; if (kv_heads <= 0) return RAD_E_SHAPE; const int64_t q_heads = kv_heads * gqa, n_seq = numel(cu) - 1; - if (n_seq <= 0 || numel(su) < n_seq) return RAD_E_SHAPE; + if (n_seq <= 0 || (su && numel(su) < n_seq)) return RAD_E_SHAPE; /* The rows are cu's span, which need not start at 0: a segment of a longer sequence is passed * as its two bounding offsets. */ const int64_t r_first = cu_at(cu, 0), rows = cu_at(cu, n_seq) - r_first; if (rows <= 0) return RAD_E_SHAPE; - const int64_t max_blocks = bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq; - const int64_t bt_rs = bt->rank >= 2 ? bt->stride[0] : max_blocks; - const int64_t bt_cs = bt->rank >= 2 ? bt->stride[1] : 1; + const int64_t max_blocks = !bt ? 0 : bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq; + const int64_t bt_rs = bt && bt->rank >= 2 ? bt->stride[0] : max_blocks; + const int64_t bt_cs = bt && bt->rank >= 2 ? bt->stride[1] : 1; /* Every prefix key must have a block-table entry. */ - for (int64_t s = 0; s < n_seq; ++s) + for (int64_t s = 0; su && s < n_seq; ++s) if (ld_int(su->dtype, su->data, offlin(su, s)) > max_blocks * block_size) return RAD_E_SHAPE; const int64_t q_rs = row_stride(q, q_heads * head_dim), k_rs = row_stride(k, kv_heads * head_dim); const int64_t v_rs = row_stride(v, kv_heads * head_dim), o_rs = row_stride(o, q_heads * head_dim); const int64_t k8_rs = i8 ? row_stride(k8, kv_heads * head_dim) : 0; const int64_t ks_rs = i8 ? row_stride(ks, kv_heads) : 0; - const int64_t sb = kv->stride[0], sh = kv->stride[1], so = kv->stride[2]; + const int64_t sb = kv ? kv->stride[0] : 0, sh = kv ? kv->stride[1] : 0; + const int64_t so = kv ? kv->stride[2] : 0; const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); REF_PAR_FOR_DYN(rows * q_heads * head_dim * 64) for (int64_t idx = 0; idx < rows * q_heads; ++idx) { const int64_t h = idx % q_heads, r = r_first + idx / q_heads, kh = h / gqa; const int64_t s = seq_of(cu, n_seq, r), b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1); - const int64_t i = r - b0, P = ld_int(su->dtype, su->data, offlin(su, s)); + const int64_t i = r - b0, P = su ? ld_int(su->dtype, su->data, offlin(su, s)) : 0; const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; const int64_t qb = r * q_rs + h * head_dim; @@ -709,8 +873,9 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; float sum = 0.0f; for (int64_t j = 0; j < nk; ++j) { - const float wgt = ref_exp(dot(j) - mx); - sum += wgt; + const float p = ref_exp(dot(j) - mx); + sum += p; + const float wgt = pv8 ? round_dt(RAD_F8E4M3, 448.0f * p) : p; if (j < P) { for (int64_t d = 0; d < head_dim; ++d) acc[d] += wgt * pkey(j, d, true); } else { @@ -720,7 +885,13 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { } const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; const int64_t ob = r * o_rs + h * head_dim; - for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d, acc[d] * inv); + if (pv8) { + const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) + stt(o, ob + d, acc[d] * ldt(vsc, offlin(vsc, kh * head_dim + d)) * inv8); + } else { + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d, acc[d] * inv); + } } return RAD_OK; } diff --git a/libref/ref_lora.cpp b/libref/ref_lora.cpp index 90bd3ea4..de8b521c 100644 --- a/libref/ref_lora.cpp +++ b/libref/ref_lora.cpp @@ -3,28 +3,23 @@ * lora_shrink t[m, j] = sum_k x(m, k) * A[s, j, k] s = slot[m] * lora_expand y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * B[s, n, j] * - * A step mixes rows of several adapters and rows of none, so the adapter is a PER-ROW operand: a - * row whose slot is outside [0, S) is a BASE row and neither op touches it. That is stronger than - * "adds zero": `y + 0` turns a -0 into +0, and the promise the engine makes is that a base row is - * bit-for-bit what the gemm wrote. So shrink writes nothing into a base row of `t` and expand does - * no read-modify-write of a base row of `y` at all -- not a store of the value it read, no store. + * The adapter is a per-row operand, since a step mixes rows of several adapters and rows of none. + * A row whose slot is outside [0, S) is a base row and neither op touches it: shrink writes nothing + * into its `t` row and expand neither reads nor stores its `y` row, so a base row stays bit for bit + * what the gemm wrote (`y + 0` would turn -0 into +0). * - * x(m, k) IS THE VALUE gemm_nt_q USES FOR THAT ACTIVATION ELEMENT, read the same way: the row and - * column strides of `a` (a column slice of a fused projection arrives with the whole projection's - * row stride), and the scale stream through ref_gemm.h's make_scales, which is gemm_nt_q's own - * reading of `a_scale`. A code times its group's scale is one f32 product; a bf16, f16 or f32 - * activation is its value as it stands. One more rounding than gemm_nt_q's group sub-sum makes on - * a quantised activation, and it is the contract (docs/OPS.md): the LoRA term is a low-rank - * correction, and folding the scale per element keeps the kernels free of a group loop. + * x(m, k) is the value gemm_nt_q uses for that activation element, read the same way: through the + * row and column strides of `a` (a column slice of a fused projection keeps the whole projection's + * row stride) and through ref_gemm.h's make_scales for `a_scale`. A code times its group's scale is + * one f32 product and a float activation is its value. That is one more rounding than gemm_nt_q's + * group sub-sum, and it is the contract (docs/OPS.md): it keeps the kernels free of a group loop. * - * THE SUM IS PER ROW AND ITS ORDER IS FIXED: k ascending for shrink, j ascending for expand, one - * f32 accumulator, no FMA (libref/CMakeLists.txt). Nothing here depends on M or on another row -- - * the batch a row arrives in cannot change its bytes, which is what lets the engine claim "mixed - * batch == the same request alone" for the LoRA term. + * The sum is per row in a fixed order (k ascending for shrink, j ascending for expand, one f32 + * accumulator, no FMA: libref/CMakeLists.txt), so a row's bytes do not depend on M or on the rows + * batched with it. * - * EVERY EXTENT IS THE OPERAND'S, and the parameters are cross-checks (ref_ops.h): `M` is the band, - * so the rows are `t`'s for shrink and `y`'s for expand, and `K`, `N`, `R`, `S` say how to read the - * tensors and are refused where the tensors are too small for them. + * Every extent is the operand's and the parameters are cross-checks (ref_ops.h): `M` is the band, + * and `K`, `N`, `R`, `S` say how to read the tensors and are refused where a tensor is too small. */ #include "ref_common.h" #include "ref_gemm.h" @@ -40,9 +35,8 @@ static inline int64_t row_slot(const RadTensor* slot, int64_t m, int64_t S) { return (s >= 0 && s < S) ? s : -1; } -/* A pool operand [S, rows, cols]: its three strides. The pools are whole declared buffers and so - * dense in the engine; a rank-3 tensor is read through its own strides anyway, because "the - * engine's buffers are dense" is a fact about one caller and not about the op. */ +/* A pool operand [S, rows, cols]: its three strides. The engine's pools are dense, but a rank-3 + * tensor is read through its own strides: density is a fact about one caller, not about the op. */ struct Pool3 { int64_t s0, s1, s2; }; static inline Pool3 pool3(const RadTensor* t, int64_t rows, int64_t cols) { if (t->rank == 3) return Pool3{ t->stride[0], t->stride[1], t->stride[2] }; @@ -77,12 +71,10 @@ int ref_lora_shrink(const RadArgs* a, RadStream) { if (coded_act(X->dtype) && !XS) return RAD_E_INVAL; /* a code without its scale */ if (T->dtype != RAD_F32) return RAD_E_DTYPE; - /* gemm_nt_q's reading of the scale stream, and a `group` cross-check: the stream states the - * group, and a parameter whose GRID disagrees with it is a caller describing other bytes. The - * grid -- groups along K -- and not the number, because a K no wider than one group has one - * group whatever `group` says (a 64-wide row under 128), and from two groups up one power of - * two gives each count. Absent the stream the parameter says nothing: a bf16 activation has no - * scale whatever `group` holds. */ + /* gemm_nt_q's reading of the scale stream, and a `group` cross-check: a parameter whose grid + * (groups along K) disagrees with the stream's describes other bytes. The grid and not the + * number, because a K no wider than one group has one group whatever `group` says. Without a + * stream the parameter says nothing: a float activation has no scale. */ const Scales SA = make_scales(XS, M, K, false); const int64_t gp = p_int(a, "group", 0); if (gp > 0 && SA.p && (K + gp - 1) / gp != (K + SA.group - 1) / SA.group) return RAD_E_SHAPE; diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 9831b243..6b0d1d3b 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -101,6 +101,7 @@ int ref_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_i8g (const RadArgs*, RadStream); int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); +int ref_quant_cols_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); int ref_givens_dense_quant(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); @@ -142,6 +143,36 @@ int ref_lane_gather(const RadArgs*, RadStream); int ref_lane_store(const RadArgs*, RadStream); int ref_randn_lanes(const RadArgs*, RadStream); int ref_flow_euler(const RadArgs*, RadStream); +int ref_rms_mod(const RadArgs*, RadStream); +int ref_rms_mod_quant_fp8(const RadArgs*, RadStream); +int ref_flow_x0_step(const RadArgs*, RadStream); +/* ref_video.cpp */ +int ref_patch_unfold(const RadArgs*, RadStream); +int ref_vtile_gather(const RadArgs*, RadStream); +int ref_vtile_stitch(const RadArgs*, RadStream); +int ref_grid_pos3(const RadArgs*, RadStream); +/* ref_vsa.cpp */ +int ref_vsa_select(const RadArgs*, RadStream); +int ref_attn_vsa(const RadArgs*, RadStream); +/* ref_audio.cpp */ +int ref_conv1d(const RadArgs*, RadStream); +int ref_conv_t1d(const RadArgs*, RadStream); +int ref_snake(const RadArgs*, RadStream); +int ref_snake_aa(const RadArgs*, RadStream); +int ref_cfg_topk_sample(const RadArgs*, RadStream); +int ref_rvq_embed(const RadArgs*, RadStream); +int ref_frame_mix_store(const RadArgs*, RadStream); +int ref_end_status(const RadArgs*, RadStream); +int ref_frame_store(const RadArgs*, RadStream); +int ref_resample_nearest(const RadArgs*, RadStream); +int ref_fourier_embed(const RadArgs*, RadStream); +int ref_win_input(const RadArgs*, RadStream); +int ref_win_prep(const RadArgs*, RadStream); +int ref_win_finish(const RadArgs*, RadStream); +int ref_chan_split(const RadArgs*, RadStream); +int ref_interleave2(const RadArgs*, RadStream); +int ref_iota(const RadArgs*, RadStream); +int ref_cu_repeat(const RadArgs*, RadStream); int ref_chan_affine(const RadArgs*, RadStream); int ref_conv2d_nhwc(const RadArgs*, RadStream); int ref_l2norm_chan(const RadArgs*, RadStream); @@ -270,6 +301,7 @@ REF_SHAPE_FN(ref_quant_act_i8); REF_SHAPE_FN(ref_quant_act_i8g); REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); +REF_SHAPE_FN(ref_quant_cols_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); REF_SHAPE_FN(ref_givens_dense_quant); REF_SHAPE_FN(ref_givens_rotate); @@ -307,6 +339,33 @@ REF_SHAPE_FN(ref_lane_gather); REF_SHAPE_FN(ref_lane_store); REF_SHAPE_FN(ref_randn_lanes); REF_SHAPE_FN(ref_flow_euler); +REF_SHAPE_FN(ref_rms_mod); +REF_SHAPE_FN(ref_rms_mod_quant_fp8); +REF_SHAPE_FN(ref_flow_x0_step); +REF_SHAPE_FN(ref_patch_unfold); +REF_SHAPE_FN(ref_vtile_gather); +REF_SHAPE_FN(ref_vtile_stitch); +REF_SHAPE_FN(ref_grid_pos3); +REF_SHAPE_FN(ref_vsa_select); +REF_SHAPE_FN(ref_attn_vsa); +REF_SHAPE_FN(ref_conv1d); +REF_SHAPE_FN(ref_conv_t1d); +REF_SHAPE_FN(ref_snake); +REF_SHAPE_FN(ref_snake_aa); +REF_SHAPE_FN(ref_cfg_topk_sample); +REF_SHAPE_FN(ref_rvq_embed); +REF_SHAPE_FN(ref_frame_mix_store); +REF_SHAPE_FN(ref_end_status); +REF_SHAPE_FN(ref_frame_store); +REF_SHAPE_FN(ref_resample_nearest); +REF_SHAPE_FN(ref_fourier_embed); +REF_SHAPE_FN(ref_win_input); +REF_SHAPE_FN(ref_win_prep); +REF_SHAPE_FN(ref_win_finish); +REF_SHAPE_FN(ref_chan_split); +REF_SHAPE_FN(ref_interleave2); +REF_SHAPE_FN(ref_iota); +REF_SHAPE_FN(ref_cu_repeat); REF_SHAPE_FN(ref_chan_affine); REF_SHAPE_FN(ref_conv2d_nhwc); REF_SHAPE_FN(ref_l2norm_chan); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 6bd43b2d..f1fc7db8 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -316,6 +316,39 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------- quant_cols_fp8 */ +/* E4M3 codes with ONE scale per column over all M rows: scale[c] = amax_r |x[r, c]| times 1/448 + * in f32 (1 for an all-zero column), y = clamp(x * (1/scale), +-448) rounded to nearest even. The + * value side of an attention's fp8 P.V: a column is one dimension of one head, so the scale + * multiplies out of the sum over keys. */ +int ref_quant_cols_fp8(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1], *s = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = numel(x) / n; + if (rows <= 0 || numel(y) < rows * n || numel(s) < n) return RAD_E_SHAPE; + const int64_t xs = laststride(x), ys = laststride(y), ss = laststride(s); + REF_PAR_FOR(rows * n) + for (int64_t c = 0; c < n; ++c) { + float amax = 0.0f; + for (int64_t r = 0; r < rows; ++r) { + const float m = std::fabs(ldt(x, rowoff(x, r, n) + c * xs)); + if (m > amax) amax = m; + } + const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t r = 0; r < rows; ++r) { + float v = ldt(x, rowoff(x, r, n) + c * xs) * inv; + if (v > 448.0f) v = 448.0f; + if (v < -448.0f) v = -448.0f; + stt(y, rowoff(y, r, n) + c * ys, v); + } + stt(s, c * ss, sc); + } + return RAD_OK; +} + /* ------------------------------------------------------------- had_quant_act_fp8 */ /* The same quantiser with a `group`-wide Hadamard before the absmax, which lowers the maximum the * grid is scaled by. diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 730bb07e..27a3829f 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -138,6 +138,9 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side") static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +/* `div` divides the rounded sum, rounded again (default 1, the plain sum): a mean of branches + * summed pairwise, as a vocoder averages its residual blocks. */ +static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; /* `scalar` 1 says `w` is one element rather than one row; kernels read that off the operand, but a * shape description needs the parameter. */ static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; @@ -173,7 +176,8 @@ static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD OUT("y") }; static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype") }; -static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") }; +static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y"), + WGT_O("b") }; /* `M` is the table's rows, one per distance. */ static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype") }; @@ -205,6 +209,8 @@ static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") }; /* No `asum`: it exists for asymmetric integer grids and fp8 is symmetric (as libr4d/r4d_rows.cpp * notes). */ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; +static const RadParamSpec pQuantCols[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oQuantCols[] = { OPD("x"), OUT("y"), OUT("scale") }; /* ParoQuant's rotation, one per part, to f16 for the 16-bit GEMMs. The tables are the "givens" * encoding's (abi/rad_encoding.h) and are weight operands, so they are placed with their weight. */ static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), @@ -285,13 +291,13 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b" static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"), WGT("bias"), OUT("y") }; -/* RUNTIME LoRA, the two halves of y += scale * (B . (A . x)) at a trunk GEMM, per row: `slot` names +/* Runtime LoRA, the two halves of y += scale * (B . (A . x)) at a trunk GEMM, per row: `slot` names * each row's adapter and a row outside [0, S) is a base row neither op touches. `a`/`a_scale` are * the GEMM's own first two operands, read as gemm_nt_q reads them, and `y` is its output. The pools - * (`lora_a` [S, R, K], `lora_b` [S, N, R], `scale` [S, N]) are ordinary inputs and not weights: the - * engine owns them as program buffers and copies an adapter into a slot between steps, so there is - * no declared weight for an issue to name. `group` is OPTIONAL and 0 means no scale stream; `dtype` - * is the tensor dtype name (rad_dtype_name) of `a` for shrink and of `y` for expand. */ + * (`lora_a` [S, R, K], `lora_b` [S, N, R], `scale` [S, N]) are inputs, not weights: the engine owns + * them as program buffers and copies an adapter into a slot between steps. `group` is optional, 0 + * meaning no scale stream; `dtype` is the tensor dtype name (rad_dtype_name) of `a` for shrink and + * of `y` for expand. */ static const RadParamSpec pLoraShrink[] = { P_INT("M"), P_INT("K"), P_INT("R"), P_INT("S"), P_INTO("group"), P_STR("dtype") }; static const RadOperandSpec oLoraShrink[] = { OPD("a"), OPD_O("a_scale"), OPD("slot"), @@ -322,7 +328,8 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) }; static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"), P_F64O("scale"), P_INTO("max_seqlen"), P_INTO("window"), - P_INTO("cu_div"), P_INTO("block") }; + P_INTO("cu_div"), P_INTO("block"), + P_INTO("window_right") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; @@ -339,7 +346,9 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), P_F64O("yarn_factor"), P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude"), - P_STRO("ladder") }; + P_STRO("ladder"), P_F64O("llama3_factor"), + P_F64O("llama3_low"), P_F64O("llama3_high"), + P_F64O("llama3_orig") }; static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; /* The cos/sin plane a fused prologue reads instead of theta, at each position's own row of a @@ -399,8 +408,10 @@ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"), P_F64O("wadd"), P_INTO("v_norm"), P_STRO("sections"), P_STRO("comps") }; -static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"), - WGT("k_w") }; +/* `positions` may be absent at `rotary_dim` 0 (the norm alone), and an absent gain is a unit + * one. */ +static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD_O("positions"), WGT_O("q_w"), + WGT_O("k_w") }; /* ---- mixture of experts ------------------------------------------------------------------- */ static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"), @@ -646,11 +657,26 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), /* ---- image generation (ref_gen.cpp) --------------------------------------------------------- */ static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; +/* `act` is the gate's activation, "tanh" (the default) or "none". */ +static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_INT("gated"), P_STR("dtype") }; static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; +/* `s` is [n_seq, >= 2n], [shift | scale] in each row. */ +static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), + P_STR("dtype") }; +static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + OPD("cu_seqlens"), INOUT("x"), OUT("z") }; +static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_INT("gated"), P_STR("dtype") }; +static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), + OUT_O("z") }; +/* `t`, `sigma` and `sigma_next` are one f32 value each. */ +static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"), + INOUT("x") }; static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"), P_INTO("round"), P_STR("dtype") }; static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") }; @@ -664,8 +690,9 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"), OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), INOUT("state"), INOUT_O("preview") }; +/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */ static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), - P_STR("mode"), P_STR("dtype") }; + P_STR("mode"), P_STR("dtype"), P_INTO("round") }; static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; @@ -677,11 +704,113 @@ static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") }; static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), - P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") }; -static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"), - OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), + P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk"), + P_STRO("pv") }; +static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD_O("kv_cache"), + OPD_O("block_table"), OPD_O("seqused"), OPD("cu_seqlens"), OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"), - OPD_O("k_scale"), OUT("out") }; + OPD_O("k_scale"), OUT("out"), OPD_O("v_scale") }; + +/* ---- video generation (ref_video.cpp). `geom` is the request's latent geometry, i32 on the + * device: (F, Hp, Wp) for patch_unfold, (frames, H, W) for vtile_gather and (frames, H, W, first, + * last) for vtile_stitch. */ +static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"), + P_INT("pw"), P_STR("mul"), P_STR("add"), + P_STR("dtype") }; +static const RadOperandSpec oPatchUnfold[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileGather[] = { P_INT("M"), P_INT("n"), P_INT("tile"), + P_INT("overlap"), P_INT("frames"), P_INT("period"), + P_INT("n_reg"), P_STR("dtype") }; +static const RadOperandSpec oVtileGather[] = { OPD("x"), WGT("reg"), OPD("geom"), OUT("y") }; +static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"), + P_INT("scale"), P_INT("pt"), P_INT("skip"), + P_INT("keep"), P_INT("blend"), P_INT("period"), + P_STR("mean"), P_STR("std") }; +static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") }; +/* `y` is [3, >= M], component-major at its own row pitch. */ +static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"), + P_INT("period"), P_F64("scale") }; +static const RadOperandSpec oGridPos3[] = { OUT("y") }; +/* ---- video sparse attention (ref_vsa.cpp). `segs` cuts the rows into dense segments and the + * video grid, last; `geom` is the request's RadVideoGeom on the device (RAD_VGEOM_*). The two ops + * share their parameters: attn_vsa recomputes k from `sparsity`. `v` of vsa_select is read for + * `coarse` alone, and attn_vsa's `gate` comes with its `coarse`. */ +static const RadParamSpec pVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale") }; +static const RadOperandSpec oVsaSelect[] = { OPD("q"), OPD("k"), OPD_O("v"), OPD("segs"), + OPD("geom"), OUT("sel"), OUT_O("coarse") }; +/* attn_vsa adds attn_prefix_self's int8 Q.K form at the end: `qk` "i8" with `k_i8` and `k_scale`, + * quant_act_i8g's codes and scales of k at group head_dim. */ +static const RadParamSpec pAttnVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"), + P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"), + P_F64("sparsity"), P_F64O("scale"), P_STRO("qk"), + P_STRO("pv") }; +static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("segs"), + OPD("geom"), OPD("sel"), OPD_O("coarse"), + OPD_O("gate"), OUT("out"), OPD_O("k_i8"), + OPD_O("k_scale"), OPD_O("v_scale") }; + +/* ---- audio generation (ref_audio.cpp) */ +static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), + P_INT("dil"), P_STRO("act"), P_STR("dtype"), + P_INTO("causal") }; +static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"), + OUT("y"), WGT_O("b") }; +static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"), + P_STR("dtype"), P_INTO("pad"), P_INTO("k") }; +static const RadOperandSpec oConvT1d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("cu_seqlens"), + OUT("y") }; +static const RadParamSpec pSnake[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("log") }; +static const RadOperandSpec oSnake[] = { OPD("x"), WGT("alpha"), OUT("y"), WGT_O("beta") }; +static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"), + P_INTO("log"), P_STR("dtype") }; +static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"), WGT("f_up"), + WGT("f_down"), OPD("cu_seqlens"), OUT("y") }; +static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), + P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), + P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), + P_INTO("sup_hi"), P_F64O("penalty") }; +static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"), + OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; +static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), + P_INT("vocab"), P_INT("off0"), P_F64("scale"), + P_STR("dtype"), P_INTO("round") }; +static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; +static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), + P_INTO("rep"), P_STR("dtype") }; +static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), + OPD("frame"), OPD("status"), INOUT("dst") }; +static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") }; +static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") }; +static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), + P_INTO("rep"), P_INTO("skip") }; +static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"), + OPD("status"), INOUT("dst") }; +static const RadParamSpec pFourier[] = { P_INT("M"), P_INT("n"), P_INTO("round"), P_STR("dtype") }; +static const RadOperandSpec oFourier[] = { OPD("t"), WGT("w"), OUT("y") }; +static const RadParamSpec pWinInput[] = { P_INT("M"), P_INT("n_lat"), P_INT("n_zero"), + P_INT("n_cond"), P_INT("stride"), P_STR("dtype") }; +static const RadOperandSpec oWinInput[] = { OPD("lat"), OPD("cond"), OPD("lat_cu"), OPD("win_lane"), + OPD("pair"), OUT("y") }; +static const RadParamSpec pWinPrep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_INT("ov"), + P_STR("dtype") }; +static const RadOperandSpec oWinPrep[] = { OPD("flags"), OPD("t"), OPD("seed"), OPD("win_index"), + OPD("win_lane"), OPD("pair"), OPD("lat_cu"), + OPD("prev"), INOUT("noise"), INOUT("lat") }; +static const RadParamSpec pWinFinish[] = { P_INT("M"), P_INT("n"), P_INT("n_cond"), P_INT("stride"), + P_INT("ov"), P_STR("dtype") }; +static const RadOperandSpec oWinFinish[] = { OPD("flags"), OPD("pair"), OPD("win_lane"), + OPD("lat_cu"), OPD("cond"), INOUT("lat"), + INOUT("prev"), INOUT("prev_cond") }; +static const RadParamSpec pChanSplit[] = { P_INT("M"), P_INT("n"), P_INT("parts"), P_STR("dtype") }; +static const RadParamSpec pInterleave[] = { P_INT("M"), P_STR("dtype") }; +static const RadOperandSpec oInterleave2[] = { OPD("a"), OPD("b"), OUT("y") }; +static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), + P_INTO("period") }; +static const RadOperandSpec oIota[] = { OUT("y") }; +static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; +static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") }; /* ================================================================== the schema table */ static const RadOpSchema kSchemas[] = { @@ -733,9 +862,10 @@ static const RadOpSchema kSchemas[] = { "antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a " "triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps " "normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." }, -{ "add", ARR(pMnD), ARR(oBinary), +{ "add", ARR(pAdd), ARR(oBinary), "y = a + b. An operand carrying exactly n elements against a taller output broadcasts along " - "rows; nothing else broadcasts." }, + "rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last " + "sum of a mean taken pairwise." }, { "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same one broadcast rule as `add`." }, { "mul_weight", ARR(pMulWeight), ARR(oMulWeight), "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " @@ -766,7 +896,8 @@ static const RadOpSchema kSchemas[] = { "as [cout, cin*kh*kw] is the convolution. Segments, cu_div and valid as conv2d's." }, { "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw), "Causal depthwise convolution over time: y[t, c] = sum_j w[c, 0, j] * x[t - (k-1) + j, c], rows " - "before the segment's start (cu/cu_div) read as zeros. f32 sum, one rounding." }, + "before the segment's start (cu/cu_div) read as zeros, plus the optional bias b[c]. f32 sum, " + "one rounding." }, { "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "Row d: sin(d * inv[i]) then cos(d * inv[i]) over n/2 timescales, inv[i] = exp(i * " "-log(max_timescale) / max(n/2 - 1, 1)), each step in f32, rounded once." }, @@ -869,6 +1000,10 @@ static const RadOpSchema kSchemas[] = { "scale shaped [M, ceil(n/group)] in f32. An all-zero group gets scale 1, not scale 0: the GEMM " "multiplies this scale by the weight's block scale, and a zero here would erase that one. Rows " "are dim 0, so a rank-3 activation is one row per token and not one per head." }, +{ "quant_cols_fp8", ARR(pQuantCols), ARR(oQuantCols), + "E4M3 codes with one scale per column over all M rows: scale[c] = amax_r |x[r, c]| / 448 (1 for " + "an all-zero column), y = clamp(x / scale, +-448). An attention's values for its fp8 P.V, where " + "a column's scale multiplies out of the sum over keys." }, { "rmsnorm_quant_fp8", ARR(pRmsQuantFp8), ARR(oRmsQuantFp8), "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The residual " "add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over is the bf16 " @@ -948,7 +1083,7 @@ static const RadOpSchema kSchemas[] = { "t[m, j] = sum_k x(m, k) * lora_a[s, j, k] for each row m whose s = slot[m] is in [0, S), f32 " "accumulate, k ascending; x(m, k) is the value gemm_nt_q uses for that element of `a` (a code " "times its group's scale from `a_scale`, a float as it is). A row outside [0, S) is a base row " - "and its `t` row is NOT WRITTEN. A row's bytes do not depend on M or on any other row." }, + "and its `t` row is not written. A row's bytes do not depend on M or on any other row." }, { "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand), "y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m whose s = " "slot[m] is in [0, S), f32 accumulate, j ascending, one rounding to y's dtype. A base row's `y` " @@ -964,8 +1099,9 @@ static const RadOpSchema kSchemas[] = { { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is " "attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < " - "window; 0 none. `block` cuts a segment into blocks of that many rows from its start, each " - "attending within itself; 0 none." }, + "window, or i - j < window and j - i < window_right with `window_right`; 0 none. `block` cuts " + "a segment into blocks of that many rows from its start, each attending within itself; 0 " + "none." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, @@ -1004,11 +1140,18 @@ static const RadOpSchema kSchemas[] = { "`sections` of frequencies, one ladder), \"imrope\" (Qwen3-VL's interleaved sections) or " "\"axial\" (contiguous sections, each on its own ladder -- a 2-D rotary). `positions` is [M], " "or [C, M] component-major for a multi-component mode; with [M] every component is that one. " - "`scale` divides the position; `rotary_dim` is optional and defaults to head_dim." }, + "An f32 `positions` holds the positions as they are (fractional coordinates), an integer one " + "integers. " + "`scale` divides the position; `rotary_dim` is optional and defaults to head_dim. `llama3_*` " + "applies Llama 3's frequency scaling (factor, low and high frequency factors, the original " + "length)." }, { "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "Per-head RMS norm of q and k against their own gains, then rope. THE NORM OUTPUT IS ROUNDED " "TO THE TENSOR'S DTYPE BEFORE THE ROTATION, which is what the unfused pair does. `v_norm` 1 " - "also RMS-norms each v head with a unit gain, unrotated." }, + "also RMS-norms each v head with a unit gain, unrotated. An absent gain is a unit gain " + "without `wadd`; `rotary_dim` 0 is the norm alone, `positions` then optional. `mode` " + "\"axial\" is rope's axial (its section ladders also over rank-1 positions), and f32 " + "positions are read as rope reads them." }, { "scale_rows", ARR(pScaleRows), ARR(oScaleRows), "y[m, i] = x[m, i] * act(s[m]): one scalar per ROW, broadcast ACROSS the row. `mul` broadcasts " @@ -1201,8 +1344,9 @@ static const RadOpSchema kSchemas[] = { "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the row's " "sequence's modulation row of `s` ([n_seq, >= n] at its own pitch). A diffusion transformer's " "adaptive norm without a shift." }, -{ "gate_add", ARR(pMnD), ARR(oGateAdd), - "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual added through its sequence's gate row." }, +{ "gate_add", ARR(pGateAdd), ARR(oGateAdd), + "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual added through its sequence's gate row; " + "with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))." }, { "timestep_embed", ARR(pTimestep), ARR(oTimestep), "the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)) with " "t' = scale * t; `round` 1 takes t through bf16 at scale and back first, as diffusers' " @@ -1223,7 +1367,8 @@ static const RadOpSchema kSchemas[] = { "latent with flag 4, the kept region of a repaint restored with flag 2 (docs/OPS.md)." }, { "chan_affine", ARR(pChanAffine), ARR(oUnary), "a per-channel affine from two parameter lists of n values (rounded to bf16): `fma` is " - "bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul)." }, + "bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul). `round` 0 keeps the lists and " + "the arithmetic in f32, rounded once into y: rd(f32(x * mul) + add), rd(f32(x - add) / mul)." }, { "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc), "an image convolution, channels innermost: x [Hin, Win * cin] and y [Hout, Wout * cout] dense, " "the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input " @@ -1253,6 +1398,115 @@ static const RadOpSchema kSchemas[] = { "rint(clamp(x * (1/scale), +-127))), the query and each prefix key are quantised by the same " "rule per (row, head), and a score is the exact integer dot product times both scales. `k` is " "then not read for the own rows." }, +/* ---- video generation -------------------------------------------------------------------- */ +{ "rms_mod", ARR(pRmsMod), ARR(oRmsMod), + "a DiT's adaptive RMS norm with a shift: with `gated` 1 first x = bf16(x + bf16(g[seq] * y)) " + "(no tanh), stored; then n1 = bf16(x * rsqrt(mean(x^2) + eps)), n2 = bf16(n1 * w), " + "m = bf16(n2 * bf16(1 + scale[seq])), z = bf16(m + shift[seq]), `s` [n_seq, >= 2n] holding " + "[shift | scale] at its own pitch." }, +{ "rms_mod_quant_fp8", ARR(pRmsModQ), ARR(oRmsModQ), + "rms_mod with the norm chain in bf16, then (q, scale) = quant_act_fp8(z, group) as " + "ln_mod_quant_fp8 makes them; z written when bound." }, +{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0), + "a sampler step toward a data-ward velocity's clean estimate, in f32: st = 1 - t, " + "d = x + st v, r = sigma_next / sigma, x = r x + (1 - r) d, each product and sum rounded " + "once; t, sigma and sigma_next one value each (MiniMax-H3's scheduler)." }, +{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold), + "patch rows [F Hp Wp, C pt ph pw] (geom = (F, Hp, Wp)) unfolded to voxel rows " + "[(F pt) (Hp ph) (Wp pw), C] and denormalised, f32(f32(x * mul[c]) + add[c]) with `mul` and " + "`add` lists of C f32 values." }, +{ "vtile_gather", ARR(pVtileGather), ARR(oVtileGather), + "a video decoder's tiles out of voxel rows [frames H W, n] (geom = (frames, H, W)): each axis " + "split into tile-wide tiles at least `overlap` apart (diffusers' _split_tiles), tile k at rows " + "[k period, (k + 1) period) of y as its frames tile tile voxels, then n_reg rows of `reg`, then " + "zeros." }, +{ "vtile_stitch", ARR(pVtileStitch), ARR(oVtileStitch), + "a decoded chunk's tiles stitched into frames (each tile's kept range, blended with the tile " + "above and then the tile to the left, both as decoded), the first `blend` kept frames blended " + "with `prev` unless the chunk is first, prev refilled from the chunk's tail (also emitted " + "when it is last), then bytes round(255 clamp(v std + mean, 0, 1)); geom = (frames, H, W, " + "first, last), u8 out." }, +{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3), + "a video decoder's rotary positions over tiles of `period` rows: token (t, i, j) of a tile's " + "T x H x W gets f32(scale) * (2 (c + 0.5) / n - 1) on each axis, in f32 as torch makes it, " + "the rest of the period 0; y f32 [3, >= M] component-major at its own row pitch." }, +{ "vsa_select", ARR(pVsa), ARR(oVsaSelect), + "video sparse attention's tile selection. Tiles: each dense segment of `segs` in chunks of " + "tile_t tile_h tile_w rows (P prefix tiles), then tile_t x tile_h x tile_w boxes over the " + "F x Hp x Wp video grid (geom's frames, height / patch, width / patch), box (a, b, c) tile " + "P + (a nb + b) nc + c (V of them). S = f32 tile means of q and k, dotted, times scale; a video " + "query tile's sel[h][i][0, k) is its k = max(1, min(ceil((1 - sparsity) V), V)) (f64) video " + "tiles of largest S, ties to the lower, ascending. With `coarse` (and `v`): softmax over all " + "tiles of S times the tile means of v, rounded once." }, +{ "attn_vsa", ARR(pAttnVsa), ARR(oAttnVsa), + "video sparse attention: a prefix query tile sees every tile, a video one the prefix tiles and " + "its k tiles of `sel` (k ascending video tiles, RAD_E_INVAL otherwise); f32 softmax with the " + "max subtracted. With `coarse` and `gate`: out = rd(rd(o) + coarse[h][tile] gate), rd the " + "output's dtype." }, +{ "conv1d", ARR(pConv1d), ARR(oConv1d), + "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], " + "y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding " + "dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each " + "sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1])." }, +{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d), + "a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` " + "((k - stride) / 2 by default, 0 the causal form): each sequence of x [rows, cin] grows " + "`stride` times into y [rows * stride, cout], output row o reading the input rows i with " + "0 <= o + pad - i stride < k; PyTorch's [cin, cout, k] weight and a bias." }, +{ "snake", ARR(pSnake), ARR(oSnake), + "the snake activation per channel: x + sin(alpha x)^2 / (alpha + 1e-9), or with `beta` " + "x + (1 / (beta + 1e-9)) sin(alpha x)^2; `log` 1 stores both as logarithms." }, +{ "snake_aa", ARR(pSnakeAa), ARR(oSnakeAa), + "BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled `ratio` " + "times by the transposed `f_up` filter, SnakeBeta, replicate-padded and filtered by `f_down` " + "at stride `ratio` (docs/OPS.md has the paddings and crops); `log` 1 reads alpha and beta " + "as logarithms." }, +{ "cfg_topk_sample", ARR(pCfgTopk), ARR(oCfgTopk), + "one pick a lane from `rep` branch rows of logits (1 or 2, conditional first): guidance " + "u + cfg (c - u) (`cfg` [n] per lane when bound), a repetition `penalty` over the lane's " + "history `hist` (cleared at frame 0, the pick recorded), ids in [sup_lo, sup_hi) never " + "candidates, with `cond_k` > 0 only the entries where c reaches its cond_k-th largest, the k " + "largest kept (ties to the lower index), over `temp`, softmax, drawn by inverse CDF with " + "rad_philox_uniform_s(seed, 2^32 + frame, stream); written to every one of the lane's slots." }, +{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed), + "a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum " + "of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or " + "with `round` 1 one f32 sum in codebook order times scale, rounded once." }, +{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), + "a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, " + "stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." }, +{ "end_status", ARR(pEndStatus), ARR(oEndStatus), + "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." }, +{ "frame_store", ARR(pFrameStore), ARR(oFrameStore), + "a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = " + "codes[k, rep i] when frame >= skip and status[lane] >= 0." }, +{ "resample_nearest", ARR(pMnD), ARR(oUnary), + "rows resampled nearest-neighbour: output row j reads input row min(floor(j * in / out), " + "in - 1) in f32, the row counts read off the operands." }, +{ "fourier_embed", ARR(pFourier), ARR(oFourier), + "[cos(2 pi t w) | sin(2 pi t w)] of t [M] f32 and a trained w [n / 2]; `round` 1 rounds each " + "tensor a bf16 reference holds (t, 2 pi t, the product, each cosine and sine)." }, +{ "win_input", ARR(pWinInput), ARR(oWinInput), + "a denoiser's input for its window entries: [lat | zeros | cond] from each entry's lane of the " + "latent and conditioning states, zeros for the conditioning of an unconditional entry " + "(pair -2)." }, +{ "win_prep", ARR(pWinPrep), ARR(oWinPrep), + "a window step's start for each entry that moves its lane: flag 1 draws the window's noise " + "(rad_philox_normal_s(seed, 1 + win_index, .)) into the lane, keeping its first `ov` rows with " + "flag 16; flag 16 binds the first rows to the previous window's end, " + "bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev))." }, +{ "win_finish", ARR(pWinFinish), ARR(oWinFinish), + "a window's end (flag 8): with flag 16 its first rows become the previous window's end " + "exactly; rows [max(0, n - 2 ov), max(.., n - ov)) of the latent and the conditioning are kept " + "as the next window's prev and prev_cond." }, +{ "chan_split", ARR(pChanSplit), ARR(oUnary), + "x [rows, parts * n] to y [parts * rows, n]: each channel group a sequence of its own." }, +{ "interleave2", ARR(pInterleave), ARR(oInterleave2), + "two streams interleaved, y [rows, 2] = (a[r], b[r])." }, +{ "iota", ARR(pIota), ARR(oIota), + "y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`." }, +{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), + "bounds of equal sequences, y[j] = j * len[0] * mult over y's elements." }, }; /* ================================================================== the kernel table */ @@ -1463,6 +1717,8 @@ SIMPLE("ref_quant_act_i8g", "quant_act_i8g", "quant", "float in, i8 out, f32 scale", ref_quant_act_i8g), SIMPLE("ref_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale", ref_quant_act_fp8), +SIMPLE("ref_quant_cols_fp8", "quant_cols_fp8", "quant", "E4M3 with one scale per column", + "float in, fp8_e4m3 out, f32 scale", ref_quant_cols_fp8), /* The fused fp8 forms, so a host-backend run can start on an fp8 model (see ref_quant.cpp). */ SIMPLE("ref_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant", "RMS norm, optional residual add, and the E4M3 quantiser in one pass", @@ -1632,7 +1888,8 @@ SIMPLE("ref_sample_merge_topk", "sample_merge_topk", "sample", "vocab-parallel candidate merge", DT_FLOAT, ref_sample_merge_topk), SIMPLE("ref_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + a sequence's scale row)", DT_FLOAT, ref_ln_mod), -SIMPLE("ref_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, ref_gate_add), +SIMPLE("ref_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT, + ref_gate_add), SIMPLE("ref_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm", "gated residual, gainless layer norm times (1 + scale row), block-scaled E4M3", DT_FLOAT, ref_ln_mod_quant_fp8), @@ -1664,6 +1921,61 @@ SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", ref_scatter_add_rows), SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn", "attention over a paged prefix and the step's own rows", DT_FLOAT, ref_attn_prefix_self), +SIMPLE("ref_rms_mod", "rms_mod", "norm", + "gated residual, RMS norm with a gain times (1 + scale row) plus a shift row", DT_FLOAT, + ref_rms_mod), +SIMPLE("ref_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm", + "gated residual, modulated RMS norm, block-scaled E4M3", DT_FLOAT, ref_rms_mod_quant_fp8), +SIMPLE("ref_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate", + DT_FLOAT, ref_flow_x0_step), +SIMPLE("ref_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows", + DT_FLOAT, ref_patch_unfold), +SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent", + DT_FLOAT, ref_vtile_gather), +SIMPLE("ref_vtile_stitch", "vtile_stitch", "elem", + "decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT, + ref_vtile_stitch), +SIMPLE("ref_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles", + DT_FLOAT, ref_grid_pos3), +SIMPLE("ref_vsa_select", "vsa_select", "attn", + "video sparse attention's top-k tiles by pooled score, and the coarse branch", + "float q, k, v and coarse; i32 segs, geom and sel", ref_vsa_select), +SIMPLE("ref_attn_vsa", "attn_vsa", "attn", + "block-sparse attention over the prefix and selected video tiles, the gated coarse term", + "float q, k, v, coarse, gate and out; i32 segs, geom and sel", ref_attn_vsa), +SIMPLE("ref_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, channels innermost", + DT_FLOAT, ref_conv1d), +SIMPLE("ref_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution growing each sequence", + DT_FLOAT, ref_conv_t1d), +SIMPLE("ref_snake", "snake", "elem", "the snake activation", DT_FLOAT, ref_snake), +SIMPLE("ref_snake_aa", "snake_aa", "elem", "the alias-free SnakeBeta: upsample, snake, downsample", + DT_FLOAT, ref_snake_aa), +SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick a lane", + DT_FLOAT, ref_cfg_topk_sample), +SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes", + DT_FLOAT, ref_rvq_embed), +SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", + DT_FLOAT, ref_frame_mix_store), +SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, + ref_end_status), +SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY, + ref_frame_store), +SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour", + DT_ANY, ref_resample_nearest), +SIMPLE("ref_fourier_embed", "fourier_embed", "elem", "random Fourier features of a time", + DT_FLOAT, ref_fourier_embed), +SIMPLE("ref_win_input", "win_input", "elem", "a denoiser's input from the window states", + DT_FLOAT, ref_win_input), +SIMPLE("ref_win_prep", "win_prep", "elem", "a window step's noise and overlap", DT_FLOAT, + ref_win_prep), +SIMPLE("ref_win_finish", "win_finish", "elem", "a window's end and the overlap it hands on", + DT_FLOAT, ref_win_finish), +SIMPLE("ref_chan_split", "chan_split", "elem", "channel groups to sequences", DT_ANY, + ref_chan_split), +SIMPLE("ref_interleave2", "interleave2", "elem", "two streams interleaved", DT_ANY, + ref_interleave2), +SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_iota), +SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat), }; /* ================================================================== plugin exports */ diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f74a9acb..a495d0a3 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -65,9 +65,11 @@ /* rad_param_find / rad_param_getdim / rad_param_gets / rad_dtype_parse. */ #include "rad_plugin.h" +#include "rad_runtime.h" /* RAD_VGEOM_N */ #include "rad_sample.h" #include +#include #include #include #include @@ -531,6 +533,7 @@ int ref_conv1d_dw_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out o.t(D, { C, 1, K }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M / cdiv, C }); /* y */ + o.skip(); /* b */ return o.finish("conv1d_dw", operand, out); } @@ -809,6 +812,16 @@ int ref_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("quant_act_fp8", operand, out); } +int ref_quant_cols_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + Opd o; + o.t(D, { M, n }); /* x */ + o.t((uint32_t)RAD_F8E4M3, { M, n }); /* y */ + o.t((uint32_t)RAD_F32, { n }); /* scale, one a column (amax / 448) */ + return o.finish("quant_cols_fp8", operand, out); +} + /* `n` is K on both axes of the accumulator: h is [n, n], not [M, n]. */ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -1009,14 +1022,13 @@ int ref_gemm_nt_q_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc return gemm_q_shape(p, n_p, operand, true, out); } -/* RUNTIME LoRA. `slot` is drawn in [0, S] -- S ITSELF IS A BASE ROW, one past the pool -- so a cold - * draw exercises the rows neither op may touch as well as the adapter rows; a draw never yields - * -1, which is the other spelling of a base row, so that one is a hand case (tests/lora_test.cpp, - * ref_test). A single row is drawn in [0, S): a one-row call whose row drew S would write nothing, - * and a comparison of nothing proves nothing (rad-avx-check refuses it as vacuous). The scale stream exists only beside a coded activation: a bf16, f16 or f32 `a` is - * read as it stands, the way gemm_nt_q's fp8a16 form reads it, and an fp8 or i8 one without its - * scale is refused by the launch. `group` defaults to the 128 every block-scaled checkpoint and - * quantiser in this project uses when the geometry does not state one. */ +/* Runtime LoRA. `slot` is drawn in [0, S], S itself being a base row one past the pool, so a cold + * draw covers the rows neither op may touch as well as the adapter rows. A draw never yields -1, + * the other spelling of a base row, which is a hand case (tests/lora_ops_test.cpp, ref_test). A + * single row is drawn in [0, S): a one-row call whose row drew S would write nothing, which + * rad-avx-check refuses as vacuous. The scale stream exists only beside a coded activation; a float + * `a` is read as it stands, as gemm_nt_q's fp8a16 form reads it. `group` defaults to 128, the + * block every block-scaled checkpoint and quantiser here uses, when the geometry states none. */ int ref_lora_shrink_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "K", 0); @@ -1187,9 +1199,14 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* * interleaved q/gate view that parameters cannot describe; opshapes.h declines it.) */ o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */ /* `blocks` takes positions [C, M], component-major, C one past the largest `comps` entry (the - * section count without `comps`). */ + * section count without `comps`); `axial` one component a section. Without a rotation + * (`rotary_dim` 0) the positions are not passed. */ const char* mode = gs(p, n_p, "mode"); - if (mode && !std::strcmp(mode, "blocks")) { + const bool blocks = mode && !std::strcmp(mode, "blocks"); + const bool axial = mode && !std::strcmp(mode, "axial"); + if (gi(p, n_p, "rotary_dim", hd) == 0) { + o.skip(); /* positions */ + } else if (blocks || axial) { int64_t nc = 0; for (const char* q = gs(p, n_p, "sections"); q && *q; ) { char* e = nullptr; @@ -1198,7 +1215,7 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ++nc; q = e; } - if (const char* cs = gs(p, n_p, "comps")) { + if (const char* cs = blocks ? gs(p, n_p, "comps") : nullptr) { int64_t mx = -1; for (const char* q = cs; *q; ) { char* e = nullptr; @@ -2172,6 +2189,58 @@ int ref_ln_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDe o.t(D, { M, n }); /* z */ return o.finish("ln_mod_quant_fp8", operand, out); } +/* rms_mod's branch and gate are passed when `gated`, and absent otherwise. */ +int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const uint32_t D = act_dt(p, n_p); + Opd o; + if (gi(p, n_p, "gated", 0)) { + o.t(D, { M, n }); /* y */ + o.t(D, { 1, n }); /* g: one sequence */ + } else { + o.skip(); + o.skip(); + } + o.t(D, { 1, 2 * n }); /* s: [shift | scale] */ + o.t(D, { n }); /* w */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* x, INOUT */ + o.t(D, { M, n }); /* z */ + return o.finish("rms_mod", operand, out); +} +int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const uint32_t D = act_dt(p, n_p); + Opd o; + if (gi(p, n_p, "gated", 0)) { + o.t(D, { M, n }); /* y */ + o.t(D, { 1, n }); /* g */ + } else { + o.skip(); + o.skip(); + } + o.t(D, { 1, 2 * n }); /* s */ + o.t(D, { n }); /* w */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* x, INOUT */ + o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ + o.t((uint32_t)RAD_F32, { M, ng }); /* scale */ + o.t(D, { M, n }); /* z */ + return o.finish("rms_mod_quant_fp8", operand, out); +} +/* The sampler's three scalars in (0, 1), the state f32. */ +int ref_flow_x0_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const uint32_t F = (uint32_t)RAD_F32; + Opd o; + o.t(act_dt(p, n_p), { M, n }); /* v */ + o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t */ + o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */ + o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_next */ + o.t(F, { M, n }); /* x, INOUT */ + return o.finish("flow_x0_step", operand, out); +} int ref_gate_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const uint32_t D = act_dt(p, n_p); @@ -2345,13 +2414,24 @@ int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDe const uint32_t Q = act_dt(p, n_p); const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv; + /* `max_ctx` 0 declares the prefix-free form: no cache, block table or prefix lengths. */ + const bool pre = gi(p, n_p, "max_ctx", -1) != 0; + const char* pv = gs(p, n_p, "pv"); + const bool pv8 = pv && !std::strcmp(pv, "fp8"); + if (pv8 && pre) return RAD_E_UNSUPPORTED; Opd o; o.t(Q, { M, nh, hd }); /* q */ o.t(Q, { M, kvh, hd }); /* k */ - o.t(Q, { M, kvh, hd }); /* v */ - o.t(KV, { S * max_blocks, kvh, bs, 2 * hd }); /* kv_cache */ - o.t_idx({ S, max_blocks }, S * max_blocks, -1, 0); /* block_table: may repeat */ - o.t_idx({ S }, 0, P, 0); /* seqused: the prefix depth */ + o.t(pv8 ? (uint32_t)RAD_F8E4M3 : Q, { M, kvh, hd }); /* v */ + if (pre) { + o.t(KV, { S * max_blocks, kvh, bs, 2 * hd }); /* kv_cache */ + o.t_idx({ S, max_blocks }, S * max_blocks, -1, 0); /* block_table: may repeat */ + o.t_idx({ S }, 0, P, 0); /* seqused: the prefix depth */ + } else { + o.skip(); + o.skip(); + o.skip(); + } o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.skip(); /* k_descale */ o.skip(); /* v_descale */ @@ -2364,6 +2444,8 @@ int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDe o.skip(); } o.t(Q, { M, nh, hd }); /* out */ + if (pv8) o.t((uint32_t)RAD_F32, { kvh * hd }); /* v_scale: one a column */ + else o.skip(); return o.finish("attn_prefix_self", operand, out); } @@ -2408,3 +2490,432 @@ int ref_scatter_add_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDe o.t(D, { 4 * M, n }); /* x, inout */ return o.finish("scatter_add_rows", operand, out); } + +/* ================================================================== video generation + * + * The request's geometry is a device operand, and a description can only draw an index operand + * as one value throughout, so every axis of `geom` is one extent c: a c x c x c grid (and, for + * vtile_stitch, a chunk that is its video's first and last). The ranged M is the output's rows; + * an M below what the grid writes declines, and rows past it are left as drawn. */ + +/* The tiles split_tiles (ref_video.cpp) lays over `len` latent units, 0 where none fit. */ +static int64_t tile_count(int64_t len, int64_t tile, int64_t overlap) { + if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return 0; + if (tile >= len) return len == tile ? 1 : 0; + int64_t nt = (len + tile - 1) / tile; + while (tile * nt - overlap * (nt - 1) - len < 0) ++nt; + return nt; +} + +/* A 2 x 2 x 2 grid of patches. */ +int ref_patch_unfold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0); + const int64_t pt = gi(p, n_p, "pt", 0), ph = gi(p, n_p, "ph", 0), pw = gi(p, n_p, "pw", 0); + const int64_t c = 2, vol = pt * ph * pw; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || M < c * c * c * vol) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, C * vol }); /* x: patch rows */ + o.t_idx({ 3 }, 0, c, 0); /* geom: (F, Hp, Wp) */ + o.t(D, { M, C }); /* y: voxel rows */ + return o.finish("patch_unfold", operand, out); +} + +/* A latent of `frames` frames, as tall and as wide as it is long. */ +int ref_vtile_gather_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), tile = gi(p, n_p, "tile", 0); + const int64_t ov = gi(p, n_p, "overlap", 0), c = gi(p, n_p, "frames", 0); + const int64_t period = gi(p, n_p, "period", 0), n_reg = gi(p, n_p, "n_reg", 0); + const int64_t nt = tile_count(c, tile, ov); + if (n <= 0 || nt <= 0 || n_reg < 0 || period < c * tile * tile + n_reg || + M < nt * nt * period) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, n }); /* x: voxel rows */ + o.t(D, { n_reg > 0 ? n_reg : 1, n }); /* reg */ + o.t_idx({ 3 }, 0, c, 0); /* geom: (frames, H, W) */ + o.t(D, { M, n }); /* y */ + return o.finish("vtile_gather", operand, out); +} + +/* The smallest grid the chunk's frames and the tile fit. */ +int ref_vtile_stitch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t ov = gi(p, n_p, "overlap", 0), S = gi(p, n_p, "scale", 0); + const int64_t pt = gi(p, n_p, "pt", 0), skip = gi(p, n_p, "skip", 0); + const int64_t keep = gi(p, n_p, "keep", 0), blend = gi(p, n_p, "blend", 0); + const int64_t period = gi(p, n_p, "period", 0); + if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep <= 0 || blend < 0 || blend > keep) + return RAD_E_UNSUPPORTED; + const int64_t c = std::max(tile, (2 * skip + keep + blend + pt - 1) / pt); + const int64_t nt = tile_count(c, tile, ov), npx = c * S * c * S; + if (nt <= 0 || period < c * tile * tile || M < (keep + blend) * npx) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { nt * nt * period, 3 * pt * S * S }); /* x: the decoded tiles */ + o.t_idx({ 5 }, 0, c, 0); /* geom: first and last set */ + o.t(D, { blend > 0 ? blend * npx : 1, 3 }); /* prev, INOUT */ + o.t((uint32_t)RAD_U8, { M, 3 }); /* y */ + return o.finish("vtile_stitch", operand, out); +} + +int ref_grid_pos3_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, { 3, M }); /* y: one row a component */ + return o.finish("grid_pos3", operand, out); +} + +/* ================================================================== video sparse attention + * + * The tiles come from the values of `segs` and `geom`, which a description draws only as + * cumulative lengths and as one value c in every entry. So the grid is a cube of c frames and + * c / patch rows and columns, c the smallest that gives every axis an edge box (more than one box, + * the last short), and `segs` cuts M into M / (F Hp Wp) segments of the grid's rows each, the last + * the video; an M not a multiple of the grid declines. `n_head` (default 2) and `dtype` (default + * bf16) are the description's, as is `coarse`: 0 leaves the optional operands out. + * + * attn_vsa's `sel` is drawn as one value, the first video tile, which is a selection only at + * k = 1; any other sparsity declines (the hand-built cases build selections, + * libavx/avx_check_hand.cpp). */ +namespace { + +struct VsaGeo { + int64_t M, hd, nh, c, n_seg, P, V, N, k; + uint32_t D; + bool coarse; +}; + +/* An axis of `len` units over boxes of `t` has more than one box, the last short; a box of one + * unit needs only a second unit. */ +bool vsa_edge(int64_t len, int64_t t) { return t > 1 ? len > t && len % t != 0 : len > 1; } + +int vsa_geo(const RadParam* p, int n_p, VsaGeo* g) { + g->M = gi(p, n_p, "M", 0); + g->hd = gi(p, n_p, "head_dim", 0); + g->nh = gi(p, n_p, "n_head", 2); + const int64_t tt = gi(p, n_p, "tile_t", 0), th = gi(p, n_p, "tile_h", 0); + const int64_t tw = gi(p, n_p, "tile_w", 0), patch = gi(p, n_p, "patch", 0); + const double sparsity = rad_param_getf(p, n_p, "sparsity", -1.0); + if (g->M <= 0 || g->hd <= 0 || g->nh <= 0 || tt <= 0 || th <= 0 || tw <= 0 || patch <= 0 || + !(sparsity >= 0.0 && sparsity < 1.0)) + return RAD_E_UNSUPPORTED; + int64_t c = 1; + while (c <= 4096 && !(vsa_edge(c, tt) && vsa_edge(c / patch, th) && vsa_edge(c / patch, tw))) + ++c; + const int64_t hp = c / patch, rows = c * hp * hp, TT = tt * th * tw; + if (c > 4096 || g->M % rows != 0) return RAD_E_UNSUPPORTED; + g->c = c; + g->n_seg = g->M / rows; + g->P = (g->n_seg - 1) * ((rows + TT - 1) / TT); + g->V = ((c + tt - 1) / tt) * ((hp + th - 1) / th) * ((hp + tw - 1) / tw); + g->N = g->P + g->V; + const double keep = (1.0 - sparsity) * (double)g->V; + g->k = std::max(1, std::min((int64_t)std::ceil(keep), g->V)); + g->D = act_dt(p, n_p); + g->coarse = gi(p, n_p, "coarse", 1) != 0; + return RAD_OK; +} + +} /* namespace */ + +int ref_vsa_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + VsaGeo g{}; + if (vsa_geo(p, n_p, &g) != RAD_OK) return RAD_E_UNSUPPORTED; + Opd o; + o.t(g.D, { g.M, g.nh, g.hd }); /* q */ + o.t(g.D, { g.M, g.nh, g.hd }); /* k */ + if (g.coarse) o.t(g.D, { g.M, g.nh, g.hd }); else o.skip(); /* v */ + o.t_idx({ g.n_seg + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* segs */ + o.t_idx({ RAD_VGEOM_N }, 0, g.c, 0); /* geom: c everywhere */ + /* A tile row and a slot past the selection's, which nothing writes. */ + o.t((uint32_t)RAD_I32, { g.nh, g.N + 1, g.k + 1 }); /* sel */ + if (g.coarse) o.t(g.D, { g.nh, g.N + 1, g.hd }); else o.skip(); /* coarse */ + return o.finish("vsa_select", operand, out); +} + +int ref_attn_vsa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + VsaGeo g{}; + if (vsa_geo(p, n_p, &g) != RAD_OK || g.k != 1) return RAD_E_UNSUPPORTED; + const char* pv = gs(p, n_p, "pv"); + const bool pv8 = pv && !std::strcmp(pv, "fp8"); + Opd o; + o.t(g.D, { g.M, g.nh, g.hd }); /* q */ + o.t(g.D, { g.M, g.nh, g.hd }); /* k */ + o.t(pv8 ? (uint32_t)RAD_F8E4M3 : g.D, { g.M, g.nh, g.hd }); /* v */ + o.t_idx({ g.n_seg + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* segs */ + o.t_idx({ RAD_VGEOM_N }, 0, g.c, 0); /* geom: c everywhere */ + o.t_idx({ g.nh, g.N, 1 }, g.N, g.P, 0); /* sel: the first video tile */ + if (g.coarse) { + o.t(g.D, { g.nh, g.N, g.hd }); /* coarse */ + o.t(g.D, { g.M, g.nh, g.hd }); /* gate */ + } else { + o.skip(); + o.skip(); + } + o.t(g.D, { g.M, g.nh, g.hd }); /* out */ + const char* qk = gs(p, n_p, "qk"); + if (qk && !std::strcmp(qk, "i8")) { + o.t((uint32_t)RAD_I8, { g.M, g.nh, g.hd }); /* k_i8 */ + o.t((uint32_t)RAD_F32, { g.M, g.nh }); /* k_scale */ + } else { + o.skip(); + o.skip(); + } + if (pv8) o.t((uint32_t)RAD_F32, { g.nh * g.hd }); /* v_scale: one a column */ + else o.skip(); + return o.finish("attn_vsa", operand, out); +} + +/* ================================================================== audio generation + * Sequenced ops (the convolutions) are described over two sequences where M allows; lane ops over + * REF_LANES lanes, as the image generator's are. */ +static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; } + +int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); + const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0); + if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0)) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t S = two_seqs(M); + Opd o; + o.t(D, { M, cin }); /* x */ + o.t(D, { cout, cin, k }); /* w */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, cout }); /* res */ + o.t(D, { M, cout }); /* y */ + o.t(D, { cout }); /* b */ + return o.finish("conv1d", operand, out); +} + +int ref_conv_t1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); + const int64_t s = gi(p, n_p, "stride", 0), k = gi(p, n_p, "k", 2 * s); + const int64_t pad = gi(p, n_p, "pad", -1); + if (M <= 0 || cin <= 0 || cout <= 0 || s <= 0 || k < s || (pad < 0 && ((k - s) & 1))) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, cin }); /* x */ + o.t(D, { cin, cout, k }); /* w */ + o.t(D, { cout }); /* b */ + o.t_idx({ two_seqs(M) + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M * s, cout }); /* y */ + return o.finish("conv_t1d", operand, out); +} + +int ref_snake_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + /* alpha in (0, 1): a trained alpha is positive, and 1 / alpha near zero is no test. */ + o.t_fill((uint32_t)RAD_F32, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* alpha */ + o.t(D, { M, n }); /* y */ + o.skip(); /* beta */ + return o.finish("snake", operand, out); +} + +int ref_snake_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t R = gi(p, n_p, "ratio", 0), k = gi(p, n_p, "k", 0); + if (M <= 0 || n <= 0 || R <= 0 || k < R) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p), F = (uint32_t)RAD_F32; + Opd o; + o.t(D, { M, n }); /* x */ + o.t_fill(F, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* alpha */ + o.t_fill(F, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* beta */ + o.t(F, { 1, 1, k }); /* f_up */ + o.t(F, { 1, 1, k }); /* f_down */ + o.t_idx({ two_seqs(M) + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, n }); /* y */ + return o.finish("snake_aa", operand, out); +} + +int ref_cfg_topk_sample_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), V = gi(p, n_p, "n_vocab", 0), rep = gi(p, n_p, "rep", 1); + if (M <= 0 || V <= 0 || rep < 1 || M % rep) return RAD_E_UNSUPPORTED; + const int64_t n = M / rep; + Opd o; + o.t((uint32_t)RAD_F32, { M, V }); /* logits */ + o.t_idx({ 2 * n }, (int64_t)1 << 30, -1, 0); /* seed */ + o.t_idx({ n }, 9000, -1, 0); /* frame */ + o.t_idx({ M }, V, -1, 0); /* ids */ + o.skip(); /* cfg */ + o.skip(); /* lane */ + o.skip(); /* hist */ + return o.finish("cfg_topk_sample", operand, out); +} + +int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0); + const int64_t K = gi(p, n_p, "n_codes", 0), voc = gi(p, n_p, "vocab", 0); + const int64_t off0 = gi(p, n_p, "off0", 0); + if (M <= 0 || D <= 0 || K < 1 || voc <= 0 || off0 < 0) return RAD_E_UNSUPPORTED; + const uint32_t B = (uint32_t)RAD_BF16; + Opd o; + o.t_idx({ K, M }, voc, -1, 0); /* codes */ + o.t(B, { off0 + voc, D }); /* t0 */ + o.t(B, { (K > 1 ? K - 1 : 1) * voc, D }); /* t1 */ + o.t(act_dt(p, n_p), { M, D }); /* y */ + return o.finish("rvq_embed", operand, out); +} + +int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0); + const int64_t st = gi(p, n_p, "stride", 0); + if (M <= 0 || D <= 0 || L <= 0 || st <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED; + const uint32_t A = act_dt(p, n_p); + Opd o; + o.t(A, { L * 2 * M, D }); /* hid: two branch rows a lane */ + o.t((uint32_t)RAD_F32, { L }); /* logits */ + o.t_fill((uint32_t)RAD_F32, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* scale */ + o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ M }, st + 1, -1, 0); /* frame, 0 included */ + o.t_idx({ REF_LANES }, 8, -1, 0); /* status */ + o.t(A, { REF_LANES * st, D }); /* dst, INOUT */ + return o.finish("frame_mix_store", operand, out); +} + +int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), end = gi(p, n_p, "end", 0); + if (M <= 0 || rep < 1 || M > REF_LANES) return RAD_E_UNSUPPORTED; + Opd o; + /* Ids over [0, 2 end): about half the lanes end. */ + o.t_idx({ rep * M }, end > 0 ? 2 * end : 2, -1, 0); /* ids */ + o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ REF_LANES }, 8, -1, 0); /* status, INOUT */ + return o.finish("end_status", operand, out); +} + +int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0); + const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1); + if (M <= 0 || K <= 0 || st <= 0 || rep < 1 || M > REF_LANES) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ K, rep * M }, 2048, -1, 0); /* codes */ + o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ M }, st, -1, 0); /* frame */ + o.t_idx({ REF_LANES }, 8, -1, 0); /* status */ + o.t_idx({ REF_LANES * K, st }, 2048, -1, 0); /* dst, INOUT */ + return o.finish("frame_store", operand, out); +} + +int ref_resample_nearest_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M / 3 + 1, n }); /* x: fewer rows than y */ + o.t(D, { M, n }); /* y */ + return o.finish("resample_nearest", operand, out); +} + +int ref_fourier_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0 || (n & 1)) return RAD_E_UNSUPPORTED; + Opd o; + o.t_fill((uint32_t)RAD_F32, { M }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t in (0, 1) */ + o.t((uint32_t)RAD_F32, { n / 2 }); /* w */ + o.t(act_dt(p, n_p), { M, n }); /* y */ + return o.finish("fourier_embed", operand, out); +} + +int ref_win_input_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "n_lat", 0), Z = gi(p, n_p, "n_zero", 0); + const int64_t Dc = gi(p, n_p, "n_cond", 0), st = gi(p, n_p, "stride", 0); + if (M <= 0 || C <= 0 || Z < 0 || Dc <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = lane_entries(p, n_p, M, st); + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t A = act_dt(p, n_p); + Opd o; + o.t(A, { REF_LANES * st, C }); /* lat */ + o.t(A, { REF_LANES * st, Dc }); /* cond */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */ + o.t_idx({ S }, REF_LANES, -1, 0); /* win_lane */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t(A, { M, C + Z + Dc }); /* y */ + return o.finish("win_input", operand, out); +} + +int ref_win_prep_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0); + const int64_t ov = gi(p, n_p, "ov", 0); + if (M <= 0 || n <= 0 || st <= 0 || ov <= 0 || ov > st) return RAD_E_UNSUPPORTED; + const int64_t S = lane_entries(p, n_p, M, st); + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t B = (uint32_t)RAD_BF16; + Opd o; + o.t_idx({ S }, 32, -1, 0); /* flags: every bit drawn */ + o.t_fill((uint32_t)RAD_F32, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t */ + o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */ + o.t_idx({ S }, 64, -1, 0); /* win_index */ + /* Distinct: two entries moving one lane would race. */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* win_lane */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */ + o.t(B, { REF_LANES * ov, n }); /* prev */ + o.t(B, { REF_LANES * ov, n }); /* noise, INOUT */ + o.t(B, { REF_LANES * st, n }); /* lat, INOUT */ + return o.finish("win_prep", operand, out); +} + +int ref_win_finish_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), Dc = gi(p, n_p, "n_cond", 0); + const int64_t st = gi(p, n_p, "stride", 0), ov = gi(p, n_p, "ov", 0); + if (M <= 0 || n <= 0 || Dc <= 0 || st <= 0 || ov <= 0 || ov > st) return RAD_E_UNSUPPORTED; + const int64_t S = lane_entries(p, n_p, M, st); + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t B = (uint32_t)RAD_BF16; + Opd o; + o.t_idx({ S }, 32, -1, 0); /* flags */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* win_lane */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */ + o.t(B, { REF_LANES * st, Dc }); /* cond */ + o.t(B, { REF_LANES * st, n }); /* lat, INOUT */ + o.t(B, { REF_LANES * ov, n }); /* prev, INOUT */ + o.t(B, { REF_LANES * ov, Dc }); /* prev_cond, INOUT */ + return o.finish("win_finish", operand, out); +} + +int ref_chan_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), P = gi(p, n_p, "parts", 0); + if (M <= 0 || n <= 0 || P <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, P * n }); /* x */ + o.t(D, { P * M, n }); /* y */ + return o.finish("chan_split", operand, out); +} + +int ref_interleave2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M }); /* a */ + o.t(D, { M }); /* b */ + o.t((uint32_t)RAD_F32, { M, 2 }); /* y */ + return o.finish("interleave2", operand, out); +} + +int ref_iota_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ M }, 1, -1, 0); /* y */ + return o.finish("iota", operand, out); +} + +int ref_cu_repeat_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 1 }, 1000, -1, 0); /* len */ + o.t_idx({ M }, 1, -1, 0); /* y */ + return o.finish("cu_repeat", operand, out); +} diff --git a/libref/ref_video.cpp b/libref/ref_video.cpp new file mode 100644 index 00000000..a690f687 --- /dev/null +++ b/libref/ref_video.cpp @@ -0,0 +1,300 @@ +/* ref_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video + * generation"): the denoised latent's patch rows unfolded to voxels, the tiles a video decoder + * runs over, gathered from the latent and stitched back into frames, and the rotary positions of + * a tile's tokens. + * + * Per-request geometry (a video's frames, height and width) comes from a `geom` operand the run + * phase writes on the device, never from the parameters, which are fixed at declare. The tiles + * are diffusers' AutoencoderKLMiniMaxH3 tiling in latent units, and the stitch rounds where its + * bf16 blends round. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include + +using namespace ref; + +namespace { + +inline int64_t ldi(const RadTensor* t, int64_t i) { + return ld_int(t->dtype, t->data, offlin(t, i)); +} + +/* A space-separated list of floats, kept in f32: a video's latent and pixel statistics are f32 + * tensors upstream, unlike the bf16 lists chan_affine reads. */ +int parse_f32_list(const char* s, std::vector* out) { + out->clear(); + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + out->push_back((float)v); + s = end; + } + return (int)out->size(); +} + +/* The tiles over one axis of `len` latent units, diffusers' _split_tiles in latent units: a tile + * at least as long as the axis is the whole axis (and must be exactly as long, every tile being + * tile x tile); otherwise the fewest tiles whose union covers the axis with every overlap at + * least `overlap`, the slack added to the overlaps one unit at a time round-robin from the first, + * and start[i + 1] = start[i] + tile - ov[i]. False where no such layout exists. */ +bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector* start, + std::vector* ov) { + start->clear(); + ov->clear(); + if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return false; + if (tile >= len) { + start->push_back(0); + return len == tile; + } + int64_t nt = (len + tile - 1) / tile; + while (tile * nt - overlap * (nt - 1) - len < 0) ++nt; + ov->assign((size_t)(nt - 1), overlap); + const int64_t rem = tile * nt - overlap * (nt - 1) - len; + for (int64_t i = 0; i < rem; ++i) (*ov)[(size_t)(i % (nt - 1))] += 1; + start->push_back(0); + for (int64_t i = 0; i + 1 < nt; ++i) start->push_back(start->back() + tile - (*ov)[(size_t)i]); + return true; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ patch_unfold */ +/* A video latent's patch rows unfolded to voxel rows and denormalised. x [F Hp Wp, C pt ph pw] + * holds patch (f, i, j), frame-major then row-major, its column (c, a, b, d) at + * c pt ph pw + a ph pw + b pw + d; y [(F pt) (Hp ph) (Wp pw), C] holds voxel (t, yy, xx) + * row-major: + * + * y[(t, yy, xx), c] = f32(f32(x[(t / pt, yy / ph, xx / pw), (c, t % pt, yy % ph, xx % pw)] + * * mul[c]) + add[c]) + * + * `geom` is (F, Hp, Wp), the request's latent grid in patches. `mul` and `add` are C values each, + * kept in f32 (the reference denormalises f32 latents with an f32 deviation and mean). y holds at + * least the voxels' rows; rows past them are not written. */ +int ref_patch_unfold(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0); + const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0); + std::vector mul, add; + if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32_list(p_str(a, "mul", ""), &mul) != C || + parse_f32_list(p_str(a, "add", ""), &add) != C || numel(geom) < 3) + return RAD_E_SHAPE; + const int64_t F = ldi(geom, 0), Hp = ldi(geom, 1), Wp = ldi(geom, 2); + if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE; + const int64_t Hv = Hp * ph, Wv = Wp * pw, K = C * pt * ph * pw, rows = F * pt * Hv * Wv; + if (rows_of(y, C) < rows || rows_of(x, K) < F * Hp * Wp) return RAD_E_SHAPE; + REF_PAR_FOR(rows * C) + for (int64_t r = 0; r < rows; ++r) { + const int64_t t = r / (Hv * Wv), yy = (r / Wv) % Hv, xx = r % Wv; + const int64_t patch = ((t / pt) * Hp + yy / ph) * Wp + xx / pw; + const int64_t sub = ((t % pt) * ph + yy % ph) * pw + xx % pw; + const int64_t xb = rowoff(x, patch, K), xs = laststride(x); + const int64_t yb = rowoff(y, r, C), ys = laststride(y); + for (int64_t c = 0; c < C; ++c) + stt(y, yb + c * ys, + ldt(x, xb + (c * pt * ph * pw + sub) * xs) * mul[(size_t)c] + add[(size_t)c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ grid_pos3 */ +/* A video decoder's rotary positions over consecutive tiles: row m is token k = m % period of its + * tile, the tile's T x H x W tokens first ((t, i, j) row-major) and the period's remaining rows + * (register tokens) at position 0. Each axis is the token's centre normalised to [-1, 1) and + * scaled, in f32 as torch's 2 * (arange(0.5, n) / n) - 1 makes it: + * + * g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1) y[axis][m] = f32(f32(scale) g) + * + * y is f32 [3, >= M], component-major, each component a row at the operand's own pitch (a [3, M] + * view of a wider buffer); M is its row length. */ +int ref_grid_pos3(const RadArgs* a, RadStream) { + if (!have(a, 1)) return RAD_E_INVAL; + const RadTensor* y = &a->t[0]; + const int64_t T = p_int(a, "T", 0), H = p_int(a, "H", 0), W = p_int(a, "W", 0); + const int64_t period = p_int(a, "period", 0); + const float scale = p_f32(a, "scale", 1.0f); + if (T <= 0 || H <= 0 || W <= 0 || period < T * H * W || y->rank != 2 || y->shape[0] < 3) + return RAD_E_SHAPE; + const int64_t M = y->shape[1], rs = y->stride[0], cs = y->stride[1]; + if (M <= 0) return RAD_E_SHAPE; + auto g = [](int64_t c, int64_t n) { + const float q = ((float)c + 0.5f) / (float)n; + return 2.0f * q - 1.0f; + }; + REF_PAR_FOR(M * 3) + for (int64_t m = 0; m < M; ++m) { + const int64_t k = m % period; + float p[3] = { 0.0f, 0.0f, 0.0f }; + if (k < T * H * W) { + p[0] = scale * g(k / (H * W), T); + p[1] = scale * g((k / W) % H, H); + p[2] = scale * g(k % W, W); + } + for (int c = 0; c < 3; ++c) stt(y, c * rs + m * cs, p[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_gather */ +/* The tiles a video decoder runs over, gathered from voxel rows x [frames H W, n] ((t, yy, xx) + * row-major), `geom` = (frames, H, W) in latent units, its frames those of the `frames` + * parameter. Each spatial axis is split by split_tiles (`tile`, `overlap`) and the tiles are taken + * row-major over (row band, column band). Tile k is rows [k period, (k + 1) period) of y: its + * frames tile tile voxels (t, ty, tx) row-major, from x's row (t, start_y + ty, start_x + tx); + * then reg's first `n_reg` rows (a decoder's register tokens) in y's dtype; then zero rows to the + * period. y holds at least n_tiles period rows. */ +int ref_vtile_gather(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *reg = &a->t[1], *geom = &a->t[2], *y = &a->t[3]; + const int64_t n = p_int(a, "n", 0), tile = p_int(a, "tile", 0); + const int64_t overlap = p_int(a, "overlap", 0), frames = p_int(a, "frames", 0); + const int64_t period = p_int(a, "period", 0), n_reg = p_int(a, "n_reg", 0); + const int64_t vox = frames * tile * tile; + if (n <= 0 || tile <= 0 || frames <= 0 || n_reg < 0 || period < vox + n_reg || + numel(geom) < 3 || rows_of(reg, n) < n_reg) + return RAD_E_SHAPE; + const int64_t H = ldi(geom, 1), W = ldi(geom, 2); + std::vector sy, sx, oy, ox; + if (ldi(geom, 0) != frames || !split_tiles(H, tile, overlap, &sy, &oy) || + !split_tiles(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nw = (int64_t)sx.size(), rows = (int64_t)sy.size() * nw * period; + if (rows_of(y, n) < rows || rows_of(x, n) < frames * H * W) return RAD_E_SHAPE; + REF_PAR_FOR(rows * n) + for (int64_t row = 0; row < rows; ++row) { + const int64_t k = row / period, p = row % period; + const int64_t yb = rowoff(y, row, n), ys = laststride(y); + if (p < vox) { + const int64_t t = p / (tile * tile), ty = (p / tile) % tile, tx = p % tile; + const int64_t src = (t * H + sy[(size_t)(k / nw)] + ty) * W + sx[(size_t)(k % nw)] + tx; + const int64_t xb = rowoff(x, src, n), xs = laststride(x); + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(x, xb + c * xs)); + } else if (p < vox + n_reg) { + const int64_t rb = rowoff(reg, p - vox, n), rs = laststride(reg); + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(reg, rb + c * rs)); + } else { + for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, 0.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vtile_stitch */ +/* A decoded chunk's tiles stitched into frames, blended with the previous chunk's overlap, and + * written as RGB bytes. + * + * x is the decoder's output over vtile_gather's tiles, [>= n_tiles period, 3 pt scale scale]: + * tile k's row k period + (lt tile + ty) tile + tx, column + * c pt scale^2 + a scale^2 + b scale + d, is colour c of pixel (ty scale + b, tx scale + d) of clip + * frame lt pt + a. `geom` = (frames, H, W, first, last): the chunk's latent geometry, and whether + * it is its video's first and last chunk (nonzero). Tiles are split_tiles' over H and W. + * + * Every product and sum below rounds to x's dtype (rd), as the reference's bf16 blends do, with + * wa(p, e) = rd(1 - rd(p / e)) and wb(p, e) = rd(p / e). Pixel (Y, X) of clip frame fc belongs to + * the tile (i, j) whose kept range holds it, [start_i scale, start_{i+1} scale) (the last tile to + * its end), at (ly, lx) within it; T(i, j, ly, lx) is that tile's decoded value. The spatial + * stitch blends the top ev = ov_y[i-1] scale rows with the tile above and then the left + * eh = ov_x[j-1] scale columns with the tile to the left, both neighbours as decoded (never + * blended): + * + * V = rd(rd(T(i-1, j, ly + tile scale - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev))) + * when i > 0 and ly < ev, else T(i, j, ly, lx) + * S = rd(rd(T(i, j-1, ly, lx + tile scale - eh) wa(lx, eh)) + rd(V wb(lx, eh))) + * when j > 0 and lx < eh, else V + * + * Output frame k < keep is clip frame skip + k, its first `blend` frames blended with `prev` + * unless the chunk is its video's first, v = rd(rd(prev[k] wa(k, blend)) + rd(S wb(k, blend))); + * prev then becomes the frames S(2 skip + keep + k'), k' < blend, at prev's dtype; with `last` + * those frames follow the kept ones in y. A byte is round-half-even(255 clamp(f32(f32(v std[c]) + + * mean[c]), 0, 1)), `mean` and `std` three f32 values each. y is u8 [frames_out, H scale, + * W scale, 3] and prev [blend, H scale, W scale, 3]; y holds at least the frames' rows. */ +int ref_vtile_stitch(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *geom = &a->t[1], *prev = &a->t[2], *y = &a->t[3]; + const int64_t tile = p_int(a, "tile", 0), overlap = p_int(a, "overlap", 0); + const int64_t S = p_int(a, "scale", 0), pt = p_int(a, "pt", 0), skip = p_int(a, "skip", 0); + const int64_t keep = p_int(a, "keep", 0), blend = p_int(a, "blend", 0); + const int64_t period = p_int(a, "period", 0); + std::vector mean, stdv; + if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep <= 0 || blend < 0 || blend > keep || + parse_f32_list(p_str(a, "mean", ""), &mean) != 3 || + parse_f32_list(p_str(a, "std", ""), &stdv) != 3 || numel(geom) < 5 || y->dtype != RAD_U8) + return RAD_E_SHAPE; + const int64_t frames = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2); + const bool first = ldi(geom, 3) != 0, last = ldi(geom, 4) != 0; + std::vector sy, sx, oy, ox; + if (frames <= 0 || 2 * skip + keep + blend > frames * pt || period < frames * tile * tile || + !split_tiles(H, tile, overlap, &sy, &oy) || !split_tiles(W, tile, overlap, &sx, &ox)) + return RAD_E_SHAPE; + const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(), cols = 3 * pt * S * S; + if (rows_of(x, cols) < nh * nw * period) return RAD_E_SHAPE; + const int64_t Hp = H * S, Wp = W * S, npx = Hp * Wp; + const int64_t fout = keep + (last ? blend : 0); + if (rows_of(y, 3) < fout * npx || (blend > 0 && rows_of(prev, 3) < blend * npx)) + return RAD_E_SHAPE; + /* The owner tile and the offset in it of every pixel row and column. */ + std::vector own_y((size_t)Hp), own_x((size_t)Wp); + for (int64_t Y = 0, i = 0; Y < Hp; ++Y) { + while (i + 1 < nh && Y >= sy[(size_t)(i + 1)] * S) ++i; + own_y[(size_t)Y] = i; + } + for (int64_t X = 0, j = 0; X < Wp; ++X) { + while (j + 1 < nw && X >= sx[(size_t)(j + 1)] * S) ++j; + own_x[(size_t)X] = j; + } + const uint32_t dt = x->dtype; + auto rd = [dt](float v) { return round_dt(dt, v); }; + auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); }; + auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); }; + auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t fc, int64_t c) { + const int64_t row = (i * nw + j) * period + ((fc / pt) * tile + ly / S) * tile + lx / S; + const int64_t col = ((c * pt + fc % pt) * S + ly % S) * S + lx % S; + return ldt(x, rowoff(x, row, cols) + col * laststride(x)); + }; + auto stitch = [&](int64_t fc, int64_t Y, int64_t X, int64_t c) { + const int64_t i = own_y[(size_t)Y], j = own_x[(size_t)X]; + const int64_t ly = Y - sy[(size_t)i] * S, lx = X - sx[(size_t)j] * S; + float v = T(i, j, ly, lx, fc, c); + const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] * S : 0; + if (ly < ev) { + const float up = T(i - 1, j, ly + tile * S - ev, lx, fc, c); + v = rd(rd(up * wa(ly, ev)) + rd(v * wb(ly, ev))); + } + const int64_t eh = j > 0 ? ox[(size_t)(j - 1)] * S : 0; + if (lx < eh) { + const float left = T(i, j - 1, ly, lx + tile * S - eh, fc, c); + v = rd(rd(left * wa(lx, eh)) + rd(v * wb(lx, eh))); + } + return v; + }; + auto byte = [&](int64_t f, int64_t px, int64_t c, float v) { + float p = v * stdv[(size_t)c] + mean[(size_t)c]; + p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p); + stt(y, rowoff(y, f * npx + px, 3) + c * laststride(y), p * 255.0f); + }; + REF_PAR_FOR(npx * 3 * (fout + blend) * 4) + for (int64_t px = 0; px < npx; ++px) { + const int64_t Y = px / Wp, X = px % Wp; + for (int64_t c = 0; c < 3; ++c) { + for (int64_t k = 0; k < keep; ++k) { + float v = stitch(skip + k, Y, X, c); + if (!first && k < blend) { + const int64_t pb = rowoff(prev, k * npx + px, 3); + const float pv = ldt(prev, pb + c * laststride(prev)); + v = rd(rd(pv * wa(k, blend)) + rd(v * wb(k, blend))); + } + byte(k, px, c, v); + } + for (int64_t k = 0; k < blend; ++k) { + const float v = stitch(2 * skip + keep + k, Y, X, c); + if (last) byte(keep + k, px, c, v); + stt(prev, rowoff(prev, k * npx + px, 3) + c * laststride(prev), v); + } + } + } + return RAD_OK; +} diff --git a/libref/ref_vsa.cpp b/libref/ref_vsa.cpp new file mode 100644 index 00000000..c29c65bd --- /dev/null +++ b/libref/ref_vsa.cpp @@ -0,0 +1,427 @@ +/* ref_vsa.cpp -- video sparse attention (docs/OPS.md, "Video sparse attention"): the tile + * selection and the block-sparse attention a step-distilled MiniMax-H3 was trained with. + * + * A pass's rows are one packed sequence cut by `segs` (cumulative row offsets from 0) into + * segments: every segment but the last is dense (the text, the soundtrack), the last is the video + * grid of F x Hp x Wp patch rows, (t, h, w) row-major, its extents read from the `geom` operand the + * run phase writes on the device (RAD_VGEOM_*), never from the parameters, which are fixed at + * declare. The tiles, at most TT = tile_t tile_h tile_w rows each: + * + * prefix each dense segment cut on its own into chunks of TT rows from its start, the last + * chunk shorter, an empty segment none; tiles 0 .. P-1 in segment order + * video boxes of tile_t x tile_h x tile_w over the grid, edge boxes smaller; box (a, b, c) + * is tile P + (a nb + b) nc + c, nb and nc the boxes along h and w; V of them + * + * A tile's rows are taken in its (t, h, w) raster order, which fixes the order of every f32 sum + * over a tile. Video query tiles keep the k = max(1, min(ceil((1 - sparsity) V), V)) video tiles + * of largest pooled score, k computed in f64 as the trained schedule computes it, and see the + * prefix tiles besides; prefix query tiles see every tile. + */ +#include "ref_common.h" +#include "ref_gemm.h" /* row_stride */ +#include "ref_ops.h" +#include "rad_runtime.h" /* RAD_VGEOM_* */ + +#include +#include + +using namespace ref; + +namespace { + +/* `sparsity` at full precision, since k is computed from it in f64; NaN when absent, which every + * caller refuses. As p_f32, an integer or string spelling is read for a direct caller. */ +double p_f64(const RadArgs* a, const char* k) { + const RadParam* p = p_find(a, k); + if (!p) return NAN; + if (p->kind == RAD_P_F64) return p->dval; + if (p->kind == RAD_P_STR && p->sval) return std::strtod(p->sval, nullptr); + if (p->kind == RAD_P_INT) return (double)p->ival; + return NAN; +} + +/* A call's tiles. */ +struct Tiles { + int64_t R = 0; /* rows the tiles cover, segs[n_seg] */ + int64_t v0 = 0; /* the video grid's first row */ + int64_t tt = 0, th = 0, tw = 0; /* the box */ + int64_t F = 0, Hp = 0, Wp = 0; /* the grid */ + int64_t nb = 0, nc = 0; /* boxes along h and w */ + int64_t P = 0, V = 0, N = 0, k = 0; + std::vector start, len; /* the prefix tiles' rows */ +}; + +/* The tiles of this call; RAD_E_SHAPE where `segs` is not cumulative offsets from 0 covering at + * least one row and at most `rows`, the last segment is not the grid's F Hp Wp rows, a box extent + * or `patch` is not positive, or `sparsity` is outside [0, 1). */ +int tiles_of(const RadArgs* a, const RadTensor* segs, const RadTensor* geom, int64_t rows, + Tiles* g) { + g->tt = p_int(a, "tile_t", 0); + g->th = p_int(a, "tile_h", 0); + g->tw = p_int(a, "tile_w", 0); + const int64_t patch = p_int(a, "patch", 0); + const double sparsity = p_f64(a, "sparsity"); + if (g->tt <= 0 || g->th <= 0 || g->tw <= 0 || patch <= 0 || + !(sparsity >= 0.0 && sparsity < 1.0)) + return RAD_E_SHAPE; + const int64_t n_seg = numel(segs) - 1; + if (n_seg < 1 || numel(geom) <= RAD_VGEOM_LAT_W || cu_at(segs, 0) != 0) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seg; ++s) + if (cu_at(segs, s + 1) < cu_at(segs, s)) return RAD_E_SHAPE; + g->R = cu_at(segs, n_seg); + g->v0 = cu_at(segs, n_seg - 1); + if (g->R <= 0 || g->R > rows) return RAD_E_SHAPE; /* zero rows is not a call */ + g->F = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_FRAMES)); + g->Hp = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_H)) / patch; + g->Wp = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_W)) / patch; + /* Each extent at most the rows first, so the product cannot overflow. */ + const int64_t vr = g->R - g->v0; + if (g->F <= 0 || g->Hp <= 0 || g->Wp <= 0 || g->F > vr || g->Hp > vr || g->Wp > vr || + g->F * g->Hp * g->Wp != vr) + return RAD_E_SHAPE; + const int64_t TT = g->tt * g->th * g->tw; + g->start.clear(); + g->len.clear(); + for (int64_t s = 0; s + 1 < n_seg; ++s) + for (int64_t r = cu_at(segs, s), e = cu_at(segs, s + 1); r < e; r += TT) { + g->start.push_back(r); + g->len.push_back(std::min(TT, e - r)); + } + g->nb = (g->Hp + g->th - 1) / g->th; + g->nc = (g->Wp + g->tw - 1) / g->tw; + g->P = (int64_t)g->start.size(); + g->V = (g->F + g->tt - 1) / g->tt * g->nb * g->nc; + g->N = g->P + g->V; + const double keep = (1.0 - sparsity) * (double)g->V; + g->k = std::max(1, std::min((int64_t)std::ceil(keep), g->V)); + return RAD_OK; +} + +/* Video tile j's box, [t0, t1) x [h0, h1) x [w0, w1) of the grid. */ +struct Box { int64_t t0, t1, h0, h1, w0, w1; }; +Box box_of(const Tiles& g, int64_t j) { + const int64_t b = j - g.P, c = b % g.nc, bh = (b / g.nc) % g.nb, at = b / (g.nc * g.nb); + return { at * g.tt, std::min(g.F, (at + 1) * g.tt), bh * g.th, std::min(g.Hp, (bh + 1) * g.th), + c * g.tw, std::min(g.Wp, (c + 1) * g.tw) }; +} + +int64_t tile_size(const Tiles& g, int64_t j) { + if (j < g.P) return g.len[(size_t)j]; + const Box x = box_of(g, j); + return (x.t1 - x.t0) * (x.h1 - x.h0) * (x.w1 - x.w0); +} + +/* fn(row) for every row of tile j, in its raster order. */ +template +void tile_rows(const Tiles& g, int64_t j, Fn&& fn) { + if (j < g.P) { + for (int64_t r = g.start[(size_t)j], e = r + g.len[(size_t)j]; r < e; ++r) fn(r); + return; + } + const Box x = box_of(g, j); + for (int64_t t = x.t0; t < x.t1; ++t) + for (int64_t h = x.h0; h < x.h1; ++h) + for (int64_t w = x.w0; w < x.w1; ++w) fn(g.v0 + (t * g.Hp + h) * g.Wp + w); +} + +/* An operand read as [rows, n_head, head_dim]: rank 3, or rank 2 [rows, n_head head_dim] as a + * column slice of a wider projection at its own row pitch (attn_dense's reading). */ +struct Heads { + const RadTensor* t; + int64_t rs, hs, ds; +}; +Heads heads_of(const RadTensor* t, int64_t nh, int64_t hd) { + Heads v{ t, 0, 0, 0 }; + v.ds = t->rank >= 2 ? t->stride[t->rank - 1] : 1; + v.hs = t->rank >= 3 ? t->stride[t->rank - 2] : hd * v.ds; + v.rs = row_stride(t, nh * hd); + return v; +} + +/* The head count `q` carries, or 0 when its shape is not [rows, n_head, head_dim] or + * [rows, n_head head_dim]. */ +int64_t heads_in(const RadTensor* q, int64_t hd) { + if (q->rank >= 3) return q->shape[q->rank - 1] == hd ? q->shape[q->rank - 2] : 0; + if (q->rank == 2) return q->shape[1] % hd == 0 ? q->shape[1] / hd : 0; + return 0; +} + +/* Rows of a per-(head, tile) operand, [n_head, tiles_cap, cols] read as [n_head tiles_cap, cols]: + * tiles_cap, or 0 when the rows do not split evenly over the heads. */ +int64_t tiles_cap(const RadTensor* t, int64_t cols, int64_t nh) { + const int64_t r = rows_of(t, cols); + return r % nh == 0 ? r / nh : 0; +} + +/* The selection's order: the larger score first, NaN above every number (torch.topk's ranking), + * equal scores (+0 and -0 among them) tied. */ +inline bool above(float a, float b) { + if (a != a) return b == b; + return b == b && a > b; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ vsa_select */ +/* Per head h and tile i, the f32 means of q, k and (with `coarse`) v over the tile's rows, each + * summed in the tile's raster order and divided by its size: + * + * S[h][i][j] = f32(dot(qp[h][i], kp[h][j]) * scale) the dot an f32 sum in ascending d + * + * For a video query tile i, sel[h][i][0 .. k) is the k video tiles j of largest S[h][i][j], + * ties to the lower tile, in ascending tile order: the k-th largest score is the threshold, every + * tile above it is taken and the ties at it from the lowest. Prefix query tiles' rows of `sel` + * and its slots past k are not written. + * + * With `coarse` (and `v`, read for it alone), for every tile i: p = softmax over all N tiles of + * S[h][i][:] (the max subtracted, e_j = exp(S_j - max) summed in ascending j, p_j = e_j / sum), + * coarse[h][i][d] = sum over ascending j of p_j vp[h][j][d], rounded once to coarse's dtype. + * `sel` is i32 [n_head, tiles_cap >= N, k_cap >= k], `coarse` [n_head, tiles_cap >= N, + * head_dim]. */ +int ref_vsa_select(const RadArgs* a, RadStream) { + const RadTensor *q = t_in(a, 0), *k = t_in(a, 1), *v = t_in(a, 2), *segs = t_in(a, 3); + const RadTensor *geom = t_in(a, 4), *sel = t_in(a, 5), *co = t_in(a, 6); + if (!q || !k || !segs || !geom || !sel) return RAD_E_INVAL; + if (!v != !co) return RAD_E_SHAPE; + if (sel->dtype != RAD_I32) return RAD_E_DTYPE; + const int64_t hd = p_int(a, "head_dim", 0); + if (hd <= 0) return RAD_E_SHAPE; + const int64_t nh = heads_in(q, hd); + if (nh <= 0) return RAD_E_SHAPE; + Tiles g; + RAD_REF_TRY(tiles_of(a, segs, geom, numel(q) / (nh * hd), &g)); + const int64_t need = g.R * nh * hd; + if (numel(k) < need || (v && numel(v) < need)) return RAD_E_SHAPE; + const int64_t kc = sel->rank ? sel->shape[sel->rank - 1] : 0; + const int64_t scap = tiles_cap(sel, kc, nh); + if (kc < g.k || scap < g.N) return RAD_E_SHAPE; + const int64_t ccap = co ? tiles_cap(co, hd, nh) : 0; + if (co && (co->shape[co->rank - 1] != hd || ccap < g.N)) return RAD_E_SHAPE; + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd)); + const Heads Q = heads_of(q, nh, hd), K = heads_of(k, nh, hd); + const Heads Vh = v ? heads_of(v, nh, hd) : Heads{ nullptr, 0, 0, 0 }; + const int64_t N = g.N, P = g.P; + + /* The pooled means, [n_head][N][head_dim] each. */ + std::vector qp((size_t)(nh * N * hd)), kp(qp.size()), vp(co ? qp.size() : 0); + REF_PAR_FOR(nh * g.R * hd * (co ? 3 : 2)) + for (int64_t u = 0; u < nh * N; ++u) { + const int64_t h = u / N, j = u % N; + float* qs = &qp[(size_t)(u * hd)]; + float* ks = &kp[(size_t)(u * hd)]; + float* vs = co ? &vp[(size_t)(u * hd)] : nullptr; + for (int64_t d = 0; d < hd; ++d) { + qs[d] = ks[d] = 0.0f; + if (vs) vs[d] = 0.0f; + } + tile_rows(g, j, [&](int64_t r) { + for (int64_t d = 0; d < hd; ++d) { + qs[d] += ldt(q, r * Q.rs + h * Q.hs + d * Q.ds); + ks[d] += ldt(k, r * K.rs + h * K.hs + d * K.ds); + if (vs) vs[d] += ldt(v, r * Vh.rs + h * Vh.hs + d * Vh.ds); + } + }); + const float n = (float)tile_size(g, j); + for (int64_t d = 0; d < hd; ++d) { + qs[d] /= n; + ks[d] /= n; + if (vs) vs[d] /= n; + } + } + + REF_PAR_FOR(nh * N * N * hd) + for (int64_t u = 0; u < nh * N; ++u) { + const int64_t h = u / N, i = u % N; + if (i < P && !co) continue; + /* Scores against every tile when the coarse branch needs them, else the video tiles. */ + const int64_t j0 = co ? 0 : P; + std::vector S((size_t)N, 0.0f); + const float* qs = &qp[(size_t)(u * hd)]; + for (int64_t j = j0; j < N; ++j) { + const float* ks = &kp[(size_t)((h * N + j) * hd)]; + float dot = 0.0f; + for (int64_t d = 0; d < hd; ++d) dot += qs[d] * ks[d]; + S[(size_t)j] = dot * scale; + } + if (i >= P) { + const int64_t V = g.V, kk = g.k; + std::vector ord(S.begin() + P, S.end()); + std::nth_element(ord.begin(), ord.begin() + (kk - 1), ord.end(), above); + const float thr = ord[(size_t)(kk - 1)]; + int64_t ties = kk; + for (int64_t j = 0; j < V; ++j) ties -= above(S[(size_t)(P + j)], thr); + const int64_t sb = rowoff(sel, h * scap + i, kc), ss = laststride(sel); + int64_t n = 0; + for (int64_t j = 0; j < V; ++j) { + const float s = S[(size_t)(P + j)]; + const bool take = above(s, thr) || (!above(thr, s) && ties-- > 0); + if (take) st_int(sel->dtype, sel->data, sb + (n++) * ss, P + j); + } + } + if (co) { + float mx = -INFINITY; + for (int64_t j = 0; j < N; ++j) if (S[(size_t)j] > mx) mx = S[(size_t)j]; + float sum = 0.0f; + for (int64_t j = 0; j < N; ++j) { + S[(size_t)j] = ref_exp(S[(size_t)j] - mx); + sum += S[(size_t)j]; + } + std::vector acc((size_t)hd, 0.0f); + for (int64_t j = 0; j < N; ++j) { + const float p = S[(size_t)j] / sum; + const float* vs = &vp[(size_t)((h * N + j) * hd)]; + for (int64_t d = 0; d < hd; ++d) acc[(size_t)d] += p * vs[d]; + } + const int64_t cb = rowoff(co, h * ccap + i, hd), cs = laststride(co); + for (int64_t d = 0; d < hd; ++d) stt(co, cb + d * cs, acc[(size_t)d]); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ attn_vsa */ +/* Block-sparse softmax attention over the tiles, per head (q, k and v share their heads). A query + * row of tile i sees the rows of every tile when i < P, else of the prefix tiles and the k video + * tiles sel[h][i][0 .. k); each such row of `sel` must be k ascending video tiles, RAD_E_INVAL + * otherwise, checked before anything is written. Keys are taken by ascending tile and each tile + * in its raster order: every score f32(dot * scale) (the dot an f32 sum in ascending d), their + * max, then e = exp(score - max) and e v accumulated in that order, o = acc * (1 / sum). + * + * out = o without coarse and gate + * out = f32(rd(o) + f32(coarse[h][i] * gate[r, h])) with them + * + * rd rounding to out's dtype and the result rounded again by the store: FastVideo's inference + * epilogue, the sparse output in bf16 and then out.addcmul_(coarse, gate) in bf16 with f32 + * arithmetic. `coarse` is vsa_select's, `gate` per element like q; both or neither. + * + * `qk` "i8" is the int8 score form: `k_i8` and `k_scale` are k's codes and per-(row, head) scales + * as quant_act_i8g writes them at group head_dim, the query row is quantised here by the same rule, + * and a score is f32(f32(f32(dot * q_scale) * k_scale) * scale) with the dot the codes' exact sum; + * `k` is not read. + * + * `pv` "fp8" is the fp8 P.V form: `v` holds E4M3 codes with a scale per column in `v_scale` + * (quant_cols_fp8), each weight p = exp(s - max) is taken to E4M3 at 448 p, and + * o = (sum w v) v_scale / (448 sum p) in f32. */ +int ref_attn_vsa(const RadArgs* a, RadStream) { + const RadTensor *q = t_in(a, 0), *k = t_in(a, 1), *v = t_in(a, 2), *segs = t_in(a, 3); + const RadTensor *geom = t_in(a, 4), *sel = t_in(a, 5), *co = t_in(a, 6), *gt = t_in(a, 7); + const RadTensor* o = t_in(a, 8); + const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10), *vsc = a->n_t > 11 ? t_in(a, 11) : nullptr; + if (!q || !k || !v || !segs || !geom || !sel || !o) return RAD_E_INVAL; + const char* pv = p_str(a, "pv", "bf16"); + const bool pv8 = std::strcmp(pv, "fp8") == 0; + if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL; + if (!co != !gt) return RAD_E_SHAPE; + const char* qk = p_str(a, "qk", "bf16"); + const bool i8 = std::strcmp(qk, "i8") == 0; + if ((!i8 && std::strcmp(qk, "bf16") != 0) || i8 != (k8 != nullptr) || i8 != (ks != nullptr)) + return RAD_E_INVAL; + if (sel->dtype != RAD_I32) return RAD_E_DTYPE; + const int64_t hd = p_int(a, "head_dim", 0); + if (hd <= 0) return RAD_E_SHAPE; + const int64_t nh = heads_in(q, hd); + if (nh <= 0) return RAD_E_SHAPE; + Tiles g; + RAD_REF_TRY(tiles_of(a, segs, geom, numel(q) / (nh * hd), &g)); + const int64_t need = g.R * nh * hd; + if (numel(k) < need || numel(v) < need || numel(o) < need || (gt && numel(gt) < need)) + return RAD_E_SHAPE; + const int64_t kc = sel->rank ? sel->shape[sel->rank - 1] : 0; + const int64_t scap = tiles_cap(sel, kc, nh); + if (kc < g.k || scap < g.N) return RAD_E_SHAPE; + const int64_t ccap = co ? tiles_cap(co, hd, nh) : 0; + if (co && (co->shape[co->rank - 1] != hd || ccap < g.N)) return RAD_E_SHAPE; + const int64_t N = g.N, P = g.P, kk = g.k, ss = laststride(sel); + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = P; i < N; ++i) { + const int64_t sb = rowoff(sel, h * scap + i, kc); + int64_t prev = P - 1; + for (int64_t s = 0; s < kk; ++s) { + const int64_t j = ld_int(sel->dtype, sel->data, sb + s * ss); + if (j <= prev || j >= N) return RAD_E_INVAL; + prev = j; + } + } + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd)); + const Heads Q = heads_of(q, nh, hd), K = heads_of(k, nh, hd), Vh = heads_of(v, nh, hd); + const Heads O = heads_of(o, nh, hd); + const Heads G = gt ? heads_of(gt, nh, hd) : Heads{ nullptr, 0, 0, 0 }; + const Heads K8 = i8 ? heads_of(k8, nh, hd) : Heads{ nullptr, 0, 0, 0 }; + const int64_t ks_rs = i8 ? row_stride(ks, nh) : 0; + if (i8 && (numel(k8) < need || numel(ks) < g.R * nh)) return RAD_E_SHAPE; + + REF_PAR_REGION(nh * g.R * hd * 64) + { + float* const ws = ws_get((size_t)(g.R + 2 * hd)); + float* const sc = ws; + float* const qf = ws + g.R; + float* const acc = qf + hd; + std::vector vis; + REF_FOR_DYN + for (int64_t u = 0; u < nh * N; ++u) { + const int64_t h = u / N, i = u % N; + vis.clear(); + for (int64_t j = 0; j < (i < P ? N : P); ++j) vis.push_back(j); + if (i >= P) { + const int64_t sb = rowoff(sel, h * scap + i, kc); + for (int64_t s = 0; s < kk; ++s) + vis.push_back(ld_int(sel->dtype, sel->data, sb + s * ss)); + } + const int64_t cb = co ? rowoff(co, h * ccap + i, hd) : 0; + const int64_t cs = co ? laststride(co) : 0; + tile_rows(g, i, [&](int64_t r) { + const int64_t qb = r * Q.rs + h * Q.hs, ob = r * O.rs + h * O.hs; + for (int64_t d = 0; d < hd; ++d) qf[d] = ldt(q, qb + d * Q.ds); + const float qs = i8 ? ref_q8_row(qf, hd, qf) : 1.0f; + /* Pass one: every visible key's score, and the max. */ + int64_t n = 0; + float mx = -INFINITY; + for (int64_t j : vis) + tile_rows(g, j, [&](int64_t c) { + float dot = 0.0f; + if (i8) { + /* Integers below 2^24 in magnitude: the f32 sum is exact. */ + const int64_t kb = c * K8.rs + h * K8.hs; + for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(k8, kb + d * K8.ds); + dot = dot * qs * ldt(ks, c * ks_rs + h); + } else { + const int64_t kb = c * K.rs + h * K.hs; + for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(k, kb + d * K.ds); + } + dot *= scale; + sc[n++] = dot; + if (dot > mx) mx = dot; + }); + if (mx == -INFINITY) { + for (int64_t d = 0; d < hd; ++d) stt(o, ob + d * O.ds, 0.0f); + return; + } + /* Pass two: exponentiate and accumulate in the same order. */ + for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f; + float sum = 0.0f; + n = 0; + for (int64_t j : vis) + tile_rows(g, j, [&](int64_t c) { + const float p = ref_exp(sc[n++] - mx); + sum += p; + const float w = pv8 ? round_dt(RAD_F8E4M3, 448.0f * p) : p; + const int64_t vb = c * Vh.rs + h * Vh.hs; + for (int64_t d = 0; d < hd; ++d) acc[d] += w * ldt(v, vb + d * Vh.ds); + }); + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f; + for (int64_t d = 0; d < hd; ++d) { + float y = pv8 ? acc[d] * ldt(vsc, offlin(vsc, h * hd + d)) * inv8 + : acc[d] * inv; + if (co) { + const float c = ldt(co, cb + d * cs); + const float e = ldt(gt, r * G.rs + h * G.hs + d * G.ds); + y = round_dt(o->dtype, y) + c * e; + } + stt(o, ob + d * O.ds, y); + } + }); + } + } + return RAD_OK; +} diff --git a/scripts/README.md b/scripts/README.md index ecf58b56..1133f833 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -11,7 +11,7 @@ checkout the script is in, and default to containers under `$HOME/models/rad/` a running (`oracle.sh` only the one on its own port) and logs to `$HOME/