Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d840861af | ||
|
|
05af4db458 | ||
|
|
ac79f4dc8a | ||
|
|
6fa7707dff | ||
|
|
ee5fcf1024 | ||
|
|
432b50d7dd | ||
|
|
32cdaa5cc7 | ||
|
|
d579bd7d45 | ||
|
|
1e27172c14 | ||
|
|
76727fa050 | ||
|
|
82da8eab69 | ||
|
|
73691a1189 | ||
|
|
92eb44619b | ||
|
|
e31be583a9 | ||
|
|
33778b2b8c | ||
|
|
6fd7421f79 | ||
|
|
59d36ae928 | ||
|
|
2af7fa4022 |
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.1 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,16 +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, and
|
||||
the fused router launch), mechkbfan (the token embedding in the pinned host pool), Code000 (the
|
||||
n-gram gather on the card and the MTP head's history-pass skip) and baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, and the request log).
|
||||
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
|
||||
|
||||
+49
-2
@@ -39,6 +39,10 @@ typedef struct RadModelMeta {
|
||||
|
||||
float rms_eps;
|
||||
float rope_theta;
|
||||
/* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope --
|
||||
* and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with
|
||||
* text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses
|
||||
* by name. A bare factor here would read every scheme as a linear position divide. */
|
||||
float rope_scale;
|
||||
|
||||
/* Free-form key/value from the container header, for anything the struct above does not
|
||||
@@ -130,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 */
|
||||
@@ -439,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
|
||||
@@ -527,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
|
||||
@@ -608,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
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds using
|
||||
* the ORIGINAL training length, never the deployment/table length. Kernels share
|
||||
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
|
||||
#include "rad_plugin.h"
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_YARN_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_YARN_HD
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
|
||||
RAD_YARN_HD float frequency(float inv, int i) const {
|
||||
if (factor == 0.0f) return inv;
|
||||
const float width = high == low ? 0.001f : high - low;
|
||||
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
|
||||
/* Keep the blend order used by the reference YaRN implementation. */
|
||||
const float mask = 1.0f - ramp;
|
||||
return (inv / factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
};
|
||||
|
||||
inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
|
||||
if (factor == 0.0f) return {};
|
||||
return { factor,
|
||||
(float)rad_args_getf_or(a, "yarn_low", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_high", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
|
||||
}
|
||||
|
||||
inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
return std::isfinite(y.factor) && (y.factor == 0.0f ||
|
||||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
|
||||
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
#endif
|
||||
+126
-3
@@ -16,6 +16,7 @@
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
@@ -626,6 +627,7 @@ struct Geom {
|
||||
float wadd_qk = 0.0f;
|
||||
float theta = 1e6f;
|
||||
float rope_scale = 1.0f;
|
||||
RadYarn yarn;
|
||||
/* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several
|
||||
* position components declares `rope` with `rope_mode` and these sections and hands it
|
||||
* RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here
|
||||
@@ -789,7 +791,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
g.dtype = dtype;
|
||||
g.act_dtype = act_dtype;
|
||||
{
|
||||
@@ -1023,19 +1025,140 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
|
||||
* cannot rotate. */
|
||||
inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
|
||||
|
||||
/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
|
||||
* exactly the parameters it was given, so its op identities and tune keys are unchanged. */
|
||||
inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_F64("yarn_factor", g.yarn.factor));
|
||||
p.push_back(RAD_F64("yarn_low", g.yarn.low));
|
||||
p.push_back(RAD_F64("yarn_high", g.yarn.high));
|
||||
p.push_back(RAD_F64("yarn_magnitude", g.yarn.magnitude));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
|
||||
* target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
|
||||
* `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
|
||||
* factor without its type would be a linear position divide for a scheme that is not one.
|
||||
*
|
||||
* The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
|
||||
* `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
|
||||
* `draft.rope_scaling.`) that names a type in `rope_type` or `type`; a multimodal target's
|
||||
* text_config is authoritative. core/format/rope_override.h writes --rope-scaling into the same
|
||||
* object, found in the same order.
|
||||
*
|
||||
* default, mrope no scaling (`mrope` is the legacy Qwen2-VL spelling of default + sections)
|
||||
* linear positions divided by `factor`
|
||||
* yarn static YaRN: frequencies blended over the correction range that `factor`,
|
||||
* `original_max_position_embeddings`, `beta_fast`/`beta_slow` and `truncate`
|
||||
* give, cos/sin scaled by `attention_factor` (default 1 + 0.1 ln factor). The
|
||||
* factor is the config's, read as vLLM and transformers read it.
|
||||
*
|
||||
* Anything else -- llama3, longrope, dynamic -- is refused by name, as is YaRN's `mscale` form. A
|
||||
* refusal leaves the geometry as it was. */
|
||||
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
|
||||
const std::string root(prefix);
|
||||
const char* who = root.empty() ? "target" : "draft";
|
||||
const std::vector<std::string> homes = root.empty()
|
||||
? std::vector<std::string>{"text_config.rope_parameters.", "rope_parameters.",
|
||||
"text_config.rope_scaling.", "rope_scaling."}
|
||||
: std::vector<std::string>{root + "rope_parameters.", root + "rope_scaling."};
|
||||
std::string home, type_key;
|
||||
const char* type = nullptr;
|
||||
for (const auto& h : homes) {
|
||||
for (const char* t : {"rope_type", "type"})
|
||||
if ((type = rad_meta_gets(meta, (h + t).c_str(), nullptr))) { type_key = h + t; break; }
|
||||
if (type) { home = h; break; }
|
||||
}
|
||||
if (!type || !std::strcmp(type, "default") || !std::strcmp(type, "mrope")) {
|
||||
g.yarn = {};
|
||||
g.rope_scale = 1.0f;
|
||||
return RAD_OK;
|
||||
}
|
||||
auto get = [&](const char* key, double fallback) {
|
||||
const char* text = rad_meta_gets(meta, (home + key).c_str(), nullptr);
|
||||
if (!text) return fallback;
|
||||
char* end = nullptr;
|
||||
const double value = std::strtod(text, &end);
|
||||
if (end == text) return (double)NAN;
|
||||
while (*end == ' ' || *end == '\t' || *end == '\n') ++end;
|
||||
return *end ? (double)NAN : value;
|
||||
};
|
||||
if (!std::strcmp(type, "linear")) {
|
||||
const double factor = get("factor", 0.0);
|
||||
const float scale = (float)factor;
|
||||
if (!std::isfinite(factor) || factor <= 0.0 || !std::isfinite(scale) || scale <= 0.0f) {
|
||||
fprintf(stderr, "radiance: %s linear rotary scaling (%s) needs a finite factor > 0\n",
|
||||
who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = {};
|
||||
g.rope_scale = scale;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (std::strcmp(type, "yarn")) {
|
||||
fprintf(stderr, "radiance: %s rotary type '%s' (%s) is not implemented; default, linear "
|
||||
"and yarn are\n", who, type, type_key.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
|
||||
* out are the same answer. */
|
||||
double truncate = 1.0;
|
||||
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
|
||||
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
|
||||
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
|
||||
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
|
||||
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
|
||||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
|
||||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
|
||||
rot < 2 || (rot & 1)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) needs a finite factor >= 1, an integral "
|
||||
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
|
||||
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* mscale variants are a different contract; never silently ignore them. */
|
||||
for (const char* k : {"mscale", "mscale_all_dim"})
|
||||
if (rad_meta_gets(meta, (home + k).c_str(), nullptr)) {
|
||||
fprintf(stderr, "radiance: %s YaRN %s%s is not implemented; attention_factor is\n",
|
||||
who, home.c_str(), k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto correction = [&](double beta) {
|
||||
return rot * std::log(original / (beta * 2.0 * 3.14159265358979323846)) /
|
||||
(2.0 * std::log((double)g.theta));
|
||||
};
|
||||
double low = correction(fast), high = correction(slow);
|
||||
if (truncate != 0.0) { low = std::floor(low); high = std::ceil(high); }
|
||||
const RadYarn y = {(float)factor, (float)std::max(0.0, low),
|
||||
(float)std::min((double)rot - 1, high), (float)magnitude};
|
||||
if (!rad_yarn_valid(y)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) resolves to an empty correction range\n", who,
|
||||
home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = y;
|
||||
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
if (g.rope_mc)
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -121,7 +121,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, RAD_OP(b, "rope",
|
||||
op_rope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -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),
|
||||
@@ -538,7 +536,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -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
|
||||
@@ -712,14 +680,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -508,7 +508,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
|
||||
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
|
||||
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -667,14 +667,14 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
+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);
|
||||
|
||||
@@ -269,7 +269,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
|
||||
op_bkey = g.rope_mc
|
||||
? RAD_OP(b, "qsa_block_key",
|
||||
? decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
@@ -278,7 +278,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_WEIGHTS(w_kn))
|
||||
: RAD_OP(b, "qsa_block_key",
|
||||
: decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
|
||||
@@ -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
@@ -185,7 +185,6 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
|
||||
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
|
||||
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
|
||||
@@ -201,6 +200,7 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
int s;
|
||||
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
|
||||
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
|
||||
@@ -431,6 +431,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the KV cache. One group: every layer is full attention. */
|
||||
RadKVGroupDecl fd{};
|
||||
|
||||
@@ -237,6 +237,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
|
||||
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
|
||||
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
|
||||
|
||||
@@ -339,7 +339,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
/* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
|
||||
* the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
|
||||
* conventions in one process, which is exactly why this is a second Geom and not a flag. */
|
||||
@@ -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. */
|
||||
@@ -635,6 +646,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
GdnFP8::Config& gc = m.gcfg;
|
||||
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
|
||||
"linear_num_key_heads", 0);
|
||||
@@ -952,7 +964,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
|
||||
* band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
|
||||
* prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("dtype", "f32")),
|
||||
|
||||
@@ -364,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
/* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
|
||||
* for the target device, the answer is a converter flag that writes a NAMED partial container
|
||||
* -- not an environment variable that makes a full one silently mean something else. A slice
|
||||
@@ -1000,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* one step; the symptom is fluent output with one arm of the model reading the other's
|
||||
* leftovers, which nothing downstream flags.
|
||||
*/
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
|
||||
RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")),
|
||||
|
||||
@@ -97,6 +97,22 @@ function(rad_add_plugin name kind)
|
||||
"because the language a project compiles in is the project's own decision.")
|
||||
endif()
|
||||
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
|
||||
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
|
||||
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
|
||||
# input path, the output path and the command line, so one source built in two directories --
|
||||
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
|
||||
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
|
||||
# object's read-only data and with it every PC-relative address .text forms into it: the same
|
||||
# instructions, different bytes. Named from what identifies the unit and nothing about where it
|
||||
# was built, the ID is the same wherever the plugin is built and still differs between any two
|
||||
# sources, which is the property clang needs of it.
|
||||
foreach(src ${P_HIP_SOURCES})
|
||||
get_filename_component(_rad_abs "${src}" ABSOLUTE)
|
||||
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
|
||||
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
|
||||
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
|
||||
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
|
||||
endforeach()
|
||||
list(APPEND srcs ${P_HIP_SOURCES})
|
||||
endif()
|
||||
add_library(${name} MODULE ${srcs})
|
||||
|
||||
@@ -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
|
||||
|
||||
+44
-1
@@ -6,6 +6,7 @@
|
||||
* (spec §6).
|
||||
*/
|
||||
#include "rad_core.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
@@ -28,6 +29,15 @@ struct Flag {
|
||||
const char* help;
|
||||
};
|
||||
|
||||
/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
|
||||
* that points at it: the two are initialised in this order. */
|
||||
static const std::string g_draft_window_help =
|
||||
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
|
||||
" --num-speculative-tokens every step; adaptive makes that\n"
|
||||
" the ceiling and follows each sequence's acceptance and the\n"
|
||||
" measured step cost (a serial draft head only). Default ") +
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
@@ -45,6 +55,8 @@ static const Flag g_flags[] = {
|
||||
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
@@ -98,6 +110,7 @@ static const Flag g_flags[] = {
|
||||
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
@@ -179,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" },
|
||||
@@ -380,6 +396,18 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
|
||||
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
|
||||
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
|
||||
else if (S("--rope-scaling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Checked here, so a typo is a refusal at the command line and not a model served
|
||||
* with its trained rotary at a length it cannot reach. */
|
||||
RopeSpec rs;
|
||||
if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
|
||||
RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
|
||||
"length, or none -- got '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->rope_scaling = v;
|
||||
}
|
||||
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
|
||||
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
|
||||
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
|
||||
@@ -443,6 +471,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-window")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
|
||||
else if (!std::strcmp(v, "adaptive")) c->draft_window = DraftWindow::Adaptive;
|
||||
else {
|
||||
RAD_ERR("--draft-window takes fixed or adaptive, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
|
||||
* own drafter -- or none -- would hand the caller a server that is not the one they
|
||||
@@ -647,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.
|
||||
*
|
||||
|
||||
@@ -93,6 +93,15 @@ private:
|
||||
std::vector<std::thread> rank_threads_;
|
||||
|
||||
Config cfg_;
|
||||
/* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
|
||||
* token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
|
||||
* whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
|
||||
* count and the difference in its weights pool. Engine::plan fills it, and every reader of the
|
||||
* resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
|
||||
* cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
|
||||
* plan and weights pool disagree. */
|
||||
std::vector<Config> rank_cfg_;
|
||||
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
|
||||
|
||||
/* The model's source, one of the two. A container stays mapped for the life of the engine:
|
||||
* the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
|
||||
@@ -117,6 +126,9 @@ private:
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
int read_checkpoint_metadata();
|
||||
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
|
||||
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
|
||||
int apply_rope_scaling();
|
||||
int declare();
|
||||
int plan();
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
@@ -257,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);
|
||||
|
||||
+231
-44
@@ -14,6 +14,7 @@
|
||||
#include "device/device.h"
|
||||
#include "device/directio.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "rad_plugin.h"
|
||||
@@ -683,7 +684,9 @@ int Engine::read_metadata() {
|
||||
meta_.n_expert_shared = geti("n_expert_shared", 0);
|
||||
meta_.rms_eps = getf("rms_eps", 1e-6);
|
||||
meta_.rope_theta = getf("rope_theta", 10000.0);
|
||||
meta_.rope_scale = getf("rope_scale", 1.0);
|
||||
/* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
|
||||
* An older container's `rope_scale` key holds the factor alone and is not read. */
|
||||
meta_.rope_scale = 1.0f;
|
||||
|
||||
/* A container that says nothing about its own shape is refused HERE, by name, rather than at
|
||||
* declare as an "invalid argument" from a plugin that was handed zeros. */
|
||||
@@ -707,6 +710,7 @@ int Engine::read_metadata() {
|
||||
default: meta_kv_v_.push_back(file_->str(kv.v.s)); break;
|
||||
}
|
||||
}
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str());
|
||||
for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str());
|
||||
@@ -741,6 +745,7 @@ int Engine::read_checkpoint_metadata() {
|
||||
}
|
||||
meta_kv_k_ = mo.keys;
|
||||
meta_kv_v_ = mo.vals;
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str());
|
||||
for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str());
|
||||
@@ -754,6 +759,56 @@ int Engine::read_checkpoint_metadata() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
|
||||
* load, where the architecture's reader takes them, so an existing container serves past its
|
||||
* trained context with no reconvert -- and is checked by the same reader a converted one is. The
|
||||
* drafter, when there is one, gets the same factor over its own trained length. Then one line says
|
||||
* what the rotary is, and a context past what it covers is named. */
|
||||
int Engine::apply_rope_scaling() {
|
||||
RopeSpec spec;
|
||||
if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
|
||||
RAD_ERR("--rope-scaling '%s': yarn:FACTOR (above 1) with an optional :ORIG, or none",
|
||||
cfg_.rope_scaling.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (spec.kind != RopeSpec::Keep) {
|
||||
std::string why;
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "", meta_.n_ctx_train, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RopeKeys kv{ meta_kv_k_, meta_kv_v_ };
|
||||
if (kv.any_prefix("draft.")) {
|
||||
int64_t dtrain = meta_.n_ctx_train;
|
||||
if (const std::string* t = kv.get("draft.max_position_embeddings"))
|
||||
dtrain = std::atoll(t->c_str());
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "draft.", dtrain, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RopeResolved r = rope_resolve(meta_kv_k_, meta_kv_v_, "");
|
||||
const long long want = cfg_.max_ctx > 0 ? (long long)cfg_.max_ctx : (long long)meta_.n_ctx_train;
|
||||
if (r.type == "yarn" && r.factor > 1.0) {
|
||||
const long long reach = (long long)(r.orig * r.factor);
|
||||
RAD_INFO("rope: YaRN factor %g over %lld trained positions -- the rotary reaches %lld; "
|
||||
"--max-model-len %lld%s", r.factor, (long long)r.orig, reach, want,
|
||||
spec.kind == RopeSpec::Yarn ? " (--rope-scaling)" : " (the container's own)");
|
||||
if (want > reach)
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions YaRN factor %g covers; "
|
||||
"positions beyond them are extrapolated", want, reach, r.factor);
|
||||
} else if (meta_.n_ctx_train > 0 && want > meta_.n_ctx_train &&
|
||||
!(r.type == "linear" && r.factor > 1.0)) {
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions the model was trained on and "
|
||||
"nothing scales its rotary, so positions beyond them are extrapolated; a model "
|
||||
"card's YaRN extension is --rope-scaling yarn:FACTOR (docs/YARN.md)", want,
|
||||
(long long)meta_.n_ctx_train);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== 3 + 4. plugins, declare */
|
||||
int Engine::load_plugins() {
|
||||
int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy,
|
||||
@@ -787,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;
|
||||
@@ -846,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");
|
||||
@@ -1233,9 +1305,111 @@ int Engine::plan() {
|
||||
r->program.arena_stage_bytes = vb.stage;
|
||||
r->program.arena_bytes = r->program.arena_stage_off + vb.stage;
|
||||
}
|
||||
|
||||
/* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
|
||||
*
|
||||
* The split above is the dearest rank's, applied to every card, and one block table serves
|
||||
* every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
|
||||
* costs less per token (an attention-zero rank keeps no attention cache, only what its
|
||||
* other groups cost) would reserve the common KV pool and page a fraction of it, while its
|
||||
* experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
|
||||
* KV pool that pages exactly the common token count and the difference in its weights
|
||||
* pool, up to every one of its weights resident. The token count, the carve, the loan and
|
||||
* the dearest ranks' pools are what they were.
|
||||
*
|
||||
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
|
||||
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
|
||||
* its weights would choose all_vram while its peers spill -- one strategy per world is the
|
||||
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
|
||||
* does not lend (--deterministic, or a device without virtual memory management) is
|
||||
* re-split all the same: the bytes it would never page are bytes its experts can hold, and
|
||||
* without virtual memory management they are allocated whole.
|
||||
* Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
|
||||
* on every rank, field for field. A rank that qualifies and is not re-split is named with
|
||||
* the reason, once. */
|
||||
rank_cfg_.assign(ranks_.size(), cfg_);
|
||||
kv_planned_tokens_ = 0;
|
||||
constexpr int64_t kMiB = (int64_t)1 << 20;
|
||||
int64_t kv_max = 0;
|
||||
for (const VramFacts& f : facts) kv_max = std::max(kv_max, f.kv_ceiling);
|
||||
std::vector<size_t> cheaper;
|
||||
for (size_t i = 0; i < facts.size() && i < ranks_.size(); ++i)
|
||||
if (facts[i].kv_ceiling < kv_max) cheaper.push_back(i);
|
||||
/* Why no cheaper rank is re-split, where the reason holds for the whole world. */
|
||||
std::string kept;
|
||||
std::vector<std::unique_ptr<KVManager>> probes(ranks_.size());
|
||||
int64_t T = -1;
|
||||
if (cheaper.empty()) {
|
||||
/* Every rank's cache costs the same per token: there is nothing to re-split. */
|
||||
} else if (!vb.derived_kv || !vb.derived_weights) {
|
||||
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
|
||||
} else if (cfg_.placement != "expert_tiered") {
|
||||
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
|
||||
cfg_.placement.c_str());
|
||||
} else {
|
||||
/* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
|
||||
* pool, the least of them. Asked of the same plan configure_kv makes, against the same
|
||||
* bytes: nothing reserves from a KV pool before its carve. */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
const int64_t t = probes[i]->paged_tokens(cfg_.vram_kv_mib * kMiB);
|
||||
if (t == KVManager::kUnboundedTokens) continue;
|
||||
if (T < 0 || t < T) T = t;
|
||||
}
|
||||
if (kept.empty() && T <= 0)
|
||||
kept = "no rank's cache pages a bounded token count in the common pool";
|
||||
}
|
||||
for (size_t i : cheaper) {
|
||||
const std::string costs =
|
||||
fmt("kv: rank %d's cache costs %s at the worst case where its dearest peer's costs "
|
||||
"%s", ranks_[i]->index, humanb(facts[i].kv_ceiling).c_str(),
|
||||
humanb(kv_max).c_str());
|
||||
if (!kept.empty()) {
|
||||
RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
|
||||
continue;
|
||||
}
|
||||
/* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
|
||||
* pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
|
||||
* a pool whose budget is exactly this many MiB. The pool's own alignment is already
|
||||
* among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
|
||||
const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
|
||||
if (need < 0) {
|
||||
RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
|
||||
"tokens in the common %lld MiB", costs.c_str(), (long long)T,
|
||||
(long long)cfg_.vram_kv_mib);
|
||||
continue;
|
||||
}
|
||||
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
|
||||
const RankSplit rs =
|
||||
vram_budget_rank_split(cfg_.vram_weights_mib, cfg_.vram_kv_mib, need, cap);
|
||||
if (!rs.resplit) {
|
||||
RAD_INFO("%s; its pools stay the common split: it needs all %lld MiB of the common "
|
||||
"pool to page the common %lld tokens", costs.c_str(),
|
||||
(long long)cfg_.vram_kv_mib, (long long)T);
|
||||
continue;
|
||||
}
|
||||
rank_cfg_[i].vram_kv_mib = rs.kv_mib;
|
||||
rank_cfg_[i].vram_weights_mib = rs.weights_mib;
|
||||
kv_planned_tokens_ = T;
|
||||
RAD_INFO("%s, so its KV pool pages the common %lld tokens in %lld MiB instead of %lld; "
|
||||
"its weights pool grows %lld -> %lld MiB (every weight resident wants %s)%s",
|
||||
costs.c_str(), (long long)T, (long long)rs.kv_mib, (long long)cfg_.vram_kv_mib,
|
||||
(long long)cfg_.vram_weights_mib, (long long)rs.weights_mib,
|
||||
humanb(cap).c_str(),
|
||||
rs.unusable_mib > 0
|
||||
? fmt(", and %lld MiB stay unclaimed", (long long)rs.unusable_mib).c_str()
|
||||
: "");
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
/* This rank's own split: cfg_ field for field unless the block above re-split it. */
|
||||
const Config& rc = rank_cfg_[ri];
|
||||
LogRank lr(r->index);
|
||||
/* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
|
||||
* reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
|
||||
@@ -1249,18 +1423,18 @@ int Engine::plan() {
|
||||
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
|
||||
* inference about what the workload will be (spec §6). Pools refuses by name and by how
|
||||
* much rather than shrinking anything. */
|
||||
int s = r->pools.configure(cfg_, props.vram_bytes);
|
||||
int s = r->pools.configure(rc, props.vram_bytes);
|
||||
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
|
||||
if (s < 0) {
|
||||
report_pool_refusal(r->index, r->device, r->pools, cfg_);
|
||||
report_pool_refusal(r->index, r->device, r->pools, rc);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
|
||||
* against its own card's budget (spec §5.3). */
|
||||
* against its own card's budget (spec §5.3) -- the same split its pools were given. */
|
||||
PlannerInput in{};
|
||||
in.program = &r->program;
|
||||
in.config = &cfg_;
|
||||
in.config = &rc;
|
||||
in.rank = r->index;
|
||||
in.world_size = cfg_.tp;
|
||||
if (file_ && file_->header().prof_count) {
|
||||
@@ -1273,6 +1447,16 @@ int Engine::plan() {
|
||||
if (cfg_.debug_placement || s < 0)
|
||||
fputs(r->plan.report(r->program).c_str(), stderr);
|
||||
if (s < 0) return s;
|
||||
/* The slab the planner filled is the pool the mover will fill: one split, read twice. */
|
||||
RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
|
||||
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
|
||||
* re-split rank whose grown weights pool took every weight still holds it. Said, because
|
||||
* the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
|
||||
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
|
||||
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
|
||||
"holds no weights; its %lld MiB (--host-pool-mib) stay allocated, as on every "
|
||||
"rank", r->index, (long long)cfg_.host_pool_mib);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -2559,10 +2743,22 @@ int Engine::configure_kv() {
|
||||
* every rank is capped at the least before any carves. At an even split the cap is what
|
||||
* every rank would have carved anyway. */
|
||||
int64_t least = -1;
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
|
||||
* construction: its pool is the least whole MiB whose paged split reaches it, asked of the
|
||||
* same plan against the same bytes. Short of it, this rank would set every rank's count
|
||||
* under what its dearest peer pages -- a broken construction, refused by name. */
|
||||
if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
|
||||
RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
|
||||
"and pages %lld: the pool and the plan that sized it disagree", r->index,
|
||||
(long long)rank_cfg_[i].vram_kv_mib, (long long)kv_planned_tokens_,
|
||||
(long long)t);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
@@ -2738,16 +2934,20 @@ int Engine::configure_kv() {
|
||||
sc.n_ckpt_slots = ck_disk_slots;
|
||||
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
|
||||
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only
|
||||
* meaningful under the container and layout that produced it; read back under
|
||||
* another, it is a lossless function of somebody else's weights. */
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
|
||||
* everything a cached block's bytes actually depend on. Read back under a
|
||||
* different container, layout or KV width, a block is a lossless function of
|
||||
* somebody else's weights -- fluent, confident and wrong. There is no cheaper
|
||||
* check than refusing the whole store, because a block carries no evidence of
|
||||
* what produced it beyond the tokens it was keyed by. */
|
||||
* different container, layout, KV width or rotary, a block is a lossless
|
||||
* function of somebody else's weights -- fluent, confident and wrong. There is
|
||||
* no cheaper check than refusing the whole store, because a block carries no
|
||||
* evidence of what produced it beyond the tokens it was keyed by.
|
||||
*
|
||||
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
|
||||
* (rope_identity): a YaRN container converted from the same checkpoint has the
|
||||
* same name and shapes as the stock one, and every cached key and QSA block key
|
||||
* is rotated differently under it. */
|
||||
{
|
||||
char theta[32];
|
||||
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
|
||||
const std::string id =
|
||||
std::string(meta_.name ? meta_.name : "") + "|" +
|
||||
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
|
||||
@@ -2755,7 +2955,8 @@ int Engine::configure_kv() {
|
||||
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
|
||||
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
|
||||
cfg_.kv_cache_dtype + "|" +
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION;
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
|
||||
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
|
||||
sc.fingerprint = h;
|
||||
@@ -3152,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 ----------------
|
||||
*
|
||||
@@ -3356,7 +3531,8 @@ int Engine::start() {
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
|
||||
const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
LogRank lr(r->index);
|
||||
RadDeviceProps props{};
|
||||
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
|
||||
@@ -3399,8 +3575,19 @@ int Engine::start() {
|
||||
* byte -- a small dense model already at the largest context its cache can hold
|
||||
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
|
||||
* Warning here would contradict that receipt and send the reader looking for a flag
|
||||
* to set. */
|
||||
if (cfg_.vram_budget_derived)
|
||||
* to set. A rank plan() re-split for the common token count also leaves what its
|
||||
* weights could not use, and the `kv: rank N ...` line said how much. */
|
||||
const int64_t unclaimed_mib =
|
||||
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
|
||||
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
|
||||
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
|
||||
"MiB are what rank %d's weights could not use of what its KV pool did not "
|
||||
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
|
||||
"line of the VRAM budget.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
|
||||
r->index, r->index);
|
||||
else if (cfg_.vram_budget_derived)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
|
||||
"neither pool could address another byte, which is the `unusable` line of "
|
||||
"the VRAM budget above.",
|
||||
|
||||
+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;
|
||||
@@ -253,7 +259,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
|
||||
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
|
||||
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
|
||||
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
|
||||
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
|
||||
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
|
||||
* be a linear position divide for llama3, longrope or YaRN. */
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
|
||||
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
|
||||
@@ -300,7 +309,48 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
m.n_expert_shared= gi("expert_shared_count", 0);
|
||||
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
|
||||
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
|
||||
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
|
||||
* those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
|
||||
* a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
|
||||
* attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
|
||||
* has no spelling for, so a file that sets one to anything but its neutral value is refused
|
||||
* here rather than served as plain YaRN. */
|
||||
{
|
||||
/* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
|
||||
* the older rope.scale_linear, and 0 or 1 is no scaling. */
|
||||
std::string type = "linear";
|
||||
g.get_str(a + ".rope.scaling.type", &type);
|
||||
const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
|
||||
const bool none = type == "none" || (type == "linear" && (factor == 0.0 || factor == 1.0));
|
||||
if (!none) {
|
||||
const struct { const char* key; double neutral; } kOff[] = {
|
||||
{ "rope.scaling.attn_factor", 1.0 }, { "rope.scaling.yarn_attn_factor", 1.0 },
|
||||
{ "rope.scaling.yarn_log_multiplier", 0.0 } };
|
||||
for (const auto& k : kOff)
|
||||
if (gf(k.key, k.neutral) != k.neutral) {
|
||||
RAD_ERR("the GGUF sets %s.%s = %g; that modifier of the rotary's scaling is "
|
||||
"not implemented", a.c_str(), k.key, gf(k.key, k.neutral));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double ext = gf("rope.scaling.yarn_ext_factor", -1.0);
|
||||
if (ext >= 0.0 && ext != 1.0) {
|
||||
RAD_ERR("the GGUF sets %s.rope.scaling.yarn_ext_factor = %g; YaRN is implemented "
|
||||
"at extrapolation factor 1", a.c_str(), ext);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->kv("rope_scaling.type", type);
|
||||
if (factor != 0.0) out->kv("rope_scaling.factor", fmt("%.17g", factor));
|
||||
const int64_t orig = gi("rope.scaling.original_context_length", 0);
|
||||
if (orig > 0) out->kv("rope_scaling.original_max_position_embeddings",
|
||||
fmt("%lld", (long long)orig));
|
||||
for (const char* beta : { "beta_fast", "beta_slow" }) {
|
||||
const double v = gf((std::string("rope.scaling.yarn_") + beta).c_str(), 0.0);
|
||||
if (v != 0.0) out->kv(std::string("rope_scaling.") + beta, fmt("%.17g", v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
@@ -779,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);
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
/* --rope-scaling, over a container's free-form metadata.
|
||||
*
|
||||
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
|
||||
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
|
||||
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
|
||||
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
|
||||
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
|
||||
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
|
||||
* it would a converted container, so there is one reader and one set of checks.
|
||||
*
|
||||
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
|
||||
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
|
||||
* sit behind that and never be read.
|
||||
*
|
||||
* Pure functions over two parallel string vectors, so they are tested without an engine
|
||||
* (tests/yarn_test.cpp holds them to yarn_from). */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct RopeSpec {
|
||||
enum Kind { Keep, None, Yarn } kind = Keep;
|
||||
double factor = 0.0;
|
||||
int64_t orig = 0; /* 0: the container's own trained length */
|
||||
};
|
||||
|
||||
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
|
||||
* else, so a typo is refused where it was typed. */
|
||||
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
|
||||
RopeSpec r;
|
||||
if (!s || !*s) { *out = r; return true; }
|
||||
if (!std::strcmp(s, "none")) { r.kind = RopeSpec::None; *out = r; return true; }
|
||||
if (std::strncmp(s, "yarn:", 5)) return false;
|
||||
char* e = nullptr;
|
||||
r.factor = std::strtod(s + 5, &e);
|
||||
if (e == s + 5 || !(r.factor > 1.0) || r.factor > 1e6) return false;
|
||||
if (*e == ':') {
|
||||
char* e2 = nullptr;
|
||||
const long long o = std::strtoll(e + 1, &e2, 10);
|
||||
if (e2 == e + 1 || *e2 || o <= 0) return false;
|
||||
r.orig = o;
|
||||
} else if (*e) {
|
||||
return false;
|
||||
}
|
||||
r.kind = RopeSpec::Yarn;
|
||||
*out = r;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RopeKeys {
|
||||
std::vector<std::string>& k;
|
||||
std::vector<std::string>& v;
|
||||
|
||||
int find(const std::string& key) const {
|
||||
for (size_t i = 0; i < k.size(); ++i)
|
||||
if (k[i] == key) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
const std::string* get(const std::string& key) const {
|
||||
const int i = find(key);
|
||||
return i < 0 ? nullptr : &v[(size_t)i];
|
||||
}
|
||||
void set(const std::string& key, const std::string& val) {
|
||||
const int i = find(key);
|
||||
if (i >= 0) { v[(size_t)i] = val; return; }
|
||||
k.push_back(key);
|
||||
v.push_back(val);
|
||||
}
|
||||
void erase(const std::string& key) {
|
||||
const int i = find(key);
|
||||
if (i < 0) return;
|
||||
k.erase(k.begin() + i);
|
||||
v.erase(v.begin() + i);
|
||||
}
|
||||
bool any_prefix(const char* pre) const {
|
||||
const size_t n = std::strlen(pre);
|
||||
for (const auto& s : k)
|
||||
if (!s.compare(0, n, pre)) return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/* The reader's order -- yarn_from's, kept in step with it. */
|
||||
inline std::vector<std::string> rope_homes(const char* group) {
|
||||
if (!*group)
|
||||
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
|
||||
"rope_scaling." };
|
||||
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
|
||||
}
|
||||
|
||||
/* The object the reader takes and the key that names its type, or empty strings when no object
|
||||
* names one (the model's rotary is then the default). */
|
||||
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
|
||||
std::string* type_key) {
|
||||
home->clear();
|
||||
type_key->clear();
|
||||
for (const auto& h : rope_homes(group))
|
||||
for (const char* t : { "rope_type", "type" })
|
||||
if (kv.get(h + t)) { *home = h; *type_key = h + t; return; }
|
||||
}
|
||||
|
||||
struct RopeResolved {
|
||||
std::string type; /* "" when nothing names one */
|
||||
double factor = 1.0;
|
||||
double orig = 0.0;
|
||||
};
|
||||
|
||||
inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const char* group) {
|
||||
RopeKeys kv{ k, v };
|
||||
RopeResolved r;
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
if (home.empty()) return r;
|
||||
r.type = *kv.get(tk);
|
||||
if (const std::string* f = kv.get(home + "factor")) r.factor = std::strtod(f->c_str(), nullptr);
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
r.orig = std::strtod(o->c_str(), nullptr);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
|
||||
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
|
||||
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
|
||||
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const RopeSpec& spec, const char* group, int64_t trained,
|
||||
std::string* why) {
|
||||
if (spec.kind == RopeSpec::Keep) return true;
|
||||
RopeKeys kv{ k, v };
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
const std::string type = home.empty() ? std::string() : *kv.get(tk);
|
||||
if (spec.kind == RopeSpec::None) {
|
||||
if (type == "yarn") kv.set(tk, "default");
|
||||
return true;
|
||||
}
|
||||
/* `mrope` is the legacy Qwen2-VL spelling of default with sections. */
|
||||
if (!type.empty() && type != "default" && type != "mrope" && type != "yarn") {
|
||||
*why = "the " + std::string(*group ? "drafter's" : "model's") + " rotary is '" + type +
|
||||
"' (" + tk + "); YaRN over it is not --rope-scaling's to decide";
|
||||
return false;
|
||||
}
|
||||
if (home.empty()) {
|
||||
home = *group ? std::string(group) + "rope_parameters."
|
||||
: kv.any_prefix("text_config.") ? "text_config.rope_parameters."
|
||||
: "rope_parameters.";
|
||||
tk = home + "rope_type";
|
||||
}
|
||||
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
|
||||
* tied to its old factor goes, so the reader derives it for the new one. */
|
||||
int64_t orig = spec.orig;
|
||||
if (!orig && type == "yarn")
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
orig = std::atoll(o->c_str());
|
||||
if (!orig) orig = trained;
|
||||
if (orig <= 0) {
|
||||
*why = "no trained length to scale from; give one: yarn:FACTOR:ORIG";
|
||||
return false;
|
||||
}
|
||||
char buf[64];
|
||||
kv.set(tk, "yarn");
|
||||
std::snprintf(buf, sizeof buf, "%.17g", spec.factor);
|
||||
kv.set(home + "factor", buf);
|
||||
std::snprintf(buf, sizeof buf, "%lld", (long long)orig);
|
||||
kv.set(home + "original_max_position_embeddings", buf);
|
||||
for (const char* stale : { "attention_factor", "mscale", "mscale_all_dim" })
|
||||
kv.erase(home + stale);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
|
||||
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
|
||||
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
|
||||
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
|
||||
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
|
||||
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
|
||||
* angles. Key order and unrelated keys do not change it. */
|
||||
inline std::string rope_identity(const std::vector<std::string>& k,
|
||||
const std::vector<std::string>& v) {
|
||||
auto names_rotary = [](const std::string& key) {
|
||||
size_t s = 0;
|
||||
while (s <= key.size()) {
|
||||
size_t e = key.find('.', s);
|
||||
if (e == std::string::npos) e = key.size();
|
||||
const std::string part = key.substr(s, e - s);
|
||||
if (part.find("rope") != std::string::npos || part.find("rotary") != std::string::npos)
|
||||
return true;
|
||||
s = e + 1;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
std::vector<std::string> rows;
|
||||
for (size_t i = 0; i < k.size() && i < v.size(); ++i)
|
||||
if (names_rotary(k[i])) rows.push_back(k[i] + "=" + v[i]);
|
||||
std::sort(rows.begin(), rows.end());
|
||||
std::string out;
|
||||
for (const auto& r : rows) { out += r; out += ';'; }
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -395,6 +395,27 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
if (max_mib <= 0) return -1;
|
||||
const auto reaches = [&](int64_t mib) {
|
||||
/* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
|
||||
* whose only paged group is zero still has to hold them. */
|
||||
if (mib * MiB < fixed_) return false;
|
||||
const int64_t t = paged_split(mib * MiB, nullptr);
|
||||
return t == kUnboundedTokens || t >= tokens;
|
||||
};
|
||||
if (!reaches(max_mib)) return -1;
|
||||
/* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
|
||||
int64_t lo = 0, hi = max_mib;
|
||||
if (reaches(lo)) return 0;
|
||||
while (hi - lo > 1) {
|
||||
const int64_t mid = lo + (hi - lo) / 2;
|
||||
if (reaches(mid)) hi = mid; else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
|
||||
@@ -182,6 +182,11 @@ public:
|
||||
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
|
||||
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
|
||||
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
|
||||
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
|
||||
|
||||
@@ -47,10 +47,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
|
||||
* of one deployment normally hold the same shard shapes and the same program, so these folds
|
||||
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
|
||||
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
@@ -393,4 +394,23 @@ int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank,
|
||||
return resolve(c, per_rank, out, false);
|
||||
}
|
||||
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes) {
|
||||
RankSplit s;
|
||||
s.weights_mib = common_weights_mib;
|
||||
s.kv_mib = common_kv_mib;
|
||||
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
|
||||
const int64_t saved = common_kv_mib - need_kv_mib;
|
||||
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
|
||||
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
|
||||
* rather than allocated empty. */
|
||||
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
|
||||
const int64_t grown = std::min(common_weights_mib + saved, cap);
|
||||
s.kv_mib = need_kv_mib;
|
||||
s.weights_mib = grown;
|
||||
s.unusable_mib = saved - (grown - common_weights_mib);
|
||||
s.resplit = true;
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+18
-1
@@ -125,7 +125,8 @@ struct VramBudget {
|
||||
};
|
||||
|
||||
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree.
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
|
||||
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
|
||||
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
|
||||
* fit on every card it is applied to.
|
||||
*
|
||||
@@ -137,4 +138,20 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
|
||||
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
|
||||
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
|
||||
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
|
||||
* every one of its weights would take resident (statics + all experts + their spare slots), this
|
||||
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
|
||||
* unclaimed. Nothing changes when the need is not below the common pool. */
|
||||
struct RankSplit {
|
||||
int64_t weights_mib = 0;
|
||||
int64_t kv_mib = 0;
|
||||
int64_t unusable_mib = 0; /* saved from the KV pool but past the weights cap: never allocated */
|
||||
bool resplit = false;
|
||||
};
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -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);
|
||||
|
||||
@@ -113,6 +113,15 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
if (p.vram_budget == pool_bytes) return RAD_OK;
|
||||
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
|
||||
"pool holds %s (%lld bytes): the planner and the pool were given different splits",
|
||||
p.rank, humanb(p.vram_budget).c_str(), (long long)p.vram_budget,
|
||||
humanb(pool_bytes).c_str(), (long long)pool_bytes);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
if (!out) return;
|
||||
|
||||
@@ -416,6 +416,13 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
|
||||
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
|
||||
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
|
||||
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
|
||||
* the rank and both sizes, when they differ. */
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
|
||||
+50
-4
@@ -129,6 +129,27 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* decides it and writes the answer into Config, so every rank plans from one choice. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; each step's head depth and each sequence's stop follow the
|
||||
* measured acceptance and the measured step cost. A serial drafter's policy only.
|
||||
* The default is kDraftWindowDefault, and the help text and the startup line read it from there.
|
||||
*
|
||||
* FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
|
||||
* two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
|
||||
*
|
||||
* concurrent sequences 1 2 4 8
|
||||
* adaptive, ceiling 3 +0.4% -0.1% +1.7% -0.3%
|
||||
* adaptive, ceiling 5 +7.1% -2.3% +7.4% -11.9%
|
||||
*
|
||||
* At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
|
||||
* 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
|
||||
* not yet timed at a load is priced on the prior. */
|
||||
enum class DraftWindow { Fixed = 0, Adaptive = 1 };
|
||||
constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
|
||||
inline const char* draft_window_name(DraftWindow w) {
|
||||
return w == DraftWindow::Adaptive ? "adaptive" : "fixed";
|
||||
}
|
||||
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
|
||||
|
||||
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
|
||||
@@ -325,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
|
||||
@@ -338,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
|
||||
@@ -577,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 */
|
||||
};
|
||||
@@ -623,6 +656,10 @@ struct Config {
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
int64_t max_seqs = 256;
|
||||
int64_t max_ctx = 0; /* 0 = the model's training context */
|
||||
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
|
||||
* model card's extension past its trained context, no reconvert); "none" takes a checkpoint's
|
||||
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
|
||||
std::string rope_scaling;
|
||||
|
||||
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
|
||||
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
|
||||
@@ -634,7 +671,10 @@ struct Config {
|
||||
* what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
|
||||
* that sum and writes the answer back into the two fields below, so every consumer downstream
|
||||
* -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
|
||||
* second place for them to disagree.
|
||||
* second place for them to disagree. Engine::plan derives each rank's own copy from it
|
||||
* (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
|
||||
* still one number per card, and the same number on every card whose cache costs as much per
|
||||
* token as the dearest rank's.
|
||||
*
|
||||
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
|
||||
int64_t vram_weights_mib = 0;
|
||||
@@ -721,8 +761,8 @@ struct Config {
|
||||
* code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
|
||||
* faults inside the HIP runtime rather than returning an error when there is no room. */
|
||||
|
||||
/* The speculative window, and the whole of the draft policy: the depth is constant and this
|
||||
* is it. See core/sched/draft.h. */
|
||||
/* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
|
||||
* core/sched/draft.h. */
|
||||
/* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
|
||||
* trained at, and a container with no draft head resolves to 0 with a line saying so.
|
||||
*
|
||||
@@ -732,6 +772,7 @@ struct Config {
|
||||
* paying for it again in VRAM, and then running at one token a step -- a small fraction of
|
||||
* the throughput the same container gives at its declared depth. */
|
||||
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
|
||||
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
|
||||
|
||||
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
|
||||
*
|
||||
@@ -751,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.
|
||||
@@ -840,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]);
|
||||
|
||||
+12
-5
@@ -73,6 +73,10 @@ struct StepEntry {
|
||||
bool draft_out = false;
|
||||
bool is_prefill = false;
|
||||
bool produces_token = false; /* this entry's last token is the sequence's last */
|
||||
/* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
|
||||
* in the reported acceptance like any other, and kept out of the adaptive window's estimate,
|
||||
* which describes the draft head (DraftController, draft.h). */
|
||||
bool ngram = false;
|
||||
/* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
|
||||
* StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
|
||||
* `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
|
||||
@@ -164,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:
|
||||
@@ -362,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;
|
||||
|
||||
+255
-1
@@ -1,9 +1,46 @@
|
||||
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
|
||||
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
|
||||
* on. See draft.h for why the first is the default and what the second changes.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
|
||||
* one round of a serial head and one more verify row against a weight-bound step. It prices a
|
||||
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
|
||||
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
|
||||
constexpr double kCostSlope = 0.06;
|
||||
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
|
||||
|
||||
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
|
||||
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
|
||||
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
|
||||
* grows by a few thousand tokens over a reply. */
|
||||
constexpr double kCostHalfLife = 32.0;
|
||||
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
|
||||
* step that waited on something other than its own work -- a first recording, an allocation, a
|
||||
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
|
||||
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
|
||||
* against: its first step may itself be the odd one. */
|
||||
constexpr double kCostOutlier = 4.0;
|
||||
constexpr int64_t kCostClipAfter = 4;
|
||||
|
||||
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
|
||||
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
|
||||
* the half-life's, and from then on it is the moving average it is meant to be. Without it a
|
||||
* sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
|
||||
* a short answer. */
|
||||
constexpr double kPriorWeight = 4.0;
|
||||
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int DraftController::configure(const Params& p) {
|
||||
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
|
||||
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
|
||||
@@ -14,6 +51,24 @@ int DraftController::configure(const Params& p) {
|
||||
tot_drafted_ = tot_accepted_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
|
||||
seen_ = 0;
|
||||
|
||||
adapt_ = p.adapt && p.max_depth > 0;
|
||||
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
|
||||
step_d_ = 0;
|
||||
step_w_ = 0;
|
||||
step_held_ = 0;
|
||||
prior_n_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
|
||||
by_depth_[d] = 0;
|
||||
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
|
||||
}
|
||||
if (adapt_)
|
||||
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
|
||||
"maximises the tokens its sequences are expected to emit over the step's measured "
|
||||
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
|
||||
"time; moves at +%.0f%% and at most every %d steps",
|
||||
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -34,6 +89,205 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
if (j < accepted) ++hit_[j];
|
||||
}
|
||||
if (drafted > seen_) seen_ = drafted;
|
||||
if (adapt_) ++by_depth_[drafted];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's cost */
|
||||
int DraftController::cost_class(int n_rows) {
|
||||
int c = 0;
|
||||
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
|
||||
return c;
|
||||
}
|
||||
|
||||
void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
|
||||
!std::isfinite(ms))
|
||||
return;
|
||||
const int c = cost_class(n_rows);
|
||||
double& m = cost_ms_[depth][c];
|
||||
int64_t& n = cost_n_[depth][c];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
}
|
||||
|
||||
int64_t DraftController::cost_samples(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
|
||||
return cost_n_[depth][cost_class(n_rows)];
|
||||
}
|
||||
|
||||
double DraftController::step_cost(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
|
||||
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
|
||||
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
|
||||
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
|
||||
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
|
||||
* ONE class -- reads the prior's shape until its own depths are measured. */
|
||||
for (int dc = 0; dc < kCostClasses; ++dc) {
|
||||
for (int sgn = 0; sgn < 2; ++sgn) {
|
||||
const int k = sgn ? c + dc : c - dc;
|
||||
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
|
||||
int best = -1;
|
||||
for (int d = 1; d <= p_.max_depth; ++d) {
|
||||
if (cost_n_[d][k] <= 0) continue;
|
||||
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
|
||||
}
|
||||
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
|
||||
}
|
||||
}
|
||||
return cost_prior(depth);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one sequence */
|
||||
int DraftController::stop_of(const float* a) const {
|
||||
double p = 1.0;
|
||||
int d = 0;
|
||||
while (d < p_.max_depth) {
|
||||
p *= (double)a[d];
|
||||
if (p < kDraftMinChance) break;
|
||||
++d;
|
||||
}
|
||||
return d < kMinDepth ? kMinDepth : d;
|
||||
}
|
||||
|
||||
double DraftController::prior_at(int j) const {
|
||||
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
|
||||
}
|
||||
|
||||
void DraftController::start(DraftAdapt& s) const {
|
||||
/* Each position from the sequences that finished before it once there are enough of them
|
||||
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
|
||||
for (int j = 0; j < p_.max_depth; ++j) {
|
||||
s.a[j] = (float)prior_at(j);
|
||||
s.n[j] = 0;
|
||||
}
|
||||
s.depth = stop_of(s.a);
|
||||
s.held = 0;
|
||||
}
|
||||
|
||||
void DraftController::adapt_retire(const DraftAdapt& s) {
|
||||
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
|
||||
1.0 / (double)(prior_n_ + 1));
|
||||
for (int j = 0; j < p_.max_depth; ++j)
|
||||
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
|
||||
: s.a[j];
|
||||
++prior_n_;
|
||||
}
|
||||
|
||||
double DraftController::yield(const DraftAdapt& s, int d) const {
|
||||
if (d > p_.max_depth) d = p_.max_depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
|
||||
return e;
|
||||
}
|
||||
|
||||
int DraftController::window_of(const DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) return 0;
|
||||
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
|
||||
return s.depth < D ? s.depth : D;
|
||||
}
|
||||
|
||||
int DraftController::window_for(DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
return window_of(s);
|
||||
}
|
||||
|
||||
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
if (drafted <= 0) return s.depth;
|
||||
const int D = p_.max_depth;
|
||||
if (drafted > D) drafted = D;
|
||||
if (accepted < 0) accepted = 0;
|
||||
if (accepted > drafted) accepted = drafted;
|
||||
|
||||
/* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
|
||||
* rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
|
||||
* and never looked at, and says nothing either way. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
|
||||
const double x = j < accepted ? 1.0 : 0.0;
|
||||
s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
|
||||
if (s.n[j] < UINT16_MAX) ++s.n[j];
|
||||
}
|
||||
/* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
|
||||
* learned about them while the window is shorter -- and a sequence held at three by prose that
|
||||
* turns into code would otherwise keep pricing positions four and up at whatever they read
|
||||
* before, and never draft deep enough to find out. The guess is that acceptance decays with
|
||||
* position rather than falling off a cliff, so the window's edge stands in for what lies past
|
||||
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
|
||||
const double edge = (double)s.a[drafted - 1];
|
||||
for (int j = drafted; j < D; ++j)
|
||||
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
|
||||
|
||||
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
|
||||
if (s.held < INT32_MAX) ++s.held;
|
||||
if (s.held < kHold) return s.depth;
|
||||
const int d = stop_of(s.a);
|
||||
if (d != s.depth) {
|
||||
s.depth = d;
|
||||
s.held = 0;
|
||||
}
|
||||
return s.depth;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
if (!adapt_ || n_seq <= 0) return step_d_;
|
||||
if (n_rows < n_seq) n_rows = n_seq;
|
||||
const int M = p_.max_depth;
|
||||
|
||||
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
|
||||
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
|
||||
* sequence drafts further and the head runs no further -- so the candidates end there. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
DraftAdapt& s = *seq[i];
|
||||
if (s.depth <= 0) start(s);
|
||||
if (s.depth > top) top = s.depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int d = 1; d <= M; ++d) {
|
||||
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
|
||||
tok[d] += e;
|
||||
}
|
||||
}
|
||||
const double plain = (double)(n_rows - n_seq);
|
||||
if (top > M) top = M;
|
||||
|
||||
int best = kMinDepth;
|
||||
double best_g = -1.0;
|
||||
for (int d = kMinDepth; d <= top; ++d) {
|
||||
const double g = (tok[d] + plain) / step_cost(d, n_rows);
|
||||
if (g > best_g) { best_g = g; best = d; }
|
||||
}
|
||||
|
||||
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
|
||||
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
|
||||
if (step_d_ <= 0) {
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
} else {
|
||||
if (step_held_ < INT32_MAX) ++step_held_;
|
||||
const int cur = step_d_ < top ? step_d_ : top;
|
||||
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
|
||||
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
|
||||
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
|
||||
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
|
||||
best_g);
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
}
|
||||
}
|
||||
step_w_ = step_d_ < top ? step_d_ : top;
|
||||
return step_d_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+190
-4
@@ -1,8 +1,8 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
*
|
||||
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
|
||||
* No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
|
||||
* dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
|
||||
* decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
|
||||
* DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
|
||||
@@ -16,6 +16,42 @@
|
||||
*
|
||||
* What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
|
||||
* and because a verify that accepts nothing has to be visible.
|
||||
*
|
||||
* UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
|
||||
* weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
|
||||
* round -- a step is NOT flat in depth: each draft is one more round of the head and one more
|
||||
* verify row. And the best depth is not a property of the model pair but of the TEXT:
|
||||
* per-position acceptance stays high deep into the window on code and JSON and falls off after a
|
||||
* position or two on prose and summaries. No constant is right for all of them, and the one that
|
||||
* is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
|
||||
*
|
||||
* So the adaptive window is a policy on the host, in two halves:
|
||||
*
|
||||
* PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
|
||||
* acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
|
||||
* deepest draft whose chance of being emitted still pays for the verify row it adds
|
||||
* (kDraftMinChance).
|
||||
*
|
||||
* PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so depth is a property of the step and not of one sequence: D maximises
|
||||
* the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
|
||||
* at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
|
||||
* and T measured online (step_time). Every sequence then drafts min(D, stop_i).
|
||||
*
|
||||
* Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
|
||||
* a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
|
||||
* and everything sized for it stays sized for it.
|
||||
*
|
||||
* IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
|
||||
* prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
|
||||
* turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
|
||||
*
|
||||
* IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
|
||||
* core/sample/accept.h, so what a step emits is the target's own token at every position whatever
|
||||
* window it verified. At temperature 0 that is the same text at every window, to exactly the
|
||||
* degree a speculative run matches a plain one at all: exact given the same logits, and a verify
|
||||
* row's logits are computed at an M that now moves with the window (accept.h says what that does
|
||||
* and does not change).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -26,18 +62,148 @@ namespace rad {
|
||||
* band (spec §10), so 64 is the largest window any batch can carry. */
|
||||
enum { RAD_SCHED_MAX_SPEC = 64 };
|
||||
|
||||
/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
|
||||
* text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
|
||||
* and the controller does the arithmetic, so neither has to look the other up.
|
||||
*
|
||||
* `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
|
||||
* It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
|
||||
* it describes is still the text the request is writing -- and a recycled slot starts it over. */
|
||||
struct DraftAdapt {
|
||||
int32_t depth = 0; /* the sequence's stop; 0 = not started */
|
||||
int32_t held = 0; /* verifies since `depth` last moved */
|
||||
float a[RAD_SCHED_MAX_SPEC] = {}; /* conditional acceptance at each draft position */
|
||||
uint16_t n[RAD_SCHED_MAX_SPEC] = {}; /* verifies that evaluated each one, saturating */
|
||||
};
|
||||
|
||||
class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
/* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
|
||||
* drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
|
||||
bool adapt = false;
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------- the policy's constants
|
||||
* Named rather than configurable: each is a property of how the policy works, not of a
|
||||
* deployment, and the one property that IS a deployment's -- what a step costs -- is
|
||||
* measured (step_time). */
|
||||
|
||||
/* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
|
||||
* percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
|
||||
* a percent verify to verify; below two percent a move would flip D between two near-equal
|
||||
* neighbours and pay a recording each time. */
|
||||
static constexpr double kHyst = 0.02;
|
||||
/* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
|
||||
* second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
|
||||
* eight steps plays from the tape for most of them; and eight verifies at the half-life below
|
||||
* move an estimate by about a third of the way to a new rate, which is a trend rather than
|
||||
* one rejection. */
|
||||
static constexpr int kHold = 8;
|
||||
/* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
|
||||
* tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
|
||||
* into a code block and back, long enough that a single rejection moves an estimate by four
|
||||
* percent rather than resetting it. */
|
||||
static constexpr double kHalfLife = 16.0;
|
||||
/* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
|
||||
* deep evaluates every position and learns all of them, one that starts shallow learns nothing
|
||||
* about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
|
||||
* and on code at the first positions, so a wrong start is corrected within a hold. */
|
||||
static constexpr double kPrior = 0.8;
|
||||
/* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
|
||||
* the mean of their estimates, a running mean and then a moving average with a half-life of 32
|
||||
* sequences, so a deployment that moves from one kind of traffic to another follows it within
|
||||
* a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
|
||||
* once it has had a half-life of verifies: before that its estimate is mostly the prior it
|
||||
* started from, and folding it back would feed the prior to itself. */
|
||||
static constexpr int kPriorMinSeqs = 4;
|
||||
static constexpr double kPriorHalfLifeSeqs = 32.0;
|
||||
/* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
|
||||
* ever move its estimate off zero again. */
|
||||
static constexpr int kMinDepth = 1;
|
||||
/* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
|
||||
* and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
|
||||
* the step whatever D is, and that row is the only cost a sequence adds once the head runs D
|
||||
* rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
|
||||
* breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
|
||||
* it adds to the step, with E around two -- and a verify row alone costs less than a round
|
||||
* plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
|
||||
* measurement: a row's share of the step is not separable from the head's rounds in step
|
||||
* times keyed by depth, and the measured T(D, n) already prices the rounds. */
|
||||
static constexpr double kDraftMinChance = 0.1;
|
||||
/* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
|
||||
* step's cost moves with how many rows share its weight reads, and a class a power of two
|
||||
* wide keeps every key fed often enough to mean something. */
|
||||
static constexpr int kCostClasses = 5;
|
||||
|
||||
int configure(const Params& p);
|
||||
const Params& params() const { return p_; }
|
||||
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
|
||||
* under the adaptive policy it is the CEILING, and window_for() is the window. */
|
||||
int next_depth() const { return p_.max_depth; }
|
||||
|
||||
/* ---------------------------------------------------------- the adaptive policy */
|
||||
bool adaptive() const { return adapt_; }
|
||||
/* The window this sequence may draft into: min(D, its stop), starting its estimate on the
|
||||
* first ask; max_depth when the policy is off. Before any step has chosen D, D is the
|
||||
* ceiling. */
|
||||
int window_for(DraftAdapt& s) const;
|
||||
/* The same for a sequence whose estimate has started, without starting one: 0 when it has
|
||||
* not. For reporting. */
|
||||
int window_of(const DraftAdapt& s) const;
|
||||
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
|
||||
* estimate, and its stop past the hold. Returns the stop after. */
|
||||
int adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
|
||||
/* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
|
||||
*
|
||||
* PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
|
||||
* every verify -- are what a fixed window would want, and under this policy they are biased:
|
||||
* only a sequence whose drafts keep being accepted is given a window that reaches the deep
|
||||
* positions, so those positions are measured almost only on the texts that predict well, and
|
||||
* a new sequence would start as if every text did. Each finished sequence counts once here, at
|
||||
* every position, and at a position it never reached its estimate is the extrapolation from
|
||||
* its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
|
||||
* much as a deep one holds them up. */
|
||||
void adapt_retire(const DraftAdapt& s);
|
||||
/* The prior a sequence starting now is given at position `j`. For tests and logs. */
|
||||
double prior_at(int j) const;
|
||||
|
||||
/* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
|
||||
* draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
|
||||
* draft nothing). Started here if they have not been. Moves D past the hold and the
|
||||
* hysteresis; with no sequence to draft, D stays. Returns D. */
|
||||
int plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
|
||||
/* The step depth in force: 0 before the first step chose one. */
|
||||
int step_depth() const { return step_d_; }
|
||||
/* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
|
||||
* was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
|
||||
* any step chose one, and with the policy off. What a proposal from outside the head (prompt
|
||||
* lookup) is held to, so it adds no deeper pass shape than the head's own. */
|
||||
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
|
||||
|
||||
/* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
|
||||
* took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
|
||||
* adaptive policy reads it. */
|
||||
void step_time(int depth, int n_rows, double ms);
|
||||
/* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
|
||||
* been measured: the key's own mean when it has samples; the nearest measured key scaled by
|
||||
* the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
|
||||
* measured. */
|
||||
double step_cost(int depth, int n_rows) const;
|
||||
/* Samples behind a key: for tests and logs. */
|
||||
int64_t cost_samples(int depth, int n_rows) const;
|
||||
|
||||
/* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
|
||||
* the verified token included. For tests and logs. */
|
||||
double yield(const DraftAdapt& s, int d) const;
|
||||
/* Verifies by the window they carried, counted only under the policy: the histogram of the
|
||||
* depths it actually chose, which the mean gauge on its own cannot show. */
|
||||
int64_t verified_at(int d) const {
|
||||
return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
|
||||
}
|
||||
|
||||
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
|
||||
* taken. Feeds the reported metrics and nothing else. */
|
||||
void observe(int drafted, int accepted);
|
||||
@@ -76,6 +242,26 @@ private:
|
||||
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
|
||||
int seen_ = 0;
|
||||
|
||||
/* The adaptive policy as configure() resolved it. */
|
||||
bool adapt_ = false;
|
||||
double alpha_ = 0.0; /* the smoothing step from kHalfLife */
|
||||
int64_t by_depth_[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int32_t step_d_ = 0; /* D; 0 until a step chose one */
|
||||
int32_t step_w_ = 0; /* min(D, the deepest stop it saw) */
|
||||
int32_t step_held_ = 0; /* steps since D last moved */
|
||||
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
|
||||
float prior_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t prior_n_ = 0;
|
||||
/* T(d, class): the mean step time of each key, and the steps behind it. */
|
||||
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
|
||||
/* Fill a sequence's estimate from the prior and set its first stop. */
|
||||
void start(DraftAdapt& s) const;
|
||||
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
|
||||
int stop_of(const float* a) const;
|
||||
static int cost_class(int n_rows);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -137,6 +137,13 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
|
||||
int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
|
||||
/* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
|
||||
* window it gives the sequences running now -- at one sequence, that sequence's window -- and
|
||||
* the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
|
||||
* where the policy stands, the histogram where it has been. */
|
||||
bool draft_adaptive = false;
|
||||
float draft_depth_adaptive = 0.0f;
|
||||
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+170
-7
@@ -97,7 +97,29 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
|
||||
DraftController::Params dp;
|
||||
dp.max_depth = cfg.n_spec;
|
||||
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
|
||||
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
|
||||
* pass at all, so for either the window stays fixed -- decided here, once, before any step
|
||||
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
|
||||
* like a flag that made no difference. */
|
||||
if (cfg.draft_window == DraftWindow::Adaptive) {
|
||||
const RadDrafterDecl& dd = prog.drafter;
|
||||
if (cfg.n_spec <= 0)
|
||||
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
|
||||
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
|
||||
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
|
||||
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
|
||||
"window prices the rounds of a serial draft head, which this deployment does "
|
||||
"not run", cfg.n_spec,
|
||||
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
|
||||
"pass"
|
||||
: "prompt lookup only");
|
||||
else
|
||||
dp.adapt = true;
|
||||
}
|
||||
RAD_TRY(draft_.configure(dp));
|
||||
draft_est_.clear();
|
||||
draft_est_.reserve((size_t)cfg.max_seqs);
|
||||
|
||||
RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
|
||||
/* The builder's bound and not a second derivation of it: it is what the block tables were
|
||||
@@ -155,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. */
|
||||
@@ -178,6 +203,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.card = -1;
|
||||
s.running = false;
|
||||
s.drafter_reset();
|
||||
/* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
|
||||
s.adapt.depth = 0;
|
||||
s.adapt.held = 0;
|
||||
s.sched_tokens = 0;
|
||||
s.entry = -1;
|
||||
s.entry_next = -1;
|
||||
@@ -221,8 +249,15 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
|
||||
/* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
|
||||
* the card already put the tokens in its batch; the host copy is what that step's commit
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped. */
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped.
|
||||
*
|
||||
* UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
|
||||
* and expect_draft() already cut this one's count to its own window -- the card verifies the
|
||||
* FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
|
||||
* count here, against the number the step was planned with: the window itself may have moved
|
||||
* at the commit in between, and the planned step is what these tokens are for. */
|
||||
if (next_open_ && s.entry_next >= 0) {
|
||||
if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
|
||||
if (n != s.draft_next) {
|
||||
RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d",
|
||||
(unsigned long long)id, n, s.draft_next);
|
||||
@@ -244,7 +279,7 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int cap = draft_.next_depth();
|
||||
int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
|
||||
for (int i = 0; i < n; ++i) s.draft[i] = tokens[i];
|
||||
@@ -353,6 +388,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
/* What the draft head did on this text is now part of what the next text starts from --
|
||||
* once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
|
||||
if (draft_.adaptive()) {
|
||||
draft_.adapt_retire(s.adapt);
|
||||
s.adapt.depth = 0;
|
||||
}
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
@@ -862,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;
|
||||
@@ -924,6 +968,8 @@ void Scheduler::undo_hit(SchedReq& s) {
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
const RadBatch* Scheduler::step() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
|
||||
draft_cycle();
|
||||
|
||||
/* The drafter's snapshots describe the step before this one and nothing reads them from here
|
||||
* on. block_end() and serial_end() clear them already; this covers a drafter that stopped
|
||||
@@ -979,10 +1025,22 @@ const RadBatch* Scheduler::step() {
|
||||
/* THE LAST GATE, and it has to be here rather than only at set_draft, because the
|
||||
* n-gram fallback below fills any proposal a drafter left empty -- so refusing a
|
||||
* draft upstream and stopping there hands the request a different draft instead of
|
||||
* none. Request::may_speculate says why a request can be ineligible. */
|
||||
* none. Request::may_speculate says why a request can be ineligible.
|
||||
*
|
||||
* AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
|
||||
* policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
|
||||
* for. The n-gram fallback is not the head and that estimate says nothing about it, so
|
||||
* it is held to the step's window instead: as deep as the head drafts this step and no
|
||||
* deeper, which adds no pass shape the head's own windows do not. */
|
||||
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
|
||||
bool ngram = false;
|
||||
if (!r.may_speculate) s.n_draft = 0;
|
||||
else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth);
|
||||
if (s.n_draft > depth) s.n_draft = depth;
|
||||
else if (s.n_draft == 0) {
|
||||
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
|
||||
ngram = s.n_draft > 0;
|
||||
}
|
||||
if (!ngram && s.n_draft > cap) s.n_draft = cap;
|
||||
s.draft_ngram = ngram;
|
||||
/* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
|
||||
* .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
|
||||
* block-table column. commit() finishes a sequence before its length reaches the
|
||||
@@ -1069,6 +1127,7 @@ const RadBatch* Scheduler::step() {
|
||||
e.draft = s.draft;
|
||||
e.n_draft = s.n_draft;
|
||||
e.is_prefill = prefill;
|
||||
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
|
||||
e.produces_token = (r.n_computed + want >= target);
|
||||
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
|
||||
* sequence after this, and restoring it again on a later chunk would rewind it. */
|
||||
@@ -1335,12 +1394,39 @@ void Scheduler::take_encodes(std::vector<std::shared_ptr<mm::Item>>* out) {
|
||||
out->swap(enc_want_);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's head depth */
|
||||
void Scheduler::draft_cycle() {
|
||||
if (!draft_.adaptive()) return;
|
||||
/* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
|
||||
* may speculate draft, and their estimates choose D; the rest emit one token each, which is
|
||||
* part of what the step yields and of what it costs. A sequence still prefilling is neither. */
|
||||
draft_est_.clear();
|
||||
int n_rows = 0;
|
||||
for (int32_t slot : running_) {
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
const Request& r = *s.req;
|
||||
if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
|
||||
++n_rows;
|
||||
if (r.may_speculate) draft_est_.push_back(&s.adapt);
|
||||
}
|
||||
(void)draft_.plan_step(draft_est_.data(), (int)draft_est_.size(), n_rows);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the next step */
|
||||
void Scheduler::expect_draft(uint64_t id, int n) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return;
|
||||
reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0;
|
||||
SchedReq& s = *reqs_[(size_t)it->second];
|
||||
/* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
|
||||
* first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
|
||||
* since: nothing commits between the two, and D is the cycle's (draft_cycle). */
|
||||
if (draft_.adaptive() && n > 0) {
|
||||
const int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
}
|
||||
s.draft_next = n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
const RadBatch* Scheduler::step_next() {
|
||||
@@ -1424,6 +1510,10 @@ const RadBatch* Scheduler::step_next_locked() {
|
||||
void Scheduler::promote_next() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!next_open_) return;
|
||||
/* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
|
||||
* called. Its proposals were counted under the last cycle's D; the next ones are drafted
|
||||
* under this one. */
|
||||
draft_cycle();
|
||||
std::swap(plan_, plan_next_);
|
||||
plan_next_.reset();
|
||||
step_prefill_tok_ = 0;
|
||||
@@ -1516,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]);
|
||||
@@ -1581,6 +1675,28 @@ int Scheduler::commit(const StepResult& res) {
|
||||
|
||||
if (e.n_spec > 0) {
|
||||
draft_.observe(e.n_spec, a);
|
||||
/* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
|
||||
* window -- when the head drafted it. A prompt-lookup proposal is accepted on
|
||||
* different text by a different rule, and folding it in would price the head's
|
||||
* next window on what the lookup found. A move takes effect at the next draft:
|
||||
* this step's drafter has already run, sized from the estimate as it stood before
|
||||
* this commit. */
|
||||
if (draft_.adaptive() && !e.ngram) {
|
||||
const int was = s.adapt.depth;
|
||||
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
|
||||
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
|
||||
char est[8 * RAD_SCHED_MAX_SPEC];
|
||||
int o = 0;
|
||||
for (int j = 0; j < draft_.next_depth() && o < (int)sizeof est - 8; ++j)
|
||||
o += std::snprintf(est + o, sizeof est - (size_t)o, "%s%.2f",
|
||||
j ? " " : "", (double)s.adapt.a[j]);
|
||||
est[o] = 0;
|
||||
RAD_DEBUG("draft window: request %llu stops at %d, was %d (expected "
|
||||
"tokens a verify %.3f -> %.3f; acceptance by position %s)",
|
||||
(unsigned long long)r.id, now, was, draft_.yield(s.adapt, was),
|
||||
draft_.yield(s.adapt, now), est);
|
||||
}
|
||||
}
|
||||
m_.draft_tokens += e.n_spec;
|
||||
m_.draft_accepted += a;
|
||||
server::sink_drafts(r.sink, e.n_spec, a);
|
||||
@@ -1707,6 +1823,16 @@ void Scheduler::step_finished() {
|
||||
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
|
||||
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
|
||||
}
|
||||
/* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
|
||||
* which is the step's share of the loop -- the draft rounds that followed it included, and a
|
||||
* step issued ahead counted from the end of the one before rather than twice. A decode step
|
||||
* only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
|
||||
* the step verified, which is the head depth it ran at whenever D held from the step before. */
|
||||
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
|
||||
int rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
|
||||
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
|
||||
}
|
||||
last_step_at_ = step_end;
|
||||
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
|
||||
step_start_ = {};
|
||||
@@ -1740,6 +1866,27 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
if (depth > 0 && *rounds > depth) *rounds = depth;
|
||||
if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
|
||||
|
||||
/* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
|
||||
* pass of the head over every drafting row, so the step runs as many as its deepest window,
|
||||
* and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
|
||||
* round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
|
||||
* draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
|
||||
* is the history pass, and that still has to run. The reservation below is then made for the
|
||||
* rounds that will actually run, which is what it is for. */
|
||||
if (may_draft && draft_.adaptive()) {
|
||||
int want = 0;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
|
||||
SchedReq& s = *reqs_[(size_t)e.slot];
|
||||
if (!s.req || s.req->state != ReqState::Running || !s.running ||
|
||||
!s.req->may_speculate)
|
||||
continue;
|
||||
const int c = draft_cap(s);
|
||||
if (c > want) want = c;
|
||||
}
|
||||
if (want > 0 && *rounds > want) *rounds = want;
|
||||
}
|
||||
|
||||
int n_draft_rows = 0;
|
||||
int64_t cu = 0; /* this entry's first token in the step just run */
|
||||
for (size_t i = 0; i < plan_.e.size(); ++i) {
|
||||
@@ -2293,6 +2440,22 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.draft_pos_reached [j] = draft_.reached(j);
|
||||
m.draft_pos_accepted[j] = draft_.hits(j);
|
||||
}
|
||||
if (draft_.adaptive()) {
|
||||
m.draft_adaptive = true;
|
||||
/* Over the running sequences whose estimate has started; one that has not drafted yet
|
||||
* has no window to report. */
|
||||
int64_t sum = 0, n = 0;
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (s.adapt.depth <= 0) continue;
|
||||
/* The window it drafts into: its stop under the step's head depth. */
|
||||
sum += draft_.window_of(s.adapt);
|
||||
++n;
|
||||
}
|
||||
m.draft_depth_adaptive = n ? (float)((double)sum / (double)n) : 0.0f;
|
||||
const int kDepth = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
for (int d = 0; d < kDepth; ++d) m.draft_verify_depth[d] = draft_.verified_at(d);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
+38
-5
@@ -109,6 +109,14 @@ struct SchedReq {
|
||||
draft_hi = 0;
|
||||
}
|
||||
|
||||
/* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
|
||||
* deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
|
||||
* preemption does not change, rather than any cache the request holds. A recycled slot starts
|
||||
* it over in add_locked. Untouched while the policy is off. */
|
||||
DraftAdapt adapt;
|
||||
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
|
||||
bool draft_ngram = false;
|
||||
|
||||
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
|
||||
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
|
||||
/* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
|
||||
@@ -280,7 +288,8 @@ public:
|
||||
* the one that is stuck. Returns how many were written. */
|
||||
int requests(ReqStat* out, int max) const;
|
||||
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
|
||||
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
|
||||
int set_draft(uint64_t id, const int32_t* tokens, int n);
|
||||
|
||||
/* ---------------------------------------------------------- media the encoder owes
|
||||
@@ -292,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
|
||||
@@ -318,7 +327,8 @@ public:
|
||||
* from one to the other.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* which is how many the next step verifies.
|
||||
* which is how many the next step verifies -- capped at the sequence's window,
|
||||
* which under the adaptive policy can be fewer than the rounds that ran.
|
||||
* step_next plans and builds that step: every row of this one, as a device row, at
|
||||
* the furthest context it can reach. Null -- and the engine plans with step()
|
||||
* after this one commits -- whenever the step needs a decision only a
|
||||
@@ -491,6 +501,29 @@ private:
|
||||
return hit_holes_draft_ ? ctx_len : 0;
|
||||
}
|
||||
|
||||
/* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
|
||||
* min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
|
||||
* It is the rule every site that caps a proposal applies -- step(), set_draft(),
|
||||
* expect_draft() and the rounds in serial_begin() -- and with the policy off it is
|
||||
* next_depth(), exactly as before. */
|
||||
int draft_cap(SchedReq& s) const {
|
||||
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
|
||||
}
|
||||
|
||||
/* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
|
||||
* first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
|
||||
* A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
|
||||
* draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
|
||||
* to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
|
||||
* different one. A D read live could move between them, because a commit or a client hanging
|
||||
* up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
|
||||
* proposal drafted under one D and planned under the next is only ever cut shorter.
|
||||
*
|
||||
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
|
||||
* allocate. */
|
||||
std::vector<DraftAdapt*> draft_est_;
|
||||
void draft_cycle();
|
||||
|
||||
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
|
||||
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
|
||||
* lengths it tries, longest first. */
|
||||
|
||||
+14
-4
@@ -280,6 +280,13 @@ public:
|
||||
o.draft_pos_reached [j] = m.draft_pos_reached [j];
|
||||
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
|
||||
}
|
||||
o.draft_adaptive = m.draft_adaptive;
|
||||
o.draft_depth_adaptive = m.draft_depth_adaptive;
|
||||
{
|
||||
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
|
||||
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
|
||||
}
|
||||
o.preemptions = m.preemptions;
|
||||
o.total_requests = m.admitted;
|
||||
o.steps = m.steps;
|
||||
@@ -691,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:
|
||||
|
||||
+35
-4
@@ -114,6 +114,11 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
|
||||
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
|
||||
* of the running sequences, and the verifies by the window they carried (index = drafts). */
|
||||
bool draft_adaptive = false;
|
||||
double draft_depth_adaptive = 0.0;
|
||||
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
|
||||
int64_t preemptions = 0;
|
||||
int64_t total_requests = 0;
|
||||
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
|
||||
@@ -510,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
|
||||
@@ -531,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;
|
||||
@@ -538,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;
|
||||
};
|
||||
|
||||
|
||||
+38
-1
@@ -140,11 +140,23 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
g_draft_pos_reached_[j].set((double)r);
|
||||
g_draft_pos_accepted_[j].set((double)m.draft_pos_accepted[j]);
|
||||
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
|
||||
}
|
||||
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
|
||||
* gauge has not been written yet. */
|
||||
draft_pos_seen_.store(seen, std::memory_order_release);
|
||||
if (m.draft_adaptive) {
|
||||
g_draft_depth_adapt_.set(m.draft_depth_adaptive);
|
||||
int top = 0;
|
||||
for (int d = 1; d <= (int)MAX_DRAFT_POS; ++d) {
|
||||
g_draft_vdepth_[d].set((double)m.draft_verify_depth[d]);
|
||||
if (m.draft_verify_depth[d] > 0) top = d;
|
||||
}
|
||||
/* After the gauges, for the reason above. */
|
||||
draft_vdepth_top_.store(top, std::memory_order_release);
|
||||
draft_adapt_on_.store(true, std::memory_order_release);
|
||||
}
|
||||
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
|
||||
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
|
||||
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
|
||||
@@ -382,7 +394,9 @@ std::string Metrics::render() const {
|
||||
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
|
||||
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
|
||||
* drafter that decays from one whose later rounds are broken; these can, and the companion
|
||||
* `_reached_total` says how much evidence each position carries. */
|
||||
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
|
||||
* same ratio over any window: at a fixed depth the next position's reach would do, but an
|
||||
* adaptive window can end at j with j taken. */
|
||||
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
|
||||
if (seen > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
@@ -397,6 +411,29 @@ std::string Metrics::render() const {
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
|
||||
w.help("radiance:draft_position_accepted_total",
|
||||
"Verifies that accepted each draft position.", "counter");
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
|
||||
}
|
||||
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
|
||||
* at one sequence, that sequence's window -- and where it has been, as verifies by the
|
||||
* number of drafts they carried. */
|
||||
if (draft_adapt_on_.load(std::memory_order_acquire)) {
|
||||
w.gauge("radiance:draft_depth_adaptive",
|
||||
"Mean draft window the adaptive policy gives the running sequences.",
|
||||
L, g_draft_depth_adapt_.get());
|
||||
const int top = draft_vdepth_top_.load(std::memory_order_acquire);
|
||||
if (top > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
w.help("radiance:draft_verify_depth_total",
|
||||
"Verifies by the number of drafts they carried, under the adaptive window.",
|
||||
"counter");
|
||||
for (int d = 1; d <= top; ++d)
|
||||
w.out += "radiance:draft_verify_depth_total" + base + ",depth=\"" +
|
||||
std::to_string(d) + "\"} " + num(g_draft_vdepth_[d].get()) + '\n';
|
||||
}
|
||||
}
|
||||
w.gauge("radiance:num_requests_preempted",
|
||||
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
|
||||
|
||||
@@ -121,7 +121,15 @@ private:
|
||||
enum { MAX_DRAFT_POS = 64 };
|
||||
Gauge g_draft_pos_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
|
||||
std::atomic<int> draft_pos_seen_{0};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
|
||||
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
|
||||
* is on, so a deployment without it exposes exactly what it always did. */
|
||||
Gauge g_draft_depth_adapt_;
|
||||
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
|
||||
std::atomic<bool> draft_adapt_on_{false};
|
||||
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
|
||||
|
||||
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
|
||||
* counter and adding the difference. Two scrapes doing that at once both read the old value
|
||||
|
||||
+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
|
||||
@@ -28,11 +28,10 @@ Window values are counter ratios with the definitions of the since-start gauges:
|
||||
| prompt from attention cache | `attn_cached_tokens` / `prompt_tokens` | `vllm:gpu_prefix_cache_hit_rate` |
|
||||
| prompt from linear checkpoint | `linear_cached_tokens` / (`linear_cached_tokens` + `prefill_tokens`) | `radiance:linear_prefix_cache_hit_rate` |
|
||||
| draft acceptance | `draft_accepted` / `draft_tokens` | `radiance:draft_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_reached`(j+1) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_accepted`(j) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
|
||||
Position j+1 is evaluated only when j was accepted, so its reach counts j's acceptances. The last
|
||||
position's acceptances are the total accepted minus every later reach. Draft blocks per decode step is
|
||||
the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
Draft blocks per decode step is the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
The adaptive draft window and verifies by draft depth have data only under `--draft-window adaptive`.
|
||||
|
||||
Prometheus extrapolates `rate()` inside the window and VictoriaMetrics does not, so short windows at
|
||||
the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's time
|
||||
|
||||
+143
-33
@@ -1252,7 +1252,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well. Position j+1 is reached only when j was accepted, so this is reached(j+1) / reached(j); the last position is the total accepted minus every later reach. A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well, accepted(j) / reached(j). A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
@@ -1265,7 +1265,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 0",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
@@ -1276,7 +1276,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 1",
|
||||
"refId": "B",
|
||||
"range": true,
|
||||
@@ -1287,7 +1287,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 2",
|
||||
"refId": "C",
|
||||
"range": true,
|
||||
@@ -1298,7 +1298,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 3",
|
||||
"refId": "D",
|
||||
"range": true,
|
||||
@@ -1309,7 +1309,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 4",
|
||||
"refId": "E",
|
||||
"range": true,
|
||||
@@ -1320,7 +1320,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 5",
|
||||
"refId": "F",
|
||||
"range": true,
|
||||
@@ -1331,7 +1331,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 6",
|
||||
"refId": "G",
|
||||
"range": true,
|
||||
@@ -1342,7 +1342,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 7",
|
||||
"refId": "H",
|
||||
"range": true,
|
||||
@@ -1353,7 +1353,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 8",
|
||||
"refId": "I",
|
||||
"range": true,
|
||||
@@ -1364,7 +1364,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 9",
|
||||
"refId": "J",
|
||||
"range": true,
|
||||
@@ -1375,7 +1375,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 10",
|
||||
"refId": "K",
|
||||
"range": true,
|
||||
@@ -1386,7 +1386,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 11",
|
||||
"refId": "L",
|
||||
"range": true,
|
||||
@@ -1397,7 +1397,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 12",
|
||||
"refId": "M",
|
||||
"range": true,
|
||||
@@ -1408,7 +1408,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 13",
|
||||
"refId": "N",
|
||||
"range": true,
|
||||
@@ -1419,7 +1419,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 14",
|
||||
"refId": "O",
|
||||
"range": true,
|
||||
@@ -1430,8 +1430,8 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "(sum(rate(radiance:draft_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])) - sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position!=\"0\"}[$__rate_interval]))) / min(sum by (position) (rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])))",
|
||||
"legendFormat": "last position",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 15",
|
||||
"refId": "P",
|
||||
"range": true,
|
||||
"instant": false
|
||||
@@ -1743,6 +1743,116 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Adaptive draft window",
|
||||
"id": 42,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Mean draft window the adaptive policy gives the running sequences; a gap while none runs. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "max by (instance) (radiance:draft_depth_adaptive{instance=~\"$instance\", model_name=~\"$model_name\"}) > 0",
|
||||
"legendFormat": "{{instance}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 5,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "none",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Verifies by draft depth",
|
||||
"id": 43,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Share of verifies by the number of drafts they carried, under the adaptive window. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum by (depth) (rate(radiance:draft_verify_depth_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval]))",
|
||||
"legendFormat": "depth {{depth}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 40,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "percent",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Scheduler",
|
||||
@@ -1753,7 +1863,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
"y": 51
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1769,7 +1879,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1846,7 +1956,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1912,7 +2022,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1977,7 +2087,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 52
|
||||
"y": 60
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1993,7 +2103,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2070,7 +2180,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2147,7 +2257,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2221,7 +2331,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 61
|
||||
"y": 69
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2237,7 +2347,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2294,7 +2404,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2362,7 +2472,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2447,7 +2557,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 70
|
||||
"y": 78
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2463,7 +2573,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2518,7 +2628,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
|
||||
@@ -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.
|
||||
|
||||
+90
-4
@@ -454,6 +454,20 @@ The cache never gets less than one `--max-model-len` sequence, and when both sid
|
||||
whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
|
||||
off the card and gives the cache more.
|
||||
|
||||
**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
|
||||
whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
|
||||
token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
|
||||
`expert_tiered` with both pools derived, a KV pool that pages exactly the common token count and the
|
||||
difference in its weights pool, up to every one of its weights resident; the startup log names the
|
||||
rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
|
||||
under `--deterministic`, or on a device without virtual memory management, the bytes that rank
|
||||
would never page go to its experts all the same. A stated `--vram-kv-mib` or `--vram-weights-mib`
|
||||
is applied to every card unchanged, and a rank whose cache costs as much per token as the dearest
|
||||
rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
|
||||
keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
|
||||
allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
|
||||
and that rank's log says its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
|
||||
|
||||
**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix
|
||||
caching holds a finished sequence's blocks so the next turn can reuse them. When the pool cannot
|
||||
hold the *live sessions*, the cache drops prefixes the next turn wanted and that turn re-prefills
|
||||
@@ -735,6 +749,33 @@ from the first token. The reply is the same either way. A hit whose nearest chec
|
||||
point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
|
||||
the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
|
||||
|
||||
**One depth for every request is a compromise; `--draft-window adaptive` lets the text decide.**
|
||||
Acceptance depends on the text: code and JSON keep accepting deep into the window, prose and
|
||||
summaries fall off after a position or two. With the adaptive window, `--num-speculative-tokens` is
|
||||
the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --num-speculative-tokens 6 --draft-window adaptive
|
||||
```
|
||||
|
||||
A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen
|
||||
for the step, not for one sequence: each step's head depth is the one that maximises the tokens all
|
||||
its sequences are expected to emit over what such a step costs. The cost is measured as the server
|
||||
runs — the time of every decode step, by its depth and by how many sequences it carried — so there
|
||||
is nothing to enter; a depth not yet measured is priced from the nearest one that was. Under that
|
||||
depth each sequence stops at the first draft that would be emitted — it and every draft before it
|
||||
accepted — less than one time in ten, so a prose reply beside a code reply does not pay verify rows
|
||||
for drafts nobody takes. The depth moves only after eight steps and for a two-percent gain, because
|
||||
every new window is a new pass shape and a new recording. A new sequence starts from what the
|
||||
sequences before it finished on, each counted once.
|
||||
|
||||
The adaptive window is the serial draft head's policy. With a block drafter, with prompt lookup
|
||||
alone, or with speculation off the window stays fixed, and the server says so at startup. Prompt
|
||||
lookup proposals made when the head declines are counted in the acceptance metrics but do not move
|
||||
the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree
|
||||
with each other; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and
|
||||
`radiance:draft_verify_depth_total` (§6.3) show where the windows stand. The default is `fixed`.
|
||||
|
||||
### 4.7 Two cards
|
||||
|
||||
```sh
|
||||
@@ -953,6 +994,7 @@ one line naming each one the command line moved.
|
||||
| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
|
||||
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
|
||||
| `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
|
||||
| `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
|
||||
|
||||
**Memory**
|
||||
|
||||
@@ -999,7 +1041,8 @@ one line naming each one the command line moved.
|
||||
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables |
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
|
||||
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
|
||||
| `--draft-model PATH` | — | **not implemented** — merge at convert time |
|
||||
|
||||
**Server**
|
||||
@@ -1053,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)
|
||||
@@ -1261,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 |
|
||||
@@ -1291,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.
|
||||
|
||||
@@ -1469,9 +1553,10 @@ lists the efforts the chat template takes, or is `null` when it takes any. `serv
|
||||
| `decode_tokens_total`, `prefill_tokens_total` | |
|
||||
| `decode_tokens_per_second`, `prefill_tokens_per_second` | |
|
||||
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
|
||||
| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position, since start |
|
||||
| `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
|
||||
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
|
||||
| `decode_rows_unspeculated_total` | rows that never drafted at all |
|
||||
| `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
|
||||
| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
|
||||
| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
|
||||
| `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | |
|
||||
@@ -1560,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` |
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ not.
|
||||
| `ple_gate` | | device | host |
|
||||
| `qk_norm_rope` | | - | host |
|
||||
| `qk_norm_rope_gate` | | device | - |
|
||||
| `qsa_block_key` | | device | - |
|
||||
| `qsa_block_key` | | device | host |
|
||||
| `qsa_score` | | device | - |
|
||||
| `qsa_select` | | device | - |
|
||||
| `qsa_tail_store` | | device | - |
|
||||
|
||||
+106
-11
@@ -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 | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` | `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 |
|
||||
| `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 `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,
|
||||
@@ -1161,11 +1250,11 @@ stages of its sorting network when the runs are a power of two long and fill the
|
||||
over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that
|
||||
hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
## Sparse attention (QSA) — device-only
|
||||
## Sparse attention (QSA)
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt | `k`, `w`w, `page`?, `pos`? → `out` |
|
||||
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` |
|
||||
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
|
||||
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
|
||||
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
|
||||
@@ -1173,7 +1262,8 @@ hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
Five ops decompose one thing: an indexer that scores blocks of key history against the query and
|
||||
hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five.
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five. **`qsa_block_key` has a host kernel in libref
|
||||
and libavx** -- the oracle for libr4d's, YaRN included -- and the other four are **device-only**.
|
||||
|
||||
`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which
|
||||
is what the indexer's block scores are taken against.
|
||||
@@ -1182,6 +1272,11 @@ is what the indexer's block scores are taken against.
|
||||
out[b] = rope( rmsnorm( mean over j<ratio of k[b*ratio + j] ), at position pos0 + b*ratio )
|
||||
```
|
||||
|
||||
The rotation is `rope`'s NeoX ladder over the first `rotary_dim` lanes, with `rope`'s YaRN
|
||||
coefficients (`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude`) when given -- the
|
||||
attention's own rotary, so a compressed key and the keys it summarises are rotated alike. With
|
||||
YaRN, `scale` must be 1.
|
||||
|
||||
**`M` is BLOCKS and `k` is `ratio` times taller.** Every other op in this document has one output
|
||||
row per input row. A caller that sized `k` at the block count would have every block pool three
|
||||
rows of the next one — plausible numbers and a different model — so libr4d's entry point checks it.
|
||||
|
||||
+30
@@ -38,6 +38,36 @@ it, and the tiers skip it when they move an entry. Every rank carves the same bl
|
||||
is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
|
||||
zero limits nobody) and capped at the least before any carves.
|
||||
|
||||
**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
|
||||
card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
|
||||
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
|
||||
attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
|
||||
such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
|
||||
the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
|
||||
because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
|
||||
difference into its weights pool, no further than every one of its weights resident. Both readers
|
||||
of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
|
||||
grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
|
||||
whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
|
||||
loan and the attention ranks' pools are unchanged; a stated `--vram-kv-mib` / `--vram-weights-mib`
|
||||
keeps meaning "this many on every card", and `auto` keeps the common split (a fully resident rank
|
||||
would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
|
||||
management re-split like any other: the cache does not lend there, and the bytes the rank never
|
||||
pages are as much its experts' as they are under a lending cache. The condition is the cost, not
|
||||
the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
|
||||
which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names the reason on
|
||||
its `kv: rank N's cache costs ...` line. The pinned host pool is not re-split: every rank allocates
|
||||
its whole `--host-pool-mib`, and a re-split rank whose weights all fit on the card says so
|
||||
(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
|
||||
|
||||
```
|
||||
kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
|
||||
I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
|
||||
```
|
||||
|
||||
The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
|
||||
than at the budget's `unusable` line alone.
|
||||
|
||||
Under a smaller attention world the plain even shard over `world` is the wrong cut for every
|
||||
attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
|
||||
call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# Static YaRN
|
||||
|
||||
Increasing `--max-model-len` reserves a larger serving window; it does not change
|
||||
the model's rotary embeddings. A checkpoint trained at 262144 positions can
|
||||
explicitly request static YaRN for a 524288-token deployment. Whether that extension
|
||||
preserves useful accuracy must be measured on the model and workload.
|
||||
|
||||
One reader takes every architecture's rotary scaling (`yarn_from`,
|
||||
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
|
||||
then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
|
||||
in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
|
||||
A drafter (DFlash2, DSpark) reads its own `draft.rope_parameters` /
|
||||
`draft.rope_scaling`; it does not inherit the target's scaling. The vision tower keeps
|
||||
its original axial rotations. A GGUF's `rope.scaling.*` keys are carried in as the
|
||||
same `rope_scaling` keys when it is read.
|
||||
|
||||
**The factor convention is the config's**, as vLLM and transformers read it:
|
||||
`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
|
||||
|
||||
Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
|
||||
variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
|
||||
`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
|
||||
same keys and declare the same ops; YaRN there has had no model run.
|
||||
|
||||
## Metadata
|
||||
|
||||
| Key within the rotary object | Meaning |
|
||||
| --- | --- |
|
||||
| `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
|
||||
| `factor` | finite number >= 1, required for YaRN |
|
||||
| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
|
||||
| `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
|
||||
| `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
|
||||
| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
|
||||
|
||||
Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
|
||||
as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
|
||||
GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
|
||||
anything but its neutral value is refused when read. Rotary width (including
|
||||
partial rotary), theta and M-RoPE section selection are unchanged.
|
||||
|
||||
## Convert a separate container
|
||||
|
||||
Use the original target and drafter checkpoints, the same quantization recipe,
|
||||
and a **new output path**. `--reuse` is valid only for the same source weights and
|
||||
recipe; it is not a way to mix weights from different model revisions.
|
||||
|
||||
```sh
|
||||
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
|
||||
--draft-model /checkpoints/Qwen3.8-27B-DFlash2 \
|
||||
--recipe data/recipes/q38-27b-fp8-df2.recipe \
|
||||
--reuse /models/qwen3.8-27b-fp8.rad \
|
||||
--set text_config.rope_parameters.rope_type=yarn \
|
||||
--set text_config.rope_parameters.factor=2 \
|
||||
--set text_config.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--set draft.rope_parameters.rope_type=yarn \
|
||||
--set draft.rope_parameters.factor=2 \
|
||||
--set draft.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--max-ctx 524288 --kv-cache-dtype bf16 \
|
||||
-o /models/qwen3.8-27b-fp8-yarn2.rad
|
||||
```
|
||||
|
||||
Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
|
||||
replacement for the explicit YaRN metadata or the server's `--max-model-len`.
|
||||
The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
|
||||
Check both target and draft settings with `rad-info --meta` after conversion.
|
||||
|
||||
Serve on enough memory for the requested window:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
|
||||
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
|
||||
```
|
||||
|
||||
That cache flag controls **both** target and drafter KV. Startup capacity and
|
||||
successful actual long requests must be checked; the command is not a promise
|
||||
of concurrency or accuracy. Keep the unmodified model and serving setup until
|
||||
long-context quality and speed meet the deployment's requirements.
|
||||
|
||||
## Serve an existing container: `--rope-scaling`
|
||||
|
||||
The same metadata can be written when the container is loaded instead of converted in:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-next-flash-fp8.rad \
|
||||
--rope-scaling yarn:2 --max-model-len 409600
|
||||
```
|
||||
|
||||
`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
|
||||
(`ORIG`, default the container's own trained length) in the rotary object the reader above
|
||||
takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
|
||||
`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
|
||||
drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
|
||||
the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
|
||||
`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
|
||||
`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
|
||||
than stacked over. The result is resolved and checked exactly as a converted container's is
|
||||
(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
|
||||
|
||||
Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
|
||||
reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
|
||||
at all, past the trained length. A persisted prefix cache (`--prefix-cache-dir`) is fingerprinted
|
||||
with the resolved rotary of the target and the drafter, so a store written under a different
|
||||
one -- another `--rope-scaling`, or a container converted with YaRN -- is not reused: every cached
|
||||
key was rotated differently.
|
||||
|
||||
The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
|
||||
a deployment that settles on one can convert it in as above and drop the flag.
|
||||
|
||||
## Kernel and test contract
|
||||
|
||||
`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
|
||||
`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
|
||||
is the original path, with the original op identities. With YaRN, `scale` must be 1:
|
||||
inverse frequencies are blended rather than all positions being divided. Axial
|
||||
rotary with YaRN is refused. Rebuild the bundled plugins together because their
|
||||
shared op schemas must match.
|
||||
|
||||
The math follows the static YaRN formulation (Peng et al.) as vLLM's
|
||||
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
|
||||
correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
|
||||
256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
|
||||
`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
|
||||
same formula at positions through 524287, within 8 ulp of each angle -- tight where
|
||||
the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
|
||||
places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
|
||||
fused versus unfused HIP rotation is checked byte-for-byte separately.
|
||||
+599
-20
@@ -55,6 +55,10 @@
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace avx;
|
||||
|
||||
/* The widest head this accumulates in one frame. MLA's 576 is the widest in circulation and
|
||||
@@ -489,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
|
||||
@@ -504,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;
|
||||
@@ -533,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) {
|
||||
@@ -549,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;
|
||||
@@ -588,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;
|
||||
@@ -616,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.
|
||||
@@ -836,6 +1216,12 @@ AVX_KERNEL(rope) {
|
||||
}
|
||||
}
|
||||
const int pair_mode = mode == ROPE_GPTJ ? ROPE_GPTJ : ROPE_NEOX;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
}
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN)
|
||||
@@ -851,6 +1237,8 @@ AVX_KERNEL(rope) {
|
||||
} else {
|
||||
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
|
||||
}
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
|
||||
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
|
||||
* this op takes the fused qkv rather than two tensors. */
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
|
||||
@@ -879,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;
|
||||
@@ -907,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;
|
||||
@@ -923,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;
|
||||
@@ -953,7 +1424,11 @@ AVX_KERNEL(rope_table) {
|
||||
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
|
||||
const int64_t rows = numel(cs) / rot;
|
||||
const int64_t half = rot / 2;
|
||||
const float* invf = inv_freqs(half, rot, theta);
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
@@ -962,6 +1437,8 @@ AVX_KERNEL(rope_table) {
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
float* buf = scratch_f32((size_t)rot);
|
||||
angles(buf, invf, half, p);
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) buf[i] *= yarn.magnitude;
|
||||
/* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
|
||||
* libref does unconditionally. The dense case is one row store. */
|
||||
if (rad_tensor_is_contiguous(cs)) {
|
||||
@@ -972,3 +1449,105 @@ AVX_KERNEL(rope_table) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qsa_block_key */
|
||||
/* QSA's compressed key (docs/OPS.md): a block's `ratio` rows of k averaged in f32 and rounded to
|
||||
* k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at the block's
|
||||
* position, YaRN included. libref's arithmetic in libref's order; what differs is that the angles
|
||||
* of a block come from one `angles` table, and the inverse frequencies are built once a launch. */
|
||||
AVX_KERNEL(qsa_block_key) {
|
||||
const RadTensor* k = rad_arg_in(a, 0);
|
||||
const RadTensor* w = rad_arg_in(a, 1);
|
||||
const RadTensor* page = rad_arg_in(a, 2);
|
||||
const RadTensor* pos = rad_arg_in(a, 3);
|
||||
const RadTensor* out = rad_arg_in(a, 4);
|
||||
if (!k || !w || !out) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
|
||||
if (n <= 0 || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
|
||||
if (rot < 0 || rot > n || (rot & 1) || rot / 2 > 512) return RAD_E_SHAPE;
|
||||
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
|
||||
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
|
||||
const int64_t M = page ? numel(page) : out->shape[0];
|
||||
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
|
||||
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
|
||||
const bool pos2 = pos && pos->rank == 2;
|
||||
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
|
||||
|
||||
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
|
||||
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
|
||||
static const char* kModes[] = { "neox", "mrope", "imrope" };
|
||||
const int mi = p_enum(a, "mode", kModes, 3, 0);
|
||||
if (mi < 0) return RAD_E_UNSUPPORTED;
|
||||
int64_t sec[3] = {};
|
||||
int n_sec = 0;
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v;) {
|
||||
char* e = nullptr;
|
||||
const long long x = std::strtoll(v, &e, 10);
|
||||
if (e == v) break;
|
||||
if (x <= 0 || n_sec >= 3) return RAD_E_SHAPE;
|
||||
sec[n_sec++] = x;
|
||||
v = e;
|
||||
}
|
||||
/* Several components only with a mode, its sections and three columns of `pos`. */
|
||||
const bool mc = mi != 0 && n_sec > 0 && pos2 && pos->shape[1] >= 3;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
|
||||
return RAD_E_INVAL;
|
||||
const int64_t half = rot / 2;
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
int comp[512] = {};
|
||||
if (mc) {
|
||||
int64_t total = 0;
|
||||
for (int c = 0; c < n_sec; ++c) total += sec[c];
|
||||
if (mi == 1 && total != half) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
int c = 0;
|
||||
if (mi == 1) {
|
||||
int64_t start = 0;
|
||||
while (c + 1 < n_sec && i >= start + sec[c]) { start += sec[c]; ++c; }
|
||||
} else if (n_sec >= 3) {
|
||||
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
|
||||
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
|
||||
}
|
||||
comp[i] = c;
|
||||
}
|
||||
}
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
float* gain = (float*)scratch_f32_c((size_t)n);
|
||||
for (int64_t t = 0; t < n; ++t) gain[t] = wadd + ldt(w, offlin(w, t));
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * ratio * n >= AVX_PAR_MIN)
|
||||
for (int64_t b = 0; b < M; ++b) {
|
||||
const int64_t orow = page ? ldi(page, offlin(page, b)) : b;
|
||||
if (orow < 0) continue;
|
||||
float* y = scratch_f32((size_t)n);
|
||||
float* cs = scratch_f32_b((size_t)(rot > 0 ? rot : 1));
|
||||
double ss = 0.0;
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
|
||||
uint64_t tmp = 0;
|
||||
st_elem(&tmp, k->dtype, 0, acc / (float)ratio);
|
||||
y[t] = ld_elem(&tmp, k->dtype, 0);
|
||||
ss += (double)y[t] * y[t];
|
||||
}
|
||||
const float s = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
|
||||
for (int64_t t = 0; t < n; ++t) y[t] = y[t] * s * gain[t];
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
float pc[3] = {};
|
||||
for (int c = 0; c < (mc ? 3 : 1); ++c)
|
||||
pc[c] = (float)(!pos ? pos0 + b * ratio
|
||||
: ldi(pos, offlin(pos, pos2 ? b * pos->shape[1] + c : b))) / div;
|
||||
if (mc) angles_multi(cs, invf, comp, half, pc);
|
||||
else angles(cs, invf, half, pc[0]);
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float c = cs[i] * yarn.magnitude, sn = cs[half + i] * yarn.magnitude;
|
||||
const float x0 = y[i], x1 = y[half + i];
|
||||
y[i] = x0 * c - x1 * sn;
|
||||
y[half + i] = x0 * sn + x1 * c;
|
||||
}
|
||||
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+102
-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,9 +254,51 @@ 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") });
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (const char* mode : { "neox", "gptj", "imrope" })
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 1e7), HF("scale", 1), HS("mode", mode),
|
||||
HI("rotary_dim", 64), HS("sections", "11 11 10"), HS("dtype", dt),
|
||||
HF("yarn_factor", 2), HF("yarn_low", 14), HF("yarn_high", 22),
|
||||
HF("yarn_magnitude", 1.069314718) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
|
||||
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
|
||||
}
|
||||
for (double magnitude : {2.0, (double)NAN}) {
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 1e7), HF("scale", 1), HS("mode", "neox"),
|
||||
HI("rotary_dim", 64), HS("dtype", "bf16"), HF("yarn_factor", 0),
|
||||
HF("yarn_magnitude", magnitude) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) });
|
||||
}
|
||||
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and
|
||||
* with YaRN, positions drawn up to the block count times the ratio. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1),
|
||||
HS("dtype", dt) });
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0),
|
||||
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
|
||||
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
|
||||
}
|
||||
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
|
||||
* tower's 2-D axial rotary over a whole 72-wide head. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
@@ -353,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(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) {
|
||||
|
||||
+102
-8
@@ -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") };
|
||||
|
||||
@@ -218,17 +248,35 @@ static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping
|
||||
|
||||
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
|
||||
P_F64("scale"), P_STR("dtype") };
|
||||
P_F64("scale"), P_STR("dtype"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
|
||||
|
||||
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
|
||||
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
|
||||
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
|
||||
P_INT("rotary_dim"), P_INTO("pos0"),
|
||||
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
|
||||
P_F64O("scale"), P_F64O("wadd"), P_STR("dtype"),
|
||||
P_STRO("mode"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
|
||||
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
|
||||
OUT("out") };
|
||||
|
||||
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") };
|
||||
|
||||
@@ -375,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") };
|
||||
@@ -422,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." },
|
||||
@@ -444,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." },
|
||||
@@ -506,6 +574,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
"QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with "
|
||||
"gain (wadd + w), rotated at the block's position with `rope`'s ladder and YaRN; libref's "
|
||||
"arithmetic with the angles from one table a block." },
|
||||
{ "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." },
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
@@ -542,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." },
|
||||
@@ -620,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)),
|
||||
@@ -693,6 +784,9 @@ ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache",
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
|
||||
L(rope_table)),
|
||||
SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn",
|
||||
"QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT,
|
||||
L(qsa_block_key)),
|
||||
SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
|
||||
DT_FLOAT, L(qk_norm_rope)),
|
||||
|
||||
|
||||
@@ -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|"
|
||||
|
||||
@@ -652,6 +652,22 @@ void r4d_moe_gemm_pin_prefill(int form);
|
||||
// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical,
|
||||
// and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gemm_pin_fk(int pin);
|
||||
// THE RUN-ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule (the down
|
||||
// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every class's
|
||||
// width allow it), 1 never that tile, 2 that tile -- refused where the shape cannot take it or the
|
||||
// launch is not the aligned form. Bit-identical, and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gemm_pin_down_tile(int pin);
|
||||
// THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 a column a thread
|
||||
// (gather_kernel), 2 a wave a token and sixteen bytes a lane (gather_wide_kernel), refused on a
|
||||
// shape it cannot take. Bit-identical, and r4d_selftest compares their bytes.
|
||||
void r4d_moe_gather_pin_form(int form);
|
||||
// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the launcher's rule
|
||||
// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, at a column-tile count
|
||||
// set by the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel
|
||||
// at n column tiles a block, capped at 16 and refused on a shape the kernel does not serve. Inside
|
||||
// the decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical, and r4d_selftest
|
||||
// compares their bytes.
|
||||
void r4d_moe_gemm_pin_down_dec(int pin);
|
||||
// THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode
|
||||
// tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide
|
||||
// kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from
|
||||
|
||||
@@ -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
|
||||
|
||||
+108
-30
@@ -45,6 +45,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
|
||||
#include <cstdlib>
|
||||
@@ -99,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;
|
||||
@@ -110,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
|
||||
@@ -250,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;
|
||||
@@ -261,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,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);
|
||||
}
|
||||
}
|
||||
@@ -356,7 +364,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
|
||||
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
|
||||
float theta, float rscale, uint32_t row_pitch,
|
||||
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane) {
|
||||
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint32_t half = rot / 2;
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
@@ -376,9 +384,11 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
if (mode == 4)
|
||||
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
|
||||
}
|
||||
inv = yarn.frequency(inv, (int)i);
|
||||
const float ang = p * inv;
|
||||
float c, s;
|
||||
sincosf(ang, &s, &c);
|
||||
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
|
||||
const uint32_t i0 = gptj ? 2 * i : i;
|
||||
const uint32_t i1 = gptj ? 2 * i + 1 : i + half;
|
||||
const float x0 = bf2f(hd[i0]), x1 = bf2f(hd[i1]);
|
||||
@@ -576,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
|
||||
@@ -671,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;
|
||||
@@ -688,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); \
|
||||
@@ -700,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;
|
||||
}
|
||||
|
||||
@@ -771,11 +791,12 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
|
||||
row_pitch, 0, nullptr, 0, 0, stream);
|
||||
}
|
||||
|
||||
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
|
||||
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
|
||||
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
int mode, const int* sec, int n_sec, int plane, long stream) {
|
||||
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
|
||||
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
|
||||
// below and the op without YaRN run the same arithmetic with the same arguments.
|
||||
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
|
||||
int gptj, float theta, float rscale, int row_pitch, int mode,
|
||||
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
|
||||
if (!qkv || !pos) return -1;
|
||||
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
|
||||
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
|
||||
@@ -787,10 +808,19 @@ extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_r
|
||||
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
|
||||
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
|
||||
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane);
|
||||
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
|
||||
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
|
||||
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
int mode, const int* sec, int n_sec, int plane, long stream) {
|
||||
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
|
||||
mode, sec, n_sec, plane, RadYarn{}, stream);
|
||||
}
|
||||
|
||||
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
|
||||
int kv_heads, int block_size, int n_blocks,
|
||||
int k_ld, int v_ld, long stream) {
|
||||
@@ -989,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)
|
||||
|
||||
@@ -1188,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
|
||||
@@ -1210,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;
|
||||
}
|
||||
@@ -1259,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) {
|
||||
@@ -1384,12 +1458,16 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
|
||||
|
||||
const float theta = (float)r4d_getf(a, "theta", 10000.0);
|
||||
const float rscale = (float)r4d_getf(a, "scale", 1.0);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL);
|
||||
/* YaRN over the axial vision rotary, or over a linear position divide, is no model's. */
|
||||
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
|
||||
* reason this op takes the fused projection rather than two tensors. */
|
||||
return r4d_rope_mc_bf16(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
|
||||
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
|
||||
mc, sec, n_sec, plane, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
|
||||
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
|
||||
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store */
|
||||
|
||||
+827
-73
File diff suppressed because it is too large.
Load diff
@@ -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*);
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "rad_yarn.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <cstdint>
|
||||
#include <cmath>
|
||||
@@ -205,7 +206,7 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
|
||||
// those here silently changes the model's output -- a different rope is a different model.
|
||||
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
|
||||
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, float theta,
|
||||
float rscale, int cs_f32, int pos_i64) {
|
||||
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
|
||||
const int m = blockIdx.x;
|
||||
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
|
||||
// A padded row addresses no table row, and a position at or past the table's height writes
|
||||
@@ -216,9 +217,10 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
const size_t o = (size_t)pp * rot;
|
||||
for (int i = threadIdx.x; i < half; i += (int)blockDim.x) {
|
||||
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
|
||||
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)rot), i);
|
||||
float c, s;
|
||||
sincosf(p * inv, &s, &c);
|
||||
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
|
||||
if (cs_f32) {
|
||||
((float*)CS)[o + i] = c;
|
||||
((float*)CS)[o + half + i] = s;
|
||||
@@ -386,8 +388,10 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
|
||||
|
||||
const float theta = (float)r4d_getf(args, "theta", 10000.0);
|
||||
const float rscale = (float)r4d_getf(args, "scale", 1.0);
|
||||
const RadYarn yarn = rad_yarn_args(args);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL);
|
||||
return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
|
||||
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, theta, rscale,
|
||||
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0);
|
||||
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body)
|
||||
@@ -31,6 +31,7 @@
|
||||
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "rad_yarn.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h" // r4d_wave_sum
|
||||
|
||||
@@ -61,7 +62,7 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
|
||||
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
|
||||
uint16_t* __restrict__ out,
|
||||
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
|
||||
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc) {
|
||||
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
|
||||
|
||||
__shared__ float sh[kMaxN];
|
||||
__shared__ float red[kMaxN / 32];
|
||||
@@ -114,9 +115,10 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
|
||||
const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp]
|
||||
: (pos0 + (long long)b * ratio);
|
||||
const float p = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
const float iv = 1.0f / powf(theta, (float)(2 * ci) / (float)rot);
|
||||
const float iv = yarn.frequency(1.0f / powf(theta, (float)(2 * ci) / (float)rot), ci);
|
||||
float s, c;
|
||||
sincosf(p * iv, &s, &c);
|
||||
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
|
||||
const float xp = sh[pt];
|
||||
res = first ? (res * c - xp * s) : (xp * s + res * c);
|
||||
}
|
||||
@@ -148,7 +150,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
|
||||
int n, int ratio, int rot, float eps, float wadd,
|
||||
float theta, float rscale, long long pos0, int k_ld,
|
||||
int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc,
|
||||
const R4dSink& sk) {
|
||||
const R4dSink& sk, RadYarn yarn = {}) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!k || !w || !out) return -1;
|
||||
if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return -2;
|
||||
@@ -162,7 +164,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
|
||||
emit_rc = R4D_EMIT(sk, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, (const uint16_t*)k, (const float*)w,
|
||||
(const int32_t*)page, (const int32_t*)bpos, (uint16_t*)out,
|
||||
n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1,
|
||||
s2, bstep, mc);
|
||||
s2, bstep, mc, yarn);
|
||||
return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -244,12 +246,16 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) {
|
||||
if (r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE);
|
||||
const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o);
|
||||
if (kp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) ||
|
||||
(yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0)))
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
const int e = r4d_qsa_block_key_bf16_emit(
|
||||
r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o),
|
||||
(int)M, (int)n, (int)ratio, (int)rot,
|
||||
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0),
|
||||
(float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0),
|
||||
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk);
|
||||
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk, yarn);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
|
||||
+318
-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 },
|
||||
@@ -276,6 +278,10 @@ static const RadParamSpec pRopeTable[] = {
|
||||
P_F64("theta"),
|
||||
P_F64("scale"),
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
|
||||
};
|
||||
static const RadOperandSpec oRopeTable[] = {
|
||||
{ "positions", RAD_OPD_IN, 0 },
|
||||
@@ -1096,6 +1102,10 @@ static const RadParamSpec pQsaBlockKey[] = {
|
||||
* its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */
|
||||
{ "mode", RAD_P_STR, RAD_OPTIONAL },
|
||||
{ "sections", RAD_P_STR, RAD_OPTIONAL },
|
||||
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
|
||||
};
|
||||
static const RadOperandSpec oQsaBlockKey[] = {
|
||||
{ "k", RAD_OPD_IN, 0 },
|
||||
@@ -1512,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 },
|
||||
};
|
||||
|
||||
@@ -1529,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 },
|
||||
@@ -1574,6 +1670,10 @@ static const RadParamSpec pRope[] = {
|
||||
{ "mode", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "rotary_dim", RAD_P_INT, RAD_OPTIONAL },
|
||||
{ "sections", RAD_P_STR, RAD_OPTIONAL },
|
||||
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------------- the vision tower */
|
||||
@@ -1641,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 },
|
||||
@@ -1824,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 "
|
||||
@@ -1862,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 "
|
||||
@@ -1947,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 "
|
||||
@@ -2395,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"),
|
||||
};
|
||||
@@ -2411,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[] = {
|
||||
@@ -3328,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",
|
||||
@@ -3383,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",
|
||||
@@ -3891,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",
|
||||
|
||||
+1278
-19
File diff suppressed because it is too large.
Load diff
+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");
|
||||
|
||||
+286
-19
@@ -27,12 +27,15 @@
|
||||
* the two-sided reading libr4d's h128 kernel documents.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "rad_yarn.h"
|
||||
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
|
||||
* in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols`
|
||||
* -- the comment above kv_store shows where that shortcut is wrong. */
|
||||
#include "ref_gemm.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
@@ -221,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
|
||||
@@ -259,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)
|
||||
@@ -276,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)
|
||||
@@ -412,11 +422,11 @@ static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, in
|
||||
}
|
||||
|
||||
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
|
||||
const RopeFreq& f, const float* pos) {
|
||||
const RopeFreq& f, const float* pos, float magnitude = 1.0f) {
|
||||
const int64_t half = rot / 2;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float ang = pos[f.comp[i]] * f.inv[i];
|
||||
const float c = std::cos(ang), s = std::sin(ang);
|
||||
const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude;
|
||||
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
|
||||
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
|
||||
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
|
||||
@@ -471,6 +481,12 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
}
|
||||
RopeFreq f;
|
||||
RAD_REF_TRY(rope_freqs(mode, rot, theta, sec, multi ? n_sec : 0, &f));
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
}
|
||||
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
|
||||
@@ -493,14 +509,16 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
|
||||
* this op takes the fused qkv rather than two tensors. */
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
|
||||
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p);
|
||||
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 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
|
||||
@@ -518,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;
|
||||
@@ -550,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;
|
||||
@@ -577,17 +755,106 @@ int ref_rope_table(const RadArgs* a, RadStream) {
|
||||
const int64_t rows = numel(cs) / rot;
|
||||
const int64_t half = rot / 2;
|
||||
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m));
|
||||
if (pp < 0 || pp >= rows) continue;
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
|
||||
const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)rot), (int)i);
|
||||
const float ang = p * inv;
|
||||
stt(cs, offlin(cs, pp * rot + i), std::cos(ang));
|
||||
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang));
|
||||
stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude);
|
||||
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qsa_block_key */
|
||||
/* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks,
|
||||
*
|
||||
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype
|
||||
* normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w)
|
||||
* out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest
|
||||
* passed through, rounded once at the store
|
||||
*
|
||||
* The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is
|
||||
* part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's
|
||||
* components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio`
|
||||
* without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The
|
||||
* rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */
|
||||
int ref_qsa_block_key(const RadArgs* a, RadStream) {
|
||||
const RadTensor* k = t_in(a, 0);
|
||||
const RadTensor* w = t_in(a, 1);
|
||||
const RadTensor* page = t_in(a, 2);
|
||||
const RadTensor* pos = t_in(a, 3);
|
||||
const RadTensor* out = t_in(a, 4);
|
||||
if (!k || !w || !out) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
|
||||
if (n <= 0 || n > REF_HD_MAX || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
|
||||
if (rot < 0 || rot > n || (rot & 1)) return RAD_E_SHAPE;
|
||||
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
|
||||
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
|
||||
const int64_t M = page ? numel(page) : out->shape[0];
|
||||
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
|
||||
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
|
||||
const bool pos2 = pos && pos->rank == 2;
|
||||
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
|
||||
|
||||
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
|
||||
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
|
||||
static const char* kModes[] = { "neox", "mrope", "imrope" };
|
||||
const int mi = p_enum(a, "mode", kModes, 3, 0);
|
||||
if (mi < 0) return RAD_E_UNSUPPORTED;
|
||||
const int mode = mi == 1 ? ROPE_MROPE : mi == 2 ? ROPE_IMROPE : ROPE_NEOX;
|
||||
int64_t sec[8] = {};
|
||||
const int n_sec = rope_sections(a, sec);
|
||||
if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE;
|
||||
/* Several components only with a mode, its sections and three columns of `pos`; otherwise
|
||||
* every frequency reads the block's one position, which every mode reads as NeoX. */
|
||||
const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
|
||||
return RAD_E_INVAL;
|
||||
RopeFreq f;
|
||||
RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, theta, sec, mc ? n_sec : 0, &f));
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t b = 0; b < M; ++b) {
|
||||
const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b;
|
||||
if (orow < 0) continue;
|
||||
float x[REF_HD_MAX], y[REF_HD_MAX];
|
||||
double ss = 0.0;
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
|
||||
uint64_t tmp = 0;
|
||||
st_dt(k->dtype, &tmp, 0, acc / (float)ratio);
|
||||
x[t] = ld_dt(k->dtype, &tmp, 0);
|
||||
ss += (double)x[t] * x[t];
|
||||
}
|
||||
const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
|
||||
for (int64_t t = 0; t < n; ++t) y[t] = x[t] * inv * (wadd + ldt(w, offlin(w, t)));
|
||||
float p[3] = {};
|
||||
for (int c = 0; c < (mc ? 3 : 1); ++c) {
|
||||
const int64_t bp = !pos ? pos0 + b * ratio
|
||||
: ld_int(pos->dtype, pos->data,
|
||||
offlin(pos, pos2 ? b * pos->shape[1] + c : b));
|
||||
p[c] = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
}
|
||||
const int64_t half = rot / 2;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float ang = p[f.comp[i]] * f.inv[i];
|
||||
const float c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude;
|
||||
const float x0 = y[i], x1 = y[half + i];
|
||||
y[i] = x0 * c - x1 * s;
|
||||
y[half + i] = x0 * s + x1 * c;
|
||||
}
|
||||
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user