From 7d840861afd568cc1b29245fb688fe52452b3077 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Wed, 7 Oct 2026 22:42:45 +0200 Subject: [PATCH] radiance 1.2.4 - EmbeddingGemma 2 (google/embeddinggemma-2): text, image, video and audio embeddings on the card (libr4d) and on the CPU (libavx); prompt_name, Matryoshka dimensions, image budgets, mixed content parts and the messages form on /v1/embeddings - #43: on serves that lend the activation arena to the experts (Qwen3.8-Flash-Next with expert_tiered), every image after the first read its rows from the wrong place -- garbage replies, or an earlier request's image. Fixed - the Qwen vision towers' attention resolves on the card again (broken on main after 1.2.3, never released) - #42: a warning at startup when amdgpu cwsr_enable is 0, and a stalled queue is reported as slow or stuck; the guide covers the GPU-hang-and-reset chain --- CMakeLists.txt | 15 +- Dockerfile | 12 +- README.md | 1 + abi/rad_builder.h | 47 +- abi/rad_runtime.h | 14 +- arch/embgemma2/CMakeLists.txt | 11 + arch/embgemma2/embgemma2.cpp | 1206 +++++++++++++++++++++++++++ core/build/rad_build.h | 1 + core/build/rad_builder.cpp | 87 +- core/build/startup.cpp | 4 +- core/config.cpp | 11 +- core/device/aql.cpp | 36 +- core/device/dispatch.cpp | 21 + core/engine.cpp | 235 +++++- core/engine.h | 9 + core/engine_bringup.cpp | 43 +- core/engine_mm.cpp | 146 ++-- core/format/checkpoint.cpp | 27 +- core/mm/item.cpp | 12 + core/mm/media.cpp | 160 +++- core/mm/media.h | 8 + core/mm/processor.cpp | 521 +++++++++++- core/mm/processor.h | 84 +- core/rad_core.h | 19 +- core/runtime/ctx.cpp | 16 +- core/runtime/oracle.cpp | 2 +- core/sched/batch.cpp | 47 +- core/sched/batch.h | 13 +- core/sched/scheduler.cpp | 12 +- core/sched/scheduler.h | 6 +- core/server/adapters.h | 11 +- core/server/iface.h | 34 +- core/server/oai.cpp | 460 +++++++--- core/server/oai.h | 6 + core/server/server.cpp | 141 +++- core/server/server.h | 4 + core/server/sink.h | 11 + core/text/tokenizer_json.cpp | 24 +- deploy/compose/.env.example | 3 + deploy/compose/embeddinggemma2.yaml | 15 + docs/ARCHITECTURES.md | 51 ++ docs/GUIDE.md | 46 +- docs/OPS.md | 101 ++- libavx/avx_attn.cpp | 500 ++++++++++- libavx/avx_cases.cpp | 74 +- libavx/avx_common.h | 46 +- libavx/avx_elementwise.cpp | 360 ++++++++ libavx/avx_gemm.cpp | 347 +++++++- libavx/avx_isa.h | 6 +- libavx/avx_norm.cpp | 18 +- libavx/avx_registry.cpp | 83 +- libr4d/CMakeLists.txt | 4 + libr4d/r4d_attn_dense_bf16.hip | 384 +++++++++ libr4d/r4d_attn_vit_h72_bf16.hip | 2 + libr4d/r4d_encoder_bf16.hip | 1028 +++++++++++++++++++++++ libr4d/r4d_fuse.cpp | 15 +- libr4d/r4d_model_bf16.hip | 99 ++- libr4d/r4d_plugin.h | 15 + libr4d/r4d_rows.cpp | 309 ++++++- libr4d/r4d_selftest.cpp | 425 ++++++++++ libr4d/r4d_shapes.cpp | 20 +- libref/ref_attn.cpp | 197 ++++- libref/ref_elementwise.cpp | 321 ++++++- libref/ref_gemm.cpp | 3 +- libref/ref_ops.h | 20 + libref/ref_quant.cpp | 2 +- libref/ref_registry.cpp | 124 ++- libref/ref_shapes.cpp | 154 +++- tests/arch_test.cpp | 10 +- tests/mm_test.cpp | 51 ++ tests/plugin_test.cpp | 25 + tests/ref_test.cpp | 265 +++++- tests/server_test.cpp | 73 +- tests/wire_test.cpp | 19 + tools/rad_convert.cpp | 21 +- tools/rad_kbench.cpp | 38 + 76 files changed, 8324 insertions(+), 467 deletions(-) create mode 100644 arch/embgemma2/CMakeLists.txt create mode 100644 arch/embgemma2/embgemma2.cpp create mode 100644 deploy/compose/embeddinggemma2.yaml create mode 100644 libr4d/r4d_attn_dense_bf16.hip create mode 100644 libr4d/r4d_encoder_bf16.hip diff --git a/CMakeLists.txt b/CMakeLists.txt index ec4b73ef..e2c98f25 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.2.3 LANGUAGES C CXX) +project(radiance VERSION 1.2.4 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -18,7 +18,7 @@ endif() # cache STRING. set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels") set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO) -set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image and video parts with libavformat/libavcodec/libswscale") +set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample") set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO) option(RAD_BUILD_TESTS "Build the test suite" ON) option(RAD_ASAN "Build with AddressSanitizer" OFF) @@ -316,22 +316,23 @@ endif() find_package(Threads REQUIRED) # ---------------------------------------------------------------- media decoding -# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by -# libswscale (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a +# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by +# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a # media part by name -- the same tri-state as HIP, because a machine that has the libraries should # not silently build without them. set(RAD_FFMPEG_FOUND OFF) if(NOT RAD_WITH_FFMPEG STREQUAL "OFF") find_package(PkgConfig QUIET) if(PkgConfig_FOUND) - pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale) + pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale + libswresample) endif() if(RAD_FFMPEG_FOUND) message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}") elseif(RAD_WITH_FFMPEG STREQUAL "ON") - message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.") + message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale/libswresample were not found.") else() - message(STATUS "radiance: no libavformat -- image and video input will be refused") + message(STATUS "radiance: no libavformat -- image, video and audio input will be refused") endif() endif() diff --git a/Dockerfile b/Dockerfile index 994c0c67..8b27ab74 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,8 +11,8 @@ # # Stages: # ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their -# streams need; the distribution's build brings ~200 packages of encoders, filters and -# display libraries the engine never calls +# streams need (pictures, video, and audio with swresample); the distribution's build +# brings ~200 packages of encoders, filters and display libraries the engine never calls # build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage # test `ctest -LE gpu` on that build -- everything that does not need a card # rootfs the install tree stripped, and every library its binaries and plugins load, resolved @@ -59,11 +59,11 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ && tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \ && ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \ --disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \ - --disable-avdevice --disable-avfilter --disable-swresample \ + --disable-avdevice --disable-avfilter --enable-swresample \ --enable-zlib --enable-libdav1d \ - --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 \ - --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 \ - --enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \ + --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-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 \ && mkdir -p /opt/ffmpeg/share/doc/ffmpeg \ diff --git a/README.md b/README.md index b1dae9d3..2ad063a9 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ If you wish to support the developement of the radiance engine you can do so [he | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.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` | +| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | A container holds everything the server needs: the weights, the tokeniser, the chat template and any drafter. Each download link's repository has the recipe and the exact command that made the diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 13606344..a0540103 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -134,6 +134,15 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int64_t max_out_rows; + + /* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no + * audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way + * max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds + * the longest clip, since one clip is one segment. The engine takes it from + * RadArchProbe::audio_frames, which is the plugin's statement of its longest clip. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int64_t max_audio_frames; } RadBuildCtx; /* ================================================================== weights */ @@ -443,6 +452,25 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); * the first step. An embedding-only or encoder-only plugin declares none, deliberately. */ int rad_declare_logits(RadBuilder* b, rad_buf logits); +/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits, + * one row a sequence of the step -- row s is sequence s's whole input pooled into one vector, + * whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads + * rows [0, n_seq) back after the step and hands each to its request; it does not normalise them, + * because that is the API's choice and not the model's. + * + * DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is: + * + * - every sequence in a step is a WHOLE input. The scheduler never splits one across steps, + * because an encoder that attends both ways cannot be fed half of its input, and it refuses + * an input longer than one step's tokens rather than truncating it; + * - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request + * ends at the step that carried it. + * + * f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A + * Program declares this or logits, never both -- a model that both generates and embeds is two + * deployments. */ +int rad_declare_pooled(RadBuilder* b, rad_buf pooled); + /* ================================================================== the drafter */ /* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits @@ -531,17 +559,21 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d); * the processor's (core/mm), which reads its geometry from the container: the two agree through * `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the * processor about either. */ +/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio + * encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and + * its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */ enum { RAD_MM_IMAGE = 1u << 0, RAD_MM_VIDEO = 1u << 1, + RAD_MM_AUDIO = 1u << 2, }; typedef struct RadEncoderDecl { const char* name; /* "vision" -- for messages */ - uint32_t modalities; /* RAD_MM_* this encoder serves */ + uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */ int64_t patch_dim; /* elements in one input patch row */ int64_t merge; /* input patches per output row */ - int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */ + int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches (max_audio_frames) */ int64_t n_embd; /* the width of an output row, the model's embedding width */ /* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after * the pass and before any other pass runs, so the planner may share its bytes with buffers @@ -612,6 +644,17 @@ typedef struct RadArchProbe { * function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the * core does not ask, and the activation arena is not lent. */ int shape_probe_ok; + + /* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin + * declares an encoder. A pass carries whole output rows, so the core rounds the pass size it + * picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator + * names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */ + int64_t enc_merge; + + /* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole + * number of its merge), when it declares one: the engine sizes the audio pass with it + * (RadBuildCtx::max_audio_frames). 0 is no audio. */ + int64_t audio_frames; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 6e676ae4..5892f88e 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -206,10 +206,16 @@ typedef struct RadBatch { const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */ const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */ - /* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder) - * and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already - * resized, normalised and cut by the processor, and its output is the encoder's declared - * `out` buffer, one row per `merge` patches, which the core reads back after the pass. + /* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing + * else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO + * for an audio encoder, the image/video mask for the other -- so a program that declared two + * knows which to run. Its input is a list of patches, already resized, normalised and cut by + * the processor, and its output is the encoder's declared `out` buffer, one row per `merge` + * patches, which the core reads back after the pass. + * + * An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's + * index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the + * clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones. * * Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video * -- and attention runs within a segment. `enc_coord` gives each patch its place in its diff --git a/arch/embgemma2/CMakeLists.txt b/arch/embgemma2/CMakeLists.txt new file mode 100644 index 00000000..e7119f87 --- /dev/null +++ b/arch/embgemma2/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(embgemma2 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp) diff --git a/arch/embgemma2/embgemma2.cpp b/arch/embgemma2/embgemma2.cpp new file mode 100644 index 00000000..1fe96b41 --- /dev/null +++ b/arch/embgemma2/embgemma2.cpp @@ -0,0 +1,1206 @@ +/* embgemma2 -- EmbeddingGemma 2, a bidirectional Gemma encoder that pools a whole input into one + * vector. bf16 weights and bf16 activations. + * + * AN EMBEDDING MODEL, NOT A GENERATIVE ONE. It declares a pooled output (rad_declare_pooled) and + * no logits, so the engine runs it with no sampler and no KV cache, carries every input whole in + * one step and hands each sequence's pooled row back as its answer. Attention is BIDIRECTIONAL on + * every layer, which is why nothing is paged: a token attends to the tokens after it, so there is + * nothing a cache could carry from one step to the next. + * + * ============================== THE SHAPE ============================== + * + * 24 layers, hidden 512, ffn 2048, vocab 262144, embedding scale sqrt(512) rounded to bf16 + * layer_types: five `sliding_attention` then one `full_attention`, four times over + * sliding: 4 heads / 2 kv heads / head_dim 256, rope theta 1e4, |i - j| <= 512 + * full: 4 heads / 1 kv head / head_dim 512, rope theta 1e6, the whole input + * attention scale 1.0 (the q/k norms carry the temperature); q, k AND v are RMS-normed per head, + * v with no gain + * Gemma's sandwich norms: a norm before AND after attention and the feed-forward, all plain + * RMSNorm gains (x_hat * w, not 1 + w) + * a gated gelu-tanh feed-forward + * PER-LAYER EMBEDDINGS, projection-only: the token embedding projected to 24 x 512, normed, and + * each layer's slice gating that layer's residual through a 512 -> 512 -> 512 bottleneck + * a learned scalar per layer, multiplying the residual stream at the layer's end + * final norm, then the mean over every token of the input, then 512 -> 768 + * + * The reference is transformers' modeling_embedding_gemma2 (model_type embedding_gemma2, which + * rad-convert spells `embeddinggemma2`). Its mean pooling and normalisation are + * sentence-transformers' modules on top; the normalisation is the server's (it truncates to + * `dimensions` first), so the pooled row here is the unnormalised mean. + * + * ============================== WHAT THIS PLUGIN DOES NOT YET DECLARE ============================== + * + * Nothing the checkpoint carries: the text model, the vision tower and the audio encoder are all + * below. + */ +#include + +#include +#include +#include +#include + +namespace embgemma2 { + +using namespace rad::arch; + +/* What a layer's attention is: the two kinds differ in head width, KV head count, rotary base and + * window, and nothing else. */ +struct Kind { + int64_t head_dim = 0; + int64_t n_head = 0; + int64_t n_head_kv = 0; + double theta = 0.0; + int64_t window = 0; /* attn_dense's `window`: |i - j| < window, 0 the whole input */ + int64_t qkv() const { return (n_head + 2 * n_head_kv) * head_dim; } + int64_t q() const { return n_head * head_dim; } +}; + +struct Layer { + int full = 0; + rad_weight w_in_norm = 0, w_qkv = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0, w_post_attn = 0; + rad_weight w_pre_ff = 0, w_gate_up = 0, w_down = 0, w_post_ff = 0; + rad_weight w_ple_gate = 0, w_ple_proj = 0, w_post_ple = 0, w_scalar = 0; + rad_op op_in_norm = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_post_attn = 0; + rad_op op_add_attn = 0, op_pre_ff = 0, op_gate_up = 0, op_act = 0, op_down = 0; + rad_op op_post_ff = 0, op_add_ff = 0, op_ple_gate = 0, op_ple_act = 0, op_ple_proj = 0; + rad_op op_post_ple = 0, op_add_ple = 0, op_scale = 0; +}; + +/* ============================== THE VISION TOWER (Gemma 4's) ============================== + * + * a patch is 16 x 16 x 3, staged by the processor as 2 * (u / 255) - 1 in bf16, (y, x, channel) + * patch embedding: a 768 x 768 linear, plus a learned row for the patch's column and one for its + * row (a [2, 10240, 768] table), the two summed first + * 16 layers: Gemma's sandwich norms, q/k RMS-normed with a gain and v without one, a 2-D rotary + * (theta 100) with x over the first half of each 64-wide head and y over the second, each half a + * rotary of its own; bidirectional attention within an image at scale 1; a gated gelu-tanh MLP + * pooling: the mean of each 3 x 3 window -- the processor lays a window's nine patches out + * consecutively -- times sqrt(768), then the multimodal embedder: an RMS norm with no gain and a + * 768 -> 512 linear. Its rows take the place of the image's placeholder tokens BEFORE the + * per-layer inputs are projected, so the per-layer inputs of an image token are its image row's. + * + * One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an + * image, or one frame of a video). */ +struct Vision { + struct Layer { + rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0; + rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0; + rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0; + rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0; + }; + bool on = false; + int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0; + int64_t npos = 0, n_embd = 0; + rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0; + rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0; + rad_op op_out = 0; + rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0, + b_py = 0, b_pool = 0, b_pn = 0, b_out = 0; + std::vector L; + + static bool present(const RadModelMeta* m) { + const char* t = rad_meta_gets(m, "vision_config.model_type", ""); + return t && !std::strcmp(t, "gemma4_vision"); + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group) { + on = false; + if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0); + hd = rad_meta_geti(m, "vision_config.head_dim", 0); + ff = rad_meta_geti(m, "vision_config.intermediate_size", 0); + pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0); + npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0); + const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0); + const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0); + const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads); + const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6); + const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0); + const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", ""); + const char* act = rad_meta_gets(m, "vision_config.hidden_activation", ""); + if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 || + depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads || + hd % 4) { + fprintf(stderr, "radiance: embgemma2: the container's vision_config is incomplete or " + "not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv " + "%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width, + (long long)heads, (long long)hd, (long long)kvh, (long long)ff, + (long long)pool, (long long)depth); + return RAD_E_INVAL; + } + /* What this tower does not carry is refused by name: clipped linears (their bounds are + * buffers the vision checkpoint states as infinite), feature standardisation, and any + * rotary or activation other than the axial one and gelu-tanh. */ + if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) || + rad_meta_geti(m, "vision_config.standardize", 0) || std::strcmp(rt, "axial") || + std::strcmp(act, "gelu_pytorch_tanh")) { + fprintf(stderr, "radiance: embgemma2: this vision tower uses clipped linears, " + "standardisation, a '%s' rotary or a '%s' activation, which this " + "plugin does not serve\n", rt, act); + return RAD_E_UNSUPPORTED; + } + n_embd = model_embd; + patch_dim = 3 * patch * patch; + const int64_t kk = pool * pool; + P = ctx->max_enc_patches; + if (P % kk) P -= P % kk; + R = P / kk; + const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE; + const char* V = "vision_tower"; + + /* ---- weights: the stem, the position tables and the embedder are model-level; each + * tower layer is its own group, past every text layer. */ + RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V))); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0)); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1)); + RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("embed_vision.embedding_projection.weight"))); + w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model()); + w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model()); + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const long long li = (long long)i; + const RadWeightGroup g = grp_layer(first_group + (int)i); + auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); }; + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li), + {src("self_attn.q_proj.linear.weight"), + src("self_attn.k_proj.linear.weight"), + src("self_attn.v_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li), + {src("mlp.gate_proj.linear.weight"), + src("mlp.up_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight"))); + l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g); + l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g); + l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g); + l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g); + l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g); + l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g); + l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g); + l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g); + l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g); + l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g); + } + + /* ---- activations, sized by the pass. */ + b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width}); + b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width}); + b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width}); + b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width}); + b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width}); + b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff}); + b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff}); + b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width}); + b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width}); + b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width}); + b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width}); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd}); + + auto rms = [&](int64_t rows, rad_weight w) { + if (!w) + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) { + return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto add = [&](int64_t rows) { + return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + auto lookup = [&](rad_weight w) { + return RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width), + RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)), + RAD_WEIGHTS(w)); + }; + op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x}); + op_px = rw(b, lookup(w_px), {}, {b_px}); + op_py = rw(b, lookup(w_py), {}, {b_py}); + op_padd = rw(b, add(P), {b_px, b_py}, {b_px}); + op_add = rw(b, add(P), {b_x, b_px}, {b_x}); + char sec[48]; + std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4)); + for (Layer& l : L) { + l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h}); + l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv}); + /* x is the column (plane 1 of the staged coordinates), y the row (plane 0). */ + l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1), + RAD_STR("sections", sec), RAD_STR("comps", "1 0")), + RAD_WEIGHTS(l.q_norm, l.k_norm)), + {b_qkv}, {b_qkv}); + l.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", P), RAD_INT("window", 0)), + RAD_NOWEIGHTS), + {b_qkv}, {b_att}); + l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o}); + l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o}); + l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x}); + l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h}); + l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu}); + l.op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_gu}, {b_ff}); + l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o}); + l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o}); + l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x}); + } + op_pool = rw(b, RAD_OP(b, "pool_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_x}, {b_pool}); + op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn}); + op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out}); + + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO; + e.patch_dim = patch_dim; + e.merge = kk; + e.max_patches = P; + e.n_embd = n_embd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, " + "pooled %lldx%lld; %lld patches a pass -> %lld rows of %lld", + (long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff, + (long long)patch, (long long)pool, (long long)pool, (long long)P, (long long)R, + (long long)n_embd); + on = true; + return RAD_OK; + } + + void step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool; + if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) { + rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, " + "more patches than it was declared for, or not whole pooling windows"); + return; + } + const int64_t Rn = Pn / kk; + const int32_t* crd = batch->enc_coord; + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand rc = praw2(crd, RAD_I32, 2, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn)); + RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn)); + RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn)); + RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn)); + RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn)); + for (const Layer& l : L) { + RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn)); + RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm)); + RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), + bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn)); + RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); + RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn)); + RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn), + brows(b_ff, Pn)); + RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); + } + RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn)); + RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn)); + RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn)); + } +}; + +/* ============================== THE AUDIO ENCODER (Gemma 4's USM conformer) ============================== + * + * a frame is 128 log-mel bins (the processor's), four frames an output row + * subsampling: two 3x3 stride-2 convolutions over (time, frequency) -- 1 -> 128 -> 32 channels, + * each input masked to the clip's real frames first, each followed by a channel LayerNorm (no + * bias) and a ReLU -- then 32 x 32 features a row through a 1024 linear + * 12 conformer blocks: a feed-forward at half weight, local attention (11 frames back, a + * relative-position term, a softplus per-dimension query scale, a softcap of 50), a gated + * depthwise causal convolution, a second half-weight feed-forward, a norm; their linears are + * CLIPPED, input and output clamped to bounds the checkpoint stores + * 1024 -> 1536 with a bias, then the multimodal embedder: an RMS norm with no gain, 1536 -> 512. + * + * The blocks' clamps at +-1e10 ("gradient clipping") are left out: they bound activations ten + * orders of magnitude past anything bf16 holds near them, so they change nothing a pass computes. + * One clip is one segment; a pass carries up to RadBuildCtx::max_audio_frames frames. */ +struct Audio { + /* A clipped linear: the weight and its four bounds. */ + struct Clip { + rad_weight w = 0, in_lo = 0, in_hi = 0, out_lo = 0, out_hi = 0; + rad_op op_in = 0, op_mm = 0, op_out = 0; + }; + struct FF { + rad_weight pre = 0, post = 0; + Clip l1, l2; + rad_op op_pre = 0, op_act = 0, op_post = 0, op_add = 0; + }; + struct Layer { + FF ff1, ff2; + rad_weight n_pre_attn = 0, n_post_attn = 0, n_out = 0, w_rel = 0, pds = 0; + Clip q, k, v, post; + rad_weight lc_pre = 0, lc_dw = 0, lc_norm = 0; + Clip lc_start, lc_end; + rad_op op_npa = 0, op_rel = 0, op_attn = 0, op_npo = 0, op_add_attn = 0; + rad_op op_lc_pre = 0, op_glu = 0, op_dw = 0, op_lc_norm = 0, op_lc_act = 0, op_lc_add = 0; + rad_op op_out = 0; + }; + bool on = false; + int64_t P = 0, R = 0, H = 0, heads = 0, hd = 0, ffw = 0, n_embd = 0, out_dims = 0; + int64_t c0 = 0, c1 = 0, nmel = 0, merge = 4, left = 0, chunk = 0, n_rel = 0; + double eps = 1e-6, softcap = 0; + rad_weight w_c0 = 0, w_c1 = 0, w_n0 = 0, w_n1 = 0, w_in = 0, w_out = 0, b_outw = 0, w_emb = 0; + rad_op op_c0 = 0, op_n0 = 0, op_r0 = 0, op_c1 = 0, op_n1 = 0, op_r1 = 0, op_in = 0; + rad_op op_relpos = 0, op_outp = 0, op_en = 0, op_emb = 0; + rad_buf b_s0 = 0, b_s1 = 0, b_x = 0, b_h = 0, b_hc = 0, b_f = 0, b_q = 0, b_k = 0, b_v = 0; + rad_buf b_att = 0, b_o = 0, b_g = 0, b_u = 0, b_relpos = 0, b_relk = 0, b_o2 = 0, b_on = 0; + rad_buf b_out = 0; + std::vector L; + + static bool present(const RadModelMeta* m) { + const char* t = rad_meta_gets(m, "audio_config.model_type", ""); + return t && !std::strcmp(t, "gemma4_audio"); + } + /* The longest clip in frames: 30 s at the extractor's 10 ms hop, rounded up to whole rows. */ + static int64_t frames_for(const RadModelMeta* m) { + const int64_t rate = rad_meta_geti(m, "preprocessor.sampling_rate", 16000); + const int64_t fl = rad_meta_geti(m, "preprocessor.frame_length", 320); + const int64_t hop = rad_meta_geti(m, "preprocessor.hop_length", 160); + if (rate <= 0 || hop <= 0) return 0; + const int64_t n = 30 * rate; + const int64_t real = (n + fl / 2 - fl - 1) / hop + 1; + return (real + 3) / 4 * 4; + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group) { + on = false; + if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK; + const char* A = "audio_config"; + auto gi = [&](const char* k, int64_t d) { + char key[96]; + std::snprintf(key, sizeof key, "%s.%s", A, k); + return rad_meta_geti(m, key, d); + }; + auto gf = [&](const char* k, double d) { + char key[96]; + std::snprintf(key, sizeof key, "%s.%s", A, k); + return rad_meta_getf(m, key, d); + }; + H = gi("hidden_size", 0); + heads = gi("num_attention_heads", 0); + out_dims = gi("output_proj_dims", 0); + chunk = gi("attention_chunk_size", 0); + /* transformers masks a key unless 0 <= q - k < attention_context_left - 1, so the + * furthest key back is context_left - 2 frames: 11 for this checkpoint, the query and + * eleven before it. */ + left = gi("attention_context_left", 0) - 2; + softcap = gf("attention_logit_cap", 0.0); + eps = gf("rms_norm_eps", 1e-6); + const int64_t depth = gi("num_hidden_layers", 0); + const int64_t kconv = gi("conv_kernel_size", 0); + const int64_t right = gi("attention_context_right", 0); + const double resw = gf("residual_weight", 0.0); + const char* act = rad_meta_gets(m, "audio_config.hidden_act", ""); + const char* chs = rad_meta_gets(m, "audio_config.subsampling_conv_channels", ""); + nmel = rad_meta_geti(m, "preprocessor.feature_size", 0); + if (std::sscanf(chs ? chs : "", "%lld %lld", (long long*)&c0, (long long*)&c1) != 2) + c0 = c1 = 0; + hd = heads > 0 ? H / heads : 0; + ffw = 4 * H; + n_rel = left + 1; + if (H <= 0 || heads <= 0 || hd * heads != H || out_dims <= 0 || depth <= 0 || kconv <= 0 || + chunk <= 0 || left < 0 || right != 0 || !(softcap > 0) || resw != 0.5 || + std::strcmp(act ? act : "", "silu") || c0 <= 0 || c1 <= 0 || nmel != 128 || + (nmel / 4) * c1 != H) { + fprintf(stderr, "radiance: embgemma2: the container's audio_config is not the " + "conformer this plugin serves (hidden %lld, heads %lld, output %lld, " + "layers %lld, conv %lld, left %lld right %lld, residual %g, act %s, " + "subsampling %lld/%lld over %lld bins)\n", (long long)H, + (long long)heads, (long long)out_dims, (long long)depth, (long long)kconv, + (long long)left, (long long)right, resw, act ? act : "", (long long)c0, + (long long)c1, (long long)nmel); + return RAD_E_UNSUPPORTED; + } + n_embd = model_embd; + P = ctx->max_audio_frames; + if (P % merge) return RAD_E_SHAPE; + R = P / merge; + const int AC = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE; + const char* T = "audio_tower"; + + /* ---- weights */ + auto w = [&](const char* dn, const char* src, std::initializer_list shp, + RadWeightGroup g) -> rad_weight { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shp, AC, N, g); + }; + auto clip = [&](Clip& c, const char* dn, const char* src, int64_t out, int64_t in, + RadWeightGroup g) { + char d1[160], s1[200]; + std::snprintf(d1, sizeof d1, "%s.w", dn); std::snprintf(s1, sizeof s1, "%s.linear.weight", src); + c.w = w(nm.f("%s", d1), nm.ckpt("%s", s1), {out, in}, g); + const char* bn[4] = { "input_min", "input_max", "output_min", "output_max" }; + rad_weight* dst[4] = { &c.in_lo, &c.in_hi, &c.out_lo, &c.out_hi }; + for (int i = 0; i < 4; ++i) { + std::snprintf(d1, sizeof d1, "%s.%s", dn, bn[i]); + std::snprintf(s1, sizeof s1, "%s.%s", src, bn[i]); + *dst[i] = w(nm.f("%s", d1), nm.ckpt("%s", s1), {1}, g); + } + }; + w_c0 = w(nm.f("a.sscp.c0"), nm.ckpt("%s.subsample_conv_projection.layer0.conv.weight", T), {c0, 1, 3, 3}, grp_model()); + w_n0 = w(nm.f("a.sscp.n0"), nm.ckpt("%s.subsample_conv_projection.layer0.norm.weight", T), {c0}, grp_model()); + w_c1 = w(nm.f("a.sscp.c1"), nm.ckpt("%s.subsample_conv_projection.layer1.conv.weight", T), {c1, c0, 3, 3}, grp_model()); + w_n1 = w(nm.f("a.sscp.n1"), nm.ckpt("%s.subsample_conv_projection.layer1.norm.weight", T), {c1}, grp_model()); + w_in = w(nm.f("a.sscp.proj"), nm.ckpt("%s.subsample_conv_projection.input_proj_linear.weight", T), {H, H}, grp_model()); + w_out = w(nm.f("a.out.w"), nm.ckpt("%s.output_proj.weight", T), {out_dims, H}, grp_model()); + b_outw = w(nm.f("a.out.b"), nm.ckpt("%s.output_proj.bias", T), {out_dims}, grp_model()); + w_emb = w(nm.f("a.embed"), nm.ckpt("embed_audio.embedding_projection.weight"), {n_embd, out_dims}, grp_model()); + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const long long li = (long long)i; + const RadWeightGroup g = grp_layer(first_group + (int)i); + char d[96], s[160]; + auto D = [&](const char* x) { std::snprintf(d, sizeof d, "a.blk.%lld.%s", li, x); return nm.f("%s", d); }; + auto S = [&](const char* x) { std::snprintf(s, sizeof s, "%s.layers.%lld.%s", T, li, x); return nm.ckpt("%s", s); }; + for (int f = 0; f < 2; ++f) { + FF& ff = f ? l.ff2 : l.ff1; + const char* fn = f ? "feed_forward2" : "feed_forward1"; + char px[64]; std::snprintf(px, sizeof px, "%s.pre_layer_norm.weight", fn); + ff.pre = w(D(px), S(px), {H}, g); + std::snprintf(px, sizeof px, "%s.post_layer_norm.weight", fn); + ff.post = w(D(px), S(px), {H}, g); + char dn[96], sn[160]; + std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l1", li, fn); + std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_1", T, li, fn); + clip(ff.l1, dn, sn, ffw, H, g); + std::snprintf(dn, sizeof dn, "a.blk.%lld.%s.l2", li, fn); + std::snprintf(sn, sizeof sn, "%s.layers.%lld.%s.ffw_layer_2", T, li, fn); + clip(ff.l2, dn, sn, H, ffw, g); + } + l.n_pre_attn = w(D("norm_pre_attn"), S("norm_pre_attn.weight"), {H}, g); + l.n_post_attn = w(D("norm_post_attn"), S("norm_post_attn.weight"), {H}, g); + l.n_out = w(D("norm_out"), S("norm_out.weight"), {H}, g); + l.w_rel = w(D("rel_k"), S("self_attn.relative_k_proj.weight"), {H, H}, g); + l.pds = w(D("per_dim_scale"), S("self_attn.per_dim_scale"), {hd}, g); + const char* qn[4] = { "q_proj", "k_proj", "v_proj", "post" }; + Clip* qc[4] = { &l.q, &l.k, &l.v, &l.post }; + for (int j = 0; j < 4; ++j) { + char dn[96], sn[160]; + std::snprintf(dn, sizeof dn, "a.blk.%lld.attn.%s", li, qn[j]); + std::snprintf(sn, sizeof sn, "%s.layers.%lld.self_attn.%s", T, li, qn[j]); + clip(*qc[j], dn, sn, H, H, g); + } + l.lc_pre = w(D("lconv.pre"), S("lconv1d.pre_layer_norm.weight"), {H}, g); + l.lc_dw = w(D("lconv.dw"), S("lconv1d.depthwise_conv1d.weight"), {H, 1, kconv}, g); + l.lc_norm = w(D("lconv.norm"), S("lconv1d.conv_norm.weight"), {H}, g); + { + char dn[96], sn[160]; + std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.start", li); + std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_start", T, li); + clip(l.lc_start, dn, sn, 2 * H, H, g); + std::snprintf(dn, sizeof dn, "a.blk.%lld.lconv.end", li); + std::snprintf(sn, sizeof sn, "%s.layers.%lld.lconv1d.linear_end", T, li); + clip(l.lc_end, dn, sn, H, H, g); + } + } + + /* ---- activations: the subsampler's planes at their own widths, the blocks' at R rows */ + b_s0 = decl_b(b, nm.f("a.s0"), RAD_BF16, {P / 2, (nmel / 2) * c0}); + b_s1 = decl_b(b, nm.f("a.s1"), RAD_BF16, {R, (nmel / 4) * c1}); + b_x = decl_b(b, nm.f("a.x"), RAD_BF16, {R, H}); + b_h = decl_b(b, nm.f("a.h"), RAD_BF16, {R, H}); + b_hc = decl_b(b, nm.f("a.hc"), RAD_BF16, {R, H}); + b_f = decl_b(b, nm.f("a.f"), RAD_BF16, {R, ffw}); + b_q = decl_b(b, nm.f("a.q"), RAD_BF16, {R, H}); + b_k = decl_b(b, nm.f("a.k"), RAD_BF16, {R, H}); + b_v = decl_b(b, nm.f("a.v"), RAD_BF16, {R, H}); + b_att = decl_b(b, nm.f("a.att"), RAD_BF16, {R, H}); + b_o = decl_b(b, nm.f("a.o"), RAD_BF16, {R, H}); + b_g = decl_b(b, nm.f("a.g"), RAD_BF16, {R, 2 * H}); + b_u = decl_b(b, nm.f("a.u"), RAD_BF16, {R, H}); + b_relpos = decl_b(b, nm.f("a.relpos"), RAD_BF16, {n_rel, H}); + b_relk = decl_b(b, nm.f("a.relk"), RAD_BF16, {n_rel, H}); + b_o2 = decl_b(b, nm.f("a.o2"), RAD_BF16, {R, out_dims}); + b_on = decl_b(b, nm.f("a.on"), RAD_BF16, {R, out_dims}); + b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {R, n_embd}); + + auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight wt) { + return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(wt)); + }; + auto rms = [&](int64_t rows, int64_t n, rad_weight wt, double mult) { + if (!wt) + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16"), RAD_F64("mult", mult)), + RAD_WEIGHTS(wt)); + }; + auto clamp = [&](int64_t rows, int64_t n, rad_weight lo, rad_weight hi) { + return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(lo, hi)); + }; + auto unary = [&](const char* op, int64_t rows, int64_t n) { + return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + auto add = [&](int64_t rows, int64_t n) { return unary("add", rows, n); }; + auto lnorm = [&](int64_t rows, int64_t n, rad_weight g) { + return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(g)); + }; + auto conv = [&](int64_t rows, int64_t width, int64_t ci, int64_t co, int64_t cu_div, + int64_t vstride, rad_weight wt) { + return RAD_OP(b, "conv2d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("width", width), + RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("kh", 3), RAD_INT("kw", 3), + RAD_INT("stride", 2), RAD_INT("pad", 1), + RAD_INT("cu_div", cu_div), + RAD_INT("valid_stride", vstride), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(wt)); + }; + /* A clipped linear over rows of `in` into `out`: the input clamp writes a copy (the input + * is shared by the projections it feeds, each with its own bounds), the output clamp is in + * place. The copy is a whole [R, n_in] buffer: a GEMM's input must be contiguous, and a + * column slice of a wider one is not. */ + auto clipped = [&](Clip& c, int64_t n_out, int64_t n_in, rad_buf in, rad_buf tmp, + rad_buf out) { + c.op_in = rw(b, clamp(R, n_in, c.in_lo, c.in_hi), {in}, {tmp}); + c.op_mm = rw(b, gemm(R, n_out, n_in, c.w), {tmp}, {out}); + c.op_out = rw(b, clamp(R, n_out, c.out_lo, c.out_hi), {out}, {out}); + }; + + op_c0 = rw(b, conv(P, nmel, 1, c0, 1, 1, w_c0), {}, {b_s0}); + op_n0 = rw(b, lnorm(P / 2 * (nmel / 2), c0, w_n0), {b_s0}, {b_s0}); + op_r0 = rw(b, unary("relu", P / 2 * (nmel / 2), c0), {b_s0}, {b_s0}); + op_c1 = rw(b, conv(P / 2, nmel / 2, c0, c1, 2, 2, w_c1), {b_s0}, {b_s1}); + op_n1 = rw(b, lnorm(R * (nmel / 4), c1, w_n1), {b_s1}, {b_s1}); + op_r1 = rw(b, unary("relu", R * (nmel / 4), c1), {b_s1}, {b_s1}); + op_in = rw(b, gemm(R, H, H, w_in), {b_s1}, {b_x}); + op_relpos = rw(b, RAD_OP(b, "rel_sinusoid", + RAD_PARAMS(RAD_RANGE("M", 1, n_rel), RAD_INT("n", H), + RAD_F64("max_timescale", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, {b_relpos}); + for (Layer& l : L) { + auto ffw_block = [&](FF& ff) { + ff.op_pre = rw(b, rms(R, H, ff.pre, 1.0), {b_x}, {b_h}); + clipped(ff.l1, ffw, H, b_h, b_hc, b_f); + ff.op_act = rw(b, unary("silu", R, ffw), {b_f}, {b_f}); + /* the activation's only reader is this linear, so its clamp is in place */ + clipped(ff.l2, H, ffw, b_f, b_f, b_o); + ff.op_post = rw(b, rms(R, H, ff.post, 0.5), {b_o}, {b_o}); + ff.op_add = rw(b, add(R, H), {b_x, b_o}, {b_x}); + }; + ffw_block(l.ff1); + l.op_npa = rw(b, rms(R, H, l.n_pre_attn, 1.0), {b_x}, {b_h}); + clipped(l.q, H, H, b_h, b_hc, b_q); + clipped(l.k, H, H, b_h, b_hc, b_k); + clipped(l.v, H, H, b_h, b_hc, b_v); + l.op_rel = rw(b, gemm(n_rel, H, H, l.w_rel), {b_relpos}, {b_relk}); + l.op_attn = rw(b, RAD_OP(b, "attn_local_rel", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("left", left), + RAD_INT("right", 0), RAD_F64("softcap", softcap), + RAD_INT("cu_div", merge), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(l.pds)), + {b_q, b_k, b_v, b_relk}, {b_att}); + clipped(l.post, H, H, b_att, b_hc, b_o); + l.op_npo = rw(b, rms(R, H, l.n_post_attn, 1.0), {b_o}, {b_o}); + l.op_add_attn = rw(b, add(R, H), {b_x, b_o}, {b_x}); + l.op_lc_pre = rw(b, rms(R, H, l.lc_pre, 1.0), {b_x}, {b_h}); + clipped(l.lc_start, 2 * H, H, b_h, b_hc, b_g); + /* GLU: the first half times the sigmoid of the second. */ + l.op_glu = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H), + RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_g}, {b_u}); + l.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", H), + RAD_INT("k", kconv), RAD_INT("cu_div", merge), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(l.lc_dw)), + {b_u}, {b_o}); + l.op_lc_norm = rw(b, rms(R, H, l.lc_norm, 1.0), {b_o}, {b_o}); + l.op_lc_act = rw(b, unary("silu", R, H), {b_o}, {b_o}); + clipped(l.lc_end, H, H, b_o, b_hc, b_u); + l.op_lc_add = rw(b, add(R, H), {b_x, b_u}, {b_x}); + ffw_block(l.ff2); + l.op_out = rw(b, rms(R, H, l.n_out, 1.0), {b_x}, {b_x}); + } + op_outp = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("N", out_dims), + RAD_INT("K", H), RAD_STR("dtype", "bf16"), + RAD_STR("act", "none")), + RAD_WEIGHTS(w_out, b_outw)), + {b_x}, {b_o2}); + op_en = rw(b, rms(R, out_dims, 0, 1.0), {b_o2}, {b_on}); + op_emb = rw(b, gemm(R, n_embd, out_dims, w_emb), {b_on}, {b_out}); + + RadEncoderDecl e{}; + e.name = "audio"; + e.modalities = RAD_MM_AUDIO; + e.patch_dim = nmel; + e.merge = merge; + e.max_patches = P; + e.n_embd = n_embd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + rad_note(b, "audio encoder: %lld conformer blocks of %lld (%lld heads x %lld), " + "subsampling %lld/%lld channels, local attention %lld back; %lld frames a " + "pass -> %lld rows of %lld", (long long)depth, (long long)H, (long long)heads, + (long long)hd, (long long)c0, (long long)c1, (long long)left, (long long)P, + (long long)R, (long long)n_embd); + on = true; + return RAD_OK; + } + + void step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg; + if (!on || Pn <= 0 || Pn > P || Pn % merge || S <= 0) { + rad_step_fail(c, "an audio pass this program's audio encoder cannot serve: none " + "declared, more frames than it was declared for, or not whole rows"); + return; + } + const int64_t Rn = Pn / merge; + const int32_t* crd = batch->enc_coord; + const RadOperand frames = praw2(batch->enc_pixels, RAD_BF16, Pn, nmel); + const RadOperand valid = praw(crd + Pn, RAD_I32, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + auto clipped = [&](const Clip& cl, rad_buf in, int64_t n_in, rad_buf tmp, rad_buf out, + int64_t n_out) { + RAD_ISSUE_N(c, cl.op_in, Rn, bcol(in, 0, n_in, Rn), RAD_W(cl.in_lo), RAD_W(cl.in_hi), + bcol(tmp, 0, n_in, Rn)); + RAD_ISSUE_N(c, cl.op_mm, Rn, bcol(tmp, 0, n_in, Rn), RAD_W(cl.w), bcol(out, 0, n_out, Rn)); + RAD_ISSUE_N(c, cl.op_out, Rn, bcol(out, 0, n_out, Rn), RAD_W(cl.out_lo), RAD_W(cl.out_hi), + 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_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_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)); + RAD_ISSUE_N(c, op_in, Rn, brows(b_s1, Rn), RAD_W(w_in), brows(b_x, Rn)); + RAD_ISSUE_N(c, op_relpos, n_rel, brows(b_relpos, n_rel)); + for (const Layer& l : L) { + auto ffw_block = [&](const FF& ff) { + RAD_ISSUE_N(c, ff.op_pre, Rn, brows(b_x, Rn), RAD_W(ff.pre), brows(b_h, Rn)); + clipped(ff.l1, b_h, H, b_hc, b_f, ffw); + RAD_ISSUE_N(c, ff.op_act, Rn, brows(b_f, Rn), brows(b_f, Rn)); + clipped(ff.l2, b_f, ffw, b_f, b_o, H); + RAD_ISSUE_N(c, ff.op_post, Rn, brows(b_o, Rn), RAD_W(ff.post), brows(b_o, Rn)); + RAD_ISSUE_N(c, ff.op_add, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn)); + }; + ffw_block(l.ff1); + RAD_ISSUE_N(c, l.op_npa, Rn, brows(b_x, Rn), RAD_W(l.n_pre_attn), brows(b_h, Rn)); + clipped(l.q, b_h, H, b_hc, b_q, H); + clipped(l.k, b_h, H, b_hc, b_k, H); + clipped(l.v, b_h, H, b_hc, b_v, H); + RAD_ISSUE_N(c, l.op_rel, n_rel, brows(b_relpos, n_rel), RAD_W(l.w_rel), + brows(b_relk, n_rel)); + RAD_ISSUE_N(c, l.op_attn, Rn, brows(b_q, Rn), brows(b_k, Rn), brows(b_v, Rn), + brows(b_relk, n_rel), RAD_W(l.pds), cu, brows(b_att, Rn)); + clipped(l.post, b_att, H, b_hc, b_o, H); + RAD_ISSUE_N(c, l.op_npo, Rn, brows(b_o, Rn), RAD_W(l.n_post_attn), brows(b_o, Rn)); + RAD_ISSUE_N(c, l.op_add_attn, Rn, brows(b_x, Rn), brows(b_o, Rn), brows(b_x, Rn)); + 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_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); + RAD_ISSUE_N(c, l.op_lc_add, Rn, brows(b_x, Rn), brows(b_u, Rn), brows(b_x, Rn)); + ffw_block(l.ff2); + RAD_ISSUE_N(c, l.op_out, Rn, brows(b_x, Rn), RAD_W(l.n_out), brows(b_x, Rn)); + } + RAD_ISSUE_N(c, op_outp, Rn, brows(b_x, Rn), RAD_W(w_out), RAD_W(b_outw), RAD_NONE, + brows(b_o2, Rn)); + RAD_ISSUE_N(c, op_en, Rn, brows(b_o2, Rn), RAD_NONE, brows(b_on, Rn)); + RAD_ISSUE_N(c, op_emb, Rn, brows(b_on, Rn), RAD_W(w_emb), brows(b_out, Rn)); + } +}; + +struct Model { + Names nm{""}; + Geom g{}; + Kind ks{}, kf{}; /* sliding, full */ + int64_t n_ple = 0; /* hidden_size_per_layer_input */ + int64_t n_out = 0; /* embedding_dim */ + + rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv_s = 0, b_qkv_f = 0, b_att_s = 0, b_att_f = 0; + rad_buf b_gu = 0, b_ff = 0, b_p = 0, b_ple = 0, b_mean = 0, b_proj = 0, b_pooled = 0; + + rad_weight w_tok = 0, w_ple_proj = 0, w_ple_norm = 0, w_norm = 0, w_out = 0; + rad_op op_embed = 0, op_ple = 0, op_ple_norm = 0, op_norm = 0, op_mean = 0, op_out = 0; + rad_op op_cast = 0; + rad_op op_mm = 0; /* the media rows over their placeholders' embeddings */ + + std::vector layers; + Vision vis; + Audio aud; +}; + +static Model g_model[MAX_RANKS]; + +/* A value as a bf16 tensor holds it: round to nearest even on the top 16 bits of the f32. */ +static double bf16_round(double v) { + float f = (float)v; + uint32_t u; + std::memcpy(&u, &f, 4); + u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u; + std::memcpy(&f, &u, 4); + return (double)f; +} + +/* The layer schedule, read and not derived: layer_types is the checkpoint's statement of which + * layers attend to the whole input, and a pattern assumed from the model card would build a model + * that runs and pools the wrong function if a sibling checkpoint moved one. */ +static int read_schedule(const RadModelMeta* meta, int64_t n_layer, std::vector* full) { + const char* s = rad_meta_gets(meta, "layer_types", nullptr); + if (!s || !*s) { + fprintf(stderr, "radiance: embgemma2: the container has no layer_types; it says which " + "layers are sliding and which see the whole input, and is not guessed\n"); + return RAD_E_INVAL; + } + full->clear(); + for (const char* p = s; *p; ) { + while (*p == ' ') ++p; + if (!*p) break; + const char* t = p; + while (*p && *p != ' ') ++p; + const size_t len = (size_t)(p - t); + if (len == 14 && !std::strncmp(t, "full_attention", 14)) full->push_back(1); + else if (len == 17 && !std::strncmp(t, "sliding_attention", 17)) full->push_back(0); + else { + fprintf(stderr, "radiance: embgemma2: layer_types names '%.*s'; this plugin knows " + "full_attention and sliding_attention\n", (int)len, t); + return RAD_E_UNSUPPORTED; + } + } + if ((int64_t)full->size() != n_layer) { + fprintf(stderr, "radiance: embgemma2: layer_types names %zu layers and the model has " + "%lld\n", full->size(), (long long)n_layer); + return RAD_E_INVAL; + } + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + /* A 270M encoder is a fraction of one card; splitting it would cost an all-reduce a layer to + * save nothing, so it is not offered. */ + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: embgemma2 runs on one card (--tp 1); the text model is 270M " + "parameters\n"); + return RAD_E_UNSUPPORTED; + } + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + Geom& g = m.g; + Names& nm = m.nm; + const int64_t T = g.max_tok, E = g.n_embd; + + std::vector full; + RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &full)); + + /* The two attention kinds. The sliding one is the config's top-level geometry; the full one + * overrides head width and KV heads per layer (per_layer_config), and every full layer of + * this checkpoint states the same override -- checked below, layer by layer. */ + m.ks.head_dim = g.head_dim; + m.ks.n_head = g.n_head; + m.ks.n_head_kv = g.n_head_kv; + m.ks.theta = rad_meta_getf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + /* A RADIUS in the reference (|i - j| <= sliding_window), and attn_dense's window is the + * strict bound, so one more. */ + const int64_t radius = meta_int2(meta, "", "sliding_window", 0); + m.ks.window = radius + 1; + m.kf.n_head = g.n_head; + m.kf.theta = rad_meta_getf(meta, "rope_parameters.full_attention.rope_theta", 0.0); + m.kf.window = 0; + for (int64_t l = 0; l < g.n_layer; ++l) { + if (!full[(size_t)l]) continue; + char k1[96], k2[96]; + std::snprintf(k1, sizeof k1, "per_layer_config.%02lld.head_dim", (long long)l); + std::snprintf(k2, sizeof k2, "per_layer_config.%02lld.num_key_value_heads", (long long)l); + const int64_t hd = meta_int2(meta, "", k1, 0), kv = meta_int2(meta, "", k2, 0); + if (!m.kf.head_dim) { m.kf.head_dim = hd; m.kf.n_head_kv = kv; } + if (hd <= 0 || kv <= 0 || hd != m.kf.head_dim || kv != m.kf.n_head_kv) { + fprintf(stderr, "radiance: embgemma2: full-attention layer %lld states head_dim %lld " + "and %lld KV heads; this plugin serves one full geometry\n", + (long long)l, (long long)hd, (long long)kv); + return RAD_E_INVAL; + } + } + m.n_ple = meta_int2(meta, "", "hidden_size_per_layer_input", 0); + m.n_out = meta_int2(meta, "", "embedding_dim", 0); + if (!(m.ks.theta > 0) || !(m.kf.theta > 0) || radius <= 0 || m.kf.head_dim <= 0 || + m.n_ple <= 0 || m.n_out <= 0 || m.ks.n_head % m.ks.n_head_kv || m.kf.n_head % m.kf.n_head_kv) { + fprintf(stderr, "radiance: embgemma2: the container does not describe the model (rope " + "thetas %g / %g, sliding_window %lld, full head_dim %lld, " + "hidden_size_per_layer_input %lld, embedding_dim %lld)\n", + m.ks.theta, m.kf.theta, (long long)radius, (long long)m.kf.head_dim, + (long long)m.n_ple, (long long)m.n_out); + return RAD_E_INVAL; + } + const int64_t P = m.n_ple * g.n_layer; + /* ONE INPUT IS AT MOST ONE STEP (Request::embed), so the longest attention segment is the + * step's token budget. */ + const int64_t max_seg = T; + + /* ---- activations. ple holds every layer's per-layer input for the whole step, read a + * column slice a layer. */ + m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {T, E}); + m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {T, E}); + m.b_o = decl_b(b, nm.f("o"), RAD_BF16, {T, E}); + m.b_qkv_s = decl_b(b, nm.f("qkv_s"), RAD_BF16, {T, m.ks.qkv()}); + m.b_qkv_f = decl_b(b, nm.f("qkv_f"), RAD_BF16, {T, m.kf.qkv()}); + m.b_att_s = decl_b(b, nm.f("att_s"), RAD_BF16, {T, m.ks.q()}); + m.b_att_f = decl_b(b, nm.f("att_f"), RAD_BF16, {T, m.kf.q()}); + m.b_gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * g.n_ff}); + m.b_ff = decl_b(b, nm.f("ffn"), RAD_BF16, {T, g.n_ff}); + m.b_p = decl_b(b, nm.f("ple_p"), RAD_BF16, {T, m.n_ple}); + m.b_ple = decl_b(b, nm.f("ple"), RAD_BF16, {T, P}); + m.b_mean = decl_b(b, nm.f("mean"), RAD_BF16, {g.max_seqs, E}); + m.b_proj = decl_b(b, nm.f("proj"), RAD_BF16, {g.max_seqs, m.n_out}); + m.b_pooled= decl_b(b, nm.f("pooled"), RAD_F32, {g.max_seqs, m.n_out}, RAD_BUF_PERSIST); + RAD_ARCH_TRY(rad_declare_pooled(b, m.b_pooled)); + + /* ---- the model-level weights. Every one at the checkpoint's own bf16, the norm gains + * included: the reference widens a gain to f32 at use, which is exact, so storing it wider + * buys nothing and costs reading it in place on the host backend. */ + const char* L = "language_model"; + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", L))); + RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj.weight"), + nm.ckpt("%s.ple.per_layer_model_projection.weight", L))); + RAD_ARCH_TRY(map_copy(b, nm.f("ple_norm.weight"), + nm.ckpt("%s.ple.per_layer_projection_norm.weight", L))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.norm.weight", L))); + RAD_ARCH_TRY(map_copy(b, nm.f("embd_proj.weight"), + nm.ckpt("%s.embedding_projection.weight", L))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, E}, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.w_ple_proj = decl_w(b, nm.f("ple_proj.weight"), RAD_BF16, {P, E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_ple_norm = decl_w(b, nm.f("ple_norm.weight"), RAD_BF16, {m.n_ple}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_norm = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_out = decl_w(b, nm.f("embd_proj.weight"), RAD_BF16, {m.n_out, E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + + auto rmsnorm = [&](int64_t rows, int64_t n, double eps, rad_weight w) { + return RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) { + return 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)); + }; + auto elem = [&](const char* op, int64_t n, rad_weight w) { + if (w) + return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + return RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + auto act_mul = [&](int64_t n) { + return RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", n), + RAD_STR("act", "gelu_tanh"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + + /* The embedding, scaled by sqrt(hidden) AS THE REFERENCE ROUNDS IT: the scale is a bf16 + * buffer, so sqrt(512) = 22.6274 multiplies as 22.625. */ + const double escale = bf16_round(std::sqrt((double)E)); + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", 0), RAD_F64("mult", escale)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + /* THE PER-LAYER INPUTS: the embedding projected to n_layer x n_ple and RMS-normed per layer. + * The reference scales the projection by hidden^-0.5 before the norm; an RMS norm of s*x with + * eps is exactly the norm of x with eps / s^2, which is what this declares, so the scale is + * applied without the extra bf16 rounding of s*x the reference pays. */ + /* A media part's rows over its placeholders' embeddings, before anything reads them: the + * per-layer inputs are projected from what the model embeds, and for an image token that is + * its image row (declared only when a tower is). */ + if ((Vision::present(meta) && ctx->max_enc_patches > 0) || + (Audio::present(meta) && ctx->max_audio_frames > 0)) + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + m.op_ple = rw(b, gemm(T, P, E, m.w_ple_proj), {m.b_x}, {m.b_ple}); + m.op_ple_norm = rw(b, rmsnorm(T * g.n_layer, m.n_ple, (double)g.eps * (double)E, m.w_ple_norm), + {m.b_ple}, {m.b_ple}); + + m.layers.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& y = m.layers[(size_t)l]; + y.full = full[(size_t)l]; + const Kind& k = y.full ? m.kf : m.ks; + const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s; + const rad_buf att = y.full ? m.b_att_f : m.b_att_s; + const long long ll = (long long)l; + const RadWeightGroup gl = grp_layer((int)l); + auto src = [&](const char* s) { return nm.ckpt("%s.layers.%lld.%s", L, ll, s); }; + + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.in_norm", ll), src("input_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.qkv", ll), + {src("self_attn.q_proj.weight"), src("self_attn.k_proj.weight"), + src("self_attn.v_proj.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.q_norm", ll), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.k_norm", ll), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.o", ll), src("self_attn.o_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_attn", ll), + src("post_attention_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.pre_ff", ll), + src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%lld.gate_up", ll), + {src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.down", ll), src("mlp.down_proj.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ff", ll), + src("post_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_gate", ll), + src("ple_block.per_layer_input_gate.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ple_proj", ll), + src("ple_block.per_layer_projection.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.post_ple", ll), + src("ple_block.post_per_layer_input_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.scalar", ll), src("layer_scalar"))); + + const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; + y.w_in_norm = decl_w(b, nm.f("blk.%lld.in_norm", ll), RAD_BF16, {E}, A, N, gl); + y.w_qkv = decl_w(b, nm.f("blk.%lld.qkv", ll), RAD_BF16, {k.qkv(), E}, A, N, gl); + y.w_q_norm = decl_w(b, nm.f("blk.%lld.q_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl); + y.w_k_norm = decl_w(b, nm.f("blk.%lld.k_norm", ll), RAD_BF16, {k.head_dim}, A, N, gl); + y.w_o = decl_w(b, nm.f("blk.%lld.o", ll), RAD_BF16, {E, k.q()}, A, N, gl); + y.w_post_attn = decl_w(b, nm.f("blk.%lld.post_attn", ll), RAD_BF16, {E}, A, N, gl); + y.w_pre_ff = decl_w(b, nm.f("blk.%lld.pre_ff", ll), RAD_BF16, {E}, A, N, gl); + y.w_gate_up = decl_w(b, nm.f("blk.%lld.gate_up", ll), RAD_BF16, {2 * g.n_ff, E}, A, N, gl); + y.w_down = decl_w(b, nm.f("blk.%lld.down", ll), RAD_BF16, {E, g.n_ff}, A, N, gl); + y.w_post_ff = decl_w(b, nm.f("blk.%lld.post_ff", ll), RAD_BF16, {E}, A, N, gl); + y.w_ple_gate = decl_w(b, nm.f("blk.%lld.ple_gate", ll), RAD_BF16, {m.n_ple, E}, A, N, gl); + y.w_ple_proj = decl_w(b, nm.f("blk.%lld.ple_proj", ll), RAD_BF16, {E, m.n_ple}, A, N, gl); + y.w_post_ple = decl_w(b, nm.f("blk.%lld.post_ple", ll), RAD_BF16, {E}, A, N, gl); + /* bf16 and one element: the reference multiplies the bf16 residual by it in bf16. */ + y.w_scalar = decl_w(b, nm.f("blk.%lld.scalar", ll), RAD_BF16, {1}, A, N, gl); + + y.op_in_norm = rw(b, rmsnorm(T, E, g.eps, y.w_in_norm), {m.b_x}, {m.b_h}); + y.op_qkv = rw(b, gemm(T, k.qkv(), E, y.w_qkv), {m.b_h}, {qkv}); + y.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim), + RAD_INT("n_head", k.n_head), + RAD_INT("n_head_kv", k.n_head_kv), + RAD_F64("theta", k.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "neox"), RAD_INT("v_norm", 1)), + RAD_WEIGHTS(y.w_q_norm, y.w_k_norm)), + {qkv}, {qkv}); + y.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", k.head_dim), + RAD_INT("gqa", k.n_head / k.n_head_kv), + RAD_INT("causal", 0), RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", max_seg), + RAD_INT("window", k.window)), + RAD_NOWEIGHTS), + {qkv}, {att}); + y.op_o = rw(b, gemm(T, E, k.q(), y.w_o), {att}, {m.b_o}); + y.op_post_attn= rw(b, rmsnorm(T, E, g.eps, y.w_post_attn), {m.b_o}, {m.b_o}); + y.op_add_attn = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x}); + y.op_pre_ff = rw(b, rmsnorm(T, E, g.eps, y.w_pre_ff), {m.b_x}, {m.b_h}); + y.op_gate_up = rw(b, gemm(T, 2 * g.n_ff, E, y.w_gate_up), {m.b_h}, {m.b_gu}); + y.op_act = rw(b, act_mul(g.n_ff), {m.b_gu}, {m.b_ff}); + y.op_down = rw(b, gemm(T, E, g.n_ff, y.w_down), {m.b_ff}, {m.b_o}); + y.op_post_ff = rw(b, rmsnorm(T, E, g.eps, y.w_post_ff), {m.b_o}, {m.b_o}); + y.op_add_ff = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x}); + y.op_ple_gate = rw(b, gemm(T, m.n_ple, E, y.w_ple_gate), {m.b_x}, {m.b_p}); + y.op_ple_act = rw(b, act_mul(m.n_ple), {m.b_p, m.b_ple}, {m.b_p}); + y.op_ple_proj = rw(b, gemm(T, E, m.n_ple, y.w_ple_proj), {m.b_p}, {m.b_o}); + y.op_post_ple = rw(b, rmsnorm(T, E, g.eps, y.w_post_ple), {m.b_o}, {m.b_o}); + y.op_add_ple = rw(b, elem("add", E, 0), {m.b_x, m.b_o}, {m.b_x}); + y.op_scale = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16"), RAD_INT("scalar", 1)), + RAD_WEIGHTS(y.w_scalar)), + {m.b_x}, {m.b_x}); + } + + m.op_norm = rw(b, rmsnorm(T, E, g.eps, m.w_norm), {m.b_x}, {m.b_h}); + m.op_mean = rw(b, RAD_OP(b, "seg_mean", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_mean}); + m.op_out = rw(b, gemm(g.max_seqs, m.n_out, E, m.w_out), {m.b_mean}, {m.b_proj}); + m.op_cast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", m.n_out), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + {m.b_proj}, {m.b_pooled}); + + RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, E, (int)g.n_layer)); + RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, E, + (int)g.n_layer + (int)m.vis.L.size())); + + int n_full = 0; + for (int f : full) n_full += f; + rad_note(b, "embedding model: %lld layers (%d whole-input, %lld sliding |i-j|<=%lld), hidden " + "%lld, ffn %lld; sliding %lldx%lld (kv %lld) theta %g, full %lldx%lld (kv %lld) " + "theta %g; per-layer inputs %lld; mean-pooled to %lld", + (long long)g.n_layer, n_full, (long long)(g.n_layer - n_full), (long long)radius, + (long long)E, (long long)g.n_ff, (long long)m.ks.n_head, (long long)m.ks.head_dim, + (long long)m.ks.n_head_kv, m.ks.theta, (long long)m.kf.n_head, + (long long)m.kf.head_dim, (long long)m.kf.n_head_kv, m.kf.theta, + (long long)m.n_ple, (long long)m.n_out); + return RAD_OK; +} + +/* Before declare: the vision tower's pooling window, so a pass size the core picks itself is a + * whole number of them. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + if (Vision::present(meta)) { + const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); + if (k > 0) out->enc_merge = k * k; + } + if (Audio::present(meta)) out->audio_frames = Audio::frames_for(meta); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + const Geom& g = m.g; + const int64_t T = batch->n_tok, S = batch->n_seq, E = g.n_embd; + if (batch->enc) { + if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch); + else m.vis.step(c, batch); + return; + } + if (T <= 0 || S <= 0) return; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand pos = praw(batch->positions, RAD_I32, T); + + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + if (m.op_mm && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows, + praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, E), + praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, T)); + RAD_ISSUE(c, m.op_ple, brows(m.b_x, T), RAD_W(m.w_ple_proj), brows(m.b_ple, T)); + /* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */ + RAD_ISSUE_N(c, m.op_ple_norm, T * g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm), + brows(m.b_ple, T)); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const Layer& y = m.layers[(size_t)l]; + const Kind& k = y.full ? m.kf : m.ks; + const rad_buf qkv = y.full ? m.b_qkv_f : m.b_qkv_s; + const rad_buf att = y.full ? m.b_att_f : m.b_att_s; + const int64_t q = k.q(), kv = k.n_head_kv * k.head_dim; + + RAD_ISSUE(c, y.op_in_norm, brows(m.b_x, T), RAD_W(y.w_in_norm), brows(m.b_h, T)); + RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(qkv, T)); + RAD_ISSUE(c, y.op_qk, brows(qkv, T), pos, RAD_W(y.w_q_norm), RAD_W(y.w_k_norm)); + RAD_ISSUE(c, y.op_attn, bcol(qkv, 0, q, T), bcol(qkv, q, kv, T), bcol(qkv, q + kv, kv, T), + cu, brows(att, T)); + RAD_ISSUE(c, y.op_o, brows(att, T), RAD_W(y.w_o), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_post_attn, brows(m.b_o, T), RAD_W(y.w_post_attn), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_add_attn, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_pre_ff, brows(m.b_x, T), RAD_W(y.w_pre_ff), brows(m.b_h, T)); + RAD_ISSUE(c, y.op_gate_up, brows(m.b_h, T), RAD_W(y.w_gate_up), brows(m.b_gu, T)); + RAD_ISSUE(c, y.op_act, bcol(m.b_gu, 0, g.n_ff, T), bcol(m.b_gu, g.n_ff, g.n_ff, T), + brows(m.b_ff, T)); + RAD_ISSUE(c, y.op_down, brows(m.b_ff, T), RAD_W(y.w_down), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_post_ff, brows(m.b_o, T), RAD_W(y.w_post_ff), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_add_ff, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_ple_gate, brows(m.b_x, T), RAD_W(y.w_ple_gate), brows(m.b_p, T)); + RAD_ISSUE(c, y.op_ple_act, brows(m.b_p, T), bcol(m.b_ple, l * m.n_ple, m.n_ple, T), + brows(m.b_p, T)); + RAD_ISSUE(c, y.op_ple_proj, brows(m.b_p, T), RAD_W(y.w_ple_proj), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_post_ple, brows(m.b_o, T), RAD_W(y.w_post_ple), brows(m.b_o, T)); + RAD_ISSUE(c, y.op_add_ple, brows(m.b_x, T), brows(m.b_o, T), brows(m.b_x, T)); + RAD_ISSUE(c, y.op_scale, brows(m.b_x, T), RAD_W(y.w_scalar), brows(m.b_x, T)); + } + + RAD_ISSUE(c, m.op_norm, brows(m.b_x, T), RAD_W(m.w_norm), brows(m.b_h, T)); + RAD_ISSUE(c, m.op_mean, brows(m.b_h, T), cu, brows(m.b_mean, S)); + RAD_ISSUE_N(c, m.op_out, S, brows(m.b_mean, S), RAD_W(m.w_out), brows(m.b_proj, S)); + RAD_ISSUE_N(c, m.op_cast, S, brows(m.b_proj, S), brows(m.b_pooled, S)); + (void)E; +} + +} /* namespace embgemma2 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(embgemma2, "embeddinggemma2", "", "0.1.0", + "EmbeddingGemma 2: a bidirectional Gemma encoder with per-layer embeddings, " + "mean-pooled to one vector an input; bf16") +RAD_ARCH_PROBE(embgemma2) +#endif diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 483126e6..6504fc57 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -132,6 +132,7 @@ public: int op_resolved (rad_op h) const; int decl_name_map(const RadNameMap* m); int declare_logits(rad_buf b); + int declare_pooled(rad_buf b); int declare_drafter(const RadDrafterDecl* d); int declare_encoder(const RadEncoderDecl* d); void note_v (const char* f, va_list ap); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index ecda5d6d..aa87a95e 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1036,10 +1036,50 @@ int Builder::declare_logits(rad_buf b) { prog_.buffers[prog_.logits_buf].name.c_str(), prog_.buffers[b].name.c_str()); return RAD_E_STATE; } + if (prog_.pooled_buf != RAD_NULL_HANDLE) { + err(RAD_E_STATE, "declare_logits: this program already declared '%s' as its pooled " + "output; a program generates or embeds, not both", + prog_.buffers[prog_.pooled_buf].name.c_str()); + return RAD_E_STATE; + } prog_.logits_buf = b; return RAD_OK; } +/* The embedding program's output (rad_declare_pooled). Checked here for the logits buffer's + * reasons, and for shape: the core reads `n_seq` f32 rows of it from the device after every step, + * so a buffer narrower than a step's sequences, or in another dtype or domain, is refused now + * rather than read past or misread at the first request. */ +int Builder::declare_pooled(rad_buf b) { + if (finished_) { err(RAD_E_STATE, "declare_pooled after declare finished"); return RAD_E_STATE; } + if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_pooled: %u is not a declared buffer", (unsigned)b); + return RAD_E_INVAL; + } + if (prog_.pooled_buf != RAD_NULL_HANDLE && prog_.pooled_buf != b) { + err(RAD_E_STATE, "declare_pooled: '%s' was already named as the pooled output; '%s' is a " + "second one", prog_.buffers[prog_.pooled_buf].name.c_str(), + prog_.buffers[b].name.c_str()); + return RAD_E_STATE; + } + if (prog_.logits_buf != RAD_NULL_HANDLE) { + err(RAD_E_STATE, "declare_pooled: this program already declared '%s' as its logits; a " + "program generates or embeds, not both", + prog_.buffers[prog_.logits_buf].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) { + err(RAD_E_INVAL, "declare_pooled: '%s' must be a device f32 buffer of [>= %lld, dim] -- " + "one row a sequence of the step", + prog_.buffers[b].name.c_str(), (long long)prog_.ctx.max_seqs); + return RAD_E_INVAL; + } + prog_.pooled_buf = b; + return RAD_OK; +} + /* WHAT THE ENCODER IS. Checked here, at declare, for the drafter's reason: an encoder is exercised * only when a request carries media, so a declaration the engine cannot drive would otherwise @@ -1054,30 +1094,36 @@ int Builder::declare_encoder(const RadEncoderDecl* d) { if (!d) { err(RAD_E_INVAL, "declare_encoder: null declaration"); return RAD_E_INVAL; } if (d->modalities == 0) return RAD_OK; /* declaring nothing is declaring nothing */ const char* nm = d->name && *d->name ? d->name : "(unnamed)"; - if (prog_.encoder.modalities != 0) { - err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's encoder; '%s' is " - "a second one", prog_.encoder_name.c_str(), nm); - return RAD_E_STATE; - } - if ((d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) { + /* One vision encoder (images and video) and one audio encoder, each at most once. */ + const bool audio = d->modalities == RAD_MM_AUDIO; + if (!audio && (d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) { err(RAD_E_INVAL, "declare_encoder '%s': modalities 0x%x names a kind this engine has no " - "processor for", nm, (unsigned)d->modalities); + "processor for (an audio encoder serves audio alone)", nm, + (unsigned)d->modalities); return RAD_E_INVAL; } + RadEncoderDecl& slot = audio ? prog_.audio_encoder : prog_.encoder; + std::string& slot_name = audio ? prog_.audio_encoder_name : prog_.encoder_name; + if (slot.modalities != 0) { + err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's %s encoder; '%s' " + "is a second one", slot_name.c_str(), audio ? "audio" : "image and video", + nm); + return RAD_E_STATE; + } + const int64_t want = audio ? prog_.ctx.max_audio_frames : prog_.ctx.max_enc_patches; if (d->patch_dim <= 0 || d->merge <= 0 || d->n_embd <= 0) { err(RAD_E_INVAL, "declare_encoder '%s': patch_dim %lld, merge %lld, n_embd %lld -- all " "three must be positive", nm, (long long)d->patch_dim, (long long)d->merge, (long long)d->n_embd); return RAD_E_INVAL; } - if (d->max_patches <= 0 || d->max_patches != prog_.ctx.max_enc_patches || - d->max_patches % d->merge != 0) { + if (d->max_patches <= 0 || d->max_patches != want || d->max_patches % d->merge != 0) { err(RAD_E_INVAL, "declare_encoder '%s': max_patches %lld, but this program was declared " - "with max_enc_patches %lld and a merge of %lld. The plugin sized its " - "activations with max_enc_patches and the core stages up to that many " - "patches a pass; they cannot differ, and a pass's patches must divide into " - "whole output rows.", nm, (long long)d->max_patches, - (long long)prog_.ctx.max_enc_patches, (long long)d->merge); + "with %s %lld and a merge of %lld. The plugin sized its activations with " + "that and the core stages up to that many patches a pass; they cannot " + "differ, and a pass's patches must divide into whole output rows.", nm, + (long long)d->max_patches, audio ? "max_audio_frames" : "max_enc_patches", + (long long)want, (long long)d->merge); return RAD_E_INVAL; } if (d->out == RAD_NULL_HANDLE || (size_t)d->out >= prog_.buffers.size()) { @@ -1096,9 +1142,9 @@ int Builder::declare_encoder(const RadEncoderDecl* d) { (long long)d->n_embd); return RAD_E_INVAL; } - prog_.encoder = *d; - prog_.encoder_name = nm; - prog_.encoder.name = nullptr; /* the plugin's storage; encoder_name is the copy */ + slot = *d; + slot_name = nm; + slot.name = nullptr; /* the plugin's storage; the name is the copy */ return RAD_OK; } @@ -1526,6 +1572,8 @@ void Builder::finish_buffer_liveness() { * empty and nothing that shared with logits before is prevented from doing so. The * undeclared-use guard in core/runtime/issue.cpp is what refuses the untruthful version. */ if ((rad_buf)i == prog_.logits_buf && last_op > b.last_use) b.last_use = last_op; + /* The pooled output for the same reason: the engine reads it after the last op. */ + if ((rad_buf)i == prog_.pooled_buf && last_op > b.last_use) b.last_use = last_op; } } @@ -1688,6 +1736,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) { return B(b)->declare_logits(logits); } +int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_pooled(pooled); +} + int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { if (!b) return RAD_E_INVAL; return B(b)->declare_drafter(d); diff --git a/core/build/startup.cpp b/core/build/startup.cpp index 6bf65818..c0e97a9e 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -376,7 +376,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R * the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT * a declare failure -- a deployment that never sends `typical_p` does not need a typical * kernel -- so this returning negative means something structural, not a miss. */ - if (also) { + /* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled): it samples nothing, so a sampler chain + * in it would be ops and buffers no step ever issues. */ + if (also && b.program().pooled_buf == RAD_NULL_HANDLE) { /* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler * needs to know how much vocabulary THIS RANK produces, and the one place that is a fact * is the logits buffer the plugin just named. Computing it a second time from n_vocab and diff --git a/core/config.cpp b/core/config.cpp index 66b369b7..6997a40f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -192,7 +192,10 @@ static const Flag g_flags[] = { { "--video-fps", "F", "frames sampled per second of video" }, { "--video-min-frames", "N", "the fewest frames sampled from a video" }, { "--video-max-frames", "N", "the most frames sampled from a video" }, - { "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" }, + { "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n" + " budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" }, + { "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n" + " default the container's); a request's `image_tokens` overrides it" }, { "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n" " (default 67108864). The media flags above default to what the container\n" " states, and do nothing for a model that takes no media" }, @@ -681,6 +684,12 @@ int config_parse(int argc, char** argv, Config* c) { if (!(d > 0.0)) { RAD_ERR("--video-fps must be > 0, not '%s'", v); return RAD_E_INVAL; } c->video_fps = d; } + else if (S("--image-tokens")) { + if (!(v = need(i))) return RAD_E_INVAL; + int64_t n = 0; + if (!parse_int(a.c_str(), v, 1, INT32_MAX, &n)) return RAD_E_INVAL; + c->image_tokens = (int32_t)n; + } else if (S("--video-min-frames") || S("--video-max-frames") || S("--video-max-frame-tokens")) { if (!(v = need(i))) return RAD_E_INVAL; int64_t n = 0; diff --git a/core/device/aql.cpp b/core/device/aql.cpp index cd5c70f2..47cc1c61 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -563,6 +563,14 @@ void on_queue_error(hsa_status_t st, hsa_queue_t*, void* data) { * Nothing on the step path takes that long, so a wait that does is a queue stuck on a packet -- * a barrier on a signal nothing will decrement, or a kernel that faulted without a report -- and * the packet at the read index is the answer. */ +/* Every queue's read index, summed: it only grows, so an unchanged sum is "no queue moved". */ +uint64_t read_progress() { + std::lock_guard lk(G().streams_mu); + uint64_t n = 0; + for (Stream* s : G().streams) n += hsa_queue_load_read_index_scacquire(s->q); + return n; +} + void dump_queues(const char* where) { std::lock_guard lk(G().streams_mu); RAD_ERR("device: %s has waited 5 s; the queues:", where); @@ -599,22 +607,40 @@ void dump_queues(const char* where) { constexpr uint32_t kStallMs = 5000; /* A spin that notices when it has gone on too long. Checked every 64k iterations, so the clock - * is read a few thousand times a second at most. */ + * is read a few thousand times a second at most. + * + * SLOW OR STUCK: the dump alone cannot say. A long prefill at a deep context can hold one wait past + * five seconds while the queue drains packet after packet, and a hung kernel holds it with the + * read index frozen. So the read indices are noted with the dump and looked at once more a stall + * period later: advanced is a long wait, unchanged is a queue the GPU is not running. */ struct Stall { const char* where; uint32_t n = 0; - bool told = false; + int told = 0; /* 0 nothing said, 1 the dump, 2 the verdict */ + uint64_t progress = 0; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); explicit Stall(const char* w) : where(w) {} void tick() { - if (told || (++n & 0xffff)) return; + if (told == 2 || (++n & 0xffff)) return; check(); } /* Every call, for a loop that sleeps between calls and so makes few of them. */ void check() { - if (!told && std::chrono::steady_clock::now() - t0 > std::chrono::milliseconds(kStallMs)) { - told = true; + 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(); 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); } } }; diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 18a5303a..506b452a 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -67,11 +67,32 @@ static std::string device_inventory(const DeviceBackend* b) { return s; } +/* COMPUTE WAVE SAVE/RESTORE OFF IS A GPU HANG WAITING FOR AN EVICTION. The driver evicts a + * process's queues whenever host memory the card maps is moved or reclaimed under memory pressure, + * and a serve with a host pool or a host KV tier maps gigabytes of it. With + * amdgpu.cwsr_enable=0 it cannot preempt a running queue and waits for it to drain, which a queue + * a serve keeps fed never does: the queue stops inside whatever kernel it was running, MES fails + * REMOVE_QUEUE, and the driver resets the card. Said at startup because nothing later can tell + * that hang from a kernel bug. */ +static void warn_cwsr_off() { + FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r"); + if (!f) return; + int v = -1; + const int got = std::fscanf(f, "%d", &v); + std::fclose(f); + if (got == 1 && v == 0) + RAD_WARN("device: amdgpu cwsr_enable is 0, so the driver cannot preempt a running queue: " + "any queue eviction (host memory the card maps, moved under memory pressure) waits " + "for a queue a serve never lets drain, and ends in a GPU hang and reset. Set " + "amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)"); +} + static const DeviceBackend* select_backend() { #if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP if (const DeviceBackend* b = aql_backend_if_present()) { RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str()); + warn_cwsr_off(); return b; } RAD_INFO("device: built with HIP but no device is visible -- using the host backend"); diff --git a/core/engine.cpp b/core/engine.cpp index 10ffd81e..b98d4fb8 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -17,6 +17,7 @@ #include "sched/scheduler.h" #include "server/adapters.h" #include "server/server.h" +#include "server/sink.h" #include "server/liveview.h" #include "text/tokenizer.h" @@ -59,6 +60,7 @@ Engine::~Engine() { * says nothing is worse than no flag at all. */ if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); + if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED); /* The disk thread first: it reads the host arena and writes the store, both of which go with * the ranks and kv_disk_ below. */ if (pump_) pump_->io.stop(); @@ -408,7 +410,7 @@ int Engine::step_loop() { std::vector cancel; /* Not in the KL mode: its scored rows are copied out of the logits buffer after the step is * collected, and a pass issued ahead would have overwritten them by then. */ - pipelining_ = !cfg_.kld() && drafter_.kind != RAD_DRAFT_BLOCK && + pipelining_ = !cfg_.kld() && !embedding_ && drafter_.kind != RAD_DRAFT_BLOCK && (serial_drafting() || cfg_.n_spec <= 0); const bool t_on = (int)log_level() >= (int)Log::Debug; /* Read once. See the block in the idle branch below for what it is for. */ @@ -582,7 +584,7 @@ int Engine::step_loop() { * rank threads are reading through batch_for() while this runs; they are applied after the * join, ahead of collect_step. */ auto stage_sampler = [&]() -> int { - if (!so.reqs.empty()) { + if (!so.reqs.empty() && !embedding_) { /* PER-REQUEST SAMPLER STATE IS BUILT HERE, ON FIRST SIGHT. A grammar arrives compiled * from admission and is only positioned here; a DRY sequence-breaker set is resolved * against the vocabulary once. Both belong off the step path, and this is the first @@ -703,7 +705,8 @@ int Engine::step_loop() { build_status_ = RAD_OK; } if (const int ps = prepare_release(b); ps < 0) return fail_loop(ps); - issue_what_.store(kIssueAll, std::memory_order_release); + /* An embedding program has no sampler to issue behind its pass. */ + issue_what_.store(embedding_ ? kIssueModel : kIssueAll, std::memory_order_release); step_batch_.store(b, std::memory_order_release); barrier_->arrive_and_wait(); /* release the ranks */ { @@ -805,7 +808,7 @@ int Engine::step_loop() { * wait, commit and staging all happen while it runs. */ st = issue_ahead(&ahead); if (st < 0) return fail_loop(st); - st = collect_step(b, so); + st = embedding_ ? collect_pooled(b, so) : collect_step(b, so); if (t_on) phase_mark(PH_COLLECT); if (st < 0) return fail_loop(st); if (cfg_.kld()) { @@ -947,10 +950,56 @@ int Engine::collect_issue(const RadBatch* b, StepOut& so) { } int Engine::mark_step_end(const RadBatch* b, StepOut& so) { - if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so)); + if (embedding_) RAD_TRY(collect_pooled_issue(b, so)); + else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so)); return rad_event_record(step_end_, ranks_[0]->ctx.stream()); } +/* AN EMBEDDING STEP'S ANSWER, ON ITS WAY TO THE HOST: the pooled buffer's first n_seq rows, copied + * into pinned memory behind the pass on rank 0's stream -- every rank holds the same vectors, so + * one copy is the answer. Nothing waits here; collect_pooled does, once. */ +int Engine::collect_pooled_issue(const RadBatch* b, StepOut& /*so*/) { + if (b->n_seq <= 0) return RAD_OK; + Rank& r0 = *ranks_[0]; + const void* src = r0.ctx.buf_ptr(r0.program.pooled_buf); + if (!src) { + RAD_ERR("the pooled output was declared but never planned"); + return RAD_E_STATE; + } + return rad_memcpy_async(pooled_host_, src, + (int64_t)b->n_seq * pooled_dim_ * (int64_t)sizeof(float), + r0.ctx.stream()); +} + +/* Each sequence's vector to its request's sink, and the step's three per-sequence arrays set so + * the commit FINISHES every request it carried: an embedding request is one step long. The token + * is never emitted (Request::embed), so its value is irrelevant; eos is what ends the request. */ +int Engine::collect_pooled(const RadBatch* b, StepOut& so) { + const StepPlan& plan = sched_.plan(); + so.token.assign(plan.e.size(), 0); + so.accepted.assign(plan.e.size(), 0); + so.eos.assign(plan.e.size(), 1); + if (plan.e.empty()) return RAD_OK; + RAD_TRY(rad_event_sync(step_end_)); + if ((int64_t)plan.e.size() != (int64_t)b->n_seq) { + RAD_ERR("an embedding step planned %zu sequences and its batch carries %lld", + plan.e.size(), (long long)b->n_seq); + return RAD_E_STATE; + } + for (size_t i = 0; i < plan.e.size(); ++i) { + const StepEntry& e = plan.e[i]; + if (!e.req) continue; + if (!e.produces_token) { + RAD_ERR("an embedding step carried part of request %llu's input; an encoder must see " + "the whole of it in one step", (unsigned long long)e.req->id); + return RAD_E_STATE; + } + const float* row = pooled_host_ + (int64_t)i * pooled_dim_; + server::sink_embedding(e.req->sink, row, pooled_dim_); + } + return RAD_OK; +} + /* Wait for the sampled ids and turn them into the three per-sequence arrays the scheduler wants. * This is the ONE host synchronisation on the step path: the host needs the tokens to commit them * and to stream them. Everything else in a step is enqueued and never waited on (spec §5.4). */ @@ -1493,12 +1542,43 @@ int Engine::serve() { RAD_ERR("serve: start() has not run, or stopped at --debug-graph"); return RAD_E_STATE; } - if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE) { - RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), so there is " - "nothing to sample. An encoder-only plugin cannot serve completions.", - plugins_.arch_plugin.c_str()); + embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE; + if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_) { + RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits) and no pooled " + "output (rad_declare_pooled), so a step produces nothing anyone can read. An " + "encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str()); return RAD_E_UNSUPPORTED; } + if (embedding_) { + if (cfg_.kld() || cfg_.n_spec > 0) { + RAD_ERR("the '%s' plugin is an embedding model: it generates nothing, so --kld and " + "speculative decoding have nothing to work on", plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + const Program& p0 = ranks_[0]->program; + pooled_dim_ = p0.buffers[p0.pooled_buf].decl.shape[1]; + for (size_t i = 1; i < ranks_.size(); ++i) { + const Program& pi = ranks_[i]->program; + if (pi.pooled_buf == RAD_NULL_HANDLE || + pi.buffers[pi.pooled_buf].decl.shape[1] != pooled_dim_) { + RAD_ERR("rank %zu declared a different pooled output from rank 0's", i); + return RAD_E_STATE; + } + } + pooled_host_ = static_cast( + rad_dev_alloc(cfg_.max_seqs * pooled_dim_ * (int64_t)sizeof(float), + RAD_MEM_HOST_PINNED)); + if (!pooled_host_) { + RAD_ERR("no pinned host memory for a step's pooled rows (%lld x %lld f32)", + (long long)cfg_.max_seqs, (long long)pooled_dim_); + return RAD_E_NOMEM; + } + /* NO PREFIX CACHE: an encoder keeps no KV to reuse, and attending both ways means a + * shared prefix does not even compute to the same rows. */ + cfg_.prefix_cache = false; + RAD_INFO("embedding model: %lld-wide pooled vectors, one step an input, up to %lld " + "tokens an input", (long long)pooled_dim_, (long long)cfg_.max_tok); + } /* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on * every rank: every rank carves the same block count (Engine::configure_kv caps each at the @@ -2128,8 +2208,42 @@ int Engine::run_server() { /* load_from_vocab warns on its own when the template is missing or will not compile; all we * decide here is whether the endpoint exists. The reply format is the architecture plugin's * when it declares one, and the template's otherwise. */ + /* WHAT AN EMBEDDING MODEL SERVES: /v1/embeddings, and no chat. */ + /* Its named prompts are the checkpoint's sentence-transformers configuration + * (`sentence_transformers.prompts.*`), and a `messages` input renders through its chat + * template. */ + struct EmbedInfo final : server::IEmbedder { + int64_t d = 0, n = 0; + const RadModelMeta* meta = nullptr; + server::IChatTemplate* tpl = nullptr; + int64_t dim() const override { return d; } + int64_t max_input() const override { return n; } + bool prompt(const std::string& name, std::string* text) const override { + const std::string key = "sentence_transformers.prompts." + name; + const char* v = rad_meta_gets(meta, key.c_str(), nullptr); + if (!v) return false; + *text = v; + return true; + } + std::string default_prompt() const override { + const char* v = rad_meta_gets(meta, "sentence_transformers.default_prompt_name", ""); + return v ? std::string(v) : std::string(); + } + server::IChatTemplate* message_template() const override { return tpl; } + } embed_info; + embed_info.d = pooled_dim_; + embed_info.n = cfg_.max_tok; + embed_info.meta = &meta_; + if (embedding_) d.embed = &embed_info; + const RadChatFormat* declared_format = rad_tools_chat_format(plugins_, meta_); - if (vocab_ && !vocab_->chat_template().empty() && + if (embedding_) { + /* No chat endpoint: the model's template, when it has one, renders a `messages` input. */ + if (vocab_ && !vocab_->chat_template().empty() && + chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && + chat_bridge.ready()) + embed_info.tpl = &chat_bridge; + } else if (vocab_ && !vocab_->chat_template().empty() && chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && chat_bridge.ready()) { d.chat = &chat_bridge; @@ -2139,6 +2253,7 @@ int Engine::run_server() { } server::ServerOptions o{}; + o.embedding_model = embedding_; o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name : meta_.name && *meta_.name ? meta_.name : "radiance"; o.host = cfg_.host; @@ -2202,15 +2317,37 @@ int Engine::run_server() { } vc.max_patches = encd.max_patches; /* THE COMMAND LINE OVER THE CONTAINER, field by field, and the result checked as a whole: - * a minimum stated alone can land above the maximum the container states. */ - if (cfg_.image_min_pixels) vc.image_min_pixels = *cfg_.image_min_pixels; - if (cfg_.image_max_pixels) vc.image_max_pixels = *cfg_.image_max_pixels; - if (cfg_.video_min_pixels) vc.video_min_pixels = *cfg_.video_min_pixels; - if (cfg_.video_max_pixels) vc.video_max_pixels = *cfg_.video_max_pixels; + * a minimum stated alone can land above the maximum the container states. + * + * A TOKEN-BUDGET PROCESSOR (Gemma 4's) sizes images and frames by soft tokens, not pixel + * bands: the band flags would do nothing on it, so they are refused by name, and the + * budgets come from --image-tokens and --video-max-frame-tokens. */ + if (vc.family == mm::Family::Gemma4) { + if (cfg_.image_min_pixels || cfg_.image_max_pixels || cfg_.video_min_pixels || + cfg_.video_max_pixels || cfg_.video_min_frames) { + RAD_ERR("media: this model's processor sizes images and video frames by a token " + "budget, so --image-min/max-pixels, --video-min/max-pixels and " + "--video-min-frames do nothing; use --image-tokens and " + "--video-max-frame-tokens"); + return RAD_E_INVAL; + } + if (cfg_.image_tokens) vc.image_soft_tokens = *cfg_.image_tokens; + if (cfg_.video_max_frame_tokens) vc.video_soft_tokens = *cfg_.video_max_frame_tokens; + } else { + if (cfg_.image_tokens) { + RAD_ERR("media: --image-tokens is a token budget, and this model's processor " + "sizes images by pixels (--image-min-pixels, --image-max-pixels)"); + return RAD_E_INVAL; + } + if (cfg_.image_min_pixels) vc.image_min_pixels = *cfg_.image_min_pixels; + if (cfg_.image_max_pixels) vc.image_max_pixels = *cfg_.image_max_pixels; + if (cfg_.video_min_pixels) vc.video_min_pixels = *cfg_.video_min_pixels; + if (cfg_.video_max_pixels) vc.video_max_pixels = *cfg_.video_max_pixels; + if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames; + if (cfg_.video_max_frame_tokens) vc.max_frame_rows = *cfg_.video_max_frame_tokens; + } if (cfg_.video_fps) vc.fps = *cfg_.video_fps; - if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames; if (cfg_.video_max_frames) vc.max_frames = *cfg_.video_max_frames; - if (cfg_.video_max_frame_tokens) vc.max_frame_rows = *cfg_.video_max_frame_tokens; if (cfg_.max_source_pixels) vc.max_source_pixels = *cfg_.max_source_pixels; if (cfg_.media_flags_set() && vc.check(&why) < 0) { RAD_ERR("media: the media flags and what the container states disagree: %s", @@ -2232,18 +2369,32 @@ int Engine::run_server() { (long long)encd.patch_dim, (long long)encd.merge); return RAD_E_INVAL; } + if (vc.family == mm::Family::Gemma4 && + (int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge > + encd.max_patches) { + RAD_ERR("media: an image of %d soft tokens or a video frame of %d is more patches than " + "one encoder pass holds (--mm-max-patches %lld)", vc.image_soft_tokens, + vc.video_soft_tokens, (long long)encd.max_patches); + return RAD_E_INVAL; + } mm_proc = std::make_unique(); RAD_TRY(mm_proc->init(vc, [&tok_bridge](const std::string& t) { return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false); })); - mm_bridge = std::make_unique(mm_proc.get(), encd.modalities); - d.mm = mm_bridge.get(); o.allow_image = (encd.modalities & RAD_MM_IMAGE) != 0; o.allow_video = (encd.modalities & RAD_MM_VIDEO) != 0; if (!mm::decoder_available()) RAD_WARN("media: the '%s' encoder is loaded but this build has no media decoder " "(RAD_WITH_FFMPEG), so every media part will be refused", ranks_[0]->program.encoder_name.c_str()); + else if (mm_proc->config().family == mm::Family::Gemma4) + RAD_INFO("media: %s%s through '%s'; an image becomes at most %d soft tokens (a " + "request's image_tokens may ask for 70..1120), a video %d a frame at %.3g " + "frames a second, at most %d frames; %lld patches a pass", + o.allow_image ? "images" : "", o.allow_video ? " and video" : "", + ranks_[0]->program.encoder_name.c_str(), mm_proc->config().image_soft_tokens, + mm_proc->config().video_soft_tokens, mm_proc->config().fps, + mm_proc->config().max_frames, (long long)encd.max_patches); else RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld " "patches a pass), a video to %lld pixels over all its frames", @@ -2252,8 +2403,42 @@ int Engine::run_server() { (long long)mm_proc->config().image_max_pixels, (long long)encd.max_patches, (long long)mm_proc->config().video_max_pixels); } + /* AUDIO, WHEN THE PROGRAM DECLARED AN AUDIO ENCODER: the feature extractor reads its framing + * from the container, and the encoder states the frame width and the frames an output row. */ + const RadEncoderDecl& aend = ranks_[0]->program.audio_encoder; + if (aend.modalities != 0) { + mm::AudioConfig ac; + std::string why; + if (ac.from_meta(meta_, &why) < 0) { + RAD_ERR("the '%s' encoder has no feature extractor: %s", + ranks_[0]->program.audio_encoder_name.c_str(), why.c_str()); + return RAD_E_INVAL; + } + if (ac.n_mels != aend.patch_dim) { + RAD_ERR("the container's feature extractor makes %d-bin frames; the '%s' encoder takes " + "%lld", ac.n_mels, ranks_[0]->program.audio_encoder_name.c_str(), + (long long)aend.patch_dim); + return RAD_E_INVAL; + } + ac.merge = (int32_t)aend.merge; + ac.max_frames = aend.max_patches; + if (!mm_proc) mm_proc = std::make_unique(); + RAD_TRY(mm_proc->init_audio(ac)); + o.allow_audio = true; + if (mm::decoder_available()) + RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, " + "%d frames a token; %lld frames a pass", + ranks_[0]->program.audio_encoder_name.c_str(), + (double)ac.max_samples / (double)ac.rate, ac.n_mels, + ac.hop * 1000 / ac.rate, ac.merge, (long long)aend.max_patches); + } + if (mm_proc) { + mm_bridge = std::make_unique( + mm_proc.get(), encd.modalities | aend.modalities); + d.mm = mm_bridge.get(); + } - if (encd.modalities == 0 && cfg_.media_flags_set()) + 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)" : "takes no images or video"); @@ -2306,9 +2491,13 @@ int Engine::run_server() { why.c_str()); return RAD_E_INVAL; } - RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, - d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", - o.api_key.empty() ? "" : " -- a bearer key is required"); + if (embedding_) + RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501)%s", + o.host.c_str(), o.port, o.api_key.empty() ? "" : " -- a bearer key is required"); + else + RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, + d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", + o.api_key.empty() ? "" : " -- a bearer key is required"); /* THE LIVE VIEW (spec §16), constructed here and nowhere else. * diff --git a/core/engine.h b/core/engine.h index 6366698d..2395284b 100644 --- a/core/engine.h +++ b/core/engine.h @@ -269,6 +269,15 @@ private: ~Readback(); }; Readback readback_; + /* AN EMBEDDING PROGRAM (rad_declare_pooled): no sampler, and a step's answer is the pooled + * buffer's first n_seq rows rather than sampled ids. `pooled_host_` is their pinned landing + * place, [max_seqs, pooled_dim_] f32; collect_pooled copies them there behind the step and + * hands each row to its request's sink after the step's one wait. */ + bool embedding_ = false; + int64_t pooled_dim_ = 0; + float* pooled_host_ = nullptr; + int collect_pooled_issue(const RadBatch* b, StepOut& so); + int collect_pooled(const RadBatch* b, StepOut& so); bool serial_drafting() const; int advance_all(int mode, int round, bool from_proposal, int rows = -1); int issue_serial_drafter(int step, const RadBatch* b, StepOut& so); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 24b47c89..10c1caf0 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -842,6 +842,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024; bc.scope = ""; bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0; + bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0; /* A row at every token of the step and the sampler's row a sequence before them * (core/kld.h); the KL mode has no speculation, so a sequence samples one. */ bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0; @@ -901,10 +902,26 @@ int Engine::declare() { * vision_config is a tower whose weights are in it. 16384 patches is a 2048 x 2048 image, the * largest one pass takes; the reference processor allows sixteen times that area, which would * need an activation region sixteen times as large on every card for one picture. */ + /* THE AUDIO ENCODER'S PASS: the plugin's longest clip, when the model file carries an audio + * encoder (`radiance.encoder` names one) and the deployment did not ask for text only. */ + if (cfg_.mm_audio_frames < 0) { + const char* enc = rad_meta_gets(&meta_, "radiance.encoder", ""); + const bool named = enc && std::strstr(enc, "audio") != nullptr; + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + const bool text_only = cfg_.mm_max_patches == 0; + cfg_.mm_audio_frames = !text_only && pb.audio_frames > 0 && (named || !file_) + ? pb.audio_frames : 0; + } if (cfg_.mm_max_patches < 0) { const char* enc = rad_meta_gets(&meta_, "radiance.encoder", ""); const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0; cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0; + /* Whole output rows a pass: the plugin's merge, when it states one. */ + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (cfg_.mm_max_patches > 0 && pb.enc_merge > 1) + cfg_.mm_max_patches -= cfg_.mm_max_patches % pb.enc_merge; if (cfg_.mm_max_patches == 0 && tower) RAD_INFO("media: off -- the checkpoint has a vision tower but this container was " "converted without its weights; convert again to serve images and video"); @@ -3336,32 +3353,6 @@ int Engine::start() { r->ctx.set_stager(&r->fstager); } - /* RADIANCE_HOST_DOMAIN puts EVERY op on the host domain, which is how you run the whole - * model on libref. The oracle the entire correctness story leans on is a per-op - * one -- it compares one kernel against ref on the operands the device handed it -- and - * that can never answer "is the GRAPH right", because both sides read the same graph. A - * whole forward pass on the reference implementation can, and it is the only thing that - * can be diffed against another engine's. - * - * The site is a per-op property already (spec §5.1) and set_op_domain refuses by name - * where a band has no host kernel, so this is the existing seam and not a new one. It - * belongs with HIP_VISIBLE_DEVICES=-1, which drops the backend to host so the arena is - * host memory a host kernel may dereference; without that this asks ref to read VRAM. */ - if (std::getenv("RADIANCE_HOST_DOMAIN")) { - if (!device_is_host()) - RAD_WARN("RADIANCE_HOST_DOMAIN on the %s backend: the arena is device memory and " - "a host kernel cannot read it. Set HIP_VISIBLE_DEVICES=-1 as well.", - device_backend_name()); - int moved = 0; - for (size_t i = 1; i < r->program.ops.size(); ++i) { - const int st = r->ctx.set_op_domain((rad_op)i, RAD_DOMAIN_HOST); - if (st < 0) return st; - ++moved; - } - RAD_WARN("RADIANCE_HOST_DOMAIN: %d op(s) on the host. This is the reference " - "implementation running the whole model, and it is as slow as that sounds.", - moved); - } } /* ---- THE LOAN: the cache's idle blocks, lent to the expert slab in place ---------------- * diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp index 30c7ad43..8fd00e33 100644 --- a/core/engine_mm.cpp +++ b/core/engine_mm.cpp @@ -11,6 +11,9 @@ * inside one; the processor has already kept every segment within a pass. Several items share a * pass when they fit, which is what a request with a handful of small pictures wants. * + * AN AUDIO CLIP IS ONE SEGMENT OF THE AUDIO ENCODER, whose passes are separate from the vision + * tower's: a program declares one of each at most, and an item goes to the one its kind names. + * * EVERY RANK RUNS THE WHOLE TOWER on its own card from its own copy of the patches. The rows are * needed on every rank anyway -- each rank embeds every token -- and running it everywhere costs the * encoder's compute once per card instead of a transfer of its output between them. @@ -29,16 +32,6 @@ int Engine::run_encodes() { sched_.take_encodes(&items); if (items.empty()) return RAD_OK; - const RadEncoderDecl& enc = ranks_[0]->program.encoder; - const int64_t max_p = sched_.encoder_patches(); - const int64_t n_embd = enc.n_embd; - Rank& r0 = *ranks_[0]; - void* out = r0.ctx.buf_ptr(enc.out); - if (!out) { - RAD_ERR("encoder '%s': its output buffer was declared but never planned", - ranks_[0]->program.encoder_name.c_str()); - return RAD_E_STATE; - } /* A DIAGNOSTIC: RADIANCE_DEBUG_MM_DUMP= writes each item's patches (`.pix.bf16`, the * processor's output in merge-block order) and its rows (`.bf16`) there as raw bf16, named by * its content key -- the tower's input and output, for comparison against a reference encoder @@ -56,65 +49,96 @@ int Engine::run_encodes() { } }; + Rank& r0 = *ranks_[0]; + const Program& prog = r0.program; for (auto& ip : items) { if (ip->encoded) continue; - ip->embd.assign((size_t)(ip->n_rows() * n_embd), 0); + const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder; + ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0); if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size()); } - size_t i = 0; - int32_t seg = 0; - while (i < items.size()) { - std::vector parts; - int64_t np = 0; - while (i < items.size()) { - mm::Item& it = *items[i]; - if (it.encoded) { ++i; seg = 0; continue; } - const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; - if (seg_p > max_p) { - RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld", - (long long)seg_p, (long long)max_p); + /* THE PASSES, ENCODER BY ENCODER: an audio clip goes through the audio encoder and a picture + * or a video through the other, each with its own pass size and output buffer. */ + for (int which = 0; which < 2; ++which) { + const bool audio = which == 1; + const RadEncoderDecl& enc = audio ? prog.audio_encoder : prog.encoder; + const std::string& enc_name = audio ? prog.audio_encoder_name : prog.encoder_name; + std::vector mine; + for (auto& ip : items) + if (!ip->encoded && (ip->kind == mm::Kind::Audio) == audio) mine.push_back(ip.get()); + if (mine.empty()) continue; + if (enc.modalities == 0) { + RAD_ERR("encoder: a %s item reached the encoder and this program declares no %s " + "encoder", audio ? "audio" : "picture", audio ? "audio" : "image"); + return RAD_E_STATE; + } + const int64_t max_p = enc.max_patches; + const int64_t n_embd = enc.n_embd; + + size_t i = 0; + int32_t seg = 0; + while (i < mine.size()) { + std::vector parts; + int64_t np = 0; + while (i < mine.size()) { + mm::Item& it = *mine[i]; + const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; + if (seg_p > max_p) { + RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld", + (long long)seg_p, (long long)max_p); + return RAD_E_STATE; + } + const int64_t room = (max_p - np) / seg_p; + const int32_t can = (int32_t)std::min(it.n_seg - seg, room); + if (can <= 0) break; + parts.push_back({ &it, seg, can }); + np += (int64_t)can * seg_p; + seg += can; + if (seg == it.n_seg) { ++i; seg = 0; } + } + if (parts.empty()) break; + + const RadBatch* b = sched_.build_encoder(parts, enc_step_++, enc); + if (!b) return RAD_E_STATE; + RAD_TRY(prepare_release(b)); + /* THE OUTPUT'S ADDRESS IS THE PASS'S LEVEL'S, read after prepare_release: a pass runs + * at the arena's full plan (Engine::arena_step), and a buffer sits at another offset + * in every level. An address taken at the level the last step left would read some + * other buffer, or memory lent to the expert slab, in place of the rows. */ + void* out = r0.ctx.buf_ptr(enc.out); + if (!out) { + RAD_ERR("encoder '%s': its output buffer was declared but never planned", + enc_name.c_str()); return RAD_E_STATE; } - const int64_t room = (max_p - np) / seg_p; - const int32_t can = (int32_t)std::min(it.n_seg - seg, room); - if (can <= 0) break; - parts.push_back({ &it, seg, can }); - np += (int64_t)can * seg_p; - seg += can; - if (seg == it.n_seg) { ++i; seg = 0; } + /* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick, + * which belongs to steps. */ + issue_what_.store(kIssueModel, std::memory_order_release); + step_batch_.store(b, std::memory_order_release); + barrier_->arrive_and_wait(); + barrier_->arrive_and_wait(); + const int st = step_status_.load(std::memory_order_acquire); + if (st < 0) { + RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st)); + return st; + } + /* The rows, in pass order: each part's segments are consecutive rows of its item. */ + int64_t row = 0; + for (const BatchBuilder::EncoderPart& p : parts) { + mm::Item& it = *const_cast(p.item); + const int64_t rows = (int64_t)p.n_seg * it.seg_rows; + const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t); + RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd, + static_cast(out) + + row * n_embd * (int64_t)sizeof(uint16_t), + bytes, r0.ctx.stream())); + row += rows; + } + /* Every rank's stream, not only rank 0's: the next pass rewrites the staging every + * rank's copy reads, and the arena every rank's tower wrote. */ + for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream())); } - if (parts.empty()) break; - - const RadBatch* b = sched_.build_encoder(parts, enc_step_++); - if (!b) return RAD_E_STATE; - RAD_TRY(prepare_release(b)); - /* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick, which - * belongs to steps. */ - issue_what_.store(kIssueModel, std::memory_order_release); - step_batch_.store(b, std::memory_order_release); - barrier_->arrive_and_wait(); - barrier_->arrive_and_wait(); - const int st = step_status_.load(std::memory_order_acquire); - if (st < 0) { - RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st)); - return st; - } - /* The rows, in pass order: each part's segments are consecutive rows of its item. */ - int64_t row = 0; - for (const BatchBuilder::EncoderPart& p : parts) { - mm::Item& it = *const_cast(p.item); - const int64_t rows = (int64_t)p.n_seg * it.seg_rows; - const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t); - RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd, - static_cast(out) + - row * n_embd * (int64_t)sizeof(uint16_t), - bytes, r0.ctx.stream())); - row += rows; - } - /* Every rank's stream, not only rank 0's: the next pass rewrites the staging every rank's - * copy reads, and the arena every rank's tower wrote. */ - for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream())); } for (auto& ip : items) { diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index cf83b9a4..101143e3 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -148,9 +148,15 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) { * `size.shortest_edge` means two different things in the two files. Absent is not an error: a * text model has neither. */ int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) { + /* processor_config.json is the newer single file: one object a sub-processor + * (`image_processor`, `video_processor`, `feature_extractor`) beside the processor's own keys + * -- EmbeddingGemma 2's image budget and its audio token rate are only there. */ static const struct { const char* file; const char* prefix; } kFiles[] = { { "preprocessor_config.json", "preprocessor" }, { "video_preprocessor_config.json", "video_preprocessor" }, + { "processor_config.json", "processor" }, + /* sentence-transformers' own: an embedding model's named prompts and its default. */ + { "config_sentence_transformers.json", "sentence_transformers" }, }; for (const auto& f : kFiles) { const std::string path = dir + "/" + f.file; @@ -823,23 +829,30 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b " holds none of them"); } - /* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. */ + /* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. A + * rank-0 tensor is one element and is read as shape [1]: safetensors stores a scalar + * parameter (Gemma 4's clipped-linear bounds) with an empty shape. */ const SrcTensor& p0 = *out->pieces[0]; const int d = out->concat_dim; - if (p0.shape.empty() || p0.shape.size() > RAD_MAX_RANK || d < 0 || d >= (int)p0.shape.size()) + auto shape_of = [](const SrcTensor& t) { + return t.shape.empty() ? std::vector{ 1 } : t.shape; + }; + const std::vector s0 = shape_of(p0); + if (s0.size() > RAD_MAX_RANK || d < 0 || d >= (int)s0.size()) return refuse(RAD_E_SHAPE, "'" + p0.name + "' cannot be joined along dim " + std::to_string(d)); - out->rank = (uint32_t)p0.shape.size(); - for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = p0.shape[i]; + out->rank = (uint32_t)s0.size(); + for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = s0[i]; for (size_t k = 1; k < out->pieces.size(); ++k) { const SrcTensor& pk = *out->pieces[k]; - bool fits = pk.shape.size() == p0.shape.size(); + const std::vector sk = shape_of(pk); + bool fits = sk.size() == s0.size(); for (uint32_t i = 0; fits && i < out->rank; ++i) - if ((int)i != d && pk.shape[i] != p0.shape[i]) fits = false; + if ((int)i != d && sk[i] != s0[i]) fits = false; if (!fits) return refuse(RAD_E_SHAPE, "'" + pk.name + "' and '" + p0.name + "' do not join along dim " + std::to_string(d)); - out->shape[d] += pk.shape[(size_t)d]; + out->shape[d] += sk[(size_t)d]; } rad_enc_view(out->rank, out->shape, &out->rows, &out->cols); diff --git a/core/mm/item.cpp b/core/mm/item.cpp index 740c2c39..18794c6f 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -7,6 +7,18 @@ namespace rad { namespace mm { void Item::coords(int64_t first, int64_t count, int32_t* planes) const { + /* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real + * frames and its staged ones. */ + if (kind == Kind::Audio) { + for (int64_t k = 0; k < count; ++k) { + const int64_t f = first + k; + planes[k] = (int32_t)f; + planes[count + k] = f < valid ? 1 : 0; + planes[2 * count + k] = valid; + planes[3 * count + k] = grid_h; + } + return; + } /* Merge-block order inverted: a patch's index within its segment is * ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */ const int64_t seg = (int64_t)grid_h * grid_w; diff --git a/core/mm/media.cpp b/core/mm/media.cpp index 2fa04d39..c0d39975 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -10,8 +10,10 @@ extern "C" { #include #include +#include #include #include +#include #include } #endif @@ -36,6 +38,10 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*, std::string* why) { return no_decoder(why); } +int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector*, + std::string* why) { + return no_decoder(why); +} #else @@ -150,13 +156,19 @@ struct Input { /* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the * frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were - * encoded with; ACCURATE_RND and FULL_CHR_H_INT keep the conversion from truncating and from - * sampling chroma at half resolution. */ + * encoded with. + * + * THE SCALER FLAGS ARE THE REFERENCE PIPELINE'S: transformers decodes video through PyAV + * (`to_ndarray(format="rgb24")`, its default backend), which converts with plain SWS_BILINEAR. + * The flags decide how chroma is upsampled, and at a sharp colour edge two choices differ by up to + * 70 levels: measured on an EmbeddingGemma 2 clip, SWS_BICUBIC | ACCURATE_RND | FULL_CHR_H_INT + * left the embedding at cosine 0.9995 against the reference, these at 0.99998 with every patch + * within one level. */ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) { const AVPixelFormat src = (AVPixelFormat)f->format; *sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height, AV_PIX_FMT_RGB24, - SWS_BICUBIC | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, nullptr, + SWS_BILINEAR, nullptr, nullptr, nullptr); if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; } int cs = f->colorspace; @@ -360,6 +372,148 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use return RAD_OK; } +/* ================================================================== audio */ + +namespace { + +/* THE AUDIO DEMUXERS A REQUEST MAY REACH, chosen as the video list is: formats that hold one + * stream of samples and cannot name another file. */ +constexpr const char* kAudioFormats = "wav,w64,mp3,flac,ogg,mov,mp4,m4a,matroska,webm,aac,aiff"; + +struct AudioIn { + MemIO io; + AVIOContext* avio = nullptr; + AVFormatContext* fmt = nullptr; + AVCodecContext* dec = nullptr; + SwrContext* swr = nullptr; + int stream = -1; + + ~AudioIn() { + if (swr) swr_free(&swr); + if (dec) avcodec_free_context(&dec); + if (fmt) avformat_close_input(&fmt); + if (avio) { + av_freep(&avio->buffer); + avio_context_free(&avio); + } + } + + int open(const uint8_t* data, size_t n, std::string* why) { + io.p = data; io.n = n; io.at = 0; + constexpr int kBuf = 64 * 1024; + uint8_t* buf = static_cast(av_malloc(kBuf)); + if (!buf) { *why = "out of memory"; return RAD_E_NOMEM; } + avio = avio_alloc_context(buf, kBuf, 0, &io, mem_read, nullptr, mem_seek); + if (!avio) { av_free(buf); *why = "out of memory"; return RAD_E_NOMEM; } + fmt = avformat_alloc_context(); + if (!fmt) { *why = "out of memory"; return RAD_E_NOMEM; } + fmt->pb = avio; + fmt->flags |= AVFMT_FLAG_CUSTOM_IO; + AVDictionary* opts = nullptr; + av_dict_set(&opts, "format_whitelist", kAudioFormats, 0); + av_dict_set(&opts, "protocol_whitelist", "", 0); + int e = avformat_open_input(&fmt, nullptr, nullptr, &opts); + av_dict_free(&opts); + if (e < 0) { + fmt = nullptr; + *why = "not a recognised audio format (" + averr(e) + ")"; + return RAD_E_INVAL; + } + e = avformat_find_stream_info(fmt, nullptr); + if (e < 0) { *why = "could not read the stream headers (" + averr(e) + ")"; return RAD_E_INVAL; } + const AVCodec* codec = nullptr; + stream = av_find_best_stream(fmt, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0); + if (stream < 0 || !codec) { *why = "no sound in it: the media holds no audio stream"; return RAD_E_INVAL; } + dec = avcodec_alloc_context3(codec); + if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; } + e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar); + if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; } + dec->thread_count = 1; + e = avcodec_open2(dec, codec, nullptr); + if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; } + return RAD_OK; + } +}; + +} /* namespace */ + +int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why) { + std::string w; + if (!why) why = &w; + out->clear(); + if (rate <= 0 || max_samples <= 0) { *why = "no sample rate or length to decode to"; return RAD_E_INVAL; } + AudioIn in; + RAD_TRY(in.open(data, n, why)); + AVCodecContext* dec = in.dec; + const int channels = dec->ch_layout.nb_channels > 0 ? dec->ch_layout.nb_channels : 1; + if (dec->sample_rate <= 0) { *why = "the audio stream states no sample rate"; return RAD_E_INVAL; } + + /* Resampled at the source's own layout, float interleaved; the mono mean is taken after. A + * layout the stream does not state is taken as `channels` unordered channels. */ + AVChannelLayout layout{}; + if (av_channel_layout_check(&dec->ch_layout)) av_channel_layout_copy(&layout, &dec->ch_layout); + else av_channel_layout_default(&layout, channels); + int e = swr_alloc_set_opts2(&in.swr, &layout, AV_SAMPLE_FMT_FLT, rate, &layout, + (AVSampleFormat)dec->sample_fmt, dec->sample_rate, 0, nullptr); + av_channel_layout_uninit(&layout); + if (e < 0 || !in.swr || swr_init(in.swr) < 0) { + *why = "no resampler for this audio (" + averr(e) + ")"; + return RAD_E_UNSUPPORTED; + } + + std::vector buf; + auto take = [&](const uint8_t** src, int n_in) -> int { + const int cap = swr_get_out_samples(in.swr, n_in); + if (cap <= 0) return 0; + buf.resize((size_t)cap * (size_t)channels); + uint8_t* dst = reinterpret_cast(buf.data()); + const int got = swr_convert(in.swr, &dst, cap, src, n_in); + if (got < 0) { *why = "resampling failed (" + averr(got) + ")"; return RAD_E_INVAL; } + for (int i = 0; i < got && (int64_t)out->size() < max_samples; ++i) { + float s = 0.0f; + for (int c = 0; c < channels; ++c) s += buf[(size_t)i * channels + c]; + out->push_back(channels == 1 ? s : s / (float)channels); + } + return 0; + }; + + AVPacket* pkt = av_packet_alloc(); + AVFrame* f = av_frame_alloc(); + if (!pkt || !f) { + av_packet_free(&pkt); + av_frame_free(&f); + *why = "out of memory"; + return RAD_E_NOMEM; + } + int st = RAD_OK; + bool done = false; + while (!done && (int64_t)out->size() < max_samples) { + e = av_read_frame(in.fmt, pkt); + if (e < 0) { + avcodec_send_packet(dec, nullptr); /* drain */ + done = true; + } else { + if (pkt->stream_index == in.stream) e = avcodec_send_packet(dec, pkt); + av_packet_unref(pkt); + if (e < 0 && e != AVERROR(EAGAIN)) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; } + } + while ((e = avcodec_receive_frame(dec, f)) >= 0) { + if ((st = take(const_cast(f->extended_data), f->nb_samples)) < 0) break; + av_frame_unref(f); + } + if (st < 0) break; + if (e != AVERROR(EAGAIN) && e != AVERROR_EOF) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; } + } + /* What the resampler still holds. */ + if (st == RAD_OK && (int64_t)out->size() < max_samples) st = take(nullptr, 0); + av_packet_free(&pkt); + av_frame_free(&f); + if (st < 0) return st; + if (out->empty()) { *why = "the audio decoded to no samples"; return RAD_E_INVAL; } + return RAD_OK; +} + #endif /* RAD_HAVE_FFMPEG */ } /* namespace mm */ diff --git a/core/mm/media.h b/core/mm/media.h index 08aaa806..ba7614f9 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -56,5 +56,13 @@ struct Video { int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user, int64_t max_pixels, Video* out, std::string* why); +/* AN AUDIO CLIP as mono float samples at `rate` Hz: the first audio stream, resampled with + * libswresample at the source's channel layout and then averaged across channels -- the plain + * mean every reference loader (librosa, torchaudio's to-mono) takes, where swresample's own + * downmix would weight a stereo pair by 0.707. At most `max_samples` are kept: a longer clip is + * cut there, as the reference feature extractor truncates. */ +int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples, + std::vector* out, std::string* why); + } /* namespace mm */ } /* namespace rad */ diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 07d4ac35..b1890d40 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -26,7 +26,55 @@ static bool read_triple(const RadModelMeta& m, const char* key, float out[3]) { return true; } +static bool soft_budget_ok(int32_t n) { + return n == 70 || n == 140 || n == 280 || n == 560 || n == 1120; +} + int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { + const char* mt = rad_meta_gets(&m, "vision_config.model_type", ""); + if (mt && !std::strcmp(mt, "gemma4_vision")) { + family = Family::Gemma4; + patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); + merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0); + temporal = 1; + if (patch <= 0 || merge <= 0) { + if (why) *why = "the container states no vision tower geometry (vision_config." + "patch_size, pooling_kernel_size)"; + return RAD_E_NOTFOUND; + } + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1); + tok_start = (int32_t)rad_meta_geti(&m, "boi_token_id", -1); + tok_end = (int32_t)rad_meta_geti(&m, "eoi_token_id", -1); + if (tok_image < 0 || tok_video < 0 || tok_start < 0 || tok_end < 0) { + if (why) *why = "the container states no media token ids (image_token_id, " + "video_token_id, boi_token_id, eoi_token_id)"; + return RAD_E_NOTFOUND; + } + /* The budgets from the processor config, the model's stated default when it is absent. */ + image_soft_tokens = (int32_t)rad_meta_geti( + &m, "processor.image_processor.max_soft_tokens", + rad_meta_geti(&m, "vision_soft_tokens_per_image", + rad_meta_geti(&m, "vision_config.default_output_length", 280))); + video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens", + 70); + fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0); + min_frames = 1; + max_frames = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_frames", 32); + max_frame_rows = 0; + /* The pixel bands are QwenVL's; here they only have to be consistent for check(). */ + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = video_min_pixels = f2; + image_max_pixels = (int64_t)image_soft_tokens * f2; + video_max_pixels = (int64_t)video_soft_tokens * f2 * max_frames; + std::string bad; + if (check(&bad) < 0) { + if (why) *why = "the container's processor configuration is inconsistent: " + bad; + return RAD_E_INVAL; + } + return RAD_OK; + } + patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); temporal = (int32_t)rad_meta_geti(&m, "vision_config.temporal_patch_size", 0); merge = (int32_t)rad_meta_geti(&m, "vision_config.spatial_merge_size", 0); @@ -90,6 +138,14 @@ int VisionConfig::check(std::string* why) const { if (max_frames < min_frames) return no("max_frames " + std::to_string(max_frames) + " is below min_frames " + std::to_string(min_frames)); + if (family == Family::Gemma4) { + if (!soft_budget_ok(image_soft_tokens)) + return no("the image soft-token budget " + std::to_string(image_soft_tokens) + + " is not one of 70, 140, 280, 560, 1120"); + if (!soft_budget_ok(video_soft_tokens)) + return no("the video frame soft-token budget " + std::to_string(video_soft_tokens) + + " is not one of 70, 140, 280, 560, 1120"); + } return RAD_OK; } @@ -173,6 +229,65 @@ std::vector sample_frames(const VideoInfo& info, double fps, int32_t mi return idx; } +int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches, + int64_t* oh, int64_t* ow, std::string* why) { + if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; } + /* get_aspect_ratio_preserving_size, in Python's doubles. */ + const double total = (double)h * (double)w; + const double target = (double)max_patches * (double)patch * (double)patch; + const double factor = std::sqrt(target / total); + const int64_t side = (int64_t)patch * pool; + int64_t th = (int64_t)std::floor(factor * (double)h / (double)side) * side; + int64_t tw = (int64_t)std::floor(factor * (double)w / (double)side) * side; + if (th == 0 && tw == 0) { + if (why) *why = "the picture is too small to make one pooled patch"; + return RAD_E_INVAL; + } + const int64_t max_side = (max_patches / ((int64_t)pool * pool)) * side; + if (th == 0) { + th = side; + tw = std::min((int64_t)std::floor((double)w / (double)h) * side, max_side); + } else if (tw == 0) { + tw = side; + th = std::min((int64_t)std::floor((double)h / (double)w) * side, max_side); + } + if ((double)th * (double)tw > target) { + if (why) *why = "the picture's aspect ratio does not fit the patch budget"; + return RAD_E_INVAL; + } + *oh = th; + *ow = tw; + return RAD_OK; +} + +/* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`, + * one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by + * numpy's linspace truncated to integers. */ +std::vector sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames) { + const int64_t total = info.n_frames; + if (total <= 0) return {}; + std::vector idx; + if (info.fps > 0.0) { + const double step = info.fps / fps; + const double duration = (double)total / info.fps; + const int64_t n = std::max(1, (int64_t)(duration * fps)); + for (int64_t i = 0; i < n; ++i) + idx.push_back(std::min(total - 1, (int64_t)((double)i * step))); + } else { + for (int64_t i = 0; i < total; ++i) idx.push_back(i); + } + if (max_frames > 0 && (int64_t)idx.size() > max_frames) { + std::vector keep((size_t)max_frames); + const double span = (double)(idx.size() - 1); + for (int32_t i = 0; i < max_frames; ++i) { + const double t = max_frames == 1 ? 0.0 : span * (double)i / (double)(max_frames - 1); + keep[(size_t)i] = idx[(size_t)(int64_t)t]; + } + idx.swap(keep); + } + return idx; +} + /* ================================================================== the resample * * Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double, @@ -320,7 +435,8 @@ inline uint64_t mix64(uint64_t x) { void content_key(const Item& it, uint64_t* hi, uint64_t* lo) { uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^ (uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w); - uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : 2u); + uint64_t b = 0xbb67ae8584caa73bull ^ + mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u); const uint8_t* p = reinterpret_cast(it.pixels.data()); const size_t n = it.pixels.size() * sizeof(uint16_t); size_t i = 0; @@ -375,6 +491,37 @@ void patchify(const VisionConfig& c, const std::vector& frames, It } } +/* Gemma 4's patch rows: merge-block order like patchify's (each pooling window's patches are + * consecutive, which is what lets the pooler be a mean of k^2 consecutive rows; attention and the + * position terms read each patch's own coordinates, so the order is free), each row (y, x, + * channel), each value 2 * (u * (1/255)) - 1 in f32 -- the processor's rescale and then the + * model's own input scaling -- rounded to bf16. One frame a segment. */ +void patchify_gemma4(const VisionConfig& c, const std::vector& frames, Item* it) { + const int P = c.patch, M = c.merge; + const int gh = it->grid_h, gw = it->grid_w; + uint16_t lut[256]; + for (int v = 0; v < 256; ++v) { + const float p = (float)v * (float)(1.0 / 255.0); + lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f)); + } + const int64_t dim = it->patch_dim; + it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0); + uint16_t* dst = it->pixels.data(); + for (int g = 0; g < it->grid_t; ++g) { + const Frame& f = *frames[(size_t)g]; + for (int bh = 0; bh < gh / M; ++bh) + for (int bw = 0; bw < gw / M; ++bw) + for (int mh = 0; mh < M; ++mh) + for (int mw = 0; mw < M; ++mw) { + const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P; + for (int y = 0; y < P; ++y) { + const uint8_t* row = f.rgb.data() + ((size_t)(py0 + y) * f.w + px0) * 3; + for (int x = 0; x < 3 * P; ++x) *dst++ = lut[row[x]]; + } + } + } +} + void finish_item(const VisionConfig& c, Item* it) { it->patch_dim = c.patch_dim(); it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w; @@ -393,6 +540,14 @@ int Processor::init(const VisionConfig& cfg, if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0) return RAD_E_INVAL; cfg_ = cfg; + if (cfg.family == Family::Gemma4) { + /* A budget is a patch count, and an image is one segment of one pass. */ + if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches || + (int64_t)cfg.video_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches) + return RAD_E_INVAL; + encode_text_ = std::move(encode_text); + return RAD_OK; + } /* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to * it, so smart_resize itself keeps every image inside a pass. */ const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch; @@ -406,6 +561,7 @@ int Processor::init(const VisionConfig& cfg, int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why) const { const VisionConfig& c = cfg_; + if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why); int64_t h = 0, w = 0; RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, &h, &w, why)); @@ -435,8 +591,80 @@ int Processor::image_from(const Frame& f, std::shared_ptr* out, std::strin return RAD_OK; } +int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, + std::string* why) const { + const VisionConfig& c = cfg_; + int64_t h = 0, w = 0; + RAD_TRY(gemma4_size(f.h, f.w, c.patch, c.merge, (int64_t)soft * c.merge * c.merge, &h, &w, + why)); + Frame r; + const Frame* src = &f; + if (h != f.h || w != f.w) { + resize_bicubic(f, (int32_t)w, (int32_t)h, &r); + src = &r; + } + auto it = std::make_shared(); + it->kind = Kind::Image; + it->grid_t = 1; + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if (it->n_patch > c.max_patches) { + if (why) *why = "the image's soft-token budget is more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + patchify_gemma4(c, { src }, it.get()); + content_key(*it, &it->key_hi, &it->key_lo); + it->expand.reserve((size_t)it->seg_rows + 2); + it->expand.push_back(c.tok_start); + it->seg_at.push_back(1); + it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image); + it->expand.push_back(c.tok_end); + *out = std::move(it); + return RAD_OK; +} + +int Processor::video_gemma4(const Video& v, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; } + int64_t h = 0, w = 0; + RAD_TRY(gemma4_size(v.frames[0].h, v.frames[0].w, c.patch, c.merge, + (int64_t)c.video_soft_tokens * c.merge * c.merge, &h, &w, why)); + auto it = std::make_shared(); + it->kind = Kind::Video; + it->grid_t = (int32_t)v.frames.size(); + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if ((int64_t)it->grid_h * it->grid_w > c.max_patches) { + if (why) *why = "a video frame's soft-token budget is more patches than one encoder pass " + "holds"; + return RAD_E_INVAL; + } + std::vector resized(v.frames.size()); + std::vector rf; + for (size_t i = 0; i < v.frames.size(); ++i) { + if (v.frames[i].h == h && v.frames[i].w == w) { rf.push_back(&v.frames[i]); continue; } + resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]); + rf.push_back(&resized[i]); + } + patchify_gemma4(c, rf, it.get()); + content_key(*it, &it->key_hi, &it->key_lo); + /* One placeholders run a frame, back to back: the reference's visual-only form + * (add_timestamps off). */ + for (int32_t g = 0; g < it->grid_t; ++g) { + it->expand.push_back(c.tok_start); + it->seg_at.push_back((int32_t)it->expand.size()); + it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video); + it->expand.push_back(c.tok_end); + } + *out = std::move(it); + return RAD_OK; +} + int Processor::video_from(const Video& v, std::shared_ptr* out, std::string* why) const { const VisionConfig& c = cfg_; + if (c.family == Family::Gemma4) return video_gemma4(v, out, why); if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; } /* The frames and their indices, padded to whole temporal groups by repeating the last. A clip * shorter than one group is padded the same way, so a single-frame video is one group. */ @@ -516,29 +744,310 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin return RAD_OK; } -int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr* out, - std::string* why) const { +int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, + std::shared_ptr* out, std::string* why) const { + if (image_tokens != 0) { + if (cfg_.family != Family::Gemma4) { + if (why) *why = "this model's processor sizes an image by its pixels, not by a token " + "budget"; + return RAD_E_UNSUPPORTED; + } + if (!soft_budget_ok(image_tokens) || + (int64_t)image_tokens * cfg_.merge * cfg_.merge > cfg_.max_patches) { + if (why) *why = "the image token budget must be one of 70, 140, 280, 560, 1120 and " + "fit one encoder pass (" + std::to_string(cfg_.max_patches) + + " patches)"; + return RAD_E_INVAL; + } + } Frame f; RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + if (cfg_.family == Family::Gemma4) + return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why); return image_from(f, out, why); } namespace { -struct SampleArgs { double fps; int32_t lo, hi; }; +struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; }; std::vector sample_cb(const VideoInfo& info, const void* user) { const SampleArgs* a = static_cast(user); - return sample_frames(info, a->fps, a->lo, a->hi); + return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi) + : sample_frames(info, a->fps, a->lo, a->hi); } } /* namespace */ int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const { Video v; - const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames }; + const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames, + cfg_.family == Family::Gemma4 }; RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why)); return video_from(v, out, why); } +/* ================================================================== audio */ + +/* A list a container flattened from a JSON array ("1 2 3"), or nothing when it is absent or null. */ +static std::vector read_list(const RadModelMeta& m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(&m, key, nullptr); + if (!s || !*s) return v; + std::istringstream is(s); + double x; + while (is >> x) v.push_back(x); + return v; +} + +int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) { + const char* mt = rad_meta_gets(&m, "audio_config.model_type", ""); + if (!mt || std::strcmp(mt, "gemma4_audio")) { + if (why) *why = "the container states no audio tower this processor knows (audio_config." + "model_type gemma4_audio)"; + return RAD_E_NOTFOUND; + } + rate = (int32_t)rad_meta_geti(&m, "preprocessor.sampling_rate", 16000); + frame_length = (int32_t)rad_meta_geti(&m, "preprocessor.frame_length", 320); + hop = (int32_t)rad_meta_geti(&m, "preprocessor.hop_length", 160); + n_mels = (int32_t)rad_meta_geti(&m, "preprocessor.feature_size", 128); + fft = (int32_t)rad_meta_geti(&m, "preprocessor.fft_length", 0); + if (fft <= 0) { + fft = 1; + while (fft < frame_length) fft *= 2; + } + if (rad_meta_geti(&m, "preprocessor.fft_overdrive", 0)) fft *= 2; + min_freq = rad_meta_getf(&m, "preprocessor.min_frequency", 0.0); + max_freq = rad_meta_getf(&m, "preprocessor.max_frequency", 8000.0); + mel_floor = rad_meta_getf(&m, "preprocessor.mel_floor", 1e-3); + preemphasis = rad_meta_getf(&m, "preprocessor.preemphasis", 0.0); + preemphasis_htk = rad_meta_geti(&m, "preprocessor.preemphasis_htk_flavor", 1) != 0; + input_scale = rad_meta_getf(&m, "preprocessor.input_scale_factor", 1.0); + bin_mean = read_list(m, "preprocessor.per_bin_mean"); + bin_std = read_list(m, "preprocessor.per_bin_stddev"); + max_samples = 480000; + tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1); + tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1); + tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id", rad_meta_geti(&m, "eoa_token_index", -1)); + /* DITHER IS NOISE: the reference adds Gaussian noise of this deviation to every sample, a + * different draw each call, and no fixed input reproduces it. */ + if (rad_meta_getf(&m, "preprocessor.dither", 0.0) != 0.0) { + if (why) *why = "the feature extractor dithers its input (preprocessor.dither), which no " + "deterministic front end reproduces"; + return RAD_E_UNSUPPORTED; + } + if (rate <= 0 || frame_length <= 1 || hop <= 0 || n_mels <= 0 || fft < frame_length || + !(max_freq > min_freq) || !(mel_floor > 0.0) || tok_audio < 0 || tok_start < 0 || + tok_end < 0 || (!bin_mean.empty() && (int64_t)bin_mean.size() != n_mels) || + (!bin_std.empty() && (int64_t)bin_std.size() != n_mels)) { + if (why) *why = "the container's audio feature configuration is incomplete or " + "inconsistent (rate, frame and hop lengths, mel bins, frequencies, " + "audio_token_id, boa_token_id, eoa_token_id)"; + return RAD_E_INVAL; + } + return RAD_OK; +} + +int64_t AudioConfig::real_frames(int64_t n) const { + /* Frame i's last sample is (frame_length / 2 zeros) + i * hop + frame_length, and it is real + * when that is inside the clip: i * hop + frame_length < frame_length / 2 + n. */ + const int64_t room = n + frame_length / 2 - frame_length - 1; + return room < 0 ? 0 : room / hop + 1; +} + +namespace { + +/* An in-place radix-2 complex FFT, n a power of two: the frame's real spectrum in double, as the + * reference's numpy rfft computes it. */ +void fft_inplace(std::vector& re, std::vector& im, + const std::vector& tw_re, const std::vector& tw_im, + const std::vector& brev) { + const size_t n = re.size(); + for (size_t i = 1; i < n; ++i) { + const size_t j = (size_t)brev[i]; + if (i < j) { std::swap(re[i], re[j]); std::swap(im[i], im[j]); } + } + for (size_t len = 2; len <= n; len <<= 1) { + const size_t step = n / len; /* stage len's k-th twiddle is the table's k * step */ + for (size_t i = 0; i < n; i += len) + for (size_t k = 0; k < len / 2; ++k) { + const double wr = tw_re[k * step], wi = tw_im[k * step]; + const size_t a = i + k, b = i + k + len / 2; + const double xr = re[b] * wr - im[b] * wi, xi = re[b] * wi + im[b] * wr; + re[b] = re[a] - xr; im[b] = im[a] - xi; + re[a] += xr; im[a] += xi; + } + } +} + +/* numpy.linspace's values: start + i * step, the last exactly `stop`. */ +std::vector linspace(double a, double b, int64_t n) { + std::vector v((size_t)n); + const double step = n > 1 ? (b - a) / (double)(n - 1) : 0.0; + for (int64_t i = 0; i < n; ++i) v[(size_t)i] = a + (double)i * step; + if (n > 1) v[(size_t)n - 1] = b; + return v; +} + +} /* namespace */ + +int Processor::init_audio(const AudioConfig& cfg) { + if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge) return RAD_E_INVAL; + acfg_ = cfg; + /* np.hanning(frame_length + 1)[:-1], the periodic window, stored as float32. */ + hann_.resize((size_t)cfg.frame_length); + for (int32_t i = 0; i < cfg.frame_length; ++i) + hann_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * M_PI * (double)i / + (double)cfg.frame_length)); + /* transformers' mel_filter_bank(norm=None, mel_scale="htk"): triangles between consecutive + * mel points, in Hz, over the FFT bins' frequencies. */ + const int64_t nb = cfg.fft / 2 + 1, nm = cfg.n_mels; + auto hz2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); }; + auto mel2hz = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); }; + const std::vector fft_f = linspace(0.0, (double)(cfg.rate / 2), nb); + std::vector filt = linspace(hz2mel(cfg.min_freq), hz2mel(cfg.max_freq), nm + 2); + for (double& f : filt) f = mel2hz(f); + mel_.assign((size_t)(nb * nm), 0.0); + mel_lo_.assign((size_t)nm, 0); + mel_hi_.assign((size_t)nm, 0); + for (int64_t i = 0; i < nm; ++i) { + int32_t lo = -1, hi = 0; + for (int64_t k = 0; k < nb; ++k) { + const double down = -(filt[(size_t)i] - fft_f[(size_t)k]) / + (filt[(size_t)i + 1] - filt[(size_t)i]); + const double up = (filt[(size_t)i + 2] - fft_f[(size_t)k]) / + (filt[(size_t)i + 2] - filt[(size_t)i + 1]); + const double w = std::max(0.0, std::min(down, up)); + mel_[(size_t)(i * nb + k)] = w; + if (w != 0.0) { if (lo < 0) lo = (int32_t)k; hi = (int32_t)k + 1; } + } + /* A triangle covers a few bins; the sum skips the zeros, which add nothing to it. */ + mel_lo_[(size_t)i] = lo < 0 ? 0 : lo; + mel_hi_[(size_t)i] = hi; + } + /* The FFT's twiddles, once: a butterfly that evaluates its own sin and cos makes the + * transform cost a 30 s clip over 100 ms. */ + brev_.assign((size_t)cfg.fft, 0); + for (int32_t i = 1, j = 0; i < cfg.fft; ++i) { + int32_t bit = cfg.fft >> 1; + for (; j & bit; bit >>= 1) j ^= bit; + j ^= bit; + brev_[(size_t)i] = j; + } + tw_re_.resize((size_t)cfg.fft / 2); + tw_im_.resize((size_t)cfg.fft / 2); + for (int32_t k = 0; k < cfg.fft / 2; ++k) { + const double ang = -2.0 * M_PI * (double)k / (double)cfg.fft; + tw_re_[(size_t)k] = std::cos(ang); + tw_im_[(size_t)k] = std::sin(ang); + } + audio_on_ = true; + return RAD_OK; +} + +int Processor::audio_from(const std::vector& samples, std::shared_ptr* out, + std::string* why) const { + if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; } + const AudioConfig& c = acfg_; + const int64_t n = std::min((int64_t)samples.size(), c.max_samples); + const int64_t real = c.real_frames(n); + const int64_t rows = (real + c.merge - 1) / c.merge; + const int64_t frames = rows * c.merge; + if (frames > c.max_frames) { + if (why) *why = "the clip is more frames than one audio encoder pass holds"; + return RAD_E_INVAL; + } + auto it = std::make_shared(); + it->kind = Kind::Audio; + it->grid_t = 1; + it->grid_h = (int32_t)frames; + it->grid_w = 1; + it->patch_dim = c.n_mels; + it->n_patch = frames; + it->valid = (int32_t)real; + it->rows_h = (int32_t)rows; + it->rows_w = 1; + it->seg_rows = (int32_t)rows; + it->n_seg = rows > 0 ? 1 : 0; + it->pixels.assign((size_t)(frames * c.n_mels), 0); + + const int64_t pad = c.frame_length / 2; + const int64_t nb = c.fft / 2 + 1; + std::vector re((size_t)c.fft), im((size_t)c.fft), mag((size_t)nb); + std::vector fr((size_t)c.frame_length + 1); + auto sample = [&](int64_t p) -> float { /* the zero-led clip, zero past its end */ + const int64_t q = p - pad; + return q >= 0 && q < n ? samples[(size_t)q] * (float)c.input_scale : 0.0f; + }; + /* Frame i's windowed samples into dst, zero past the frame. */ + auto window = [&](int64_t i, double* dst) { + for (int32_t j = 0; j <= c.frame_length; ++j) fr[(size_t)j] = sample(i * c.hop + j); + for (int32_t j = 0; j < c.frame_length; ++j) { + float v; + if (c.preemphasis > 0.0) { + const float pe = (float)c.preemphasis; + v = c.preemphasis_htk ? (j == 0 ? fr[0] * (1.0f - pe) : fr[(size_t)j] - pe * fr[(size_t)j - 1]) + : fr[(size_t)j + 1] - pe * fr[(size_t)j]; + } else { + v = fr[(size_t)j]; + } + dst[j] = (double)(v * hann_[(size_t)j]); /* the product in float32 */ + } + for (int32_t j = c.frame_length; j < c.fft; ++j) dst[j] = 0.0; + }; + /* Frame i's mel bins from its magnitudes. */ + auto emit = [&](int64_t i, const double* m) { + uint16_t* dst = it->pixels.data() + i * c.n_mels; + for (int32_t b = 0; b < c.n_mels; ++b) { + double s = 0.0; + const double* w = mel_.data() + (size_t)b * nb; + for (int32_t k = mel_lo_[(size_t)b]; k < mel_hi_[(size_t)b]; ++k) s += m[k] * w[k]; + double v = std::log(s + c.mel_floor); + if (!c.bin_mean.empty()) v -= c.bin_mean[(size_t)b]; + if (!c.bin_std.empty()) v /= c.bin_std[(size_t)b]; + dst[b] = rad_f32_to_bf16((float)v); + } + }; + /* TWO REAL FRAMES A COMPLEX TRANSFORM: frame a in the real part, frame b in the imaginary, + * and the two spectra separate by symmetry -- A[k] = (Z[k] + conj Z[n-k]) / 2 and + * B[k] = (Z[k] - conj Z[n-k]) / 2i. Half the transforms; the magnitudes agree with one + * transform a frame to a few ulps of double. |X| is sqrt(re^2 + im^2), within an ulp of + * numpy's hypot and far below the float32 the features are rounded to. */ + std::vector mag2((size_t)nb); + const int64_t N = c.fft; + for (int64_t i = 0; i < real; i += 2) { + const bool pair = i + 1 < real; + window(i, re.data()); + if (pair) window(i + 1, im.data()); + else std::fill(im.begin(), im.end(), 0.0); + fft_inplace(re, im, tw_re_, tw_im_, brev_); + for (int64_t k = 0; k < nb; ++k) { + const size_t a = (size_t)k, b = k ? (size_t)(N - k) : 0; + const double ar = 0.5 * (re[a] + re[b]), ai = 0.5 * (im[a] - im[b]); + const double br = 0.5 * (im[a] + im[b]), bi = -0.5 * (re[a] - re[b]); + mag[a] = std::sqrt(ar * ar + ai * ai); + mag2[a] = std::sqrt(br * br + bi * bi); + } + emit(i, mag.data()); + if (pair) emit(i + 1, mag2.data()); + } + content_key(*it, &it->key_hi, &it->key_lo); + it->expand.push_back(c.tok_start); + it->seg_at.push_back(1); + it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio); + it->expand.push_back(c.tok_end); + /* A clip too short for one real frame is and nothing to encode. */ + if (rows == 0) it->encoded = true; + *out = std::move(it); + return RAD_OK; +} + +int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr* out, + std::string* why) const { + if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; } + std::vector s; + RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples, &s, why)); + return audio_from(s, out, why); +} + /* ================================================================== rotary layout */ void PromptMedia::layout() { diff --git a/core/mm/processor.h b/core/mm/processor.h index c46f5af9..92cfec31 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -37,10 +37,27 @@ struct RadModelMeta; namespace rad { namespace mm { -enum class Kind { Image, Video }; +enum class Kind { Image, Video, Audio }; + +/* THE PROCESSOR FAMILY, from the container's vision_config.model_type. The two differ in how a + * picture is sized, what a patch value is, and how a video is sampled and spelled in the prompt; + * the Item they produce and everything after it is shared. + * + * QwenVL smart_resize into a pixel band; patches (channel, frame, y, x) normalised by the + * configured mean and deviation; videos in temporal groups, each after a "". + * Gemma4 the largest size whose sides are multiples of patch * pooling and whose patch count + * fits the soft-token budget (budget * pooling^2), aspect ratio kept; patches (y, x, + * channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is + * frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment + * at the per-frame budget, each spelled placeholders with no timestamp. */ +enum class Family { QwenVL, Gemma4 }; struct VisionConfig { + Family family = Family::QwenVL; int32_t patch = 0, temporal = 0, merge = 0; + /* Gemma4: soft tokens (output rows) an image, and a video frame, may take. One of 70, 140, + * 280, 560, 1120 -- the budgets the model was trained at. */ + int32_t image_soft_tokens = 0, video_soft_tokens = 0; int64_t image_min_pixels = 0, image_max_pixels = 0; int64_t video_min_pixels = 0, video_max_pixels = 0; double fps = 2.0; @@ -75,6 +92,37 @@ struct VisionConfig { int from_meta(const RadModelMeta& m, std::string* why); }; +/* WHAT AN AUDIO CLIP BECOMES: Gemma 4's feature extractor (Gemma4AudioFeatureExtractor), read + * from the container's `preprocessor.*` (the checkpoint's preprocessor_config.json) and its + * audio_config. The samples are mono at `rate`, cut at `max_samples`; `frame_length / 2` zeros go + * in front; frame i is samples [i * hop, i * hop + frame_length) of that, pre-emphasised when the + * config says so, times a periodic Hann window, through a `fft`-point real FFT; its magnitudes go + * through an HTK mel bank (no area normalisation) and log(x + mel_floor), optionally standardised + * per bin. A frame is real when its last sample is a real one -- the reference's mask -- so a clip + * of n samples has floor((n - frame_length / 2 - 1) / hop) + 1 real frames and the reference's + * output keeps ceil(real / merge) rows of it: that many placeholders, between and . + * The staged patches are the real frames then zero frames to a whole number of rows -- equal, for + * every row the reference keeps, to the frames past the end the reference zeroes. */ +struct AudioConfig { + int32_t rate = 0, frame_length = 0, hop = 0, fft = 0, n_mels = 0; + double min_freq = 0.0, max_freq = 0.0, mel_floor = 0.0; + double preemphasis = 0.0, input_scale = 1.0; + bool preemphasis_htk = true; + std::vector bin_mean, bin_std; /* empty: no per-bin standardisation */ + /* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz). */ + int64_t max_samples = 0; + int32_t tok_audio = -1, tok_start = -1, tok_end = -1; + + /* THE ENCODER'S: frames an output row, and the most frames a pass carries. */ + int32_t merge = 0; + int64_t max_frames = 0; + + /* Read from the container; refuses one that states no Gemma 4 audio tower. */ + int from_meta(const RadModelMeta& m, std::string* why); + /* The real frames of an n-sample clip. */ + int64_t real_frames(int64_t n_samples) const; +}; + /* One media part after processing: its patches, its place in the prompt's token stream, and -- * once the encoder has run -- its rows. Shared between the request that owns it and the engine * thread that encodes it; the engine writes `embd` once and nothing reads it before then. */ @@ -88,6 +136,9 @@ struct Item { /* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group. * `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */ int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0; + /* An audio clip's REAL feature frames; the rest of its `grid_h` are the zero frames that make + * it whole output rows. 0 for a picture or a video. */ + int32_t valid = 0; int64_t n_rows() const { return (int64_t)n_seg * seg_rows; } /* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of @@ -184,15 +235,38 @@ public: int init(const VisionConfig& cfg, std::function(const std::string&)> encode_text); const VisionConfig& config() const { return cfg_; } - int image(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; + /* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a + * processor that sizes images by pixels refuses a non-zero one. */ + int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out, + std::string* why) const; int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; /* The pieces, exposed for the test suite: an already-decoded picture or frame list. */ int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const; int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; + /* AUDIO, when the program declared an audio encoder: `merge` and `max_frames` are its. */ + int init_audio(const AudioConfig& cfg); + bool has_audio() const { return audio_on_; } + const AudioConfig& audio_config() const { return acfg_; } + int audio(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; + /* ...and from samples already decoded (mono at the configured rate), for the test suite. */ + int audio_from(const std::vector& samples, std::shared_ptr* out, + std::string* why) const; + private: + int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, + std::string* why) const; + int video_gemma4(const Video& v, std::shared_ptr* out, std::string* why) const; + VisionConfig cfg_{}; + AudioConfig acfg_{}; + bool audio_on_ = false; + std::vector hann_; /* the window, float32 as the reference stores it */ + std::vector mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */ + std::vector mel_lo_, mel_hi_; /* filter b's nonzero bins, [lo, hi) */ + std::vector tw_re_, tw_im_; /* exp(-2 pi i k / fft), k < fft/2 */ + std::vector brev_; /* the FFT's bit-reversal permutation */ std::function(const std::string&)> encode_text_; }; @@ -205,6 +279,12 @@ int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t /* Which frames a video keeps. */ std::vector sample_frames(const VideoInfo& info, double fps, int32_t min_frames, int32_t max_frames); +/* ...the Gemma 4 rule: one frame each 1 / fps seconds, thinned evenly to `max_frames`. */ +std::vector sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames); +/* Gemma 4's target size: the largest (h, w), both multiples of `side`, whose patch count stays + * within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */ +int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches, + int64_t* oh, int64_t* ow, std::string* why); /* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a * horizontal pass into an 8-bit intermediate and then a vertical one. */ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); diff --git a/core/rad_core.h b/core/rad_core.h index 72a3d660..4cb287ac 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -346,6 +346,9 @@ public: * purpose -- the engine refuses to SERVE such a program and says so at startup, rather * than discovering at the first step that there is nothing to sample. */ rad_buf logits_buf = 0; + /* The buffer the plugin named as this step's pooled vectors (rad_declare_pooled): set only by + * an EMBEDDING program, which then has no logits buffer. */ + rad_buf pooled_buf = 0; /* THE DRAFT HEAD THIS PLUGIN DECLARED (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when * it declared none, which is the normal case -- the engine then speculates with the @@ -359,6 +362,9 @@ public: * media (RadBuildCtx::max_enc_patches 0). `encoder_name` for the reason `drafter_name` is. */ RadEncoderDecl encoder{}; std::string encoder_name; + /* ...and the audio encoder, the second a program may declare (RAD_MM_AUDIO). */ + RadEncoderDecl audio_encoder{}; + std::string audio_encoder_name; /* Two arenas, because a host-site activation cannot index device memory. The buffer plan * colours the domains SEPARATELY -- a transient may share storage only with a transient in the @@ -598,6 +604,12 @@ struct Request { * it; the logits buffer is sized for it there and nowhere else. */ bool score = false; + /* AN EMBEDDING REQUEST: the whole prompt in ONE step, never split -- an encoder that attends + * both ways cannot be fed half its input -- and finished at that step with its pooled vector + * in the sink (Sink::embedding). Nothing is generated and nothing is emitted. Only an + * embedding program (rad_declare_pooled) serves these, and it serves nothing else. */ + bool embed = false; + std::string finish_reason; void* sink = nullptr; /* the server's per-request stream sink */ }; @@ -780,6 +792,9 @@ struct Config { * when the container carries a vision tower and 0 when it does not. 0 serves text only and * keeps a tower the container carries off the card. */ int64_t mm_max_patches = -1; + /* The audio encoder's pass in frames, resolved at bring-up from the plugin's probe when the + * container carries an audio encoder; --mm-max-patches 0 (text only) turns it off too. */ + int64_t mm_audio_frames = -1; std::string host = "0.0.0.0"; /* The chat endpoint's default `reasoning_effort`, empty for the template's own default. @@ -869,10 +884,12 @@ struct Config { std::optional video_fps; std::optional video_min_frames, video_max_frames, video_max_frame_tokens; std::optional max_source_pixels; + /* A token-budget processor's (Gemma 4's) soft tokens an image. */ + std::optional image_tokens; bool media_flags_set() const { return image_min_pixels || image_max_pixels || video_min_pixels || video_max_pixels || video_fps || video_min_frames || video_max_frames || video_max_frame_tokens || - max_source_pixels; + max_source_pixels || image_tokens; } /* An operator-supplied generation_config.json, overriding the search described above. */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 53c5f2c4..41e3465e 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -401,9 +401,21 @@ int Ctx::bind_ops() { /* Execution site. Site is a property of the weights (spec §5.1), so an op whose every * weight operand was placed on the host runs its host kernel and everything else runs on * the device. An op with no weights stays on the device; the planner overrides through - * set_op_domain, which is where the "contiguous host runs" objective actually lands. */ + * set_op_domain, which is where the "contiguous host runs" objective actually lands. + * + * ON THE HOST BACKEND (no card visible: CPU-only serving) the device domain is the host's + * own memory and an op with no device kernel in any band runs its host kernel -- the + * whole model on libavx (or libref) with no switch to set. An op that does carry device + * rows there is a test registering fakes, and keeps them. */ int dom = RAD_DOMAIN_DEVICE; - if (!oi.weights.empty()) { + if (device_is_host()) { + bool any_device = false; + for (int b = 0; b < p.n_bands && !any_device; ++b) + any_device = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS + + RAD_DOMAIN_DEVICE].launch != nullptr; + if (!any_device) dom = RAD_DOMAIN_HOST; + } + if (dom == RAD_DOMAIN_DEVICE && !oi.weights.empty()) { bool all_host = true; for (rad_weight w : oi.weights) { const WeightInfo* wi = P.weight(w); diff --git a/core/runtime/oracle.cpp b/core/runtime/oracle.cpp index 2ed5bc37..7d7b9674 100644 --- a/core/runtime/oracle.cpp +++ b/core/runtime/oracle.cpp @@ -883,7 +883,7 @@ const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) { static const IssuePlan kRepeatArmed{}; return &kRepeatArmed; } - /* NOT GATED ON THE DEVICE DOMAIN. Under RADIANCE_HOST_DOMAIN the launch IS the host kernel, + /* NOT GATED ON THE DEVICE DOMAIN. On the host backend the launch IS the host kernel, * so the comparison is host against host and agrees by construction -- but the per-operand * lines are still the only ordered trace of what the graph computed, and diffing those * against another engine's is what the whole-model reference exists for. */ diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index f090bdfc..2480d991 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -495,21 +495,27 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) { : a.conv_grp < b.conv_grp; }); - mm_on_ = prog.encoder.modalities != 0; + mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0; return RAD_OK; } /* ------------------------------------------------------------------ media staging */ BatchBuilder::MediaBytes BatchBuilder::media_bytes() { - const RadEncoderDecl& e = prog_->encoder; - n_embd_ = e.n_embd; - enc_patches_ = e.max_patches; - enc_dim_ = e.patch_dim; - /* The most segments one pass can hold: a segment is at least one output row, `merge` patches. */ - enc_segs_ = e.max_patches / (e.merge > 0 ? e.merge : 1) + 1; + /* The larger of the two encoders' passes, field by field: they run one at a time. Both write + * rows of the model's embedding width. */ + enc_patches_ = enc_pix_elems_ = enc_segs_ = 0; + n_embd_ = 0; + for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) { + if (e->modalities == 0) continue; + n_embd_ = std::max(n_embd_, e->n_embd); + enc_patches_ = std::max(enc_patches_, e->max_patches); + enc_pix_elems_ = std::max(enc_pix_elems_, e->max_patches * e->patch_dim); + /* The most segments one pass can hold: a segment is at least one output row. */ + enc_segs_ = std::max(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1); + } MediaBytes m; m.mm = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t); - m.pix = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t); + m.pix = enc_pix_elems_ * (int64_t)sizeof(uint16_t); m.crd = 4 * enc_patches_ * (int64_t)sizeof(int32_t); m.cu = (enc_segs_ + 1) * (int64_t)sizeof(int32_t); return m; @@ -546,7 +552,7 @@ int BatchBuilder::alloc_media() { } if (rad_event_create_as(&mm_ev_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0) return RAD_E_DEVICE; RAD_INFO("media staging: %s a rank for a step's encoder rows and %s for an encoder pass of " - "%lld patches", humanb(mm_bytes).c_str(), + "up to %lld patches", humanb(mm_bytes).c_str(), humanb(pix_bytes + crd_bytes + cu_bytes).c_str(), (long long)enc_patches_); return RAD_OK; } @@ -1272,24 +1278,27 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const { } /* ------------------------------------------------------------------ the encoder pass */ -const RadBatch* BatchBuilder::build_encoder(const std::vector& parts, int step) { - if (!mm_on_ || parts.empty()) return nullptr; +const RadBatch* BatchBuilder::build_encoder(const std::vector& parts, int step, + const RadEncoderDecl& enc) { + if (!mm_on_ || parts.empty() || enc.modalities == 0) return nullptr; + const int64_t enc_dim = enc.patch_dim; + const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1; int64_t n_patch = 0, n_seg = 0, max_seg = 0; enc_cu_host_[0] = 0; for (const EncoderPart& p : parts) { const mm::Item& it = *p.item; const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; const int64_t np = seg_p * p.n_seg; - if (it.patch_dim != enc_dim_ || n_patch + np > enc_patches_ || - n_seg + p.n_seg > enc_segs_ || p.seg0 + p.n_seg > it.n_seg) { + if (it.patch_dim != enc_dim || n_patch + np > enc.max_patches || + n_seg + p.n_seg > max_segs || p.seg0 + p.n_seg > it.n_seg) { RAD_ERR("encoder pass: %lld patches in %lld segments do not fit the declared pass of " "%lld patches of %lld elements", (long long)(n_patch + np), - (long long)(n_seg + p.n_seg), (long long)enc_patches_, (long long)enc_dim_); + (long long)(n_seg + p.n_seg), (long long)enc.max_patches, (long long)enc_dim); return nullptr; } - std::memcpy(enc_pix_host_ + n_patch * enc_dim_, - it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim_, - (size_t)(np * enc_dim_) * sizeof(uint16_t)); + std::memcpy(enc_pix_host_ + n_patch * enc_dim, + it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim, + (size_t)(np * enc_dim) * sizeof(uint16_t)); n_patch += np; for (int32_t q = 0; q < p.n_seg; ++q) { enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p; @@ -1316,7 +1325,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part for (size_t r = 0; r < ranks_.size(); ++r) { RadStream st = ranks_[r].stream; if (rad_memcpy_async(enc_pix_dev_[r], enc_pix_host_, - n_patch * enc_dim_ * (int64_t)sizeof(uint16_t), st) < 0 || + n_patch * enc_dim * (int64_t)sizeof(uint16_t), st) < 0 || rad_memcpy_async(enc_coord_dev_[r], enc_coord_host_, 4 * n_patch * (int64_t)sizeof(int32_t), st) < 0 || rad_memcpy_async(enc_cu_dev_[r], enc_cu_host_, @@ -1333,7 +1342,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part B.step = step; B.n_kv_groups = (int)o.kv[r].size(); B.kv = o.kv[r].data(); - B.enc = 1; + B.enc = (int32_t)enc.modalities; B.enc_n_patch = n_patch; B.enc_pixels = enc_pix_dev_[r]; B.enc_coord = static_cast(enc_coord_dev_[r]); diff --git a/core/sched/batch.h b/core/sched/batch.h index d238e71a..91e66b0e 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -168,9 +168,11 @@ public: const mm::Item* item = nullptr; int32_t seg0 = 0, n_seg = 0; }; - const RadBatch* build_encoder(const std::vector& parts, int step); + /* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts, + * and its modalities are RadBatch::enc. */ + const RadBatch* build_encoder(const std::vector& parts, int step, + const RadEncoderDecl& enc); bool has_encoder() const { return mm_on_; } - int64_t encoder_patches() const { return enc_patches_; } private: @@ -366,9 +368,10 @@ private: uint16_t* mm_host_ = nullptr; RadEvent mm_ev_ = nullptr; bool mm_ev_live_ = false; - /* ...and the encoder's inputs: patches, their coordinates and the segment boundaries, the - * largest pass the plugin declared. One copy a rank, since each runs the tower itself. */ - int64_t enc_patches_ = 0, enc_dim_ = 0, enc_segs_ = 0; + /* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized + * for the larger of the passes the plugin declared (a vision tower's and an audio encoder's + * run one at a time and share it). One copy a rank, since each runs the tower itself. */ + int64_t enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0; std::vector enc_pix_dev_, enc_coord_dev_, enc_cu_dev_; uint16_t* enc_pix_host_ = nullptr; int32_t* enc_coord_host_ = nullptr; diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 9903d8f0..e49c3531 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -177,6 +177,9 @@ int Scheduler::add_locked(std::unique_ptr r) { if (!r) return RAD_E_INVAL; if (r->prompt.empty()) return RAD_E_INVAL; if (by_id_.count(r->id)) return RAD_E_DUPLICATE; + /* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a + * step could never be admitted and would wait for good. */ + if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL; /* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step * that is never coming, so the sink is failed here -- it is the one thing the caller is * listening to -- and the refusal says why. */ @@ -900,6 +903,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { int64_t target = s.seq_len(); int64_t ckpt = -1; int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt); + /* The whole input or nothing this step (Request::embed): the next step starts with a whole + * budget, and add_locked refused an input no budget holds. */ + if (r.embed && want < target - (int64_t)r.n_computed) want = 0; int rc = RAD_OK; if (want <= 0) rc = RAD_E_FULL; else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL; @@ -1600,7 +1606,11 @@ int Scheduler::commit(const StepResult& res) { * reports. `n_cached` is what the prefix cache supplied and is not recomputed here. */ if (r.n_computed >= (int64_t)r.prompt.size()) server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached); - if (e.produces_token && res.token) { + if (e.produces_token && res.token && r.embed) { + /* The answer is the pooled vector the engine already put in the sink; there is + * no token to emit, and `eos` ends the request below. */ + if (!s.first_tok_us) s.first_tok_us = mono_us(); + } else if (e.produces_token && res.token) { if (!s.first_tok_us) s.first_tok_us = mono_us(); r.output.push_back(res.token[i]); overflowed = !server::sink_push(r.sink, res.token[i]); diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 3842a1d8..087c93e6 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -301,11 +301,11 @@ public: bool encodes_pending() const; void take_encodes(std::vector>* out); /* An encoder pass over whole segments; see BatchBuilder::build_encoder. */ - const RadBatch* build_encoder(const std::vector& parts, int step) { + const RadBatch* build_encoder(const std::vector& parts, int step, + const RadEncoderDecl& enc) { std::lock_guard lk(mu_); - return builder_.build_encoder(parts, step); + return builder_.build_encoder(parts, step, enc); } - int64_t encoder_patches() const { return builder_.encoder_patches(); } /* Drop every prefix-cache entry, returning how many were dropped, or RAD_E_UNSUPPORTED when * this engine has no prefix cache. Under the step lock: releasing the cache's references is diff --git a/core/server/adapters.h b/core/server/adapters.h index ca2b51d0..96bd00ac 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -698,14 +698,17 @@ public: if (!p_ || !mm::decoder_available()) return false; if (k == MediaKind::Image) return (mod_ & RAD_MM_IMAGE) != 0; if (k == MediaKind::Video) return (mod_ & RAD_MM_VIDEO) != 0; + if (k == MediaKind::Audio) return (mod_ & RAD_MM_AUDIO) != 0 && p_->has_audio(); return false; } - int prepare(MediaKind k, const std::vector& bytes, std::shared_ptr* out, - std::string* why) override { + int prepare(MediaKind k, const std::vector& bytes, const MediaOpts& opts, + std::shared_ptr* out, std::string* why) override { if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; } - return k == MediaKind::Image ? p_->image(bytes.data(), bytes.size(), out, why) - : p_->video(bytes.data(), bytes.size(), out, why); + if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why); + return k == MediaKind::Image + ? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why) + : p_->video(bytes.data(), bytes.size(), out, why); } private: diff --git a/core/server/iface.h b/core/server/iface.h index 5245334b..1aae8d15 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -515,13 +515,32 @@ public: /* ================================================================== optional backends */ -/* /v1/embeddings. Absent, the endpoint is 501 naming that this model was not loaded with an - * embedding head -- not an empty 200. */ +/* /v1/embeddings: WHAT THE LOADED MODEL EMBEDS, present only when it is an embedding model + * (rad_declare_pooled). Absent, the endpoint is 501 naming that -- not an empty 200. + * + * The vectors themselves come through the scheduler like any other request: the server submits + * one Request a input with Request::embed set, and each finishes at its one step with its pooled + * vector in its sink (Sink::embedding). So batching, admission, media encoding and cancellation + * are the scheduler's, exactly as they are for a completion. */ class IEmbedder { public: virtual ~IEmbedder() = default; - virtual int embed(const std::vector& tokens, std::vector& out) = 0; + /* The width of a pooled vector. */ virtual int64_t dim() const = 0; + /* The longest input one step carries: an input is never split, so a longer one is refused. */ + virtual int64_t max_input() const = 0; + /* THE MODEL'S NAMED PROMPTS (sentence-transformers' `prompts`): the text a `prompt_name` puts + * in front of an input -- "query" -> "task: search result | query: ". False when the model + * states no prompt of that name. */ + virtual bool prompt(const std::string& name, std::string* text) const { + (void)name; (void)text; + return false; + } + /* The prompt an input takes when the request names none, "" for none. */ + virtual std::string default_prompt() const { return std::string(); } + /* The template a `messages` input renders through -- the model's chat template -- or null + * when it has none. */ + virtual IChatTemplate* message_template() const { return nullptr; } }; /* Multimodal preprocessing (spec §11). The server pulls the bytes out of a content part; the @@ -536,6 +555,13 @@ enum class MediaKind { Image, Video, Audio }; * the templates are the same templates. */ #define RAD_MEDIA_MARKER "<__media__>" +/* WHAT A REQUEST ASKED OF ITS MEDIA, beside the bytes. Zero is the server's default. */ +struct MediaOpts { + /* Soft tokens (encoder output rows) an image may become, for a processor that sizes images + * by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */ + int32_t image_tokens = 0; +}; + class IMultimodal { public: virtual ~IMultimodal() = default; @@ -543,7 +569,7 @@ public: /* Decode and process one part. `bytes` is the decoded file, not a URL: the server never * fetches a remote URL on a request's behalf. On success `*out` carries the patches and the * token run that replaces the marker; on failure `why` says what is wrong with the media. */ - virtual int prepare(MediaKind k, const std::vector& bytes, + virtual int prepare(MediaKind k, const std::vector& bytes, const MediaOpts& opts, std::shared_ptr* out, std::string* why) = 0; }; diff --git a/core/server/oai.cpp b/core/server/oai.cpp index bbae27d6..47e45a29 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -59,29 +60,48 @@ std::string base64_encode(const void* data, size_t len) { } bool base64_decode(const std::string& in, std::vector* out) { - auto val = [](char c) -> int { - if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '+') return 62; - if (c == '/') return 63; - return -1; - }; + /* One table lookup a character: 0..63 a digit, -2 padding or whitespace (skipped wherever it + * stands), -1 anything else. A media part is megabytes of this, and a branch ladder a + * character decoded a 30 s clip at about 120 MB/s. */ + static const auto kVal = [] { + std::array t{}; + t.fill(-1); + for (int i = 0; i < 26; ++i) { t[(size_t)('A' + i)] = (int8_t)i; t[(size_t)('a' + i)] = (int8_t)(26 + i); } + for (int i = 0; i < 10; ++i) t[(size_t)('0' + i)] = (int8_t)(52 + i); + t[(size_t)'+'] = 62; + t[(size_t)'/'] = 63; + for (char c : { '=', '\n', '\r', ' ', '\t' }) t[(size_t)(uint8_t)c] = -2; + return t; + }(); + out->resize(in.size() * 3 / 4 + 3); + uint8_t* o = out->data(); + const uint8_t* p = (const uint8_t*)in.data(); + const uint8_t* const end = p + in.size(); uint32_t acc = 0; int bits = 0; - out->clear(); - out->reserve(in.size() * 3 / 4); - for (char c : in) { - if (c == '=' || c == '\n' || c == '\r' || c == ' ' || c == '\t') continue; - int v = val(c); - if (v < 0) return false; + while (p < end) { + /* Four digits at once while they are four digits: the body of any real payload. */ + if (bits == 0 && end - p >= 4) { + const int a = kVal[p[0]], b = kVal[p[1]], c = kVal[p[2]], d = kVal[p[3]]; + if ((a | b | c | d) >= 0) { + const uint32_t v = ((uint32_t)a << 18) | ((uint32_t)b << 12) | ((uint32_t)c << 6) | (uint32_t)d; + o[0] = (uint8_t)(v >> 16); o[1] = (uint8_t)(v >> 8); o[2] = (uint8_t)v; + o += 3; + p += 4; + continue; + } + } + const int v = kVal[*p++]; + if (v == -2) continue; + if (v < 0) { out->clear(); return false; } /* nothing of a refused payload is left */ acc = (acc << 6) | (uint32_t)v; bits += 6; if (bits >= 8) { bits -= 8; - out->push_back((uint8_t)((acc >> bits) & 0xFF)); + *o++ = (uint8_t)((acc >> bits) & 0xFF); } } + out->resize((size_t)(o - out->data())); return true; } @@ -209,7 +229,8 @@ const char* kAcceptedChat[] = { const char* kAcceptedCompletion[] = { "prompt", "echo" }; -const char* kAcceptedEmbedding[] = { "model", "input", "encoding_format", "dimensions" }; +const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format", + "dimensions", "image_tokens", "prompt_name" }; /* Inert by definition in the OpenAI schema: routing and bookkeeping labels the server is free to * ignore. Named explicitly so that "we ignore it" is a decision in the source and not an @@ -945,6 +966,103 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro /* Rewrite content parts in place: text stays, media becomes the marker and its bytes are handed * to the encoder. `media` collects (kind, bytes) in the order they appear, which is the order the * markers appear in the rendered prompt. */ +/* ONE MEDIA CONTENT PART, read and decoded: 1 with `*kind` and `*bytes` set when `part` is an + * image, video or audio part, 0 when it is some other type (the caller's to judge), negative with + * `*err` set when it is a media part that cannot be served. `field` prefixes the error's field + * name -- "messages[].content[]" for chat, "input[]" for embeddings. + * + * IMAGE AND VIDEO PARTS, in the two spellings clients send: OpenAI's + * {"type":"image_url","image_url":{"url":...}} (and the bare-string form), the Responses API's + * "input_image", and the video equivalents vLLM's clients use -- {"type":"video_url", + * "video_url":{"url":...}} and "input_video". AUDIO is OpenAI's {"type":"input_audio", + * "input_audio":{"data": base64, "format": "wav"|"mp3"}} -- and the other formats the decoder + * admits by the same spelling -- or vLLM's {"type":"audio_url","audio_url":{"url": data URL}}. */ +static int read_media_part(const json& part, const std::string& type, const std::string& field, + const OaiDeps& d, const OaiLimits& lim, MediaKind* kind, + std::vector* bytes, ApiError* err) { + const bool is_image = type == "image_url" || type == "input_image"; + const bool is_video = type == "video_url" || type == "input_video"; + if (is_image || is_video) { + *kind = is_image ? MediaKind::Image : MediaKind::Video; + const char* what = is_image ? "image" : "video"; + const bool allowed = is_image ? lim.allow_image : lim.allow_video; + if (!allowed || !d.mm || !d.mm->accepts(*kind)) { + *err = err_not_implemented( + std::string(what) + " input requires a vision encoder (spec 11); this " + "model was loaded without one"); + return RAD_E_UNSUPPORTED; + } + const std::string key = is_image ? "image_url" : "video_url"; + const std::string fld = field + "." + key; + std::string url; + auto iu = part.find(key); + if (iu == part.end() && type == "input_image") iu = part.find("image_url"); + if (iu == part.end() && type == "input_video") iu = part.find("video_url"); + if (iu != part.end() && iu->is_object() && iu->contains("url") && + iu->at("url").is_string()) + url = iu->at("url").get(); + else if (iu != part.end() && iu->is_string()) + url = iu->get(); + else { + *err = err_bad(fld, "expected {\"url\": ...}"); + return RAD_E_INVAL; + } + RAD_TRY(decode_media_url(url, fld + ".url", bytes, err)); + return 1; + } + if (type == "input_audio" || type == "audio_url") { + *kind = MediaKind::Audio; + if (!lim.allow_audio || !d.mm || !d.mm->accepts(MediaKind::Audio)) { + *err = err_not_implemented( + "audio input requires an audio encoder (spec 11); this model was loaded " + "without one"); + return RAD_E_UNSUPPORTED; + } + if (type == "audio_url") { + const std::string fld = field + ".audio_url"; + auto au = part.find("audio_url"); + std::string url; + if (au != part.end() && au->is_object() && au->contains("url") && + au->at("url").is_string()) + url = au->at("url").get(); + else if (au != part.end() && au->is_string()) + url = au->get(); + else { + *err = err_bad(fld, "expected {\"url\": ...}"); + return RAD_E_INVAL; + } + RAD_TRY(decode_media_url(url, fld + ".url", bytes, err)); + return 1; + } + auto ia = part.find("input_audio"); + if (ia == part.end() || !ia->is_object() || !ia->contains("data") || + !ia->at("data").is_string()) { + *err = err_bad(field + ".input_audio", "expected {\"data\": ..., \"format\": ...}"); + return RAD_E_INVAL; + } + auto fit = ia->find("format"); + const std::string fmt = + fit != ia->end() && fit->is_string() ? fit->get() : std::string(); + /* The decoder recognises the container by its bytes; the format is checked against + * what it admits so a typo is named here rather than as an undecodable clip. */ + static const char* const kAudioFormats[] = { "wav", "mp3", "flac", "ogg", "opus", + "m4a", "aac", "webm", "aiff" }; + bool known = false; + for (const char* f : kAudioFormats) known = known || fmt == f; + if (!known) { + *err = err_bad(field + ".input_audio.format", + "must be one of wav, mp3, flac, ogg, opus, m4a, aac, webm, aiff"); + return RAD_E_INVAL; + } + if (!base64_decode(ia->at("data").get(), bytes)) { + *err = err_bad(field + ".input_audio.data", "invalid base64"); + return RAD_E_INVAL; + } + return 1; + } + return 0; +} + static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits& lim, std::vector>>* media, ApiError* err) { @@ -997,82 +1115,28 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits } continue; } - /* IMAGE AND VIDEO PARTS, in the two spellings clients send: OpenAI's - * {"type":"image_url","image_url":{"url":...}} (and the bare-string form), the - * Responses API's "input_image", and the video equivalents vLLM's clients use -- - * {"type":"video_url","video_url":{"url":...}} and "input_video". */ - const bool is_image = type == "image_url" || type == "input_image"; - const bool is_video = type == "video_url" || type == "input_video"; - if (is_image || is_video) { - const MediaKind kind = is_image ? MediaKind::Image : MediaKind::Video; - const char* what = is_image ? "image" : "video"; - const bool allowed = is_image ? lim.allow_image : lim.allow_video; - if (!allowed || !d.mm || !d.mm->accepts(kind)) { - *err = err_not_implemented( - std::string(what) + " input requires a vision encoder (spec 11); this " - "model was loaded without one"); - return RAD_E_UNSUPPORTED; - } - const std::string key = is_image ? "image_url" : "video_url"; - const std::string field = "messages[].content[]." + key; - std::string url; - auto iu = part.find(key); - if (iu == part.end() && type == "input_image") iu = part.find("image_url"); - if (iu == part.end() && type == "input_video") iu = part.find("video_url"); - if (iu != part.end() && iu->is_object() && iu->contains("url") && - iu->at("url").is_string()) - url = iu->at("url").get(); - else if (iu != part.end() && iu->is_string()) - url = iu->get(); - else { - *err = err_bad(field, "expected {\"url\": ...}"); - return RAD_E_INVAL; - } + /* IMAGE, VIDEO AND AUDIO PARTS (read_media_part). A MEDIA MARKER, NOT TEXT, takes the + * part's place: the chat layer flattens a message's parts into one string and joins + * TEXT parts with a newline; it joins a marker to its neighbours with nothing, which + * is what the model's own template does with an image part (<|vision_end|> runs + * straight into the text after it). Joined as text, every picture would cost one + * '\n' token the model's own prompt does not have. */ + { + MediaKind kind; std::vector bytes; - RAD_TRY(decode_media_url(url, field + ".url", &bytes, err)); - media->emplace_back(kind, std::move(bytes)); - /* A MEDIA MARKER, NOT TEXT. The chat layer flattens a message's parts into one - * string and joins TEXT parts with a newline; it joins a marker to its neighbours - * with nothing, which is what the model's own template does with an image part - * (<|vision_end|> runs straight into the text after it). Joined as text, every - * picture would cost one '\n' token the model's own prompt does not have. */ - part.erase(key); - part["type"] = "media_marker"; - part["text"] = MEDIA_MARKER; - continue; - } - if (type == "input_audio") { - if (!lim.allow_audio || !d.mm || !d.mm->accepts(MediaKind::Audio)) { - *err = err_not_implemented( - "audio input requires an audio encoder (spec 11); this model was loaded " - "without one"); - return RAD_E_UNSUPPORTED; + const int mr = read_media_part(part, type, "messages[].content[]", d, lim, &kind, + &bytes, err); + if (mr < 0) return mr; + if (mr > 0) { + media->emplace_back(kind, std::move(bytes)); + part.erase(type == "input_audio" ? "input_audio" + : type == "audio_url" ? "audio_url" + : (type == "image_url" || type == "input_image") ? "image_url" + : "video_url"); + part["type"] = "media_marker"; + part["text"] = MEDIA_MARKER; + continue; } - auto ia = part.find("input_audio"); - if (ia == part.end() || !ia->is_object() || !ia->contains("data") || - !ia->at("data").is_string()) { - *err = err_bad("messages[].content[].input_audio", - "expected {\"data\": ..., \"format\": ...}"); - return RAD_E_INVAL; - } - auto fit = ia->find("format"); - const std::string fmt = - fit != ia->end() && fit->is_string() ? fit->get() : std::string(); - if (fmt != "wav" && fmt != "mp3") { - *err = err_bad("messages[].content[].input_audio.format", - "must be \"wav\" or \"mp3\""); - return RAD_E_INVAL; - } - std::vector bytes; - if (!base64_decode(ia->at("data").get(), &bytes)) { - *err = err_bad("messages[].content[].input_audio.data", "invalid base64"); - return RAD_E_INVAL; - } - media->emplace_back(MediaKind::Audio, std::move(bytes)); - part.erase("input_audio"); - part["type"] = "media_marker"; - part["text"] = MEDIA_MARKER; - continue; } *err = err_bad("messages[].content[].type", "unsupported content part type \"" + type + "\""); @@ -1093,7 +1157,7 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits * scheduler's thread, where every other request's step would wait on it. */ static int tokenize_with_media(const std::string& rendered, const OaiDeps& d, std::vector>>& media, - PromptInput* out, ApiError* err) { + const MediaOpts& opts, PromptInput* out, ApiError* err) { out->text = rendered; auto pm = std::make_shared(); const std::string marker = MEDIA_MARKER; @@ -1117,7 +1181,7 @@ static int tokenize_with_media(const std::string& rendered, const OaiDeps& d, } std::shared_ptr item; std::string why; - const int s = d.mm->prepare(media[mi].first, media[mi].second, &item, &why); + const int s = d.mm->prepare(media[mi].first, media[mi].second, opts, &item, &why); if (s < 0 || !item) { *err = err_bad("messages[].content[]", "the media could not be used: " + (why.empty() ? std::string(rad_strerror(s)) @@ -1536,7 +1600,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true); p.text = rendered; } else { - RAD_TRY(tokenize_with_media(rendered, d, media, &p, err)); + RAD_TRY(tokenize_with_media(rendered, d, media, MediaOpts{}, &p, err)); } if (p.tokens.empty()) { *err = err_bad("messages", "the rendered prompt tokenised to nothing"); @@ -1702,16 +1766,109 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa out->base64_embeddings = (enc == "base64"); if (b.contains("dimensions") && !b.at("dimensions").is_null()) { - *err = err_unsupported("dimensions", - "Matryoshka truncation is not implemented; the model's embedding " - "dimension is fixed"); - return RAD_E_UNSUPPORTED; + const json& dv = b.at("dimensions"); + if (!dv.is_number_integer() || dv.get() <= 0) { + *err = err_bad("dimensions", "must be a positive integer"); + return RAD_E_INVAL; + } + /* Bounded by the model's width in the handler, which knows it. */ + out->dimensions = dv.get(); + } + /* A soft-token budget for this request's images (Gemma 4's processor); the processor refuses + * it on a model that sizes images otherwise. */ + if (b.contains("image_tokens") && !b.at("image_tokens").is_null()) { + const json& iv = b.at("image_tokens"); + const int64_t n = iv.is_number_integer() ? iv.get() : 0; + if (n != 70 && n != 140 && n != 280 && n != 560 && n != 1120) { + *err = err_bad("image_tokens", "must be one of 70, 140, 280, 560, 1120"); + return RAD_E_INVAL; + } + out->image_tokens = (int32_t)n; + } + + /* THE NAMED PROMPT: sentence-transformers' `prompt_name`, the model's own text in front of + * each text or content-part input. A model that states a default prompt applies it to a + * request that names none, as its reference library does. */ + std::string prefix; + const bool prompt_named = b.contains("prompt_name") && !b.at("prompt_name").is_null(); + { + std::string pname; + const bool named = prompt_named; + if (named) { + if (!b.at("prompt_name").is_string()) { + *err = err_bad("prompt_name", "expected a string"); + return RAD_E_INVAL; + } + pname = b.at("prompt_name").get(); + } else if (d.embed) { + pname = d.embed->default_prompt(); + } + if (!pname.empty() && (!d.embed || !d.embed->prompt(pname, &prefix))) { + *err = err_bad("prompt_name", "this model states no prompt named \"" + pname + "\""); + return RAD_E_INVAL; + } + } + + /* THE MESSAGES FORM, vLLM's chat embedding: one input rendered through the model's own chat + * template (EmbeddingGemma 2's concatenates the system text and then every message's text and + * media placeholders), the tokenizer's special tokens around the whole as for an input. */ + if (b.contains("messages") && !b.at("messages").is_null()) { + if (b.contains("input") && !b.at("input").is_null()) { + *err = err_bad("messages", "a request takes `input` or `messages`, not both"); + return RAD_E_INVAL; + } + if (b.contains("prompt_name") && !b.at("prompt_name").is_null()) { + *err = err_bad("prompt_name", "a `messages` input is rendered by the chat template " + "and takes no prompt"); + return RAD_E_INVAL; + } + IChatTemplate* tpl = d.embed ? d.embed->message_template() : nullptr; + if (!tpl) { + *err = err_bad("messages", "this model has no chat template to render messages with"); + return RAD_E_INVAL; + } + json messages = b.at("messages"); + std::vector>> media; + RAD_TRY(lower_content_parts(messages, d, lim, &media, err)); + ChatRenderOptions opt; + opt.add_generation_prompt = false; + ChatRender render; + std::string why; + if (tpl->apply(messages, json::array(), opt, &render, &why) < 0 || render.prompt.empty()) { + *err = err_bad("messages", "the chat template did not render the messages" + + (why.empty() ? std::string() : ": " + why)); + return RAD_E_INVAL; + } + PromptInput p; + if (media.empty()) { + p.text = render.prompt; + p.tokens = d.tok->encode(render.prompt, true, /*parse_special=*/true); + } else { + MediaOpts mo; + mo.image_tokens = out->image_tokens; + RAD_TRY(tokenize_with_media(render.prompt, d, media, mo, &p, err)); + const ITokenizer::VocabInfo vi = d.tok->vocab_info(); + if (vi.add_bos && vi.bos >= 0) { + p.tokens.insert(p.tokens.begin(), vi.bos); + for (auto& pl : p.media->items) pl.tok += 1; + p.media->layout(); + } + if (vi.add_eos && vi.eos >= 0) p.tokens.push_back(vi.eos); + } + out->prompts.push_back(std::move(p)); + return RAD_OK; } auto it = b.find("input"); if (it == b.end() || it->is_null()) { *err = err_bad("input", "is required"); return RAD_E_INVAL; } auto push_ids = [&](const json& arr, ApiError* e) -> bool { + /* A prompt is text; token ids take none, and asking for one by name is refused rather + * than dropped. A model's default prompt applies to text inputs only. */ + if (prompt_named && !prefix.empty()) { + *e = err_bad("prompt_name", "a prompt is text and cannot go in front of token ids"); + return false; + } PromptInput p; for (const auto& v : arr) { if (!v.is_number_integer()) { @@ -1729,33 +1886,108 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa return true; }; + /* ONE INPUT OF CONTENT PARTS -- text, images, video, audio, in order -- the same parts a chat + * message carries, and one vector for the lot. The parts are joined with nothing between + * them and each media part becomes its processor's token run, which is what an embedding + * model's own template does (EmbeddingGemma 2's concatenates text and placeholders), and the + * tokenizer's own special tokens go around the whole: what HuggingFace's processor feeds the + * model. */ + auto push_parts = [&](const json& parts, ApiError* e) -> int { + std::vector>> media; + std::string rendered = prefix; + for (const auto& part : parts) { + if (!part.is_object()) { + *e = err_bad("input[]", "a content part must be an object"); + return RAD_E_INVAL; + } + auto tit = part.find("type"); + if (tit == part.end() || !tit->is_string()) { + *e = err_bad("input[].type", "expected a string"); + return RAD_E_INVAL; + } + const std::string type = tit->get(); + if (type == "text") { + if (!part.contains("text") || !part.at("text").is_string()) { + *e = err_bad("input[].text", "expected a string"); + return RAD_E_INVAL; + } + const std::string t = part.at("text").get(); + /* The marker is how a media part's position survives into tokenisation, so text + * that spells it would be taken for one. */ + if (t.find(MEDIA_MARKER) != std::string::npos) { + *e = err_bad("input[].text", std::string("contains \"") + MEDIA_MARKER + + "\", which this server reserves for media"); + return RAD_E_INVAL; + } + rendered += t; + continue; + } + MediaKind kind; + std::vector bytes; + const int mr = read_media_part(part, type, "input[]", d, lim, &kind, &bytes, e); + if (mr < 0) return mr; + if (mr == 0) { + *e = err_bad("input[].type", "unsupported content part type \"" + type + "\""); + return RAD_E_INVAL; + } + media.emplace_back(kind, std::move(bytes)); + rendered += MEDIA_MARKER; + } + PromptInput p; + if (media.empty()) { + p.text = rendered; + p.tokens = d.tok->encode(rendered, true, /*parse_special=*/true); + } else { + MediaOpts mo; + mo.image_tokens = out->image_tokens; + RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, e)); + /* tokenize_with_media adds no special tokens (a chat template renders its own); + * this input has no template, so the tokenizer's own rule applies around it. */ + const ITokenizer::VocabInfo vi = d.tok->vocab_info(); + if (vi.add_bos && vi.bos >= 0) { + p.tokens.insert(p.tokens.begin(), vi.bos); + for (auto& pl : p.media->items) pl.tok += 1; + p.media->layout(); + } + if (vi.add_eos && vi.eos >= 0) p.tokens.push_back(vi.eos); + } + out->prompts.push_back(std::move(p)); + return RAD_OK; + }; + auto is_parts = [](const json& a) { return a.is_array() && !a.empty() && a.front().is_object(); }; + /* Parsed like a /v1/completions prompt, and for the same reason: the input is the client's * own text with no template around it. */ if (it->is_string()) { PromptInput p; - p.text = it->get(); + p.text = prefix + it->get(); p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true); out->prompts.push_back(std::move(p)); } else if (it->is_array()) { if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; } - if (it->front().is_string()) { - for (const auto& s : *it) { - if (!s.is_string()) { *err = err_bad("input", "expected all strings"); return RAD_E_INVAL; } - PromptInput p; - p.text = s.get(); - p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true); - out->prompts.push_back(std::move(p)); - } - } else if (it->front().is_number_integer()) { + if (it->front().is_number_integer()) { if (!push_ids(*it, err)) return RAD_E_INVAL; - } else if (it->front().is_array()) { - for (const auto& a : *it) { - if (!a.is_array()) { *err = err_bad("input", "expected arrays"); return RAD_E_INVAL; } - if (!push_ids(a, err)) return RAD_E_INVAL; - } + } else if (is_parts(*it)) { + RAD_TRY(push_parts(*it, err)); } else { - *err = err_bad("input", "expected a string, an array of strings, or token ids"); - return RAD_E_INVAL; + /* A BATCH: each element its own input -- a string, a token array or an array of + * content parts. */ + for (const auto& el : *it) { + if (el.is_string()) { + PromptInput p; + p.text = prefix + el.get(); + p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true); + out->prompts.push_back(std::move(p)); + } else if (is_parts(el)) { + RAD_TRY(push_parts(el, err)); + } else if (el.is_array()) { + if (!push_ids(el, err)) return RAD_E_INVAL; + } else { + *err = err_bad("input", "expected strings, token arrays or arrays of content " + "parts"); + return RAD_E_INVAL; + } + } } } else { *err = err_bad("input", "expected a string or an array"); diff --git a/core/server/oai.h b/core/server/oai.h index e75e2b6f..a5c52e7d 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -114,6 +114,11 @@ struct OaiRequest { /* /v1/embeddings */ bool base64_embeddings = false; + /* OpenAI's `dimensions`: the vector's first `dimensions` components, renormalised -- a + * Matryoshka-trained model's shorter embedding. 0 is the model's own width. */ + int64_t dimensions = 0; + /* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */ + int32_t image_tokens = 0; int n_choices() const { return (int)prompts.size() * n; } }; @@ -239,6 +244,7 @@ struct OaiDeps { IChatTemplate* chat = nullptr; IGrammarCompiler* grammar = nullptr; IMultimodal* mm = nullptr; + IEmbedder* embed = nullptr; }; /* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */ diff --git a/core/server/server.cpp b/core/server/server.cpp index 416384c6..d2895546 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -76,6 +77,7 @@ Server::Server(const Deps& d, const ServerOptions& o) odeps_.chat = deps_.chat; odeps_.grammar = deps_.grammar; odeps_.mm = deps_.mm; + odeps_.embed = deps_.embed; queue_depth_ = opt_.queue_depth > 0 ? opt_.queue_depth : opt_.max_seqs * 8; started_at_ = unix_now(); @@ -956,6 +958,10 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) HttpResponse Server::handle_chat(const HttpRequest& req) { if (!deps_.sched || !deps_.tok) return error_response(err_not_implemented("the server has no engine attached"), req.peer); + if (opt_.embedding_model) + return error_response(err_not_implemented("this is an embedding model: it serves " + "/v1/embeddings and generates no text"), + req.peer); OaiRequest r; ApiError err; @@ -977,6 +983,10 @@ HttpResponse Server::handle_chat(const HttpRequest& req) { HttpResponse Server::handle_completion(const HttpRequest& req) { if (!deps_.sched || !deps_.tok) return error_response(err_not_implemented("the server has no engine attached"), req.peer); + if (opt_.embedding_model) + return error_response(err_not_implemented("this is an embedding model: it serves " + "/v1/embeddings and generates no text"), + req.peer); OaiRequest r; ApiError err; @@ -996,35 +1006,138 @@ HttpResponse Server::handle_completion(const HttpRequest& req) { } HttpResponse Server::handle_embeddings(const HttpRequest& req) { - if (!deps_.tok) - return error_response(err_not_implemented("the server has no tokenizer attached"), + if (!deps_.sched || !deps_.tok) + return error_response(err_not_implemented("the server has no engine attached"), req.peer); if (!deps_.embed) return error_response(err_not_implemented( - "/v1/embeddings requires an embedding head; this model was not loaded with one"), - req.peer); + "/v1/embeddings requires an embedding model; this one generates text"), req.peer); OaiRequest r; ApiError err; if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err, req.peer); + r.peer = req.peer; - std::vector> vecs; - UsageOut u; - vecs.reserve(r.prompts.size()); - for (const auto& p : r.prompts) { - std::vector v; - int s = deps_.embed->embed(p.tokens, v); - if (s < 0) { + const int64_t dim = deps_.embed->dim(); + if (r.dimensions > dim) + return error_response(err_bad("dimensions", "this model's vectors are " + + std::to_string(dim) + " wide"), req.peer); + /* AN INPUT IS NEVER SPLIT (Request::embed), so one longer than a step is refused here, with + * the number, rather than by the scheduler with none. */ + for (size_t i = 0; i < r.prompts.size(); ++i) { + const int64_t n = (int64_t)r.prompts[i].tokens.size(); + if (n > deps_.embed->max_input()) { + ApiError e = err_bad("input", "input " + std::to_string(i) + " is " + + std::to_string(n) + " tokens; this deployment " + "embeds at most " + + std::to_string(deps_.embed->max_input()) + + " (--max-num-batched-tokens)"); + e.code = "context_length_exceeded"; + return error_response(e, req.peer); + } + } + + sweep_abandoned(); + const int n_in = (int)r.prompts.size(); + if (!admit(n_in)) { + metrics_.observe_rejected(); + return error_response(err_overloaded( + "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) + + "s. The server refuses rather than queueing without bound"), req.peer); + } + log_admitted(r); + + /* EVERY INPUT AT ONCE, so the scheduler can put them in one step. */ + std::vector gens; + std::vector rqs; + gens.reserve((size_t)n_in); + rqs.reserve((size_t)n_in); + for (int i = 0; i < n_in; ++i) { + Generation g; + g.index = i; + g.prompt_index = i; + g.sink = std::make_shared(16); + Request rq; + rq.prompt = r.prompts[(size_t)i].tokens; + rq.media = r.prompts[(size_t)i].media; + rq.embed = true; + rq.max_tokens = 1; + rq.sp.temp = 0.0f; + rq.sink = g.sink.get(); + rqs.push_back(std::move(rq)); + gens.push_back(std::move(g)); + } + std::vector ids; + deps_.sched->submit_all(rqs, &ids); + for (size_t i = 0; i < ids.size(); ++i) { + gens[i].id = ids[i]; + gens[i].sink->id = ids[i]; + if (!ids[i]) { + retire(gens); + release(n_in); ApiError e; e.status = 500; e.type = "internal_server_error"; - e.message = std::string("the embedding pass failed: ") + rad_strerror(s); + e.message = "the scheduler refused input " + std::to_string(i); return error_response(e, req.peer); } - u.prompt += (int64_t)p.tokens.size(); - vecs.push_back(std::move(v)); } + + for (;;) { + bool all = true; + for (auto& g : gens) { + if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); } + all = all && g.closed; + } + if (all) break; + if (req.peer_gone()) { + cancel_all(gens, true); + retire(gens); + release(n_in); + metrics_.observe_http(499); + return HttpResponse::text(499, "client closed request\n"); + } + if (stopping_.load()) { + cancel_all(gens, false); + retire(gens); + release(n_in); + return error_response(err_overloaded("the server is shutting down"), req.peer); + } + for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; } + } + + /* THE VECTORS, truncated to `dimensions` and L2-normalised: what OpenAI's endpoint returns and + * what a sentence-transformers model's Normalize module does. Truncating a unit vector does + * not keep it unit, so the normalisation comes after. */ + std::vector> vecs; + vecs.reserve((size_t)n_in); + UsageOut u; + const int64_t keep = r.dimensions > 0 ? r.dimensions : dim; + for (auto& g : gens) { + const std::vector& v = g.sink->embedding(); + if (g.finish == Finish::Error || g.finish == Finish::Cancelled || (int64_t)v.size() != dim) { + const std::string why = g.finish == Finish::Error ? engine_failure(*g.sink) + : std::string("the engine returned no vector for input ") + + std::to_string(g.index); + retire(gens); + release(n_in); + ApiError e; + e.status = 500; + e.type = "internal_server_error"; + e.message = why; + return error_response(e, req.peer); + } + std::vector out(v.begin(), v.begin() + keep); + double ss = 0.0; + for (float x : out) ss += (double)x * x; + const float inv = ss > 0.0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f; + for (float& x : out) x *= inv; + u.prompt += (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size(); + vecs.push_back(std::move(out)); + } + retire(gens); + release(n_in); metrics_.observe_http(200); return HttpResponse::json_body(200, embeddings_body(r, vecs, u)); } diff --git a/core/server/server.h b/core/server/server.h index f73c0dd3..782dd10b 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -53,6 +53,10 @@ struct Deps { struct ServerOptions { std::string model_id = "radiance"; + /* AN EMBEDDING MODEL (rad_declare_pooled) GENERATES NOTHING: /v1/chat/completions and + * /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine + * would finish after one step with no text. */ + bool embedding_model = false; std::string host = "0.0.0.0"; int port = 8000; int n_threads = 0; diff --git a/core/server/sink.h b/core/server/sink.h index a702d0c4..15cd5b35 100644 --- a/core/server/sink.h +++ b/core/server/sink.h @@ -142,6 +142,13 @@ public: /* The engine's request id, so a dropped connection can reach IScheduler::cancel. */ uint64_t id = 0; + /* AN EMBEDDING REQUEST'S ANSWER: the pooled vector, written once by the engine before the + * step's commit finishes the request, and read by the consumer only after done(). finish() + * publishes with a release store and done() reads with an acquire load, so the vector is + * visible to anyone who has seen the request finish. Empty for every generating request. */ + void set_embedding(const float* v, int64_t n) { embd_.assign(v, v + n); } + const std::vector& embedding() const { return embd_; } + private: void notify(); @@ -168,6 +175,7 @@ private: std::atomic n_prompt_{0}; std::atomic n_cached_{0}; bool has_logprobs_ = false; + std::vector embd_; std::mutex m_; std::condition_variable cv_; @@ -196,6 +204,9 @@ inline void sink_admitted(void* s) { inline void sink_drafts(void* s, int32_t n, int32_t accepted) { if (s) static_cast(s)->add_drafts(n, accepted); } +inline void sink_embedding(void* s, const float* v, int64_t n) { + if (s) static_cast(s)->set_embedding(v, n); +} } /* namespace server */ } /* namespace rad */ diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index 027518b0..f308288e 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -496,8 +496,9 @@ void read_config_json(const std::string& dir, VocabBuild& out) { out.unk = out.unk >= 0 ? out.unk : token_id("unk_token"); out.sep = token_id("sep_token"); out.eot = out.eos; - out.add_bos = bool_or(c, "add_bos_token", false); - out.add_eos = bool_or(c, "add_eos_token", false); + /* The default is what tokenizer.json's post-processor already said (interpret_tokenizer_json). */ + out.add_bos = bool_or(c, "add_bos_token", out.add_bos); + out.add_eos = bool_or(c, "add_eos_token", out.add_eos); const json* ct = get(c, "chat_template"); if (ct && ct->is_string()) out.chat_template = ct->get(); @@ -573,6 +574,25 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi if (const json* a = get(j, "added_tokens")) RAD_TRY(read_added(*a, out, origin, id_limit)); + /* WHAT `add_special_tokens` ADDS, when the file says it in its post-processor rather than in + * tokenizer_config.json. HuggingFace's encode runs the post-processor, so a TemplateProcessing + * whose single-sequence template is ` $A ` IS the model's add-BOS-and-EOS rule -- + * Gemma states it there and nowhere else, and an embedding model fed its input without the + * it was trained to pool over computes a different vector. Only the two shapes that map + * onto add_bos / add_eos are read: one special token before the sequence, one after. The + * config's own add_bos_token / add_eos_token, read later, win where present. */ + if (const json* pp = get(j, "post_processor")) { + if (str_or(*pp, "type", "") == "TemplateProcessing") { + const json* single = get(*pp, "single"); + if (single && single->is_array() && !single->empty()) { + auto special = [](const json& e) -> bool { return e.is_object() && e.contains("SpecialToken"); }; + const bool seq_in_middle = single->size() >= 2; + if (special(single->front()) && seq_in_middle) out.add_bos = true; + if (special(single->back()) && seq_in_middle) out.add_eos = true; + } + } + } + if (pre.empty() && out.kind == RAD_TOK_BPE) { RAD_ERR("%s: a BPE model with no pre_tokenizer would tokenise the whole prompt as one " "word. Refusing.", origin); diff --git a/deploy/compose/.env.example b/deploy/compose/.env.example index 81525f84..d8f688db 100644 --- a/deploy/compose/.env.example +++ b/deploy/compose/.env.example @@ -22,3 +22,6 @@ RADIANCE_UID=1000 RADIANCE_GID=1000 RENDER_GID= VIDEO_GID= + +# The card a one-card model runs on (embeddinggemma2.yaml), by index. +RADIANCE_GPU=0 diff --git a/deploy/compose/embeddinggemma2.yaml b/deploy/compose/embeddinggemma2.yaml new file mode 100644 index 00000000..e922ac4b --- /dev/null +++ b/deploy/compose/embeddinggemma2.yaml @@ -0,0 +1,15 @@ +# EmbeddingGemma 2 (google/embeddinggemma-2) in bf16 as the checkpoint ships it: one vector a text, +# image, video, audio clip or any mix of them, on /v1/embeddings. The model is small (a 270M text +# model and its two towers) and runs on one card, RADIANCE_GPU in .env (default 0). An input is one +# step, so --max-num-batched-tokens is the longest input as well as the batch. +name: radiance-embeddinggemma2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-embeddinggemma2 + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/embeddinggemma2-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 64 --max-num-batched-tokens 8192 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index f293a544..cbd4186d 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -13,6 +13,7 @@ into the id an architecture plugin claims. | `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations | | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | +| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | This document is the geometry of each, and the handful of readings that are **arithmetically silent** — wrong in a way that produces fluent output and no error anywhere. @@ -395,3 +396,53 @@ N = 160 — wide enough that formats which differ by less than that rank in any graded statistic that has thousands of samples rather than hundreds (the mean |delta| over the logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at N ≥ 160 before acting on it. + +--- + +# `embeddinggemma2` — an embedding model + +`arch/embgemma2` declares a POOLED output (`rad_declare_pooled`) and no logits, which makes the +program an embedding program: the engine runs it with no sampler and no KV cache, carries every +input whole in one step, and returns each sequence's pooled row on `/v1/embeddings` +([GUIDE §5.6](GUIDE.md)). One card (`--tp 1`). + +``` +text 24 layers, hidden 512, ffn 2048 (gelu-tanh, gated), vocab 262144 + layer_types: five sliding (|i-j| <= 512, 4 x 256, 2 kv heads, theta 1e4) then one full + (4 x 512, 1 kv head, theta 1e6), four times; BIDIRECTIONAL everywhere, scale 1 + q, k RMS-normed with a gain, v without; sandwich norms with plain gains + per-layer inputs: the embedding projected to 24 x 512 and normed, gating a 512 bottleneck + a learned scalar a layer on the residual; mean over every token, then 512 -> 768 +vision Gemma 4's: 16 layers of 768 (12 x 64), a learned row/column table, a two-block 2-D rotary + (x on the first half of a head, y on the second, theta 100), 3 x 3 mean pooling * sqrt(768), + an unscaled RMS norm and 768 -> 512; up to 280 soft tokens an image by default +audio Gemma 4's USM conformer: two stride-2 3 x 3 convolutions over (time, mel), 12 blocks + (half-weight feed-forwards, local attention 11 back with a relative-position term and a + softcap of 50, a gated depthwise causal convolution), clipped linears; 1024 -> 1536 -> + embedder -> 512; 4 frames (40 ms) a token, clips cut at 30 s +``` + +The traps: + +- **The embedding scale is the bf16 of sqrt(512)**, 22.625, because the reference stores it as a + bf16 buffer. sqrt(512) itself is off by one part in 800 on every embedding. +- **A media row replaces its placeholder's embedding before the per-layer inputs are projected.** + The per-layer input of an image token is computed from its image row, not from the placeholder + id's embedding. +- **The vision rotary is two independent neox rotaries**, one over each half of a head (`qk_norm_rope` + mode `blocks`). `rope` mode `axial` pairs across the halves and is a different function. +- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`), and + the processor lays each 3 x 3 window's patches out consecutively so the pooler is a mean of nine + consecutive rows; attention and both position terms read each patch's own coordinates. +- **The audio subsampler masks its input to the clip's real frames before each convolution**: the + second convolution reads the first one's output at frame 2t's validity (`conv2d`'s `valid` + operand, stride 2), which zeroes the one row past the real ones that the zero padding alone + would not. +- **The audio attention reaches 11 rows back, not 12.** The config says `attention_context_left` + 13 and the chunked layout fetches 12 keys behind each block, but the mask transformers applies + keeps a key only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent a block + and leaves rows at cosine 0.6 by the last one. +- **An audio clip's tokens are ceil(real frames / 4)**, real frames being those whose last sample + is a real one; the processor stages exactly those plus zero frames to whole rows, which + reproduces every row the reference keeps. + diff --git a/docs/GUIDE.md b/docs/GUIDE.md index feec5c6e..5d75d9fb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1096,7 +1096,8 @@ for a model that takes no images or video. | `--video-min-pixels N`, `--video-max-pixels N` | container's | the same for a video's sampled frames together | | `--video-fps F` | container's, else 2 | frames sampled per second of video | | `--video-min-frames N`, `--video-max-frames N` | container's, else 4 and 768 | the fewest and most frames sampled from a video | -| `--video-max-frame-tokens N` | container's, else 768 | the most prompt tokens one frame may become; 0 is no cap | +| `--video-max-frame-tokens N` | container's, else 768 | the most prompt tokens one frame may become; 0 is no cap. A token-budget processor (Gemma 4's) takes 70, 140, 280, 560 or 1120 | +| `--image-tokens N` | container's | a token-budget processor's image budget (Gemma 4's: 70, 140, 280, 560, 1120); a request's `image_tokens` overrides it. The pixel-band flags are refused on such a model | | `--max-source-pixels N` | 67108864 | the largest image or frame the decoder accepts, before any resize | **Quality measurement** — instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode) @@ -1304,6 +1305,45 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ `/tokenize` takes `prompt` **or** `messages`, not both. +**An embedding model** (EmbeddingGemma 2) serves `/v1/embeddings` and nothing else; completions and +chat answer 501. One input is one vector, and an input is never split: it has to fit one step +(`--max-num-batched-tokens`), and a longer one is refused with `context_length_exceeded`. + +```sh +# text, a batch of texts, or token ids +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"input":["first document","second document"]}' + +# the model's named prompt in front ("query" -> "task: search result | query: ") +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"input":"what is the capital of France?","prompt_name":"query"}' + +# Matryoshka: the first 256 dimensions, renormalised +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"input":"hello","dimensions":256}' + +# one vector for text and media together: content parts, in order +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"input":[{"type":"text","text":"a photo of "}, + {"type":"image_url","image_url":{"url":"data:image/png;base64,..."}}], + "image_tokens":560}' + +# or the chat form, rendered through the model's template +curl -s http://localhost:8000/v1/embeddings -H 'Content-Type: application/json' \ + -d '{"messages":[{"role":"user","content":[{"type":"input_audio", + "input_audio":{"data":"","format":"wav"}}]}]}' +``` + +`input` is a string, an array of token ids, one array of content parts, or a batch of any of +those. A content part is `text`, `image_url`, `video_url`, `input_audio` (wav, mp3, flac, ogg, +opus, m4a, aac, webm or aiff, base64) or `audio_url`; media comes as `data:` URLs, never fetched. +An image becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tokens`: 70, +140, 280, 560 or 1120), a video one frame a second, at most 32 frames of 140 tokens +(`--video-fps`, `--video-max-frames`, `--video-max-frame-tokens`), and audio 25 tokens a second, +cut at 30 seconds. `prompt_name` takes the names the model's sentence-transformers configuration +states (`query`, `document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part +inputs; a model that states a default prompt applies it when the request names none. + ### 5.7 Request fields | field | notes | @@ -1334,7 +1374,8 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ | `response_format` | chat only. Mutually exclusive with `grammar` | | `grammar` | a GBNF grammar directly. On chat it passes through the chat template and a template that drops it makes the request a refusal — see §5.5 | | `echo` | `/v1/completions` only | -| `encoding_format` | `/v1/embeddings` only: `float` or `base64`. `dimensions` is refused — the embedding width is fixed | +| `encoding_format` | `/v1/embeddings` only: `float` or `base64` | +| `dimensions`, `prompt_name`, `image_tokens` | `/v1/embeddings` only (an embedding model, §5.6). `dimensions` truncates to the first N and renormalises; it cannot exceed the model's width | Any field the request omits keeps the deployment default (§4.9). A field the request names wins. @@ -1604,6 +1645,7 @@ released until it does. | `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`; 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. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` | | `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 was seen to refuse any single pin above about 2.5 GiB; a piece failing 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 that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line | +| `a synchronisation has waited 5 s` naming a kernel, then `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 is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the engine warns at startup 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 puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended | | `--draft-model is not implemented` | This 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 at all | 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 | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` | diff --git a/docs/OPS.md b/docs/OPS.md index fcdc9969..22609f66 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -158,7 +158,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th | op | params | operands | |---|---|---| -| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `w`w → `y` | +| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) | | `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` | | `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` | | `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | @@ -168,6 +168,15 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th | `add` | `M`(range) `n` `dtype` | `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) | +| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) | +| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) | +| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) | +| `relu` | `M`(range) `n` `dtype` | `x` → `y` | +| `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` | `x`, `w`w, `cu_seqlens`, `valid`? → `y` | +| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` | +| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` | | `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` | | `cast` | `M`(range) `n` `from` `to` | `x` → `y` | | `softmax` | `M`(range) `n` `dtype` | `x` → `y` | @@ -224,6 +233,54 @@ attention-zero rank's block (`docs/TP3.md`) is one `fill` of its output wire bef A wire shared across layers cannot be zeroed once a step, and a memset knows neither the row pitch nor the dtype; this does. +**`mul_weight`** is a learned gain on an activation: `w` is a WEIGHT of one element, a scalar for +the whole output -- Gemma 4's per-layer `layer_scalar` on the residual stream -- or of one row, +broadcast down the rows (a per-channel layer scale). Its own op rather than a form of `mul` +because an operand is a weight or an activation by its schema, and `mul`'s `b` is an activation. +`scalar` 1 states the one-element form; kernels read the form off the operand, and the parameter +is what lets a shape description (rad-kbench's) build the right weight. + +**`act_mul`** is `silu_mul` with its two halves in two operands, so the multiplier can be any +tensor -- the two column slices of a fused `gate_up`, or a gate and a separate per-layer input +(EmbeddingGemma 2's per-layer-embedding block multiplies `gelu_tanh(gate(x))` by one). `act` is +`silu`, `gelu` (exact erf), `gelu_tanh` or `sigmoid` (a GLU's gate: `a` the gate half, `b` the +value half); the activation is rounded to `y`'s dtype before the product, which is what the +unfused pair stores. + +**`seg_mean`** is a sentence embedding's mean pooling over a ragged batch: row `s` of `y` is the +mean of `x`'s rows `[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token +count and bands the op; the segment count is `cu_seqlens`' length less one. An empty segment is a +zero row. + +**`pool_rows`** is a vision pooler over windows its processor laid out consecutively: row `r` of `y` +is the mean of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times +`mult` and rounded again (the unfused pair stores the mean). `M` is the input row count and a +multiple of `k`. + +**`rmsnorm`'s `mult`** scales the normed row before its one rounding: a residual branch weighted by +a constant -- Gemma 4's audio feed-forward adds half of its output -- with no second pass. For a +power of two it is exactly the reference's norm-then-scale, since scaling by one commutes with the +rounding. + +**The audio tower's operators** (Gemma 4's USM conformer): + +- **`relu`** is `max(x, 0)` at each operand's own row pitch. +- **`clamp`** is `min(max(x, lo), hi)` with `lo` and `hi` WEIGHTS of one element each -- a clipped + linear's input or output range, which the checkpoint states per projection. +- **`conv2d`** convolves over (time, width) with channels innermost: element `(t, w, c)` of `x` is + at row `t`, column `w * cin + c`, and `w` is PyTorch's `[cout, cin, kh, kw]`. Each `cu_seqlens` + segment -- rows `[cu[s] / cu_div, cu[s+1] / cu_div)` -- is convolved on its own with zero padding + `pad` at its edges on both axes, so two clips in one pass never see each other, and its output + rows start at `cu[s] / (cu_div * stride)` (a segment whose start does not divide is refused). + With the optional `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`: + the frame mask the subsampler multiplies in 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 the rows before the segment's start reading as zeros. +- **`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 torch expressions + are, then rounded. + ## Quantisation and rotation | op | params | operands | @@ -369,11 +426,22 @@ that folds dequantisation into its epilogue still receives them. | 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 | `q`, `k`, `v`, `cu_seqlens` → `out` | +| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/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 | `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 | `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 | `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 | + +**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a +softcap. Query row `i` of a segment sees the key rows `j` of the same segment with `0 <= i - j <= +left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)` -- softplus +rounded to `pds`'s dtype, as the reference evaluates it on the parameter -- and `logit = qf . k * +(ln(1 + e) / ln 2) + qf . relk[i - j]`, then `softcap * tanh(logit / softcap)`, a softmax over the +visible keys and the weighted sum of `v`, all in f32 and rounded once. `relk` is `[left + 1, +n_head * head_dim]`, row `d` the projected position for distance `d`. The reference computes this +in 12-query blocks over 24-key windows with a Transformer-XL shift; every key outside the window +carries a `-1e9` logit there, so the sliding form is the same function. `attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each @@ -388,11 +456,24 @@ row each — is what the scheduler builds whenever prefill and decode coexist, a satisfy the uniform form. `q_len` is then the batch MAXIMUM, which is what selects the band; the per-sequence lengths come from `cu_seqlens` alone. -`attn_dense` is the vision tower's: non-causal, nothing paged, `cu_seqlens` bounding one image per -entry so a whole batch is one launch. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or +`attn_dense` is the vision tower's and an encoder's: nothing paged, `cu_seqlens` bounding one +image 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 `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy. +**`qk_norm_rope`'s `v_norm`** set to 1 also RMS-norms every v head of the fused row with a UNIT +gain and does not rotate it: Gemma 4's value norm, which has no weight to name. + +**`qk_norm_rope`'s `blocks` mode** rotates each section as its own block of channels: section `c` +is `sections[c]` pairs over the next `2 * sections[c]` channels, paired `(start + j, start + +sections[c] + j)` -- NeoX inside the block -- and turned by position component `comps[c]` (default +`c`) at `theta^(-j / sections[c])`. The sections fill `rotary_dim` exactly and `positions` is +`[C, M]`. It is Gemma 4's vision rotary: x over the first half of each head and y over the second, +each half a complete rotary of its own; `mode` `axial` of `rope` pairs across the halves instead. + **`rope`'s multi-component modes.** `mrope`, `imrope` and `axial` rotate with NeoX pairing and let several position components drive different frequencies. `positions` is then `[C, M]`, component-major, and `sections` names how many of the `rotary_dim / 2` frequencies each component @@ -823,7 +904,7 @@ form exists, as for `ar_hc_write`. | op | params | operands | |---|---|---| -| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w → `x` | +| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt `mult`:f64/opt | `tokens`, `wte`w → `x` | | `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? | | `logits_gemm` | `M`(range) `n_vocab` `n_embd` `dtype` | `x`, `lm_head`w → `logits` | | `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? | @@ -880,6 +961,14 @@ bf16 would matter, because `libref` is the oracle for every op here and its bf16 float, which is not guaranteed to return a NaN payload unchanged. At u8 every value is 0..255, float carries it exactly, and oracle and kernel agree bit for bit on any payload at all. +### `embed_lookup`'s `mult` + +Every gathered row multiplied by `mult` and rounded once to `x`'s dtype; absent, the gather is a +plain copy. Gemma scales its embedding by `sqrt(hidden)` held in a bf16 buffer, so the plugin +passes that value rounded to bf16 (22.625 at a hidden of 512, not 22.6274) and the product is the +reference's to the bit. `wscale` is not this: it is the scale `embed_lookup_q`'s layout quantises +with, and `embed_lookup` reads none. + ### `embed_lookup`'s `vocab_offset` `vocab_offset` (optional, default 0) is the first vocabulary row this rank holds. With it, diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 2a2702b0..b772e576 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -54,6 +54,9 @@ */ #include "avx_vec.h" #include "avx_common.h" + +#include +#include #include "rad_yarn.h" using namespace avx; @@ -490,6 +493,282 @@ AVX_KERNEL(attn_paged) { return RAD_OK; } +/* ------------------------------------------------------------------ attn_dense, bf16 blocks */ +/* AN ENCODER'S ATTENTION IS ALL PREFILL, and the per-query loop below is built for a decode row: + * it parallelises over (segment, head) -- eight units for one long input on a sixteen-core part -- + * and widens every key row to f32 again for every query that reads it, so a 2000-token segment + * pays four million row conversions a head. Measured at 130 GFLOPS on the sliding layers. + * + * Where q, k and v are bf16 with unit element stride and the CPU has AVX512_BF16, this blocked + * form runs instead. A task is (segment, KV head, 32 query positions) and holds the rows of every + * query head that reads that KV head, so one key tile serves gqa x 32 rows. Per tile of 64 keys: + * + * S = Q K^T vdpbf16ps against the tile packed once as key-interleaved bf16 pairs, each + * query pair broadcast into 16-key vectors: no score is horizontally reduced + * the mask causal, window and segment end, on the scores + * the softmax online, the running max moved at tile boundaries (this file's arrangement) + * O += P V V's tile packed once for the task as key-interleaved bf16 pairs, P rounded to + * bf16 pairs along the keys (as PyTorch's CPU flash attention does), six rows of + * 64 output columns a block + * + * The key range of a task is cut to what its queries can see, so a sliding layer costs + * O(T * window). Each output row is one task's, so the result does not depend on the thread + * count. Same arithmetic class as the loop below: f32 scores (bf16 products are exact in f32), + * f32 softmax and accumulator, one rounding at the store. */ +#if AVX_LEVEL == 3 +#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) + +/* S[r][0..63] for MB_ query rows against a key tile packed as bf16 PAIRS INTERLEAVED BY KEY: + * kp[d2 * 64 + j] holds key j's dims 2*d2 and 2*d2+1. Each step broadcasts one row's pair and + * multiplies it into four 16-key vectors, so a score is never horizontally reduced -- with a + * 64-wide head a reduction per score cost more than the two products it closed. */ +template +AVX_BF16_TARGET static inline void qk_rows(const uint16_t* const* qr, const uint32_t* kp, + int64_t D2, float scale, float* S, int64_t ldS) { + __m512 acc[MB_][4]; + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) + #pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) acc[i][v] = _mm512_setzero_ps(); + for (int64_t d2 = 0; d2 < D2; ++d2) { + const uint32_t* kr = kp + d2 * 64; + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(kr)); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 16)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 32)); + const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 48)); + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) { + uint32_t pr; + std::memcpy(&pr, qr[i] + 2 * d2, 4); + const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pr); + acc[i][0] = _mm512_dpbf16_ps(acc[i][0], a, b0); + acc[i][1] = _mm512_dpbf16_ps(acc[i][1], a, b1); + acc[i][2] = _mm512_dpbf16_ps(acc[i][2], a, b2); + acc[i][3] = _mm512_dpbf16_ps(acc[i][3], a, b3); + } + } + const __m512 vs = _mm512_set1_ps(scale); + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) + #pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) _mm512_storeu_ps(S + i * ldS + 16 * v, _mm512_mul_ps(acc[i][v], vs)); +} + +/* acc[r][c0 .. c0+63] += P[r] . V for MB_ rows, in bf16 pairs: pp[r * 32 + k2] holds row r's + * probabilities for keys 2*k2 and 2*k2+1, vp[k2 * D + d] holds those two keys' values at column + * d. PyTorch's CPU flash attention -- the reference's -- rounds P to bf16 for this product as + * well; the softmax's sum is kept in f32 from the unrounded P. */ +template +AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t* pp, + const uint32_t* vp, int64_t K2, int64_t c0) { + __m512 o[MB_][4]; + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) + #pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) o[i][v] = _mm512_loadu_ps(acc + i * D + c0 + 16 * v); + for (int64_t k2 = 0; k2 < K2; ++k2) { + const uint32_t* vr = vp + k2 * D + c0; + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(vr)); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 16)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 32)); + const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 48)); + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) { + const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pp[i * 32 + k2]); + o[i][0] = _mm512_dpbf16_ps(o[i][0], a, b0); + o[i][1] = _mm512_dpbf16_ps(o[i][1], a, b1); + o[i][2] = _mm512_dpbf16_ps(o[i][2], a, b2); + o[i][3] = _mm512_dpbf16_ps(o[i][3], a, b3); + } + } + #pragma GCC unroll 8 + for (int i = 0; i < MB_; ++i) + #pragma GCC unroll 4 + for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]); +} + +AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* k, + const RadTensor* v, const RadTensor* cu, + const RadTensor* o, int64_t D, int64_t gqa, + int64_t kv_heads, int causal, int64_t window, + 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) { + static const bool have = __builtin_cpu_supports("avx512bf16"); + if (!have) return false; + if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return false; + if (q_ds != 1 || k_ds != 1 || v_ds != 1 || o_ds != 1 || D % 64 != 0 || gqa > 16) return false; + + constexpr int64_t QB = 32, KT = 64; + const int64_t n_seq = numel(cu) - 1; + /* The task list: (segment, kv head, query block), flattened through a prefix over segments. */ + std::vector first((size_t)n_seq + 1, 0); + for (int64_t s = 0; s < n_seq; ++s) { + const int64_t len = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s)); + first[(size_t)s + 1] = first[(size_t)s] + kv_heads * ((len + QB - 1) / QB); + } + const int64_t n_task = first[(size_t)n_seq]; + const uint16_t* Q = (const uint16_t*)q->data; + const uint16_t* K = (const uint16_t*)k->data; + const uint16_t* V = (const uint16_t*)v->data; + const int64_t R_MAX = QB * gqa; + +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) +#endif + for (int64_t t = 0; t < n_task; ++t) { + int64_t s = (int64_t)(std::upper_bound(first.begin(), first.end(), t) - first.begin()) - 1; + const int64_t b0 = ldi(cu, offlin(cu, s)), len = ldi(cu, offlin(cu, s + 1)) - b0; + const int64_t local = t - first[(size_t)s]; + const int64_t nqb = (len + QB - 1) / QB; + const int64_t kh = local / nqb, q0 = (local % nqb) * QB; + const int64_t q1 = std::min(q0 + QB, len), nq = q1 - q0, R = nq * gqa; + + float* frame = scratch_f32((size_t)(R_MAX * D + R_MAX * KT + 2 * R_MAX + KT * D / 2 + + KT * D / 2 + R_MAX * KT / 2) + 64); + float* acc = frame; + float* S = acc + R_MAX * D; + float* m = S + R_MAX * KT; + float* l = m + R_MAX; + uint32_t* kpack = reinterpret_cast(l + R_MAX); + uint32_t* vpack = kpack + KT * D / 2; + uint32_t* ppack = vpack + KT * D / 2; + const int64_t D2 = D / 2; + const uint16_t* qrow[16 * QB]; + for (int64_t r = 0; r < R; ++r) { + const int64_t qi = r / gqa, g = r % gqa; + qrow[r] = Q + (b0 + q0 + qi) * q_rs + (kh * gqa + g) * q_hs; + m[r] = -INFINITY; + l[r] = 0.0f; + } + std::memset(acc, 0, sizeof(float) * (size_t)(R * D)); + + 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); + } + for (int64_t j0 = jbeg; j0 < jend; j0 += KT) { + const int64_t kt = std::min(KT, jend - j0); + /* The key tile packed once for every row of the task: pairs interleaved by key, the + * keys past the tile's end zero (their scores are never read). */ + for (int64_t d2 = 0; d2 < D2; ++d2) { + uint32_t* dst = kpack + d2 * KT; + for (int64_t j = 0; j < kt; ++j) + std::memcpy(dst + j, K + (b0 + j0 + j) * k_rs + kh * k_hs + 2 * d2, 4); + for (int64_t j = kt; j < KT; ++j) dst[j] = 0; + } + + /* S, six rows a block against the whole packed tile. */ + int64_t r = 0; + for (; r + 6 <= R; r += 6) qk_rows<6>(qrow + r, kpack, D2, scale, S + r * KT, KT); + for (; r < R; ++r) qk_rows<1>(qrow + r, kpack, D2, scale, S + r * KT, KT); + /* The mask, by position inside the segment. */ + if (causal || window > 0) { + for (int64_t r = 0; r < R; ++r) { + const int64_t i = q0 + r / gqa; + 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 (!ok) S[r * KT + j] = -INFINITY; + } + } + } + /* The online softmax, row by row, four vectors a row; S becomes P in place. The keys + * past a short tile's end score -inf, so P is zero there and every row is full width. */ + if (kt < KT) + for (int64_t r = 0; r < R; ++r) + for (int64_t j = kt; j < KT; ++j) S[r * KT + j] = -INFINITY; + for (int64_t r = 0; r < R; ++r) { + float* sr = S + r * KT; + const float tmax = _mm512_reduce_max_ps( + _mm512_max_ps(_mm512_max_ps(_mm512_loadu_ps(sr), _mm512_loadu_ps(sr + 16)), + _mm512_max_ps(_mm512_loadu_ps(sr + 32), _mm512_loadu_ps(sr + 48)))); + 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 : std::exp(m[r] - tmax); + if (alpha != 1.0f) { + float* ar = acc + r * D; + const __m512 va = _mm512_set1_ps(alpha); + for (int64_t d = 0; d < D; d += 16) + _mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), va)); + l[r] *= alpha; + } + m[r] = tmax; + } + const vf vm = vf_set1(m[r]); + __m512 sum = _mm512_setzero_ps(); + for (int64_t j = 0; j < KT; j += 16) { + /* exp of -inf is the clamp's floor, ~1e-38: zero to every sum it joins. */ + const vf e = vf_exp(vf_sub(vf_loadu(sr + j), vm)); + vf_storeu(sr + j, e); + sum = _mm512_add_ps(sum, e); + } + l[r] += _mm512_reduce_add_ps(sum); + } + /* V's tile packed once for every row of the task, consecutive keys interleaved in + * pairs (a key past the tile's end is zero), and each row's P rounded to bf16 pairs + * along the keys. */ + const int64_t K2 = (kt + 1) / 2; + { + /* Two key rows' words interleaved, 32 columns a step: lanes 0..15 of the first + * output are (k0[d], k1[d]) for d = 0..15, the second's for d = 16..31. */ + const __m512i ilo = _mm512_set_epi16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10, + 41, 9, 40, 8, 39, 7, 38, 6, 37, 5, 36, 4, 35, 3, + 34, 2, 33, 1, 32, 0); + const __m512i ihi = _mm512_set_epi16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26, + 57, 25, 56, 24, 55, 23, 54, 22, 53, 21, 52, 20, + 51, 19, 50, 18, 49, 17, 48, 16); + for (int64_t k2 = 0; k2 < K2; ++k2) { + const uint16_t* v0 = V + (b0 + j0 + 2 * k2) * v_rs + kh * v_hs; + const bool two = 2 * k2 + 1 < kt; + uint32_t* dst = vpack + k2 * D; + for (int64_t d = 0; d < D; d += 32) { + const __m512i a = _mm512_loadu_si512((const void*)(v0 + d)); + const __m512i bb = two ? _mm512_loadu_si512((const void*)(v0 + v_rs + d)) + : _mm512_setzero_si512(); + _mm512_storeu_si512((void*)(dst + d), _mm512_permutex2var_epi16(a, ilo, bb)); + _mm512_storeu_si512((void*)(dst + d + 16), + _mm512_permutex2var_epi16(a, ihi, bb)); + } + } + } + /* P to bf16, round to nearest even: a row's 64 values are its 32 key pairs in order. */ + for (int64_t r = 0; r < R; ++r) { + const float* sr = S + r * KT; + uint32_t* pr = ppack + r * 32; + _mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16), + _mm512_loadu_ps(sr))); + _mm512_storeu_si512((void*)(pr + 16), + (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48), + _mm512_loadu_ps(sr + 32))); + } + for (int64_t c0 = 0; c0 < D; c0 += 64) { + int64_t r = 0; + for (; r + 6 <= R; r += 6) pv_rows<6>(acc + r * D, D, ppack + r * 32, vpack, K2, c0); + for (; r < R; ++r) pv_rows<1>(acc + r * D, D, ppack + r * 32, vpack, K2, c0); + } + } + for (int64_t r = 0; r < R; ++r) { + const int64_t qi = r / gqa, g = r % gqa; + const int64_t ob = (b0 + q0 + qi) * o_rs + (kh * gqa + g) * o_hs; + float* ar = acc + r * D; + const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r]; + const __m512 vi = _mm512_set1_ps(inv); + for (int64_t d = 0; d < D; d += 16) + _mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), vi)); + out_row(o, ob, D, ar); + } + } + return true; +} +#endif + /* ------------------------------------------------------------------ attn_dense */ /* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one * attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a @@ -505,10 +784,15 @@ 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); - if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE; + /* libref's window: causal, i - j < window; non-causal, |i - j| < window; 0 none. */ + const int64_t window = p_int(a, "window", 0); + if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE; if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED; - const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] : 1; + /* A rank-2 operand is [tokens, heads * head_dim], so its head count is its width over the + * head; reading it as one head would take every head of a multi-head slice for one long one. */ + const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] + : (q->rank == 2 ? q->shape[1] / head_dim : 1); const int64_t kv_heads = q_heads / gqa; if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE; const int64_t n_seq = numel(cu) - 1; @@ -534,6 +818,11 @@ AVX_KERNEL(attn_dense) { const int64_t o_rs = row_stride(o, q_heads * head_dim); const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); +#if AVX_LEVEL == 3 + if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, 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 AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2) for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) { @@ -550,7 +839,11 @@ AVX_KERNEL(attn_dense) { for (int64_t i = b0; i < b1; ++i) { const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs; - const int64_t jend = causal ? (i + 1) : b1; + 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); + } const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf); for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; float m = -INFINITY, l = 0.0f; @@ -589,7 +882,7 @@ AVX_KERNEL(attn_dense) { ntile = 0; }; - for (int64_t j = b0; j < jend; ++j) { + for (int64_t j = jbeg; j < jend; ++j) { const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf); sbuf[ntile] = dotf(qv, kvr, head_dim) * scale; vbase[ntile] = j * v_rs + kh * v_hs; @@ -617,6 +910,92 @@ AVX_KERNEL(attn_dense) { return RAD_OK; } +/* ------------------------------------------------------------------ attn_local_rel */ +/* libref's local attention with a relative-position term (Gemma 4's audio). A query sees at most + * left + 1 keys -- thirteen at the checkpoint's geometry -- so the work is a few dot products a + * (row, head) and the loop is libref's, vectorised along the head and parallel over (row, head). */ +AVX_KERNEL(attn_local_rel) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3]; + const RadTensor *pds = &a->t[4], *cu = &a->t[5], *o = &a->t[6]; + const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0); + const int64_t L = p_int(a, "left", 0), R = p_int(a, "right", 0); + const int64_t cdiv = p_int(a, "cu_div", 1); + const float cap = p_f32(a, "softcap", 0.0f); + if (D <= 0 || H <= 0 || L < 0 || cdiv <= 0 || !(cap > 0.0f)) return RAD_E_SHAPE; + if (R != 0) return RAD_E_UNSUPPORTED; + if (D > AVX_HD_MAX || L + 1 > AVX_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t Wd = H * D; + if (numel(pds) < D || numel(rk) < (L + 1) * Wd) return RAD_E_SHAPE; + const int64_t S = numel(cu) - 1; + if (S <= 0) return RAD_E_SHAPE; + const int64_t Mq = numel(q) / Wd, Mk = numel(k) / Wd, Mv = numel(v) / Wd, Mo = numel(o) / Wd; + const int64_t q_rs = row_stride(q, Wd), k_rs = row_stride(k, Wd), v_rs = row_stride(v, Wd); + const int64_t r_rs = row_stride(rk, Wd), o_rs = row_stride(o, Wd); + const int64_t q_ds = laststride(q), k_ds = laststride(k), v_ds = laststride(v); + const int64_t r_ds = laststride(rk), o_ds = laststride(o); + + const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0)); + const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); + /* softplus(pds), rounded to the weight's dtype as the reference evaluates it on the bf16 + * parameter (libref's reading), and the query's whole scale folded into one vector. */ + float* spd = (float*)scratch_raw((size_t)D * sizeof(float) + 64); + for (int64_t d = 0; d < D; ++d) { + const float x = ldt(pds, d * laststride(pds)); + const float sp = x > 20.0f ? x : (x > 0.0f ? x + std::log1p(std::exp(-x)) + : std::log1p(std::exp(x))); + float r = sp; + if (pds->dtype == RAD_BF16) r = rad_bf16_to_f32(rad_f32_to_bf16(sp)); + else if (pds->dtype == RAD_F16) r = rad_f16_to_f32(rad_f32_to_f16(sp)); + spd[d] = r; + } + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; + if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF((t1 - t0) * H * (L + 1) * D >= AVX_PAR_MIN) + for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) { + const int64_t i = t0 + ih / H, h = ih % H; + float* frame = scratch_f32((size_t)(4 * D + L + 1) + 16); + float* qf = frame; + float* kb = frame + D; + float* acc = frame + 2 * D; + float* tmp = frame + 3 * D; + float* lg = frame + 4 * D; + const float* qv = head_f32(q, i * q_rs + h * D * q_ds, q_ds, D, 1.0f, tmp); + for (int64_t d = 0; d < D; ++d) qf[d] = qv[d] * qs * spd[d]; + const int64_t j0 = i - L > t0 ? i - L : t0; + float mx = -INFINITY; + for (int64_t j = j0; j <= i; ++j) { + const float* kv = head_f32(k, j * k_rs + h * D * k_ds, k_ds, D, 1.0f, tmp); + for (int64_t d = 0; d < D; ++d) kb[d] = kv[d] * ks; + float ac = dotf(qf, kb, D); + const float* rv = head_f32(rk, (i - j) * r_rs + h * D * r_ds, r_ds, D, 1.0f, tmp); + ac += dotf(qf, rv, D); + const float x = cap * std::tanh(ac / cap); + lg[j - j0] = x; + mx = x > mx ? x : mx; + } + float sum = 0.0f; + for (int64_t j = j0; j <= i; ++j) { + lg[j - j0] = std::exp(lg[j - j0] - mx); + sum += lg[j - j0]; + } + for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f; + for (int64_t j = j0; j <= i; ++j) + axpy(acc, head_f32(v, j * v_rs + h * D * v_ds, v_ds, D, 1.0f, tmp), + lg[j - j0] / sum, D); + const int64_t ob = i * o_rs + h * D * o_ds; + if (o_ds == 1) out_row(o, ob, D, acc); + else for (int64_t d = 0; d < D; ++d) stt(o, ob + d * o_ds, acc[d]); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ kv_store */ /* The cache operand is INOUT and not OUT: this op touches only the mapped slots and every other * slot in the pool must survive it, which is a liveness fact the buffer planner has to know. @@ -888,27 +1267,77 @@ AVX_KERNEL(qk_norm_rope) { const float eps = p_f32(a, "eps", 1e-6f); const float rscale = p_f32(a, "scale", 1.0f); const float wadd = p_f32(a, "wadd", 0.0f); - static const char* kModes[] = { "neox", "gptj" }; - const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX); + const int v_norm = (int)p_int(a, "v_norm", 0); + static const char* kModes[] = { "neox", "gptj", "blocks" }; + const int mode = p_enum(a, "mode", kModes, 3, ROPE_NEOX); + if (mode < 0) return RAD_E_UNSUPPORTED; + const bool blocks = mode == 2; 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; + /* BLOCKS (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired + * (start + j, start + sec[c] + j), turned by position component comps[c]. */ + int64_t sec[8] = {}, comp[8] = {}; + int n_sec = 0; + if (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); + if (end == v) break; + if (x <= 0) return RAD_E_SHAPE; + comp[n_sec] = n_sec; + sec[n_sec++] = x; + v = end; + } + int64_t total = 0; + for (int c = 0; c < n_sec; ++c) total += sec[c]; + if (n_sec <= 0 || 2 * total != rot) return RAD_E_SHAPE; + if (const char* cs = p_str(a, "comps", nullptr)) { + int k = 0; + for (const char* v = cs; *v && k < 8; ) { + char* end = nullptr; + const long long x = std::strtoll(v, &end, 10); + if (end == v) break; + comp[k++] = x; + v = end; + } + if (k != n_sec) return RAD_E_SHAPE; + } + } + const bool multi = pos->rank >= 2; + const int64_t n_comp = multi ? pos->shape[0] : 1; + if (multi && !blocks) return RAD_E_SHAPE; + for (int c = 0; c < n_sec; ++c) + if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) 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; - const int64_t M = numel(pos); + const int64_t M = 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); const int64_t half = rot / 2; - /* One arena call for the launch-invariant tables: the inverse frequencies and both widened - * gains. A second scratch_raw would reallocate under the parallel region. */ - float* tab = (float*)scratch_raw((size_t)(half + 2 * head_dim) * sizeof(float) + 64); + /* One arena call for the launch-invariant tables: the inverse frequencies (and, for blocks, + * each pair's component) and both widened gains. A second scratch_raw would reallocate under + * the parallel region. */ + float* tab = (float*)scratch_raw((size_t)(2 * half + 2 * head_dim) * sizeof(float) + 64); float* invf = tab; - float* gq = tab + half; - float* gk = tab + half + head_dim; - for (int64_t i = 0; i < half; ++i) - invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot); + float* pcomp = tab + half; + float* gq = tab + 2 * half; + float* gk = tab + 2 * half + head_dim; + if (!blocks) { + for (int64_t i = 0; i < half; ++i) + invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot); + } else { + int64_t i = 0; + for (int c = 0; c < n_sec; ++c) + for (int64_t j = 0; j < sec[c]; ++j, ++i) { + invf[i] = 1.0f / std::pow(theta, (float)j / (float)sec[c]); + pcomp[i] = (float)comp[c]; + } + } 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; @@ -916,12 +1345,23 @@ AVX_KERNEL(qk_norm_rope) { 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 p = (float)ldi(pos, offlin(pos, m)) / (rscale != 0.0f ? rscale : 1.0f); + const float div = rscale != 0.0f ? rscale : 1.0f; + float pc[8]; + if (multi) + for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div; + else + pc[0] = (float)ldi(pos, offlin(pos, m)) / div; const int64_t row = m * rs; float* cs = scratch_f32((size_t)rot); float* buf = scratch_f32_b((size_t)head_dim); float* rbuf = scratch_f32_c((size_t)head_dim); - angles(cs, invf, half, p); + if (!blocks) angles(cs, invf, half, pc[0]); + else + for (int64_t i = 0; i < half; ++i) { + const float ang = pc[(int)pcomp[i]] * invf[i]; + cs[i] = std::cos(ang); + cs[half + i] = std::sin(ang); + } for (int64_t h = 0; h < n_head + n_head_kv; ++h) { const float* g = h < n_head ? gq : gk; const int64_t base = row + h * head_dim * ds; @@ -932,11 +1372,33 @@ AVX_KERNEL(qk_norm_rope) { for (; d + VF_N <= head_dim; d += VF_N) vf_storeu(rbuf + d, vf_mul(vf_mul(vf_loadu(xv + d), vs), vf_loadu(g + d))); for (; d < head_dim; ++d) rbuf[d] = xv[d] * sc * g[d]; - /* Written back through the operand's dtype, then re-read by rope_head -- the rounding - * across the seam is the contract. */ + /* Written back through the operand's dtype, then re-read by the rotation -- the + * rounding across the seam is the contract. */ 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]); - rope_head(qkv, base, ds, rot, mode, cs, half, rbuf); + if (!blocks) { + rope_head(qkv, base, ds, rot, mode, cs, half, rbuf); + continue; + } + int64_t i = 0, start = 0; + for (int c = 0; c < n_sec; ++c) { + for (int64_t j = 0; j < sec[c]; ++j, ++i) { + const int64_t i0 = start + j, i1 = start + sec[c] + j; + const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds); + stt(qkv, base + i0 * ds, x0 * cs[i] - x1 * cs[half + i]); + stt(qkv, base + i1 * ds, x0 * cs[half + i] + x1 * cs[i]); + } + start += 2 * sec[c]; + } + } + /* v_norm: the v heads RMS-normed with a unit gain and not rotated (libref). */ + for (int64_t h = 0; v_norm && h < n_head_kv; ++h) { + const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds; + const float* xv = head_f32(qkv, base, ds, head_dim, 1.0f, buf); + const float sc = 1.0f / std::sqrt(row_sumsq(xv, head_dim) / (float)head_dim + eps); + for (int64_t d = 0; d < head_dim; ++d) rbuf[d] = xv[d] * sc; + if (ds == 1) out_row(qkv, base, head_dim, rbuf); + else for (int64_t d = 0; d < head_dim; ++d) stt(qkv, base + d * ds, rbuf[d]); } } return RAD_OK; diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 8a9df914..b71d5ec0 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -58,6 +58,30 @@ std::vector build_cases() { EB(6, 645, w, 1)); add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2)); + for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" }) + add("act_mul", { HI("M", 6), HI("n", 645), HS("act", act), HS("dtype", dt) }, + EB(6, 645, w, 3)); + add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 2)); + add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt), HI("scalar", 1) }, + EB(9, 645, w, 2)); + add("seg_mean", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 1)); + add("relu", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2)); + add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2)); + add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt), + HF("wadd", 0), HF("mult", 0.5) }, EB(5, 645, w, 2)); + /* The audio subsampler's two geometries, scaled down in time, with and without the + * frame mask, and a segment boundary (cu_div 2: the cu counts finer than the rows). */ + add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 1), HI("cout", 24), HI("kh", 3), + HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt) }); + add("conv2d", { HI("M", 24), HI("width", 8), HI("cin", 20), HI("cout", 12), HI("kh", 3), + HI("kw", 3), HI("stride", 2), HI("pad", 1), HI("cu_div", 2), + HI("valid_stride", 2), HS("dtype", dt) }); + add("conv1d_dw", { HI("M", 26), HI("n", 645), HI("k", 5), HS("dtype", dt) }); + add("conv1d_dw", { HI("M", 24), HI("n", 64), HI("k", 5), HI("cu_div", 4), HS("dtype", dt) }); + add("rel_sinusoid", { HI("M", 13), HI("n", 1024), HF("max_timescale", 10000.0), + HS("dtype", dt) }); + add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035), + HS("dtype", dt) }, EB(27, 645, w, 1)); add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) }, EB(6, 645, w, 2)); @@ -146,6 +170,18 @@ std::vector build_cases() { add("logits_gemm", { HI("M", M), HI("n_vocab", 96), HI("n_embd", 259), HS("dtype", dt) }, 0, fl); } + /* Encoder-sized M at a width that is not a whole number of 48-column panels, with K odd and + * even: 37 rows take the bf16 dot-product path, 133 the outer-product one -- its column edge, + * its zero-paired last k and its five-row tail. */ + for (const char* dt : { "f32", "bf16" }) + for (int M : { 37, 133 }) + for (int K : { 259, 64 }) { + const double fl = 2.0 * M * 100 * K; + add("gemm_nt", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt) }, + 0, fl); + add("gemm_nt_bias", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt), + HS("act", "gelu_tanh") }, 0, fl); + } /* fp8a8 and fp8a16 ARE THE ONLY TWO libref CAN DESCRIBE, and that is a real limit rather than * a gap in this table: `gemm_nt_q` is one op over six weight formats and the SCALE GRID is * what differs between them -- per row, per row-group, per output-row-block, an e8m0 exponent @@ -172,7 +208,9 @@ std::vector build_cases() { HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256); for (const char* dt : { "f32", "bf16" }) { add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt), - HI("vocab_offset", 0), HF("wscale", 0) }); + HI("vocab_offset", 0), HF("mult", 1) }); + add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt), + HI("vocab_offset", 0), HF("mult", 22.625) }); add("embed_lookup_q", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt), HI("vocab_offset", 0), HF("wscale", 0.01) }); } @@ -191,7 +229,20 @@ std::vector build_cases() { for (int causal : { 0, 1 }) 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("max_seqlen", 24), HI("window", 0) }); + /* The sliding window both ways: bidirectional |i - j| < 5 and causal i - j < 5, over + * segments longer than the window so both bounds bite. */ + for (const char* dt : { "f32", "bf16" }) + for (int causal : { 0, 1 }) + 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) }); + /* Gemma 4's audio attention: left 12 over segments longer than the window. */ + for (const char* dt : { "f32", "bf16" }) + for (int cd : { 1, 4 }) + add("attn_local_rel", { HI("M", 40), HI("head_dim", 32), HI("n_head", 3), + HI("left", 12), HI("right", 0), HF("softcap", 50.0), + HI("cu_div", cd), HS("dtype", dt) }); for (const char* dt : { "f32", "bf16" }) add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2), HI("block_size", 16), HS("kv_dtype", dt), HF("k_scale", 1.0), @@ -203,6 +254,18 @@ std::vector build_cases() { 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), HF("scale", 1.0), HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0) }); + 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), HF("scale", 1.0), + HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0), + HI("v_norm", 1) }); + } + /* `blocks`, the two-component vision form: x over the first half, y over the second, the + * components named in the other order from the planes. */ + for (const char* dt : { "f32", "bf16" }) { + 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-6), HS("mode", "blocks"), + HS("sections", "16 16"), HS("comps", "1 0"), HI("v_norm", 1), + HS("dtype", dt) }); } add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0), HS("dtype", "f32") }); @@ -383,6 +446,13 @@ std::vector build_cases() { 0, 2.0 * M * 2048 * 2048); speed("gemm_nt", { HI("M", M), HI("N", 5632), HI("K", 2048), HS("dtype", "bf16") }, 0, 2.0 * M * 5632 * 2048); + } + /* An encoder step: every token of the batch at once, at EmbeddingGemma 2's two FFN shapes. */ + for (int M : { 2048 }) { + speed("gemm_nt", { HI("M", M), HI("N", 4096), HI("K", 512), HS("dtype", "bf16") }, + 0, 2.0 * M * 4096 * 512); + speed("gemm_nt", { HI("M", M), HI("N", 512), HI("K", 2048), HS("dtype", "bf16") }, + 0, 2.0 * M * 512 * 2048); speed("rmsnorm", { HI("M", M), HI("n", 2048), HF("eps", 1e-6), HS("dtype", "bf16"), HF("wadd", 0) }, (double)M * 2048 * 2 * 2, 0); speed("silu_mul", { HI("M", M), HI("n", 5632), HS("dtype", "bf16") }, diff --git a/libavx/avx_common.h b/libavx/avx_common.h index 3cfdb55b..4907ee14 100644 --- a/libavx/avx_common.h +++ b/libavx/avx_common.h @@ -40,8 +40,49 @@ #ifdef _OPENMP #include +#include +#include +#include +/* THE TEAM IS ONE THREAD A PHYSICAL CORE, not one a logical CPU. These kernels are FMA- or + * bandwidth-bound, so an SMT sibling adds next to nothing to them -- and the engine runs threads + * of its own beside the team (a worker per stream, the scheduler, the HTTP server). A team as + * wide as the logical CPU count leaves those nowhere to run but on a core a team thread is + * spinning on, and a team barrier then waits for a descheduled thread: measured on a 16-core, + * 32-thread part, an encoder step of 576 tokens took 0.75 s at 32 threads and 0.09 s at 16. + * Counted over the process's affinity mask, so a pinned or containerised engine sizes its team to + * what it was given; OMP_NUM_THREADS, when set, is the operator's and wins, and a thread that + * asked OpenMP for fewer (omp_set_num_threads) gets fewer. */ +static inline int avx_team_size() { + /* The physical core count is a property of the process and counted once; the OpenMP request + * is the calling thread's and read every time, so a caller that asks for fewer threads + * (omp_set_num_threads, as the benchmark does for its single-thread figures) gets them. */ + static const int cores = [] { + if (const char* e = std::getenv("OMP_NUM_THREADS"); e && *e) return 0; + cpu_set_t set; + if (sched_getaffinity(0, sizeof set, &set) != 0) return 0; + int n = 0; + for (int c = 0; c < CPU_SETSIZE; ++c) { + if (!CPU_ISSET(c, &set)) continue; + /* A CPU counts when it is the first of its core's siblings that is in the mask. */ + char path[96]; + std::snprintf(path, sizeof path, + "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", c); + int first = c; + if (FILE* f = std::fopen(path, "r")) { + int v = -1; + if (std::fscanf(f, "%d", &v) == 1 && v >= 0 && v < CPU_SETSIZE && CPU_ISSET(v, &set)) + first = v; + std::fclose(f); + } + n += first == c; + } + return n; + }(); + const int asked = omp_get_max_threads(); + return cores > 0 && cores < asked ? cores : asked; +} #define AVX_PRAGMA(x) _Pragma(#x) -#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static)) +#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static) num_threads(avx_team_size())) /* THE OUTER LOOP IS WORTH A TEAM ONLY WHEN THERE IS ENOUGH WORK TO PAY FOR STARTING ONE, and the * `if` clause is how that is said without writing the serial loop twice. A fork/join costs a few * microseconds; an op below the threshold spends more time in the barrier than in the arithmetic, @@ -49,7 +90,8 @@ * measured by `rad-avx-bench --threads`. * * `cond` is pasted into the pragma text, so it must contain no comma. */ -#define AVX_PARALLEL_FOR_IF(cond) AVX_PRAGMA(omp parallel for schedule(static) if(cond)) +#define AVX_PARALLEL_FOR_IF(cond) \ + AVX_PRAGMA(omp parallel for schedule(static) if(cond) num_threads(avx_team_size())) #else #define AVX_PARALLEL_FOR #define AVX_PARALLEL_FOR_IF(cond) diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index 13b20cdd..13f7c086 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -80,6 +80,366 @@ static int elementwise2(const RadArgs* a) { AVX_KERNEL(add) { return elementwise2(a); } AVX_KERNEL(mul) { return elementwise2(a); } +/* y = x * w, `w` a weight of one element or one row (libref's mul_weight). */ +AVX_KERNEL(mul_weight) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", numel(Y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + const bool scalar = numel(W) == 1; + if (!scalar && numel(W) != n) return RAD_E_SHAPE; + /* The gain, widened once: it is the same row for every row of x. */ + float* wrow = (float*)scratch_raw((size_t)n * sizeof(float) + 64); + if (scalar) { const float v = ldt(W, 0); for (int64_t i = 0; i < n; ++i) wrow[i] = v; } + else for (int64_t i = 0; i < n; ++i) wrow[i] = ldt(W, i * laststride(W)); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sa = scratch_f32((size_t)n); + float* sy = scratch_f32_c((size_t)n); + const float* x = in_row(X, rowoff(X, r, n), n, sa); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(sy + i, vf_mul(vf_loadu(x + i), vf_loadu(wrow + i))); + for (; i < n; ++i) sy[i] = x[i] * wrow[i]; + out_row(Y, rowoff(Y, r, n), n, sy); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ act_mul */ +/* y = act(a) * b over two operands, libref's contract: the activation is rounded to y's dtype + * before the product, because the unfused pair stores it. + * + * silu and gelu_tanh are VECTORISED on vf_exp. An encoder's gated FFN puts this op on every token + * of every layer, and the scalar libm form was 9% of an EmbeddingGemma 2 step on a 9950X3D -- a + * per-element tanhf behind 2048 columns. gelu_tanh keeps the reference's own structure, + * + * 0.5 g (1 + tanh z), z = sqrt(2/pi) (g + 0.044715 g^3), tanh z = (1 - e^(-2z)) / (1 + e^(-2z)) + * + * and not the algebraically equal g / (1 + e^(-2z)): the two differ by an ulp or two of f32, and + * after the bf16 rounding the rearranged form moved an EmbeddingGemma 2 embedding measurably + * further from transformers' (cosine 0.999919 -> 0.999894 on one input; torch computes this same + * 0.5 g (1 + tanh) in f32). vf_exp saturates rather than overflowing, so the large-|g| limits come + * out as g and 0. erf has no vector form in this plugin, so gelu stays scalar. */ +static inline float act_of(int act, float g) { + if (act == 0) return g / (1.0f + std::exp(-g)); + if (act == 1) return 0.5f * g * (1.0f + std::erf(g * 0.70710678118654752f)); + if (act == 3) return 1.0f / (1.0f + std::exp(-g)); + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + return 0.5f * g * (1.0f + std::tanh(k0 * (g + k1 * g * g * g))); +} + +/* sy[0..n) = act(g[0..n)) for silu (0) and gelu_tanh (2); the tail is the scalar form. */ +static inline void act_row(int act, const float* g, float* sy, int64_t n) { + int64_t i = 0; + const vf one = vf_set1(1.0f); + if (act == 0) { + for (; i + VF_N <= n; i += VF_N) { + const vf x = vf_loadu(g + i); + vf_storeu(sy + i, vf_div(x, vf_add(one, vf_exp(vf_sub(vf_zero(), x))))); + } + } else if (act == 2) { + const vf m2k0 = vf_set1(-2.0f * 0.7978845608028654f), k1 = vf_set1(0.044715f); + const vf half = vf_set1(0.5f); + for (; i + VF_N <= n; i += VF_N) { + const vf x = vf_loadu(g + i); + const vf inner = vf_fma(vf_mul(k1, x), vf_mul(x, x), x); /* g + k1 g^3 */ + const vf e = vf_exp(vf_mul(m2k0, inner)); /* e^(-2z) */ + const vf t = vf_div(vf_sub(one, e), vf_add(one, e)); /* tanh z */ + vf_storeu(sy + i, vf_mul(vf_mul(half, x), vf_add(one, t))); + } + } + for (; i < n; ++i) sy[i] = act_of(act, g[i]); +} + +AVX_KERNEL(act_mul) { + 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)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE; + static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" }; + const int act = p_enum(a, "act", kActs, 4, -1); + if (act < 0) return RAD_E_INVAL; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sa = scratch_f32((size_t)n); + float* sb = scratch_f32_b((size_t)n); + float* sy = scratch_f32_c((size_t)n); + const float* g = in_row(A, rowoff(A, r, n), n, sa); + const float* u = in_row(B, rowoff(B, r, n), n, sb); + act_row(act, g, sy, n); + /* sa is free once the activation is taken (g is either sa or the tensor itself); sb may + * hold u, which the product still reads. */ + roundtrip(Y->dtype, sy, n, sa); + for (int64_t i = 0; i < n; ++i) sy[i] *= u[i]; + out_row(Y, rowoff(Y, r, n), n, sy); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ relu / clamp */ +/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi WEIGHTS of one element each (a + * clipped linear's range). Row-wise at each operand's own pitch, like the libref forms. */ +AVX_KERNEL(relu) { + 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", numel(Y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sx = scratch_f32((size_t)n); + float* sy = scratch_f32_b((size_t)n); + const float* v = in_row(X, rowoff(X, r, n), n, sx); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_max(vf_loadu(v + i), vf_zero())); + for (; i < n; ++i) sy[i] = v[i] > 0.0f ? v[i] : 0.0f; + out_row(Y, rowoff(Y, r, n), n, sy); + } + return RAD_OK; +} + +AVX_KERNEL(clamp) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", numel(Y)); + if (n <= 0 || numel(L) < 1 || numel(H) < 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + const float lo = ldt(L, 0), hi = ldt(H, 0); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sx = scratch_f32((size_t)n); + float* sy = scratch_f32_b((size_t)n); + const float* v = in_row(X, rowoff(X, r, n), n, sx); + for (int64_t i = 0; i < n; ++i) { + float t = v[i] < lo ? lo : v[i]; + sy[i] = t > hi ? hi : t; + } + out_row(Y, rowoff(Y, r, n), n, sy); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv2d */ +/* libref's segment-wise convolution over (time, width), channels innermost. The weight is turned + * once a launch from PyTorch's [cout, cin, kh, kw] into [kh][kw][cin][cout], so each input value is + * broadcast against a contiguous run of output channels: the inner loop is a vector FMA over cout + * rather than a dot product over cin. Same sum (in a different order), one rounding. */ +AVX_KERNEL(conv2d) { + if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data) + return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4]; + const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr; + const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); + const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); + const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1); + if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || + vst <= 0) + return RAD_E_SHAPE; + const int64_t Wo = (W + 2 * pad - kw) / st + 1; + if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE; + const int64_t S = numel(cu) - 1; + if (S <= 0) return RAD_E_SHAPE; + const int64_t rin = W * cin, rout = Wo * cout; + const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout); + + float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout) * sizeof(float) + 64); + const int64_t ws = laststride(Wt); + for (int64_t co = 0; co < cout; ++co) + for (int64_t ci = 0; ci < cin; ++ci) + for (int64_t i = 0; i < kh; ++i) + for (int64_t j = 0; j < kw; ++j) + wt[((i * kw + j) * cin + ci) * cout + co] = + ldt(Wt, (((co * cin + ci) * kh + i) * kw + j) * ws); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0; + if (T <= 0) continue; + const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st; + if (To <= 0) continue; + if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE; + if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(To * rout * cin * kh * kw >= AVX_PAR_MIN) + for (int64_t to = 0; to < To; ++to) { + float* acc = scratch_f32((size_t)rout); + float* sx = scratch_f32_b((size_t)rin); + for (int64_t e = 0; e < rout; ++e) acc[e] = 0.0f; + for (int64_t i = 0; i < kh; ++i) { + const int64_t ti = to * st - pad + i; + if (ti < 0 || ti >= T) continue; + const int64_t tg = t0 + ti; + if (V && ldi(V, offlin(V, tg * vst)) == 0) continue; + const float* xr = in_row(X, rowoff(X, tg, rin), rin, sx); + for (int64_t wo = 0; wo < Wo; ++wo) { + float* ar = acc + wo * cout; + for (int64_t j = 0; j < kw; ++j) { + const int64_t wi = wo * st - pad + j; + if (wi < 0 || wi >= W) continue; + const float* xv = xr + wi * cin; + const float* wb = wt + (i * kw + j) * cin * cout; + for (int64_t ci = 0; ci < cin; ++ci) { + const vf b = vf_set1(xv[ci]); + const float* wr = wb + ci * cout; + int64_t c = 0; + for (; c + VF_N <= cout; c += VF_N) + vf_storeu(ar + c, vf_fma(b, vf_loadu(wr + c), vf_loadu(ar + c))); + for (; c < cout; ++c) ar[c] += xv[ci] * wr[c]; + } + } + } + } + out_row(Y, rowoff(Y, o0 + to, rout), rout, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv1d_dw */ +/* libref's causal depthwise convolution over time, the weight turned to [k][C] once a launch so + * a row is a vector FMA per tap. */ +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 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; + 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); + + float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64); + 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 s = 0; s < S; ++s) { + const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; + if (t1 > Mx || t1 > My) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF((t1 - t0) * C * K >= AVX_PAR_MIN) + for (int64_t t = t0; t < t1; ++t) { + float* acc = scratch_f32((size_t)C); + float* sx = scratch_f32_b((size_t)C); + for (int64_t c = 0; c < C; ++c) acc[c] = 0.0f; + for (int64_t j = 0; j < K; ++j) { + const int64_t tt = t - (K - 1) + j; + if (tt < t0) continue; + const float* xr = in_row(X, rowoff(X, tt, C), C, sx); + const float* wr = wt + j * C; + int64_t c = 0; + for (; c + VF_N <= C; c += VF_N) + 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]; + } + out_row(Y, rowoff(Y, t, C), C, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ rel_sinusoid */ +/* libref's table, to the operation: the same f32 steps and the same libm calls. */ +AVX_KERNEL(rel_sinusoid) { + if (!rad_args_have(a, 1)) return RAD_E_INVAL; + const RadTensor* Y = &a->t[0]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || n % 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0) return RAD_E_SHAPE; + const int64_t h = n / 2; + const double mt = (double)p_f32(a, "max_timescale", 10000.0f); + const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t d = 0; d < rows; ++d) { + float* sy = scratch_f32((size_t)n); + for (int64_t i = 0; i < h; ++i) { + const float inv = std::exp((float)i * -inc); + const float ang = (float)d * inv; + sy[i] = std::sin(ang); + sy[h + i] = std::cos(ang); + } + out_row(Y, rowoff(Y, d, n), n, sy); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ seg_mean */ +/* One row a cu_seqlens segment: the mean of its rows, summed in double and rounded once, which is + * libref's arithmetic -- a pooled embedding should not depend on which host kernel pooled it. */ +AVX_KERNEL(seg_mean) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + const int64_t S = numel(cu) - 1; + if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE; + const int64_t total = ldi(cu, offlin(cu, S)); + if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(S >= 2) + for (int64_t s = 0; s < S; ++s) { + const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1)); + double* acc = (double*)scratch_raw((size_t)n * sizeof(double) + 64); + float* sx = scratch_f32_b((size_t)n); + float* sy = scratch_f32_c((size_t)n); + for (int64_t i = 0; i < n; ++i) acc[i] = 0.0; + for (int64_t r = b0; r < b1; ++r) { + const float* x = in_row(X, rowoff(X, r, n), n, sx); + for (int64_t i = 0; i < n; ++i) acc[i] += x[i]; + } + const double inv = b1 > b0 ? 1.0 / (double)(b1 - b0) : 0.0; + for (int64_t i = 0; i < n; ++i) sy[i] = b1 > b0 ? (float)(acc[i] * inv) : 0.0f; + out_row(Y, rowoff(Y, s, n), n, sy); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pool_rows */ +/* libref's: the mean of each k consecutive rows summed in f32 and rounded to y's dtype, then the + * multiplier and a second rounding -- the unfused pair. Parallel over output rows. */ +AVX_KERNEL(pool_rows) { + 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), k = p_int(a, "k", 0); + const float mult = p_f32(a, "mult", 1.0f); + if (n <= 0 || k <= 0) return RAD_E_SHAPE; + const int64_t rows_in = rows_of(X, n); + if (rows_in <= 0 || rows_in % k) return RAD_E_SHAPE; + const int64_t rows = rows_in / k; + if (numel(Y) < rows * n) return RAD_E_SHAPE; + const float inv = 1.0f / (float)k; + + AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* acc = scratch_f32((size_t)n); + float* sx = scratch_f32_b((size_t)n); + for (int64_t i = 0; i < n; ++i) acc[i] = 0.0f; + for (int64_t j = 0; j < k; ++j) { + const float* v = in_row(X, rowoff(X, r * k + j, n), n, sx); + for (int64_t i = 0; i < n; ++i) acc[i] += v[i]; + } + for (int64_t i = 0; i < n; ++i) acc[i] *= inv; + roundtrip(Y->dtype, acc, n, sx); + for (int64_t i = 0; i < n; ++i) acc[i] *= mult; + out_row(Y, rowoff(Y, r, n), n, acc); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ scale_rows */ /* y[m, i] = x[m, i] * act(s[m]), then + add[m, i] if the optional residual is passed. * diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index 63a7b492..ca9855ad 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -367,6 +367,333 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal return RAD_OK; } +/* ================================================================== the bf16 outer-product path + * + * AN ENCODER'S GEMM IS ALL PREFILL: M is the step's whole token count, thousands of rows, every + * launch. The driver above is shaped for decode -- it packs A on the calling thread one M block at + * a time and re-widens each weight row into f32 once per M block -- and at M = 3000, K = 2048 that + * is the weight widened a hundred times over, behind a single-threaded pack, for 0.14 TFLOPS on a + * 16-core part. + * + * Where both operands are bf16 with unit element stride and the CPU has AVX512_BF16 (Zen 4 on, + * Cooper Lake and Sapphire Rapids on), this path runs instead, and it is the OUTER-PRODUCT form + * this file otherwise argues against -- because here M is large enough to pay for the one thing + * that argument says it costs, a pack of B: + * + * B is packed ONCE A CALL, in parallel, into panels of 48 columns in vdpbf16ps's pair layout, + * Bp[panel][K/2][48][2]: one k-pair of 48 columns is three zmm, read contiguously. Columns past + * N and the second half of an odd K's last pair are zeros. + * The microkernel is 8 rows of A by one panel: per k-pair, three panel loads, eight 32-bit + * broadcasts of A's (k, k+1) pair, 24 vdpbf16ps into 24 accumulators. NO HORIZONTAL REDUCTION + * anywhere -- each accumulator lane is one output element -- and a row is stored as three + * 16-wide vectors. + * Threads take tiles of (64 rows) x (up to four panels), dynamically. Within a tile the panel + * loop is outer, so a panel (K x 96 bytes: 48 KiB at K = 512, 192 KiB at K = 2048) stays in L2 + * while the tile's row blocks stream through it. + * + * MEASURED on a 9950X3D, 16 threads, M = 2048: 6.9 TFLOPS at N = 4096, K = 512 and 6.1 at + * N = 512, K = 2048. The dot-product form -- vdpbf16ps along K straight out of both rows, 4 x 6 + * blocks -- reached 1.5 at both: at K = 512 a block does sixteen k steps and then 24 sixteen-lane + * reductions, so the reductions were most of its instruction stream. Below 128 rows the per-call + * pack is not paid back, and that form (gemm_bf16_dot) still runs there. + * + * It is one instruction stream inside the AVX-512 object, compiled for the extra feature with a + * function attribute and entered only after __builtin_cpu_supports says the CPU has it: an + * AVX-512 part without BF16 takes the driver above, unchanged. + * + * THE ARITHMETIC: products of bf16 pairs in f32, accumulated per output in k order two at a time, + * with bf16 denormals read as zero (the instruction's DAZ); the bias is the accumulator's start + * and the store rounds to nearest even. A different summation order from the driver's, inside the + * checker's bf16 tolerance like every vectorised reduction here. Each output element is computed + * by one thread, so the result does not depend on the thread count. */ +#if AVX_LEVEL == 3 +#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) + +constexpr int64_t BP_COLS = 48; /* columns a panel: three zmm of f32 accumulators */ +constexpr int64_t BP_MR = 8; /* rows of A a microkernel */ + +/* f32 -> bf16 round-to-nearest-even, sixteen lanes, a NaN kept a (quiet) NaN: the scalar + * converter's arithmetic, vectorised. */ +AVX_BF16_TARGET static inline __m256i bf16_rne16(__m512 x) { + const __m512i u = _mm512_castps_si512(x); + const __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1)); + __m512i r = _mm512_srli_epi32(_mm512_add_epi32(_mm512_add_epi32(u, _mm512_set1_epi32(0x7fff)), + lsb), 16); + const __mmask16 nan = _mm512_cmpgt_epu32_mask(_mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff)), + _mm512_set1_epi32(0x7f800000)); + r = _mm512_mask_mov_epi32(r, nan, _mm512_or_si512(_mm512_srli_epi32(u, 16), + _mm512_set1_epi32(0x40))); + return _mm512_cvtepi32_epi16(r); +} + +/* MR_ rows of A against one packed panel, over all of K, stored to the panel's `cols` columns of + * Y rows 0..MR_-1 (Y already offset to the block's first element). `bv` starts the accumulators: + * the bias, or zeros. */ +template +AVX_BF16_TARGET static inline void op_block(const uint16_t* A, int64_t lda, const uint16_t* panel, + int64_t K, const __m512* bv, void* Y, int64_t ys_r, + bool yb, int64_t cols) { + __m512 acc[MR_][3]; +#pragma GCC unroll 8 + for (int i = 0; i < MR_; ++i) { + acc[i][0] = bv[0]; + acc[i][1] = bv[1]; + acc[i][2] = bv[2]; + } + const int64_t kp_full = K / 2; + const uint16_t* bp = panel; + for (int64_t kp = 0; kp < kp_full; ++kp, bp += 2 * BP_COLS) { + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); +#pragma GCC unroll 8 + for (int i = 0; i < MR_; ++i) { + uint32_t pr; + std::memcpy(&pr, A + i * lda + 2 * kp, 4); + const __m512bh av = (__m512bh)_mm512_set1_epi32((int)pr); + acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); + acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); + acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); + } + } + if (K & 1) { + /* The odd last k: A's element alone in the pair's low half, never the one past the row. */ + const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); + const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); + const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); +#pragma GCC unroll 8 + for (int i = 0; i < MR_; ++i) { + const __m512bh av = (__m512bh)_mm512_set1_epi32((int)(uint32_t)A[i * lda + K - 1]); + acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); + acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); + acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); + } + } + /* Every accumulator index is a constant, so the block never leaves the registers. */ + auto mask = [&](int64_t c0) { + const int64_t w = cols - c0 <= 0 ? 0 : (cols - c0 < 16 ? cols - c0 : 16); + return (__mmask16)((1u << w) - 1); + }; + const __mmask16 m0 = mask(0), m1 = mask(16), m2 = mask(32); +#pragma GCC unroll 8 + for (int i = 0; i < MR_; ++i) { + if (yb) { + uint16_t* yr = (uint16_t*)Y + i * ys_r; + _mm256_mask_storeu_epi16(yr, m0, bf16_rne16(acc[i][0])); + _mm256_mask_storeu_epi16(yr + 16, m1, bf16_rne16(acc[i][1])); + _mm256_mask_storeu_epi16(yr + 32, m2, bf16_rne16(acc[i][2])); + } else { + float* yr = (float*)Y + i * ys_r; + _mm512_mask_storeu_ps(yr, m0, acc[i][0]); + _mm512_mask_storeu_ps(yr + 16, m1, acc[i][1]); + _mm512_mask_storeu_ps(yr + 32, m2, acc[i][2]); + } + } +} + +/* THE SMALL-M FORM: vdpbf16ps along K straight out of both rows, 4 x 6 blocks, no pack. The pack + * in gemm_bf16_dp touches every weight once a call -- 250 MB a forward pass for EmbeddingGemma + * 2 -- which an encoder step of thousands of rows amortises and a single 16-token query does not: + * there the outer-product path took a query from 13 to 17 ms. The pack pays for itself where the rows it + * serves are many; by the measured rates (1.5 against 6 TFLOPS, the pack streaming at memory + * speed) that is from about 75 rows, and 128 is the switch. */ +template +AVX_BF16_TARGET static inline void dp_block(const uint16_t* A, int64_t lda, const uint16_t* B, + int64_t ldb, int64_t K, float out[MB_][NB_]) { + __m512 acc[MB_][NB_]; + for (int i = 0; i < MB_; ++i) + for (int j = 0; j < NB_; ++j) acc[i][j] = _mm512_setzero_ps(); + int64_t k = 0; + for (; k + 32 <= K; k += 32) { + __m512bh av[MB_]; + for (int i = 0; i < MB_; ++i) + av[i] = (__m512bh)_mm512_loadu_si512((const void*)(A + i * lda + k)); + for (int j = 0; j < NB_; ++j) { + const __m512bh bv = (__m512bh)_mm512_loadu_si512((const void*)(B + j * ldb + k)); + for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); + } + } + if (k < K) { + const __mmask32 mk = (__mmask32)((1ull << (K - k)) - 1); + __m512bh av[MB_]; + for (int i = 0; i < MB_; ++i) + av[i] = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(A + i * lda + k)); + for (int j = 0; j < NB_; ++j) { + const __m512bh bv = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(B + j * ldb + k)); + for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); + } + } + for (int i = 0; i < MB_; ++i) + for (int j = 0; j < NB_; ++j) out[i][j] = _mm512_reduce_add_ps(acc[i][j]); +} + +static inline uint16_t f32_bf16_rne(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu)) return (uint16_t)((u >> 16) | 0x40u); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +AVX_BF16_TARGET static void gemm_bf16_dot(const uint16_t* A, int64_t lda, const uint16_t* B, + int64_t ldb, const RadTensor* Y, int64_t ys_r, + const RadTensor* bias, int64_t M, int64_t N, int64_t K) { + const bool yb = Y->dtype == RAD_BF16; + /* The tile grid: 64 rows of A by a column count chosen so there are at least four tiles a + * thread, capped at 192 columns. */ + constexpr int64_t BMR = 4, BNR = 6, MC = 64; + const int64_t mt = (M + MC - 1) / MC; +#ifdef _OPENMP + const int64_t nth = (int64_t)avx_team_size(); +#else + const int64_t nth = 1; +#endif + int64_t want_nt = (4 * nth + mt - 1) / mt; + if (want_nt < 1) want_nt = 1; + int64_t NC = (N + want_nt - 1) / want_nt; + NC = ((NC + BNR - 1) / BNR) * BNR; + if (NC > 192) NC = 192; + if (NC < BNR) NC = BNR; + const int64_t ntl = (N + NC - 1) / NC; + + auto store = [&](int64_t m, int64_t n, float v) { + if (bias) v += ldt(bias, n * laststride(bias)); + if (yb) ((uint16_t*)Y->data)[m * ys_r + n] = f32_bf16_rne(v); + else ((float*)Y->data)[m * ys_r + n] = v; + }; + +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) +#endif + for (int64_t t = 0; t < mt * ntl; ++t) { + const int64_t m_lo = (t / ntl) * MC, n_lo = (t % ntl) * NC; + const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; + const int64_t n_hi = n_lo + NC < N ? n_lo + NC : N; + for (int64_t n0 = n_lo; n0 < n_hi; n0 += BNR) { + const int64_t nn = n_hi - n0 < BNR ? n_hi - n0 : BNR; + for (int64_t m0 = m_lo; m0 < m_hi; m0 += BMR) { + const int64_t mm = m_hi - m0 < BMR ? m_hi - m0 : BMR; + if (mm == BMR && nn == BNR) { + float o[BMR][BNR]; + dp_block(A + m0 * lda, lda, B + n0 * ldb, ldb, K, o); + for (int i = 0; i < BMR; ++i) + for (int j = 0; j < BNR; ++j) store(m0 + i, n0 + j, o[i][j]); + } else { + for (int64_t i = 0; i < mm; ++i) + for (int64_t j = 0; j < nn; ++j) { + float o[1][1]; + dp_block<1, 1>(A + (m0 + i) * lda, lda, B + (n0 + j) * ldb, ldb, K, o); + store(m0 + i, n0 + j, o[0][0]); + } + } + } + } + } +} + +/* A bf16 x bf16 product into Y, or false when this path does not apply and the driver should run. */ +AVX_BF16_TARGET static bool gemm_bf16_dp(const Mat& ma, const Mat& mb, const RadTensor* Y, + const RadTensor* bias, int64_t M, int64_t N, int64_t K) { + static const bool have = __builtin_cpu_supports("avx512bf16"); + if (!have || M < 16) return false; + if (ma.t->dtype != RAD_BF16 || mb.t->dtype != RAD_BF16 || ma.cs != 1 || mb.cs != 1) return false; + if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false; + const int64_t ys_r = row_stride(Y, N); + const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; + if (ys_c != 1) return false; + + const uint16_t* A = (const uint16_t*)ma.t->data; + const uint16_t* B = (const uint16_t*)mb.t->data; + const int64_t lda = ma.rs, ldb = mb.rs; + if (M < 128) { + gemm_bf16_dot(A, lda, B, ldb, Y, ys_r, bias, M, N, K); + return true; + } + const bool yb = Y->dtype == RAD_BF16; + const size_t yel = yb ? 2 : 4; + + /* ---- the pack, into the calling thread's arena before any worker reads it */ + const int64_t np = (N + BP_COLS - 1) / BP_COLS; + const int64_t kp_n = (K + 1) / 2; + const int64_t pstride = kp_n * 2 * BP_COLS; /* uint16 a panel */ + uint16_t* Bp = (uint16_t*)scratch_raw((size_t)(np * pstride) * sizeof(uint16_t) + 64); +#ifdef _OPENMP +#pragma omp parallel for schedule(static) num_threads(avx_team_size()) if(np * pstride >= 65536) +#endif + for (int64_t p = 0; p < np; ++p) { + uint32_t* dst = (uint32_t*)(Bp + p * pstride); + const int64_t n0 = p * BP_COLS; + for (int64_t c = 0; c < BP_COLS; ++c) { + const int64_t n = n0 + c; + if (n >= N) { + for (int64_t kp = 0; kp < kp_n; ++kp) dst[kp * BP_COLS + c] = 0; + continue; + } + const uint16_t* row = B + n * ldb; + for (int64_t kp = 0; kp < K / 2; ++kp) { + uint32_t pr; + std::memcpy(&pr, row + 2 * kp, 4); + dst[kp * BP_COLS + c] = pr; + } + if (K & 1) dst[(kp_n - 1) * BP_COLS + c] = (uint32_t)row[K - 1]; + } + } + + /* ---- the tile grid: 64-row M blocks by groups of panels, at least four tiles a thread */ + constexpr int64_t MC = 64; + const int64_t mt = (M + MC - 1) / MC; +#ifdef _OPENMP + const int64_t nth = (int64_t)avx_team_size(); +#else + const int64_t nth = 1; +#endif + int64_t groups = (4 * nth + mt - 1) / mt; + if (groups < 1) groups = 1; + int64_t PG = (np + groups - 1) / groups; + if (PG > 4) PG = 4; + if (PG < 1) PG = 1; + const int64_t ng = (np + PG - 1) / PG; + +#ifdef _OPENMP +#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) +#endif + for (int64_t t = 0; t < mt * ng; ++t) { + const int64_t m_lo = (t / ng) * MC, p_lo = (t % ng) * PG; + const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; + const int64_t p_hi = p_lo + PG < np ? p_lo + PG : np; + for (int64_t p = p_lo; p < p_hi; ++p) { + const int64_t n0 = p * BP_COLS; + const int64_t cols = N - n0 < BP_COLS ? N - n0 : BP_COLS; + __m512 bv[3]; + for (int v = 0; v < 3; ++v) { + alignas(64) float bb[16]; + for (int e = 0; e < 16; ++e) { + const int64_t n = n0 + 16 * v + e; + bb[e] = (bias && n < N) ? ldt(bias, n * laststride(bias)) : 0.0f; + } + bv[v] = _mm512_load_ps(bb); + } + const uint16_t* panel = Bp + p * pstride; + for (int64_t m0 = m_lo; m0 < m_hi; m0 += BP_MR) { + const int64_t mm = m_hi - m0 < BP_MR ? m_hi - m0 : BP_MR; + const uint16_t* Ar = A + m0 * lda; + void* Yr = (char*)Y->data + (size_t)(m0 * ys_r + n0) * yel; + switch (mm) { + case 8: op_block<8>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 7: op_block<7>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 6: op_block<6>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 5: op_block<5>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 4: op_block<4>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 3: op_block<3>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + case 2: op_block<2>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + default: op_block<1>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; + } + } + } + } + return true; +} +#endif + /* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name which parameters carry * N and K, because logits_gemm spells them n_vocab and n_embd. */ /* gemm_nt_bias's epilogue (docs/OPS.md): an activation of the stored product, then a residual, @@ -409,8 +736,13 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c if (res && numel(res) < M * N) return RAD_E_SHAPE; const Mat ma = as_mat(A, K), mb = as_mat(B, K); - const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); - if (st < 0) return st; +#if AVX_LEVEL == 3 + if (!gemm_bf16_dp(ma, mb, Y, bias, M, N, K)) +#endif + { + const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); + if (st < 0) return st; + } if (act || res) gemm_epilogue(Y, res, act, M, N); return RAD_OK; } @@ -546,8 +878,10 @@ static int embed_impl(const RadArgs* a) { if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; const int64_t M = numel(x) / n_embd; if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; - /* An absent scale is one (ref_embed_lookup_q says why the op allows it). */ - const float scale = QUANT && sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f; + /* An absent scale is one (ref_embed_lookup_q says why the op allows it). embed_lookup's + * `mult` is the same multiply, a parameter instead of a table scale. */ + const float scale = QUANT ? (sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f) + : p_f32(a, "mult", 1.0f); /* Validated before the loop, because an OpenMP body cannot return. */ if (voff == 0) @@ -559,7 +893,8 @@ static int embed_impl(const RadArgs* a) { /* A ROW COPY WHEN NOTHING HAS TO CHANGE, which for the unquantised gather is the usual case: * the table and the activation are the same dtype and a memcpy moves the row at the width of * the machine instead of through an f32 round trip that would also re-round it. */ - const bool copy = !QUANT && wte->dtype == x->dtype && wc == 1 && laststride(x) == 1; + const bool copy = !QUANT && scale == 1.0f && wte->dtype == x->dtype && wc == 1 && + laststride(x) == 1; const size_t rowb = copy ? (size_t)((rad_dtype_bits(x->dtype) * n_embd) / 8) : 0; AVX_PARALLEL_FOR_IF(M * n_embd >= AVX_PAR_MIN) @@ -578,7 +913,7 @@ static int embed_impl(const RadArgs* a) { for (int64_t i = 0; i < n_embd; ++i) s[i] = 0.0f; } else if (wc == 1) { row_to_f32(wte->dtype, byte_at(wte->data, wte->dtype, id * ws), s, n_embd); - if (QUANT) { + if (scale != 1.0f) { const vf vs = vf_set1(scale); int64_t i = 0; for (; i + VF_N <= n_embd; i += VF_N) vf_storeu(s + i, vf_mul(vf_loadu(s + i), vs)); diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index b6be024d..ff9a10d0 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -90,7 +90,9 @@ int avx_isa_force(int level); X(mul) X(silu_mul) X(gelu) X(silu) \ X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ - X(scale_rows) X(fill) \ + X(scale_rows) X(fill) X(act_mul) X(seg_mean) \ + X(mul_weight) X(pool_rows) X(relu) X(clamp) \ + X(conv2d) X(conv1d_dw) X(rel_sinusoid) \ /* ---- quantisation and rotation */ \ X(quant_act_i8) 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) \ @@ -100,7 +102,7 @@ int avx_isa_force(int level); X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \ /* ---- attention */ \ X(attn_paged) X(attn_dense) X(kv_store) X(rope) \ - X(rope_table) X(qk_norm_rope) X(qsa_block_key) \ + X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \ /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ diff --git a/libavx/avx_norm.cpp b/libavx/avx_norm.cpp index 8bfae97a..3f288d7e 100644 --- a/libavx/avx_norm.cpp +++ b/libavx/avx_norm.cpp @@ -61,17 +61,25 @@ static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) { /* ------------------------------------------------------------------ rmsnorm */ /* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) */ AVX_KERNEL(rmsnorm) { - if (!rad_args_have(a, 3)) return RAD_E_INVAL; - const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[2]; - const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0); + if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[2]; + /* An absent gain is one (libref's reading), and `wadd` belongs to a gain. */ + const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr; + const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0); const float eps = p_f32(a, "eps", 1e-6f); const float wadd = p_f32(a, "wadd", 0.0f); if (n <= 0) return RAD_E_SHAPE; + if (!w && wadd != 0.0f) return RAD_E_INVAL; const int64_t rows = rows_of(x, n); - if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE; + if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE; float* gain = (float*)scratch_raw((size_t)n * sizeof(float)); - widen_gain(w, n, wadd, gain); + if (w) widen_gain(w, n, wadd, gain); + else for (int64_t i = 0; i < n; ++i) gain[i] = 1.0f; + /* `mult` folded into the gain: the row is scaled before its one rounding. */ + const float mult = p_f32(a, "mult", 1.0f); + if (mult != 1.0f) + for (int64_t i = 0; i < n; ++i) gain[i] *= mult; AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 0b2c5f85..e1302e5d 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -75,9 +75,13 @@ #define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0])) /* ---- elementwise and norms ---------------------------------------------------------------- */ +/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */ +static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), + P_F64O("wadd") }; static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), - P_F64O("wadd") }; -static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") }; + P_F64O("wadd"), P_F64O("mult") }; +/* `w` optional: absent, the gain is one. */ +static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") }; static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), @@ -126,9 +130,35 @@ 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") }; +static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; +static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") }; +static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; +static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") }; +static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), + P_STR("dtype") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; +/* The audio (USM conformer) tower's operators; libref's lists, field for field. */ +static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") }; +static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), + P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"), + P_INTO("cu_div"), P_INTO("valid_stride"), + P_STR("dtype") }; +static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"), + 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 RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), + P_STR("dtype") }; +static const RadOperandSpec oRelSin[] = { OUT("y") }; +static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("left"), P_INT("right"), P_F64("softcap"), + P_INTO("cu_div"), P_STR("dtype") }; +static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"), + WGT("pds"), OPD("cu_seqlens"), OUT("out") }; /* `fill` has no input: `value` is the whole of what it writes. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; @@ -206,7 +236,7 @@ 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("max_seqlen"), P_INTO("window") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; @@ -244,7 +274,9 @@ static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page") static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"), P_F64O("scale"), P_STRO("mode"), - P_INTO("rotary_dim"), P_F64O("wadd") }; + 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") }; @@ -391,6 +423,9 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") }; static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale") }; +static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), + P_STR("dtype"), P_INTO("vocab_offset"), + P_F64O("wscale"), P_F64O("mult") }; static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") }; static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"), OPD_O("ahead") }; @@ -438,7 +473,7 @@ static const RadOpSchema kSchemas[] = { { "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm), "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector " "reduction, so it does not sum in libref's order and does not claim to." }, -{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd), +{ "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd), "residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the " "unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's " "rule and both are observable, so both are reproduced exactly." }, @@ -460,6 +495,23 @@ static const RadOpSchema kSchemas[] = { { "add", ARR(pMnD), ARR(oBinary), "elementwise sum." }, { "mul", ARR(pMnD), ARR(oBinary), "elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." }, +{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight), + "y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." }, +{ "act_mul", ARR(pActMul), ARR(oBinary), + "y = act(a) * b, act silu / gelu / gelu_tanh, the activation rounded to y's dtype first." }, +{ "seg_mean", ARR(pSegMean), ARR(oSegMean), + "y[s] = the mean of x's rows in cu_seqlens segment s, summed in double, rounded once." }, +{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0)." }, +{ "clamp", ARR(pMnD), ARR(oClamp), "y = min(max(x, lo), hi), lo and hi one-element weights." }, +{ "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." }, +{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." }, +{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel), + "local attention with a relative-position term and a softcap (Gemma 4's audio)." }, +{ "pool_rows", ARR(pPoolRows), ARR(oUnary), + "y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), "silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." }, { "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." }, @@ -562,7 +614,8 @@ static const RadOpSchema kSchemas[] = { { "all_reduce", ARR(pAllReduce), ARR(oAllReduce), "sum across ranks, f32, ascending rank order." }, { "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." }, -{ "embed_lookup", ARR(pEmbed), ARR(oEmbed), "embedding gather, vocab-parallel with an offset." }, +{ "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), "embedding gather, one scale for the table; without a scale the table is read as it is." }, { "logits_gemm", ARR(pLogits), ARR(oLogits), "the lm_head projection." }, @@ -640,6 +693,24 @@ SIMPLE("avx_grid_embed", "grid_embed", "elem", "bilinear resample of a learned position grid, added in", DT_FLOAT, L(grid_embed)), SIMPLE("avx_add", "add", "elem", "elementwise sum", DT_FLOAT, L(add)), SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT, L(mul)), +SIMPLE("avx_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, L(act_mul)), +SIMPLE("avx_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, + L(mul_weight)), +SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, + L(seg_mean)), +SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", + DT_FLOAT, L(pool_rows)), +SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)), +SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)), +SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost", + DT_FLOAT, L(conv2d)), +SIMPLE("avx_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise convolution", + DT_FLOAT, L(conv1d_dw)), +SIMPLE("avx_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table", + DT_FLOAT, L(rel_sinusoid)), +SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn", + "local attention with a relative-position term and a softcap", DT_FLOAT, + L(attn_local_rel)), SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, L(silu_mul)), SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 1df168d1..f4bd2ded 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -67,6 +67,10 @@ set(R4D_UNITS # head is replicated across a rank pair. Again four lines that set the ratio and include the body. "r4d_attn_paged_h256_gqa6_bs4|" "r4d_attn_vit_h72_bf16|" + # An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and + # the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening. + "r4d_attn_dense_bf16|" + "r4d_encoder_bf16|" # The vision tower's own small ops: layer norm, the learned-grid position embedding, and the # biased GEMM with a linear layer's activation and residual in its store. "r4d_vit_bf16|" diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip new file mode 100644 index 00000000..f5431ccc --- /dev/null +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -0,0 +1,384 @@ +// 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. +// +// The core is the vision kernel's (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32 +// column-distributed accumulator gives each lane one query row, the softmax state is lane-private, +// and the C fragment of S^T is already the B fragment the PV matmul wants -- P never goes through +// LDS. What this file adds: +// +// GQA IN THE WORKGROUP. A workgroup owns one KV head and every query head that reads it, so a +// staged K/V tile is consumed by GQA times as many WMMAs as one head would give it. The grid is +// (query blocks, kv heads, segments). +// +// A WINDOW. A workgroup's key range is cut to the keys any of its queries can see, and the +// per-element test runs only on tiles that straddle a window edge or the segment's end; an +// interior tile pays nothing. Sliding layers at |i - j| <= 512 then cost O(T * window), not +// O(T^2). +// +// A HEAD SPLIT ACROSS WAVES (DSPLIT). One lane's output is head_dim / 2 floats, so head_dim 512 +// would need 256 accumulator VGPRs before the query fragments -- more than a lane has. At +// DSPLIT 2 two waves own the same 16 queries and half the head each: each contracts its half +// of q.k, the two partial scores are summed through LDS, both run the same softmax (a + b == +// b + a, so the two copies agree to the bit), and each accumulates its half of P.V. +// +// Every operand is read at its own token pitch, so q, k and v may be column slices of one fused +// projection; pitches and head offsets must be multiples of 8 elements for the 16-byte fetches. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_dt16.h" + +#include + +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 q_ld, int k_ld, int v_ld, int o_ld) +{ + typedef DT16<1> D; + typedef D::frag frag16; + + constexpr int NWARPS = NQB * GQA * DSPLIT; + constexpr int NTHR = NWARPS * 32; + constexpr int BQ = NQB * 16; // query rows per head per workgroup + constexpr int HDP = HD / DSPLIT; // the head dims one wave owns + constexpr int NKS = HDP / 16; // its 16-wide k-tiles + constexpr int MT = TILE / 16; + // Row strides padded by 8 shorts: 16-byte aligned, and off the bank period. + constexpr int KSTR = HD + 8; + constexpr int VSTR = TILE + 8; + constexpr int DG = HD / 8; // eight-element dim groups in a row + constexpr int KGRP = TILE / 8; // eight-key groups in a tile + constexpr int KITEMS = TILE * DG; // 16-byte K fetches a tile + constexpr int KP = (KITEMS + NTHR - 1) / NTHR; + constexpr int NTR = KGRP * DG; // transposed V units, eight lanes each + constexpr int LGRP = NTHR / 8; + constexpr int VP = (NTR + LGRP - 1) / LGRP; + constexpr float GROW = D::GROW; + static_assert(HD % (16 * DSPLIT) == 0 && TILE % 16 == 0, "geometry"); + static_assert(DSPLIT == 1 || DSPLIT == 2, "a head is split across at most two waves"); + + __shared__ __align__(16) uint16_t sK[TILE * KSTR]; + __shared__ __align__(16) uint16_t sV[HD * VSTR]; + __shared__ __align__(16) float sX[DSPLIT > 1 ? NWARPS * 32 * 8 : 4]; + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int c = lane & 15, h = lane >> 4; + const int dp = warp % DSPLIT; + const int g = (warp / DSPLIT) % GQA; + const int qbi = warp / (DSPLIT * GQA); + const int kvh = blockIdx.y, seq = blockIdx.z; + const int hq = kvh * GQA + g; + + const int s0 = cu[seq], slen = cu[seq + 1] - s0; + const int q0 = blockIdx.x * BQ; + if (slen <= 0 || q0 >= slen) return; + const int qlast = min(q0 + BQ, slen) - 1; + + // The keys any query of this workgroup can see. + int kb = 0, ke = slen; + if (window > 0) { + kb = max(0, q0 - (window - 1)); + ke = min(slen, qlast + window); + } + + const float mul = scale * 1.44269504089f; + const int qpos = q0 + qbi * 16 + c; + const bool live = qpos < slen; + + // ---- this wave's half (or whole) of its 16 query rows, scaled once ------------------------- + frag16 qf[NKS]; + { + const int qrow = live ? qpos : slen - 1; + const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hq * HD + dp * HDP; + #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}; + + const int vj = tid & 7, lgi = tid >> 3; + const uint16_t* kbase = gk + (long)kvh * HD; + const uint16_t* vbase = gv + (long)kvh * HD; + + const int ntiles = (ke - kb + TILE - 1) / TILE; + for (int ti = 0; ti < ntiles; ++ti) { + const int k0 = kb + ti * TILE; + // Whether any (query, key) pair of this tile is outside the window or past the keys: + // uniform over the workgroup, so the interior tiles skip the test entirely. + const bool mask = (k0 + TILE > ke) || + (window > 0 && (k0 < qlast - (window - 1) || + k0 + TILE - 1 > q0 + (window - 1))); + + uint4 kr[KP], vr[VP]; + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int i = tid + p * NTHR; + if (KITEMS % NTHR == 0 || i < KITEMS) { + const int key = i / DG, gg = i % DG; + const int kk = (k0 + key < ke) ? k0 + key : ke - 1; + kr[p] = *(const uint4*)(kbase + (long)(s0 + kk) * k_ld + gg * 8); + } + } + // V transposed on the way in: the eight lanes of a group name eight key rows at the same + // eight dims, and global_load_tr_b128 hands lane j dim d0+j across all eight. + #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 < ke) ? kk0 : ke - 1; + vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vbase + (long)(s0 + kk) * v_ld + + dg * 8)); + } + } + + lds_barrier(); // the previous tile's readers are done + #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 uint4 w = vr[r]; + *(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = + make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y), + D::from_bf16w(w.z), D::from_bf16w(w.w)); + } + } + #pragma unroll + for (int p = 0; p < KP; ++p) { + const int i = tid + p * NTHR; + if (KITEMS % NTHR == 0 || i < KITEMS) { + const uint4 w = kr[p]; + *(uint4*)&sK[(i / DG) * KSTR + (i % DG) * 8] = + make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y), + D::from_bf16w(w.z), D::from_bf16w(w.w)); + } + } + lds_barrier(); + + #pragma unroll 1 + for (int mt = 0; mt < MT; ++mt) { + v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + { + const uint16_t* krow = &sK[(mt * 16 + c) * KSTR + dp * HDP] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 kf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) { + const uint4 u = *(const uint4*)(krow + 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) + if (t0 + j < NKS) s = D::wmma(kf[j], qf[t0 + j], s); + } + } + if (DSPLIT > 1) { + // The other half of q.k, from the wave that owns it. + float* mine = &sX[(warp * 32 + lane) * 8]; + const float* theirs = &sX[((warp ^ 1) * 32 + lane) * 8]; + *(float4*)mine = make_float4(s[0], s[1], s[2], s[3]); + *(float4*)(mine + 4) = make_float4(s[4], s[5], s[6], s[7]); + lds_barrier(); + const float4 a = *(const float4*)theirs, b = *(const float4*)(theirs + 4); + s[0] += a.x; s[1] += a.y; s[2] += a.z; s[3] += a.w; + s[4] += b.x; s[5] += b.y; s[6] += b.z; s[7] += b.w; + lds_barrier(); + } + + float sc[8]; + #pragma unroll + for (int e = 0; e < 8; ++e) sc[e] = s[e]; + if (mask) { + const int kq = k0 + mt * 16 + 8 * h; + #pragma unroll + 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)); + sc[e] = ok ? sc[e] : -INFINITY; + } + } + + // The softmax against a reference max, rescaled only when the row max outgrows what + // the f16 P can hold (r4d_dt16.h). + float smax = sc[0]; + #pragma unroll + for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]); + 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; + } + + uint32_t pw[4]; + #pragma unroll + for (int e = 0; e < 8; e += 2) + pw[e >> 1] = D::pk(ex2(sc[e] + soff), ex2(sc[e + 1] + soff)); + // The row sum off the packed P, so the denominator is the values P.V used. + const v2hf one = {(__fp16)1.0f, (__fp16)1.0f}; + #pragma unroll + for (int e = 0; e < 4; ++e) + l_i = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf, pw[e]), one, l_i, false); + const frag16 p16 = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3])); + + { + const uint16_t* vrow = &sV[(dp * HDP + c) * VSTR + mt * 16] + 8 * h; + #pragma unroll + for (int t0 = 0; t0 < NKS; t0 += 4) { + frag16 vf[4]; + #pragma unroll + for (int j = 0; j < 4; ++j) + if (t0 + j < NKS) { + const uint4 u = *(const uint4*)(vrow + (t0 + j) * 16 * VSTR); + vf[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) + if (t0 + j < NKS) acc[t0 + j] = D::wmma(vf[j], p16, acc[t0 + j]); + } + } + } + } + + 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)(s0 + qpos) * o_ld + (long)hq * HD + dp * HDP; + #pragma unroll + for (int t = 0; t < NKS; ++t) { + uint32_t tw[4]; + #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]); + } +} + +// ---- launch ---------------------------------------------------------------------------------- +// One instantiation per (head_dim, gqa), at a workgroup shape picked for it: +// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads) +// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB) +// 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 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, 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 and sizes the grid. window 0 is the whole segment. +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 q_ld, int k_ld, int v_ld, int o_ld, + void* stream) +{ + 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) return -4; + if (num_seqs <= 0 || max_seqlen <= 0) return 0; + 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, 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, 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, q_ld, + k_ld, v_ld, o_ld, s); + return -1; +} + +// ============================================================== the plugin ABI entry point + +enum { DN_Q = 0, DN_K, DN_V, DN_CU, DN_OUT }; + +extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, DN_Q); + const RadTensor* k = r4d_opt(a, DN_K); + const RadTensor* v = r4d_opt(a, DN_V); + const RadTensor* cu = r4d_opt(a, DN_CU); + 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 head_dim = r4d_geti_or(a, "head_dim", 0); + const long long gqa = r4d_geti_or(a, "gqa", 1); + if (head_dim <= 0 || gqa <= 0) return R4D_NO(RAD_E_SHAPE); + /* [tokens, heads * head_dim] (or [tokens, heads, head_dim]) at the operand's own row pitch. */ + auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) { + long long width = 1; + for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; + if (t->rank < 2 || width % head_dim) return false; + *n_head = width / head_dim; + *ld = r4d_rows_pitch(t, width, n_tok); + return *ld >= 0; + }; + long long total = 0, nh = 0, q_ld = 0; + long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0; + if (!rows(q, &total, &nh, &q_ld) || !rows(k, &tk, &hk, &k_ld) || + !rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld)) + return R4D_NO(RAD_E_STRIDE); + if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE); + if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE); + if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); + const int num_seqs = (int)(cu->shape[0] - 1); + + /* max_seqlen sizes the grid and is a bound, not a length: the kernel reads the device-side + * cu_seqlens. Absent, the total token count is a valid bound. */ + long long msl = r4d_geti_or(a, "max_seqlen", 0); + 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 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)q_ld, (int)k_ld, (int)v_ld, (int)o_ld, s); + if (e == -1) return R4D_NO(RAD_E_SHAPE); + return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} diff --git a/libr4d/r4d_attn_vit_h72_bf16.hip b/libr4d/r4d_attn_vit_h72_bf16.hip index f46fd48b..0f35398d 100644 --- a/libr4d/r4d_attn_vit_h72_bf16.hip +++ b/libr4d/r4d_attn_vit_h72_bf16.hip @@ -531,6 +531,8 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) { * kernel steps by. */ const long long head_dim = r4d_geti_or(a, "head_dim", q->rank == 3 ? q->shape[2] : 72); if (head_dim != 72) return R4D_NO(RAD_E_SHAPE); + /* Every key of a segment is attended to; a window would be ignored, so it is refused. */ + if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_INVAL); auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) { long long width = 1; for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i]; diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip new file mode 100644 index 00000000..9d8008e1 --- /dev/null +++ b/libr4d/r4d_encoder_bf16.hip @@ -0,0 +1,1028 @@ +// The small ops an encoder issues between its GEMMs and its attention: a gated activation over two +// operands, the QK(V)-norm-and-rotary preamble over a fused projection, mean pooling over +// cu_seqlens segments, and the bf16 -> f32 widening of a pooled row. r4d_model_bf16.hip's rules +// hold here too: each kernel equals a libref function, reductions accumulate in f32 (seg_mean in +// f64, as ref does) and only the store narrows, and the transcendental functions are the accurate +// libm forms. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" + +#include +#include +#include + +namespace { + +constexpr uint32_t kThreads = 256; + +__device__ __forceinline__ float bf2f(uint16_t h) { + return __builtin_bit_cast(float, (uint32_t)h << 16); +} + +// ---------------------------------------------------------------------------- act_mul +// ref_act_mul: y = round(act(a)) * b. The activation is rounded to bf16 before the product +// because the unfused pair stores it. +template +__device__ __forceinline__ float act_of(float g) { + if (ACT == 0) return g / (1.0f + expf(-g)); + if (ACT == 1) return 0.5f * g * (1.0f + erff(g * 0.70710678118654752f)); + if (ACT == 3) return 1.0f / (1.0f + expf(-g)); + return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g))); +} + +// THE ROW AXIS IS GRID-STRIDED. A grid's y extent stops at 65535, and an elementwise op over the +// audio subsampler's (time, frequency) rows is 96000 of them: a launch of y = M runs nothing past +// row 65535. A row kernel takes M, launches min(M, kGridYMax) and walks the rest. +constexpr uint32_t kGridYMax = 65535; +static inline uint32_t grid_rows(int64_t M) { + return (uint32_t)(M < (int64_t)kGridYMax ? M : (int64_t)kGridYMax); +} + +template +__global__ __launch_bounds__(kThreads) void act_mul_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, 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 g = bf2f(f32_to_bf16(act_of(bf2f(a[(size_t)m * a_ld + i])))); + y[(size_t)m * y_ld + i] = f32_to_bf16(g * bf2f(b[(size_t)m * b_ld + i])); + } +} + +// ---------------------------------------------------------------------------- seg_mean +// ref_seg_mean: row s of y is the mean of x's rows [cu[s], cu[s+1]), summed in f64 and rounded +// once. A workgroup is 32 columns by 8 row lanes; each lane sums every eighth row of its column +// and the eight partial sums meet in LDS. An empty segment writes zeros. +__global__ __launch_bounds__(kThreads) void seg_mean_kernel( + const uint16_t* __restrict__ x, const int* __restrict__ cu, uint16_t* __restrict__ y, + uint32_t n, uint32_t x_ld, uint32_t y_ld) { + __shared__ double part[8][33]; + const uint32_t s = blockIdx.y; + const uint32_t col = threadIdx.x & 31, rl = threadIdx.x >> 5; + const uint32_t i = blockIdx.x * 32 + col; + const int b0 = cu[s], b1 = cu[s + 1]; + double acc = 0.0; + if (i < n) + for (int r = b0 + (int)rl; r < b1; r += 8) acc += (double)bf2f(x[(size_t)r * x_ld + i]); + part[rl][col] = acc; + __syncthreads(); + if (rl == 0 && i < n) { + double t = 0.0; + #pragma unroll + for (int k = 0; k < 8; ++k) t += part[k][col]; + const int len = b1 - b0; + y[(size_t)s * y_ld + i] = f32_to_bf16(len > 0 ? (float)(t / (double)len) : 0.0f); + } +} + +// ---------------------------------------------------------------------------- qk_norm_rope +// ref_qk_norm_rope over a fused [q heads | k heads | v heads] row, in place: each q and k head is +// RMS-normed against its gain and rounded to bf16 (the unfused pair stores the norm), then +// rotated; with v_norm each v head is RMS-normed with a unit gain and not rotated. +// +// ONE WORKGROUP A TOKEN, A WAVE A HEAD, THE HEAD IN REGISTERS. Lane l holds the head's elements +// l, l+32, l+64, ... (neox) or the pairs 2l, 2l+1, 2l+64, 2l+65, ... (gptj), which puts both +// halves of every rotary pair in the same lane: the norm is a wave sum and the rotation needs no +// exchange at all. The token's sin/cos are computed once into LDS for all its heads -- 4 KiB, so +// occupancy is not what LDS decides. A first form staged the token's whole fused row in LDS +// (12 KiB a workgroup at head_dim 512) and ran slower than a workgroup a (token, head). +// +// The layout needs head_dim a multiple of 32 and, for neox, rotary_dim / 2 a multiple of 32 (for +// gptj, head_dim a multiple of 64); the launcher refuses anything else. +constexpr uint32_t kQkThreads = 256; +constexpr uint32_t kQkMaxHalf = 512; // rotary pairs a head +constexpr int kQkMaxE = 32; // elements a lane: head_dim up to 1024 + +/* The `blocks` mode's sections: pairs a section, and the position component each one reads. */ +struct QkBlocks { + int n = 0; + int sec[8] = {}; + int comp[8] = {}; +}; + +// 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, + uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, + QkBlocks blk, uint32_t pplane) { + __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; + const uint32_t m = blockIdx.x; + const uint32_t n_rope = n_head + n_head_kv; + const uint32_t n_norm = n_rope + (v_norm ? n_head_kv : 0); + const uint32_t half = rot / 2; + uint16_t* row = qkv + (size_t)m * ld; + const float div = rscale != 0.0f ? rscale : 1.0f; + + if (MODE == 2) { + // Pair i of section c is the (i - start_c)-th of its block, at theta^(-j / sec[c]). + 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 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; + 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]); + } + } + __syncthreads(); + + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + const int E = (int)(head_dim / 32); + auto at = [&](int j) -> uint32_t { + return MODE == 1 ? 64u * (uint32_t)(j >> 1) + 2u * lane + (uint32_t)(j & 1) + : lane + 32u * (uint32_t)j; + }; + for (uint32_t hh = wave; hh < n_norm; hh += kQkThreads / 32) { + uint16_t* h = row + hh * head_dim; + float x[kQkMaxE]; + float ss = 0.0f; + #pragma unroll + for (int j = 0; j < kQkMaxE; ++j) + if (j < E) { x[j] = bf2f(h[at(j)]); ss += x[j] * x[j]; } + 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; + #pragma unroll + for (int j = 0; j < kQkMaxE; ++j) + if (j < E) { + const float g = is_v ? 1.0f : bf2f(w[at(j)]) + wadd; + x[j] = bf2f(f32_to_bf16(x[j] * sc * g)); + } + if (!is_v) { + if (MODE == 1) { + #pragma unroll + for (int j = 0; j < kQkMaxE; j += 2) { + const uint32_t i = at(j) / 2; + if (j < E && i < half) { + const float x0 = x[j], x1 = x[j + 1]; + x[j] = x0 * cs_s[i] - x1 * sn_s[i]; + x[j + 1] = x0 * sn_s[i] + x1 * cs_s[i]; + } + } + } else if (MODE == 0) { + const int hj = (int)(half / 32); + #pragma unroll + for (int j = 0; j < kQkMaxE / 2; ++j) + if (j < hj) { + const uint32_t i = lane + 32u * (uint32_t)j; + const float x0 = x[j], x1 = x[j + hj]; + x[j] = x0 * cs_s[i] - x1 * sn_s[i]; + x[j + hj] = x0 * sn_s[i] + x1 * cs_s[i]; + } + } else { + // Each section's block starts on a 32-channel slice. A section of 16 pairs is + // one slice, its partners in the other half-wave; a multiple of 32 pairs keeps + // both halves of a pair in the lane. (The launcher refuses anything else.) + int s0 = 0; + for (int c = 0; c < blk.n; ++c) { + const int sec = blk.sec[c], j0 = s0 / 16; + if (sec == 16) { + #pragma unroll + for (int j = 0; j < kQkMaxE; ++j) + if (j == j0) { + const float mine = x[j], other = swap16(x[j]); + const uint32_t i = (uint32_t)s0 + (lane & 15u); + x[j] = lane < 16 ? mine * cs_s[i] - other * sn_s[i] + : other * sn_s[i] + mine * cs_s[i]; + } + } else { + const int hj = sec / 32; + #pragma unroll + for (int j = 0; j < kQkMaxE; ++j) + if (j >= j0 && j < j0 + hj) { + const uint32_t i = (uint32_t)s0 + lane + 32u * (uint32_t)(j - j0); + const float x0 = x[j], x1 = x[j + hj]; + x[j] = x0 * cs_s[i] - x1 * sn_s[i]; + x[j + hj] = x0 * sn_s[i] + x1 * cs_s[i]; + } + } + s0 += sec; + } + } + } + #pragma unroll + for (int j = 0; j < kQkMaxE; ++j) + if (j < E) h[at(j)] = f32_to_bf16(x[j]); + } +} + +// ---------------------------------------------------------------------------- pool_rows +// ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to +// bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column. +__global__ __launch_bounds__(kThreads) void pool_rows_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t k, float mult, + 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 r = blockIdx.y; r < M; r += gridDim.y) { + float acc = 0.0f; + for (uint32_t j = 0; j < k; ++j) acc += bf2f(x[((size_t)r * k + j) * x_ld + i]); + const float mean = bf2f(f32_to_bf16(acc * (1.0f / (float)k))); + y[(size_t)r * y_ld + i] = f32_to_bf16(mean * mult); + } +} + +// ---------------------------------------------------------------------------- cast bf16 -> f32 +__global__ __launch_bounds__(kThreads) void widen_kernel( + const uint16_t* __restrict__ x, float* __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] = bf2f(x[(size_t)m * x_ld + i]); +} + +// ---------------------------------------------------------------------------- the audio tower +// Gemma 4's USM conformer: an elementwise rectifier and clamp, the subsampler's segment-wise +// convolution, the light-conv block's causal depthwise convolution, the relative-position table, +// and the local attention with a relative term. An audio pass is at most a few thousand frames +// (750 tokens for 30 s), so each kernel is the plain form -- a workgroup a row, a thread an +// element -- and equal to its libref function in arithmetic: f32 throughout, one rounding. + +// ref_relu. +__global__ __launch_bounds__(kThreads) void relu_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(v > 0.0f ? v : 0.0f); + } +} + +// ref_silu: x * sigmoid(x) with the sigmoid taken first, libref's act_silu term for term. The +// audio tower's feed-forward issues it on its own between two clipped linears. +__global__ __launch_bounds__(kThreads) void silu_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(v * (1.0f / (1.0f + expf(-v)))); + } +} + +// 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, + int b_f32, 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; + const float l = b_f32 ? ((const float*)lo)[0] : bf2f(((const uint16_t*)lo)[0]); + const float h = b_f32 ? ((const float*)hi)[0] : bf2f(((const uint16_t*)hi)[0]); + for (uint32_t m = blockIdx.y; m < M; m += gridDim.y) { + float v = bf2f(x[(size_t)m * x_ld + i]); + v = v < l ? l : v; + v = v > h ? h : v; + y[(size_t)m * y_ld + i] = f32_to_bf16(v); + } +} + +struct ConvGeom { + int W, cin, cout, kh, kw, st, pad, cdiv, vst, Wo, S; +}; + +// ref_conv2d. A workgroup an OUTPUT time row of the pass: it finds the segment whose output rows +// hold it (a scan over cu_seqlens, which is a handful of entries), and a thread computes output +// elements (width, channel) of that row. Rows no segment covers are left alone, as libref does. +__global__ __launch_bounds__(kThreads) void conv2d_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, + const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, + uint32_t y_ld) { + const int r = (int)blockIdx.x; + int t0 = -1, T = 0, to = 0; + for (int s = 0; s < g.S; ++s) { + const int c0 = cu[s], c1 = cu[s + 1]; + if (c0 % g.cdiv || c1 % g.cdiv || (c0 / g.cdiv) % g.st || c1 < c0) continue; + const int a = c0 / g.cdiv, Ts = c1 / g.cdiv - a; + if (Ts <= 0) continue; + const int To = (Ts + 2 * g.pad - g.kh) / g.st + 1, o0 = a / g.st; + if (r >= o0 && r < o0 + To) { t0 = a; T = Ts; to = r - o0; break; } + } + if (t0 < 0) return; + const int nel = g.Wo * g.cout; + for (int e = threadIdx.x; e < nel; e += kThreads) { + const int wo = e / g.cout, co = e % g.cout; + float acc = 0.0f; + for (int i = 0; i < g.kh; ++i) { + const int ti = to * g.st - g.pad + i; + if (ti < 0 || ti >= T) continue; + const int tg = t0 + ti; + if (valid && valid[(size_t)tg * g.vst] == 0) continue; + const uint16_t* xr = x + (size_t)tg * x_ld; + for (int j = 0; j < g.kw; ++j) { + const int wi = wo * g.st - g.pad + j; + if (wi < 0 || wi >= g.W) continue; + const uint16_t* xv = xr + (size_t)wi * g.cin; + const uint16_t* wv = w + (((size_t)co * g.cin) * g.kh + i) * g.kw + j; + for (int ci = 0; ci < g.cin; ++ci) + acc += bf2f(xv[ci]) * bf2f(wv[(size_t)ci * g.kh * g.kw]); + } + } + y[(size_t)r * y_ld + e] = f32_to_bf16(acc); + } +} + +// conv2d_kernel's arithmetic with each kernel row's input row and weights staged in LDS: the form +// for the audio subsampler's second convolution, 64 x 128 channels in and 32 x 32 out a row, +// where the plain kernel re-reads every weight from global memory for every output and spends +// 6 ms on a 30 s clip. Weights sit [j][ci][co] so the lanes of a wave -- consecutive output +// channels -- read consecutive LDS words, and each input element is one broadcast. A thread owns +// kConvEpt outputs strided by the workgroup, all of one output channel. The sum runs over i, j, +// ci in the plain kernel's order. +constexpr int kConvEpt = 4; +constexpr int kConvXs = 8192; /* W * cin, one input row */ +constexpr int kConvWs = 12288; /* kw * cin * cout, one kernel row's weights */ + +__global__ __launch_bounds__(kThreads) void conv2d_lds_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu, + const int* __restrict__ valid, uint16_t* __restrict__ y, ConvGeom g, uint32_t x_ld, + uint32_t y_ld) { + __shared__ uint16_t xs[kConvXs]; + __shared__ uint16_t ws[kConvWs]; + const int r = (int)blockIdx.x; + int t0 = -1, T = 0, to = 0; + for (int s = 0; s < g.S; ++s) { + const int c0 = cu[s], c1 = cu[s + 1]; + if (c0 % g.cdiv || c1 % g.cdiv || (c0 / g.cdiv) % g.st || c1 < c0) continue; + const int a = c0 / g.cdiv, Ts = c1 / g.cdiv - a; + if (Ts <= 0) continue; + const int To = (Ts + 2 * g.pad - g.kh) / g.st + 1, o0 = a / g.st; + if (r >= o0 && r < o0 + To) { t0 = a; T = Ts; to = r - o0; break; } + } + if (t0 < 0) return; + const int nel = g.Wo * g.cout, nx = g.W * g.cin, nw = g.kw * g.cin * g.cout; + const int tid = (int)threadIdx.x; + float acc[kConvEpt]; + #pragma unroll + for (int q = 0; q < kConvEpt; ++q) acc[q] = 0.0f; + for (int i = 0; i < g.kh; ++i) { + const int ti = to * g.st - g.pad + i; + if (ti < 0 || ti >= T) continue; + const int tg = t0 + ti; + if (valid && valid[(size_t)tg * g.vst] == 0) continue; + __syncthreads(); + const uint16_t* xr = x + (size_t)tg * x_ld; + for (int e = tid; e < nx; e += kThreads) xs[e] = xr[e]; + for (int e = tid; e < nw; e += kThreads) { + const int co = e % g.cout, rest = e / g.cout, ci = rest % g.cin, j = rest / g.cin; + ws[e] = w[(((size_t)co * g.cin + ci) * g.kh + i) * g.kw + j]; + } + __syncthreads(); + #pragma unroll + for (int q = 0; q < kConvEpt; ++q) { + const int e = tid + q * kThreads; + if (e >= nel) break; + const int wo = e / g.cout, co = e % g.cout; + float a = acc[q]; + for (int j = 0; j < g.kw; ++j) { + const int wi = wo * g.st - g.pad + j; + if (wi < 0 || wi >= g.W) continue; + const uint16_t* xv = xs + wi * g.cin; + const uint16_t* wv = ws + (size_t)j * g.cin * g.cout + co; + for (int ci = 0; ci < g.cin; ++ci) a += bf2f(xv[ci]) * bf2f(wv[(size_t)ci * g.cout]); + } + acc[q] = a; + } + } + #pragma unroll + for (int q = 0; q < kConvEpt; ++q) { + const int e = tid + q * kThreads; + if (e < nel) y[(size_t)r * y_ld + e] = f32_to_bf16(acc[q]); + } +} + +// ref_conv1d_dw. A thread a (row, channel); the segment found by a scan over cu_seqlens. +__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) { + 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) { + int t0 = -1; + for (int s = 0; s < S; ++s) { + const int c0 = cu[s], c1 = cu[s + 1]; + if (c0 % cdiv || c1 % cdiv || c1 < c0) continue; + if (t >= c0 / cdiv && t < c1 / cdiv) { t0 = c0 / cdiv; break; } + } + if (t0 < 0) continue; + float acc = 0.0f; + for (int j = 0; j < K; ++j) { + const int tt = t - (K - 1) + j; + if (tt < t0) continue; + acc += bf2f(x[(size_t)tt * x_ld + c]) * bf2f(w[(size_t)c * K + j]); + } + y[(size_t)t * y_ld + c] = f32_to_bf16(acc); + } +} + +// ref_rel_sinusoid, the same f32 steps with the accurate libm forms. +__global__ __launch_bounds__(kThreads) void rel_sinusoid_kernel( + uint16_t* __restrict__ y, uint32_t h, float inc, uint32_t y_ld) { + const uint32_t d = blockIdx.x; + for (uint32_t i = threadIdx.x; i < h; i += kThreads) { + const float inv = expf((float)i * -inc); + const float ang = (float)d * inv; + y[(size_t)d * y_ld + i] = f32_to_bf16(sinf(ang)); + y[(size_t)d * y_ld + h + i] = f32_to_bf16(cosf(ang)); + } +} + +// ref_attn_local_rel. A workgroup a (query row, head), a thread a head dimension; each of the at +// most left + 1 logits is a workgroup sum, then the softmax over them and the weighted sum of v. +constexpr uint32_t kLrThreads = 128; +constexpr int kLrMaxKeys = 64; + +struct LocalRelGeom { + int D, H, L, cdiv, S, pds_f32; + float cap, qs, ks; + uint32_t q_ld, k_ld, v_ld, r_ld, o_ld; +}; + +__global__ __launch_bounds__(kLrThreads) void attn_local_rel_kernel( + const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, + const uint16_t* __restrict__ v, const uint16_t* __restrict__ rk, const void* __restrict__ pds, + const int* __restrict__ cu, uint16_t* __restrict__ o, LocalRelGeom g) { + __shared__ float red[kLrThreads / 32]; + __shared__ float lg[kLrMaxKeys]; + const int i = (int)blockIdx.x, h = (int)blockIdx.y; + int t0 = -1; + for (int s = 0; s < g.S; ++s) { + const int c0 = cu[s], c1 = cu[s + 1]; + if (c0 % g.cdiv || c1 % g.cdiv || c1 < c0) continue; + if (i >= c0 / g.cdiv && i < c1 / g.cdiv) { t0 = c0 / g.cdiv; break; } + } + if (t0 < 0) return; + const int j0 = i - g.L > t0 ? i - g.L : t0, nk = i - j0 + 1; + const int tid = (int)threadIdx.x; + for (int jj = 0; jj < nk; ++jj) { + const int j = j0 + jj; + float part = 0.0f; + for (int d = tid; d < g.D; d += kLrThreads) { + const float x = g.pds_f32 ? ((const float*)pds)[d] : bf2f(((const uint16_t*)pds)[d]); + float sp = x > 20.0f ? x : (x > 0.0f ? x + log1pf(expf(-x)) : log1pf(expf(x))); + if (!g.pds_f32) sp = bf2f(f32_to_bf16(sp)); + const float qf = bf2f(q[(size_t)i * g.q_ld + h * g.D + d]) * g.qs * sp; + part += qf * (bf2f(k[(size_t)j * g.k_ld + h * g.D + d]) * g.ks); + part += qf * bf2f(rk[(size_t)(i - j) * g.r_ld + h * g.D + d]); + } + part = r4d_wave_sum(part); + if ((tid & 31) == 0) red[tid >> 5] = part; + __syncthreads(); + if (tid == 0) { + float s = 0.0f; + for (uint32_t w = 0; w < kLrThreads / 32; ++w) s += red[w]; + lg[jj] = g.cap * tanhf(s / g.cap); + } + __syncthreads(); + } + float mx = -INFINITY; + for (int jj = 0; jj < nk; ++jj) mx = lg[jj] > mx ? lg[jj] : mx; + float sum = 0.0f; + for (int jj = 0; jj < nk; ++jj) sum += expf(lg[jj] - mx); + for (int d = tid; d < g.D; d += kLrThreads) { + float acc = 0.0f; + for (int jj = 0; jj < nk; ++jj) + acc += expf(lg[jj] - mx) / sum * bf2f(v[(size_t)(j0 + jj) * g.v_ld + h * g.D + d]); + o[(size_t)i * g.o_ld + h * g.D + d] = f32_to_bf16(acc); + } +} + +} // namespace + +// ============================================================== launchers + +// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid. +extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, int a_ld, int b_ld, + int y_ld, long stream) { + if (!a || !b || !y) return -1; + if (M <= 0 || n <= 0 || act < 0 || act > 3) return -2; + const dim3 grid((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)); +#define R4D_AM(A) \ + hipLaunchKernelGGL(act_mul_kernel, grid, 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, (uint32_t)M) + if (act == 0) R4D_AM(0); + else if (act == 1) R4D_AM(1); + else if (act == 2) R4D_AM(2); + else R4D_AM(3); +#undef R4D_AM + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld, int y_ld, + long stream) { + if (!x || !cu || !y) return -1; + if (S <= 0 || n <= 0) return -2; + hipLaunchKernelGGL(seg_mean_kernel, dim3((uint32_t)((n + 31) / 32), (uint32_t)S), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, + (const int*)cu, (uint16_t*)y, (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +// mode: 0 neox, 1 gptj, 2 blocks (`blk` and the position plane stride `pplane` used only there). +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 || head_dim % 32 || + mode < 0 || mode > 2) + return -2; + if (mode == 1 && head_dim % 64) return -2; + if (mode == 0 && (rot / 2) % 32) return -2; + QkBlocks b{}; + if (mode == 2) { + if (!blk || blk->n <= 0 || blk->n > 8) return -2; + b = *blk; + int total = 0; + for (int c = 0; c < b.n; ++c) { + if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) return -2; + total += b.sec[c]; + } + if (2 * total != rot) return -2; + } +#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, \ + (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, eps, rscale, wadd, \ + (uint32_t)ld, b, (uint32_t)pplane) + if (mode == 1) R4D_QN(1); + else if (mode == 2) R4D_QN(2); + else R4D_QN(0); +#undef R4D_QN + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_pool_rows_bf16(long x, long y, int rows, int n, int k, float mult, int x_ld, + int y_ld, long stream) { + if (!x || !y) return -1; + if (rows <= 0 || n <= 0 || k <= 0) return -2; + hipLaunchKernelGGL(pool_rows_kernel, dim3((uint32_t)((n + kThreads - 1) / kThreads), + grid_rows(rows)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, + (uint32_t)n, (uint32_t)k, mult, (uint32_t)x_ld, (uint32_t)y_ld, + (uint32_t)rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_widen_bf16_f32(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(widen_kernel, dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (float*)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; + hipLaunchKernelGGL(relu_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; + hipLaunchKernelGGL(silu_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_clamp_bf16(long x, long lo, long hi, int b_f32, long y, int M, int n, int x_ld, + int y_ld, long stream) { + if (!x || !lo || !hi || !y) return -1; + if (M <= 0 || n <= 0) return -2; + hipLaunchKernelGGL(clamp_kernel, dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, + (const void*)lo, (const void*)hi, b_f32, (uint16_t*)y, (uint32_t)n, + (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* `rows_out` is the output operand's rows: a workgroup each, every one a segment does not cover + * returning at once. */ +extern "C" int r4d_conv2d_bf16(long x, long w, long cu, long valid, long y, int rows_out, + const ConvGeom* g, int x_ld, int y_ld, long stream) { + if (!x || !w || !cu || !y || !g) return -1; + if (rows_out <= 0 || g->Wo <= 0 || g->S <= 0) return -2; + const bool lds = g->W * g->cin <= kConvXs && g->kw * g->cin * g->cout <= kConvWs && + g->Wo * g->cout <= kConvEpt * (int)kThreads; + if (lds) + hipLaunchKernelGGL(conv2d_lds_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0, + (hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w, + (const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, + (uint32_t)y_ld); + else + hipLaunchKernelGGL(conv2d_kernel, dim3((uint32_t)rows_out), dim3(kThreads), 0, + (hipStream_t)stream, (const uint16_t*)x, (const uint16_t*)w, + (const int*)cu, (const int*)valid, (uint16_t*)y, *g, (uint32_t)x_ld, + (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +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) { + 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); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_rel_sinusoid_bf16(long y, int rows, int n, double max_timescale, int y_ld, + long stream) { + if (!y) return -1; + if (rows <= 0 || n <= 0 || (n & 1)) return -2; + const int h = n / 2; + const float inc = (float)(std::log(max_timescale / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + hipLaunchKernelGGL(rel_sinusoid_kernel, dim3((uint32_t)rows), dim3(kThreads), 0, + (hipStream_t)stream, (uint16_t*)y, (uint32_t)h, inc, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_attn_local_rel_bf16(long q, long k, long v, long rk, long pds, long cu, long o, + int rows, const LocalRelGeom* g, long stream) { + if (!q || !k || !v || !rk || !pds || !cu || !o || !g) return -1; + if (rows <= 0 || g->D <= 0 || g->H <= 0 || g->L < 0 || g->L + 1 > kLrMaxKeys) return -2; + hipLaunchKernelGGL(attn_local_rel_kernel, dim3((uint32_t)rows, (uint32_t)g->H), + dim3(kLrThreads), 0, (hipStream_t)stream, (const uint16_t*)q, + (const uint16_t*)k, (const uint16_t*)v, (const uint16_t*)rk, + (const void*)pds, (const int*)cu, (uint16_t*)o, *g); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +// ============================================================== the plugin ABI entry points + +static inline int dt_bf16(const RadTensor* t) { + return (t && t->dtype == RAD_BF16) ? RAD_OK : RAD_E_DTYPE; +} +#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) + +/* ------------------------------------------------------------------ act_mul */ +extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) { + const RadTensor* A = r4d_opt(a, 0); + const RadTensor* B = r4d_opt(a, 1); + const RadTensor* Y = r4d_opt(a, 2); + 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 char* act = r4d_gets(a, "act"); + int ai = -1; + if (act && !std::strcmp(act, "silu")) ai = 0; + else if (act && !std::strcmp(act, "gelu")) ai = 1; + else if (act && !std::strcmp(act, "gelu_tanh")) ai = 2; + else if (act && !std::strcmp(act, "sigmoid")) ai = 3; + if (ai < 0) 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); + long long M = 0, Ma = 0, Mb = 0; + const long long y_ld = r4d_rows_pitch(Y, n, &M); + const long long a_ld = r4d_rows_pitch(A, n, &Ma); + const long long b_ld = r4d_rows_pitch(B, n, &Mb); + if (y_ld < 0 || a_ld < 0 || b_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Ma < M || Mb < M) return R4D_NO(RAD_E_SHAPE); + return r4d_act_mul_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, ai, (int)a_ld, + (int)b_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK + : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ seg_mean */ +extern "C" int r4d_rad_seg_mean(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* cu = r4d_opt(a, 1); + const RadTensor* Y = r4d_opt(a, 2); + if (!X || !cu || !Y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(X)); + R4D_NEED(dt_bf16(Y)); + if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); + 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); + const long long S = r4d_numel(cu) - 1; + long long Mx = 0, My = 0; + const long long x_ld = r4d_rows_pitch(X, n, &Mx); + const long long y_ld = r4d_rows_pitch(Y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (My < S) return R4D_NO(RAD_E_SHAPE); + return r4d_seg_mean_bf16(r4d_addr(X), r4d_addr(cu), r4d_addr(Y), (int)S, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ qk_norm_rope */ +enum { QN_QKV = 0, QN_POS, QN_QW, QN_KW }; + +static int parse_ints(const char* v, int* out, int max) { + int n = 0; + while (v && *v && n < max) { + char* end = nullptr; + const long x = std::strtol(v, &end, 10); + if (end == v) break; + out[n++] = (int)x; + v = end; + } + return n; +} + +extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { + const RadTensor* qkv = r4d_opt(a, QN_QKV); + 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); + 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); + 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) + return R4D_NO(RAD_E_SHAPE); + /* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a + * 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */ + if (hd % 32 || hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + 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, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); + QkBlocks blk{}; + long long M = 0, pplane = 0; + if (md == 2) { + blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8); + if (blk.n <= 0) return R4D_NO(RAD_E_SHAPE); + for (int c = 0; c < blk.n; ++c) blk.comp[c] = c; + if (const char* cs = r4d_gets(a, "comps")) + if (parse_ints(cs, blk.comp, 8) != blk.n) return R4D_NO(RAD_E_SHAPE); + if (pos->rank != 2) return R4D_NO(RAD_E_SHAPE); + for (int c = 0; c < blk.n; ++c) + if (blk.comp[c] < 0 || blk.comp[c] >= pos->shape[0]) return R4D_NO(RAD_E_SHAPE); + M = pos->shape[1]; + pplane = pos->stride[0]; + } else { + 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 (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, + (int)r4d_geti_or(a, "v_norm", 0), + (float)r4d_getf(a, "theta", 10000.0), + (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); + if (e == -2) return R4D_NO(RAD_E_SHAPE); + return e == 0 ? RAD_OK : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ pool_rows */ +extern "C" int r4d_rad_pool_rows(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)); + R4D_NEED(dt_bf16(Y)); + const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0); + if (n <= 0 || k <= 0) return R4D_NO(RAD_E_SHAPE); + long long Mx = 0, My = 0; + const long long x_ld = r4d_rows_pitch(X, n, &Mx); + const long long y_ld = r4d_rows_pitch(Y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mx <= 0 || Mx % k || My < Mx / k) return R4D_NO(RAD_E_SHAPE); + return r4d_pool_rows_bf16(r4d_addr(X), r4d_addr(Y), (int)(Mx / k), (int)n, (int)k, + (float)r4d_getf(a, "mult", 1.0), (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ cast bf16 -> f32 */ +extern "C" int r4d_rad_cast_widen(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_F32) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, 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 r4d_widen_bf16_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ the audio tower */ + +extern "C" int r4d_rad_relu(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)); + R4D_NEED(dt_bf16(Y)); + 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 r4d_relu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +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); + R4D_NEED(dt_bf16(X)); + R4D_NEED(dt_bf16(Y)); + 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 r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_clamp(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* L = r4d_opt(a, 1); + const RadTensor* H = r4d_opt(a, 2); + const RadTensor* Y = r4d_opt(a, 3); + if (!X || !L || !H || !Y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(X)); + R4D_NEED(dt_bf16(Y)); + if (L->dtype != H->dtype || (L->dtype != RAD_BF16 && L->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); + if (r4d_numel(L) < 1 || r4d_numel(H) < 1) return R4D_NO(RAD_E_SHAPE); + 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 r4d_clamp_bf16(r4d_addr(X), r4d_addr(L), r4d_addr(H), L->dtype == RAD_F32, + r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_conv2d(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* Wt = r4d_opt(a, 1); + const RadTensor* cu = r4d_opt(a, 2); + const RadTensor* V = r4d_opt(a, 3); + const RadTensor* Y = 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 (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE); + if (V && (V->dtype != RAD_I32 || !r4d_contig(V))) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(Wt)) return R4D_NO(RAD_E_STRIDE); + ConvGeom g{}; + g.W = (int)r4d_geti_or(a, "width", 0); + g.cin = (int)r4d_geti_or(a, "cin", 0); + g.cout = (int)r4d_geti_or(a, "cout", 0); + g.kh = (int)r4d_geti_or(a, "kh", 0); + g.kw = (int)r4d_geti_or(a, "kw", 0); + g.st = (int)r4d_geti_or(a, "stride", 1); + g.pad = (int)r4d_geti_or(a, "pad", 0); + g.cdiv = (int)r4d_geti_or(a, "cu_div", 1); + g.vst = (int)r4d_geti_or(a, "valid_stride", 1); + if (g.W <= 0 || g.cin <= 0 || g.cout <= 0 || g.kh <= 0 || g.kw <= 0 || g.st <= 0 || g.pad < 0 || + g.cdiv <= 0 || g.vst <= 0) + return R4D_NO(RAD_E_SHAPE); + g.Wo = (g.W + 2 * g.pad - g.kw) / g.st + 1; + g.S = (int)(r4d_numel(cu) - 1); + if (g.Wo <= 0 || r4d_numel(Wt) < (long long)g.cout * g.cin * g.kh * g.kw) + return R4D_NO(RAD_E_SHAPE); + long long Mx = 0, My = 0; + const long long x_ld = r4d_rows_pitch(X, (long long)g.W * g.cin, &Mx); + const long long y_ld = r4d_rows_pitch(Y, (long long)g.Wo * g.cout, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mx <= 0 || My <= 0) return R4D_NO(RAD_E_SHAPE); + return r4d_conv2d_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), V ? r4d_addr(V) : 0, + r4d_addr(Y), (int)My, &g, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) { + const RadTensor* X = r4d_opt(a, 0); + const RadTensor* Wt = r4d_opt(a, 1); + const RadTensor* cu = r4d_opt(a, 2); + const RadTensor* Y = r4d_opt(a, 3); + 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 (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); + 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); + 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); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (My <= 0 || Mx < My) return R4D_NO(RAD_E_SHAPE); + return 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) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) { + const RadTensor* Y = r4d_opt(a, 0); + if (!Y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(Y)); + const long long n = r4d_geti_or(a, "n", 0); + if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE); + long long M = 0; + const long long y_ld = r4d_rows_pitch(Y, n, &M); + if (y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + /* libref reads the parameter as a float before widening it; the same here, so a timescale + * that is not a float is rounded in both. */ + const double mt = (double)(float)r4d_getf(a, "max_timescale", 10000.0); + return r4d_rel_sinusoid_bf16(r4d_addr(Y), (int)M, (int)n, mt, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_attn_local_rel(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, 0); + const RadTensor* k = r4d_opt(a, 1); + const RadTensor* v = r4d_opt(a, 2); + const RadTensor* rk = r4d_opt(a, 3); + const RadTensor* pds = r4d_opt(a, 4); + const RadTensor* cu = r4d_opt(a, 5); + const RadTensor* o = r4d_opt(a, 6); + if (!q || !k || !v || !rk || !pds || !cu || !o) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(q)); + R4D_NEED(dt_bf16(k)); + R4D_NEED(dt_bf16(v)); + R4D_NEED(dt_bf16(rk)); + R4D_NEED(dt_bf16(o)); + if (pds->dtype != RAD_BF16 && pds->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(pds)) return R4D_NO(RAD_E_STRIDE); + if (r4d_geti_or(a, "right", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED); + LocalRelGeom g{}; + g.D = (int)r4d_geti_or(a, "head_dim", 0); + g.H = (int)r4d_geti_or(a, "n_head", 0); + g.L = (int)r4d_geti_or(a, "left", 0); + g.cdiv = (int)r4d_geti_or(a, "cu_div", 1); + g.cap = (float)r4d_getf(a, "softcap", 0.0); + if (g.D <= 0 || g.H <= 0 || g.L < 0 || g.L + 1 > kLrMaxKeys || g.cdiv <= 0 || !(g.cap > 0.0f)) + return R4D_NO(RAD_E_SHAPE); + const long long Wd = (long long)g.H * g.D; + if (r4d_numel(pds) < g.D || r4d_numel(rk) < (long long)(g.L + 1) * Wd) return R4D_NO(RAD_E_SHAPE); + long long Mq = 0, Mk = 0, Mv = 0, Mr = 0, Mo = 0; + const long long q_ld = r4d_rows_pitch(q, Wd, &Mq), k_ld = r4d_rows_pitch(k, Wd, &Mk); + const long long v_ld = r4d_rows_pitch(v, Wd, &Mv), r_ld = r4d_rows_pitch(rk, Wd, &Mr); + const long long o_ld = r4d_rows_pitch(o, Wd, &Mo); + if (q_ld < 0 || k_ld < 0 || v_ld < 0 || r_ld < 0 || o_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mo <= 0 || Mq < Mo || Mk < Mo || Mv < Mo) return R4D_NO(RAD_E_SHAPE); + g.S = (int)(r4d_numel(cu) - 1); + g.pds_f32 = pds->dtype == RAD_F32; + g.qs = (float)(1.0 / std::sqrt((double)g.D) / std::log(2.0)); + g.ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); + g.q_ld = (uint32_t)q_ld; g.k_ld = (uint32_t)k_ld; g.v_ld = (uint32_t)v_ld; + g.r_ld = (uint32_t)r_ld; g.o_ld = (uint32_t)o_ld; + return r4d_attn_local_rel_bf16(r4d_addr(q), r4d_addr(k), r4d_addr(v), r4d_addr(rk), + r4d_addr(pds), r4d_addr(cu), r4d_addr(o), (int)Mo, &g, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index efa86604..61e2983a 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -415,15 +415,12 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre * half-of-an-operand problem. Three launches an attention layer becoming one is what the fusion * bought; the three are named here. * - * `act` silu IS DECLINED, and not because the arithmetic differs -- `silu` is an op of the - * vocabulary and `f2bf(gv / (1.0f + expf(-gv)))` is what a silu step would have to compute. It is - * declined because THIS PLUGIN HAS NO `silu` ROW: libr4d declares `sigmoid` (sigmoid_bf16) and - * `silu_mul` (silu_mul_bf16) and no bare `silu`, so the only implementation a caller could reach - * is libref's, whose `act_silu(x)` is `x * act_sigmoid(x)` -- two f32 roundings where this - * kernel does one divide. A chain that resolved there would report a difference in the last bit of - * every element and call it a fault in the kernel, and a false failure is worse than a skip. A - * libr4d `silu` row spelled `x / (1 + expf(-x))` would close the gap; without one the decline - * stands. Nothing in the tree issues this row with silu -- the gated attention's gate is a + * `act` silu IS DECLINED because the arithmetic differs in the last bit. The chain's `silu` step + * resolves to silu_bf16 or libref, and both compute libref's `act_silu(x)`, `x * act_sigmoid(x)` + * -- two f32 roundings where this kernel does one divide, `f2bf(gv / (1.0f + expf(-gv)))`. A + * chain checked against it would report a difference in the last bit of many elements and call it + * a fault in the kernel, and a false failure is worse than a skip. Accepting silu needs this + * kernel to take the sigmoid first as well. Nothing in the tree issues this row with silu -- the gated attention's gate is a * sigmoid, which is why the shim's `mode` defaults to 1. * * TMP(0) is act(gate): an [M, n] bf16 plane the fusion genuinely never writes, so it is a diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 61f0b17e..1539c9d8 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -100,9 +100,11 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { // vocab-parallel: ids stay global, a rank subtracts the offset, and a token belonging to another // rank takes the same zero-row path the padding id takes. Summing the ranks then reconstructs x. // At vocab_off = 0 this is the plain gather, to the bit. +// `mult` multiplies every gathered entry, the product rounded once (Gemma's sqrt(hidden)); 1 is the +// plain copy, to the bit. __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x, - uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld) { + uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) { const uint32_t m = blockIdx.x; const int32_t id = tok[m] - vocab_off; uint16_t* __restrict__ dst = x + (size_t)m * x_ld; @@ -111,7 +113,11 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( return; } const uint16_t* __restrict__ src = wte + (size_t)id * n_embd; - for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i]; + if (mult == 1.0f) { + for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i]; + return; + } + for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf2f(src[i]) * mult); } // ---------------------------------------------------------------------------- embed_lookup_q @@ -251,7 +257,7 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel( template __global__ __launch_bounds__(THR) void rmsnorm_kernel( const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, - uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t y_ld) { + 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; @@ -262,8 +268,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( 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 = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); - yr[i] = f32_to_bf16(bf2f(xr[i]) * s * (g + wadd)); + const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); + yr[i] = f32_to_bf16(bf2f(xr[i]) * s * (g + wadd) * mult); } } @@ -272,15 +278,16 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( // against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is // what makes a bias add this op instead of a second one, and the narrowness is the point -- silent // broadcasting of an arbitrary shape is how a shape bug becomes a plausible number. +// `b_step` 0 reads one element for the whole row -- with b_ld 0 too, a scalar for the whole op. __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 n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step) { 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 = bf2f(ar[i]), v = bf2f(br[i]); + const float u = bf2f(ar[i]), v = bf2f(br[i * b_step]); yr[i] = f32_to_bf16(mul ? u * v : u + v); } } @@ -579,20 +586,20 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( * the launch has to be describable, and writing the geometry twice is the one thing ABI v10's * contract says not to do. One body, two ways in. */ static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab, - int vocab_off, int x_ld, const R4dSink& sk) { + int vocab_off, int x_ld, float mult, const R4dSink& sk) { if (!tok || !wte || !x) return -1; if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2; if (!x_ld) x_ld = n_embd; return R4D_EMIT(sk, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (const int32_t*)tok, (const uint16_t*)wte, (uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off, - (uint32_t)x_ld) == RAD_OK ? 0 : -4; + (uint32_t)x_ld, mult) == RAD_OK ? 0 : -4; } extern "C" int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, long stream) { R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; - return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, sk); + return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, 1.0f, sk); } /* The quad walk when the width, the pitch and both bases allow its 4- and 8-byte accesses (a bf16 @@ -674,10 +681,11 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d return scatter_rows_u8_emit(v, idx, x, M, n, dst_rows, v_ld, x_ld, sk); } -// `w_f32` says whether the gain is f32 (every norm gain the architecture plugins declare) or bf16. -extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, - int w_f32, int x_ld, int y_ld, long stream) { - if (!x || !w || !y) return -1; +// `w_f32` says whether the gain is f32 (every norm gain the architecture plugins declare) or bf16; +// a null `w` is a gain of one. `mult` scales the row before its one rounding (rmsnorm's `mult`). +extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd, + float mult, int w_f32, int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; @@ -691,7 +699,7 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, #define R4D_RN_T(wf, T) \ hipLaunchKernelGGL((rmsnorm_kernel), dim3((uint32_t)M), dim3(T), 0, \ (hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \ - (uint32_t)n, eps, wadd, (uint32_t)x_ld, (uint32_t)y_ld) + (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld) #define R4D_RN(wf) \ do { if (thr == 1024) R4D_RN_T(wf, 1024); \ else if (thr == 512) R4D_RN_T(wf, 512); \ @@ -703,17 +711,26 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, return hipGetLastError() == hipSuccess ? 0 : -4; } +/* The unscaled form, the entry point every caller before `mult` used: times one is exact. */ +extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, + int w_f32, int x_ld, int y_ld, long stream) { + return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream); +} + // `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the // caller passes a b_ld of zero and every row reads the same n elements. +// b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows. extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, int a_ld, int b_ld, int y_ld, long stream) { if (!a || !b || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!a_ld) a_ld = n; if (!y_ld) y_ld = n; + const uint32_t b_step = b_ld < 0 ? 0u : 1u; + 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); + (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -1002,9 +1019,10 @@ static int rad_embed_lookup_body(const RadArgs* a, const R4dSink& sk) { if (x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); + const float mult = (float)r4d_getf(a, "mult", 1.0); return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x), (int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld, - sk) == 0 ? RAD_OK : RAD_E_DEVICE; + mult, sk) == 0 ? RAD_OK : RAD_E_DEVICE; } R4D_ENTRY(r4d_rad_embed_lookup, rad_embed_lookup_body) @@ -1201,9 +1219,25 @@ 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 || !w || !y) return R4D_NO(RAD_E_INVAL); + if (!x || !y) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_bf16(x)); R4D_NEED(dt_bf16(y)); + /* An ABSENT gain is one: a norm with no scale (Gemma 4's value norm, its multimodal + * embedder's pre-projection norm). `wadd` belongs to a gain and is refused without one. */ + if (!w) { + 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); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + return r4d_rmsnorm_mult_bf16(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n, + (float)r4d_getf(a, "eps", 1e-6), 0.0f, + (float)r4d_getf(a, "mult", 1.0), 0, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + } if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); /* THE GAIN IS THE ONE OPERAND THAT IS NOT bf16. Every architecture plugin here declares its * norm gains RAD_F32 -- a few thousand elements against gigabytes of weights, and the norm is @@ -1223,7 +1257,8 @@ 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); - return r4d_rmsnorm_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd, + 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 : RAD_E_DEVICE; } @@ -1272,6 +1307,32 @@ static int binary(const RadArgs* a, int mul, RadStream s) { extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0, s); } 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) -- the binary kernel's two broadcast forms. */ +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 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); + long long w_ld; + 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); + 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; +} + /* ------------------------------------------------------------------ sigmoid */ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index dcaef1ed..7e2c7d86 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -90,6 +90,7 @@ int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*); int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*); int r4d_rad_attn_vit (const RadArgs*, RadStream); +int r4d_rad_attn_dense (const RadArgs*, RadStream); /* 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 is 8 here against the gqa6 leg's 10 -- which is the row's constraint value. */ @@ -409,6 +410,19 @@ int r4d_rad_gather_rows_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int r4d_rad_rmsnorm (const RadArgs*, RadStream); int r4d_rad_add (const RadArgs*, RadStream); int r4d_rad_mul (const RadArgs*, RadStream); +int r4d_rad_mul_weight (const RadArgs*, RadStream); +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_pool_rows (const RadArgs*, RadStream); +int r4d_rad_relu (const RadArgs*, RadStream); +int r4d_rad_silu (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); +int r4d_rad_rel_sinusoid (const RadArgs*, RadStream); +int r4d_rad_attn_local_rel (const RadArgs*, RadStream); int r4d_rad_sigmoid (const RadArgs*, RadStream); int r4d_rad_fill (const RadArgs*, RadStream); int r4d_rad_silu_mul (const RadArgs*, RadStream); @@ -466,6 +480,7 @@ int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_binary (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_layernorm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_grid_embed (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index d706234f..f37624e9 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -191,6 +191,8 @@ static const RadParamSpec pAttnDense[] = { * cu_seqlens segments. Absent, the shim passes the total token count, which is a valid bound * and picks the tall arm -- a speed choice, never a correctness one. */ P_INTO("max_seqlen"), + /* attn_paged's window over a segment's own positions (docs/OPS.md); 0 is none. */ + P_INTO("window"), }; static const RadOperandSpec oAttnDense[] = { { "q", RAD_OPD_IN, 0 }, @@ -1520,10 +1522,12 @@ static const RadParamSpec pRmsNorm[] = { P_F64("eps"), { "dtype", RAD_P_STR, RAD_REQUIRED }, P_F64O("wadd"), + P_F64O("mult"), /* scales the row before its one rounding */ }; +/* `w` optional: absent, the gain is one. */ static const RadOperandSpec oRmsNorm[] = { { "x", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_WEIGHT, 0 }, + { "w", RAD_OPD_WEIGHT, 1 }, { "y", RAD_OPD_OUT, 0 }, }; @@ -1537,6 +1541,90 @@ static const RadOperandSpec oBinary[] = { { "b", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pActMul[] = { + P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype"), +}; +/* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */ +static const RadParamSpec pSegMean[] = { + P_INT("M"), P_INT("n"), P_STR("dtype"), +}; +static const RadOperandSpec oSegMean[] = { + { "x", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +/* docs/OPS.md's `qk_norm_rope`: a fused [q | k | v] row in place, theta and not a table. */ +static const RadParamSpec pQkNormRope[] = { + P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), + P_F64("eps"), P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"), P_F64O("wadd"), + P_INTO("v_norm"), P_STRO("sections"), P_STRO("comps"), +}; +/* `M` is the INPUT row count, a multiple of `k`. */ +static const RadParamSpec pPoolRows[] = { + P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"), +}; +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 }, +}; +/* `scalar` 1 says `w` is one element rather than one row -- for the shape description; the shim + * reads it off the operand. */ +static const RadParamSpec pMulWeight[] = { + P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar"), +}; +/* The audio (USM conformer) tower's operators; libref's lists, field for field. */ +static const RadOperandSpec oClamp[] = { + { "x", RAD_OPD_IN, 0 }, + { "lo", RAD_OPD_WEIGHT, 0 }, + { "hi", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pConv2d[] = { + P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), P_INT("kh"), P_INT("kw"), + P_INT("stride"), P_INT("pad"), P_INTO("cu_div"), P_INTO("valid_stride"), P_STR("dtype"), +}; +static const RadOperandSpec oConv2d[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "valid", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pConv1dDw[] = { + P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype"), +}; +static const RadOperandSpec oConv1dDw[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pRelSin[] = { + P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype"), +}; +static const RadOperandSpec oRelSin[] = { + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pAttnLocalRel[] = { + P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("left"), P_INT("right"), + P_F64("softcap"), P_INTO("cu_div"), P_STR("dtype"), +}; +static const RadOperandSpec oAttnLocalRel[] = { + { "q", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "relk", RAD_OPD_IN, 0 }, + { "pds", RAD_OPD_WEIGHT, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oMulWeight[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadOperandSpec oGateUp[] = { { "gate_up", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, @@ -1653,6 +1741,17 @@ static const RadParamSpec pEmbed[] = { * libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */ { "wscale", RAD_P_F64, RAD_OPTIONAL }, }; +/* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's + * sqrt(hidden)); libref's list, which embed_lookup_q does not share. */ +static const RadParamSpec pEmbedM[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n_embd", RAD_P_INT, RAD_REQUIRED }, + { "n_vocab", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, + { "wscale", RAD_P_F64, RAD_OPTIONAL }, + { "mult", RAD_P_F64, RAD_OPTIONAL }, +}; static const RadOperandSpec oEmbed[] = { { "tokens", RAD_OPD_IN, 0 }, { "wte", RAD_OPD_WEIGHT, 0 }, @@ -1836,10 +1935,45 @@ static const RadOpSchema kSchemas[] = { "y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts " "along rows, and nothing else broadcasts at all."), 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 " + "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."), SCHEMA("silu_mul", pMnDtype, oGateUp, "y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, " "which is the order rad-convert fuses gate_proj and up_proj in."), + SCHEMA("act_mul", pActMul, oBinary, + "y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before " + "the product: silu_mul with its two halves in two operands."), + SCHEMA("seg_mean", pSegMean, oSegMean, + "Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 " + "and rounded once; an empty segment is zeros."), + 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."), + 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("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, + "A 2-D convolution over (time, width), channels innermost, w [cout, cin, kh, kw]. Each " + "cu_seqlens segment (rows cu/cu_div) is convolved on its own with zero padding at its " + "edges; its output rows start at cu/(cu_div*stride). With `valid`, input row t reads " + "as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding."), + SCHEMA("conv1d_dw", pConv1dDw, oConv1dDw, + "Causal depthwise convolution over time, w [C, 1, k], rows before the segment's start " + "(cu/cu_div) reading as zeros. f32 sum, one rounding."), + SCHEMA("rel_sinusoid", pRelSin, oRelSin, + "The sinusoidal relative-position table: row d is sin(d * inv[i]) then cos(d * inv[i]), " + "inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)), in f32, rounded once."), + SCHEMA("attn_local_rel", pAttnLocalRel, oAttnLocalRel, + "Local attention with a relative-position term and a softcap (Gemma 4's audio): query i " + "of a segment sees keys j with 0 <= i - j <= left; qf = q * head_dim^-0.5/ln2 * " + "softplus(pds); logit = qf.k * ln(1+e)/ln2 + qf.relk[i-j], softcapped; softmax; .v."), SCHEMA("fill", pFill, oFill, "y = value, every element of an [M, n] extent (default 0). The op a rank issues where " "it computes nothing and a reader downstream -- an all-reduce, a residual -- still " @@ -1874,7 +2008,7 @@ static const RadOpSchema kSchemas[] = { SCHEMA("kv_store", pKvStore, oKvStore, "scatter k and v into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim] -- K at " "[.., d] and V at [.., head_dim + d]. A negative slot stores nothing."), - SCHEMA("embed_lookup", pEmbed, oEmbed, + SCHEMA("embed_lookup", pEmbedM, oEmbed, "the embedding gather. A negative token id writes a zero row, and so does one outside " "[vocab_offset, vocab_offset + n_vocab) -- which is what makes the table shardable " "across the vocabulary, the symmetry lm_head already had. Ids stay GLOBAL; summing the " @@ -1959,7 +2093,8 @@ static const RadOpSchema kSchemas[] = { "merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 " "with one scale per 128 columns into `q8` / `q8_scale`."), SCHEMA("attn_dense", pAttnDense, oAttnDense, - "dense non-causal attention over cu_seqlens segments -- the vision tower's."), + "dense attention over cu_seqlens segments, with attn_paged's window rule over a " + "segment's positions."), SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate, "split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate " "copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a " @@ -2407,6 +2542,10 @@ static const RadConstraint cAttnDecodeH128G8Bf16[] = { /* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's * `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The * predicate -- "bf16, and nothing else" -- is unchanged. */ +/* NO CONSTRAINT ON `window`. It is optional in the schema, a tower without one does not pass it, + * and a constraint whose key the geometry lacks does not hold -- so C_EQ("window", 0) here made + * this row unreachable for every Qwen vision tower. The kernel attends to the whole segment and + * refuses a non-zero window at launch instead (r4d_rad_attn_vit). */ static const RadConstraint cAttnVit[] = { C_EQ("head_dim", 72), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; @@ -2423,6 +2562,31 @@ static const RadConstraint cAttnVit[] = { static const RadConstraint cCastBf16[] = { C_IN("from", "bf16"), C_IN("to", "bf16"), }; +/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the + * device in. */ +/* The audio attention's window: a query's keys are held in LDS, 64 of them at most. */ +static const RadConstraint cAttnLocalRel[] = { + C_IN("dtype", "bf16"), C_LE("left", 63), C_EQ("right", 0), +}; +static const RadConstraint cCastWiden[] = { + C_IN("from", "bf16"), C_IN("to", "f32"), +}; +/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs + * r4d_attn_dense_bf16.hip compiles. */ +static const RadConstraint cAttnDenseH64[] = { + C_EQ("head_dim", 64), C_EQ("gqa", 1), C_EQ("causal", 0), 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 cAttnDenseH512G4[] = { + C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; +/* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to + * 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */ +static const RadConstraint cQkNormRope[] = { + C_LE("head_dim", 1024), C_DIV("head_dim", 32), +}; /* ---- gated delta net ----------------------------------------------------------------------- */ static const RadConstraint cGdnChunkScan[] = { @@ -3340,6 +3504,111 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr, r4d_shape_cast }, +{ "cast_bf16_f32", "cast", "elem", + "y = x, bf16 widened to f32", + "any M and n; both row pitches are read off the operands", + "bf16 in, f32 out, exact", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cCastWiden), NOTUNE, + nullptr, nullptr, r4d_rad_cast_widen, 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", + "bf16 in and out, f32 arithmetic, libm silu / erf / tanh", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_act_mul, nullptr, nullptr, nullptr, + r4d_shape_binary }, + +{ "seg_mean_bf16", "seg_mean", "elem", + "mean pooling: one row a cu_seqlens segment", + "any n; 32 columns by 8 row lanes a workgroup, one workgroup row a segment", + "bf16 in and out, f64 sum, one rounding", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_seg_mean, nullptr, nullptr, nullptr }, + +{ "qk_norm_rope_bf16", "qk_norm_rope", "attn", + "per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place", + "head_dim a multiple of 32 up to 1024, neox (rotary_dim / 2 a multiple of 32), gptj, or " + "blocks (sections of 16 or a multiple of 32 pairs, each starting on a 32-channel slice); 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", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRope), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope, nullptr, nullptr, nullptr }, + +{ "relu_bf16", "relu", "elem", + "max(x, 0)", + "any n; both row pitches read off the operands", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_relu, nullptr, nullptr, nullptr, + r4d_shape_unary }, + +{ "silu_bf16", "silu", "elem", + "x * sigmoid(x), the sigmoid rounded nowhere: libref's act_silu", + "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_silu, 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", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_clamp, nullptr, nullptr, nullptr }, + +{ "conv2d_bf16", "conv2d", "elem", + "segment-wise 2-D convolution over (time, width), channels innermost, optional row mask", + "any geometry; a workgroup an output time row, a thread an output element; sized for an audio " + "subsampler (a few thousand frames, kernels of 3)", + "bf16 x / w / y, i32 cu_seqlens and mask, f32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_conv2d, nullptr, nullptr, nullptr }, + +{ "conv1d_dw_bf16", "conv1d_dw", "elem", + "segment-wise causal depthwise convolution over time", + "any channels and taps; a thread a (row, channel)", + "bf16 x / w / y, i32 cu_seqlens, f32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_conv1d_dw, nullptr, nullptr, nullptr }, + +{ "rel_sinusoid_bf16", "rel_sinusoid", "elem", + "the sinusoidal relative-position table", + "any rows and even width; a workgroup a row", + "bf16 out, f32 libm sin / cos / exp", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_rel_sinusoid, nullptr, nullptr, nullptr }, + +{ "attn_local_rel_bf16", "attn_local_rel", "attn", + "local attention with a relative-position term and a softcap (Gemma 4's audio)", + "any head_dim and heads, left <= 63, right 0; a workgroup a (row, head), each logit a " + "workgroup sum", + "bf16 q / k / v / relk / out, bf16 or f32 per-dim scale, f32 softmax", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnLocalRel), NOTUNE, + nullptr, nullptr, r4d_rad_attn_local_rel, nullptr, nullptr, nullptr }, + +{ "pool_rows_bf16", "pool_rows", "elem", + "mean of every k consecutive rows, then a multiplier: a vision pooler over windows its " + "processor laid out consecutively", + "any n and k; a workgroup an output row, a thread a column", + "bf16 in and out, f32 sum, two roundings", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_pool_rows, nullptr, nullptr, nullptr }, + { "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", @@ -3395,6 +3664,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_mul, nullptr, nullptr, nullptr, r4d_shape_binary }, +{ "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", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), 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", @@ -3903,6 +4181,31 @@ static const RadKernelInfo kKernels[] = { ROW(cAttnVit), NOTUNE, nullptr, nullptr, r4d_rad_attn_vit, nullptr, nullptr, nullptr }, +{ "attn_dense_h64_bf16", "attn_dense", "attn", + "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "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", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH64), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + +{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn", + "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH256G2), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + +{ "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", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH512G4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr }, + /* -------------------------------------------------------------------------- gated delta net */ { "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn", "gated delta net chunked scan: WY recompute, state recurrence and output in one kernel", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index a80b67e7..1ed738b5 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -11010,6 +11010,431 @@ static void device_phase(const Plugin& pl) { run_case(r, ts, ps); } } + /* The encoder attention rows: a fused [q|k|v] projection read through column slices, at each + * compiled (head_dim, gqa), with and without a window. Numerics are rad-kbench's (libref is + * the oracle); this is the launch at every geometry. */ + { + 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_h512_gqa4_bf16", 512, 4, 1 } }) { + if (!sel(g.name)) continue; + const RadKernelInfo* r = find(pl, g.name); + if (!r) { ok(g.name, false, "row absent"); continue; } + for (const int64_t window : { (int64_t)0, (int64_t)9 }) { + const int64_t total = 48, wq = g.nh * g.hd, wkv = g.nkv * g.hd; + const int64_t width = wq + 2 * wkv; + void* qkv = dalloc((size_t)(total * width * 2)); + auto col = [&](int64_t first, int64_t w) { + RadTensor t = T(qkv, RAD_BF16, { total, w }); + t.data = (void*)((uint16_t*)qkv + first); + t.stride[0] = width; + return t; + }; + std::vector ts = { + col(0, wq), col(wq, wkv), col(wq + wkv, wkv), + T(nullptr, RAD_I32, { 3 }), T(nullptr, RAD_BF16, { total, wq }), + }; + std::vector ps = { + PI("M", total), PI("head_dim", g.hd), PI("gqa", g.nh / g.nkv), + PI("causal", 0), PS("dtype", "bf16"), PF("scale", 1.0), + PI("max_seqlen", 32), PI("window", window), + }; + run_case(r, ts, ps); + } + } + } + if (sel("act_mul_bf16")) { + const RadKernelInfo* r = find(pl, "act_mul_bf16"); + if (!r) ok("act_mul_bf16", false, "row absent"); + else + for (const char* act : { "silu", "gelu", "gelu_tanh" }) { + std::vector ts = { T(nullptr, RAD_BF16, { 5, 645 }), + T(nullptr, RAD_BF16, { 5, 645 }), + T(nullptr, RAD_BF16, { 5, 645 }) }; + std::vector ps = { PI("M", 5), PI("n", 645), PS("act", act), + PS("dtype", "bf16") }; + run_case(r, ts, ps); + } + } + if (sel("seg_mean_bf16")) { + const RadKernelInfo* r = find(pl, "seg_mean_bf16"); + if (!r) ok("seg_mean_bf16", false, "row absent"); + else { + std::vector ts = { T(nullptr, RAD_BF16, { 23, 645 }), + T(nullptr, RAD_I32, { 4 }), + T(nullptr, RAD_BF16, { 3, 645 }) }; + std::vector ps = { PI("M", 23), PI("n", 645), PS("dtype", "bf16") }; + run_case(r, ts, ps); + } + } + if (sel("qk_norm_rope_bf16")) { + const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16"); + if (!r) ok("qk_norm_rope_bf16", false, "row absent"); + else + for (const int64_t hd : { (int64_t)256, (int64_t)512 }) { + std::vector ts = { T(nullptr, RAD_BF16, { 7, 8 * hd }), + T(nullptr, RAD_I32, { 7 }), + T(nullptr, RAD_BF16, { hd }), + T(nullptr, RAD_BF16, { hd }) }; + std::vector ps = { PI("M", 7), PI("head_dim", hd), PI("n_head", 4), + PI("n_head_kv", 2), PF("theta", 10000.0), + PF("eps", 1e-6), PS("mode", "neox"), + PI("v_norm", 1) }; + run_case(r, ts, ps); + } + } + if (sel("mul_weight_bf16")) { + const RadKernelInfo* r = find(pl, "mul_weight_bf16"); + if (!r) ok("mul_weight_bf16", false, "row absent"); + else + for (const int64_t wn : { (int64_t)1, (int64_t)512 }) { + std::vector ts = { T(nullptr, RAD_BF16, { 5, 512 }), + T(nullptr, RAD_BF16, { wn }), + T(nullptr, RAD_BF16, { 5, 512 }) }; + std::vector ps = { PI("M", 5), PI("n", 512), PS("dtype", "bf16"), + PI("scalar", wn == 1) }; + run_case(r, ts, ps); + } + } + if (sel("qk_norm_rope_bf16")) { + const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16"); + if (r) { + /* blocks, the vision form: 12 heads of 64, x and y halves, components (row, col). */ + std::vector ts = { T(nullptr, RAD_BF16, { 9, 36 * 64 }), + T(nullptr, RAD_I32, { 2, 9 }), + T(nullptr, RAD_BF16, { 64 }), + T(nullptr, RAD_BF16, { 64 }) }; + std::vector ps = { PI("M", 9), PI("head_dim", 64), PI("n_head", 12), + PI("n_head_kv", 12), PF("theta", 100.0), PF("eps", 1e-6), + PS("mode", "blocks"), PS("sections", "16 16"), + PS("comps", "1 0"), PI("v_norm", 1) }; + run_case(r, ts, ps); + } + } + if (sel("pool_rows_bf16")) { + const RadKernelInfo* r = find(pl, "pool_rows_bf16"); + if (!r) ok("pool_rows_bf16", false, "row absent"); + else { + std::vector ts = { T(nullptr, RAD_BF16, { 27, 768 }), + T(nullptr, RAD_BF16, { 3, 768 }) }; + std::vector ps = { PI("M", 27), PI("n", 768), PI("k", 9), + PF("mult", 27.712812921102035), PS("dtype", "bf16") }; + run_case(r, ts, ps); + } + } + /* --- the audio tower's ops, NUMERICALLY: each kernel against the formula libref implements, + * computed here on the host from the same bf16 inputs. rad-kbench's replay fixture predates + * these ops and a container-driven run needs the model, so this is where a wrong index in + * one of them shows up without either. Relative L2 against a bf16 rounding of the answer. */ + { + uint64_t seed = 0x5eedull; + auto rnd = [&]() { + seed = seed * 6364136223846793005ull + 1442695040888963407ull; + return (float)((int64_t)(seed >> 40) % 2001 - 1000) / 1000.0f; + }; + auto up = [&](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; + }; + auto down = [&](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; + }; + auto 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 = h_bf16(h_to_bf16(want[i])); + e += (got[i] - w) * (got[i] - w); + r += w * w; + } + return r > 0 ? std::sqrt(e / r) : std::sqrt(e); + }; + auto check = [&](const char* name, const std::vector& got, + const std::vector& want, double tol) { + const double r = rel(got, want); + char d[96]; + std::snprintf(d, sizeof d, "rel_l2 %.3g", r); + ok(name, r <= tol, d); + }; + auto randv = [&](size_t n, float scale) { + std::vector v(n); + for (auto& x : v) x = rnd() * scale; + return v; + }; + + if (sel("relu_bf16") || sel("silu_bf16") || sel("clamp_bf16")) { + const int64_t M = 5, n = 300; + std::vector x = randv((size_t)(M * n), 2.0f); + void* dx = up(x); + void* dy = dalloc((size_t)(M * n) * 2); + if (const RadKernelInfo* r = find(pl, "relu_bf16")) { + std::vector ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want(x.size()); + for (size_t i = 0; i < x.size(); ++i) want[i] = x[i] > 0 ? x[i] : 0; + check("relu_bf16 numerics", down(dy, x.size()), want, 0.0); + } else ok("relu_bf16", false, "row absent"); + if (const RadKernelInfo* r = find(pl, "silu_bf16")) { + std::vector ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want(x.size()); + for (size_t i = 0; i < x.size(); ++i) { + const float v = h_bf16(h_to_bf16(x[i])); + want[i] = v * (1.0f / (1.0f + std::exp(-v))); + } + /* expf on the card and std::exp here may differ by an ulp of f32, which can move + * a bf16 rounding; anything beyond that is a wrong kernel. */ + check("silu_bf16 numerics", down(dy, x.size()), want, 1e-3); + } else ok("silu_bf16", false, "row absent"); + /* PAST THE GRID'S Y LIMIT: the audio subsampler's rectifier runs over 96000 rows of + * 128, and a launch of one grid row a matrix row stops at 65535. */ + if (const RadKernelInfo* r = find(pl, "relu_bf16")) { + const int64_t Mb = 70000, nb = 32; + std::vector xb = randv((size_t)(Mb * nb), 2.0f); + void* dxb = up(xb); + void* dyb = dalloc((size_t)(Mb * nb) * 2); + std::vector ts = { T(dxb, RAD_BF16, { Mb, nb }), T(dyb, RAD_BF16, { Mb, nb }) }; + std::vector ps = { PI("M", Mb), PI("n", nb), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want(xb.size()); + for (size_t i = 0; i < xb.size(); ++i) want[i] = xb[i] > 0 ? xb[i] : 0; + check("relu_bf16 numerics past 65535 rows", down(dyb, xb.size()), want, 0.0); + } + if (const RadKernelInfo* r = find(pl, "clamp_bf16")) { + std::vector lo = { -0.5f }, hi = { 0.7f }; + void* dl = up(lo); + void* dh = up(hi); + std::vector ts = { T(dx, RAD_BF16, { M, n }), T(dl, RAD_BF16, { 1 }), + T(dh, RAD_BF16, { 1 }), T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want(x.size()); + for (size_t i = 0; i < x.size(); ++i) + want[i] = x[i] < lo[0] ? lo[0] : (x[i] > hi[0] ? hi[0] : x[i]); + check("clamp_bf16 numerics", down(dy, x.size()), want, 0.0); + } else ok("clamp_bf16", false, "row absent"); + } + if (sel("act_mul_bf16")) { + const RadKernelInfo* r = find(pl, "act_mul_bf16"); + const int64_t M = 4, n = 200; + std::vector g = randv((size_t)(M * n), 4.0f), u = randv((size_t)(M * n), 1.0f); + void* dg = up(g); + void* du = up(u); + void* dy = dalloc((size_t)(M * n) * 2); + std::vector ts = { T(dg, RAD_BF16, { M, n }), T(du, RAD_BF16, { M, n }), + T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PS("act", "sigmoid"), + PS("dtype", "bf16") }; + if (r) run_case(r, ts, ps); + std::vector want(g.size()); + for (size_t i = 0; i < g.size(); ++i) + want[i] = h_bf16(h_to_bf16(1.0f / (1.0f + std::exp(-g[i])))) * u[i]; + check("act_mul_bf16 sigmoid numerics", down(dy, g.size()), want, 1e-2); + } + if (sel("rmsnorm_bf16")) { + const RadKernelInfo* r = find(pl, "rmsnorm_bf16"); + const int64_t M = 3, n = 1024; + std::vector x = randv((size_t)(M * n), 3.0f), w = randv((size_t)n, 1.0f); + void* dx = up(x); + void* dw = up(w); + void* dy = dalloc((size_t)(M * n) * 2); + std::vector ts = { T(dx, RAD_BF16, { M, n }), T(dw, RAD_BF16, { n }), + T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PF("eps", 1e-6), + PS("dtype", "bf16"), PF("mult", 0.5) }; + if (r) run_case(r, ts, ps); + std::vector want(x.size()); + for (int64_t m = 0; m < M; ++m) { + double ss = 0; + for (int64_t i = 0; i < n; ++i) ss += (double)x[(size_t)(m * n + i)] * x[(size_t)(m * n + i)]; + const float s = 1.0f / std::sqrt((float)(ss / n) + 1e-6f); + for (int64_t i = 0; i < n; ++i) + want[(size_t)(m * n + i)] = x[(size_t)(m * n + i)] * s * w[(size_t)i] * 0.5f; + } + check("rmsnorm_bf16 mult numerics", down(dy, x.size()), want, 1e-2); + } + if (sel("conv2d_bf16")) { + const RadKernelInfo* r = find(pl, "conv2d_bf16"); + if (!r) ok("conv2d_bf16", false, "row absent"); + /* The subsampler's two layers, two segments each, with a masked row. */ + struct G { int64_t M, W, cin, cout, cdiv, vst; }; + for (const G& g : { G{ 24, 128, 1, 128, 1, 1 }, G{ 12, 64, 128, 32, 2, 2 } }) { + if (!r) break; + const int64_t kh = 3, kw = 3, st = 2, pad = 1; + const int64_t Wo = (g.W + 2 * pad - kw) / st + 1; + const int64_t T0 = g.M / 2; /* rows a segment */ + const int64_t To = (T0 + 2 * pad - kh) / st + 1, Mo = 2 * To; + std::vector x = randv((size_t)(g.M * g.W * g.cin), 1.0f); + std::vector w = randv((size_t)(g.cout * g.cin * kh * kw), 0.3f); + std::vector cu = { 0, (int32_t)(T0 * g.cdiv), (int32_t)(g.M * g.cdiv) }; + std::vector valid((size_t)(g.M * g.vst), 1); + valid[(size_t)(3 * g.vst)] = 0; + void* dx = up(x); + void* dw = up(w); + void* dcu = dalloc(cu.size() * 4); + void* dv = dalloc(valid.size() * 4); + fill_i32(dcu, cu); + fill_i32(dv, valid); + void* dy = dalloc((size_t)(Mo * Wo * g.cout) * 2); + std::vector ts = { T(dx, RAD_BF16, { g.M, g.W * g.cin }), + T(dw, RAD_BF16, { g.cout, g.cin, kh, kw }), + T(dcu, RAD_I32, { 3 }), + T(dv, RAD_I32, { g.M * g.vst }), + T(dy, RAD_BF16, { Mo, Wo * g.cout }) }; + std::vector ps = { PI("M", g.M), PI("width", g.W), PI("cin", g.cin), + PI("cout", g.cout), PI("kh", kh), PI("kw", kw), + PI("stride", st), PI("pad", pad), PI("cu_div", g.cdiv), + PI("valid_stride", g.vst), PS("dtype", "bf16") }; + run_case(r, ts, ps); + std::vector want((size_t)(Mo * Wo * g.cout), 0.0f); + for (int64_t s = 0; s < 2; ++s) + for (int64_t to = 0; to < To; ++to) + for (int64_t wo = 0; wo < Wo; ++wo) + for (int64_t co = 0; co < g.cout; ++co) { + float acc = 0.0f; + for (int64_t i = 0; i < kh; ++i) { + const int64_t ti = to * st - pad + i; + if (ti < 0 || ti >= T0) continue; + const int64_t tg = s * T0 + ti; + if (!valid[(size_t)(tg * g.vst)]) continue; + for (int64_t j = 0; j < kw; ++j) { + const int64_t wi = wo * st - pad + j; + if (wi < 0 || wi >= g.W) continue; + for (int64_t ci = 0; ci < g.cin; ++ci) + acc += x[(size_t)((tg * g.W + wi) * g.cin + ci)] * + w[(size_t)(((co * g.cin + ci) * kh + i) * kw + j)]; + } + } + want[(size_t)(((s * To + to) * Wo + wo) * g.cout + co)] = acc; + } + check(g.cin == 1 ? "conv2d_bf16 layer0 numerics" : "conv2d_bf16 layer1 numerics", + down(dy, want.size()), want, 1e-2); + } + } + if (sel("conv1d_dw_bf16")) { + const RadKernelInfo* r = find(pl, "conv1d_dw_bf16"); + const int64_t M = 20, C = 1024, K = 5; + std::vector x = randv((size_t)(M * C), 1.0f), w = randv((size_t)(C * K), 0.5f); + std::vector cu = { 0, 7, 20 }; + void* dx = up(x); + void* dw = up(w); + void* dcu = dalloc(12); + fill_i32(dcu, cu); + void* dy = dalloc((size_t)(M * C) * 2); + std::vector ts = { T(dx, RAD_BF16, { M, C }), T(dw, RAD_BF16, { C, 1, K }), + T(dcu, RAD_I32, { 3 }), T(dy, RAD_BF16, { M, C }) }; + std::vector ps = { PI("M", M), PI("n", C), PI("k", K), PS("dtype", "bf16") }; + if (r) run_case(r, ts, ps); + 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 < K; ++j) { + const int64_t tt = t - (K - 1) + j; + if (tt >= t0) acc += x[(size_t)(tt * C + c)] * w[(size_t)(c * K + j)]; + } + want[(size_t)(t * C + c)] = acc; + } + } + check("conv1d_dw_bf16 numerics", down(dy, want.size()), want, 1e-2); + } + if (sel("rel_sinusoid_bf16")) { + const RadKernelInfo* r = find(pl, "rel_sinusoid_bf16"); + const int64_t M = 13, n = 1024, h = n / 2; + void* dy = dalloc((size_t)(M * n) * 2); + std::vector ts = { T(dy, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PF("max_timescale", 10000.0), + PS("dtype", "bf16") }; + if (r) run_case(r, ts, ps); + const float inc = (float)(std::log(10000.0) / (double)(h - 1)); + std::vector want((size_t)(M * n)); + for (int64_t d = 0; d < M; ++d) + for (int64_t i = 0; i < h; ++i) { + const float ang = (float)d * std::exp((float)i * -inc); + want[(size_t)(d * n + i)] = std::sin(ang); + want[(size_t)(d * n + h + i)] = std::cos(ang); + } + check("rel_sinusoid_bf16 numerics", down(dy, want.size()), want, 1e-2); + } + if (sel("attn_local_rel_bf16")) { + const RadKernelInfo* r = find(pl, "attn_local_rel_bf16"); + const int64_t M = 40, H = 8, D = 128, L = 12, W = H * D; + const float cap = 50.0f; + std::vector q = randv((size_t)(M * W), 2.0f), k = randv((size_t)(M * W), 2.0f); + std::vector v = randv((size_t)(M * W), 1.0f); + std::vector rk = randv((size_t)((L + 1) * W), 1.0f), pds = randv((size_t)D, 3.0f); + std::vector cu = { 0, 17, 40 }; + void* dq = up(q); + void* dk = up(k); + void* dv = up(v); + void* drk = up(rk); + void* dp = up(pds); + void* dcu = dalloc(12); + fill_i32(dcu, cu); + void* dout = dalloc((size_t)(M * W) * 2); + std::vector ts = { T(dq, RAD_BF16, { M, W }), T(dk, RAD_BF16, { M, W }), + T(dv, RAD_BF16, { M, W }), T(drk, RAD_BF16, { L + 1, W }), + T(dp, RAD_BF16, { D }), T(dcu, RAD_I32, { 3 }), + T(dout, RAD_BF16, { M, W }) }; + std::vector ps = { PI("M", M), PI("head_dim", D), PI("n_head", H), + PI("left", L), PI("right", 0), PF("softcap", cap), + PS("dtype", "bf16") }; + if (r) run_case(r, ts, ps); + const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0)); + const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); + std::vector want((size_t)(M * W)); + for (int64_t i = 0; i < M; ++i) + for (int64_t hh = 0; hh < H; ++hh) { + const int64_t t0 = i < 17 ? 0 : 17, j0 = std::max(t0, i - L); + std::vector lg; + float mx = -1e30f; + for (int64_t j = j0; j <= i; ++j) { + float ss = 0.0f; + for (int64_t d = 0; d < D; ++d) { + const float x = pds[(size_t)d]; + const float sp = h_bf16(h_to_bf16( + x > 20.0f ? x : (x > 0 ? x + std::log1p(std::exp(-x)) + : std::log1p(std::exp(x))))); + const float qf = q[(size_t)(i * W + hh * D + d)] * qs * sp; + ss += qf * (k[(size_t)(j * W + hh * D + d)] * ks) + + qf * rk[(size_t)((i - j) * W + hh * D + d)]; + } + lg.push_back(cap * std::tanh(ss / cap)); + mx = std::max(mx, lg.back()); + } + float sum = 0.0f; + for (float& l : lg) { l = std::exp(l - mx); sum += l; } + for (int64_t d = 0; d < D; ++d) { + float acc = 0.0f; + for (int64_t j = j0; j <= i; ++j) + acc += lg[(size_t)(j - j0)] / sum * v[(size_t)(j * W + hh * D + d)]; + want[(size_t)(i * W + hh * D + d)] = acc; + } + } + check("attn_local_rel_bf16 numerics", down(dout, want.size()), want, 1e-2); + } + } + if (sel("cast_bf16_f32")) { + const RadKernelInfo* r = find(pl, "cast_bf16_f32"); + if (!r) ok("cast_bf16_f32", false, "row absent"); + else { + std::vector ts = { T(nullptr, RAD_BF16, { 3, 768 }), + T(nullptr, RAD_F32, { 3, 768 }) }; + std::vector ps = { PI("M", 3), PI("n", 768), PS("from", "bf16"), + PS("to", "f32") }; + run_case(r, ts, ps); + } + } /* --- cast: the strided row copy an intermediate-hidden-state tap writes with ------------- diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 23480654..34393a7e 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -382,11 +382,12 @@ 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"); /* `from` and `to` are separate keys because the whole point of the op is that the two ends - * differ. This row is compiled for bf16 -> bf16 only -- it is a strided row copy -- and the - * shim refuses anything else on dtype, so a geometry that names another pair is declined here - * rather than described into a refusal. */ + * differ. Two rows serve it -- bf16 -> bf16 (a strided row copy) and bf16 -> f32 (the + * widening) -- and the shims refuse anything else on dtype, so a geometry that names another + * pair is declined here rather than described into a refusal. */ 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) return RAD_E_UNSUPPORTED; + if (f != (uint32_t)RAD_BF16 || (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32)) + return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) }; R4D_PICK(l); } @@ -528,6 +529,17 @@ extern "C" int r4d_shape_binary(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* mul_weight: the one-row form of the weight (a per-channel gain), or with `scalar` the + * one-element form. */ +extern "C" int r4d_shape_mul_weight(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 uint32_t D = dt_act(p, n_p, "dtype"); + const int64_t wn = pi(p, n_p, "scalar") ? 1 : n; + const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1, wn), opd(D, M, n) }; + R4D_PICK(l); +} + extern "C" int r4d_shape_fill(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"); diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index 6e90a119..1d7ec165 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -34,6 +34,8 @@ #include "ref_gemm.h" #include "ref_ops.h" +#include + using namespace ref; namespace { @@ -222,7 +224,10 @@ int ref_attn_dense(const RadArgs* a, RadStream) { const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); const int64_t gqa = p_int(a, "gqa", 1); const int causal = (int)p_int(a, "causal", 0); - if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE; + /* `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. 0 is no window. */ + const int64_t window = p_int(a, "window", 0); + if (head_dim <= 0 || gqa <= 0 || 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] -- a column slice of a fused @@ -260,9 +265,13 @@ int ref_attn_dense(const RadArgs* a, RadStream) { const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); for (int64_t i = b0; i < b1; ++i) { const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs; - const int64_t jend = causal ? (i + 1) : b1; + 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); + } float mx = -INFINITY; - for (int64_t j = b0; j < jend; ++j) { + for (int64_t j = jbeg; j < jend; ++j) { const int64_t kb = j * k_rs + kh * k_hs; float dot = 0.0f; for (int64_t d = 0; d < head_dim; ++d) @@ -277,7 +286,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) { continue; } float sum = 0.0f; - for (int64_t j = b0; j < jend; ++j) { + for (int64_t j = jbeg; j < jend; ++j) { const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs; float dot = 0.0f; for (int64_t d = 0; d < head_dim; ++d) @@ -507,7 +516,9 @@ int ref_rope(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ qk_norm_rope */ /* The QK-norm preamble and the rotation in one op: an RMS norm over each 128-wide (or whatever - * head_dim is) q and k head against its own gain vector, then RoPE. + * head_dim is) q and k head against its own gain vector, then RoPE. `v_norm` 1 also RMS-norms + * each v head with a UNIT gain and no rotation -- Gemma 4's value norm, which has no weight. The + * v heads are otherwise left alone. * * THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of * writing it back in place -- it is what the unfused pair does, because the norm stores a tensor @@ -525,26 +536,65 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const float eps = p_f32(a, "eps", 1e-6f); const float rscale = p_f32(a, "scale", 1.0f); const float wadd = p_f32(a, "wadd", 0.0f); - static const char* kModes[] = { "neox", "gptj" }; - const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX); + const int v_norm = (int)p_int(a, "v_norm", 0); + static const char* kModes[] = { "neox", "gptj", "blocks" }; + const int mode = p_enum(a, "mode", kModes, 3, 0); + if (mode < 0) return RAD_E_UNSUPPORTED; + const bool blocks = mode == 2; 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; + /* 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 + * theta^(-j / sec[c]) -- each section a complete neox rotary of its own width. The sections + * fill the rotated prefix exactly. Positions are [C, M], component-major. */ + int64_t sec[8] = {}, comp[8] = {}; + int n_sec = 0; + if (blocks) { + n_sec = rope_sections(a, sec); + if (n_sec <= 0) return RAD_E_SHAPE; + int64_t total = 0; + for (int c = 0; c < n_sec; ++c) { total += sec[c]; comp[c] = c; } + if (2 * total != rot) return RAD_E_SHAPE; + if (const char* cs = p_str(a, "comps", nullptr)) { + int k = 0; + for (const char* v = cs; *v && k < 8; ) { + char* end = nullptr; + const long long x = std::strtoll(v, &end, 10); + if (end == v) break; + comp[k++] = x; + v = end; + } + if (k != n_sec) return RAD_E_SHAPE; + } + } + const bool multi = 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) return RAD_E_SHAPE; + for (int c = 0; 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; - const int64_t M = 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); RopeFreq f; - RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f)); + if (!blocks) RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f)); #pragma omp parallel for schedule(static) for (int64_t m = 0; m < M; ++m) { float p[8]; - const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / - (rscale != 0.0f ? rscale : 1.0f); - for (int c = 0; c < 8; ++c) p[c] = one; + const float div = rscale != 0.0f ? rscale : 1.0f; + if (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; + 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 RadTensor* w = h < n_head ? qw : kw; @@ -557,7 +607,128 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps); for (int64_t d = 0; d < head_dim; ++d) stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc * (ldt(w, d * ws) + wadd)); - rope_head(qkv, base, ds, rot, mode, f, p); + if (!blocks) { + rope_head(qkv, base, ds, rot, mode, f, p); + continue; + } + int64_t start = 0; + for (int c = 0; c < n_sec; ++c) { + for (int64_t j = 0; j < sec[c]; ++j) { + const float inv = 1.0f / std::pow(theta, (float)j / (float)sec[c]); + const float ang = p[comp[c]] * inv; + const float cs = std::cos(ang), sn = std::sin(ang); + const int64_t i0 = start + j, i1 = start + sec[c] + j; + const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds); + stt(qkv, base + i0 * ds, x0 * cs - x1 * sn); + stt(qkv, base + i1 * ds, x0 * sn + x1 * cs); + } + start += 2 * sec[c]; + } + } + for (int64_t h = 0; v_norm && h < n_head_kv; ++h) { + const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds; + float ss = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) { + float x = ldt(qkv, base + d * ds); + ss += x * x; + } + const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps); + for (int64_t d = 0; d < head_dim; ++d) + stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc); + } + } + return RAD_OK; +} + +/* A value as a tensor of `dt` holds it: rounded through the dtype's own store and load. */ +static inline float round_dt(uint32_t dt, float v) { + uint64_t buf = 0; + st_dt(dt, &buf, 0, v); + return ld_dt(dt, &buf, 0); +} +static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; } + +/* ------------------------------------------------------------------ attn_local_rel */ +/* Local attention with a relative-position term: Gemma 4's audio (USM conformer) attention. + * + * Query row i of a cu_seqlens segment sees the key rows j of the same segment with + * 0 <= i - j <= left (`right` must be 0). Per head: + * + * qf[d] = q[i,d] * (head_dim^-0.5 / ln 2) * softplus(pds[d]) + * logit = sum_d qf[d] * k[j,d] * (ln(1 + e) / ln 2) + sum_d qf[d] * relk[i - j, d] + * logit = softcap * tanh(logit / softcap) + * + * then a softmax over those keys and the weighted sum of v, all in f32 and rounded once. `relk` + * is [left + 1, n_head * head_dim]: row d is the projected relative position for distance d. + * + * The reference computes this in 12-query blocks over 24-key context windows and shifts the + * relative term into place (Transformer-XL's rel_shift); every key outside 0 <= i - j <= left + * carries a -1e9 logit there and a zero weight after the softmax, so the sliding form below is + * the same function. softplus(pds) is rounded to the weight's dtype before use, as the reference + * evaluates it on the bf16 parameter. */ +int ref_attn_local_rel(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3]; + const RadTensor *pds = &a->t[4], *cu = &a->t[5], *o = &a->t[6]; + const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0); + const int64_t L = p_int(a, "left", 0), R = p_int(a, "right", 0); + const int64_t cdiv = p_int(a, "cu_div", 1); + const float cap = p_f32(a, "softcap", 0.0f); + if (D <= 0 || H <= 0 || L < 0 || cdiv <= 0 || !(cap > 0.0f)) return RAD_E_SHAPE; + if (R != 0) return RAD_E_UNSUPPORTED; + if (D > REF_HD_MAX || L + 1 > REF_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t W = H * D; + if (numel(pds) < D || numel(rk) < (L + 1) * W) return RAD_E_SHAPE; + const int64_t S = numel(cu) - 1; + if (S <= 0) return RAD_E_SHAPE; + const int64_t Mq = rows_n(q, W), Mk = rows_n(k, W), Mv = rows_n(v, W), Mo = rows_n(o, W); + + const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0)); + const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); + float spd[REF_HD_MAX]; + for (int64_t d = 0; d < D; ++d) + spd[d] = round_dt(pds->dtype, act_softplus(ldt(pds, d * laststride(pds)), 20.0f)); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); + const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; + if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) { + const int64_t i = t0 + ih / H, h = ih % H; + float qf[REF_HD_MAX], lg[REF_HD_MAX], acc[REF_HD_MAX]; + const int64_t qb = rowoff(q, i, W) + h * D * laststride(q); + for (int64_t d = 0; d < D; ++d) qf[d] = ldt(q, qb + d * laststride(q)) * qs * spd[d]; + const int64_t j0 = i - L > t0 ? i - L : t0; + float mx = -INFINITY; + for (int64_t j = j0; j <= i; ++j) { + const int64_t kb = rowoff(k, j, W) + h * D * laststride(k); + const int64_t rb = rowoff(rk, i - j, W) + h * D * laststride(rk); + float ac = 0.0f, bd = 0.0f; + for (int64_t d = 0; d < D; ++d) { + ac += qf[d] * (ldt(k, kb + d * laststride(k)) * ks); + bd += qf[d] * ldt(rk, rb + d * laststride(rk)); + } + const float x = cap * std::tanh((ac + bd) / cap); + lg[j - j0] = x; + mx = x > mx ? x : mx; + } + float sum = 0.0f; + for (int64_t j = j0; j <= i; ++j) { + lg[j - j0] = std::exp(lg[j - j0] - mx); + sum += lg[j - j0]; + } + for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f; + for (int64_t j = j0; j <= i; ++j) { + const float p = lg[j - j0] / sum; + const int64_t vb = rowoff(v, j, W) + h * D * laststride(v); + for (int64_t d = 0; d < D; ++d) acc[d] += p * ldt(v, vb + d * laststride(v)); + } + const int64_t ob = rowoff(o, i, W) + h * D * laststride(o); + for (int64_t d = 0; d < D; ++d) stt(o, ob + d * laststride(o), acc[d]); } } return RAD_OK; diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index e4087203..28bcc217 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -25,24 +25,31 @@ static inline int64_t rows_of(const RadTensor* t, int64_t n) { * r4d_rmsnorm_had_quant_i8 says the same). It defaults to 0, so a plain RMS norm is the plain * call. */ int ref_rmsnorm(const RadArgs* a, RadStream) { - if (!have(a, 3)) return RAD_E_INVAL; - const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[2]; - const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0); + if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[2]; + /* An absent gain is one, and `wadd` belongs to a gain, so it is refused without one. */ + const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr; + const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0); const float eps = p_f32(a, "eps", 1e-6f); const float wadd = p_f32(a, "wadd", 0.0f); + /* `mult` scales the normed row before its one rounding: a residual branch weighted by a + * constant (Gemma 4's audio feed-forward, a half) without a second pass over the row. */ + const float mult = p_f32(a, "mult", 1.0f); if (n <= 0) return RAD_E_SHAPE; + if (!w && wadd != 0.0f) return RAD_E_INVAL; const int64_t rows = rows_of(x, n); - if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE; + if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE; #pragma omp parallel for schedule(static) for (int64_t r = 0; r < rows; ++r) { const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); - const int64_t xs = laststride(x), ys = laststride(y), ws = laststride(w); + const int64_t xs = laststride(x), ys = laststride(y), ws = w ? laststride(w) : 0; float ss = 0.0f; for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); ss += v * v; } const float s = 1.0f / std::sqrt(ss / (float)n + eps); for (int64_t i = 0; i < n; ++i) - stt(y, yb + i * ys, ldt(x, xb + i * xs) * s * (ldt(w, i * ws) + wadd)); + stt(y, yb + i * ys, + ldt(x, xb + i * xs) * s * (w ? ldt(w, i * ws) + wadd : 1.0f) * mult); } return RAD_OK; } @@ -212,6 +219,33 @@ static int elementwise2(const RadArgs* a, bool mul) { int ref_add(const RadArgs* a, RadStream) { return elementwise2(a, false); } int ref_mul(const RadArgs* a, RadStream) { return elementwise2(a, true); } +/* ------------------------------------------------------------------ mul_weight */ +/* y = x * w, `w` a WEIGHT of one element or of one row: a learned gain on an activation -- a + * per-layer scalar on the residual stream (Gemma 4's layer_scalar), or a per-channel one (a + * vision tower's layer scale). Its own op and not a form of `mul` because an op's operand is a + * weight or an activation by its schema, and `mul`'s `b` is an activation. The product is f32, + * rounded once to y's dtype. */ +int ref_mul_weight(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", numel(Y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + const bool scalar = numel(W) == 1; + if (!scalar && numel(W) != n) return RAD_E_SHAPE; + const int64_t ws = scalar ? 0 : laststride(W); + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); + const int64_t xs = laststride(X), ys = laststride(Y); + for (int64_t i = 0; i < n; ++i) + stt(Y, yb + i * ys, ldt(X, xb + i * xs) * ldt(W, i * ws)); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ scale_rows */ /* y[m, i] = x[m, i] * act(s[m]) -- one scalar per ROW, broadcast across the row. * @@ -283,6 +317,281 @@ int ref_silu_mul(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ act_mul */ +/* y = act(a) * b, the gated product with its two halves in two operands. `silu_mul` reads one + * fused gate_up row; this reads the gate and the multiplier from wherever they are, which covers + * a fused gate_up as two column slices of it AND a gate whose multiplier is some other tensor -- + * Gemma's per-layer-input block multiplies gelu(gate(x)) by a per-layer embedding. + * + * THE ACTIVATION IS ROUNDED TO y's DTYPE BEFORE THE PRODUCT, which is what the unfused pair does: + * `act(gate)` is a tensor, and the product reads it back. */ +static float gelu_tanh_f(float x) { + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x))); +} + +int ref_act_mul(const RadArgs* a, RadStream) { + 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)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE; + static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" }; + const int act = p_enum(a, "act", kActs, 4, -1); + if (act < 0) return RAD_E_INVAL; + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t ab = rowoff(A, r, n), bb = rowoff(B, r, n), yb = rowoff(Y, r, n); + const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y); + for (int64_t i = 0; i < n; ++i) { + const float g = ldt(A, ab + i * as); + const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g) + : act == 2 ? gelu_tanh_f(g) : act_sigmoid(g); + stt(Y, yb + i * ys, round_to(Y->dtype, v) * ldt(B, bb + i * bs)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ seg_mean */ +/* y[s, :] = the mean of x's rows [cu[s], cu[s+1]): one row a segment, which is a sentence + * embedding's mean pooling over a ragged batch. The sum is taken in DOUBLE and divided once, so the + * pooled row does not depend on how many rows a segment has beyond the one rounding to y's dtype. + * An empty segment writes zeros. */ +int ref_seg_mean(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0); + const int64_t S = numel(cu) - 1; + if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE; + const int64_t total = ld_int(cu->dtype, cu->data, offlin(cu, S)); + if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t s = 0; s < S; ++s) { + const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); + const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + const int64_t yb = rowoff(Y, s, n), ys = laststride(Y), xs = laststride(X); + for (int64_t i = 0; i < n; ++i) { + double acc = 0.0; + for (int64_t r = b0; r < b1; ++r) acc += ldt(X, rowoff(X, r, n) + i * xs); + stt(Y, yb + i * ys, b1 > b0 ? (float)(acc / (double)(b1 - b0)) : 0.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pool_rows */ +/* Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then + * multiplied by `mult` and rounded again -- the unfused pair, which stores the mean. A vision + * pooler whose processor lays each k-patch window out consecutively pools with this. */ +int ref_pool_rows(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), k = p_int(a, "k", 0); + const float mult = p_f32(a, "mult", 1.0f); + if (n <= 0 || k <= 0) return RAD_E_SHAPE; + const int64_t rows_in = rows_of(X, n); + if (rows_in <= 0 || rows_in % k) return RAD_E_SHAPE; + const int64_t rows = rows_in / k; + if (numel(Y) < rows * n) return RAD_E_SHAPE; + const float inv = 1.0f / (float)k; + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t yb = rowoff(Y, r, n), ys = laststride(Y), xs = laststride(X); + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int64_t j = 0; j < k; ++j) acc += ldt(X, rowoff(X, r * k + j, n) + i * xs); + stt(Y, yb + i * ys, acc * inv); + stt(Y, yb + i * ys, ldt(Y, yb + i * ys) * mult); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ relu */ +/* y = max(x, 0) over [M, n], each operand at its own row pitch. */ +int ref_relu(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", numel(Y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); + const int64_t xs = laststride(X), ys = laststride(Y); + for (int64_t i = 0; i < n; ++i) { + const float v = ldt(X, xb + i * xs); + stt(Y, yb + i * ys, v > 0.0f ? v : 0.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ clamp */ +/* y = min(max(x, lo), hi), the bounds WEIGHTS of one element each: a clipped linear's input or + * output range (Gemma 4's audio tower), which the checkpoint states per projection. */ +int ref_clamp(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", numel(Y)); + if (n <= 0 || numel(L) < 1 || numel(H) < 1) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + const float lo = ldt(L, 0), hi = ldt(H, 0); + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); + const int64_t xs = laststride(X), ys = laststride(Y); + for (int64_t i = 0; i < n; ++i) { + float v = ldt(X, xb + i * xs); + v = v < lo ? lo : v; + v = v > hi ? hi : v; + stt(Y, yb + i * ys, v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ conv2d */ +/* A 2-D convolution over (time, width) with channels innermost, segment by segment. + * + * x is [M, W * cin]: row t is time t, element (t, w, c) at column w * cin + c. Each cu_seqlens + * segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved ON ITS OWN, zero-padded by `pad` at its + * edges on both axes -- two clips in one pass must not see each other -- and its output rows start + * at cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw]. With the optional `valid` + * operand, input row t (pass-global) is read as zeros unless valid[t * valid_stride] != 0: the + * frame mask Gemma 4's subsampler multiplies in before each convolution. f32 accumulation, one + * rounding. */ +int ref_conv2d(const RadArgs* a, RadStream) { + if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data) + return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4]; + const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr; + const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); + const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0); + const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1); + if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || + vst <= 0) + return RAD_E_SHAPE; + const int64_t Wo = (W + 2 * pad - kw) / st + 1; + if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE; + const int64_t S = numel(cu) - 1; + if (S <= 0) return RAD_E_SHAPE; + const int64_t rin = W * cin, rout = Wo * cout; + const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); + const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0; + if (T <= 0) continue; + const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st; + if (To <= 0) continue; + if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE; + if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t to = 0; to < To; ++to) { + const int64_t yb = rowoff(Y, o0 + to, rout), ys = laststride(Y), xs = laststride(X); + for (int64_t wo = 0; wo < Wo; ++wo) + for (int64_t co = 0; co < cout; ++co) { + float acc = 0.0f; + for (int64_t i = 0; i < kh; ++i) { + const int64_t ti = to * st - pad + i; + if (ti < 0 || ti >= T) continue; + const int64_t tg = t0 + ti; + if (V && ld_int(V->dtype, V->data, offlin(V, tg * vst)) == 0) continue; + const int64_t xb = rowoff(X, tg, rin); + for (int64_t j = 0; j < kw; ++j) { + const int64_t wi = wo * st - pad + j; + if (wi < 0 || wi >= W) continue; + for (int64_t ci = 0; ci < cin; ++ci) + acc += ldt(X, xb + (wi * cin + ci) * xs) * + ldt(Wt, ((co * cin + ci) * kh + i) * kw + j); + } + } + stt(Y, yb + (wo * cout + co) * ys, acc); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ 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. */ +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 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; + 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); + + for (int64_t s = 0; s < S; ++s) { + const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s)); + const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)); + if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE; + const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv; + if (t1 > Mx || t1 > My) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t t = t0; t < t1; ++t) { + const int64_t yb = rowoff(Y, t, C), ys = laststride(Y), xs = laststride(X); + for (int64_t c = 0; c < C; ++c) { + float acc = 0.0f; + for (int64_t j = 0; j < K; ++j) { + const int64_t tt = t - (K - 1) + j; + if (tt < t0) continue; + acc += ldt(X, rowoff(X, tt, C) + c * xs) * ldt(Wt, c * K + j); + } + stt(Y, yb + c * ys, acc); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ rel_sinusoid */ +/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first + * half, cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)). + * Computed in f32 step by step the way the reference's torch expressions are, then rounded. */ +int ref_rel_sinusoid(const RadArgs* a, RadStream) { + if (!have(a, 1)) return RAD_E_INVAL; + const RadTensor* Y = &a->t[0]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || n % 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0) return RAD_E_SHAPE; + const int64_t h = n / 2; + const double mt = (double)p_f32(a, "max_timescale", 10000.0f); + const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1)); + + #pragma omp parallel for schedule(static) + for (int64_t d = 0; d < rows; ++d) { + const int64_t yb = rowoff(Y, d, n), ys = laststride(Y); + for (int64_t i = 0; i < h; ++i) { + const float inv = std::exp((float)i * -inc); + const float ang = (float)d * inv; + stt(Y, yb + i * ys, std::sin(ang)); + stt(Y, yb + (h + i) * ys, std::cos(ang)); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gelu / silu */ static int unary(const RadArgs* a, int which) { if (!have(a, 2)) return RAD_E_INVAL; diff --git a/libref/ref_gemm.cpp b/libref/ref_gemm.cpp index 9a894f85..2c0c66da 100644 --- a/libref/ref_gemm.cpp +++ b/libref/ref_gemm.cpp @@ -310,6 +310,7 @@ int ref_embed_lookup(const RadArgs* a, RadStream) { const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0); const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0); const int64_t voff = p_int(a, "vocab_offset", 0); + const float mult = p_f32(a, "mult", 1.0f); if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; const int64_t M = numel(x) / n_embd; if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; @@ -338,7 +339,7 @@ int ref_embed_lookup(const RadArgs* a, RadStream) { const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x); const bool have_row = id >= 0 && id < n_vocab; for (int64_t i = 0; i < n_embd; ++i) - stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) : 0.0f); + stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * mult : 0.0f); } return RAD_OK; } diff --git a/libref/ref_ops.h b/libref/ref_ops.h index b076923c..454d76db 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -73,6 +73,16 @@ int ref_grid_embed (const RadArgs*, RadStream); int ref_add (const RadArgs*, RadStream); int ref_mul (const RadArgs*, RadStream); int ref_silu_mul (const RadArgs*, RadStream); +int ref_act_mul (const RadArgs*, RadStream); +int ref_mul_weight (const RadArgs*, RadStream); +int ref_seg_mean (const RadArgs*, RadStream); +int ref_pool_rows (const RadArgs*, RadStream); +int ref_relu (const RadArgs*, RadStream); +int ref_clamp (const RadArgs*, RadStream); +int ref_conv2d (const RadArgs*, RadStream); +int ref_conv1d_dw (const RadArgs*, RadStream); +int ref_rel_sinusoid (const RadArgs*, RadStream); +int ref_attn_local_rel (const RadArgs*, RadStream); int ref_gelu (const RadArgs*, RadStream); int ref_silu (const RadArgs*, RadStream); int ref_sigmoid (const RadArgs*, RadStream); @@ -191,6 +201,16 @@ REF_SHAPE_FN(ref_grid_embed); REF_SHAPE_FN(ref_add); REF_SHAPE_FN(ref_mul); REF_SHAPE_FN(ref_silu_mul); +REF_SHAPE_FN(ref_act_mul); +REF_SHAPE_FN(ref_mul_weight); +REF_SHAPE_FN(ref_seg_mean); +REF_SHAPE_FN(ref_pool_rows); +REF_SHAPE_FN(ref_relu); +REF_SHAPE_FN(ref_clamp); +REF_SHAPE_FN(ref_conv2d); +REF_SHAPE_FN(ref_conv1d_dw); +REF_SHAPE_FN(ref_rel_sinusoid); +REF_SHAPE_FN(ref_attn_local_rel); REF_SHAPE_FN(ref_gelu); REF_SHAPE_FN(ref_silu); REF_SHAPE_FN(ref_sigmoid); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 7c7ebb53..f01559b0 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -469,7 +469,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) { * * THREE OPS THAT EXIST SO THAT A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 activation * quantiser into whichever kernel already has the row in registers, and declares the fused form as - * its own op. Without a host kernel for those names, `RADIANCE_HOST_DOMAIN` -- the only thing that + * its own op. Without a host kernel for those names, a host-backend run -- the only thing that * can answer "is the GRAPH right", because the per-op oracle reads the same graph both sides -- * cannot start on an fp8 model ("site 'host' is unavailable for this band"). * diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 116c3cd3..cc6d24d9 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -73,9 +73,15 @@ #define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0])) /* ---- elementwise and norms ---------------------------------------------------------------- */ -static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), +/* `mult` scales the normed row before its one rounding (default 1). */ +/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */ +static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd") }; -static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") }; +static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), + P_F64O("wadd"), P_F64O("mult") }; +/* `w` is optional: absent, the gain is one (a norm with no scale, such as Gemma 4's value norm and + * its multimodal embedder's pre-projection norm). */ +static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") }; /* The GATED RESIDUAL pair. `inject` and `group` are the two switches the operand list is banded * on: `inject` 0 is the final mixer (no per-branch gate weight, no gate output) and `group` 0 is a @@ -141,9 +147,41 @@ 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") }; +/* `scalar` 1 says `w` is one element rather than one row: a kernel reads that off the operand, and + * the parameter is what lets a shape description say which of the two geometries it is. */ +static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; +static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") }; +static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; +/* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */ +static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") }; +/* `M` is the INPUT row count, a multiple of `k`; y has M / k rows. */ +static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), + P_STR("dtype") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; +/* The audio (USM conformer) tower's operators. */ +static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") }; +/* `M` is the INPUT time rows. */ +static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"), + P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"), + P_INTO("cu_div"), P_INTO("valid_stride"), + P_STR("dtype") }; +static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"), + 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") }; +/* `M` is the table's rows: one a distance. */ +static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"), + P_STR("dtype") }; +static const RadOperandSpec oRelSin[] = { OUT("y") }; +static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("left"), P_INT("right"), P_F64("softcap"), + P_INTO("cu_div"), P_STR("dtype") }; +static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"), + WGT("pds"), OPD("cu_seqlens"), OUT("out") }; /* `fill` has no input: `value` is the whole of what it writes. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; @@ -262,7 +300,7 @@ 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("max_seqlen"), P_INTO("window") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; @@ -304,10 +342,13 @@ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("rati static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"), OUT("out") }; +/* `mode` "blocks" rotates each of `sections` (pair counts) as its own neox block of channels, + * reading the position component `comps` names for it; positions are then [C, M]. */ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"), P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"), - P_F64O("wadd") }; + 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") }; @@ -506,6 +547,11 @@ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_voc * A parameter because a global scale needs the whole table * and the transform sees one block. */ P_F64O("wscale") }; +/* embed_lookup's own list: pEmbed and `mult`, the factor every gathered row is multiplied by -- + * Gemma's sqrt(hidden). embed_lookup_q has its table scale and does not take it. */ +static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), + P_STR("dtype"), P_INTO("vocab_offset"), + P_F64O("wscale"), P_F64O("mult") }; static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") }; /* The quantised table: one scale for all of it. A SEPARATE OP and not a dtype on the above -- * the operand list differs and operands are positional, the same argument gemm_nt_q makes. */ @@ -566,11 +612,12 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), /* ================================================================== the schema table */ static const RadOpSchema kSchemas[] = { { "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm), - "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is not in docs/OPS.md's elementwise table: " + "y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wadd` is not in docs/OPS.md's elementwise table: " "it is GemmaRMSNorm's `1 +`, which Qwen3.5, Qwen3-Next and Gemma all need, and it defaults to 0. " "Spelled `wadd` and not `w_add` because that is what libr4d's fused norms call it and one " - "vocabulary cannot have two spellings of one parameter." }, -{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd), + "vocabulary cannot have two spellings of one parameter. `mult` (default 1) scales the row " + "before its one rounding." }, +{ "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd), "residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from " "the unrounded f32 sum; the multiply reads residual_out back AFTER it has been narrowed, which " "is what every fused implementation does." }, @@ -606,6 +653,38 @@ static const RadOpSchema kSchemas[] = { "y = a + b. An operand carrying exactly n elements against a taller output broadcasts along " "rows; nothing else broadcasts." }, { "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 " + "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." }, +{ "act_mul", ARR(pActMul), ARR(oBinary), + "y = act(a) * b, `act` \"silu\", \"gelu\" (exact erf), \"gelu_tanh\" or \"sigmoid\". The activation is " + "rounded to y's dtype before the product, which is the unfused pair. `a` and `b` may be column " + "slices of one fused row." }, +{ "seg_mean", ARR(pSegMean), ARR(oSegMean), + "y[s] = mean of x's rows [cu[s], cu[s+1]): one row a segment, summed in double and rounded " + "once to y's dtype. An empty segment is a zero row." }, +{ "pool_rows", ARR(pPoolRows), ARR(oUnary), + "Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then " + "times `mult` (default 1) and rounded again. M, the input rows, is a multiple of k." }, +{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0), each operand at its own row pitch." }, +{ "clamp", ARR(pMnD), ARR(oClamp), + "y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." }, +{ "conv2d", ARR(pConv2d), ARR(oConv2d), + "A 2-D convolution over (time, width), channels innermost: x[t, w*cin + c] -> y[t, w*cout + c], " + "w [cout, cin, kh, kw]. Each cu_seqlens segment (rows cu/cu_div) is convolved on its own with " + "zero padding `pad` at its edges; its output rows start at cu/(cu_div*stride). With `valid`, " + "input row t reads as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding." }, +{ "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." }, +{ "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." }, +{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel), + "Local attention with a relative-position term (Gemma 4's audio): query i of a segment sees " + "keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit " + "= qf.k * ln(1+e)/ln2 + qf.relk[i-j]; softcap * tanh(logit / softcap); softmax; .v. f32, one " + "rounding." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), "y[i] = silu(gate_up[i]) * gate_up[n + i]. The GATE IS THE FIRST HALF, which is the order " "rad-convert fuses gate and up into one weight in." }, @@ -755,7 +834,8 @@ static const RadOpSchema kSchemas[] = { "including this step's query rows. k_descale / v_descale are optional and apply to an fp8 " "cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." }, { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), - "Dense varlen attention over cu_seqlens segments -- the vision tower's. Nothing paged." }, + "Dense varlen attention over cu_seqlens segments. Nothing paged. `window` is attn_paged's rule " + "over a segment's positions: causal, i - j < window; non-causal, |i - j| < window; 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." }, @@ -778,7 +858,8 @@ static const RadOpSchema kSchemas[] = { "`scale` divides the position; `rotary_dim` is optional and defaults to head_dim." }, { "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." }, + "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." }, { "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 " @@ -895,9 +976,10 @@ static const RadOpSchema kSchemas[] = { "[rows][row] and y is [rows][world_size][row], so one row of y carries every rank's words for " "that row. The vocab-parallel candidate merge reads exactly that." }, -{ "embed_lookup", ARR(pEmbed), ARR(oEmbed), +{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed), "A gather from wte[n_vocab, n_embd]. A negative token id writes a zero row (padding); an id at " - "or above n_vocab fails the launch." }, + "or above n_vocab fails the launch. `mult`, when given, multiplies every gathered row and the " + "product is rounded once to x's dtype (Gemma's sqrt(hidden)); absent it is a plain copy." }, { "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), "The same gather from a table quantised with ONE scale for all of it: x[m] = wte[id] * scale[0]. " "Qwen3.8-Flash-Next-FP8's 320-million-row n-gram embedding is stored that way -- E4M3 codes and a " @@ -1007,6 +1089,24 @@ SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add), SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul), SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, ref_silu_mul), +SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul), +SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, + ref_mul_weight), +SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, + ref_seg_mean), +SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", + DT_FLOAT, ref_pool_rows), +SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu), +SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp), +SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost", + DT_FLOAT, ref_conv2d), +SIMPLE("ref_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise convolution", + DT_FLOAT, ref_conv1d_dw), +SIMPLE("ref_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table", DT_FLOAT, + ref_rel_sinusoid), +SIMPLE("ref_attn_local_rel", "attn_local_rel", "attn", + "local attention with a relative-position term and a softcap", DT_FLOAT, + ref_attn_local_rel), SIMPLE("ref_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, ref_gelu), SIMPLE("ref_silu", "silu", "elem", "silu", DT_FLOAT, ref_silu), SIMPLE("ref_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, ref_sigmoid), @@ -1028,7 +1128,7 @@ SIMPLE("ref_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4 "float in, fp8_e4m3 out, f32 scale", ref_quant_act_fp8), /* THE FUSED FORMS, AND THEY EXIST SO A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 * activation quantiser into whichever kernel already has the row in registers and declares the - * fused op as its own; without host kernels for those names, RADIANCE_HOST_DOMAIN -- the only + * fused op as its own; without host kernels for those names, a host-backend run -- the only * thing that can answer "is the GRAPH right", because the per-op oracle reads the same graph on * both sides -- cannot start on an fp8 model. */ SIMPLE("ref_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 9ae0a7e2..22d8b4f6 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -468,6 +468,131 @@ int ref_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return binary_shape(p, n_p, operand, "mul", out); } +int ref_mul_weight_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 */ + if (gi(p, n_p, "scalar", 0)) o.t(D, { 1 }); /* w -- the scalar form */ + else o.t(D, { n }); /* w -- one row */ + o.t(D, { M, n }); /* y */ + return o.finish("mul_weight", operand, out); +} + +int ref_act_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return binary_shape(p, n_p, operand, "act_mul", out); +} + +int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = n_seq_of(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { S, n }); /* y */ + return o.finish("seg_mean", operand, out); +} + +int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); + /* A band's bound need not be whole windows; the rows a pass issues always are, so the + * description takes the whole windows under it. */ + int64_t M = gi(p, n_p, "M", 0); + if (k > 0) M -= M % k; + if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { M / k, n }); /* y */ + return o.finish("pool_rows", operand, out); +} + +int ref_relu_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(D, { M, n }); /* y */ + return o.finish("relu", operand, out); +} + +int ref_clamp_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(D, { 1 }); /* lo */ + o.t(D, { 1 }); /* hi */ + o.t(D, { M, n }); /* y */ + return o.finish("clamp", operand, out); +} + +/* THE AUDIO TOWER'S SEGMENTED OPS ARE DESCRIBED AS ONE SEGMENT. `cu_seqlens` counts in units + * `cu_div` times finer than the operand's rows (a subsampled layer reads the pass's frame + * boundaries), so the description's rows are M / cu_div and a band that does not divide -- or, + * for a strided convolution, does not divide into whole output rows -- is declined rather than + * described into a refusal. */ +int ref_conv2d_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), W = gi(p, n_p, "width", 0); + const int64_t cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); + const int64_t kh = gi(p, n_p, "kh", 0), kw = gi(p, n_p, "kw", 0); + const int64_t st = gi(p, n_p, "stride", 1), pad = gi(p, n_p, "pad", 0); + const int64_t cdiv = gi(p, n_p, "cu_div", 1), vst = gi(p, n_p, "valid_stride", 1); + if (M <= 0 || W <= 0 || st <= 0 || cdiv <= 0 || vst <= 0 || M % (cdiv * st)) + return RAD_E_UNSUPPORTED; + const int64_t T = M / cdiv; + const int64_t To = (T + 2 * pad - kh) / st + 1, Wo = (W + 2 * pad - kw) / st + 1; + Opd o; + o.t(D, { T, W * cin }); /* x */ + o.t(D, { cout, cin, kh, kw }); /* w */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t_idx({ T * vst }, 2, -1, 0); /* valid: 0 or 1 a row */ + o.t(D, { To, Wo * cout }); /* y */ + return o.finish("conv2d", operand, out); +} + +int ref_conv1d_dw_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), C = gi(p, n_p, "n", 0), K = gi(p, n_p, "k", 0); + const int64_t cdiv = gi(p, n_p, "cu_div", 1); + if (M <= 0 || cdiv <= 0 || M % cdiv) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M / cdiv, C }); /* x */ + 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 */ + return o.finish("conv1d_dw", operand, out); +} + +int ref_rel_sinusoid_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 }); /* y */ + return o.finish("rel_sinusoid", operand, out); +} + +int ref_attn_local_rel_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), hd = gi(p, n_p, "head_dim", 0); + const int64_t H = gi(p, n_p, "n_head", 0), L = gi(p, n_p, "left", 0); + const int64_t cdiv = gi(p, n_p, "cu_div", 1); + if (M <= 0 || cdiv <= 0 || M % cdiv || L < 0) return RAD_E_UNSUPPORTED; + const int64_t T = M / cdiv; + Opd o; + o.t(D, { T, H * hd }); /* q */ + o.t(D, { T, H * hd }); /* k */ + o.t(D, { T, H * hd }); /* v */ + o.t(D, { L + 1, H * hd }); /* relk */ + o.t(D, { hd }); /* pds */ + o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { T, H * hd }); /* out */ + return o.finish("attn_local_rel", operand, out); +} + int ref_silu_mul_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); @@ -1017,7 +1142,34 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* * the parameters could know it. The vocabulary's `qk_norm_rope` takes the same contiguous fused * [q|k|v] row `rope` does, so it is describable and is described. */ o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */ - o.t_idx({ M }, 0, -1, 0); /* positions */ + /* `blocks` takes a position per component, [C, M] component-major, C being one past the + * largest component `comps` names (the section count when it names none). */ + const char* mode = gs(p, n_p, "mode"); + if (mode && !std::strcmp(mode, "blocks")) { + int64_t nc = 0; + for (const char* q = gs(p, n_p, "sections"); q && *q; ) { + char* e = nullptr; + (void)std::strtoll(q, &e, 10); + if (e == q) break; + ++nc; + q = e; + } + if (const char* cs = gs(p, n_p, "comps")) { + int64_t mx = -1; + for (const char* q = cs; *q; ) { + char* e = nullptr; + const long long x = std::strtoll(q, &e, 10); + if (e == q) break; + mx = x > mx ? x : mx; + q = e; + } + nc = mx + 1; + } + if (nc <= 0) return RAD_E_UNSUPPORTED; + o.t_idx({ nc, M }, M, -1, 0); /* positions */ + } else { + o.t_idx({ M }, 0, -1, 0); /* positions */ + } o.t(D, { hd }); /* q_w -- one gain per head channel */ o.t(D, { hd }); /* k_w */ return o.finish("qk_norm_rope", operand, out); diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 1540f514..357c8b04 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -90,9 +90,12 @@ struct RadBuilder { /* The buffer the plugin named as this step's logits (rad_declare_logits). */ rad_buf logits = 0; - /* The vision tower's declaration (rad_declare_encoder), when the plugin made one. */ + /* The vision tower's declaration (rad_declare_encoder), when the plugin made one, and the + * audio encoder's. */ RadEncoderDecl encoder{}; std::string encoder_name; + RadEncoderDecl audio_encoder{}; + std::string audio_encoder_name; /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty * is a builder with no model behind it, where every weight is plain in its declared dtype. */ @@ -248,6 +251,11 @@ extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { } extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; + if (d->modalities == RAD_MM_AUDIO) { + b->audio_encoder = *d; + b->audio_encoder_name = d->name; + return RAD_OK; + } b->encoder = *d; b->encoder_name = d->name; return RAD_OK; diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp index 3d277cd1..11cde127 100644 --- a/tests/mm_test.cpp +++ b/tests/mm_test.cpp @@ -15,8 +15,12 @@ #include "mm/media.h" #include "mm/processor.h" #include "mm_golden.h" +#include "rad_plugin.h" +#include +#include #include +#include #include #include #include @@ -332,4 +336,51 @@ TEST(a_media_configuration_with_an_empty_band_names_it) { CHECK(why.find("max_frames") != std::string::npos); } +/* THE AUDIO FRONT END IS THE REFERENCE'S. Gemma4AudioFeatureExtractor (transformers 5.18) on a + * 16037-sample tone (0.5 sin 440 Hz + 0.25 sin 3 kHz at 16 kHz): 100 real frames, and these + * log-mel values. The front end stores bf16, so each is checked to bf16's resolution. */ +TEST(the_audio_front_end_is_the_references) { + mm::AudioConfig c; + c.rate = 16000; c.frame_length = 320; c.hop = 160; c.fft = 512; c.n_mels = 128; + c.min_freq = 0.0; c.max_freq = 8000.0; c.mel_floor = 1e-3; + c.max_samples = 480000; + c.tok_audio = 258881; c.tok_start = 256000; c.tok_end = 258883; + c.merge = 4; c.max_frames = 3000; + mm::Processor p; + CHECK_EQ(p.init_audio(c), RAD_OK); + const int n = 16037; + std::vector x((size_t)n); + for (int i = 0; i < n; ++i) { + const float t = (float)i / 16000.0f; + x[(size_t)i] = 0.5f * std::sin(2.0f * 3.14159265358979f * 440.0f * t) + + 0.25f * std::sin(2.0f * 3.14159265358979f * 3000.0f * t); + } + std::shared_ptr it; + std::string why; + CHECK_EQ(p.audio_from(x, &it, &why), RAD_OK); + CHECK(it != nullptr); + if (!it) return; + CHECK_EQ(it->valid, 100); + CHECK_EQ(it->seg_rows, 25); + CHECK_EQ(it->grid_h, 100); + CHECK_EQ(it->expand.size(), (size_t)27); + CHECK_EQ(it->expand.front(), 256000); + CHECK_EQ(it->expand.back(), 258883); + struct Want { int frame, bin; float v; }; + const Want want[] = { { 0, 0, -6.907755374908447f }, { 0, 14, 0.5496962070465088f }, + { 1, 14, -2.903297185897827f }, { 50, 14, -2.905748128890991f }, + { 50, 96, -5.7037482261657715f }, { 99, 14, -2.902763605117798f }, + { 99, 127, -5.386524200439453f } }; + for (const Want& w : want) { + const float got = rad_bf16_to_f32(it->pixels[(size_t)(w.frame * 128 + w.bin)]); + CHECK_NEAR(got, w.v, 0.008f * std::max(1.0f, std::fabs(w.v))); + } + /* A clip shorter than one real frame is and nothing to encode. */ + std::vector tiny(150, 0.1f); + CHECK_EQ(p.audio_from(tiny, &it, &why), RAD_OK); + CHECK_EQ(it->seg_rows, 0); + CHECK(it->encoded); + CHECK_EQ(it->expand.size(), (size_t)2); +} + RAD_TEST_MAIN() diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 02cfee3b..bfdf4c2f 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -936,4 +936,29 @@ TEST(libr4d_resolves_the_four_rank_fused_writes_on_the_exact_wire_only) { } } +/* THE VISION TOWER'S ATTENTION RESOLVES AS rad_block_vit.h DECLARES IT: head_dim 72, no `window`. + * `window` is optional in attn_dense's schema and a constraint on a key the geometry lacks does not + * hold, so a row that constrains it is unreachable for a caller that leaves it out -- which is how + * every Qwen image request on a card came to stop the engine with "no device kernel for this + * band". rad-kbench cannot see that: its cases always name the window. */ +TEST(libr4d_resolves_the_vision_attention_without_a_window) { + const std::string so = home() + "/kernels/libr4d.so"; + if (access(so.c_str(), R_OK) != 0) { + fprintf(stderr, " SKIP %s: no %s (a build without HIP)\n", ::radtest::current(), + so.c_str()); + return; + } + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + Geometry g; + g.set_i("head_dim", 72); + g.set_i("gqa", 1); + g.set_i("causal", 0); + g.set_s("dtype", "bf16"); + g.set_i("max_seqlen", 16384); + const std::vector b = r.build_bands("attn_dense", "M", 1, 16384, g); + CHECK(!b.empty()); + for (const Band& x : b) CHECK_EQ(picked(x.dom[RAD_DOMAIN_DEVICE].row), "attn_vit_h72_bf16"); +} + RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 8c254434..82e328d8 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -255,14 +255,15 @@ TEST(plugin_surface) { TEST(op_vocabulary) { static const char* kOps[] = { "rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter", - "layernorm", "add", "mul", "silu_mul", "gelu", "silu", + "layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows", + "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "embed_lookup_q", "cast", "scale_rows", "softmax", "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "had_quant_act_i8", "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands - * between RADIANCE_HOST_DOMAIN and "site 'host' is unavailable for this band". */ + * between a host-backend run and "site 'host' is unavailable for this band". */ "rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select", "rmsnorm_had_quant_i8", "gated_had_quant_i8", @@ -1712,6 +1713,266 @@ TEST(op_attn_dense) { CHECK_NEAR(o.at(3), 1.0f / sum, 1e-6); } +/* THE WINDOW IS TWO-SIDED WHEN THE ATTENTION IS: with window 2 a key one position away either + * side is visible and one two away is not. Three tokens, unit queries and keys, values that say + * which key they came from -- token 0 sees keys 0..1, token 1 sees 0..2, token 2 sees 1..2. */ +TEST(op_attn_dense_window) { + T q(RAD_F32, {3, 1, 1}); q.f({0, 0, 0}); /* zero scores: a plain mean of the keys */ + T k(RAD_F32, {3, 1, 1}); k.f({0, 0, 0}); + T v(RAD_F32, {3, 1, 1}); v.f({1, 10, 100}); + T cu(RAD_I32, {2}); cu.n({0, 3}); + T o(RAD_F32, {3, 1, 1}); + A a; a.t(q).t(k).t(v).t(cu).t(o) + .i("M", 3).i("head_dim", 1).i("gqa", 1).i("causal", 0).i("window", 2) + .s("dtype", "f32"); + CHECK_OK(run("attn_dense", a)); + CHECK_NEAR(o.at(0), 11.0f / 2, 1e-5); + CHECK_NEAR(o.at(1), 111.0f / 3, 1e-5); + CHECK_NEAR(o.at(2), 110.0f / 2, 1e-5); + /* Causal with the same window: token 2 sees keys 1..2 and nothing after itself. */ + T o2(RAD_F32, {3, 1, 1}); + A c; c.t(q).t(k).t(v).t(cu).t(o2) + .i("M", 3).i("head_dim", 1).i("gqa", 1).i("causal", 1).i("window", 2) + .s("dtype", "f32"); + CHECK_OK(run("attn_dense", c)); + CHECK_NEAR(o2.at(0), 1.0f, 1e-5); + CHECK_NEAR(o2.at(1), 11.0f / 2, 1e-5); + CHECK_NEAR(o2.at(2), 110.0f / 2, 1e-5); +} + +/* act_mul over two column slices of one fused row, the way an MLP's gate_up reaches it. */ +TEST(op_act_mul) { + T gu(RAD_F32, {2, 4}); gu.f({ 1, -2, 3, 4, 0.5f, 0, -1, 2 }); + T g(RAD_F32, {2, 2}), u(RAD_F32, {2, 2}); + g.t.data = gu.t.data; g.t.stride[0] = 4; + u.t.data = (void*)((float*)gu.t.data + 2); u.t.stride[0] = 4; + T y(RAD_F32, {2, 2}); + auto gt = [](float x) { return 0.5f * x * (1.0f + std::tanh(0.7978845608f * (x + 0.044715f * x * x * x))); }; + A a; a.t(g).t(u).t(y).i("M", 2).i("n", 2).s("act", "gelu_tanh").s("dtype", "f32"); + CHECK_OK(run("act_mul", a)); + CHECK_NEAR(y.at(0), gt(1) * 3, 1e-5); + CHECK_NEAR(y.at(1), gt(-2) * 4, 1e-5); + CHECK_NEAR(y.at(2), gt(0.5f) * -1, 1e-5); + CHECK_NEAR(y.at(3), 0.0f, 1e-6); + A bad; bad.t(g).t(u).t(y).i("M", 2).i("n", 2).s("act", "relu").s("dtype", "f32"); + CHECK(run("act_mul", bad) < 0); +} + +/* seg_mean: one row a segment, an empty segment a zero row. */ +TEST(op_seg_mean) { + T x(RAD_F32, {4, 2}); x.f({ 1, 2, 3, 4, 5, 6, 7, 9 }); + T cu(RAD_I32, {4}); cu.n({0, 3, 3, 4}); + T y(RAD_F32, {3, 2}); + A a; a.t(x).t(cu).t(y).i("M", 4).i("n", 2).s("dtype", "f32"); + CHECK_OK(run("seg_mean", a)); + CHECK_NEAR(y.at(0), 3.0f, 1e-6); CHECK_NEAR(y.at(1), 4.0f, 1e-6); + CHECK_EQ(y.at(2), 0.0f); CHECK_EQ(y.at(3), 0.0f); + CHECK_NEAR(y.at(4), 7.0f, 1e-6); CHECK_NEAR(y.at(5), 9.0f, 1e-6); +} + +/* relu and clamp: the plain element rules. */ +TEST(op_relu_clamp) { + T x(RAD_F32, {1, 3}); x.f({ -3.0f, 0.5f, 4.0f }); + T y(RAD_F32, {1, 3}); + A a; a.t(x).t(y).i("M", 1).i("n", 3).s("dtype", "f32"); + CHECK_OK(run("relu", a)); + CHECK_EQ(y.at(0), 0.0f); CHECK_EQ(y.at(1), 0.5f); CHECK_EQ(y.at(2), 4.0f); + T lo(RAD_F32, {1}); lo.f({ -1.0f }); + T hi(RAD_F32, {1}); hi.f({ 2.0f }); + A c; c.t(x).t(lo).t(hi).t(y).i("M", 1).i("n", 3).s("dtype", "f32"); + CHECK_OK(run("clamp", c)); + CHECK_EQ(y.at(0), -1.0f); CHECK_EQ(y.at(1), 0.5f); CHECK_EQ(y.at(2), 2.0f); +} + +/* rmsnorm's mult scales the normed row; act_mul's sigmoid is a GLU gate. */ +TEST(op_rmsnorm_mult_act_sigmoid) { + T x(RAD_F32, {1, 2}); x.f({ 3, 4 }); + T y(RAD_F32, {1, 2}); + A a; a.t(x).tnull().t(y).i("M", 1).i("n", 2).d("eps", 0.0).d("mult", 0.5).s("dtype", "f32"); + CHECK_OK(run("rmsnorm", a)); + const float r = 0.5f / std::sqrt(12.5f); + CHECK_NEAR(y.at(0), 3.0f * r, 1e-6); CHECK_NEAR(y.at(1), 4.0f * r, 1e-6); + T g(RAD_F32, {1, 2}); g.f({ 0.0f, 2.0f }); + T u(RAD_F32, {1, 2}); u.f({ 3.0f, 1.0f }); + A b; b.t(g).t(u).t(y).i("M", 1).i("n", 2).s("act", "sigmoid").s("dtype", "f32"); + CHECK_OK(run("act_mul", b)); + CHECK_NEAR(y.at(0), 1.5f, 1e-6); + CHECK_NEAR(y.at(1), 1.0f / (1.0f + std::exp(-2.0f)), 1e-6); +} + +/* conv2d: a 3x3 stride-2 window of ones over (time, width), each segment padded at its own + * edges, and the row mask. */ +TEST(op_conv2d) { + T x(RAD_F32, {4, 2}); x.f({ 1, 2, 3, 4, 5, 6, 7, 8 }); + T w(RAD_F32, {1, 1, 3, 3}); w.f({ 1, 1, 1, 1, 1, 1, 1, 1, 1 }); + T cu(RAD_I32, {2}); cu.n({ 0, 4 }); + T y(RAD_F32, {2, 1}); + auto args = [&](A& a) { + a.i("M", 4).i("width", 2).i("cin", 1).i("cout", 1).i("kh", 3).i("kw", 3).i("stride", 2) + .i("pad", 1).s("dtype", "f32"); + }; + A a; a.t(x).t(w).t(cu).tnull().t(y); args(a); + CHECK_OK(run("conv2d", a)); + CHECK_NEAR(y.at(0), 1 + 2 + 3 + 4, 1e-6); /* rows -1..1, cols -1..1 */ + CHECK_NEAR(y.at(1), 3 + 4 + 5 + 6 + 7 + 8, 1e-6); /* rows 1..3 */ + T valid(RAD_I32, {4}); valid.n({ 1, 1, 0, 1 }); + A b; b.t(x).t(w).t(cu).t(valid).t(y); args(b); + CHECK_OK(run("conv2d", b)); + CHECK_NEAR(y.at(1), 3 + 4 + 7 + 8, 1e-6); /* row 2 masked */ + T cu2(RAD_I32, {3}); cu2.n({ 0, 2, 4 }); + A c; c.t(x).t(w).t(cu2).tnull().t(y); args(c); + CHECK_OK(run("conv2d", c)); + CHECK_NEAR(y.at(0), 1 + 2 + 3 + 4, 1e-6); + CHECK_NEAR(y.at(1), 5 + 6 + 7 + 8, 1e-6); /* row 1 is the other segment's */ +} + +/* conv1d_dw: causal, the taps before a segment's start read as zero. */ +TEST(op_conv1d_dw) { + T x(RAD_F32, {4, 1}); x.f({ 1, 1, 1, 1 }); + T w(RAD_F32, {1, 1, 3}); w.f({ 1, 2, 3 }); + T cu(RAD_I32, {3}); cu.n({ 0, 2, 4 }); + T y(RAD_F32, {4, 1}); + A a; a.t(x).t(w).t(cu).t(y).i("M", 4).i("n", 1).i("k", 3).s("dtype", "f32"); + CHECK_OK(run("conv1d_dw", a)); + CHECK_NEAR(y.at(0), 3.0f, 1e-6); CHECK_NEAR(y.at(1), 5.0f, 1e-6); + CHECK_NEAR(y.at(2), 3.0f, 1e-6); CHECK_NEAR(y.at(3), 5.0f, 1e-6); +} + +/* rel_sinusoid: sin then cos over the timescales. */ +TEST(op_rel_sinusoid) { + T y(RAD_F32, {2, 4}); + A a; a.t(y).i("M", 2).i("n", 4).d("max_timescale", 10000.0).s("dtype", "f32"); + CHECK_OK(run("rel_sinusoid", a)); + const float inv1 = std::exp(-std::log(10000.0f)); + CHECK_EQ(y.at(0), 0.0f); CHECK_EQ(y.at(2), 1.0f); + CHECK_NEAR(y.at(4), std::sin(1.0f), 1e-6); CHECK_NEAR(y.at(5), std::sin(inv1), 1e-9); + CHECK_NEAR(y.at(6), std::cos(1.0f), 1e-6); CHECK_NEAR(y.at(7), std::cos(inv1), 1e-6); +} + +/* attn_local_rel: the window, the relative term and the softcap, against the formula. */ +TEST(op_attn_local_rel) { + const int Tn = 3, D = 2, L = 1; + T q(RAD_F32, {Tn, D}); q.f({ 0.5f, -1.0f, 1.0f, 0.25f, -0.5f, 2.0f }); + T k(RAD_F32, {Tn, D}); k.f({ 1.0f, 0.0f, 0.5f, 0.5f, -1.0f, 1.5f }); + T v(RAD_F32, {Tn, D}); v.f({ 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f }); + T rk(RAD_F32, {L + 1, D}); rk.f({ 0.1f, 0.2f, -0.3f, 0.4f }); + T pds(RAD_F32, {D}); pds.f({ 0.0f, 1.0f }); + T cu(RAD_I32, {2}); cu.n({ 0, Tn }); + T o(RAD_F32, {Tn, D}); + A a; a.t(q).t(k).t(v).t(rk).t(pds).t(cu).t(o).i("M", Tn).i("head_dim", D).i("n_head", 1) + .i("left", L).i("right", 0).d("softcap", 5.0).s("dtype", "f32"); + CHECK_OK(run("attn_local_rel", a)); + const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0)); + const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0)); + for (int i = 0; i < Tn; ++i) { + float lg[2], p[2], qf[2]; + for (int d = 0; d < D; ++d) { + const float x = pds.at(d); + qf[d] = q.at(i * D + d) * qs * std::log1p(std::exp(x)); + } + const int j0 = i - L > 0 ? i - L : 0; + float mx = -1e30f, sum = 0.0f; + for (int j = j0; j <= i; ++j) { + float s = 0.0f; + for (int d = 0; d < D; ++d) + s += qf[d] * k.at(j * D + d) * ks + qf[d] * rk.at((i - j) * D + d); + lg[j - j0] = 5.0f * std::tanh(s / 5.0f); + mx = lg[j - j0] > mx ? lg[j - j0] : mx; + } + for (int j = j0; j <= i; ++j) { p[j - j0] = std::exp(lg[j - j0] - mx); sum += p[j - j0]; } + for (int d = 0; d < D; ++d) { + float acc = 0.0f; + for (int j = j0; j <= i; ++j) acc += p[j - j0] / sum * v.at(j * D + d); + CHECK_NEAR(o.at(i * D + d), acc, 1e-5); + } + } +} + +/* pool_rows: the mean of every k rows, rounded, then the multiplier. */ +TEST(op_pool_rows) { + T x(RAD_F32, {4, 2}); x.f({ 1, 2, 3, 4, 5, 6, 7, 9 }); + T y(RAD_F32, {2, 2}); + A a; a.t(x).t(y).i("M", 4).i("n", 2).i("k", 2).d("mult", 2.0).s("dtype", "f32"); + CHECK_OK(run("pool_rows", a)); + CHECK_NEAR(y.at(0), 4.0f, 1e-6); CHECK_NEAR(y.at(1), 6.0f, 1e-6); + CHECK_NEAR(y.at(2), 12.0f, 1e-6); CHECK_NEAR(y.at(3), 15.0f, 1e-6); + A bad; bad.t(x).t(y).i("M", 4).i("n", 2).i("k", 3).s("dtype", "f32"); + CHECK(run("pool_rows", bad) < 0); +} + +/* rmsnorm with no gain: a unit gain. */ +TEST(op_rmsnorm_no_gain) { + T x(RAD_F32, {1, 2}); x.f({ 3, 4 }); + T y(RAD_F32, {1, 2}); + A a; a.t(x).tnull().t(y).i("M", 1).i("n", 2).d("eps", 0.0).s("dtype", "f32"); + CHECK_OK(run("rmsnorm", a)); + const float r = 1.0f / std::sqrt(12.5f); + CHECK_NEAR(y.at(0), 3.0f * r, 1e-6); CHECK_NEAR(y.at(1), 4.0f * r, 1e-6); +} + +/* qk_norm_rope `blocks`: each section rotates its own channel block by its own component. */ +TEST(op_qk_norm_rope_blocks) { + /* one token, one q head and one k head of 8 channels; sections "2 2", comps "1 0". */ + T qkv(RAD_F32, {1, 24}); + std::vector v(24); + for (int i = 0; i < 24; ++i) v[(size_t)i] = 0.1f * (float)(i + 1); + qkv.f(v); + T pos(RAD_I32, {2, 1}); pos.n({ 3, 5 }); + T qw(RAD_F32, {8}); qw.f({ 1, 1, 1, 1, 1, 1, 1, 1 }); + T kw(RAD_F32, {8}); kw.f({ 1, 1, 1, 1, 1, 1, 1, 1 }); + A a; a.t(qkv).t(pos).t(qw).t(kw).i("M", 1).i("head_dim", 8).i("n_head", 1).i("n_head_kv", 1) + .d("theta", 100.0).d("eps", 0.0).s("mode", "blocks").s("sections", "2 2").s("comps", "1 0"); + CHECK_OK(run("qk_norm_rope", a)); + /* The q head: normed, then block 0 (channels 0..3) turned by component 1 (5) and block 1 + * (channels 4..7) by component 0 (3), pairs (j, j+2) at theta^(-j/2). */ + float h[8], ss = 0.0f; + for (int i = 0; i < 8; ++i) { h[i] = 0.1f * (float)(i + 1); ss += h[i] * h[i]; } + const float sc = 1.0f / std::sqrt(ss / 8.0f); + for (int i = 0; i < 8; ++i) h[i] *= sc; + const float p[2] = { 5.0f, 3.0f }; + for (int c = 0; c < 2; ++c) + for (int j = 0; j < 2; ++j) { + const float ang = p[c] / std::pow(100.0f, (float)j / 2.0f); + const float x0 = h[4 * c + j], x1 = h[4 * c + 2 + j]; + CHECK_NEAR(qkv.at(4 * c + j), x0 * std::cos(ang) - x1 * std::sin(ang), 1e-5); + CHECK_NEAR(qkv.at(4 * c + 2 + j), x0 * std::sin(ang) + x1 * std::cos(ang), 1e-5); + } +} + +/* mul_weight: a one-element weight scales every element, a one-row weight every column. */ +TEST(op_mul_weight) { + T x(RAD_F32, {2, 3}); x.f({ 1, 2, 3, 4, 5, 6 }); + T s(RAD_F32, {1}); s.f({ 0.5f }); + T y(RAD_F32, {2, 3}); + A a; a.t(x).t(s).t(y).i("M", 2).i("n", 3).s("dtype", "f32"); + CHECK_OK(run("mul_weight", a)); + for (int i = 0; i < 6; ++i) CHECK_NEAR(y.at(i), 0.5f * (float)(i + 1), 1e-6); + T r(RAD_F32, {3}); r.f({ 1, 10, 100 }); + A b; b.t(x).t(r).t(y).i("M", 2).i("n", 3).s("dtype", "f32"); + CHECK_OK(run("mul_weight", b)); + CHECK_NEAR(y.at(4), 50.0f, 1e-6); + T bad(RAD_F32, {2}); bad.f({ 1, 2 }); + A c; c.t(x).t(bad).t(y).i("M", 2).i("n", 3).s("dtype", "f32"); + CHECK(run("mul_weight", c) < 0); +} + +/* v_norm: the v heads are RMS-normed with unit gain and not rotated; q and k as before. */ +TEST(op_qk_norm_rope_v_norm) { + T qkv(RAD_F32, {1, 6}); qkv.f({ 3, 4, 1, 1, 6, 8 }); /* one q, one k, one v head of 2 */ + T pos(RAD_I32, {1}); pos.n({ 0 }); /* position 0: no rotation */ + T qw(RAD_F32, {2}); qw.f({ 1, 1 }); + T kw(RAD_F32, {2}); kw.f({ 2, 2 }); + A a; a.t(qkv).t(pos).t(qw).t(kw) + .i("M", 1).i("head_dim", 2).i("n_head", 1).i("n_head_kv", 1) + .d("theta", 10000.0).d("eps", 0.0).i("v_norm", 1); + CHECK_OK(run("qk_norm_rope", a)); + const float r = 1.0f / std::sqrt(12.5f); + CHECK_NEAR(qkv.at(0), 3 * r, 1e-5); CHECK_NEAR(qkv.at(1), 4 * r, 1e-5); + CHECK_NEAR(qkv.at(2), 2.0f, 1e-5); CHECK_NEAR(qkv.at(3), 2.0f, 1e-5); + const float rv = 1.0f / std::sqrt(50.0f); + CHECK_NEAR(qkv.at(4), 6 * rv, 1e-5); CHECK_NEAR(qkv.at(5), 8 * rv, 1e-5); +} + TEST(op_kv_store) { T k(RAD_F32, {2, 1, 2}); k.f({1, 2, 5, 6}); T v(RAD_F32, {2, 1, 2}); v.f({3, 4, 7, 8}); diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 6e003849..1f40f37e 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -240,8 +240,8 @@ struct FakeGrammar : IGrammarCompiler { * server's own validation of them. */ struct FakeMultimodal : IMultimodal { bool accepts(MediaKind) const override { return true; } - int prepare(MediaKind, const std::vector&, std::shared_ptr* out, - std::string*) override { + int prepare(MediaKind, const std::vector&, const MediaOpts&, + std::shared_ptr* out, std::string*) override { auto it = std::make_shared(); it->expand = { 0 }; *out = std::move(it); @@ -2807,6 +2807,75 @@ TEST(a_raw_prompt_parses_control_tokens_on_every_endpoint_that_takes_one) { } } +/* An embedding model's request fields: prompt_name puts the model's named prompt in front of text + * and content-part inputs and is refused on token ids and on a name the model does not state; + * dimensions must be a positive integer; image_tokens one of the trained budgets; a messages input + * renders through the model's template and excludes `input`. */ +struct FakeEmbedder final : IEmbedder { + IChatTemplate* tpl = nullptr; + int64_t dim() const override { return 768; } + int64_t max_input() const override { return 8192; } + bool prompt(const std::string& name, std::string* text) const override { + if (name != "query") return false; + *text = "task: search result | query: "; + return true; + } + IChatTemplate* message_template() const override { return tpl; } +}; + +TEST(embeddings_take_the_models_named_prompts_and_its_fields) { + Fixture f; + FakeEmbedder emb; + emb.tpl = &f.tmpl; + OaiDeps d = f.odeps(); + d.embed = &emb; + { + OaiRequest r; ApiError e; + CHECK_OK(parse_embeddings_request(R"({"input":"capital?","prompt_name":"query"})", d, + f.limits(), &r, &e)); + CHECK_EQ(r.prompts.size(), (size_t)1); + CHECK_EQ(r.prompts[0].text, std::string("task: search result | query: capital?")); + } + { + OaiRequest r; ApiError e; + CHECK_OK(parse_embeddings_request(R"({"input":["a","b"],"prompt_name":"query"})", d, + f.limits(), &r, &e)); + CHECK_EQ(r.prompts.size(), (size_t)2); + CHECK_EQ(r.prompts[1].text, std::string("task: search result | query: b")); + } + { + OaiRequest r; ApiError e; + CHECK(parse_embeddings_request(R"({"input":"x","prompt_name":"nope"})", d, f.limits(), + &r, &e) < 0); + CHECK_EQ(e.param, std::string("prompt_name")); + } + { + OaiRequest r; ApiError e; + CHECK(parse_embeddings_request(R"({"input":[1,2,3],"prompt_name":"query"})", d, + f.limits(), &r, &e) < 0); + } + { + OaiRequest r; ApiError e; + CHECK_OK(parse_embeddings_request(R"({"input":"x","dimensions":256})", d, f.limits(), &r, + &e)); + CHECK_EQ(r.dimensions, (int64_t)256); + CHECK(parse_embeddings_request(R"({"input":"x","dimensions":0})", d, f.limits(), &r, + &e) < 0); + CHECK(parse_embeddings_request(R"({"input":"x","image_tokens":300})", d, f.limits(), &r, + &e) < 0); + } + { + OaiRequest r; ApiError e; + CHECK_OK(parse_embeddings_request( + R"({"messages":[{"role":"user","content":"hello"}]})", d, f.limits(), &r, &e)); + CHECK_EQ(r.prompts.size(), (size_t)1); + CHECK(!r.prompts[0].tokens.empty()); + CHECK(parse_embeddings_request( + R"({"input":"x","messages":[{"role":"user","content":"hello"}]})", d, + f.limits(), &r, &e) < 0); + } +} + TEST(detokenize_answers_under_the_key_vllm_uses) { Fixture f; HttpResponse r = f.post("/detokenize", R"({"tokens":[65,66,67]})"); diff --git a/tests/wire_test.cpp b/tests/wire_test.cpp index c33c714d..50c8c085 100644 --- a/tests/wire_test.cpp +++ b/tests/wire_test.cpp @@ -183,6 +183,25 @@ TEST(base64_decode_rejects_a_character_outside_the_alphabet) { CHECK_EQ(out.size(), 0u); } +/* Every length mod 3 round-trips; padding and whitespace are skipped wherever they stand, which + * splits the four-digit blocks the decoder takes at once; anything else is refused. */ +TEST(base64_round_trips_and_refuses_stray_bytes) { + std::vector bytes(1000); + for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = (uint8_t)((i * 2654435761u) >> 13); + for (size_t n : { 0, 1, 2, 3, 4, 5, 999, 1000 }) { + std::vector got; + CHECK(base64_decode(base64_encode(bytes.data(), n), &got)); + CHECK(got == std::vector(bytes.begin(), bytes.begin() + (long)n)); + } + std::string e = base64_encode(bytes.data(), 100), spaced; + for (size_t i = 0; i < e.size(); ++i) { spaced += e[i]; if (i % 7 == 3) spaced += (i % 2 ? "\n" : " "); } + std::vector got; + CHECK(base64_decode(spaced, &got)); + CHECK(got == std::vector(bytes.begin(), bytes.begin() + 100)); + CHECK(!base64_decode("QUJD*REVG", &got)); + CHECK(!base64_decode("QUJDREVG\x80", &got)); +} + /* ================================================================== ids and errors */ TEST(a_random_id_carries_its_prefix_and_does_not_repeat) { diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index ae9324ef..d822fcbd 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -516,7 +516,17 @@ int main(int argc, char** argv) { } ctx.max_spec = max_spec; /* AND THE ENCODER, for the draft head's reason. */ - if (rad_meta_geti(&meta.m, "vision_config.patch_size", 0) > 0) ctx.max_enc_patches = 16384; + if (rad_meta_geti(&meta.m, "vision_config.patch_size", 0) > 0) { + ctx.max_enc_patches = 16384; + RadArchProbe probe{}; + (void)rad_tools_probe(plugins, meta.m, &probe); + if (probe.enc_merge > 1) ctx.max_enc_patches -= ctx.max_enc_patches % probe.enc_merge; + } + { + RadArchProbe probe{}; + (void)rad_tools_probe(plugins, meta.m, &probe); + ctx.max_audio_frames = probe.audio_frames > 0 ? probe.audio_frames : 0; + } /* THE ENCODING EVERY WEIGHT WILL HAVE, answered to declare as rad_weight_encoding: the * recipe's when a rule matches, the checkpoint's own when it is trivial. Remembered once @@ -749,7 +759,14 @@ int main(int argc, char** argv) { w.meta_f("rope_theta", meta.m.rope_theta); for (int i = 0; i < meta.m.n_kv; ++i) w.meta_s(meta.m.kv_key[i], meta.m.kv_val[i]); /* THE CONTAINER CARRIES AN ENCODER'S WEIGHTS: what `--mm-max-patches auto` keys on. */ - if (prog.encoder.modalities != 0) w.meta_s("radiance.encoder", prog.encoder_name.c_str()); + /* The encoders the container carries, by name: a vision tower, an audio encoder, or both. */ + { + std::string enc; + if (prog.encoder.modalities != 0) enc = prog.encoder_name; + if (prog.audio_encoder.modalities != 0) + enc += (enc.empty() ? "" : ",") + prog.audio_encoder_name; + if (!enc.empty()) w.meta_s("radiance.encoder", enc.c_str()); + } /* ---------------------------------------------------------------- the weights * diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp index 784eee63..2db4b432 100644 --- a/tools/rad_kbench.cpp +++ b/tools/rad_kbench.cpp @@ -1495,6 +1495,9 @@ void usage() { " filter does not change any other case's inputs\n" " --tol X override every tolerance with X (for bisecting, not for passing)\n" " --max-tok N the max_tok declare is run at (default 512; small on purpose)\n" + " --mm-max-patches N the encoder pass declare is run at, so a media tower's\n" + " kernels are in the graph: default 2048 (rounded to whole output\n" + " rows) when the container carries an encoder, 0 to leave it out\n" " --no-fusion skip the fusion oracle: a kernel that declares the chain it\n" " replaces is otherwise run against that chain, out of its own\n" " plugin, and the outputs compared BYTE for byte\n" @@ -1539,6 +1542,11 @@ int main(int argc, char** argv) { uint64_t seed = 20260904; double tol_override = -1; int64_t max_tok = 512; + /* THE ENCODER PASS. A program declared with no pass has no media tower in it, and none of the + * tower's kernels would ever be checked. -1 is auto: a pass when the container carries an + * encoder (radiance.encoder), smaller than a serve's -- the tower's ops are the same kernels + * at every pass size, and the cases are capped per geometry anyway. */ + int64_t mm_max_patches = -1; /* THE DEEPEST CONTEXT AN ATTENTION CASE IS BUILT AT. A paged KV cache at this depth is * allocated per case, so it is a memory budget as much as a coverage choice: at 16384 the * 27B's cache is 67 MB a case, at 262144 it would be a gigabyte. The sweep takes 2048 and @@ -1610,6 +1618,7 @@ int main(int argc, char** argv) { else if (a == "--tol") tol_override = std::strtod(next("--tol"), nullptr); else if (a == "--max-tok") max_tok = std::atoll(next("--max-tok")); else if (a == "--max-ctx") max_ctx_flag = std::atoll(next("--max-ctx")); + else if (a == "--mm-max-patches") mm_max_patches = std::atoll(next("--mm-max-patches")); else if (a == "--kv-cache-dtype") { const std::string v = next("--kv-cache-dtype"); if (v == "fp8") kv_dtype = RAD_F8E4M3; @@ -1757,6 +1766,20 @@ int main(int argc, char** argv) { RadArchProbe probe{}; (void)rad_tools_probe(plugins, meta, &probe); ctx.max_spec = n_spec >= 0 ? n_spec : probe.draft_depth; + if (mm_max_patches < 0) { + const char* enc = rad_meta_gets(&meta, "radiance.encoder", ""); + mm_max_patches = (enc && *enc) ? 2048 : 0; + } + if (mm_max_patches > 0 && probe.enc_merge > 1) + mm_max_patches -= mm_max_patches % probe.enc_merge; + ctx.max_enc_patches = mm_max_patches > 0 ? mm_max_patches : 0; + { + const char* enc = rad_meta_gets(&meta, "radiance.encoder", ""); + if (mm_max_patches != 0 && enc && std::strstr(enc, "audio") && probe.audio_frames > 0) + ctx.max_audio_frames = probe.audio_frames; + } + if (ctx.max_enc_patches > 0) + RAD_INFO(" encoder pass %lld patches (--mm-max-patches)", (long long)ctx.max_enc_patches); ctx.max_seqs = 8; ctx.max_ctx = max_ctx_flag > 0 ? max_ctx_flag : meta.n_ctx_train; ctx.kv_dtype = kv_dtype; @@ -2090,6 +2113,21 @@ int main(int argc, char** argv) { ++st.skipped; continue; } + /* AN OPTIONAL WEIGHT THE DECLARATION LEAVES UNBOUND IS ABSENT, as it is at every + * launch: a norm with no gain, a LayerNorm with no bias. The description names + * the operand because the op can take it; this call does not, so both sides get + * a null tensor. The weight list is positional over WEIGHT-role operands, so an + * unbound one still takes its place in it. */ + { + size_t wpos = 0; + for (size_t k = 0; k < sh.size() && k < (size_t)o.schema->n_operands; ++k) { + const RadOperandSpec& os = o.schema->operands[k]; + if (os.role != RAD_OPD_WEIGHT) continue; + const rad_weight h = wpos < o.weights.size() ? o.weights[wpos] : 0; + ++wpos; + if (!h && os.optional) sh[k].absent = true; + } + } /* TWO LIBRARIES CAN DISAGREE ABOUT WHAT AN OP IS, AND THAT IS NOT A FAILING * KERNEL.