Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d840861af | ||
|
|
05af4db458 |
No files matched your search
+8
-7
@@ -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.2 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()
|
||||
|
||||
|
||||
+6
-6
@@ -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 \
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
|
||||
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
|
||||
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
|
||||
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
|
||||
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
|
||||
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
|
||||
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, the
|
||||
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
|
||||
decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
|
||||
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
|
||||
serving any world size from the shipped container, the request log, an uneven world's per-rank
|
||||
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
|
||||
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
|
||||
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
|
||||
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
|
||||
tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the
|
||||
fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana
|
||||
dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form
|
||||
and row groups, the fused router launch, the adaptive draft window, the MoE prefill forms and the
|
||||
sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000
|
||||
(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, the request log, an uneven world's
|
||||
per-rank KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary
|
||||
paths).
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -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
|
||||
|
||||
+45
-2
@@ -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);
|
||||
|
||||
+10
-4
@@ -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
|
||||
|
||||
@@ -65,8 +65,10 @@
|
||||
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
|
||||
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
|
||||
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Here it also buys
|
||||
* something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
|
||||
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
|
||||
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
|
||||
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* global without an all-gather and the selector's codebooks can be indexed directly.
|
||||
*
|
||||
* ============================== THE NORMS ARE PLAIN ==============================
|
||||
@@ -230,10 +232,11 @@ struct Dflash2 {
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* THE SIX LINEARS ARE FP8 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
|
||||
* block fp8 and the recipe makes it so -- and the reason is bytes: the drafter is read WHOLE on
|
||||
* every decode step, which makes it one of the largest single items in the decode budget
|
||||
* after the trunk's own GEMMs.
|
||||
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
|
||||
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
|
||||
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
|
||||
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
|
||||
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
|
||||
* Nothing it computes can change an emitted token, because every draft is verified against the
|
||||
* trunk exactly; the only thing quantising it can move is acceptance. */
|
||||
DenseFP8 w_fc{};
|
||||
@@ -284,6 +287,14 @@ struct Dflash2 {
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
|
||||
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
|
||||
rad_weight w_lm = 0;
|
||||
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
|
||||
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
@@ -471,8 +482,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
|
||||
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
|
||||
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
|
||||
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
|
||||
* pass is `block` rows by construction.
|
||||
@@ -489,12 +502,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
|
||||
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -515,18 +523,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
|
||||
* weight its prefetch interval and its residency class, so two weights want two ops even
|
||||
* where one would issue both. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -603,24 +601,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h2q, w.h2s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -633,12 +616,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.atq, w.ats}, {w.h});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
@@ -650,12 +628,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h2q, w.h2s}, {w.gate_up});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
|
||||
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
|
||||
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
|
||||
@@ -667,7 +640,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* because M > 64 is a refusal in the kernel and not a slower path. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0) {
|
||||
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
@@ -678,12 +651,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffq, w.ffs}, {w.h});
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
|
||||
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
|
||||
@@ -789,31 +757,56 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
|
||||
* replicated, so that graph is the one it always was -- an optional parameter present with
|
||||
* the value 0 is not the same declaration as an absent one. */
|
||||
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
|
||||
if (!rerank) top_w = cfg.sel_topk;
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_INT("R", top_w), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
|
||||
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
|
||||
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
|
||||
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
|
||||
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
|
||||
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
|
||||
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
|
||||
*
|
||||
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
|
||||
* gather and merge below then rank exact values. A replicated draft head above one rank
|
||||
* proposes ids another rank owns, so it keeps its own scores. */
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("n_vocab", head_rows(g)), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
rad_buf rd[2] = { w.sel_h, w.cand };
|
||||
rad_buf wr[3] = { w.cand, w.unary, w.dpair };
|
||||
rad_op_reads (b, op_drerank, rd, 2);
|
||||
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
|
||||
}
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
|
||||
* candidate gather carries `row`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.sel_topk * 2),
|
||||
RAD_INT("numel", srows * top_w * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", cfg.sel_topk * 2)),
|
||||
RAD_INT("row", top_w * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -851,16 +844,16 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
* rows. */
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -898,11 +891,11 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
@@ -919,7 +912,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
|
||||
* its coefficients come from the replicated pre-attention norm, so either order is the
|
||||
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
|
||||
@@ -941,13 +934,12 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
@@ -980,15 +972,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), RAD_NONE);
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
+55
-2
@@ -1127,11 +1127,35 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
*/
|
||||
struct DenseFP8 {
|
||||
rad_weight w = 0, s = 0;
|
||||
/* OR AN OCP-MXFP4 WEIGHT, when that is what the container holds for it (a recipe's `codes=
|
||||
* fp4_e2m1 group=32 scale=e8m0`): e2m1 codes, the E8M0 plane, and that plane again as the
|
||||
* per-row reference -- LinearFP8's mx branch, without the GEMM. A block that declares its own
|
||||
* GEMM over a DenseFP8 asks `gemm()` for it and passes `bref()` as the op's last operand, so
|
||||
* one block serves either format against the same E4M3 activation pair. */
|
||||
rad_weight ref = 0;
|
||||
bool mx = false;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts = {});
|
||||
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
|
||||
if (mx)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
}
|
||||
/* The op's trailing `b_ref` operand: the reference view for MXFP4, absent for fp8. */
|
||||
RadOperand bref() const { return mx ? RAD_W(ref) : RAD_NONE; }
|
||||
};
|
||||
|
||||
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
@@ -1139,6 +1163,36 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts) {
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---- OCP-MXFP4, read off the encoding the name map resolves to. The exponent grid is one row
|
||||
* tall, so a part needs only whole 16-row tiles; K takes whole 128s because the E4M3 activation
|
||||
* in front carries a scale per (row, 128). */
|
||||
{
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
RadEncoding enc{};
|
||||
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
|
||||
if (mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
|
||||
"in 16s and K in whole %d-column activation scale blocks.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t q : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, p, np);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
return w && s && ref ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
|
||||
"%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
|
||||
@@ -1163,8 +1217,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
}
|
||||
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sn = nm.f("%s.scale", base); /* the name map was made above */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np);
|
||||
s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard,
|
||||
grp, sp, np);
|
||||
|
||||
@@ -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=<radiance prefix>`) -- 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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -493,13 +493,24 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
* vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
|
||||
* op declared over it is a read past its end. */
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, dc.sel_topk});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, dc.sel_topk});
|
||||
/* THE CANDIDATES ARE RESCORED against the target's head when logit_rerank can read its plane
|
||||
* (fp8 or int8 rows) and every candidate a rank proposes is one it owns -- the rule the block
|
||||
* applies; the planes are then kRerankR wide and the selector reads the first sel_topk. */
|
||||
{
|
||||
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
|
||||
if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
m.df.w_lm = m.w_lm_head;
|
||||
m.df.top_w = Dflash2::kRerankR;
|
||||
}
|
||||
}
|
||||
const int64_t tw = m.df.w_lm ? m.df.top_w : dc.sel_topk;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
|
||||
/* The vocab-parallel candidate exchange, and only when there is one: this rank's top-R as
|
||||
* (int32 id, float value) pairs and the all-gathered world_size * R of them. */
|
||||
if (Dflash2::head_sharded(dg)) {
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, dc.sel_topk, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.sel_topk, 2});
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
/* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through
|
||||
* the selector and never through the sampler's token buffer. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
+70
-17
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
+10
-1
@@ -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;
|
||||
|
||||
+31
-5
@@ -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<std::mutex> 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<std::mutex> 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);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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");
|
||||
|
||||
+212
-23
@@ -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<uint64_t> 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<float*>(
|
||||
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<mm::Processor>();
|
||||
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<server::MultimodalBridge>(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<mm::Processor>();
|
||||
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<server::MultimodalBridge>(
|
||||
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.
|
||||
*
|
||||
|
||||
@@ -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);
|
||||
|
||||
+17
-26
@@ -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 ----------------
|
||||
*
|
||||
|
||||
+85
-61
@@ -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=<dir> 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<BatchBuilder::EncoderPart> 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<mm::Item*> 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<BatchBuilder::EncoderPart> 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<int64_t>(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<int64_t>(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<mm::Item*>(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<const char*>(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<mm::Item*>(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<const char*>(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) {
|
||||
|
||||
@@ -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<int64_t>{ 1 } : t.shape;
|
||||
};
|
||||
const std::vector<int64_t> 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<int64_t> 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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+157
-3
@@ -10,8 +10,10 @@
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/imgutils.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
#include <libswscale/swscale.h>
|
||||
}
|
||||
#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<float>*,
|
||||
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<uint8_t*>(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<float>* 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<float> 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<uint8_t*>(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<const uint8_t**>(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 */
|
||||
|
||||
@@ -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<float>* out, std::string* why);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
+515
-6
@@ -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<int64_t> 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>((int64_t)std::floor((double)w / (double)h) * side, max_side);
|
||||
} else if (tw == 0) {
|
||||
tw = side;
|
||||
th = std::min<int64_t>((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<int64_t> 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<int64_t> 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<int64_t>(1, (int64_t)(duration * fps));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
idx.push_back(std::min<int64_t>(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<int64_t> 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<const uint8_t*>(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<const Frame*>& 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<const Frame*>& 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<Item>* 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<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* 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<Item>();
|
||||
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<Item>* 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<Item>();
|
||||
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<Frame> resized(v.frames.size());
|
||||
std::vector<const Frame*> 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 <boi> placeholders <eoi> 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<Item>* 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<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
std::shared_ptr<Item>* 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<int64_t> sample_cb(const VideoInfo& info, const void* user) {
|
||||
const SampleArgs* a = static_cast<const SampleArgs*>(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<Item>* 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<double> read_list(const RadModelMeta& m, const char* key) {
|
||||
std::vector<double> 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<double>& re, std::vector<double>& im,
|
||||
const std::vector<double>& tw_re, const std::vector<double>& tw_im,
|
||||
const std::vector<int32_t>& 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<double> linspace(double a, double b, int64_t n) {
|
||||
std::vector<double> 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<double> fft_f = linspace(0.0, (double)(cfg.rate / 2), nb);
|
||||
std::vector<double> 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<float>& samples, std::shared_ptr<Item>* 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>((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<Item>();
|
||||
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<double> re((size_t)c.fft), im((size_t)c.fft), mag((size_t)nb);
|
||||
std::vector<float> 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<double> 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 <boa><eoa> 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<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
std::vector<float> 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() {
|
||||
|
||||
+82
-2
@@ -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 "<T seconds>".
|
||||
* 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 <boi> placeholders <eoi> 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 <boa> and <eoa>.
|
||||
* 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<double> 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<std::vector<int32_t>(const std::string&)> encode_text);
|
||||
const VisionConfig& config() const { return cfg_; }
|
||||
|
||||
int image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* 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<Item>* out,
|
||||
std::string* why) const;
|
||||
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* 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<Item>* out, std::string* why) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* 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<Item>* 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<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
private:
|
||||
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
VisionConfig cfg_{};
|
||||
AudioConfig acfg_{};
|
||||
bool audio_on_ = false;
|
||||
std::vector<float> hann_; /* the window, float32 as the reference stores it */
|
||||
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
|
||||
std::vector<int32_t> mel_lo_, mel_hi_; /* filter b's nonzero bins, [lo, hi) */
|
||||
std::vector<double> tw_re_, tw_im_; /* exp(-2 pi i k / fft), k < fft/2 */
|
||||
std::vector<int32_t> brev_; /* the FFT's bit-reversal permutation */
|
||||
std::function<std::vector<int32_t>(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<int64_t> 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<int64_t> 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);
|
||||
|
||||
+18
-1
@@ -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<double> video_fps;
|
||||
std::optional<int32_t> video_min_frames, video_max_frames, video_max_frame_tokens;
|
||||
std::optional<int64_t> max_source_pixels;
|
||||
/* A token-budget processor's (Gemma 4's) soft tokens an image. */
|
||||
std::optional<int32_t> 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. */
|
||||
|
||||
+14
-2
@@ -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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+28
-19
@@ -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<int64_t>(n_embd_, e->n_embd);
|
||||
enc_patches_ = std::max<int64_t>(enc_patches_, e->max_patches);
|
||||
enc_pix_elems_ = std::max<int64_t>(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<int64_t>(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<EncoderPart>& parts, int step) {
|
||||
if (!mm_on_ || parts.empty()) return nullptr;
|
||||
const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& 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<EncoderPart>& 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<EncoderPart>& 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<const int32_t*>(enc_coord_dev_[r]);
|
||||
|
||||
+8
-5
@@ -168,9 +168,11 @@ public:
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& 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<EncoderPart>& 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<void*> enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
|
||||
uint16_t* enc_pix_host_ = nullptr;
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
|
||||
@@ -177,6 +177,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> 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]);
|
||||
|
||||
@@ -301,11 +301,11 @@ public:
|
||||
bool encodes_pending() const;
|
||||
void take_encodes(std::vector<std::shared_ptr<mm::Item>>* out);
|
||||
/* An encoder pass over whole segments; see BatchBuilder::build_encoder. */
|
||||
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step) {
|
||||
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc) {
|
||||
std::lock_guard<std::mutex> 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
|
||||
|
||||
@@ -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<uint8_t>& bytes, std::shared_ptr<mm::Item>* out,
|
||||
std::string* why) override {
|
||||
int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
|
||||
std::shared_ptr<mm::Item>* 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:
|
||||
|
||||
+30
-4
@@ -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<int32_t>& tokens, std::vector<float>& 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<uint8_t>& bytes,
|
||||
virtual int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
|
||||
std::shared_ptr<mm::Item>* out, std::string* why) = 0;
|
||||
};
|
||||
|
||||
|
||||
+346
-114
@@ -6,6 +6,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
@@ -59,29 +60,48 @@ std::string base64_encode(const void* data, size_t len) {
|
||||
}
|
||||
|
||||
bool base64_decode(const std::string& in, std::vector<uint8_t>* 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<int8_t, 256> 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<uint8_t>* 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<std::string>();
|
||||
else if (iu != part.end() && iu->is_string())
|
||||
url = iu->get<std::string>();
|
||||
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<std::string>();
|
||||
else if (au != part.end() && au->is_string())
|
||||
url = au->get<std::string>();
|
||||
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>() : 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<std::string>(), 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<std::pair<MediaKind, std::vector<uint8_t>>>* 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<std::string>();
|
||||
else if (iu != part.end() && iu->is_string())
|
||||
url = iu->get<std::string>();
|
||||
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<uint8_t> 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>() : 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<uint8_t> bytes;
|
||||
if (!base64_decode(ia->at("data").get<std::string>(), &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<std::pair<MediaKind, std::vector<uint8_t>>>& media,
|
||||
PromptInput* out, ApiError* err) {
|
||||
const MediaOpts& opts, PromptInput* out, ApiError* err) {
|
||||
out->text = rendered;
|
||||
auto pm = std::make_shared<mm::PromptMedia>();
|
||||
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<mm::Item> 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<int64_t>() <= 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<int64_t>();
|
||||
}
|
||||
/* 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<int64_t>() : 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<std::string>();
|
||||
} 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<std::pair<MediaKind, std::vector<uint8_t>>> 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<std::pair<MediaKind, std::vector<uint8_t>>> 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<std::string>();
|
||||
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<std::string>();
|
||||
/* 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<uint8_t> 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<std::string>();
|
||||
p.text = prefix + it->get<std::string>();
|
||||
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<std::string>();
|
||||
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<std::string>();
|
||||
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");
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+127
-14
@@ -7,6 +7,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
@@ -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<std::vector<float>> vecs;
|
||||
UsageOut u;
|
||||
vecs.reserve(r.prompts.size());
|
||||
for (const auto& p : r.prompts) {
|
||||
std::vector<float> 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<Generation> gens;
|
||||
std::vector<Request> 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<Sink>(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<uint64_t> 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<std::vector<float>> 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<float>& 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<float> 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));
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<float>& embedding() const { return embd_; }
|
||||
|
||||
private:
|
||||
void notify();
|
||||
|
||||
@@ -168,6 +175,7 @@ private:
|
||||
std::atomic<int32_t> n_prompt_{0};
|
||||
std::atomic<int32_t> n_cached_{0};
|
||||
bool has_logprobs_ = false;
|
||||
std::vector<float> 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<Sink*>(s)->add_drafts(n, accepted);
|
||||
}
|
||||
inline void sink_embedding(void* s, const float* v, int64_t n) {
|
||||
if (s) static_cast<Sink*>(s)->set_embedding(v, n);
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -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<std::string>();
|
||||
@@ -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 `<bos> $A <eos>` 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
|
||||
* <eos> 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);
|
||||
|
||||
@@ -9,20 +9,21 @@
|
||||
# What the recipe adds:
|
||||
#
|
||||
# - the lm_head, block fp8: the widest GEMM in the model at half the bytes
|
||||
# - the drafter's linears, block fp8 from its bf16 release: it is read whole on every decode
|
||||
# - the drafter's linears, OCP-MXFP4 from its bf16 release: it is read whole on every decode
|
||||
# step, and a draft is verified, so its precision can move acceptance and never an emitted token
|
||||
# - the drafter's 2-bit copy of the target's head (u2 codes, an f16 scale and a u8 zero a group
|
||||
# of 128), read by its draft rounds only
|
||||
# of 128, least-squares clip search), read by its draft rounds only; the engine rescores its
|
||||
# top 32 against the target's fp8 head
|
||||
#
|
||||
# The drafter's selector projection, codebooks and convolution weights stay bf16.
|
||||
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
|
||||
|
||||
dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
@@ -7,18 +7,24 @@
|
||||
# the trunk is served at the 4-bit weights Quark shipped, against E4M3 activations. The checkpoint
|
||||
# is served by the family's quantised plugin (qwen35_fp8). The delta net's a/b projection is
|
||||
# declared bf16, and every MXFP4 value is exact in bf16, so `cast` keeps Quark's values that way.
|
||||
# The rest is as in q38-27b-fp8-df2.recipe: the head at block fp8, the drafter's linears at block
|
||||
# fp8, and its 2-bit copy of the target's head.
|
||||
# The target's head goes block fp8, as in q38-27b-fp8-df2.recipe.
|
||||
#
|
||||
# THE DRAFTER is made as small as its acceptance allows, since it is read whole on every decode step
|
||||
# and a draft is verified, so its precision moves acceptance and never an emitted token: its linears
|
||||
# at OCP-MXFP4 like the trunk, and a 2-bit copy of the target's head (u2 with a u8 zero, least-squares
|
||||
# clip search) whose top 32 the engine rescores against the target's fp8 head. Against fp8 linears
|
||||
# and an unsearched 2-bit head without the rescore, TP1 at depth 7: 108.9 -> 121.6 tok/s one
|
||||
# stream, 0.75 GiB less weight.
|
||||
|
||||
blk.*.ssm_ab.weight cast dtype=bf16
|
||||
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
|
||||
|
||||
dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
|
||||
+44
-2
@@ -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":"<base64 wav>","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` |
|
||||
|
||||
+95
-6
@@ -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,
|
||||
|
||||
+481
-19
@@ -54,6 +54,9 @@
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#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 <int MB_>
|
||||
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 <int MB_>
|
||||
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<int64_t> 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<uint32_t*>(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<int64_t>(0, q0 - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(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<int64_t>(b0, i - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(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;
|
||||
|
||||
+72
-2
@@ -58,6 +58,30 @@ std::vector<Case> 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<Case> 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<Case> 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<Case> 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<Case> 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<Case> 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") },
|
||||
|
||||
+44
-2
@@ -40,8 +40,49 @@
|
||||
|
||||
#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#include <sched.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
/* 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)
|
||||
|
||||
@@ -80,6 +80,366 @@ static int elementwise2(const RadArgs* a) {
|
||||
AVX_KERNEL(add) { return elementwise2<false>(a); }
|
||||
AVX_KERNEL(mul) { return elementwise2<true>(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.
|
||||
*
|
||||
|
||||
+341
-6
@@ -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 <int MR_>
|
||||
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 <int MB_, int NB_>
|
||||
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<BMR, BNR>(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));
|
||||
|
||||
+4
-2
@@ -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) \
|
||||
|
||||
+13
-5
@@ -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) {
|
||||
|
||||
+77
-6
@@ -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)),
|
||||
|
||||
@@ -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|"
|
||||
|
||||
@@ -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 <cmath>
|
||||
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
__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<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
|
||||
float scale, int window, int 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<HD, GQA, NQB, DSPLIT, TILE>), grid,
|
||||
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
|
||||
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, 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);
|
||||
}
|
||||
@@ -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];
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+6
-9
@@ -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
|
||||
|
||||
+80
-19
@@ -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 <bool WF32, uint32_t THR>
|
||||
__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<THR / kWave>(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<wf, T>), 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) {
|
||||
|
||||
@@ -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*);
|
||||
|
||||
+306
-3
@@ -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",
|
||||
|
||||
@@ -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<RadTensor> ts = {
|
||||
col(0, wq), col(wq, wkv), col(wq + wkv, wkv),
|
||||
T(nullptr, RAD_I32, { 3 }), T(nullptr, RAD_BF16, { total, wq }),
|
||||
};
|
||||
std::vector<RadParam> 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<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 645 }),
|
||||
T(nullptr, RAD_BF16, { 5, 645 }),
|
||||
T(nullptr, RAD_BF16, { 5, 645 }) };
|
||||
std::vector<RadParam> 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<RadTensor> ts = { T(nullptr, RAD_BF16, { 23, 645 }),
|
||||
T(nullptr, RAD_I32, { 4 }),
|
||||
T(nullptr, RAD_BF16, { 3, 645 }) };
|
||||
std::vector<RadParam> 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<RadTensor> 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<RadParam> 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<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 512 }),
|
||||
T(nullptr, RAD_BF16, { wn }),
|
||||
T(nullptr, RAD_BF16, { 5, 512 }) };
|
||||
std::vector<RadParam> 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<RadTensor> 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<RadParam> 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<RadTensor> ts = { T(nullptr, RAD_BF16, { 27, 768 }),
|
||||
T(nullptr, RAD_BF16, { 3, 768 }) };
|
||||
std::vector<RadParam> 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<float>& h) {
|
||||
std::vector<uint16_t> 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<uint16_t> b(n);
|
||||
st_memcpy(b.data(), d, n * 2, hipMemcpyDeviceToHost);
|
||||
std::vector<float> f(n);
|
||||
for (size_t i = 0; i < n; ++i) f[i] = h_bf16(b[i]);
|
||||
return f;
|
||||
};
|
||||
auto rel = [](const std::vector<float>& got, const std::vector<float>& 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<float>& got,
|
||||
const std::vector<float>& 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<float> 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<float> 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<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
|
||||
run_case(r, ts, ps);
|
||||
std::vector<float> 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<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
|
||||
run_case(r, ts, ps);
|
||||
std::vector<float> 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<float> xb = randv((size_t)(Mb * nb), 2.0f);
|
||||
void* dxb = up(xb);
|
||||
void* dyb = dalloc((size_t)(Mb * nb) * 2);
|
||||
std::vector<RadTensor> ts = { T(dxb, RAD_BF16, { Mb, nb }), T(dyb, RAD_BF16, { Mb, nb }) };
|
||||
std::vector<RadParam> ps = { PI("M", Mb), PI("n", nb), PS("dtype", "bf16") };
|
||||
run_case(r, ts, ps);
|
||||
std::vector<float> 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<float> lo = { -0.5f }, hi = { 0.7f };
|
||||
void* dl = up(lo);
|
||||
void* dh = up(hi);
|
||||
std::vector<RadTensor> 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<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
|
||||
run_case(r, ts, ps);
|
||||
std::vector<float> 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<float> 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<RadTensor> ts = { T(dg, RAD_BF16, { M, n }), T(du, RAD_BF16, { M, n }),
|
||||
T(dy, RAD_BF16, { M, n }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("act", "sigmoid"),
|
||||
PS("dtype", "bf16") };
|
||||
if (r) run_case(r, ts, ps);
|
||||
std::vector<float> 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<float> 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<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dw, RAD_BF16, { n }),
|
||||
T(dy, RAD_BF16, { M, n }) };
|
||||
std::vector<RadParam> 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<float> 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<float> x = randv((size_t)(g.M * g.W * g.cin), 1.0f);
|
||||
std::vector<float> w = randv((size_t)(g.cout * g.cin * kh * kw), 0.3f);
|
||||
std::vector<int32_t> cu = { 0, (int32_t)(T0 * g.cdiv), (int32_t)(g.M * g.cdiv) };
|
||||
std::vector<int32_t> 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<RadTensor> 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<RadParam> 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<float> 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<float> x = randv((size_t)(M * C), 1.0f), w = randv((size_t)(C * K), 0.5f);
|
||||
std::vector<int32_t> 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<RadTensor> 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<RadParam> ps = { PI("M", M), PI("n", C), PI("k", K), PS("dtype", "bf16") };
|
||||
if (r) run_case(r, ts, ps);
|
||||
std::vector<float> 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<RadTensor> ts = { T(dy, RAD_BF16, { M, n }) };
|
||||
std::vector<RadParam> 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<float> 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<float> q = randv((size_t)(M * W), 2.0f), k = randv((size_t)(M * W), 2.0f);
|
||||
std::vector<float> v = randv((size_t)(M * W), 1.0f);
|
||||
std::vector<float> rk = randv((size_t)((L + 1) * W), 1.0f), pds = randv((size_t)D, 3.0f);
|
||||
std::vector<int32_t> 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<RadTensor> 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<RadParam> 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<float> 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<float> 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<RadTensor> ts = { T(nullptr, RAD_BF16, { 3, 768 }),
|
||||
T(nullptr, RAD_F32, { 3, 768 }) };
|
||||
std::vector<RadParam> 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 -------------
|
||||
|
||||
+16
-4
@@ -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");
|
||||
|
||||
+184
-13
@@ -34,6 +34,8 @@
|
||||
#include "ref_gemm.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
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<int64_t>(b0, i - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(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;
|
||||
|
||||
+315
-6
@@ -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;
|
||||
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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").
|
||||
*
|
||||
|
||||
+112
-12
@@ -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",
|
||||
|
||||
+153
-1
@@ -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);
|
||||
|
||||
+9
-1
@@ -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;
|
||||
|
||||
@@ -15,8 +15,12 @@
|
||||
#include "mm/media.h"
|
||||
#include "mm/processor.h"
|
||||
#include "mm_golden.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
@@ -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<float> 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<mm::Item> 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 <boa><eoa> and nothing to encode. */
|
||||
std::vector<float> 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()
|
||||
@@ -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<Band> 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()
|
||||
+263
-2
@@ -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<float> 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});
|
||||
|
||||
+71
-2
@@ -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<uint8_t>&, std::shared_ptr<mm::Item>* out,
|
||||
std::string*) override {
|
||||
int prepare(MediaKind, const std::vector<uint8_t>&, const MediaOpts&,
|
||||
std::shared_ptr<mm::Item>* out, std::string*) override {
|
||||
auto it = std::make_shared<mm::Item>();
|
||||
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]})");
|
||||
|
||||
@@ -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<uint8_t> 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<uint8_t> got;
|
||||
CHECK(base64_decode(base64_encode(bytes.data(), n), &got));
|
||||
CHECK(got == std::vector<uint8_t>(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<uint8_t> got;
|
||||
CHECK(base64_decode(spaced, &got));
|
||||
CHECK(got == std::vector<uint8_t>(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) {
|
||||
|
||||
+19
-2
@@ -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
|
||||
*
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user