Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89cee7ce41 | ||
|
|
6a2ee986d6 | ||
|
|
7e796642e6 | ||
|
|
9238b1f23d | ||
|
|
6b4a67f52e | ||
|
|
a97985e7c2 | ||
|
|
7c0bd03841 | ||
|
|
d5b584a4c1 | ||
|
|
3a3345951f | ||
|
|
86128c2e75 | ||
|
|
7fd2cd7fa6 | ||
|
|
7d840861af | ||
|
|
05af4db458 |
No files matched your search
+16
-7
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
|
||||
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
|
||||
# a plugin contract and a server release do not move together.
|
||||
project(radiance VERSION 1.2.2 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.3.0 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)
|
||||
@@ -219,6 +219,14 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
|
||||
endif()
|
||||
# THE DOWNLOADER `radiance --model <owner/name>` RUNS (core/hf_model.cpp). The engine finds it at
|
||||
# <bin>/../libexec/radiance/, so the build puts a copy at the same place under the build tree and
|
||||
# a binary run from either tree finds it without a path to configure.
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance)
|
||||
|
||||
# rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package
|
||||
# config includes that same file: a third party building a plugin from their own repository needs
|
||||
# the function, and a second copy of it in the package config would drift from this one. The file
|
||||
@@ -316,22 +324,23 @@ endif()
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# ---------------------------------------------------------------- media decoding
|
||||
# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by
|
||||
# libswscale (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
|
||||
# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by
|
||||
# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
|
||||
# media part by name -- the same tri-state as HIP, because a machine that has the libraries should
|
||||
# not silently build without them.
|
||||
set(RAD_FFMPEG_FOUND OFF)
|
||||
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
|
||||
find_package(PkgConfig QUIET)
|
||||
if(PkgConfig_FOUND)
|
||||
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale)
|
||||
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale
|
||||
libswresample)
|
||||
endif()
|
||||
if(RAD_FFMPEG_FOUND)
|
||||
message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}")
|
||||
elseif(RAD_WITH_FFMPEG STREQUAL "ON")
|
||||
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.")
|
||||
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale/libswresample were not found.")
|
||||
else()
|
||||
message(STATUS "radiance: no libavformat -- image and video input will be refused")
|
||||
message(STATUS "radiance: no libavformat -- image, video and audio input will be refused")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
+6
-6
@@ -11,8 +11,8 @@
|
||||
#
|
||||
# Stages:
|
||||
# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their
|
||||
# streams need; the distribution's build brings ~200 packages of encoders, filters and
|
||||
# display libraries the engine never calls
|
||||
# streams need (pictures, video, and audio with swresample); the distribution's build
|
||||
# brings ~200 packages of encoders, filters and display libraries the engine never calls
|
||||
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage
|
||||
# test `ctest -LE gpu` on that build -- everything that does not need a card
|
||||
# rootfs the install tree stripped, and every library its binaries and plugins load, resolved
|
||||
@@ -59,11 +59,11 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
&& tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \
|
||||
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
|
||||
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
|
||||
--disable-avdevice --disable-avfilter --disable-swresample \
|
||||
--disable-avdevice --disable-avfilter --enable-swresample \
|
||||
--enable-zlib --enable-libdav1d \
|
||||
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe \
|
||||
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263 \
|
||||
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \
|
||||
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \
|
||||
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
|
||||
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
|
||||
&& make -j"${JOBS:-$(nproc)}" \
|
||||
&& make install \
|
||||
&& mkdir -p /opt/ffmpeg/share/doc/ffmpeg \
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
|
||||
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
|
||||
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
|
||||
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
|
||||
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
|
||||
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
|
||||
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, the
|
||||
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
|
||||
decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
|
||||
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
|
||||
serving any world size from the shipped container, the request log, an uneven world's per-rank
|
||||
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
|
||||
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
|
||||
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
|
||||
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
|
||||
tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the
|
||||
fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana
|
||||
dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form
|
||||
and row groups, the fused router launch, the adaptive draft window, the MoE prefill forms and the
|
||||
sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000
|
||||
(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, the request log, an uneven world's
|
||||
per-rank KV and weights split, --rope-scaling, the model entry's context length, root and
|
||||
capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of
|
||||
the three-rank lossy-wire crash, and cardclock.py), hazyumps (static YaRN for the Qwen rotary
|
||||
paths) and redxherring (--model taking a Hugging Face repo id).
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# radiance
|
||||
|
||||
An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. Model
|
||||
architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
|
||||
An LLM inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's chat, completions
|
||||
and Responses APIs, Anthropic's Messages API and llama-server's native one, so their clients and
|
||||
SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
|
||||
and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags
|
||||
@@ -23,6 +24,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
|
||||
@@ -75,8 +77,14 @@ cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/r
|
||||
```sh
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own
|
||||
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
|
||||
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
|
||||
```
|
||||
|
||||
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it
|
||||
holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy
|
||||
it has. The Docker image has neither tool, so with Docker download the file as shown above.
|
||||
|
||||
These are the flags each model is served with. They match its compose file, minus Flash-Next's
|
||||
prefix-cache tiers:
|
||||
|
||||
@@ -99,10 +107,10 @@ At `--tp 4` the gated residual's write carries the exact all-reduce, with the Mo
|
||||
of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes
|
||||
on a prefill chunk; both produce the same bits. The row above runs exact.
|
||||
`--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot,
|
||||
above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at
|
||||
startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against
|
||||
`--tp 2` on the same cards has not been measured. The
|
||||
`--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the
|
||||
two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6`
|
||||
stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate
|
||||
against `--tp 2` on the same cards has not been measured. The
|
||||
tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of
|
||||
every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the
|
||||
odd block alternates with the parity, so every rank's share is whole blocks and every block has
|
||||
@@ -113,7 +121,7 @@ above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `tt
|
||||
of RAM by default: that row needs 96 GiB of RAM or a raised limit
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op
|
||||
and the kernel it resolved to, then exit without serving. Then:
|
||||
|
||||
```sh
|
||||
|
||||
+2
-1
@@ -602,7 +602,8 @@ typedef int (*RadKernelConcurrentFn)(int i);
|
||||
* other, whatever it is called:
|
||||
* - the loader ranks it below every unnamed kernel library, because a reference matches every
|
||||
* op it declares and would otherwise answer for them ahead of the library serving the card
|
||||
* (naming it in --kernels still puts it where it is named);
|
||||
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
|
||||
* not name it leaves it out);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* told to with --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
|
||||
+45
-2
@@ -134,6 +134,15 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_out_rows;
|
||||
|
||||
/* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no
|
||||
* audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way
|
||||
* max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds
|
||||
* the longest clip, since one clip is one segment. The engine takes it from
|
||||
* RadArchProbe::audio_frames, which is the plugin's statement of its longest clip.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_audio_frames;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== weights */
|
||||
@@ -443,6 +452,25 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
* the first step. An embedding-only or encoder-only plugin declares none, deliberately. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits,
|
||||
* one row a sequence of the step -- row s is sequence s's whole input pooled into one vector,
|
||||
* whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads
|
||||
* rows [0, n_seq) back after the step and hands each to its request; it does not normalise them,
|
||||
* because that is the API's choice and not the model's.
|
||||
*
|
||||
* DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is:
|
||||
*
|
||||
* - every sequence in a step is a WHOLE input. The scheduler never splits one across steps,
|
||||
* because an encoder that attends both ways cannot be fed half of its input, and it refuses
|
||||
* an input longer than one step's tokens rather than truncating it;
|
||||
* - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request
|
||||
* ends at the step that carried it.
|
||||
*
|
||||
* f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A
|
||||
* Program declares this or logits, never both -- a model that both generates and embeds is two
|
||||
* deployments. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits
|
||||
@@ -531,17 +559,21 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* the processor's (core/mm), which reads its geometry from the container: the two agree through
|
||||
* `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the
|
||||
* processor about either. */
|
||||
/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio
|
||||
* encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and
|
||||
* its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */
|
||||
enum {
|
||||
RAD_MM_IMAGE = 1u << 0,
|
||||
RAD_MM_VIDEO = 1u << 1,
|
||||
RAD_MM_AUDIO = 1u << 2,
|
||||
};
|
||||
|
||||
typedef struct RadEncoderDecl {
|
||||
const char* name; /* "vision" -- for messages */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */
|
||||
int64_t patch_dim; /* elements in one input patch row */
|
||||
int64_t merge; /* input patches per output row */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches (max_audio_frames) */
|
||||
int64_t n_embd; /* the width of an output row, the model's embedding width */
|
||||
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
|
||||
* the pass and before any other pass runs, so the planner may share its bytes with buffers
|
||||
@@ -612,6 +644,17 @@ typedef struct RadArchProbe {
|
||||
* function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the
|
||||
* core does not ask, and the activation arena is not lent. */
|
||||
int shape_probe_ok;
|
||||
|
||||
/* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin
|
||||
* declares an encoder. A pass carries whole output rows, so the core rounds the pass size it
|
||||
* picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator
|
||||
* names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */
|
||||
int64_t enc_merge;
|
||||
|
||||
/* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole
|
||||
* number of its merge), when it declares one: the engine sizes the audio pass with it
|
||||
* (RadBuildCtx::max_audio_frames). 0 is no audio. */
|
||||
int64_t audio_frames;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
+10
-4
@@ -206,10 +206,16 @@ typedef struct RadBatch {
|
||||
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
|
||||
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
|
||||
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
|
||||
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
|
||||
* resized, normalised and cut by the processor, and its output is the encoder's declared
|
||||
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO
|
||||
* for an audio encoder, the image/video mask for the other -- so a program that declared two
|
||||
* knows which to run. Its input is a list of patches, already resized, normalised and cut by
|
||||
* the processor, and its output is the encoder's declared `out` buffer, one row per `merge`
|
||||
* patches, which the core reads back after the pass.
|
||||
*
|
||||
* An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's
|
||||
* index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the
|
||||
* clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones.
|
||||
*
|
||||
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
|
||||
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
|
||||
|
||||
+2
-1
@@ -44,7 +44,8 @@ enum {
|
||||
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
|
||||
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
|
||||
RAD_SP_XTC = 1 << 3,
|
||||
RAD_SP_DRY = 1 << 4
|
||||
RAD_SP_DRY = 1 << 4,
|
||||
RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */
|
||||
};
|
||||
|
||||
/* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no
|
||||
|
||||
@@ -65,8 +65,10 @@
|
||||
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
|
||||
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
|
||||
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Here it also buys
|
||||
* something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
|
||||
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
|
||||
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
|
||||
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* global without an all-gather and the selector's codebooks can be indexed directly.
|
||||
*
|
||||
* ============================== THE NORMS ARE PLAIN ==============================
|
||||
@@ -230,10 +232,11 @@ struct Dflash2 {
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* THE SIX LINEARS ARE FP8 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
|
||||
* block fp8 and the recipe makes it so -- and the reason is bytes: the drafter is read WHOLE on
|
||||
* every decode step, which makes it one of the largest single items in the decode budget
|
||||
* after the trunk's own GEMMs.
|
||||
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
|
||||
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
|
||||
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
|
||||
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
|
||||
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
|
||||
* Nothing it computes can change an emitted token, because every draft is verified against the
|
||||
* trunk exactly; the only thing quantising it can move is acceptance. */
|
||||
DenseFP8 w_fc{};
|
||||
@@ -284,6 +287,14 @@ struct Dflash2 {
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
|
||||
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
|
||||
rad_weight w_lm = 0;
|
||||
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
|
||||
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
@@ -471,8 +482,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
|
||||
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
|
||||
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
|
||||
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
|
||||
* pass is `block` rows by construction.
|
||||
@@ -489,12 +502,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
|
||||
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -515,18 +523,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
|
||||
* weight its prefetch interval and its residency class, so two weights want two ops even
|
||||
* where one would issue both. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -603,24 +601,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h2q, w.h2s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -633,12 +616,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.atq, w.ats}, {w.h});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
@@ -650,12 +628,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h2q, w.h2s}, {w.gate_up});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
|
||||
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
|
||||
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
|
||||
@@ -667,7 +640,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* because M > 64 is a refusal in the kernel and not a slower path. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0) {
|
||||
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
@@ -678,12 +651,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffq, w.ffs}, {w.h});
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
|
||||
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
|
||||
@@ -789,31 +757,56 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
|
||||
* replicated, so that graph is the one it always was -- an optional parameter present with
|
||||
* the value 0 is not the same declaration as an absent one. */
|
||||
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
|
||||
if (!rerank) top_w = cfg.sel_topk;
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_INT("R", top_w), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
|
||||
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
|
||||
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
|
||||
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
|
||||
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
|
||||
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
|
||||
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
|
||||
*
|
||||
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
|
||||
* gather and merge below then rank exact values. A replicated draft head above one rank
|
||||
* proposes ids another rank owns, so it keeps its own scores. */
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("n_vocab", head_rows(g)), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
rad_buf rd[2] = { w.sel_h, w.cand };
|
||||
rad_buf wr[3] = { w.cand, w.unary, w.dpair };
|
||||
rad_op_reads (b, op_drerank, rd, 2);
|
||||
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
|
||||
}
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
|
||||
* candidate gather carries `row`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.sel_topk * 2),
|
||||
RAD_INT("numel", srows * top_w * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", cfg.sel_topk * 2)),
|
||||
RAD_INT("row", top_w * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -851,16 +844,16 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
* rows. */
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -898,11 +891,11 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
@@ -919,7 +912,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
|
||||
* its coefficients come from the replicated pre-attention norm, so either order is the
|
||||
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
|
||||
@@ -941,13 +934,12 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
@@ -980,15 +972,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), RAD_NONE);
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
+55
-2
@@ -1127,11 +1127,35 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
*/
|
||||
struct DenseFP8 {
|
||||
rad_weight w = 0, s = 0;
|
||||
/* OR AN OCP-MXFP4 WEIGHT, when that is what the container holds for it (a recipe's `codes=
|
||||
* fp4_e2m1 group=32 scale=e8m0`): e2m1 codes, the E8M0 plane, and that plane again as the
|
||||
* per-row reference -- LinearFP8's mx branch, without the GEMM. A block that declares its own
|
||||
* GEMM over a DenseFP8 asks `gemm()` for it and passes `bref()` as the op's last operand, so
|
||||
* one block serves either format against the same E4M3 activation pair. */
|
||||
rad_weight ref = 0;
|
||||
bool mx = false;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts = {});
|
||||
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
|
||||
if (mx)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
}
|
||||
/* The op's trailing `b_ref` operand: the reference view for MXFP4, absent for fp8. */
|
||||
RadOperand bref() const { return mx ? RAD_W(ref) : RAD_NONE; }
|
||||
};
|
||||
|
||||
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
@@ -1139,6 +1163,36 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts) {
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---- OCP-MXFP4, read off the encoding the name map resolves to. The exponent grid is one row
|
||||
* tall, so a part needs only whole 16-row tiles; K takes whole 128s because the E4M3 activation
|
||||
* in front carries a scale per (row, 128). */
|
||||
{
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
RadEncoding enc{};
|
||||
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
|
||||
if (mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
|
||||
"in 16s and K in whole %d-column activation scale blocks.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t q : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, p, np);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
return w && s && ref ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
|
||||
"%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
|
||||
@@ -1163,8 +1217,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
}
|
||||
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sn = nm.f("%s.scale", base); /* the name map was made above */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np);
|
||||
s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard,
|
||||
grp, sp, np);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
|
||||
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(embgemma2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -493,13 +493,24 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
* vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
|
||||
* op declared over it is a read past its end. */
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, dc.sel_topk});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, dc.sel_topk});
|
||||
/* THE CANDIDATES ARE RESCORED against the target's head when logit_rerank can read its plane
|
||||
* (fp8 or int8 rows) and every candidate a rank proposes is one it owns -- the rule the block
|
||||
* applies; the planes are then kRerankR wide and the selector reads the first sel_topk. */
|
||||
{
|
||||
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
|
||||
if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
m.df.w_lm = m.w_lm_head;
|
||||
m.df.top_w = Dflash2::kRerankR;
|
||||
}
|
||||
}
|
||||
const int64_t tw = m.df.w_lm ? m.df.top_w : dc.sel_topk;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
|
||||
/* The vocab-parallel candidate exchange, and only when there is one: this rank's top-R as
|
||||
* (int32 id, float value) pairs and the all-gathered world_size * R of them. */
|
||||
if (Dflash2::head_sharded(dg)) {
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, dc.sel_topk, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.sel_topk, 2});
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
/* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through
|
||||
* the selector and never through the sampler's token buffer. */
|
||||
@@ -678,7 +689,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state
|
||||
* instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of
|
||||
* what depth costs at that concurrency, and halving the width halves it. It also halves what a
|
||||
* sequence costs in --vram-kv-mib, which is context and batch size as well as time.
|
||||
* sequence costs in the KV pool, which is context and batch size as well as time.
|
||||
*
|
||||
* IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a
|
||||
* long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge,
|
||||
|
||||
@@ -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);
|
||||
|
||||
+98
-29
@@ -10,6 +10,7 @@
|
||||
* and have fusion be a selection rather than a compiler pass (spec §2.3).
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
#include "../device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
@@ -45,6 +46,26 @@ std::string Program::Miss::line() const {
|
||||
why.c_str());
|
||||
}
|
||||
|
||||
std::vector<const Program::Miss*> Program::device_holes(bool host_backend) const {
|
||||
/* By INSTANCE, because bands are: two declarations of one op can differ in geometry and in
|
||||
* whether they carry a weight, and only the instance that missed decides whether the planner
|
||||
* can move it to the host. */
|
||||
std::set<std::pair<int32_t, std::string>> no_host;
|
||||
for (const Miss& m : misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
|
||||
std::vector<const Miss*> out;
|
||||
for (const Miss& m : misses) {
|
||||
if (m.domain == RAD_DOMAIN_HOST) continue;
|
||||
const bool host_kernel = no_host.count(std::make_pair(m.index, m.span)) == 0;
|
||||
/* An instance with no weight has nothing the planner places, so nothing moves it. */
|
||||
const bool weightless = m.index > 0 && (size_t)m.index < ops.size() &&
|
||||
ops[(size_t)m.index].weights.empty();
|
||||
if (host_kernel && (host_backend || !weightless)) continue;
|
||||
out.push_back(&m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const char* bld_access_name(int a) {
|
||||
switch (a) {
|
||||
case RAD_ACCESS_PER_TOKEN: return "per-token";
|
||||
@@ -565,7 +586,7 @@ void Builder::resolve_bands(OpInfo& oi) {
|
||||
* reports the list whole (spec §3.1). */
|
||||
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
|
||||
b.miss[d].empty() ? "no kernel matched" : b.miss[d],
|
||||
d });
|
||||
d, oi.index });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -616,7 +637,7 @@ void Builder::finish_instances() {
|
||||
r.geom.str().c_str(), rad_strerror(s));
|
||||
b.miss[d] = fmt("init() refused the instance: %s", rad_strerror(s));
|
||||
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
|
||||
b.miss[d], d });
|
||||
b.miss[d], d, oi.index });
|
||||
r = Resolved{};
|
||||
}
|
||||
}
|
||||
@@ -1036,10 +1057,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 +1115,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 +1163,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 +1593,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1573,16 +1642,11 @@ int Builder::finish() {
|
||||
* SPLIT BY DOMAIN, because the two counts mean different things and one total means
|
||||
* neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert
|
||||
* -- reads this line and nothing else, so it has to say which kind it found. */
|
||||
/* A device miss whose op resolved on the HOST for the same band is not a hole -- the
|
||||
* planner runs it there (engine_bringup.cpp's miss_report says the same thing at more
|
||||
* length). Counting it as a device miss makes a deliberately host-only op open every run
|
||||
* with a warning that names a hole there is not. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
for (const Program::Miss& m : prog_.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
size_t dev = 0;
|
||||
for (const Program::Miss& m : prog_.misses)
|
||||
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) ++dev;
|
||||
/* A device miss a host kernel stands in for is not a hole -- the planner runs it there
|
||||
* (Program::device_holes has the rule, engine_bringup.cpp's miss_report the longer
|
||||
* account). Counting it as a device miss makes a deliberately host-only op open every
|
||||
* run with a warning that names a hole there is not. */
|
||||
const size_t dev = prog_.device_holes(device_is_host()).size();
|
||||
/* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp --
|
||||
* so it does not get warned about here either. The device count is the one that means
|
||||
* something to a tool reading this line and nothing else. */
|
||||
@@ -1688,6 +1752,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
|
||||
|
||||
+58
-22
@@ -39,15 +39,18 @@ static const std::string g_draft_window_help =
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--model", "PATH", "the .rad container, a checkpoint served as it stands, or a\n"
|
||||
"Hugging Face repo id (owner/name), fetched before startup" },
|
||||
{ "--download-dir", "DIR", "where a repo id is fetched to; default\n"
|
||||
"$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
"homes separated by ':' are searched in order, the first winning" },
|
||||
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
|
||||
{ "--kernels", "LIST", "the kernel libraries to use, comma-separated, first wins; unnamed ones are not loaded. Default: every library found" },
|
||||
|
||||
{ "--tp", "N", "tensor-parallel ranks" },
|
||||
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
|
||||
"none at 8" },
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n"
|
||||
"and 4, none at 8" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
|
||||
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
|
||||
"asks the driver, on requires peer access and stops without\n"
|
||||
@@ -59,15 +62,12 @@ static const Flag g_flags[] = {
|
||||
"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" },
|
||||
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
|
||||
" keeps it in the pinned host pool, read over the link in place;\n"
|
||||
" auto keeps it on the card unless the KV cache could then not\n"
|
||||
" hold one --max-model-len sequence. disk is refused: the lookup\n"
|
||||
" writes the card's activations, which no host read can reach" },
|
||||
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
|
||||
" pins it in host memory beside --host-pool-mib, read over the\n"
|
||||
" link in place; by default a model whose output head reads the\n"
|
||||
" table, or a host without the memory, keeps it on the card" },
|
||||
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
|
||||
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
|
||||
" vram puts all of it on every card; ram copies it into\n"
|
||||
@@ -192,7 +192,10 @@ static const Flag g_flags[] = {
|
||||
{ "--video-fps", "F", "frames sampled per second of video" },
|
||||
{ "--video-min-frames", "N", "the fewest frames sampled from a video" },
|
||||
{ "--video-max-frames", "N", "the most frames sampled from a video" },
|
||||
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" },
|
||||
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n"
|
||||
" budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" },
|
||||
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n"
|
||||
" default the container's); a request's `image_tokens` overrides it" },
|
||||
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
|
||||
" (default 67108864). The media flags above default to what the container\n"
|
||||
" states, and do nothing for a model that takes no media" },
|
||||
@@ -223,10 +226,19 @@ static const Flag g_flags[] = {
|
||||
|
||||
void config_usage(const char* argv0) {
|
||||
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
|
||||
/* A help text's continuation lines start under its first line, whatever indentation the
|
||||
* string itself carries. */
|
||||
for (const Flag& f : g_flags) {
|
||||
char left[64];
|
||||
snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
|
||||
fprintf(stderr, " %-32s %s\n", left, f.help);
|
||||
std::string help;
|
||||
for (const char* p = f.help; *p; ++p) {
|
||||
help += *p;
|
||||
if (*p != '\n') continue;
|
||||
help.append(35, ' ');
|
||||
while (p[1] == ' ') ++p;
|
||||
}
|
||||
fprintf(stderr, " %-32s %s\n", left, help.c_str());
|
||||
}
|
||||
fprintf(stderr,
|
||||
"\nEvery pool is budgeted explicitly. The trade between KV blocks and resident weights\n"
|
||||
@@ -373,6 +385,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("-v")) log_set_level(Log::Debug);
|
||||
else if (S("-vv")) log_set_level(Log::Trace);
|
||||
else if (S("--model")) { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
|
||||
else if (S("--download-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
|
||||
else if (S("--radiance-home")) { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
|
||||
else if (S("--kernels")) { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = split_commas(v); }
|
||||
else if (S("--tp")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp = atoi(v); }
|
||||
@@ -405,8 +418,16 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
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); }
|
||||
/* THE TWO POOLS ARE THE BUDGET RESOLVER'S, always (core/mem/vram_budget.h). A launch
|
||||
* line that tries to size them is told which flags move the split, rather than "unknown
|
||||
* option". */
|
||||
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
|
||||
RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
|
||||
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
|
||||
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay "
|
||||
"on the card", a.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
|
||||
* "-mib" is the unit, which every other size flag in this list also spells out. Both
|
||||
* parse to the same field. */
|
||||
@@ -425,11 +446,20 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
TablePlacement p;
|
||||
if (!parse_table_placement(v, &p)) {
|
||||
/* The embedding has two tiers: its lookup writes activations the card reads, which a
|
||||
* host kernel reading the container cannot reach, so there is no disk -- and with
|
||||
* ram the default wherever it can be honoured, nothing left for auto to choose. */
|
||||
if (emb && (!parse_table_placement(v, &p) ||
|
||||
(p != TablePlacement::Ram && p != TablePlacement::Vram))) {
|
||||
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!emb && !parse_table_placement(v, &p)) {
|
||||
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
(emb ? c->embedding_placement : c->ngram_placement) = p;
|
||||
if (emb) c->embedding_placement_given = true;
|
||||
}
|
||||
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
|
||||
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
|
||||
@@ -681,6 +711,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;
|
||||
@@ -726,12 +762,12 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
* rank the one that IS installed behind the reference implementation, which matches every op
|
||||
* and would answer for all of them.
|
||||
*
|
||||
* An empty hierarchy is not "no order". The loader orders what it finds: everything named by
|
||||
* --kernels or RADIANCE_KERNELS first, then every other plugin, then the reference library
|
||||
* last by construction because it matches anything (core/plugin/loader.cpp). So dropping a
|
||||
* kernel library into $RADIANCE_HOME/kernels is enough to be used, on any card, with no
|
||||
* configuration -- and naming one ahead of another is what settles a tie between two that
|
||||
* both serve an op. */
|
||||
* An empty hierarchy is not "no order". The loader loads everything it finds and orders it,
|
||||
* the reference library last by construction because it matches anything
|
||||
* (core/plugin/loader.cpp). So dropping a kernel library into $RADIANCE_HOME/kernels is
|
||||
* enough to be used, on any card, with no configuration. A list names the libraries to use:
|
||||
* only those load, in its order, so naming one ahead of another settles a tie between two that
|
||||
* both serve an op and leaving one out keeps it out. */
|
||||
if (c->model.empty()) {
|
||||
RAD_ERR("--model is required");
|
||||
return RAD_E_INVAL;
|
||||
|
||||
+66
-11
@@ -57,6 +57,7 @@
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
@@ -563,6 +564,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 +608,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);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -2059,10 +2086,17 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
|
||||
* process takes is the runtime's HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the same capability the thunk
|
||||
* decides by, and the log says it once.
|
||||
*
|
||||
* What hipHostMalloc does besides the pin is kept, so the pages are the same pages: shared
|
||||
* anonymous memory, huge pages advised from 2 MiB up, a preferred NUMA node that is the one
|
||||
* nearest the current card (ROCr allocates from that node's pool), fine-grained coherence (the
|
||||
* pool locked to), and access from every card.
|
||||
* What hipHostMalloc does besides the pin is kept: huge pages advised from 2 MiB up, a preferred
|
||||
* NUMA node that is the one nearest the current card (ROCr allocates from that node's pool),
|
||||
* fine-grained coherence (the pool locked to), and access from every card. The memory is PRIVATE
|
||||
* anonymous memory and not hipHostMalloc's shared kind, because the advice is only as good as the
|
||||
* policy behind it: shared anonymous memory is shmem, whose huge pages follow
|
||||
* transparent_hugepage/shmem_enabled, `never` on stock Ubuntu, so the pool got 4 KiB pages there
|
||||
* whatever it advised. Private memory follows transparent_hugepage/enabled, `madvise` on the same
|
||||
* hosts. Where an IOMMU translates the cards' reads (Intel VT-d, which these pieces exist for) each
|
||||
* page is a translation of its own, and a pool streamed from at 4 KiB measured 10-21% slower
|
||||
* prefill on such a host. MADV_DONTFORK keeps the range out of any child: a private range
|
||||
* a card has pinned is copied whole into a forked child, where it is of no use.
|
||||
*
|
||||
* kPinPiece is a power of two well under the failing size. The cost is one buffer object per piece
|
||||
* per card: a few dozen for the largest pools. */
|
||||
@@ -2107,6 +2141,21 @@ void prefer_numa_node(void* p, int64_t len, int node) {
|
||||
std::strerror(errno));
|
||||
}
|
||||
|
||||
/* TRANSPARENT HUGE PAGES TURNED OFF leave every pinned range at 4 KiB pages whatever it advises:
|
||||
* said once, because on a host whose IOMMU translates the cards' reads that is a slower stream
|
||||
* from the host pool and nothing else on the log points at it. */
|
||||
void warn_if_no_huge_pages() {
|
||||
static std::atomic<bool> said{false};
|
||||
if (said.exchange(true)) return;
|
||||
std::ifstream f("/sys/kernel/mm/transparent_hugepage/enabled");
|
||||
std::string mode;
|
||||
if (!std::getline(f, mode) || mode.find("[never]") == std::string::npos) return;
|
||||
RAD_WARN("device: transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled "
|
||||
"is never), so pinned host memory gets 4 KiB pages; where an IOMMU translates the "
|
||||
"cards' reads, streaming from the host pool is slower. 'madvise' gives the pinned "
|
||||
"ranges huge pages and nothing else.");
|
||||
}
|
||||
|
||||
const char* hsa_why(hsa_status_t st) {
|
||||
const char* m = nullptr;
|
||||
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
|
||||
@@ -2167,7 +2216,7 @@ void* pin_pieces(int64_t bytes) {
|
||||
/* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's
|
||||
* fixed-stride slots inherit its base alignment, and a huge page needs it. */
|
||||
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_READ | PROT_WRITE,
|
||||
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
|
||||
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (m == MAP_FAILED) {
|
||||
device_set_error("rad_dev_alloc(%s): mmap: %s", humanb(bytes).c_str(), std::strerror(errno));
|
||||
return nullptr;
|
||||
@@ -2179,7 +2228,11 @@ void* pin_pieces(int64_t bytes) {
|
||||
char* const p = (char*)at;
|
||||
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
if (len >= ((int64_t)2 << 20)) {
|
||||
::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
warn_if_no_huge_pages();
|
||||
}
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
@@ -2317,6 +2370,8 @@ DeviceBackend g_aql;
|
||||
|
||||
} // namespace
|
||||
|
||||
size_t aql_code_registered(void) { return a_code_mark(); }
|
||||
|
||||
const DeviceBackend* aql_backend_if_present(void) {
|
||||
static const DeviceBackend* b = []() -> const DeviceBackend* {
|
||||
const DeviceBackend* hip = hip_backend_if_present();
|
||||
|
||||
@@ -376,6 +376,10 @@ const DeviceBackend* hip_backend_if_present(void);
|
||||
const DeviceBackend* aql_backend_if_present(void);
|
||||
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
|
||||
int64_t aql_pageable_bytes(void);
|
||||
/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
|
||||
* this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
|
||||
* no card. The host backend's code_mark in a HIP build. */
|
||||
size_t aql_code_registered(void);
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ the error slot */
|
||||
|
||||
@@ -67,16 +67,50 @@ 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)");
|
||||
}
|
||||
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
|
||||
* registration hooks are this build's own exported symbols and see every dlopen'ed kernel
|
||||
* library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
|
||||
* which library brought device code. An engine serving here leaves that library's device rows out
|
||||
* of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
|
||||
static DeviceBackend g_host_beside_hip;
|
||||
#endif
|
||||
|
||||
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");
|
||||
#endif
|
||||
g_host_beside_hip = *host_backend();
|
||||
g_host_beside_hip.code_mark = aql_code_registered;
|
||||
const DeviceBackend* b = &g_host_beside_hip;
|
||||
#else
|
||||
const DeviceBackend* b = host_backend();
|
||||
#endif
|
||||
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
|
||||
return b;
|
||||
}
|
||||
|
||||
+241
-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()) {
|
||||
@@ -864,6 +867,10 @@ int Engine::step_loop() {
|
||||
res.n_accepted = so.accepted.data();
|
||||
res.token = so.token.data();
|
||||
res.eos = so.eos.data();
|
||||
if (!so.lp.empty()) {
|
||||
res.lp = so.lp.data();
|
||||
res.first_row = so.first_row.data();
|
||||
}
|
||||
st = sched_.commit(res);
|
||||
if (t_on) phase_mark(PH_COMMIT);
|
||||
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
|
||||
@@ -947,10 +954,70 @@ 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;
|
||||
}
|
||||
|
||||
/* One sampled row's logprobs into the step's table, which is sized on the first row that asks.
|
||||
* A ROW WHOSE LOGPROBS CANNOT BE COMPUTED FAILS ITS REQUEST, NOT THE STEP: its numbers are not
|
||||
* finite (RAD_E_INVAL), so its entry is left at token -1 (TokenLogprobs), which the scheduler
|
||||
* answers by failing that request with the reason, and every other sequence in the batch goes on.
|
||||
* A row outside the step, or one that was never staged for logprobs, is the engine's own fault. */
|
||||
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
|
||||
if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
|
||||
if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
|
||||
TokenLogprobs& lp = so.lp[(size_t)row];
|
||||
const int s = ranks_[0]->sampler.logprobs_for(row, token, &lp);
|
||||
if (s == RAD_E_INVAL) { lp = TokenLogprobs{}; return RAD_OK; }
|
||||
return s;
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
@@ -959,6 +1026,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
so.token.assign(plan.e.size(), 0);
|
||||
so.accepted.assign(plan.e.size(), 0);
|
||||
so.eos.assign(plan.e.size(), 0);
|
||||
so.lp.clear();
|
||||
if (so.n_rows <= 0) return RAD_OK;
|
||||
|
||||
so.rows.resize((size_t)so.n_rows);
|
||||
@@ -1048,6 +1116,11 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
so.accepted[i] = acc;
|
||||
so.token[i] = out[acc];
|
||||
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
|
||||
/* Each emitted token's logprobs from its own row: an accepted draft is the token the
|
||||
* target drew at its position, so its row is the distribution it came from. */
|
||||
if (e.req && e.req->sp.n_probs >= 0)
|
||||
for (int32_t j = 0; j <= acc; ++j)
|
||||
RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
|
||||
/* EVERY token that leaves, in order: the grammar's state has to advance over the
|
||||
* accepted drafts too, or the next step's mask is built n_accepted tokens behind.
|
||||
* Bounded by the truncated `acc`, so it sees exactly the tokens the client does. */
|
||||
@@ -1073,6 +1146,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
}
|
||||
so.token[i] = so.rows[(size_t)so.first_row[i]];
|
||||
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
|
||||
if (e.req && e.req->sp.n_probs >= 0)
|
||||
RAD_TRY(row_logprobs(so, so.first_row[i], so.token[i]));
|
||||
/* The grammar must see the token it just emitted, or the next step's mask is built from a
|
||||
* state one token behind the sequence. EVERY rank, not just rank 0: each rank builds the
|
||||
* mask for its own vocabulary shard from its own automaton, so a rank whose grammar did
|
||||
@@ -1493,12 +1568,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 +2234,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 +2279,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;
|
||||
@@ -2149,11 +2290,14 @@ int Engine::run_server() {
|
||||
* more choices a request; the floor keeps a small batch from refusing what it would queue. */
|
||||
o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max<int64_t>(o.max_n, cfg_.max_seqs);
|
||||
o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
o.model_path = cfg_.model;
|
||||
o.default_reasoning_effort = cfg_.reasoning_effort;
|
||||
o.reasoning_effort_map = cfg_.reasoning_effort_map;
|
||||
o.default_thinking_budget = cfg_.thinking_token_budget;
|
||||
o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
|
||||
o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value();
|
||||
/* An embedding model samples nothing, so it has no logprobs to give. */
|
||||
o.supports_logprobs = !embedding_ && ranks_[0]->sampler.has_logprobs();
|
||||
/* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request
|
||||
* against the context, so it needs one to resolve against. */
|
||||
if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens;
|
||||
@@ -2202,15 +2346,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 +2398,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 +2432,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 +2520,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.
|
||||
*
|
||||
|
||||
+14
-2
@@ -134,8 +134,7 @@ private:
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
* (engine_bringup.cpp says how auto chooses). */
|
||||
int resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
|
||||
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
|
||||
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
|
||||
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
|
||||
@@ -167,6 +166,9 @@ private:
|
||||
std::vector<int32_t> token; /* [n_seq] */
|
||||
std::vector<int32_t> accepted; /* [n_seq] */
|
||||
std::vector<uint8_t> eos; /* [n_seq] */
|
||||
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
|
||||
* empty on a step with none. */
|
||||
std::vector<TokenLogprobs> lp;
|
||||
};
|
||||
|
||||
/* The text frontend, loaded out of the container. `vocab_view_` is what the sampler's
|
||||
@@ -238,6 +240,7 @@ private:
|
||||
* wait left until after them. */
|
||||
int collect_issue(const RadBatch* b, StepOut& so);
|
||||
int collect_step(const RadBatch* b, StepOut& so);
|
||||
int row_logprobs(StepOut& so, int32_t row, int32_t token);
|
||||
/* WHERE THE STEP ENDS ON THE CARD: after its last draft pass and the copies the host reads,
|
||||
* and before the step issued ahead of it. collect_step waits for this and not for the
|
||||
* stream, so the card runs the next step while the host commits this one. */
|
||||
@@ -269,6 +272,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);
|
||||
|
||||
+152
-143
@@ -52,15 +52,17 @@ namespace rad {
|
||||
/* ================================================================== the miss report */
|
||||
/* WHAT DID NOT RESOLVE, in the three shapes the three answers want.
|
||||
*
|
||||
* A DEVICE miss WITH NO HOST KERNEL EITHER is a hole. The band exists, a request can land in it,
|
||||
* and the step that does fails at ISSUE rather than here -- declare completes either way -- so
|
||||
* every one gets a line of its own carrying the geometry and the constraint that refused it.
|
||||
* A DEVICE miss NO HOST KERNEL STANDS IN FOR is a hole (Program::device_holes has the rule). The
|
||||
* band exists and a request can land in it, so the engine refuses to start on one rather than
|
||||
* serve until the first step that does -- and every one gets a line of its own carrying the
|
||||
* geometry and the constraint that refused it.
|
||||
*
|
||||
* A DEVICE miss whose op DID resolve on the host is not a hole at all. The planner puts that op's
|
||||
* A DEVICE miss a host kernel stands in for is not a hole at all. The planner puts that op's
|
||||
* arithmetic on the host and its weights in the container's mapping, which is how `embed_lookup_q`
|
||||
* serves a table too large to copy into VRAM when no device kernel for it is loaded. Reporting
|
||||
* that as fatal produces an error nobody believes, and an error nobody believes is how a real one
|
||||
* goes unread.
|
||||
* goes unread. An op with no weights has nothing to place, so on a card its host kernel does not
|
||||
* stand in: paged attention reads a cache in VRAM, and only a device kernel can.
|
||||
*
|
||||
* A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU
|
||||
* it is the ordinary case rather than news: most ops have no host implementation and never will.
|
||||
@@ -70,7 +72,7 @@ namespace rad {
|
||||
* with thousands of lines of `E` that are all host misses, and a real device hole is invisible
|
||||
* among them. */
|
||||
struct MissReport {
|
||||
std::vector<std::string> device; /* one line each; fatal at issue */
|
||||
std::vector<std::string> device; /* one line each; the engine does not start */
|
||||
std::string host; /* one line, or empty */
|
||||
/* Device bands whose op DOES have a host kernel. Not a hole: the planner runs such an op on
|
||||
* the host and pins its weights there (Tier::Mapped), which is the whole of how a table too
|
||||
@@ -78,29 +80,43 @@ struct MissReport {
|
||||
* operator has to learn to ignore -- and an error nobody believes is how a real one goes
|
||||
* unread. */
|
||||
std::string host_only;
|
||||
/* A hole is an all-reduce instance declared on the lossy wire (`exact` 0, which the model
|
||||
* plugin derives from --tp-wire, rad_builder.h). The libraries may serve that world size on
|
||||
* the exact wire, so the refusal names the flag that asks for it. */
|
||||
bool lossy_wire = false;
|
||||
|
||||
bool operator==(const MissReport& o) const {
|
||||
return device == o.device && host == o.host && host_only == o.host_only;
|
||||
return device == o.device && host == o.host && host_only == o.host_only &&
|
||||
lossy_wire == o.lossy_wire;
|
||||
}
|
||||
};
|
||||
|
||||
static MissReport miss_report(const Program& p) {
|
||||
static MissReport miss_report(const Program& p, bool host_backend) {
|
||||
MissReport r;
|
||||
std::vector<std::string> host_ops; /* in first-seen order */
|
||||
std::map<std::string, std::string> host_spans; /* op -> "M <= 64, M in (64, 512]" */
|
||||
|
||||
/* (op, band) pairs the HOST could not serve either. A device miss that is in this set is a
|
||||
* hole; one that is not has a host kernel standing behind it. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
const std::vector<const Program::Miss*> holes = p.device_holes(host_backend);
|
||||
std::set<std::pair<int32_t, std::string>> no_host; /* (instance, band) with no host kernel */
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
|
||||
for (const Program::Miss* m : holes) {
|
||||
long long exact = 1;
|
||||
if (m->index > 0 && (size_t)m->index < p.ops.size() &&
|
||||
p.ops[(size_t)m->index].base.get_i("exact", &exact) && exact == 0)
|
||||
r.lossy_wire = true;
|
||||
r.device.push_back(m->line());
|
||||
if (!no_host.count(std::make_pair(m->index, m->span)))
|
||||
r.device.back() += " (its host kernel cannot stand in: the op has no weights for "
|
||||
"the planner to place on the host)";
|
||||
}
|
||||
|
||||
std::vector<std::string> host_only_ops;
|
||||
for (const Program::Miss& m : p.misses) {
|
||||
if (m.domain != RAD_DOMAIN_HOST) {
|
||||
if (no_host.count(std::make_pair(m.op, m.span))) r.device.push_back(m.line());
|
||||
else if (std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
|
||||
host_only_ops.end()) host_only_ops.push_back(m.op);
|
||||
if (std::find(holes.begin(), holes.end(), &m) == holes.end() &&
|
||||
std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
|
||||
host_only_ops.end()) host_only_ops.push_back(m.op);
|
||||
continue;
|
||||
}
|
||||
auto it = host_spans.find(m.op);
|
||||
@@ -234,20 +250,27 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
|
||||
}
|
||||
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
|
||||
* would send the reader after the wrong cause: the device's reason above is the answer. */
|
||||
const int64_t want = (int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024 + pinned + mapped;
|
||||
const int64_t pool = (cfg.host_pool_mib + cfg.embedding_host_mib) * 1024 * 1024;
|
||||
const int64_t want = (int64_t)cfg.tp * pool + pinned + mapped;
|
||||
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
|
||||
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
RAD_ERR("host: --host-pool-mib %lld%s is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
|
||||
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
|
||||
"raised), and %s of RAM is available. %s",
|
||||
(long long)cfg.host_pool_mib, cfg.tp,
|
||||
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
|
||||
(long long)cfg.host_pool_mib,
|
||||
cfg.embedding_host_mib
|
||||
? fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib).c_str()
|
||||
: "",
|
||||
cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(),
|
||||
humanb(pinned + mapped).c_str(), rank,
|
||||
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
|
||||
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
|
||||
"the device gave is above"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
: cfg.embedding_host_mib
|
||||
? "Lower --host-pool-mib, keep the embedding on the card with "
|
||||
"--embedding-placement vram, or raise the cap"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,7 +440,8 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
|
||||
bool Engine::ngram_gather_to_host() {
|
||||
for (auto& r : ranks_) {
|
||||
WeightFootprint f;
|
||||
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk);
|
||||
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk,
|
||||
device_is_host(), file_ != nullptr);
|
||||
if (!f.ngram_host) return false;
|
||||
}
|
||||
for (auto& r : ranks_)
|
||||
@@ -432,78 +456,79 @@ bool Engine::ngram_gather_to_host() {
|
||||
/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every
|
||||
* rank before the card is split, and written into Config for the planner and the load phase.
|
||||
*
|
||||
* THE EMBEDDING: Auto keeps it on the card -- where every other weight a step reads lives --
|
||||
* unless that leaves the split unable to hold the fixed weights, or leaves a derived KV pool
|
||||
* unable to hold one --max-model-len sequence (`kv_floor`); then the pinned host pool takes it if
|
||||
* --host-pool-mib can, the card's lookup reading it over the link in place. Disk is refused: the
|
||||
* THE EMBEDDING: Ram, the default, pins it in host memory of its own beside --host-pool-mib
|
||||
* (Config::embedding_host_mib), the card's lookup reading its M rows a step over the link in
|
||||
* place, so its VRAM goes to the KV cache and the experts. Where it cannot -- a model whose output
|
||||
* head is tied to the table reads it whole every step, and a host without the memory has nowhere
|
||||
* to pin it -- the default keeps it on the card and says why, and a named `ram` stops the server.
|
||||
* Vram keeps it on the card with every other weight a step reads. There is no third tier: the
|
||||
* lookup writes the activations a card reads, which a host kernel reading the container cannot
|
||||
* reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
|
||||
*
|
||||
* THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy,
|
||||
* pinned for that kernel to read over the link or locked for the host gather; Disk in the
|
||||
* container, read by the host gather. Each tier is refused where no kernel reads it there. Auto
|
||||
* takes the first that holds the table, in that order: the card's test is the embedding's, and
|
||||
* RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated,
|
||||
* and the memlock limit for a locked copy. */
|
||||
* takes the first that holds the table, in that order: the card's test is the fixed weights and a
|
||||
* KV pool for one --max-model-len sequence (`kv_floor`) beside it, and RAM's is lockable_room's --
|
||||
* the memory and every cgroup after the pools still to be allocated, and the memlock limit for a
|
||||
* locked copy. */
|
||||
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
|
||||
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host) {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t emb_max = 0;
|
||||
for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b);
|
||||
|
||||
TablePlacement emb = cfg_.embedding_placement;
|
||||
const bool emb_asked = cfg_.embedding_placement_given;
|
||||
std::string emb_why;
|
||||
if (emb == TablePlacement::Disk) {
|
||||
RAD_ERR("--embedding-placement disk: the token embedding's lookup writes activations the "
|
||||
"card reads, and a host kernel reading the container cannot write them -- the "
|
||||
"architecture declares that buffer on the device. Use vram, ram or auto.");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* THE HOST MEMORY THE TABLE WOULD PIN, every rank its own shard, after the pools and the prefix
|
||||
* cache's host tier still to be allocated: lockable_room's test, without the memlock limit,
|
||||
* which a pin the cards read is not charged to. */
|
||||
const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB);
|
||||
const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
|
||||
cfg_.prefix_cache_host_mib * MiB;
|
||||
std::string emb_room_why;
|
||||
auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
|
||||
if (emb_max == 0) {
|
||||
if (emb == TablePlacement::Ram) {
|
||||
if (emb == TablePlacement::Ram && emb_asked) {
|
||||
RAD_ERR("--embedding-placement ram: this model has no token embedding table that only "
|
||||
"embed_lookup reads. An output head tied to the table reads it too, and would "
|
||||
"stream it over the link every step.");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = "no table only embed_lookup reads";
|
||||
} else if (emb == TablePlacement::Auto) {
|
||||
VramBudget tb;
|
||||
const int st = vram_budget_trial(cfg_, facts, &tb);
|
||||
const bool holds = st == RAD_OK && (!tb.derived_kv || tb.kv >= kv_floor);
|
||||
const bool host = cfg_.host_pool_mib * MiB >= emb_max;
|
||||
if (holds) {
|
||||
emb_why = "no table only embed_lookup reads (an output head tied to it reads it too, "
|
||||
"whole, every step)";
|
||||
} else if (emb == TablePlacement::Ram) {
|
||||
if (!emb_room()) {
|
||||
if (emb_asked) {
|
||||
RAD_ERR("--embedding-placement ram: the token embedding (%s a rank, pinned on "
|
||||
"every rank) cannot be held in host memory: %s. Use vram.",
|
||||
humanb(emb_max).c_str(), emb_room_why.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = "the card holds it beside the other weights and a KV pool for one "
|
||||
"--max-model-len sequence";
|
||||
} else if (host) {
|
||||
emb = TablePlacement::Ram;
|
||||
emb_why = st != RAD_OK
|
||||
? "the card cannot hold the other weights with it, and the pinned host pool can"
|
||||
: fmt("with it on the card the KV pool is %s, short of the %s one --max-model-len "
|
||||
"sequence needs, and the pinned host pool can hold it",
|
||||
humanb(tb.kv).c_str(), humanb(kv_floor).c_str());
|
||||
emb_why = "the host cannot pin it: " + emb_room_why;
|
||||
} else {
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = fmt("the card is short of room for it, and --host-pool-mib %lld cannot hold "
|
||||
"%s either", (long long)cfg_.host_pool_mib, humanb(emb_max).c_str());
|
||||
emb_why = emb_asked ? "as asked"
|
||||
: "pinned in host memory and read over the link in place, so its "
|
||||
"VRAM goes to the KV cache and the experts";
|
||||
}
|
||||
} else {
|
||||
emb_why = "as asked";
|
||||
}
|
||||
cfg_.embedding_resolved = emb;
|
||||
cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0;
|
||||
|
||||
TablePlacement ng = cfg_.ngram_placement;
|
||||
std::string ng_why;
|
||||
/* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding
|
||||
* all of it (a lookup is not sharded), with the fixed weights and a KV pool for one
|
||||
* --max-model-len sequence beside it, as the embedding's test is; then a copy in RAM -- pinned
|
||||
* --max-model-len sequence beside it; then a copy in RAM -- pinned
|
||||
* for a device kernel to read over the link, or locked for the host gather; then the
|
||||
* container, which only the host gather reads. Each is open only where a kernel reads it. */
|
||||
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
|
||||
const int64_t still = (int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib) * MiB +
|
||||
cfg_.prefix_cache_host_mib * MiB;
|
||||
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
|
||||
@@ -513,10 +538,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
for (size_t i = 0; i < with.size(); ++i) {
|
||||
VramFacts& f = with[i];
|
||||
f.statics += ngram_bytes;
|
||||
if (emb == TablePlacement::Ram) {
|
||||
f.statics -= emb_max;
|
||||
f.expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
if (emb == TablePlacement::Ram) f.statics -= emb_bytes[i];
|
||||
fixed = std::max(fixed, f.statics);
|
||||
}
|
||||
/* `fixed` and not the trial's own statics: the split clamps those to what the card can give
|
||||
@@ -528,7 +550,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
* only the card, and a table that took their room would leave them nowhere. */
|
||||
const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
|
||||
tb.experts < tb.expert_floor;
|
||||
if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor))
|
||||
if (st == RAD_OK && !over && !starved && tb.kv >= kv_floor)
|
||||
return true;
|
||||
if (st != RAD_OK)
|
||||
*why = "the card cannot hold the other weights with it";
|
||||
@@ -608,8 +630,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
|
||||
if (emb_max > 0)
|
||||
RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(),
|
||||
table_placement_name(emb),
|
||||
cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str());
|
||||
table_placement_name(emb), emb_asked ? "" : " (default)", emb_why.c_str());
|
||||
if (ngram_bytes > 0)
|
||||
RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(),
|
||||
table_placement_name(ng),
|
||||
@@ -842,6 +863,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
|
||||
bc.scope = "";
|
||||
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
|
||||
bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0;
|
||||
/* A row at every token of the step and the sampler's row a sequence before them
|
||||
* (core/kld.h); the KL mode has no speculation, so a sequence samples one. */
|
||||
bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0;
|
||||
@@ -901,10 +923,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");
|
||||
@@ -939,9 +977,9 @@ int Engine::declare() {
|
||||
const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1;
|
||||
RAD_WARN("tp wire: LOSSY (--tp-wire wht6) at %lld KiB a message and above. A cross-rank "
|
||||
"all-reduce of that size carries a quantised payload instead of bf16 (libr4d's "
|
||||
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at four), so this "
|
||||
"process does not compute the same function the exact wire does. Steps of at "
|
||||
"most %lld rows are exact: single-sequence decode, and a "
|
||||
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at three and "
|
||||
"four), so this process does not compute the same function the exact wire does. "
|
||||
"Steps of at most %lld rows are exact: single-sequence decode, and a "
|
||||
"decode step until sequences x (1 + speculative depth) passes that; prefill and "
|
||||
"a busy decode step are lossy. --tp-wire-min-kb moves the floor.",
|
||||
(long long)cfg_.tp_wire_min_kb, (long long)exact_rows);
|
||||
@@ -959,7 +997,7 @@ int Engine::declare() {
|
||||
* rank whose report differs is itself worth seeing, and gets its own. */
|
||||
{
|
||||
std::vector<MissReport> rep;
|
||||
for (auto& r : ranks_) rep.push_back(miss_report(r->program));
|
||||
for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host()));
|
||||
bool same = true;
|
||||
for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false;
|
||||
|
||||
@@ -975,6 +1013,23 @@ int Engine::declare() {
|
||||
if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str());
|
||||
if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str());
|
||||
}
|
||||
/* A HOLE IS A REFUSAL HERE, not an error the first request finds. Every band is one a
|
||||
* request can land in -- the bands are cut from the limits this run was started with --
|
||||
* and the step that lands in one fails at issue and takes the engine down with it. A
|
||||
* kernel library that serves the op (--kernels), or a model whose geometry the installed
|
||||
* one covers, is the remedy; serving until then is not. --debug-graph serves nothing, so
|
||||
* it goes on to print the graph the holes are in, and its exit status says they are there
|
||||
* (Engine::dump). */
|
||||
for (const MissReport& m : rep)
|
||||
if (!m.device.empty() && !cfg_.debug_graph) {
|
||||
if (m.lossy_wire)
|
||||
RAD_ERR("the band(s) above include the lossy wire --tp-wire wht6 asks for, "
|
||||
"which the loaded kernel libraries do not implement at --tp %d; "
|
||||
"--tp-wire exact asks for the exact one", cfg_.tp);
|
||||
RAD_ERR("not starting: the kernel libraries loaded have no kernel for the device "
|
||||
"band(s) above, and this model needs them");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* A CHECKPOINT WEIGHT THAT IS NOT SERVED AS IT STANDS was declared as plain and nothing can
|
||||
* load it: every one is named, with the remedy, whatever declare made of the rest. */
|
||||
@@ -1181,11 +1236,10 @@ int Engine::plan() {
|
||||
* already this card's even share of the static weights: declare ran once per rank
|
||||
* with every dimension divided. */
|
||||
WeightFootprint wf;
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk);
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk,
|
||||
device_is_host(), file_ != nullptr);
|
||||
f.statics = wf.statics;
|
||||
f.experts = wf.experts;
|
||||
/* The expert floor waits for the tables' placement: the embedding may take its share
|
||||
* of the host pool first. */
|
||||
wfs.push_back(wf);
|
||||
/* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
|
||||
f.lends = VMem::supported() && !cfg_.deterministic &&
|
||||
@@ -1196,8 +1250,8 @@ int Engine::plan() {
|
||||
ngram_host = ngram_host || wf.ngram_host;
|
||||
/* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single
|
||||
* sequence, which is the least a KV pool can hold and still serve every request the
|
||||
* API accepts (configure_kv warns below it). --embedding-placement auto keeps the
|
||||
* table off the card only to stay above it. */
|
||||
* API accepts (configure_kv warns below it). --ngram-placement auto puts the table
|
||||
* on the card only where the pool stays above it. */
|
||||
{
|
||||
Config one = cfg_;
|
||||
one.max_seqs = 1;
|
||||
@@ -1253,28 +1307,22 @@ int Engine::plan() {
|
||||
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
|
||||
facts.push_back(f);
|
||||
}
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it
|
||||
* before any expert: the embedding when it is placed there, and the file tier's staging.
|
||||
* Both floors are known before the tables are placed, so placing them can ask whether the
|
||||
* experts would still have a tier. */
|
||||
std::vector<int64_t> floor_emb_ram(facts.size(), 0);
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less the file tier's staging, which
|
||||
* Planner::plan takes out of it before any expert. The embedding placed in host memory
|
||||
* brings its own room (Config::embedding_host_mib), so it leaves this floor as it is. */
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
|
||||
floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max<int64_t>(room - emb_bytes[i], 0));
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host));
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
|
||||
ngram_host));
|
||||
/* The n-gram table was counted off the card; on it, it is every rank's whole table. */
|
||||
if (cfg_.ngram_resolved == TablePlacement::Vram)
|
||||
for (VramFacts& f : facts) f.statics += ngram_bytes;
|
||||
if (cfg_.embedding_resolved == TablePlacement::Ram)
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
facts[i].statics -= emb_bytes[i];
|
||||
facts[i].expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
|
||||
VramBudget vb;
|
||||
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
|
||||
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
|
||||
@@ -1300,8 +1348,7 @@ int Engine::plan() {
|
||||
* 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
|
||||
* Only a split under expert_tiered is re-split: 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
|
||||
@@ -1324,8 +1371,6 @@ int Engine::plan() {
|
||||
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());
|
||||
@@ -1425,6 +1470,7 @@ int Engine::plan() {
|
||||
in.n_profile = (int64_t)file_->header().prof_count;
|
||||
}
|
||||
in.container = file_ != nullptr;
|
||||
in.host_backend = device_is_host();
|
||||
Planner planner(in);
|
||||
s = planner.plan(&r->plan);
|
||||
if (cfg_.debug_placement || s < 0)
|
||||
@@ -2312,7 +2358,7 @@ int Engine::load_weights() {
|
||||
* past the end of the weights pool is a write to device memory the process does not own,
|
||||
* and on this driver that does not fault -- the copy is accepted, never completes, and
|
||||
* the host thread spins inside the runtime with the copy engine idle and no I/O. It looks
|
||||
* exactly like a hang, and it moves with --vram-weights-mib because a bigger pool is a
|
||||
* exactly like a hang, and it moves with the weights pool's size because a bigger pool is a
|
||||
* later overrun. Cheap enough to check on every copy, and checked before any of them
|
||||
* start rather than as each one is issued. */
|
||||
const uint8_t* wp_lo = (const uint8_t*)r->pools.weights().base();
|
||||
@@ -3200,6 +3246,7 @@ int Engine::start() {
|
||||
/* The cards are chosen, so a kernel library's device code is checked against the ones the
|
||||
* ranks will run on and not against whichever device the backend happens to list first. */
|
||||
rad_tools_registry().set_code_device(devs[0]);
|
||||
rad_tools_registry().set_no_device_code(device_is_host());
|
||||
RAD_TRY(load_plugins());
|
||||
|
||||
ranks_.clear();
|
||||
@@ -3336,32 +3383,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 ----------------
|
||||
*
|
||||
@@ -3579,34 +3600,27 @@ int Engine::start() {
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
|
||||
humanb(room).c_str());
|
||||
} else if (got > want + 256 * MiB) {
|
||||
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
|
||||
* made the split, what is left is left because neither pool could address another
|
||||
* 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. 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. */
|
||||
/* "TOO MUCH" IS NOT A FAULT: the resolver made the split, and what is left is left
|
||||
* because neither pool could address another 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. 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)
|
||||
if (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)
|
||||
else
|
||||
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.",
|
||||
r->device, humanb(got).c_str(), asked.c_str());
|
||||
else
|
||||
RAD_WARN("card %d settled at %s free against %s, so %s is unused. On a model that "
|
||||
"does not fit in VRAM every unused GiB is weight that has to be moved "
|
||||
"instead of read, and that is decode step time.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(got - want).c_str());
|
||||
} else
|
||||
RAD_INFO("card %d settled at %s free, against %s",
|
||||
r->device, humanb(got).c_str(), asked.c_str());
|
||||
@@ -3623,17 +3637,12 @@ int Engine::dump() {
|
||||
Program& p = ranks_[0]->program;
|
||||
fputs(dump_graph_str(p, nullptr).c_str(), stdout);
|
||||
if (cfg_.debug_selection) fputs(rad_tools_registry().selection_table().c_str(), stdout);
|
||||
/* A HOST miss is not a failure -- see miss_report(). The exit code answers "is there a
|
||||
* hole a request can fall into", and a host miss is not one. NOR IS A DEVICE MISS WHOSE OP
|
||||
* HAS A HOST KERNEL: the planner places that op on the host and pins its weights in the
|
||||
* container's mapping, which is how a table too large to copy into VRAM is served at all. A
|
||||
* hole is a band NEITHER domain resolved. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span)))
|
||||
return RAD_E_NOKERNEL;
|
||||
/* The exit code answers "is there a hole a request can fall into", by the rule declare()
|
||||
* refuses to serve on (Program::device_holes, miss_report()): a device band no kernel
|
||||
* resolved, unless a host kernel stands in for an op whose weights the planner can place on
|
||||
* the host. A host miss is not one. */
|
||||
for (auto& r : ranks_)
|
||||
if (!r->program.device_holes(device_is_host()).empty()) return RAD_E_NOKERNEL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+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) {
|
||||
|
||||
@@ -114,9 +114,10 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
|
||||
* WHY THAT IS ENOUGH FOR A KL DIVERGENCE, with no log-sum-exp anywhere. Renormalised over a
|
||||
* fixed candidate set S, p~_i = exp(l_i) / sum_{j in S} exp(l_j) -- the partition function
|
||||
* over the WHOLE vocabulary cancels, in both engines independently. So a top-K KLD against
|
||||
* another engine's top-K logprobs needs only these logits. An OpenAI `logprobs` FIELD would
|
||||
* need the normaliser, and `supports_logprobs` is false; this is a probe, and it says so by
|
||||
* being an environment variable at -vv rather than a response field. */
|
||||
* another engine's top-K logprobs needs only these logits. The OpenAI `logprobs` field carries
|
||||
* the normaliser (sample_logprobs) and only the RAW distribution's top 20; this reads the
|
||||
* plane the pick drew from, which is a probe, and it says so by being an environment variable
|
||||
* at -vv rather than a response field. */
|
||||
static const int head = [] {
|
||||
const char* s = std::getenv("RADIANCE_DUMP_HEAD");
|
||||
const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
|
||||
@@ -156,8 +157,8 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
|
||||
* writing different code -- so the question a LOSSY LEVER asks ("how much worse, if at all")
|
||||
* needs an instrument of its own.
|
||||
*
|
||||
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server returns no logprobs (`supports_logprobs` is
|
||||
* never set, so it refuses them) and a served prefill produces logits only at the rows
|
||||
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server's logprobs are the generated positions'
|
||||
* only -- never the prompt's -- and a served prefill produces logits only at the rows
|
||||
* `out_ids` names; the teacher-forced scoring pass is the KL mode's (core/kld.h), which runs in
|
||||
* place of the server. What a serving engine offers: send N distinct prompts at max_tokens = 1,
|
||||
* and every build under comparison sees IDENTICAL inputs at one row each. The top of that row,
|
||||
|
||||
+60
-25
@@ -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;
|
||||
@@ -258,18 +264,23 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
* 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
|
||||
* rather than by a flag. */
|
||||
if (const char* qm = gs("quantization_config.quant_method")) {
|
||||
out->quant = qm;
|
||||
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
|
||||
}
|
||||
|
||||
out->quant = quant_descriptor(*out);
|
||||
out->finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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
|
||||
* rather than by a flag. */
|
||||
std::string quant_descriptor(const MetaOwn& m) {
|
||||
std::string q;
|
||||
if (const char* qm = m.get("quantization_config.quant_method")) {
|
||||
q = qm;
|
||||
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
if (!g.get_str("general.architecture", &out->arch)) {
|
||||
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
|
||||
@@ -408,10 +419,24 @@ int Checkpoint::open_gguf(const std::string& path) {
|
||||
return meta_from_gguf(gguf_, &meta_);
|
||||
}
|
||||
|
||||
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
|
||||
const std::unordered_map<std::string, std::string>* owner) {
|
||||
shards_.push_back(std::make_unique<SafeTensorsFile>());
|
||||
RAD_TRY(shards_.back()->open(p));
|
||||
const std::string file = p.substr(p.find_last_of('/') + 1);
|
||||
for (const auto& t : shards_.back()->tensors()) {
|
||||
/* THE INDEX SAYS WHICH SHARD A TENSOR IS READ FROM. A directory that merges two
|
||||
* checkpoints -- a finetune's changed tensors in its own shards beside links to the base
|
||||
* model's -- holds some names in two shards, and only the index tells the copies apart. */
|
||||
if (owner) {
|
||||
auto it = owner->find(t.name);
|
||||
if (it != owner->end() && it->second != file) continue;
|
||||
}
|
||||
if (index_.count(prefix + t.name)) {
|
||||
RAD_ERR("%s: '%s' is also in %s, and no index entry says which copy to read", p.c_str(),
|
||||
t.name.c_str(), shards_[index_shard_[prefix + t.name]]->path().c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (t.dtype == RAD_DT_INVALID) {
|
||||
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
|
||||
t.name.c_str(), t.dtype_str.c_str());
|
||||
@@ -423,6 +448,7 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
s.shape = t.shape; /* safetensors is already row-major */
|
||||
s.data = t.data;
|
||||
s.bytes = (int64_t)t.bytes;
|
||||
index_shard_.emplace(s.name, shards_.size() - 1);
|
||||
index_.emplace(s.name, tensors_.size());
|
||||
tensors_.push_back(std::move(s));
|
||||
}
|
||||
@@ -431,13 +457,13 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
|
||||
namespace {
|
||||
|
||||
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
|
||||
/* Every shard an index names, once each and in name order, or the one model.safetensors; `map`
|
||||
* is the index's weight_map, empty without one. */
|
||||
int shard_list(const std::string& dir, const std::string& index, bool index_given,
|
||||
std::vector<std::string>* out) {
|
||||
std::unordered_map<std::string, std::string> map;
|
||||
const int s = st_load_index(index, &map);
|
||||
std::vector<std::string>* out, std::unordered_map<std::string, std::string>* map) {
|
||||
const int s = st_load_index(index, map);
|
||||
if (s == RAD_OK) {
|
||||
for (auto& [t, f] : map)
|
||||
for (auto& [t, f] : *map)
|
||||
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
|
||||
std::sort(out->begin(), out->end());
|
||||
for (auto& f : *out) f = dir + "/" + f;
|
||||
@@ -454,6 +480,7 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
kind_ = SafeT;
|
||||
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
|
||||
std::vector<std::string> shards;
|
||||
std::unordered_map<std::string, std::string> owner;
|
||||
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
|
||||
const bool is_file = path.size() > 12 &&
|
||||
path.compare(path.size() - 12, 12, ".safetensors") == 0;
|
||||
@@ -461,9 +488,9 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
shards.push_back(path);
|
||||
} else {
|
||||
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
|
||||
is_index, &shards));
|
||||
is_index, &shards, &owner));
|
||||
}
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
|
||||
|
||||
RAD_TRY(meta_from_config_json(dir_, &meta_));
|
||||
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
|
||||
@@ -663,8 +690,9 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
|
||||
? prefix
|
||||
: prefix.substr(0, prefix.size() - 1), &meta_));
|
||||
std::vector<std::string> shards;
|
||||
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
|
||||
std::unordered_map<std::string, std::string> owner;
|
||||
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -823,23 +851,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);
|
||||
|
||||
|
||||
@@ -84,6 +84,8 @@ struct MetaOwn {
|
||||
};
|
||||
|
||||
int meta_from_config_json(const std::string& dir, MetaOwn* out);
|
||||
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
|
||||
std::string quant_descriptor(const MetaOwn& m);
|
||||
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
|
||||
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
|
||||
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
|
||||
@@ -142,7 +144,10 @@ public:
|
||||
std::string* why);
|
||||
|
||||
private:
|
||||
int add_shard(const std::string& p, const std::string& prefix = "");
|
||||
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
|
||||
* another shard is not read from this one. */
|
||||
int add_shard(const std::string& p, const std::string& prefix = "",
|
||||
const std::unordered_map<std::string, std::string>* owner = nullptr);
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
@@ -154,6 +159,7 @@ private:
|
||||
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
|
||||
std::vector<SrcTensor> tensors_;
|
||||
std::unordered_map<std::string, size_t> index_;
|
||||
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
|
||||
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* hf_model.cpp -- resolve a --model that is a Hugging Face repo id (hf_model.h).
|
||||
*
|
||||
* The entry point (main.cpp) calls resolve_hf_model() once, between config_parse and the Engine,
|
||||
* and the rest of bring-up sees a plain file or directory. The fetching is scripts/hfget.sh (curl
|
||||
* and jq, no Python), run as a child process; it is installed to libexec/radiance/ and the build
|
||||
* copies it to the same place under the build tree, so it is found beside the binary either way.
|
||||
*
|
||||
* WHERE IT GOES. Not under $RADIANCE_HOME: that is a ':'-separated search path for plugins, and
|
||||
* its default is the install's share/ directory, which a user cannot write. A model is a cache --
|
||||
* the XDG cache directory by default, --download-dir (vLLM's name) to put it on another disk.
|
||||
*
|
||||
* A HUB THAT CANNOT BE REACHED DOES NOT STOP A RESTART. hfget.sh exits 3 when it changed nothing
|
||||
* on disk (the listing failed, or an update does not fit), and the copy a complete fetch left --
|
||||
* marked by the manifest it writes only on success -- is then served with a warning. Any other
|
||||
* failure may have left a file half-transferred, so it is not served. */
|
||||
#include "hf_model.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
bool repo_part(const std::string& p) {
|
||||
if (p.empty() || p.front() == '.' || p.front() == '-') return false;
|
||||
for (char ch : p) {
|
||||
const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') || ch == '.' || ch == '_' || ch == '-';
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* suf) {
|
||||
const size_t n = std::strlen(suf);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
|
||||
}
|
||||
|
||||
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
|
||||
* copies it. */
|
||||
std::string hfget_path() {
|
||||
char buf[4096];
|
||||
const ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
|
||||
if (n <= 0) return std::string();
|
||||
buf[n] = '\0';
|
||||
const fs::path p = fs::path(buf).parent_path() / ".." / "libexec" / "radiance" / "hfget.sh";
|
||||
std::error_code ec;
|
||||
return fs::is_regular_file(p, ec) ? p.lexically_normal().string() : std::string();
|
||||
}
|
||||
|
||||
/* The script's exit status, or -1 when it could not be run. */
|
||||
int run_hfget(const std::string& script, const std::string& repo, const std::string& dest) {
|
||||
const pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
RAD_ERR("hfget: fork: %s", std::strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pid == 0) {
|
||||
const char* argv[] = { "sh", script.c_str(), repo.c_str(), dest.c_str(), nullptr };
|
||||
execv("/bin/sh", const_cast<char* const*>(argv));
|
||||
std::fprintf(stderr, "hfget: /bin/sh: %s\n", std::strerror(errno));
|
||||
_exit(127);
|
||||
}
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, 0) < 0)
|
||||
if (errno != EINTR) return -1;
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool hf_repo_id(const std::string& s) {
|
||||
std::error_code ec;
|
||||
if (s.empty() || fs::exists(s, ec)) return false;
|
||||
const size_t slash = s.find('/');
|
||||
if (slash == std::string::npos || s.find('/', slash + 1) != std::string::npos) return false;
|
||||
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
|
||||
if (!repo_part(owner) || !repo_part(name)) return false;
|
||||
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
|
||||
if (ends_with(name, suf)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hf_default_download_dir() {
|
||||
if (const char* x = std::getenv("XDG_CACHE_HOME"); x && *x)
|
||||
return std::string(x) + "/radiance/hf";
|
||||
if (const char* h = std::getenv("HOME"); h && *h)
|
||||
return std::string(h) + "/.cache/radiance/hf";
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string hf_served_path(const std::string& dir, std::string* why) {
|
||||
std::vector<std::string> rad;
|
||||
std::error_code ec;
|
||||
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
|
||||
std::error_code fe;
|
||||
if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad"))
|
||||
rad.push_back(e.path().filename().string());
|
||||
}
|
||||
if (ec) {
|
||||
*why = dir + ": " + ec.message();
|
||||
return std::string();
|
||||
}
|
||||
if (rad.empty()) return dir;
|
||||
if (rad.size() == 1) return dir + "/" + rad[0];
|
||||
std::string names;
|
||||
for (size_t i = 0; i < rad.size(); ++i) names += (i ? ", " : "") + rad[i];
|
||||
*why = dir + " holds " + std::to_string(rad.size()) + " containers (" + names +
|
||||
"); pass the one to serve as --model " + dir + "/<file>";
|
||||
return std::string();
|
||||
}
|
||||
|
||||
bool resolve_hf_model(Config& c) {
|
||||
if (!hf_repo_id(c.model)) return true;
|
||||
const std::string repo = c.model;
|
||||
const std::string root = c.download_dir.empty() ? hf_default_download_dir() : c.download_dir;
|
||||
if (root.empty()) {
|
||||
RAD_ERR("--model %s: no download directory -- neither XDG_CACHE_HOME nor HOME is set; "
|
||||
"name one with --download-dir", repo.c_str());
|
||||
return false;
|
||||
}
|
||||
const std::string dest = root + "/" + repo;
|
||||
std::error_code ec;
|
||||
const bool cached = fs::is_regular_file(dest + "/.hfget-manifest", ec);
|
||||
|
||||
const std::string script = hfget_path();
|
||||
if (script.empty()) {
|
||||
RAD_ERR("--model %s: not a path here, and hfget.sh, which fetches a Hugging Face repo, is "
|
||||
"not installed beside this binary (libexec/radiance/)", repo.c_str());
|
||||
return false;
|
||||
}
|
||||
RAD_INFO("model: %s is not a path here; fetching it as a Hugging Face repo into %s",
|
||||
repo.c_str(), dest.c_str());
|
||||
const int rc = run_hfget(script, repo, dest);
|
||||
if (rc != 0) {
|
||||
if (rc == 3 && cached) {
|
||||
RAD_WARN("model: %s could not be checked for changes (hfget.sh, above); serving the "
|
||||
"copy fetched before", repo.c_str());
|
||||
} else {
|
||||
RAD_ERR("--model %s: not a path here, and fetching it as a Hugging Face repo failed "
|
||||
"(hfget.sh exit %d, above)", repo.c_str(), rc);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::string why;
|
||||
const std::string path = hf_served_path(dest, &why);
|
||||
if (path.empty()) {
|
||||
RAD_ERR("--model %s: %s", repo.c_str(), why.c_str());
|
||||
return false;
|
||||
}
|
||||
c.model = path;
|
||||
RAD_INFO("model: serving %s", c.model.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,33 @@
|
||||
/* hf_model.h -- a --model that names a Hugging Face repo instead of a local path.
|
||||
*
|
||||
* `radiance --model StillDeadcode/minicpm5-2b-fp8` fetches the repo with scripts/hfget.sh into
|
||||
* the download directory and serves what it fetched: the one container at the repo's top level,
|
||||
* or the directory as a checkpoint when it holds none. Every start re-checks the hub, so a
|
||||
* changed file is fetched again before bring-up; a start that cannot reach the hub serves the
|
||||
* copy a complete earlier fetch left. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Is `s` a repo id ("owner/name") rather than a path? A path that exists always wins. A repo id is
|
||||
* exactly two non-empty parts of [A-Za-z0-9._-], neither starting with '.' or '-', and a name that
|
||||
* does not end like a model file (.rad, .safetensors, .gguf, .json): a missing local file should
|
||||
* be reported as missing, not looked up on the hub. */
|
||||
bool hf_repo_id(const std::string& s);
|
||||
|
||||
/* $XDG_CACHE_HOME/radiance/hf, else $HOME/.cache/radiance/hf; empty if neither is set. */
|
||||
std::string hf_default_download_dir();
|
||||
|
||||
/* What to serve from a fetched repo directory: its one top-level .rad, or the directory itself (a
|
||||
* checkpoint) when it holds none. Several containers are ambiguous: empty, and *why names them. */
|
||||
std::string hf_served_path(const std::string& dir, std::string* why);
|
||||
|
||||
/* If c.model is a repo id, fetch it and point c.model at what to serve. False after an error has
|
||||
* been logged. */
|
||||
bool resolve_hf_model(Config& c);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -2,6 +2,7 @@
|
||||
* a command line into that sequence and a status into an exit code.
|
||||
*/
|
||||
#include "engine.h"
|
||||
#include "hf_model.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
rad::Config cfg;
|
||||
@@ -9,6 +10,8 @@ int main(int argc, char** argv) {
|
||||
if (s == 1) { rad::config_usage(argv[0]); return 0; }
|
||||
if (s < 0) { rad::config_usage(argv[0]); return 2; }
|
||||
|
||||
if (!rad::resolve_hf_model(cfg)) return 1; /* a repo id: fetched, and --model points at it */
|
||||
|
||||
rad::Engine engine(std::move(cfg));
|
||||
|
||||
s = engine.start();
|
||||
|
||||
+7
-7
@@ -424,8 +424,7 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
}
|
||||
|
||||
int KVManager::carve_into(Pool& kv_pool) {
|
||||
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
|
||||
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
/* The pool is what the resolver derived; nothing here re-decides it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
const int64_t budget_bytes = kv_pool.avail();
|
||||
const int64_t fixed = fixed_;
|
||||
pool_base_ = kv_pool.base();
|
||||
@@ -434,10 +433,11 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
if (fixed >= budget_bytes) {
|
||||
RAD_ERR("vram_kv does not fit its fixed costs:\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" --vram-kv-mib %10s\n"
|
||||
" vram_kv %10s\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
|
||||
"for you (spec §6).",
|
||||
"Lower --max-num-seqs, or give the cache more of the card: a smaller "
|
||||
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
|
||||
"them for you (spec §6).",
|
||||
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -459,8 +459,8 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
}
|
||||
if (p.n_blocks <= 0) {
|
||||
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
|
||||
"--max-seqs.",
|
||||
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or "
|
||||
"lower --max-num-seqs.",
|
||||
p.name.c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
|
||||
+3
-3
@@ -156,8 +156,8 @@ public:
|
||||
* exhaust at the same total token count, and any other split strands memory in whichever
|
||||
* group outlasts the others.
|
||||
*
|
||||
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
|
||||
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
|
||||
* The byte budget is the budget resolver's and is not re-derived here: it is whatever
|
||||
* `kv_pool` still has (vram_kv). The linear-state snapshots take none of it -- they live
|
||||
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
|
||||
* else (spec §6, §7.3). */
|
||||
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
|
||||
@@ -165,7 +165,7 @@ public:
|
||||
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
|
||||
* from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
|
||||
* says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
|
||||
* allocated before carve() runs, so a derived --vram-kv-mib has to be decided from these two
|
||||
* allocated before carve() runs, so the KV pool has to be decided from these two
|
||||
* and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
|
||||
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
|
||||
int64_t ceiling(int64_t ctx) const;
|
||||
|
||||
+12
-2
@@ -988,7 +988,7 @@ static bool chain_extends(const std::vector<BlockHash>& shorter,
|
||||
}
|
||||
|
||||
void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns) {
|
||||
uint64_t now_ns, const std::string& label) {
|
||||
if (chain.empty()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
|
||||
@@ -1008,6 +1008,9 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
* to say which of them republished. So the most recent of them is touched and no row is
|
||||
* added, which is the one answer that is wrong about nothing. */
|
||||
uint64_t first_seen = 0;
|
||||
/* A conversation's label outlives the turn that sent it: a later turn without one keeps the
|
||||
* name an earlier one gave. */
|
||||
std::string kept_label = label;
|
||||
bool absorbed = false;
|
||||
std::vector<uint64_t>& at_root = roots_[chain[0]];
|
||||
for (size_t i = 0; i < at_root.size();) {
|
||||
@@ -1016,6 +1019,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
if (!chain_extends(it->second.chain, chain)) { ++i; continue; }
|
||||
if (first_seen == 0 || it->second.first_seen_ns < first_seen)
|
||||
first_seen = it->second.first_seen_ns;
|
||||
if (kept_label.empty()) kept_label = it->second.label;
|
||||
sessions_.erase(it);
|
||||
at_root.erase(at_root.begin() + (long)i);
|
||||
absorbed = true;
|
||||
@@ -1028,7 +1032,11 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
if (it == sessions_.end() || !chain_extends(chain, it->second.chain)) continue;
|
||||
if (!newest || it->second.last_used_ns > newest->last_used_ns) newest = &it->second;
|
||||
}
|
||||
if (newest) { newest->last_used_ns = now_ns; return; }
|
||||
if (newest) {
|
||||
newest->last_used_ns = now_ns;
|
||||
if (!label.empty()) newest->label = label;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Session& s = sessions_[id];
|
||||
@@ -1036,6 +1044,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
s.n_tokens = n_tokens;
|
||||
s.first_seen_ns = first_seen ? first_seen : now_ns;
|
||||
s.chain = chain;
|
||||
s.label = std::move(kept_label);
|
||||
at_root.push_back(id);
|
||||
}
|
||||
|
||||
@@ -1079,6 +1088,7 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
si.model = model_;
|
||||
si.n_tokens = kv.second.n_tokens;
|
||||
si.first_seen_ns = kv.second.first_seen_ns;
|
||||
si.label = kv.second.label;
|
||||
si.last_used_ns = kv.second.last_used_ns;
|
||||
si.bytes = (int64_t)kv.second.chain.size() * cfg_.entry_bytes;
|
||||
out.push_back(std::move(si));
|
||||
|
||||
+3
-1
@@ -383,6 +383,7 @@ public:
|
||||
struct SessionInfo {
|
||||
uint64_t id = 0;
|
||||
std::string model;
|
||||
std::string label; /* the client's own name for the conversation, or "" */
|
||||
int64_t n_tokens = 0;
|
||||
int64_t bytes = 0;
|
||||
uint64_t first_seen_ns = 0;
|
||||
@@ -426,7 +427,7 @@ public:
|
||||
* is a row per turn -- a table nobody can read, holding a copy of every prefix of the
|
||||
* transcript for as long as the newest. */
|
||||
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns);
|
||||
uint64_t now_ns, const std::string& label = std::string());
|
||||
void set_model(const std::string& m) { model_ = m; }
|
||||
/* Newest activity first. Recomputes each session's tier histogram from the records, so it is
|
||||
* a view and never a second copy of the truth. The walk takes the lock in slices and lets
|
||||
@@ -545,6 +546,7 @@ private:
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
std::vector<BlockHash> chain;
|
||||
std::string label;
|
||||
};
|
||||
|
||||
/* Erase one row and its root index entry together. */
|
||||
|
||||
+11
-37
@@ -199,22 +199,20 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t w = cfg.vram_weights_mib * MiB;
|
||||
const int64_t kv = cfg.vram_kv_mib * MiB;
|
||||
const int64_t hp = cfg.host_pool_mib * MiB;
|
||||
const int64_t hp = (cfg.host_pool_mib + cfg.embedding_host_mib) * MiB;
|
||||
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the
|
||||
* operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured
|
||||
* driver residency and the computed arena -- and either way they arrive here as two numbers
|
||||
* with a report behind them. Either way this component refuses rather than shrinking
|
||||
* anything: an engine that quietly re-optimises a split is an engine whose
|
||||
* benchmarks do not reproduce (spec §6). A zero here means the resolver was never called,
|
||||
* which is a wiring bug and gets named as one. */
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
|
||||
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
|
||||
* computed arena, and they arrive here as two numbers with a report behind them. This
|
||||
* component refuses rather than shrinking anything: an engine that quietly re-optimises a
|
||||
* split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
|
||||
* resolver was never called, which is a wiring bug and gets named as one. */
|
||||
std::string missing;
|
||||
if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n";
|
||||
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
|
||||
if (!missing.empty()) {
|
||||
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
|
||||
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
|
||||
+ missing;
|
||||
fit_report_ = "VRAM pool budgets are empty: the budget resolver (core/mem/vram_budget.cpp) "
|
||||
"did not run before the pools were configured:\n" + missing;
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -230,8 +228,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
|
||||
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
|
||||
"The resolved split is larger than the card, which the resolver does not produce: a "
|
||||
"wiring bug (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(),
|
||||
humanb(want - vram_capacity).c_str());
|
||||
@@ -239,30 +237,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there
|
||||
* should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is
|
||||
* not the sum of the budgets. What is left over here is the driver's residency, the activation
|
||||
* arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's
|
||||
* report breaks that down term by term. A budget a couple of GiB under the card is that much
|
||||
* of the expert plane streaming from host memory instead, which costs real prefill throughput
|
||||
* on a model whose experts do not fit.
|
||||
*
|
||||
* THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a
|
||||
* small dense model whose cache is already at the largest context it can address leaves many
|
||||
* GiB that NOTHING can spend, and warning there would tell the operator to leave unset the
|
||||
* very flags they already left unset. Where the resolver made the split it has already printed
|
||||
* every term including the unusable one, and there is nothing to add. */
|
||||
if (vram_capacity > 0 && !cfg.vram_budget_derived) {
|
||||
const int64_t slack = vram_capacity - want;
|
||||
if (slack >= 1024 * MiB)
|
||||
RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor "
|
||||
"accounted. The driver's context, the activation arena and "
|
||||
"--gpu-headroom-mib come out of it; anything past those is throughput on the "
|
||||
"floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split "
|
||||
"automatically.",
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str());
|
||||
}
|
||||
|
||||
int st = RAD_OK;
|
||||
int s;
|
||||
/* Order matters only for the diagnostic: allocate the two big ones first so a failure names
|
||||
|
||||
+2
-2
@@ -342,7 +342,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) {
|
||||
int64_t n_tokens, const std::string& label) {
|
||||
if (!enabled_) return RAD_OK;
|
||||
if (blocks.size() != groups_.size()) return RAD_E_INVAL;
|
||||
if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL;
|
||||
@@ -427,7 +427,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
if (it == map_.end()) continue;
|
||||
tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
|
||||
}
|
||||
tiers_->note_session(session, hs, n_tokens, now);
|
||||
tiers_->note_session(session, hs, n_tokens, now, label);
|
||||
}
|
||||
|
||||
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
|
||||
|
||||
+2
-1
@@ -206,7 +206,8 @@ public:
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens);
|
||||
int64_t n_tokens,
|
||||
const std::string& label = std::string());
|
||||
|
||||
/* Drop the least recently used entries, releasing their KV references. Returns how many were
|
||||
* dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
|
||||
|
||||
+45
-68
@@ -82,11 +82,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
const bool shared = host_reserve > b.headroom;
|
||||
if (shared) b.headroom = host_reserve;
|
||||
|
||||
/* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve
|
||||
* and inventing a capacity would be exactly the inference §6 forbids. */
|
||||
/* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
|
||||
* exactly the inference §6 forbids. What each pool needs is still known: the weights pool
|
||||
* holds what the planner would copy out of the container -- the statics and experts
|
||||
* weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
|
||||
* (The host backend reports half the machine's memory and is split like a card.) */
|
||||
if (b.capacity <= 0) {
|
||||
b.weights = cfg.vram_weights_mib * kMiB;
|
||||
b.kv = cfg.vram_kv_mib * kMiB;
|
||||
b.weights = std::max<int64_t>(b.statics + b.expert_ceiling, kMiB);
|
||||
b.kv = std::max<int64_t>(b.kv_ceiling, kMiB);
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
cfg.vram_kv_mib = to_mib_up(b.kv);
|
||||
if (log)
|
||||
b.report = fmt("the device reports no capacity: weights pool %s (what the planner "
|
||||
"copies out of the container), cache %s (every sequence at the full "
|
||||
"context)", humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -98,17 +108,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* plugin's init has run and its code object is resident. */
|
||||
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
|
||||
|
||||
const bool want_w = cfg.vram_weights_mib <= 0;
|
||||
const bool want_kv = cfg.vram_kv_mib <= 0;
|
||||
b.derived_weights = want_w;
|
||||
b.derived_kv = want_kv;
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
|
||||
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
|
||||
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
|
||||
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
|
||||
b.claimable = b.capacity - fixed;
|
||||
b.drift = kDriverDrift;
|
||||
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
|
||||
b.queues);
|
||||
|
||||
if (b.claimable < 0) {
|
||||
b.report = fmt(
|
||||
@@ -120,7 +123,6 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" activation arena %10s (buffer plan + kernel scratch)\n"
|
||||
" step staging %10s (block tables, media and KV tier staging)\n"
|
||||
" hardware queues %10s (%d at %s each, measured)\n"
|
||||
"%s%s"
|
||||
" ------------------------------\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
@@ -128,42 +130,31 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
|
||||
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
|
||||
humanb(-b.claimable).c_str());
|
||||
if (log) RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB;
|
||||
b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB;
|
||||
|
||||
/* ---- the static weights come off the top ------------------------------------------------
|
||||
*
|
||||
* They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator
|
||||
* who stated --vram-weights-mib has already decided what the weights get, and second-guessing
|
||||
* that is the re-optimisation §6 forbids. */
|
||||
if (want_w) {
|
||||
b.statics = std::min(b.statics, b.claimable);
|
||||
if (b.statics >= b.claimable && b.claimable > 0) {
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
}
|
||||
* They are a floor and not a share. */
|
||||
b.statics = std::min(b.statics, b.claimable);
|
||||
if (b.statics >= b.claimable && b.claimable > 0) {
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
}
|
||||
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
|
||||
b.elastic = b.claimable - b.statics;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is divided --------------------------------------------------- */
|
||||
if (want_w && want_kv) {
|
||||
{
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
|
||||
* zero, which weight_footprint always measures. */
|
||||
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
|
||||
@@ -198,20 +189,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.kv = kv;
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
|
||||
} else if (want_kv) {
|
||||
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
|
||||
b.unusable = b.claimable - b.kv;
|
||||
} else if (want_w) {
|
||||
/* The KV pool was stated, so `claimable` is already net of it; the weights take the rest,
|
||||
* still capped at what the model has to put there. */
|
||||
int64_t exp = b.elastic;
|
||||
if (exp > b.expert_ceiling) {
|
||||
b.unusable = exp - b.expert_ceiling;
|
||||
exp = b.expert_ceiling;
|
||||
}
|
||||
b.experts = exp;
|
||||
b.weights = b.statics + exp;
|
||||
}
|
||||
/* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
|
||||
* container's mapping has it -- every op on the host, on the host backend -- the statics and
|
||||
* experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
|
||||
* out of the headroom as the rounding's is. */
|
||||
b.weights = std::max<int64_t>(b.weights, kMiB);
|
||||
|
||||
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
|
||||
*
|
||||
@@ -227,12 +210,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* The share is the budget's -- what the slab alone leaves off -- which is the most a step can
|
||||
* see: the loans the KV cache and the smaller arena levels make only ever add residency. A
|
||||
* layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
|
||||
if (want_w && layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
cfg.placement != "layer_offload") {
|
||||
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
|
||||
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
|
||||
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
if (b.lends && want_kv) {
|
||||
if (b.lends) {
|
||||
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
|
||||
* leave one with no tier, while the region is lent to the slab whenever the steps are
|
||||
* small -- the same memory the cache would have lent. */
|
||||
@@ -263,7 +246,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
|
||||
* context no single request can complete is a configuration error however much slack the pool
|
||||
* has (core/engine_bringup.cpp, configure_kv). */
|
||||
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
|
||||
"%.1f full-length sessions. That is concurrency at length before the scheduler "
|
||||
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
|
||||
@@ -276,13 +259,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
|
||||
* cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful
|
||||
* fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was
|
||||
* STATED it is not ours to shave and the MiB comes out of the headroom instead. */
|
||||
cfg.vram_budget_derived = want_w || want_kv;
|
||||
* cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
|
||||
* the headroom stays whole. */
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
|
||||
cfg.vram_kv_mib = want_kv ? to_mib(std::max<int64_t>(b.kv - w_over, 0)) : to_mib(b.kv);
|
||||
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
|
||||
|
||||
/* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
|
||||
* can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
|
||||
@@ -320,13 +301,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
|
||||
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
|
||||
"outright"
|
||||
shared ? "integrated graphics: this memory is the host's"
|
||||
: "left unclaimed on purpose",
|
||||
humanb(b.claimable).c_str(),
|
||||
humanb(b.statics).c_str(),
|
||||
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
|
||||
: "(not charged here -- --vram-weights-mib was stated)",
|
||||
"off the top: every rank's own shard, and not a share of anything",
|
||||
humanb(b.elastic).c_str(),
|
||||
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
|
||||
" and lends what no live request holds to the "
|
||||
@@ -375,10 +354,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"slab while steps are small\n", humanb(b.stage).c_str(),
|
||||
b.lends ? "cache" : "experts").c_str()
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(),
|
||||
b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
|
||||
humanb(unclaimed).c_str());
|
||||
|
||||
if (out) *out = b;
|
||||
|
||||
+14
-7
@@ -3,7 +3,7 @@
|
||||
* ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
|
||||
*
|
||||
* Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
|
||||
* re-optimise a split the operator stated. The reason given there is exact and worth repeating:
|
||||
* re-optimise the split it is handed. The reason given there is exact and worth repeating:
|
||||
* a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
|
||||
* window on the machine's desktop.
|
||||
*
|
||||
@@ -46,10 +46,17 @@
|
||||
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
|
||||
* both fit, both are whole.
|
||||
*
|
||||
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
|
||||
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
|
||||
* THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
|
||||
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
|
||||
* GiB costs measurable decode time.
|
||||
* GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
|
||||
* takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
|
||||
* decides which experts must stay on the card -- and the arithmetic follows from them.
|
||||
*
|
||||
* A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
|
||||
* split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
|
||||
* where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
|
||||
* capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
|
||||
* at its ceiling.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -97,8 +104,9 @@ struct VramFacts {
|
||||
int64_t host_reserve = 0;
|
||||
};
|
||||
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including when the
|
||||
* operator stated the budgets -- the placement report and the pool report both want the totals. */
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
|
||||
* device that reports no capacity -- the placement report and the pool report both want the
|
||||
* totals. */
|
||||
struct VramBudget {
|
||||
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
|
||||
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
|
||||
@@ -120,7 +128,6 @@ struct VramBudget {
|
||||
* any. */
|
||||
int64_t stage = 0;
|
||||
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
|
||||
bool derived_weights = false, derived_kv = false;
|
||||
std::string report; /* the block the engine prints at startup */
|
||||
};
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+184
-8
@@ -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;
|
||||
@@ -167,13 +179,35 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
|
||||
sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
|
||||
1 << 16, 1 << 16);
|
||||
/* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
|
||||
* store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
|
||||
* 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
|
||||
* exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
|
||||
* at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
|
||||
* and the end as the scaler expects. */
|
||||
AVFrame* rgb = av_frame_alloc();
|
||||
if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
rgb->format = AV_PIX_FMT_RGB24;
|
||||
rgb->width = f->width;
|
||||
rgb->height = f->height;
|
||||
if (av_frame_get_buffer(rgb, 0) < 0) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "out of memory";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
|
||||
if (e != f->height) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "colour conversion failed";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
out->rgb.resize((size_t)f->width * (size_t)f->height * 3);
|
||||
uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr };
|
||||
int dst_ls[4] = { f->width * 3, 0, 0, 0 };
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls);
|
||||
if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; }
|
||||
const size_t row = (size_t)f->width * 3;
|
||||
out->rgb.resize(row * (size_t)f->height);
|
||||
for (int y = 0; y < f->height; ++y)
|
||||
std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
|
||||
av_frame_free(&rgb);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -360,6 +394,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);
|
||||
|
||||
@@ -114,8 +114,8 @@ Mover::~Mover() {
|
||||
}
|
||||
|
||||
/* One place the mover asks for memory. Everything device-side and everything pinned comes out of
|
||||
* the budgets the operator stated (spec §6); the fallback exists so the placement test can run
|
||||
* without standing a whole Pools up, and it announces itself. */
|
||||
* the resolved budgets (spec §6); the fallback exists so the placement test can run without
|
||||
* standing a whole Pools up, and it announces itself. */
|
||||
void* Mover::reserve(const char* what, int64_t bytes, int kind) {
|
||||
if (bytes <= 0) return nullptr;
|
||||
if (budget_) {
|
||||
@@ -134,7 +134,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
stats_ = MoverStats{};
|
||||
if (!budget_)
|
||||
RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That "
|
||||
"double-spends --vram-weights-mib against whatever else already reserved it, so "
|
||||
"double-spends the weights pool against whatever else already reserved it, so "
|
||||
"it is a test path and not a deployment.");
|
||||
|
||||
unit_.assign(plan.units.size(), UnitState{});
|
||||
@@ -180,7 +180,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
* resident count is untouched by turning the engine on. Under a static plan the plan
|
||||
* asked for none and the slab is exactly the resident set. */
|
||||
/* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of
|
||||
* --vram-weights-mib and the report told the operator how many; allocating a different
|
||||
* the weights pool and the report told the operator how many; allocating a different
|
||||
* count here would mean the mover works against one number while the operator was charged
|
||||
* for another, and the direction that is wrong in is an overrun. */
|
||||
const int64_t shadow = plan.dynamic ? sc.n_shadow : 0;
|
||||
|
||||
+4
-4
@@ -336,7 +336,7 @@ private:
|
||||
/* ------------------------------------------------------------------ configuration */
|
||||
struct MoverConfig {
|
||||
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
|
||||
* --vram-weights-mib and reported in the plan (SlabClass::n_shadow, n_stage), and a second
|
||||
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
|
||||
* knob for the same quantity is a second number for the mover and the operator to disagree
|
||||
* about -- with an overrun as the direction that disagreement goes wrong in.
|
||||
*
|
||||
@@ -419,7 +419,7 @@ public:
|
||||
* diagnosis.
|
||||
*
|
||||
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
|
||||
* --vram-weights-mib as one block; a mover that called rad_dev_alloc beside it would spend
|
||||
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
|
||||
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
|
||||
* launch much later. Reserving from Pools::weights() is also what makes it structurally
|
||||
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
|
||||
@@ -598,7 +598,7 @@ public:
|
||||
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
|
||||
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
|
||||
* and after the layer it is published as null again (unstage_units does that half). The
|
||||
* buffers are the two the plan charged out of --vram-weights-mib (Plan::file_stage_vram).
|
||||
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
|
||||
*
|
||||
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
|
||||
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
|
||||
@@ -655,7 +655,7 @@ private:
|
||||
};
|
||||
|
||||
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
|
||||
* come out of --vram-weights-mib like every other weight allocation and sit at a fixed stride
|
||||
* come out of the weights pool like every other weight allocation and sit at a fixed stride
|
||||
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
|
||||
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
|
||||
* They cannot be one range because the flex slots are scattered over every layer's stripe of
|
||||
|
||||
+24
-15
@@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) {
|
||||
Budgets Budgets::from(const Config& c) {
|
||||
Budgets b;
|
||||
b.vram_weights = c.vram_weights_mib * 1024 * 1024;
|
||||
b.host_pool = c.host_pool_mib * 1024 * 1024;
|
||||
b.host_pool = (c.host_pool_mib + c.embedding_host_mib) * 1024 * 1024;
|
||||
b.ssd = c.weights_disk_tier;
|
||||
return b;
|
||||
}
|
||||
@@ -123,7 +123,7 @@ int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
TablePlacement ngram, bool host_backend, bool container) {
|
||||
if (!out) return;
|
||||
*out = WeightFootprint{};
|
||||
|
||||
@@ -146,7 +146,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
/* build_units: a model-level weight is its own unit, everything else groups by the declared
|
||||
* (layer, expert). Ordered, for the same reason build_units is. */
|
||||
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
|
||||
bool emb = false, ngram = false, host = true; };
|
||||
bool emb = false, ngram = false, host = true, direct = true; };
|
||||
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
|
||||
std::vector<U> units;
|
||||
|
||||
@@ -175,6 +175,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
|
||||
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
|
||||
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
|
||||
if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
|
||||
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
|
||||
/* The placement flags' tables: model-level, so the unit is this one weight. */
|
||||
if (layer < 0) {
|
||||
@@ -186,6 +187,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
|
||||
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
|
||||
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
|
||||
for (U& mu : units) mu.mapped = mapped_unit(mu.mapped, container && mu.direct, host_backend);
|
||||
std::map<int32_t, int64_t> layer_experts;
|
||||
std::set<int64_t> expert_strides;
|
||||
bool ngram_host = true;
|
||||
@@ -284,8 +286,8 @@ void Planner::resolve_sites(const Program& prog) {
|
||||
* consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
|
||||
* in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
|
||||
* what the planner falls back to when VRAM runs out; this one is where the weight has to be
|
||||
* whatever the budgets say, and charging a pool for bytes that are never copied would make the
|
||||
* operator size a pool against a number that does not exist.
|
||||
* whatever the budgets say, and charging a pool for bytes that are never copied would size that
|
||||
* pool against a number that does not exist.
|
||||
*
|
||||
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
|
||||
* has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
|
||||
@@ -295,9 +297,15 @@ void Planner::resolve_sites(const Program& prog) {
|
||||
void Planner::pin_mapped(const Program& prog, Plan* p) {
|
||||
const TablePlacement ng = in_.config->ngram_resolved;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
bool host_only = false;
|
||||
for (rad_weight w : mu.weights)
|
||||
bool host_only = false, direct = in_.container;
|
||||
for (rad_weight w : mu.weights) {
|
||||
if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
|
||||
if (w < prog.weights.size() &&
|
||||
!weight_file_direct(prog.weights[w], prog.ctx.world_size)) direct = false;
|
||||
}
|
||||
/* On the host backend a unit stored in another form than its host kernel reads is placed
|
||||
* like any other weight, in the pool its kernel can read too (mapped_unit). */
|
||||
host_only = mapped_unit(host_only, direct, in_.host_backend);
|
||||
/* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
|
||||
* a device kernel could read it there: ram and disk are where the operator put it, and the
|
||||
* strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
|
||||
@@ -619,8 +627,8 @@ int Planner::assign_all_vram(Plan* p) {
|
||||
used += mu.slot_bytes;
|
||||
}
|
||||
if (p->vram_budget > 0 && used > p->vram_budget) {
|
||||
p->notes.push_back(fmt("all_vram needs %s of weights against a --vram-weights-mib "
|
||||
"budget of %s: %s short",
|
||||
p->notes.push_back(fmt("all_vram needs %s of weights against a weights pool "
|
||||
"of %s: %s short",
|
||||
humanb(used).c_str(), humanb(p->vram_budget).c_str(),
|
||||
humanb(used - p->vram_budget).c_str()));
|
||||
return RAD_E_NOMEM;
|
||||
@@ -768,9 +776,9 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
rank_units(p, &order);
|
||||
|
||||
/* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the
|
||||
* shadow slots a promotion writes into, and they all come out of --vram-weights-mib -- so a
|
||||
* shadow slots a promotion writes into, and they all come out of the weights pool -- so a
|
||||
* fill that spends the whole budget on residents leaves the mover with nowhere to move into
|
||||
* and, worse, makes the mover's allocation overrun the pool the operator sized.
|
||||
* and, worse, makes the mover's allocation overrun the weights pool.
|
||||
*
|
||||
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
|
||||
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
|
||||
@@ -900,7 +908,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
k = fill(uncapped, --cap);
|
||||
if (fixed + k.used + k.spare + k.file > p->vram_budget) {
|
||||
p->notes.push_back(fmt("the file tier's two layer buffers need %s, beside %s of "
|
||||
"fixed weights, against a --vram-weights-mib budget of %s",
|
||||
"fixed weights, against a weights pool of %s",
|
||||
humanb(k.file).c_str(), humanb(fixed).c_str(),
|
||||
humanb(p->vram_budget).c_str()));
|
||||
return RAD_E_NOMEM;
|
||||
@@ -1119,8 +1127,8 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
|
||||
mu.host_forced = true;
|
||||
mu.reason = "--embedding-placement ram; read over the link in place";
|
||||
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
|
||||
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
|
||||
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
|
||||
"(--embedding-placement ram%s)", name.c_str(), humanb(mu.bytes).c_str(),
|
||||
cfg.embedding_placement_given ? "" : ", the default");
|
||||
}
|
||||
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
|
||||
* so an empty pass is a plan built from a different program than the budget was: a wiring
|
||||
@@ -1243,7 +1251,8 @@ int Planner::assign(Plan* p) {
|
||||
/* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to
|
||||
* spill against would have to infer one from free VRAM, and an engine that quietly
|
||||
* re-optimises its own split is an engine whose benchmarks do not reproduce. */
|
||||
RAD_ERR("placement: %s needs --vram-weights-mib; there is nothing to spill against",
|
||||
RAD_ERR("placement: %s needs a weights budget and none was resolved; there is nothing to "
|
||||
"spill against",
|
||||
strategy_name(s));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
+23
-6
@@ -111,7 +111,7 @@ struct MoveUnit {
|
||||
|
||||
/* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The
|
||||
* planner budgets against this and the mover allocates this, so the two cannot drift -- and
|
||||
* the direction they would drift in is an overrun of the pool the operator sized. `bytes` is
|
||||
* the direction they would drift in is an overrun of the weights pool. `bytes` is
|
||||
* still what the report attributes to the weights, because padding is not a weight. */
|
||||
int64_t slot_bytes = 0;
|
||||
|
||||
@@ -179,7 +179,7 @@ struct SlabClass {
|
||||
/* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one
|
||||
* and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h).
|
||||
*
|
||||
* THEY COME OUT OF --vram-weights-mib, like everything else in the slab. Taking them from
|
||||
* THEY COME OUT OF THE WEIGHTS POOL, like everything else in the slab. Taking them from
|
||||
* whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool
|
||||
* explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic
|
||||
* placement costs a few resident units, and the plan report prints exactly how many.
|
||||
@@ -260,7 +260,7 @@ public:
|
||||
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
|
||||
* file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is
|
||||
* how the stager packs them; `file_stage_vram` is the two buffers, taken out of
|
||||
* --vram-weights-mib before any expert is made resident. Both 0 when nothing routed is on the
|
||||
* the weights pool before any expert is made resident. Both 0 when nothing routed is on the
|
||||
* file tier. */
|
||||
int64_t file_layer_max = 0;
|
||||
int64_t file_stage_vram = 0;
|
||||
@@ -310,8 +310,23 @@ struct PlannerInput {
|
||||
* served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this
|
||||
* false no unit is file-direct and both tiers are closed (spec §4.3). */
|
||||
bool container = true;
|
||||
/* No card is visible and the device backend is the host's own memory (device_is_host()), so a
|
||||
* host kernel can read the weights pool as well as the container's mapping. See
|
||||
* mapped_unit(). */
|
||||
bool host_backend = false;
|
||||
};
|
||||
|
||||
/* DOES A UNIT STAY IN THE CONTAINER'S MAPPING because only a host kernel can read it? On a card,
|
||||
* always: a host kernel cannot read VRAM, and the mapping is the one host address its bytes
|
||||
* already have. On the host backend the weights pool is host memory too, and a unit whose stored
|
||||
* form is not the container's (a widening or a relayout its host kernel asked for at load, or a
|
||||
* checkpoint served directly) has no place in the mapping that looks the way its kernel reads it,
|
||||
* so there it takes a converted copy in the weights pool like any other weight. One rule, for the
|
||||
* planner and the budget alike. */
|
||||
inline bool mapped_unit(bool host_only, bool direct, bool host_backend) {
|
||||
return host_only && (direct || !host_backend);
|
||||
}
|
||||
|
||||
class Planner {
|
||||
public:
|
||||
explicit Planner(const PlannerInput& in) : in_(in) {}
|
||||
@@ -399,10 +414,12 @@ struct WeightFootprint {
|
||||
};
|
||||
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
|
||||
* statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
|
||||
* kernel reads it. Stated by every caller, so the budget and the planner cannot count it
|
||||
* differently. */
|
||||
* kernel reads it. `host_backend` and `container` are PlannerInput's: whether a host kernel can
|
||||
* read the weights pool, and whether the weights lie in a container at all (a checkpoint served
|
||||
* directly has no mapping a unit could stay in). Stated by every caller, so the budget and the
|
||||
* planner cannot count it differently. */
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram);
|
||||
TablePlacement ngram, bool host_backend, bool container);
|
||||
|
||||
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
|
||||
|
||||
+61
-16
@@ -360,12 +360,16 @@ int Registry::commit_(Staged& s, int order) {
|
||||
* libraries for several cards would serve none of them but the first in the hierarchy.
|
||||
* What the library carries is read out of the fat binaries its dlopen registered, which is
|
||||
* what the launch itself will consult (core/device/aql_code.cpp), not out of
|
||||
* build_target, which is prose. Its host rows run anywhere and stay. */
|
||||
* build_target, which is prose. Its host rows run anywhere and stay. On the host backend
|
||||
* an engine that serves says no GPU code runs at all (set_no_device_code). */
|
||||
int n_device = 0;
|
||||
for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
|
||||
std::string why;
|
||||
if (no_device_code_)
|
||||
why = "no card is visible, so this process runs on the host backend and no GPU code "
|
||||
"object runs here";
|
||||
if (n_device > 0 && s.code_to > s.code_from &&
|
||||
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0) {
|
||||
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) {
|
||||
std::vector<std::pair<const RadKernelInfo*, int>> keep;
|
||||
for (const auto& r : staged_rows)
|
||||
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
|
||||
@@ -480,8 +484,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
if (rad_dev_count() > code_device_ && rad_dev_props(code_device_, &dp) == RAD_OK &&
|
||||
dp.arch[0] && !target_covers(p.build_target, dp.arch))
|
||||
RAD_WARN("kernel plugin '%s' declares it was built for %s and this machine reports %s. "
|
||||
"Its kernels will fail to launch; build it for %s, or put a library that "
|
||||
"serves this device ahead of it with --kernels.",
|
||||
"Its kernels will fail to launch; build it for %s, or leave it out with "
|
||||
"--kernels.",
|
||||
p.name.c_str(), p.build_target.c_str(), dp.arch, dp.arch);
|
||||
}
|
||||
|
||||
@@ -576,33 +580,74 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
staged.push_back(s);
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered. A plugin the operator named takes that
|
||||
* position; a plugin present on disk but absent from the list loads after everything named,
|
||||
* so dropping an .so into the directory adds it with no configuration and naming it ahead of
|
||||
* another is what substitutes it.
|
||||
/* An entry names a library by its declared name or by its file, written as the operator sees
|
||||
* it on disk: `libr4d`, `r4d`, `libr4d.so` and a path to it are one library. */
|
||||
auto names = [](const std::string& h, const Staged& s) {
|
||||
return h == s.name || h == s.file || stem_of(h) == s.file;
|
||||
};
|
||||
std::string found; /* every kernel library on the search path, for a list that names none */
|
||||
for (const Staged& s : staged)
|
||||
if (s.info && s.info->kind == RAD_PLUGIN_KERNEL)
|
||||
found += (found.empty() ? "" : ", ") + s.name;
|
||||
|
||||
/* A HIERARCHY NAMES THE KERNEL LIBRARIES THAT SERVE, AND ONLY THOSE LOAD. Ordering alone
|
||||
* cannot keep a library out: selection runs per domain, so a library named first that has no
|
||||
* device row for an op leaves that op to whichever unnamed library does -- a GPU library on a
|
||||
* machine whose card it was not built for, say -- and an operator who listed what to use gets
|
||||
* something else. A kernel library on the search path that the list leaves out is closed again
|
||||
* before it registers anything, and said once. Architecture and quantiser plugins are not
|
||||
* kernel libraries and no list ranks them. */
|
||||
if (!hierarchy.empty()) {
|
||||
std::vector<Staged> kept;
|
||||
std::string left_out;
|
||||
for (Staged& s : staged) {
|
||||
const bool kernel = s.info && s.info->kind == RAD_PLUGIN_KERNEL;
|
||||
const bool named = std::find_if(hierarchy.begin(), hierarchy.end(),
|
||||
[&](const std::string& h) {
|
||||
return names(h, s);
|
||||
}) != hierarchy.end();
|
||||
if (!kernel || named) {
|
||||
kept.push_back(s);
|
||||
continue;
|
||||
}
|
||||
left_out += (left_out.empty() ? "" : ", ") + s.name;
|
||||
unstage_(s);
|
||||
}
|
||||
staged.swap(kept);
|
||||
if (!left_out.empty())
|
||||
RAD_INFO("kernel libraries on the search path that --kernels (or RADIANCE_KERNELS) "
|
||||
"does not name, and so not loaded: %s", left_out.c_str());
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered: a library the operator named takes that
|
||||
* position. With no list every kernel library on the search path loads, so dropping an .so
|
||||
* into the directory adds it with no configuration.
|
||||
*
|
||||
* A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for
|
||||
* every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library
|
||||
* for this machine's card would load, never be selected for anything, and leave the whole
|
||||
* model resolving to the naive implementation. Pinning it is what makes an unconfigured
|
||||
* drop-in work. Naming it in the hierarchy overrides this, which is how it is put in front of
|
||||
* a library to compare against. Which library is one is its own declaration
|
||||
* drop-in work. Naming it in the hierarchy places it where it is named, which is how it is put
|
||||
* in front of a library to compare against. Which library is one is its own declaration
|
||||
* (RadPluginReferenceFn), not its name. */
|
||||
const size_t kUnnamed = (size_t)INT_MAX - 1;
|
||||
std::vector<size_t> rank(staged.size());
|
||||
for (size_t i = 0; i < staged.size(); ++i)
|
||||
rank[i] = staged[i].reference ? (size_t)INT_MAX : kUnnamed;
|
||||
for (size_t h = 0; h < hierarchy.size(); ++h) {
|
||||
bool found = false;
|
||||
bool hit = false;
|
||||
for (size_t i = 0; i < staged.size(); ++i) {
|
||||
if (staged[i].name == hierarchy[h] || staged[i].file == hierarchy[h]) {
|
||||
if (names(hierarchy[h], staged[i])) {
|
||||
rank[i] = h;
|
||||
found = true;
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
RAD_WARN("kernel hierarchy names '%s', which is not in %s -- ignored",
|
||||
hierarchy[h].c_str(), dir.c_str());
|
||||
/* The list is what loads, so an entry that matches nothing is a library that is not
|
||||
* there to select -- and a list none of whose entries match loads no kernel library. */
|
||||
if (!hit)
|
||||
RAD_WARN("--kernels (or RADIANCE_KERNELS) names '%s', which is no kernel library in "
|
||||
"%s, so nothing loads in its place; the kernel libraries there are: %s",
|
||||
hierarchy[h].c_str(), dir.c_str(), found.empty() ? "none" : found.c_str());
|
||||
}
|
||||
std::vector<size_t> idx(staged.size());
|
||||
for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
|
||||
|
||||
+14
-4
@@ -150,10 +150,12 @@ public:
|
||||
/* ---------------------------------------------------------- loading (§2, §18) */
|
||||
/* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured,
|
||||
* not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the
|
||||
* file's stem, whichever the operator wrote), so substituting a kernel is dropping an .so in a
|
||||
* directory and naming it ahead of the default. A plugin present on disk but absent from the
|
||||
* list loads at the END, after everything named, in filename order so the result is
|
||||
* reproducible.
|
||||
* file as the operator wrote it -- `libr4d`, `r4d`, `libr4d.so`), so substituting a kernel is
|
||||
* dropping an .so in a directory and naming it ahead of the default. A non-empty list is
|
||||
* EXCLUSIVE: a kernel library it does not name is closed before it registers anything, and an
|
||||
* entry that matches nothing is warned about by name. An empty list loads every kernel library
|
||||
* found, in filename order so the result is reproducible, with a reference library last.
|
||||
* Architecture and quantiser plugins are not ranked and always load.
|
||||
*
|
||||
* Always completes: every plugin that can be loaded is, every refusal is recorded in
|
||||
* load_errors(), and the FIRST negative status is returned. Reporting the whole list beats
|
||||
@@ -181,6 +183,13 @@ public:
|
||||
* loads anything, once it has chosen its cards. */
|
||||
void set_code_device(int device) { code_device_ = device; }
|
||||
|
||||
/* THE ENGINE ABOUT TO SERVE ON THE HOST BACKEND SAYS SO: no card is visible, and no GPU code
|
||||
* object runs in this process at all. A kernel library that brought device code then has its
|
||||
* device rows left out of selection at load, its host rows staying, so every op takes its host
|
||||
* kernel. Only the engine says this. A tool that selects without serving -- rad-convert's
|
||||
* recipe check, rad-kbench's tables, a test of a library's constraints -- sees every row, as
|
||||
* it would on the machine the model is served on. */
|
||||
void set_no_device_code(bool v) { no_device_code_ = v; }
|
||||
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
|
||||
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
|
||||
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
|
||||
@@ -333,6 +342,7 @@ private:
|
||||
};
|
||||
|
||||
int code_device_ = 0;
|
||||
bool no_device_code_ = false;
|
||||
Geometry device_facts_;
|
||||
TuneCache tune_;
|
||||
|
||||
|
||||
+79
-17
@@ -122,11 +122,12 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* it, and why the operator gets to choose.
|
||||
*
|
||||
* Vram resident on the card, a weight like any other.
|
||||
* Ram in host memory the card or a host kernel reads in place: the embedding in the pinned
|
||||
* host pool, read over the link; an n-gram table as a locked copy made at load.
|
||||
* Disk read from the container on demand.
|
||||
* Auto the fastest of the three that has room once every other weight is placed; Engine::plan
|
||||
* decides it and writes the answer into Config, so every rank plans from one choice. */
|
||||
* Ram in host memory the card or a host kernel reads in place: the embedding pinned beside
|
||||
* the host pool, read over the link; an n-gram table as a copy made at load.
|
||||
* Disk read from the container on demand; the n-gram table's only.
|
||||
* Auto the fastest of the three that has room once every other weight is placed; the n-gram
|
||||
* table's only. Engine::plan decides it and writes the answer into Config, so every rank
|
||||
* plans from one choice. The embedding takes Ram or Vram. */
|
||||
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).
|
||||
@@ -346,6 +347,9 @@ public:
|
||||
* purpose -- the engine refuses to SERVE such a program and says so at startup, rather
|
||||
* than discovering at the first step that there is nothing to sample. */
|
||||
rad_buf logits_buf = 0;
|
||||
/* The buffer the plugin named as this step's pooled vectors (rad_declare_pooled): set only by
|
||||
* an EMBEDDING program, which then has no logits buffer. */
|
||||
rad_buf pooled_buf = 0;
|
||||
|
||||
/* THE DRAFT HEAD THIS PLUGIN DECLARED (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when
|
||||
* it declared none, which is the normal case -- the engine then speculates with the
|
||||
@@ -359,6 +363,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
|
||||
@@ -399,9 +406,18 @@ public:
|
||||
std::string span; /* the band, as Band::span */
|
||||
std::string why;
|
||||
int domain = 0; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
|
||||
int32_t index = 0; /* the instance that missed (OpInfo::index): bands are its own */
|
||||
std::string line() const; /* "op geometry [domain] -> why", the full-detail rendering */
|
||||
};
|
||||
std::vector<Miss> misses;
|
||||
/* THE DEVICE MISSES A REQUEST CAN FALL INTO, in `misses` order: the device bands no kernel
|
||||
* serves and no host kernel stands in for. A host kernel for the same band stands in on the
|
||||
* host backend, where every op without a device row runs on the host (Ctx::bind_ops); on a
|
||||
* card it stands in only for an op that has weights, because the planner moves an op to the
|
||||
* host by placing its weights there and has nothing to place for an op without them --
|
||||
* attention over a cache that lives in VRAM is the case that matters. One rule for the engine
|
||||
* that refuses to start on a hole and for the tools that count them. */
|
||||
std::vector<const Miss*> device_holes(bool host_backend) const;
|
||||
|
||||
/* Every (kernel, shape) pair rad-tune would need to benchmark (spec §15). */
|
||||
/* `info` is the kernel's own row, so rad-tune can read its RadTunable axes and expand the
|
||||
@@ -476,6 +492,24 @@ struct ReasoningCount {
|
||||
bool inside() const { return st == Think; }
|
||||
};
|
||||
|
||||
/* THE MOST ALTERNATIVES ONE TOKEN'S LOGPROBS MAY CARRY: OpenAI's bound on top_logprobs. A request
|
||||
* above it is refused. The sampler declares `sample_logprobs` one wider (Sampler::kLpK), for the
|
||||
* width of the row the split-vocabulary gather moves; the extra pair is never reported. */
|
||||
static constexpr int RAD_MAX_LOGPROBS = 20;
|
||||
|
||||
/* One emitted token's log-probability under the model's RAW distribution -- the logits before any
|
||||
* penalty, temperature, mask or cut -- and its `n_top` most likely alternatives in descending
|
||||
* order, ties to the lower id. What OpenAI's `logprobs` and llama-server's `n_probs` report.
|
||||
* `token` -1 is a token whose logprobs could not be computed (a row with no finite logit): the
|
||||
* scheduler fails its request rather than report a number for it. */
|
||||
struct TokenLogprobs {
|
||||
int32_t token = -1;
|
||||
float logprob = 0.0f;
|
||||
int32_t n_top = 0;
|
||||
int32_t top_id[RAD_MAX_LOGPROBS] = {};
|
||||
float top_lp[RAD_MAX_LOGPROBS] = {};
|
||||
};
|
||||
|
||||
struct SamplingParams {
|
||||
float temp = 1.0f;
|
||||
int top_k = 0; /* 0 = off */
|
||||
@@ -492,6 +526,14 @@ struct SamplingParams {
|
||||
int dry_penalty_last_n = -1;
|
||||
float xtc_probability = 0.0f;
|
||||
float xtc_threshold = 0.1f;
|
||||
/* TEMPERATURE AFTER THE CUTS rather than before them: top-p, min-p, typical and XTC read the
|
||||
* distribution at temperature 1 and the pick draws at `temp`. llama.cpp's default order; the
|
||||
* default here is vLLM's, temperature first. A request names the order with `samplers`. */
|
||||
bool temp_last = false;
|
||||
/* LOGPROBS: -1 is none; 0..RAD_MAX_LOGPROBS returns every emitted token's logprob and that
|
||||
* many alternatives. Speculation is unaffected: every verified position is a row of its own,
|
||||
* and an accepted draft is the token the target drew there. */
|
||||
int n_probs = -1;
|
||||
uint64_t seed = 0;
|
||||
bool greedy() const { return top_k == 1 || temp <= 0.0f; }
|
||||
std::string grammar; /* GBNF, or "" */
|
||||
@@ -598,6 +640,17 @@ 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;
|
||||
|
||||
/* THE CONVERSATION AS THE CLIENT NAMES IT (OpenRouter's `session_id`), "" when it names
|
||||
* none: carried to the session the prefix cache records for it, as a label on /sessions and
|
||||
* the dashboard. It changes nothing about how the request is served. */
|
||||
std::string session_label;
|
||||
|
||||
std::string finish_reason;
|
||||
void* sink = nullptr; /* the server's per-request stream sink */
|
||||
};
|
||||
@@ -608,7 +661,8 @@ struct Request {
|
||||
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
|
||||
|
||||
struct Config {
|
||||
std::string model; /* path to the .rad */
|
||||
std::string model; /* path to the .rad, or a Hugging Face repo id (hf_model.h) */
|
||||
std::string download_dir; /* where a repo id is fetched to; empty = the XDG cache */
|
||||
std::string radiance_home;
|
||||
std::vector<std::string> kernel_hierarchy; /* ordered; first wins */
|
||||
|
||||
@@ -649,8 +703,8 @@ struct Config {
|
||||
* 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.
|
||||
/* THE ENGINE DERIVES THE BUDGET FROM THE CARD, AND IT IS STATED IN FULL BEFORE ANYTHING IS
|
||||
* ALLOCATED.
|
||||
*
|
||||
* Spec §6 forbids a derived budget because a budget derived from the FREE VRAM at startup is
|
||||
* a benchmark that moves when a desktop opens a window. What it does not forbid is arithmetic
|
||||
@@ -664,7 +718,7 @@ struct Config {
|
||||
* 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. */
|
||||
* NO FLAG SETS THEM: zero until the resolver has run. */
|
||||
int64_t vram_weights_mib = 0;
|
||||
int64_t vram_kv_mib = 0;
|
||||
int64_t gpu_headroom_mib = 96; /* --gpu-headroom, left unclaimed on every card */
|
||||
@@ -677,11 +731,6 @@ struct Config {
|
||||
* a third name for the second one, and a flag whose values are not all distinct is a flag
|
||||
* whose log line cannot be read back. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
/* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into
|
||||
* this config, which erases the only evidence of whether they were stated or derived -- and
|
||||
* Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or
|
||||
* a split it made itself and already printed a receipt for. */
|
||||
bool vram_budget_derived = false;
|
||||
int64_t host_pool_mib = 0;
|
||||
/* THE FILE TIER FOR WEIGHTS: what fits neither the VRAM slab nor the pinned host pool is read
|
||||
* from the container itself, with O_DIRECT, ahead of the ops that read it -- a scheduled unit by
|
||||
@@ -693,11 +742,19 @@ struct Config {
|
||||
|
||||
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
|
||||
/* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
|
||||
* is), and what Engine::plan resolved them to before any rank planned: never Auto. */
|
||||
TablePlacement embedding_placement = TablePlacement::Auto;
|
||||
* is), and what Engine::plan resolved them to before any rank planned: never Auto. The
|
||||
* embedding's default is Ram; `embedding_placement_given` says whether the operator named it,
|
||||
* because a named tier that cannot be honoured stops the server where the default gives way
|
||||
* to the card with the reason. */
|
||||
TablePlacement embedding_placement = TablePlacement::Ram;
|
||||
bool embedding_placement_given = false;
|
||||
TablePlacement ngram_placement = TablePlacement::Auto;
|
||||
TablePlacement embedding_resolved = TablePlacement::Vram;
|
||||
TablePlacement ngram_resolved = TablePlacement::Disk;
|
||||
/* SET BY THE RESOLVER: the pinned host room the token embedding takes when it resolves to Ram,
|
||||
* a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool,
|
||||
* and a dense model that has no pool still has a place for it. */
|
||||
int64_t embedding_host_mib = 0;
|
||||
bool deterministic = false;
|
||||
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
|
||||
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
|
||||
@@ -780,6 +837,9 @@ struct Config {
|
||||
* when the container carries a vision tower and 0 when it does not. 0 serves text only and
|
||||
* keeps a tower the container carries off the card. */
|
||||
int64_t mm_max_patches = -1;
|
||||
/* The audio encoder's pass in frames, resolved at bring-up from the plugin's probe when the
|
||||
* container carries an audio encoder; --mm-max-patches 0 (text only) turns it off too. */
|
||||
int64_t mm_audio_frames = -1;
|
||||
|
||||
std::string host = "0.0.0.0";
|
||||
/* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
|
||||
@@ -869,10 +929,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. */
|
||||
|
||||
@@ -577,13 +577,16 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
|
||||
}
|
||||
|
||||
if (order == ChainOrder::Radiance) {
|
||||
host_temp(s, sp.temp);
|
||||
/* `temp_last` moves temperature behind the cuts, as the device chain moves it onto the
|
||||
* candidate plane (Sampler::issue); the cuts keep this order either way. */
|
||||
if (!sp.temp_last) host_temp(s, sp.temp);
|
||||
host_mask(s, in.bitmask, in.n_words);
|
||||
host_top_k(s, sp.top_k);
|
||||
host_top_p(s, sp.top_p, 1);
|
||||
host_min_p(s, sp.min_p, 1);
|
||||
host_typical(s, sp.typical_p, 1);
|
||||
host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
|
||||
if (sp.temp_last) host_temp(s, sp.temp);
|
||||
} else {
|
||||
/* llama.cpp's default order, for checking this port against llama.cpp itself. Note the
|
||||
* absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a
|
||||
|
||||
+302
-9
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
@@ -177,6 +178,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
buf_params_ = decl("sampler.params", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* One byte beside every history token: nonzero where that token is a whole DRY sequence
|
||||
* breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
|
||||
@@ -194,7 +197,16 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
|
||||
}
|
||||
|
||||
if (!buf_params_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_) {
|
||||
/* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
|
||||
* declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
|
||||
* over the op list would hand its bytes to the candidate planes the stages after it write. */
|
||||
buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
|
||||
if (vocab_parallel())
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -252,6 +264,15 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
|
||||
* which is all the kernel reads it as -- a row length. */
|
||||
{
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
RadParam{ "n_vocab", RAD_P_INT, (long long)ncand, 0, nullptr },
|
||||
};
|
||||
op_temp_late_ = rad_decl_op(b, "sample_temp", p, 2, nullptr, 0);
|
||||
}
|
||||
|
||||
if (vocab_parallel()) {
|
||||
/* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
|
||||
@@ -269,6 +290,31 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_merge_ = op_cand("sample_merge_topk");
|
||||
}
|
||||
|
||||
/* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
|
||||
* deployment whose kernels lack it serves every request that does not ask for logprobs;
|
||||
* check_request refuses the ones that do, by name. */
|
||||
{
|
||||
RadParam p[4] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr },
|
||||
RadParam{ "k", RAD_P_INT, (long long)kLpK, 0, nullptr },
|
||||
RadParam{ "vocab_off", RAD_P_INT, (long long)cfg_.vocab_off, 0, nullptr },
|
||||
};
|
||||
op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
|
||||
}
|
||||
if (vocab_parallel()) {
|
||||
/* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
|
||||
* row lands beside the others' as the candidate pairs do. */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
|
||||
RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
|
||||
RadParam{ "row", RAD_P_INT, (long long)lp_width(), 0, nullptr },
|
||||
};
|
||||
op_lp_gather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
|
||||
if (!op_lp_gather_) op_logprobs_ = RAD_NULL_HANDLE;
|
||||
}
|
||||
|
||||
RAD_TRY(stage_alloc());
|
||||
declared_ = true;
|
||||
|
||||
@@ -288,14 +334,32 @@ int Sampler::stage_alloc() {
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
late_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_ready_ = false;
|
||||
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !hist_stage_ || !brk_stage_ || !mask_stage_) {
|
||||
/* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
|
||||
* reads them. */
|
||||
if (cfg_.rank == 0) {
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
lp_host_ = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
|
||||
lp_ci_host_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
|
||||
lp_cv_host_ = (float*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
|
||||
if (!lp_host_ || !lp_ci_host_ || !lp_cv_host_) {
|
||||
RAD_ERR("sampler: could not pin %s for the logprobs readback",
|
||||
humanb(rows * (w + 2 * cfg_.max_candidates) * 4).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
|
||||
!mask_stage_) {
|
||||
RAD_ERR("sampler: could not pin %s of staging",
|
||||
humanb(rows * ((int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
mask_words_ * 4)).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
@@ -306,11 +370,19 @@ int Sampler::stage_alloc() {
|
||||
void Sampler::stage_free() {
|
||||
if (params_stage_) rad_dev_free(params_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (greedy_stage_) rad_dev_free(greedy_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED);
|
||||
lp_host_ = nullptr;
|
||||
lp_ci_host_ = nullptr;
|
||||
lp_cv_host_ = nullptr;
|
||||
params_stage_ = nullptr;
|
||||
greedy_stage_ = nullptr;
|
||||
late_stage_ = nullptr;
|
||||
cur_stage_ = nullptr;
|
||||
hist_stage_ = nullptr;
|
||||
brk_stage_ = nullptr;
|
||||
@@ -349,6 +421,11 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (sp.top_k > cfg_.max_candidates)
|
||||
return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
|
||||
RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
|
||||
* sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
|
||||
* work is queued, rather than truncated -- a request whose breakers quietly went missing is a
|
||||
@@ -366,12 +443,18 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return (wanted && !h) ? n : nullptr;
|
||||
};
|
||||
/* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
|
||||
* it: not the argmax, but the top-k, the merge and the pick that build_step's top_k = 1 sends
|
||||
* it through. Admission has to check what will actually be issued. */
|
||||
const bool greedy_chain = sp.greedy() && vocab_parallel();
|
||||
* it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
|
||||
* build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
|
||||
* batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
|
||||
* is. Admission has to check what will actually be issued. */
|
||||
/* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
|
||||
* token comes off a candidate plane (sampler.h). */
|
||||
const bool lp = sp.n_probs >= 0;
|
||||
const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
|
||||
const char* missing = nullptr;
|
||||
if (!missing) missing = need(lp, op_logprobs_, "sample_logprobs");
|
||||
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
|
||||
if (!missing) missing = need(!sp.greedy(), op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
|
||||
/* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
|
||||
* the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
|
||||
@@ -381,6 +464,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
|
||||
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
|
||||
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
|
||||
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
|
||||
"sample_temp (over the candidates, for temperature last)");
|
||||
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
|
||||
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
|
||||
"sample_mask");
|
||||
@@ -514,7 +599,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int64_t cap = rows_for(cfg_);
|
||||
n_seq_ = 0;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
|
||||
/* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
|
||||
* strings resolved against the vocabulary, so what they mean for this window is worked out
|
||||
@@ -651,11 +738,28 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
* Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
|
||||
* skips a row that does, because in an unsplit batch that flag is what keeps the pick
|
||||
* from overwriting the argmax's answer with a draw. */
|
||||
/* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
|
||||
* its token has to come off a candidate plane, which is where logprobs_for reads the
|
||||
* value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
|
||||
* same. */
|
||||
const bool want_lp = sp.n_probs >= 0;
|
||||
if (sp.greedy()) {
|
||||
if (vocab_parallel()) p.top_k = 1;
|
||||
else p.flags |= RAD_SP_GREEDY;
|
||||
if (vocab_parallel() || want_lp) p.top_k = 1;
|
||||
else p.flags |= RAD_SP_GREEDY;
|
||||
}
|
||||
if (want_lp) p.flags |= RAD_SP_LOGPROBS;
|
||||
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
|
||||
/* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
|
||||
* the temperature stage skips -- in whichever of the two it does not run in. Every row
|
||||
* gets a late row, because the late stage is issued over the whole batch. */
|
||||
const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
|
||||
DeviceSampleParams& lp = late_stage_[row];
|
||||
lp = p;
|
||||
lp.temp = late ? sp.temp : 1.0f;
|
||||
if (late) {
|
||||
p.temp = 1.0f;
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
|
||||
* -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
|
||||
@@ -766,6 +870,23 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
|
||||
if (budget && think.inside() && think.body >= sp.thinking_budget)
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
|
||||
if (want_lp) {
|
||||
/* The temperature the candidate value carries: the early stage's and the late
|
||||
* one's, each only where its kernel runs (temp > 0 and not 1). */
|
||||
auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
|
||||
LpRow L;
|
||||
L.row = row;
|
||||
L.n_top = sp.n_probs;
|
||||
L.temp = t_of(p.temp) * t_of(late_stage_[row].temp);
|
||||
L.p = p;
|
||||
if (p.hist_len > 0) {
|
||||
const int32_t* h = hist_stage_ + row * cfg_.max_hist;
|
||||
L.hist.assign(h, h + p.hist_len);
|
||||
}
|
||||
L.dry = brk;
|
||||
lp_rows_.push_back(std::move(L));
|
||||
}
|
||||
}
|
||||
|
||||
/* Back to where the sequence actually is. The tokens it really accepted are applied by
|
||||
@@ -881,6 +1002,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
* number that makes a host-side grammar affordable at all (spec §13). */
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
/* The late temperature's rows only when this build staged one: a greedy build's rows come
|
||||
* from greedy_stage_, and late_stage_ then holds an older build's. */
|
||||
const bool late = any_late_ && cur_stage_ == params_stage_;
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
if (any_penalty || any_dry)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
|
||||
n_seq_ * cfg_.max_hist * 4, s));
|
||||
@@ -906,6 +1033,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
|
||||
};
|
||||
|
||||
/* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
|
||||
* place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
|
||||
* stages none, and must not overwrite the summary rank 0 is about to copy back. */
|
||||
const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
|
||||
const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
|
||||
if (lp) {
|
||||
RAD_TRY(issue(op_logprobs_, { o_logits, o_params, o_lp }));
|
||||
if (vocab_parallel())
|
||||
RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
|
||||
}
|
||||
|
||||
/* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
|
||||
* breaker marks only when some row in the batch has breakers; its fourth operand is optional
|
||||
* and absent means no token is exempt. */
|
||||
@@ -962,8 +1100,163 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_minp) RAD_TRY(issue(op_minp_, { o_ci, o_cv, o_params }));
|
||||
if (any_typ) RAD_TRY(issue(op_typical_, { o_ci, o_cv, o_params }));
|
||||
if (any_xtc) RAD_TRY(issue(op_xtc_, { o_ci, o_cv, o_params }));
|
||||
if (late)
|
||||
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
|
||||
/* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
|
||||
* summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
|
||||
* there when the summary does not hold it). Only the rows between the first and the last
|
||||
* that asked, and only on rank 0, which is the rank collect_step asks. */
|
||||
if (lp && cfg_.rank == 0) {
|
||||
lp_lo_ = lp_rows_.front().row;
|
||||
lp_hi_ = lp_rows_.back().row + 1;
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
const int64_t nc = cfg_.max_candidates, n = lp_hi_ - lp_lo_;
|
||||
const char* sp = (const char*)rad_buf_ptr(c, vocab_parallel() ? buf_lp_g_ : buf_lp_);
|
||||
const char* ci = (const char*)rad_buf_ptr(c, buf_cand_i_);
|
||||
const char* cv = (const char*)rad_buf_ptr(c, buf_cand_v_);
|
||||
if (!sp || !ci || !cv) return RAD_E_STATE;
|
||||
RAD_TRY(rad_memcpy_async(lp_host_ + lp_lo_ * w, sp + lp_lo_ * w * 4, n * w * 4, s));
|
||||
RAD_TRY(rad_memcpy_async(lp_ci_host_ + lp_lo_ * nc, ci + lp_lo_ * nc * 4, n * nc * 4, s));
|
||||
RAD_TRY(rad_memcpy_async(lp_cv_host_ + lp_lo_ * nc, cv + lp_lo_ * nc * 4, n * nc * 4, s));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== logprobs */
|
||||
|
||||
float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
const DeviceSampleParams& p = L.p;
|
||||
double y = (double)v * (double)L.temp;
|
||||
/* DRY subtracted a penalty that depends on the token and the window alone, so the host
|
||||
* reference computes it for this one token: a single candidate at 0 comes back at minus the
|
||||
* penalty. */
|
||||
if (p.flags & RAD_SP_DRY) {
|
||||
static const DryBreakers kNone;
|
||||
CandidateSet s;
|
||||
s.c.push_back(Candidate{ token, 0.0f, 0.0f });
|
||||
DryParams dp;
|
||||
dp.multiplier = p.dry_multiplier;
|
||||
dp.base = p.dry_base;
|
||||
dp.allowed_length = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2;
|
||||
dp.penalty_last_n = p.dry_penalty_last_n < 0 ? -1 : p.dry_penalty_last_n;
|
||||
host_dry(s, L.hist.data(), (int64_t)L.hist.size(), (int64_t)L.hist.size(), dp,
|
||||
L.dry ? *L.dry : kNone);
|
||||
y -= (double)s.c[0].logit;
|
||||
}
|
||||
/* The penalties, inverted: presence and frequency added back, then the repetition penalty
|
||||
* undone on the side of zero the logit is on -- it never changes sign. The window is the
|
||||
* stage's: the tail of the staged history, penalty_last_n long when that is positive. */
|
||||
if (p.flags & RAD_SP_PENALTY) {
|
||||
int64_t n = (int64_t)L.hist.size(), o = 0;
|
||||
if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
|
||||
int64_t count = 0;
|
||||
for (int64_t i = 0; i < n; ++i) count += L.hist[(size_t)(o + i)] == token;
|
||||
if (count > 0) {
|
||||
y += (double)count * p.freq_penalty + p.pres_penalty;
|
||||
y = y > 0.0 ? y * p.rep_penalty : y / p.rep_penalty;
|
||||
}
|
||||
}
|
||||
return (float)y;
|
||||
}
|
||||
|
||||
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
||||
int cap) {
|
||||
const int64_t w = 2 + 2 * (int64_t)k;
|
||||
auto live = [&](int r) {
|
||||
const float m = st[r * w], z = st[r * w + 1];
|
||||
return std::isfinite(m) && std::isfinite(z) && z > 0.0f;
|
||||
};
|
||||
double mx = -INFINITY;
|
||||
for (int r = 0; r < W; ++r)
|
||||
if (live(r)) mx = std::max(mx, (double)st[r * w]);
|
||||
double sum = 0.0;
|
||||
for (int r = 0; r < W; ++r)
|
||||
if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
|
||||
*log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
|
||||
|
||||
/* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
|
||||
* more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
|
||||
struct Pair { float v; int32_t id; };
|
||||
Pair buf[256];
|
||||
std::vector<Pair> heap;
|
||||
Pair* top = buf;
|
||||
if ((int64_t)W * k > (int64_t)(sizeof buf / sizeof buf[0])) {
|
||||
heap.resize((size_t)W * (size_t)k);
|
||||
top = heap.data();
|
||||
}
|
||||
int m = 0;
|
||||
for (int r = 0; r < W; ++r) {
|
||||
if (!live(r)) continue;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
const int32_t id = (int32_t)st[r * w + 2 + 2 * j];
|
||||
const float v = st[r * w + 3 + 2 * j];
|
||||
if (id >= 0 && std::isfinite(v)) top[m++] = Pair{ v, id };
|
||||
}
|
||||
}
|
||||
std::sort(top, top + m, [](const Pair& a, const Pair& b) {
|
||||
return a.v > b.v || (a.v == b.v && a.id < b.id);
|
||||
});
|
||||
const int n = std::min(cap, m);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
ids[j] = top[j].id;
|
||||
vals[j] = top[j].v;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const {
|
||||
if (!out || !lp_host_ || row < lp_lo_ || row >= lp_hi_) return RAD_E_STATE;
|
||||
const LpRow* L = nullptr;
|
||||
for (const LpRow& x : lp_rows_)
|
||||
if (x.row == row) { L = &x; break; }
|
||||
if (!L) return RAD_E_STATE;
|
||||
|
||||
/* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
|
||||
* rescale, the largest by value with the lower id first. */
|
||||
const int W = vocab_parallel() ? cfg_.world_size : 1;
|
||||
double log_z = 0.0;
|
||||
int32_t ids[kLpK * 8];
|
||||
float vals[kLpK * 8];
|
||||
const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
|
||||
(int)(sizeof ids / sizeof ids[0]));
|
||||
/* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
|
||||
* model, or every one at -inf -- and any number sent for it would be invented. */
|
||||
if (!std::isfinite(log_z)) {
|
||||
RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
|
||||
(long long)row);
|
||||
out->token = -1;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
out->token = token;
|
||||
out->n_top = std::min(L->n_top, n);
|
||||
for (int j = 0; j < out->n_top; ++j) {
|
||||
out->top_id[j] = ids[j];
|
||||
out->top_lp[j] = (float)((double)vals[j] - log_z);
|
||||
}
|
||||
|
||||
/* The token's own raw logit: exact when it is among the largest, and otherwise recovered
|
||||
* from the value the pick drew it at. */
|
||||
double own = NAN;
|
||||
for (int j = 0; j < n && std::isnan(own); ++j)
|
||||
if (ids[j] == token) own = (double)vals[j];
|
||||
if (std::isnan(own)) {
|
||||
const int64_t nc = cfg_.max_candidates;
|
||||
const int32_t* ci = lp_ci_host_ + row * nc;
|
||||
const float* cv = lp_cv_host_ + row * nc;
|
||||
for (int64_t c = 0; c < nc && std::isnan(own); ++c)
|
||||
if (ci[c] == token) own = (double)raw_logit(*L, token, cv[c]);
|
||||
}
|
||||
if (!std::isfinite(own)) {
|
||||
RAD_WARN("sampler: row %lld sampled token %d, which has no finite logit on the candidate "
|
||||
"plane it was drawn from; its logprobs cannot be computed", (long long)row, token);
|
||||
out->token = -1;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->logprob = (float)(own - log_z);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,21 @@
|
||||
* XTC
|
||||
* the pick
|
||||
*
|
||||
* TEMPERATURE MAY RUN AFTER THE CUTS INSTEAD, per sequence: llama.cpp's order, which a request
|
||||
* names with `samplers` (SamplingParams::temp_last). Such a row's temperature is staged at 1 for
|
||||
* the stage above, which skips it, and at its own value for a second `sample_temp` over the
|
||||
* candidate plane after XTC -- the same kernel at the candidate width, so no plugin needs a
|
||||
* second implementation of it. Every other row is 1 there.
|
||||
*
|
||||
* LOGPROBS ARE READ OFF THE RAW LOGITS, before the first stage: `sample_logprobs` summarises each
|
||||
* row that asks (RAD_SP_LOGPROBS) as its maximum, its normaliser and its kLpK largest (one more
|
||||
* than RAD_MAX_LOGPROBS, for the row's width below), and rank 0 copies that back behind the pick.
|
||||
* The emitted token's own logprob is its raw logit less the log normaliser. When it is not among the largest its raw logit is no longer on the card
|
||||
* -- every stage wrote the logits in place -- so it is recovered from the value the pick drew it
|
||||
* at, the candidate plane's, by undoing temperature, DRY and the penalties on the host
|
||||
* (logprobs_for). Such a row is never a greedy-flagged one: a greedy row asking for logprobs is
|
||||
* staged as a top-1 chain row, so that its token is drawn from a candidate plane too.
|
||||
*
|
||||
* A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask,
|
||||
* because temperature 0 collapses every other logit to -inf and a mask applied afterwards would
|
||||
* leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must
|
||||
@@ -50,6 +65,7 @@
|
||||
* sample_xtc M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
|
||||
* sample_pick M(range) n_cand cand_idx, cand_val, params -> token
|
||||
* sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val
|
||||
* sample_logprobs M(range) n_vocab k vocab_off? logits, params -> stats
|
||||
*
|
||||
* `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per
|
||||
* sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is
|
||||
@@ -196,6 +212,16 @@ public:
|
||||
* top-k) happens between the top-k and the cuts; full logits are never gathered. */
|
||||
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
|
||||
|
||||
/* THE EMITTED TOKEN'S LOGPROBS, after the step the last build_step staged has completed on the
|
||||
* card: row `row` must have been staged for a request with SamplingParams::n_probs >= 0, and
|
||||
* `token` is what the step sampled there. Rank 0's sampler only -- it is the one that copies
|
||||
* the summary back. RAD_E_STATE for a row that was not staged for logprobs; RAD_E_INVAL, with
|
||||
* `out->token` -1, for one whose numbers are not finite -- a row with no finite logit, or a
|
||||
* token drawn where none was -- which is a number no client should be sent. */
|
||||
int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
|
||||
/* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */
|
||||
bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
|
||||
|
||||
/* The parameter rows the last build_step or build_greedy staged, and how many. What `run`
|
||||
* uploads, readable so the staging can be checked without a device behind it. */
|
||||
const DeviceSampleParams* staged_params(int64_t* n) const {
|
||||
@@ -240,6 +266,7 @@ private:
|
||||
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
||||
rad_op op_dry_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
|
||||
rad_op op_mask_ = RAD_NULL_HANDLE;
|
||||
rad_op op_topk_ = RAD_NULL_HANDLE;
|
||||
rad_op op_topp_ = RAD_NULL_HANDLE;
|
||||
@@ -250,9 +277,12 @@ private:
|
||||
rad_op op_argmax_ = RAD_NULL_HANDLE;
|
||||
rad_op op_allgather_ = RAD_NULL_HANDLE;
|
||||
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
|
||||
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* the raw distribution's summary */
|
||||
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
|
||||
|
||||
/* Device-side buffers, from the ordinary buffer plan. */
|
||||
rad_buf buf_params_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
|
||||
rad_buf buf_hist_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
|
||||
rad_buf buf_mask_ = RAD_NULL_HANDLE;
|
||||
@@ -260,9 +290,15 @@ private:
|
||||
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_gather_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
|
||||
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
||||
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
||||
|
||||
/* Pinned staging. One allocation each, at declare, never on the step path. */
|
||||
DeviceSampleParams* params_stage_ = nullptr;
|
||||
/* The late temperature's rows: params_stage_'s, with each row's temperature at 1 unless it
|
||||
* runs last. Uploaded only by a step where some row does (any_late_). */
|
||||
DeviceSampleParams* late_stage_ = nullptr;
|
||||
bool any_late_ = false;
|
||||
/* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the
|
||||
* step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not
|
||||
* have run yet; rows written into the same staging would reach that step's sampler instead.
|
||||
@@ -305,6 +341,35 @@ private:
|
||||
* request must not stop the step loop for everyone else. */
|
||||
std::vector<uint64_t> failed_;
|
||||
|
||||
/* ---------------------------------------------------------- logprobs */
|
||||
/* THE SUMMARY'S WIDTH: RAD_MAX_LOGPROBS + 1 pairs, not RAD_MAX_LOGPROBS, so that a row is 44
|
||||
* floats -- whole 16-byte words, which is what the all-gather of a split vocabulary moves (and
|
||||
* libr4d's refuses anything else). The extra pair is never reported. */
|
||||
static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
|
||||
static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
|
||||
/* WHAT UNDOING A ROW'S CHAIN NEEDS, kept from build_step for each row staged with
|
||||
* RAD_SP_LOGPROBS: the staged row itself, the temperature the candidate value carries, the
|
||||
* history window both history stages read, and the request's DRY breakers. Copied rather
|
||||
* than pointed at, because the staging is rebuilt by the next step. */
|
||||
struct LpRow {
|
||||
int64_t row = -1;
|
||||
int32_t n_top = 0;
|
||||
float temp = 1.0f; /* the candidate value is l / temp */
|
||||
DeviceSampleParams p{};
|
||||
std::vector<int32_t> hist; /* the staged history row, [0, hist_len) */
|
||||
const DryBreakers* dry = nullptr; /* lives in seqs_ for the request's lifetime */
|
||||
};
|
||||
std::vector<LpRow> lp_rows_;
|
||||
/* Rank 0's copies, written behind the pick: the summaries ([rows, W * lp_width()], W ranks
|
||||
* side by side) and the candidate planes the pick drew from. */
|
||||
float* lp_host_ = nullptr;
|
||||
int32_t* lp_ci_host_ = nullptr;
|
||||
float* lp_cv_host_ = nullptr;
|
||||
int64_t lp_lo_ = 0, lp_hi_ = 0; /* the rows copied, [lo, hi) */
|
||||
/* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
|
||||
* undone, in the reverse of the order the chain applied them. */
|
||||
float raw_logit(const LpRow& L, int32_t token, float v) const;
|
||||
|
||||
/* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request
|
||||
* because Request is a frozen struct shared across components and a unique_ptr in it would
|
||||
* make the scheduler's copies a compile error. */
|
||||
@@ -314,4 +379,13 @@ private:
|
||||
void stage_free();
|
||||
};
|
||||
|
||||
/* SPLIT-VOCABULARY SUMMARIES, MERGED: `W` ranks' `sample_logprobs` rows of `k` pairs each, side by
|
||||
* side in `st` (W * (2 + 2k) floats). Sets the shared log normaliser and fills up to `cap` of the
|
||||
* largest (id, logit) pairs over every rank, descending, ties to the lower id; returns how many. A
|
||||
* rank whose maximum or normaliser is not finite contributes nothing, nor does a pair whose logit
|
||||
* is not finite, and `*log_z` comes back NaN when no rank contributes. One rank is the same
|
||||
* arithmetic. What Sampler::logprobs_for reads a step's summaries with. */
|
||||
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
||||
int cap);
|
||||
|
||||
} /* namespace rad */
|
||||
+28
-19
@@ -495,21 +495,27 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
: a.conv_grp < b.conv_grp;
|
||||
});
|
||||
|
||||
mm_on_ = prog.encoder.modalities != 0;
|
||||
mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ media staging */
|
||||
BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
const RadEncoderDecl& e = prog_->encoder;
|
||||
n_embd_ = e.n_embd;
|
||||
enc_patches_ = e.max_patches;
|
||||
enc_dim_ = e.patch_dim;
|
||||
/* The most segments one pass can hold: a segment is at least one output row, `merge` patches. */
|
||||
enc_segs_ = e.max_patches / (e.merge > 0 ? e.merge : 1) + 1;
|
||||
/* The larger of the two encoders' passes, field by field: they run one at a time. Both write
|
||||
* rows of the model's embedding width. */
|
||||
enc_patches_ = enc_pix_elems_ = enc_segs_ = 0;
|
||||
n_embd_ = 0;
|
||||
for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) {
|
||||
if (e->modalities == 0) continue;
|
||||
n_embd_ = std::max<int64_t>(n_embd_, e->n_embd);
|
||||
enc_patches_ = std::max<int64_t>(enc_patches_, e->max_patches);
|
||||
enc_pix_elems_ = std::max<int64_t>(enc_pix_elems_, e->max_patches * e->patch_dim);
|
||||
/* The most segments one pass can hold: a segment is at least one output row. */
|
||||
enc_segs_ = std::max<int64_t>(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1);
|
||||
}
|
||||
MediaBytes m;
|
||||
m.mm = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t);
|
||||
m.pix = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t);
|
||||
m.pix = enc_pix_elems_ * (int64_t)sizeof(uint16_t);
|
||||
m.crd = 4 * enc_patches_ * (int64_t)sizeof(int32_t);
|
||||
m.cu = (enc_segs_ + 1) * (int64_t)sizeof(int32_t);
|
||||
return m;
|
||||
@@ -546,7 +552,7 @@ int BatchBuilder::alloc_media() {
|
||||
}
|
||||
if (rad_event_create_as(&mm_ev_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0) return RAD_E_DEVICE;
|
||||
RAD_INFO("media staging: %s a rank for a step's encoder rows and %s for an encoder pass of "
|
||||
"%lld patches", humanb(mm_bytes).c_str(),
|
||||
"up to %lld patches", humanb(mm_bytes).c_str(),
|
||||
humanb(pix_bytes + crd_bytes + cu_bytes).c_str(), (long long)enc_patches_);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1272,24 +1278,27 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the encoder pass */
|
||||
const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& parts, int step) {
|
||||
if (!mm_on_ || parts.empty()) return nullptr;
|
||||
const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc) {
|
||||
if (!mm_on_ || parts.empty() || enc.modalities == 0) return nullptr;
|
||||
const int64_t enc_dim = enc.patch_dim;
|
||||
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
|
||||
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
|
||||
enc_cu_host_[0] = 0;
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
const int64_t seg_p = (int64_t)it.grid_h * it.grid_w;
|
||||
const int64_t np = seg_p * p.n_seg;
|
||||
if (it.patch_dim != enc_dim_ || n_patch + np > enc_patches_ ||
|
||||
n_seg + p.n_seg > enc_segs_ || p.seg0 + p.n_seg > it.n_seg) {
|
||||
if (it.patch_dim != enc_dim || n_patch + np > enc.max_patches ||
|
||||
n_seg + p.n_seg > max_segs || p.seg0 + p.n_seg > it.n_seg) {
|
||||
RAD_ERR("encoder pass: %lld patches in %lld segments do not fit the declared pass of "
|
||||
"%lld patches of %lld elements", (long long)(n_patch + np),
|
||||
(long long)(n_seg + p.n_seg), (long long)enc_patches_, (long long)enc_dim_);
|
||||
(long long)(n_seg + p.n_seg), (long long)enc.max_patches, (long long)enc_dim);
|
||||
return nullptr;
|
||||
}
|
||||
std::memcpy(enc_pix_host_ + n_patch * enc_dim_,
|
||||
it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim_,
|
||||
(size_t)(np * enc_dim_) * sizeof(uint16_t));
|
||||
std::memcpy(enc_pix_host_ + n_patch * enc_dim,
|
||||
it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim,
|
||||
(size_t)(np * enc_dim) * sizeof(uint16_t));
|
||||
n_patch += np;
|
||||
for (int32_t q = 0; q < p.n_seg; ++q) {
|
||||
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
|
||||
@@ -1316,7 +1325,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RadStream st = ranks_[r].stream;
|
||||
if (rad_memcpy_async(enc_pix_dev_[r], enc_pix_host_,
|
||||
n_patch * enc_dim_ * (int64_t)sizeof(uint16_t), st) < 0 ||
|
||||
n_patch * enc_dim * (int64_t)sizeof(uint16_t), st) < 0 ||
|
||||
rad_memcpy_async(enc_coord_dev_[r], enc_coord_host_,
|
||||
4 * n_patch * (int64_t)sizeof(int32_t), st) < 0 ||
|
||||
rad_memcpy_async(enc_cu_dev_[r], enc_cu_host_,
|
||||
@@ -1333,7 +1342,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
B.step = step;
|
||||
B.n_kv_groups = (int)o.kv[r].size();
|
||||
B.kv = o.kv[r].data();
|
||||
B.enc = 1;
|
||||
B.enc = (int32_t)enc.modalities;
|
||||
B.enc_n_patch = n_patch;
|
||||
B.enc_pixels = enc_pix_dev_[r];
|
||||
B.enc_coord = static_cast<const int32_t*>(enc_coord_dev_[r]);
|
||||
|
||||
+8
-5
@@ -168,9 +168,11 @@ public:
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step);
|
||||
/* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts,
|
||||
* and its modalities are RadBatch::enc. */
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc);
|
||||
bool has_encoder() const { return mm_on_; }
|
||||
int64_t encoder_patches() const { return enc_patches_; }
|
||||
|
||||
|
||||
private:
|
||||
@@ -366,9 +368,10 @@ private:
|
||||
uint16_t* mm_host_ = nullptr;
|
||||
RadEvent mm_ev_ = nullptr;
|
||||
bool mm_ev_live_ = false;
|
||||
/* ...and the encoder's inputs: patches, their coordinates and the segment boundaries, the
|
||||
* largest pass the plugin declared. One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_dim_ = 0, enc_segs_ = 0;
|
||||
/* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized
|
||||
* for the larger of the passes the plugin declared (a vision tower's and an audio encoder's
|
||||
* run one at a time and share it). One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0;
|
||||
std::vector<void*> enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
|
||||
uint16_t* enc_pix_host_ = nullptr;
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
|
||||
@@ -374,7 +374,7 @@ struct PCBinding final : IPrefixCache {
|
||||
/* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by --
|
||||
* so the tiers' session view and the checkpoint index are talking about one thing. */
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label);
|
||||
}
|
||||
/* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
|
||||
* now, and says whether any landed. Called on the step thread under the scheduler's lock. */
|
||||
|
||||
@@ -177,6 +177,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
if (!r) return RAD_E_INVAL;
|
||||
if (r->prompt.empty()) return RAD_E_INVAL;
|
||||
if (by_id_.count(r->id)) return RAD_E_DUPLICATE;
|
||||
/* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a
|
||||
* step could never be admitted and would wait for good. */
|
||||
if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
|
||||
/* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step
|
||||
* that is never coming, so the sink is failed here -- it is the one thing the caller is
|
||||
* listening to -- and the refusal says why. */
|
||||
@@ -900,6 +903,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
int64_t target = s.seq_len();
|
||||
int64_t ckpt = -1;
|
||||
int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt);
|
||||
/* The whole input or nothing this step (Request::embed): the next step starts with a whole
|
||||
* budget, and add_locked refused an input no budget holds. */
|
||||
if (r.embed && want < target - (int64_t)r.n_computed) want = 0;
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL;
|
||||
@@ -942,6 +948,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
r.state = ReqState::Running;
|
||||
s.running = true;
|
||||
server::sink_admitted(r.sink);
|
||||
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(), r.n_cached);
|
||||
s.sched_tokens = (int32_t)want;
|
||||
s.pending_ckpt = ckpt;
|
||||
++m_.admitted;
|
||||
@@ -1581,6 +1588,10 @@ int Scheduler::commit(const StepResult& res) {
|
||||
bool eos = res.eos && res.eos[i] && !r.ignore_eos;
|
||||
|
||||
bool overflowed = false;
|
||||
/* A token whose logprobs the engine could not compute (TokenLogprobs::token -1) for a
|
||||
* request that asked for them: the request fails with the reason rather than send that
|
||||
* token without the numbers it was asked for, and nothing after it is sent. */
|
||||
bool lp_failed = false;
|
||||
|
||||
/* THE SNAPSHOT THE ENGINE JUST TOOK IS NOW READABLE. Marking it here rather than at
|
||||
* reservation is the difference between a checkpoint and a promise: reserve_checkpoint
|
||||
@@ -1596,14 +1607,24 @@ int Scheduler::commit(const StepResult& res) {
|
||||
if (e.is_prefill) {
|
||||
r.n_computed += e.n_tokens;
|
||||
step_prefill_tok_ += e.n_tokens;
|
||||
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
|
||||
r.n_cached);
|
||||
/* Once, when the prompt is fully placed: the admission accounting the usage block
|
||||
* 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]);
|
||||
const TokenLogprobs* lp =
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i]] : nullptr;
|
||||
if (lp && lp->token < 0) lp_failed = true;
|
||||
else overflowed = !server::sink_push(r.sink, res.token[i], lp);
|
||||
/* The conv window absorbed this chunk; the cursor advances by one committed
|
||||
* position, exactly as it does in decode. */
|
||||
s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
|
||||
@@ -1651,15 +1672,21 @@ int Scheduler::commit(const StepResult& res) {
|
||||
/* AND THE CONTEXT BOUNDS IT WHATEVER max_tokens SAYS, including "no limit": a
|
||||
* sequence may not grow past the positions this deployment can address. */
|
||||
if (ctx_limit_ > 0 && ctx_limit_ - s.seq_len() < room) room = ctx_limit_ - s.seq_len();
|
||||
auto emit = [&](int32_t t) {
|
||||
/* `j` is the token's place in the step's emission: its logprobs row is the entry's
|
||||
* j-th, when the request asked for them. */
|
||||
auto emit = [&](int32_t t, int32_t j) {
|
||||
if (room <= 0) return;
|
||||
--room;
|
||||
if (!s.first_tok_us) s.first_tok_us = mono_us();
|
||||
r.output.push_back(t);
|
||||
if (!server::sink_push(r.sink, t)) overflowed = true;
|
||||
const TokenLogprobs* lp =
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i] + j] : nullptr;
|
||||
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
|
||||
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
|
||||
};
|
||||
for (int32_t j = 0; j < a; ++j) emit(s.draft[j]);
|
||||
if (res.token) emit(res.token[i]);
|
||||
for (int32_t j = 0; j < a; ++j) emit(s.draft[j], j);
|
||||
if (res.token) emit(res.token[i], a);
|
||||
r.n_computed = valid;
|
||||
step_decode_tok_ += 1 + a;
|
||||
|
||||
@@ -1709,6 +1736,11 @@ int Scheduler::commit(const StepResult& res) {
|
||||
close_request(s, ReqState::Failed, "sink_overflow", carried);
|
||||
++m_.failed;
|
||||
completed_.push_back(r.id);
|
||||
} else if (lp_failed) {
|
||||
close_request(s, ReqState::Failed, "logprobs", carried, true, RAD_E_STATE,
|
||||
"the logprobs of a token it generated could not be computed");
|
||||
++m_.failed;
|
||||
completed_.push_back(r.id);
|
||||
} else if (server::sink_cancelled(r.sink)) {
|
||||
/* The client hung up. Spec §14: the blocks go back now rather than at the end of a
|
||||
* generation nobody will read. */
|
||||
|
||||
@@ -176,6 +176,10 @@ public:
|
||||
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
|
||||
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
|
||||
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
|
||||
/* LOGPROBS, null on a step where no request asked: entry i's j-th emitted token (its
|
||||
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
|
||||
const TokenLogprobs* lp = nullptr;
|
||||
const int32_t* first_row = nullptr; /* [n_seq] */
|
||||
};
|
||||
|
||||
/* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it,
|
||||
@@ -301,11 +305,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
|
||||
|
||||
+33
-5
@@ -142,6 +142,7 @@ public:
|
||||
SessionStat o;
|
||||
o.id = s.id;
|
||||
o.model = s.model;
|
||||
o.label = s.label;
|
||||
o.n_tokens = s.n_tokens;
|
||||
o.bytes = s.bytes;
|
||||
o.idle_s = now > s.last_used_ns ? (double)(now - s.last_used_ns) / 1e9 : 0.0;
|
||||
@@ -319,6 +320,7 @@ public:
|
||||
std::string push(int32_t t) override { return d_.push(t); }
|
||||
std::string flush() override { return d_.flush(); }
|
||||
bool stopped() const override { return d_.stopped(); }
|
||||
std::string stop_hit() const override { return d_.stop_hit(); }
|
||||
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
|
||||
private:
|
||||
Detokenizer d_;
|
||||
@@ -376,6 +378,14 @@ public:
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return utf8_sanitize(vocab_->text(id));
|
||||
}
|
||||
std::string token_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/true);
|
||||
}
|
||||
std::string reply_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/false);
|
||||
}
|
||||
|
||||
std::unique_ptr<IDetokenizer> detokenizer(
|
||||
const std::vector<std::string>& stops,
|
||||
@@ -549,7 +559,21 @@ public:
|
||||
bool supports_tools() const override { return t_.caps().tools; }
|
||||
bool supports_reasoning() const override { return t_.caps().preserve_reasoning; }
|
||||
std::string tool_refusal() const override { return tool_refusal_; }
|
||||
const std::string& source() const { return t_.source(); }
|
||||
std::string source() const override { return t_.source(); }
|
||||
/* Under llama-server's names (its chat_template_caps), from the same probe. */
|
||||
std::string caps() const override {
|
||||
const ChatCaps& c = t_.caps();
|
||||
json o;
|
||||
o["supports_tools"] = c.tools;
|
||||
o["supports_tool_calls"] = c.tool_calls;
|
||||
o["supports_system_role"] = c.system_role;
|
||||
o["supports_parallel_tool_calls"] = c.parallel_tool_calls;
|
||||
o["supports_preserve_reasoning"] = c.preserve_reasoning;
|
||||
o["supports_string_content"] = c.string_content;
|
||||
o["supports_typed_content"] = c.typed_content;
|
||||
o["supports_object_arguments"] = c.object_arguments;
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
|
||||
ChatRender* out, std::string* why) const override {
|
||||
@@ -559,6 +583,7 @@ public:
|
||||
o.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
o.tool_choice = opt.tool_choice;
|
||||
o.reasoning_format = opt.reasoning_format;
|
||||
o.continue_final = opt.continue_final;
|
||||
o.grammar = opt.grammar;
|
||||
o.json_schema = opt.json_schema;
|
||||
o.template_kwargs = opt.template_kwargs;
|
||||
@@ -698,14 +723,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:
|
||||
|
||||
+194
-27
@@ -1,6 +1,7 @@
|
||||
/* core/server/admin.cpp -- vLLM's non-generation endpoints.
|
||||
/* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
|
||||
*
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache.
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
|
||||
* /props.
|
||||
*
|
||||
* Separate from server.cpp because none of it touches the step path: no admission, no Sink, no
|
||||
* cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered
|
||||
@@ -8,15 +9,17 @@
|
||||
* streaming lifetime would make that file harder to read for no shared code at all.
|
||||
*
|
||||
* WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
|
||||
* /rerank (an embedding or cross-encoder model, which this engine does not load), /sleep, /wake_up
|
||||
* /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
|
||||
* and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and
|
||||
* /v1/responses (a stateful conversation store, which is a component and not an endpoint). Each
|
||||
* would be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
|
||||
* Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
|
||||
* component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
|
||||
* be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
*/
|
||||
#include "server.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -143,8 +146,61 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
auto msgs = b.find("messages");
|
||||
auto prom = b.find("prompt");
|
||||
if (msgs != b.end() && prom != b.end())
|
||||
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"), req.peer);
|
||||
auto cont = b.find("content");
|
||||
if ((msgs != b.end()) + (prom != b.end()) + (cont != b.end()) > 1)
|
||||
return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
|
||||
req.peer);
|
||||
|
||||
/* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
|
||||
* as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
|
||||
* control tokens recognised), answered under its own key, `tokens`, as ids or with
|
||||
* `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
|
||||
* llama-server sends it. */
|
||||
if (cont != b.end()) {
|
||||
const bool add_special = get_bool_or(b, "add_special", false);
|
||||
const bool parse_special = get_bool_or(b, "parse_special", true);
|
||||
const bool with_pieces = get_bool_or(b, "with_pieces", false);
|
||||
auto take = [&](const json& v, bool first) -> bool {
|
||||
if (v.is_string()) {
|
||||
const std::vector<int32_t> t =
|
||||
deps_.tok->encode(v.get<std::string>(), first && add_special, parse_special);
|
||||
toks.insert(toks.end(), t.begin(), t.end());
|
||||
return true;
|
||||
}
|
||||
int32_t id = 0;
|
||||
if (!v.is_number_integer() || !token_id(v, &id)) return false;
|
||||
toks.push_back(id);
|
||||
return true;
|
||||
};
|
||||
bool ok = true;
|
||||
if (cont->is_array()) {
|
||||
bool first = true;
|
||||
for (const json& v : *cont) { ok = ok && take(v, first); first = false; }
|
||||
} else {
|
||||
ok = cont->is_string() && take(*cont, true);
|
||||
}
|
||||
if (!ok)
|
||||
return error_response(err_bad("content", "must be a string, or an array of strings "
|
||||
"and token ids"), req.peer);
|
||||
json arr = json::array();
|
||||
for (int32_t t : toks) {
|
||||
if (!with_pieces) { arr.push_back(t); continue; }
|
||||
const std::string piece = deps_.tok->token_bytes(t);
|
||||
json e;
|
||||
e["id"] = t;
|
||||
/* A piece that is not whole UTF-8 goes as its bytes, 0-255, as llama-server sends it. */
|
||||
if (utf8_valid_prefix(piece) == piece.size()) e["piece"] = piece;
|
||||
else e["piece"] = std::vector<int>((const unsigned char*)piece.data(),
|
||||
(const unsigned char*)piece.data() + piece.size());
|
||||
arr.push_back(std::move(e));
|
||||
}
|
||||
json o;
|
||||
o["tokens"] = std::move(arr);
|
||||
o["count"] = (int64_t)toks.size();
|
||||
o["max_model_len"] = opt_.max_ctx;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
if (msgs != b.end()) {
|
||||
if (!deps_.chat)
|
||||
@@ -227,8 +283,113 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
toks.push_back(id);
|
||||
}
|
||||
|
||||
/* `prompt` is vLLM's key and `content` llama-server's, for the same text. */
|
||||
json o;
|
||||
o["prompt"] = deps_.tok->decode(toks);
|
||||
o["content"] = o["prompt"];
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
/* ================================================================== /props */
|
||||
/* llama-server's /props, for the clients built against it: a front-end that sizes its context
|
||||
* from default_generation_settings.n_ctx, shows an image button when modalities.vision is set,
|
||||
* and reads what a request that sends no sampler fields inherits. /server_info says all of it and
|
||||
* more, but nothing written for llama-server knows to ask there.
|
||||
*
|
||||
* Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
|
||||
* per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
|
||||
* n_ctx means to the clients reading it; left out when the server does not know its length. */
|
||||
HttpResponse Server::handle_props(const HttpRequest&) {
|
||||
const SamplingParams& sp = opt_.default_sampling;
|
||||
/* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
|
||||
* missing. The samplers this server does not run are reported at their off values -- which
|
||||
* is what it serves -- and `samplers` is its own order, temperature first. */
|
||||
const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
|
||||
json params;
|
||||
params["n_predict"] = n_predict;
|
||||
params["max_tokens"] = n_predict;
|
||||
params["seed"] = -1;
|
||||
params["temperature"] = sp.temp;
|
||||
params["dynatemp_range"] = 0.0;
|
||||
params["dynatemp_exponent"] = 1.0;
|
||||
params["top_k"] = sp.top_k;
|
||||
params["top_p"] = sp.top_p;
|
||||
params["min_p"] = sp.min_p;
|
||||
params["top_n_sigma"] = -1.0;
|
||||
params["typical_p"] = sp.typical_p;
|
||||
params["typ_p"] = sp.typical_p;
|
||||
params["xtc_probability"] = sp.xtc_probability;
|
||||
params["xtc_threshold"] = sp.xtc_threshold;
|
||||
params["repeat_last_n"] = sp.penalty_last_n;
|
||||
params["repeat_penalty"] = sp.rep_penalty;
|
||||
params["presence_penalty"] = sp.pres_penalty;
|
||||
params["frequency_penalty"] = sp.freq_penalty;
|
||||
params["dry_multiplier"] = sp.dry_multiplier;
|
||||
params["dry_base"] = sp.dry_base;
|
||||
params["dry_allowed_length"] = sp.dry_allowed_length;
|
||||
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
|
||||
params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
|
||||
? std::vector<std::string>{ "\n", ":", "\"", "*" }
|
||||
: sp.dry_seq_breakers;
|
||||
params["mirostat"] = 0;
|
||||
params["mirostat_tau"] = 5.0;
|
||||
params["mirostat_eta"] = 0.1;
|
||||
params["stop"] = json::array();
|
||||
params["n_keep"] = 0;
|
||||
params["n_discard"] = 0;
|
||||
params["ignore_eos"] = false;
|
||||
params["stream"] = true;
|
||||
params["logit_bias"] = json::array();
|
||||
params["n_probs"] = 0;
|
||||
params["min_keep"] = 0;
|
||||
params["grammar"] = "";
|
||||
params["grammar_lazy"] = false;
|
||||
params["grammar_triggers"] = json::array();
|
||||
params["preserved_tokens"] = json::array();
|
||||
params["chat_format"] = "";
|
||||
params["reasoning_format"] = "auto";
|
||||
params["reasoning_in_content"] = false;
|
||||
params["generation_prompt"] = "";
|
||||
params["samplers"] = { "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p",
|
||||
"xtc" };
|
||||
params["backend_sampling"] = false;
|
||||
params["timings_per_token"] = false;
|
||||
params["post_sampling_probs"] = false;
|
||||
params["lora"] = json::array();
|
||||
|
||||
json gen;
|
||||
if (opt_.max_ctx > 0) gen["n_ctx"] = opt_.max_ctx;
|
||||
gen["params"] = std::move(params);
|
||||
|
||||
json modal;
|
||||
modal["vision"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
modal["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
modal["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
|
||||
json o;
|
||||
o["default_generation_settings"] = std::move(gen);
|
||||
o["total_slots"] = opt_.max_seqs;
|
||||
o["model_alias"] = opt_.model_id;
|
||||
o["model_path"] = opt_.model_path;
|
||||
o["modalities"] = std::move(modal);
|
||||
o["endpoint_slots"] = false;
|
||||
o["endpoint_props"] = false;
|
||||
o["endpoint_metrics"] = true;
|
||||
o["chat_template"] = deps_.chat ? deps_.chat->source() : std::string();
|
||||
o["chat_template_caps"] = json::parse(deps_.chat ? deps_.chat->caps() : std::string("{}"),
|
||||
nullptr, false);
|
||||
std::string bos, eos;
|
||||
if (deps_.tok) {
|
||||
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
|
||||
if (v.bos >= 0) bos = deps_.tok->piece(v.bos);
|
||||
if (v.eos >= 0) eos = deps_.tok->piece(v.eos);
|
||||
}
|
||||
o["bos_token"] = bos;
|
||||
o["eos_token"] = eos;
|
||||
o["build_info"] = "radiance " + opt_.version;
|
||||
o["role"] = "model";
|
||||
o["is_sleeping"] = false;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
@@ -262,6 +423,30 @@ HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) {
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
/* ================================================================== capabilities */
|
||||
json Server::capabilities() const {
|
||||
json caps;
|
||||
caps["chat"] = deps_.chat != nullptr;
|
||||
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
|
||||
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
|
||||
caps["grammar"] = deps_.grammar != nullptr;
|
||||
caps["embedding"] = deps_.embed != nullptr;
|
||||
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
return caps;
|
||||
}
|
||||
|
||||
/* ================================================================== /server_info */
|
||||
/* vLLM returns the repr() of its config object, which is a Python string a client can only print.
|
||||
* This returns the same information as JSON, in two halves: what the SERVER decided, which is
|
||||
@@ -288,25 +473,7 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
srv["uptime_s"] = unix_now() - started_at_;
|
||||
srv["in_flight"] = in_flight_.load(std::memory_order_relaxed);
|
||||
|
||||
json caps;
|
||||
caps["chat"] = deps_.chat != nullptr;
|
||||
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
|
||||
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
|
||||
caps["grammar"] = deps_.grammar != nullptr;
|
||||
caps["embedding"] = deps_.embed != nullptr;
|
||||
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
json caps = capabilities();
|
||||
|
||||
/* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each
|
||||
* field, so a client can read off exactly what leaving one out means on this deployment. */
|
||||
|
||||
@@ -59,6 +59,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
json e;
|
||||
e["id"] = s.id;
|
||||
e["model"] = s.model;
|
||||
if (!s.label.empty()) e["label"] = s.label;
|
||||
e["tokens"] = s.n_tokens;
|
||||
e["bytes"] = s.bytes;
|
||||
e["idle_s"] = s.idle_s;
|
||||
@@ -681,6 +682,7 @@ th + th, td + td { padding-left:14px; }
|
||||
/* Fixed, so the tier column starts at one x in both tables. */
|
||||
.stbl .ret { width:340px; }
|
||||
.sid { font-weight:500; }
|
||||
.slabel { margin-left:8px; color:var(--faint); }
|
||||
.mv { font:500 10px/1 var(--ui); color:var(--faint); border:1px solid var(--rule);
|
||||
border-radius:4px; padding:2px 5px; margin-left:6px; }
|
||||
/* WHERE IT IS, by share of the conversation's context, one colour a tier. A conversation is
|
||||
@@ -2850,6 +2852,8 @@ function sessRow(r, hybrid, manyModels) {
|
||||
const tr = el("tr");
|
||||
const id = tr.appendChild(el("td"));
|
||||
id.appendChild(el("span", "sid", "#" + r.id));
|
||||
/* The client's own name for the conversation (`session_id`), when it sent one. */
|
||||
if (r.label) id.appendChild(el("span", "slabel", r.label));
|
||||
if (r.moving) id.appendChild(el("span", "mv", "moving"));
|
||||
if (manyModels) tr.appendChild(el("td", "l", r.model || DASH));
|
||||
tr.appendChild(el("td", null, cnt3(r.tokens) + " tok"));
|
||||
|
||||
+32
-6
@@ -363,10 +363,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
* leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the
|
||||
* chat template. This does not. */
|
||||
const std::string& p = hreq.path;
|
||||
if (!api_key.empty() && p != "/health" && p != "/ping" && p != "/" && p != "/dashboard") {
|
||||
std::string got = hreq.get_header_value("Authorization");
|
||||
const std::string want = "Bearer " + api_key;
|
||||
if (got != want) {
|
||||
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
|
||||
p != "/dashboard") {
|
||||
/* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
|
||||
* llama-server takes as well; either one carrying the key is enough. */
|
||||
const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
|
||||
hreq.get_header_value("X-Api-Key") == api_key;
|
||||
if (!ok) {
|
||||
/* Said like every other refusal (Server::error_response), which this one never
|
||||
* reaches: the gate answers before the router does. */
|
||||
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
|
||||
@@ -453,15 +456,38 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
bridge(q, std::move(body), s);
|
||||
});
|
||||
}
|
||||
svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) {
|
||||
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
|
||||
* the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
|
||||
* that does not list one fails the request before it is sent. A wildcard would not do: CORS
|
||||
* never lets `*` stand for Authorization, so the requested list is echoed back. */
|
||||
svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (cors) {
|
||||
const std::string asked = req.get_header_value("Access-Control-Request-Headers");
|
||||
res.set_header("Access-Control-Allow-Origin", "*");
|
||||
res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
res.set_header("Access-Control-Allow-Headers",
|
||||
asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
|
||||
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.set_header("Access-Control-Max-Age", "86400");
|
||||
}
|
||||
res.status = 204;
|
||||
});
|
||||
|
||||
/* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
|
||||
* other refusal this server makes is an error object, and a client reading one finds an
|
||||
* empty 404 unparseable; so an error with no body gets one here. A response that already
|
||||
* carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
|
||||
svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
|
||||
if (cors) res.set_header("Access-Control-Allow-Origin", "*");
|
||||
const std::string type = res.status == 404 ? "not_found_error"
|
||||
: res.status >= 500 ? "internal_server_error"
|
||||
: "invalid_request_error";
|
||||
const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
|
||||
: httplib::status_message(res.status);
|
||||
res.set_content(error_body(type.c_str(), what), "application/json");
|
||||
return httplib::Server::HandlerResponse::Handled;
|
||||
});
|
||||
|
||||
/* Bound once: asking for a named port and then for any port would leave the first socket
|
||||
* bound and unused. */
|
||||
const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
|
||||
|
||||
+52
-4
@@ -160,6 +160,7 @@ struct SchedMetrics {
|
||||
struct SessionStat {
|
||||
uint64_t id = 0;
|
||||
std::string model; /* the container it was built against */
|
||||
std::string label; /* the client's name for it (`session_id`), or "" */
|
||||
int64_t n_tokens = 0;
|
||||
int64_t bytes = 0;
|
||||
double idle_s = 0; /* since its last turn */
|
||||
@@ -307,6 +308,8 @@ public:
|
||||
* search text that can no longer contain what it is searching for, and the generation would
|
||||
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
|
||||
virtual bool stopped() const { return false; }
|
||||
/* The stop string that stopped it, "" when none has. */
|
||||
virtual std::string stop_hit() const { return std::string(); }
|
||||
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
|
||||
* defer_stops_until): the reply starts inside its reasoning block. */
|
||||
virtual void defer_stops_until(const std::string& /*marker*/) {}
|
||||
@@ -349,6 +352,15 @@ public:
|
||||
* turned the flag on to see. "" when the id is out of range. */
|
||||
virtual std::string piece(int32_t /*id*/) const { return std::string(); }
|
||||
|
||||
/* THE BYTES ONE ID DECODES TO, unsanitised, control tokens rendered: llama-server's
|
||||
* `with_pieces`. Not necessarily whole UTF-8 -- a byte-fallback or a split multi-byte
|
||||
* character is a fragment -- so the caller checks before putting it in a JSON string. */
|
||||
virtual std::string token_bytes(int32_t /*id*/) const { return std::string(); }
|
||||
/* The bytes one id adds to a REPLY: token_bytes with control tokens rendered as nothing, as
|
||||
* the decoder renders them -- what a logprobs entry spells the token as, so the entries'
|
||||
* texts add up to the reply, as llama-server's do. */
|
||||
virtual std::string reply_bytes(int32_t id) const { return token_bytes(id); }
|
||||
|
||||
/* One incremental decoder per in-flight generation. It is made by the tokenizer rather than
|
||||
* default-constructed by the caller, because it needs the vocabulary to decode anything.
|
||||
* `stops` is passed down because core/text's Detokenizer can suppress a stop string that
|
||||
@@ -382,6 +394,9 @@ struct ChatRenderOptions {
|
||||
std::string grammar; /* the caller's GBNF, or "" */
|
||||
std::string json_schema; /* a response_format schema, as JSON text, or "" */
|
||||
std::string reasoning_format = "auto";
|
||||
/* ASSISTANT PREFILL: continue the conversation's last (assistant) message rather than open a
|
||||
* new turn. "" off, else llama.cpp's "auto", "content" or "reasoning_content". */
|
||||
std::string continue_final;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
/* A render whose refusal is an answer and not an error -- the startup probes of what the
|
||||
* template takes -- so the template's refusal is not logged. */
|
||||
@@ -438,6 +453,13 @@ public:
|
||||
* request that sends tools is refused with this sentence rather than answered with calls
|
||||
* nobody can read back. */
|
||||
virtual std::string tool_refusal() const { return std::string(); }
|
||||
|
||||
/* THE TEMPLATE'S SOURCE TEXT and what the capability probe found in it, for /props: what
|
||||
* llama-server reports as `chat_template` and `chat_template_caps`, so a client built against
|
||||
* it can render a prompt the way this server will. "" when unknown; the caps are a JSON
|
||||
* object as text, "{}" when unknown. */
|
||||
virtual std::string source() const { return std::string(); }
|
||||
virtual std::string caps() const { return "{}"; }
|
||||
};
|
||||
|
||||
/* A reply taken apart: what core/text's reply parser gives back once the reply is complete. */
|
||||
@@ -515,13 +537,32 @@ public:
|
||||
|
||||
/* ================================================================== optional backends */
|
||||
|
||||
/* /v1/embeddings. Absent, the endpoint is 501 naming that this model was not loaded with an
|
||||
* embedding head -- not an empty 200. */
|
||||
/* /v1/embeddings: WHAT THE LOADED MODEL EMBEDS, present only when it is an embedding model
|
||||
* (rad_declare_pooled). Absent, the endpoint is 501 naming that -- not an empty 200.
|
||||
*
|
||||
* The vectors themselves come through the scheduler like any other request: the server submits
|
||||
* one Request a input with Request::embed set, and each finishes at its one step with its pooled
|
||||
* vector in its sink (Sink::embedding). So batching, admission, media encoding and cancellation
|
||||
* are the scheduler's, exactly as they are for a completion. */
|
||||
class IEmbedder {
|
||||
public:
|
||||
virtual ~IEmbedder() = default;
|
||||
virtual int embed(const std::vector<int32_t>& tokens, std::vector<float>& out) = 0;
|
||||
/* The width of a pooled vector. */
|
||||
virtual int64_t dim() const = 0;
|
||||
/* The longest input one step carries: an input is never split, so a longer one is refused. */
|
||||
virtual int64_t max_input() const = 0;
|
||||
/* THE MODEL'S NAMED PROMPTS (sentence-transformers' `prompts`): the text a `prompt_name` puts
|
||||
* in front of an input -- "query" -> "task: search result | query: ". False when the model
|
||||
* states no prompt of that name. */
|
||||
virtual bool prompt(const std::string& name, std::string* text) const {
|
||||
(void)name; (void)text;
|
||||
return false;
|
||||
}
|
||||
/* The prompt an input takes when the request names none, "" for none. */
|
||||
virtual std::string default_prompt() const { return std::string(); }
|
||||
/* The template a `messages` input renders through -- the model's chat template -- or null
|
||||
* when it has none. */
|
||||
virtual IChatTemplate* message_template() const { return nullptr; }
|
||||
};
|
||||
|
||||
/* Multimodal preprocessing (spec §11). The server pulls the bytes out of a content part; the
|
||||
@@ -536,6 +577,13 @@ enum class MediaKind { Image, Video, Audio };
|
||||
* the templates are the same templates. */
|
||||
#define RAD_MEDIA_MARKER "<__media__>"
|
||||
|
||||
/* WHAT A REQUEST ASKED OF ITS MEDIA, beside the bytes. Zero is the server's default. */
|
||||
struct MediaOpts {
|
||||
/* Soft tokens (encoder output rows) an image may become, for a processor that sizes images
|
||||
* by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */
|
||||
int32_t image_tokens = 0;
|
||||
};
|
||||
|
||||
class IMultimodal {
|
||||
public:
|
||||
virtual ~IMultimodal() = default;
|
||||
@@ -543,7 +591,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;
|
||||
};
|
||||
|
||||
|
||||
+2149
-356
File diff suppressed because it is too large.
Load diff
+243
-29
@@ -8,12 +8,12 @@
|
||||
* exception crossing the transport is a connection closed with no body, which is the least
|
||||
* diagnosable thing a client can be handed.
|
||||
*
|
||||
* A parameter we do not support is a 400 that names it. Not a silent ignore. A client that sends
|
||||
* `logit_bias` and gets a 200 has been told its bias was applied, and the resulting bug report
|
||||
* ("the model ignores my bias") is unanswerable from the server side. The cost of strictness is
|
||||
* that a client sending a field we have not heard of gets a 400 rather than a shrug; the
|
||||
* allowlist below is where the genuinely inert OpenAI metadata fields (`user`, `store`, ...)
|
||||
* are named, so that cost falls only on fields that actually mean something.
|
||||
* A parameter that would change the answer and is not served is a 400 that names it, not a
|
||||
* silent ignore: a client that sends a `logit_bias` and gets a 200 has been told its bias was
|
||||
* applied, and the bug report that follows ("the model ignores my bias") is unanswerable from the
|
||||
* server side. Such a field is accepted at its "off" value, which is what llama.cpp-built clients
|
||||
* send on every request. A field this server has never heard of is ignored, as llama.cpp and vLLM
|
||||
* ignore it (oai.cpp, key vetting).
|
||||
*/
|
||||
#pragma once
|
||||
#include "iface.h"
|
||||
@@ -40,6 +40,11 @@ struct ApiError {
|
||||
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
|
||||
* envelope, so a client can retry with one rather than parse the sentence. */
|
||||
std::vector<std::string> supported;
|
||||
/* A prompt the context cannot hold: its length and the context's, under llama-server's names,
|
||||
* so a client that compacts its history on overflow reads the numbers rather than the
|
||||
* sentence. -1 leaves them out. */
|
||||
int64_t n_prompt_tokens = -1;
|
||||
int64_t n_ctx = -1;
|
||||
|
||||
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
|
||||
};
|
||||
@@ -60,6 +65,11 @@ ApiError err_overloaded(const std::string& why);
|
||||
|
||||
enum class Endpoint { Chat, Completion, Embedding };
|
||||
|
||||
/* WHICH API A CHAT REQUEST CAME IN THROUGH, and so which shape its answer goes out in. Every shape
|
||||
* is parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
|
||||
* served by the same path; only the bytes on the wire differ. */
|
||||
enum class ApiShape { OpenAI, Anthropic, Responses, LlamaNative };
|
||||
|
||||
struct PromptInput {
|
||||
std::vector<int32_t> tokens;
|
||||
std::string text; /* the rendered prompt; needed for `echo` and for the logs */
|
||||
@@ -73,13 +83,36 @@ struct OaiRequest {
|
||||
std::string id; /* "chatcmpl-..." / "cmpl-..." */
|
||||
int64_t created = 0; /* unix seconds */
|
||||
|
||||
ApiShape shape = ApiShape::OpenAI;
|
||||
bool stream = false;
|
||||
bool include_usage = false; /* stream_options.include_usage */
|
||||
/* llama.cpp's streaming extras: `timings` on every chunk, not only the last; and
|
||||
* `prompt_progress` chunks while the prompt is read. */
|
||||
bool timings_per_token = false;
|
||||
bool return_progress = false;
|
||||
/* The conversation as the client names it (OpenRouter's `session_id`), "" when it names none:
|
||||
* a label on /sessions, nothing else. */
|
||||
std::string session_label;
|
||||
/* The build, as OpenAI's `system_fingerprint` and llama.cpp's own: what produced the reply. */
|
||||
std::string system_fingerprint;
|
||||
|
||||
int n = 1;
|
||||
SamplingParams sp;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
/* Of `stop`, how many the client sent; the rest are the chat format's own end-of-turn
|
||||
* markers. A reply cut on one of the first is Anthropic's `stop_sequence`, on the rest its
|
||||
* `end_turn`. */
|
||||
size_t n_client_stops = 0;
|
||||
/* The assistant text a continued conversation ends in (assistant prefill), "" otherwise. The
|
||||
* OpenAI shape answers the whole message, as llama-server does; Anthropic's answers what
|
||||
* follows it, as Anthropic's API does. */
|
||||
std::string continued;
|
||||
/* The Responses API's request fields its response object echoes (instructions, tools,
|
||||
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
|
||||
std::string echo_json;
|
||||
/* llama-server's native /completion: the generated token ids beside the text. */
|
||||
bool return_tokens = false;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
|
||||
std::string stops_after;
|
||||
@@ -94,6 +127,9 @@ struct OaiRequest {
|
||||
bool want_logprobs = false;
|
||||
|
||||
bool tools_present = false;
|
||||
/* OpenAI's deprecated functions API: the request sent `functions`, so the reply carries its
|
||||
* call as `function_call` (one at most) and ends in finish_reason "function_call". */
|
||||
bool legacy_functions = false;
|
||||
/* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
|
||||
* a chat request carried, and the last user message's opening (one line, bounded) that the
|
||||
* debug level prints so a log line can be matched to what was typed. Completion requests
|
||||
@@ -114,6 +150,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; }
|
||||
};
|
||||
@@ -121,6 +162,7 @@ struct OaiRequest {
|
||||
/* What the server needs to know about itself to validate a request. */
|
||||
struct OaiLimits {
|
||||
std::string model_id = "radiance";
|
||||
std::string version; /* the build, for `system_fingerprint` */
|
||||
int64_t max_ctx = 0; /* 0 = unknown, no length check */
|
||||
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
|
||||
* resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
|
||||
@@ -239,28 +281,51 @@ 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. */
|
||||
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
/* `native` is llama-server's /completion: its `return_tokens`, and a prompt array of strings and
|
||||
* token ids mixed as ONE prompt, as llama-server reads it. */
|
||||
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
OaiRequest* out, ApiError* err, bool native = false);
|
||||
/* Embeddings: fills `out->prompts` with one entry per input. */
|
||||
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err);
|
||||
|
||||
/* ================================================================== responses */
|
||||
|
||||
struct LogprobEntry {
|
||||
/* One emitted token's logprobs as the wire carries them. `bytes` is the token's own bytes and
|
||||
* `text` is their longest well-formed UTF-8 prefix -- a byte-level token can hold half a
|
||||
* character, and a JSON string cannot -- llama-server's spelling. `end` is where the token's
|
||||
* decoded text ends in the choice's text, which is what decides whether it went out before a stop
|
||||
* string cut the reply. */
|
||||
struct LogprobAlt {
|
||||
int32_t token = 0;
|
||||
std::string text;
|
||||
std::string text, bytes;
|
||||
float logprob = 0.0f;
|
||||
};
|
||||
struct LogprobEntry {
|
||||
int32_t token = 0;
|
||||
std::string text, bytes;
|
||||
float logprob = 0.0f;
|
||||
std::vector<LogprobAlt> top;
|
||||
size_t end = 0;
|
||||
};
|
||||
|
||||
/* The entries as a JSON array's elements, comma-joined, in OpenAI's chat shape with llama-server's
|
||||
* `id` beside each token -- which is also llama-server's native `completion_probabilities`. */
|
||||
std::string logprobs_content(const LogprobEntry* e, size_t n);
|
||||
/* OpenAI's legacy /v1/completions `logprobs` object for the entries, `offset` the text offset of
|
||||
* the first, with llama-server's `content` array beside the legacy arrays. */
|
||||
std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset);
|
||||
|
||||
struct ChoiceOut {
|
||||
int index = 0;
|
||||
std::string text; /* raw generated text */
|
||||
std::string stop_word; /* the stop string that cut it, "" when none or unknown */
|
||||
ParsedMessage msg; /* chat: content / reasoning / tool_calls after parsing */
|
||||
Finish finish = Finish::None;
|
||||
std::vector<LogprobEntry> logprobs;
|
||||
@@ -312,7 +377,30 @@ std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
|
||||
const UsageOut& u, const TimingsOut& t = TimingsOut());
|
||||
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& vecs,
|
||||
const UsageOut& u);
|
||||
std::string models_body(const std::string& model_id, int64_t created);
|
||||
/* ONE MODEL ENTRY: what /v1/models lists and /v1/models/:id returns on its own. */
|
||||
struct ModelCard {
|
||||
std::string id;
|
||||
int64_t created = 0;
|
||||
/* The context the server was started with (--max-model-len, else the container's trained
|
||||
* length), the field vLLM's model card carries. Clients size their own context from it -- an
|
||||
* agent that compresses its history at the window's edge, a UI that shows how much is left --
|
||||
* and without it they guess from the model's name, which is wrong whenever the deployment sets
|
||||
* its own length. 0 leaves the field out rather than reporting a length the server does not
|
||||
* know. */
|
||||
int64_t max_model_len = 0;
|
||||
/* What the server loaded (ServerOptions::model_path), vLLM's `root`. Empty leaves it out. */
|
||||
std::string root;
|
||||
/* What the model can be asked for -- tools, reasoning, images -- as /server_info reports it.
|
||||
* There is no field for it in OpenAI's model object, so without this a client learns it by
|
||||
* sending a request and reading the refusal; the entry it already fetches can say so up
|
||||
* front. A JSON object as text, spliced in as it is; empty leaves it out. */
|
||||
std::string capabilities;
|
||||
};
|
||||
/* The list, for GET /v1/models. */
|
||||
std::string models_body(const ModelCard& m);
|
||||
/* The entry itself, for GET /v1/models/:id: OpenAI's retrieve answers the model object, not a
|
||||
* list of one, and its SDK reads `id` off the top level. */
|
||||
std::string model_body(const ModelCard& m);
|
||||
|
||||
/* The usage chunk of each endpoint's stream: an SSE event whose choices array is empty and whose
|
||||
* only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE
|
||||
@@ -337,42 +425,54 @@ bool calls_complete(const ParsedMessage& m);
|
||||
* what it has delivered, so nothing here diffs, holds back or reconciles: a delta is the next
|
||||
* piece of the answer, and the chunks a client concatenates are the answer the buffered path
|
||||
* returns.
|
||||
*
|
||||
* THE WIRE SHAPE IS THE SUBCLASS'S. Reading the reply -- the reader, the message it adds up to,
|
||||
* the finish it implies -- is the same for every API this server speaks, so it lives here once;
|
||||
* what one increment looks like on the wire is OpenAI's chunk (ChatDeltaStream) or Anthropic's
|
||||
* event (AnthropicStream).
|
||||
*/
|
||||
class ChatDeltaStream {
|
||||
class ReplyStream {
|
||||
public:
|
||||
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
ReplyStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
virtual ~ReplyStream() = default;
|
||||
|
||||
/* The `role: assistant` opener OpenAI clients expect before any content. */
|
||||
std::string first_chunk();
|
||||
/* What opens the stream: OpenAI's `role: assistant` chunk, Anthropic's message_start. */
|
||||
virtual std::string first_chunk() = 0;
|
||||
|
||||
/* Feed the text generated since the last push; returns zero or more SSE `data:` lines.
|
||||
/* Feed the text generated since the last push; returns the bytes for what it completed.
|
||||
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
|
||||
std::string push(std::string_view appended, bool is_final);
|
||||
|
||||
/* The terminating chunk carrying finish_reason, and this choice's `timings` when they are
|
||||
* valid -- on the final chunk whether or not the request asked for a usage chunk, as
|
||||
* llama.cpp sends them. The usage chunk is the stream's, not the choice's: chat_usage_chunk. */
|
||||
std::string final_chunk(Finish f, const TimingsOut& t = TimingsOut());
|
||||
/* What closes the choice: the finish reason, and this choice's `timings` when they are valid
|
||||
* (llama.cpp sends them on the final chunk). `u` is the request's usage, for the shapes that
|
||||
* close a message with it. */
|
||||
virtual std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) = 0;
|
||||
/* What closes a choice the engine failed, in place of final_chunk: the shape's own failure,
|
||||
* so a client reading to the terminal event never takes a truncated reply as complete.
|
||||
* OpenAI's chunks have none, so theirs is the final chunk with finish_reason "error" and the
|
||||
* error object after it. */
|
||||
virtual std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u);
|
||||
|
||||
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
|
||||
* been called with is_final. */
|
||||
const ParsedMessage& parsed() const { return last_; }
|
||||
Finish adjusted_finish(Finish f) const;
|
||||
|
||||
private:
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string emit(const std::vector<ReplyDelta>& ev);
|
||||
/* llama.cpp's `timings_per_token`, for the shapes that carry timings. */
|
||||
virtual void set_timings(const TimingsOut&) {}
|
||||
/* Logprobs entries (logprobs_content's elements) for the next chunk this stream writes, for
|
||||
* the shapes that carry them; the others drop them. */
|
||||
virtual void add_logprobs(const std::string&) {}
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out) const;
|
||||
protected:
|
||||
/* The bytes for the increments one push completed. Each emitter folds every increment into
|
||||
* `last_` through absorb() first. */
|
||||
virtual std::string emit(const std::vector<ReplyDelta>& ev) = 0;
|
||||
bool absorb(const ReplyDelta& d);
|
||||
static void quote(std::string& out, std::string_view s);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
|
||||
std::unique_ptr<IReplyReader> reader_;
|
||||
std::string id_, model_;
|
||||
std::string id_, model_, fingerprint_;
|
||||
int64_t created_;
|
||||
int index_;
|
||||
bool finished_ = false;
|
||||
@@ -381,6 +481,116 @@ private:
|
||||
std::vector<ReplyDelta> ev_;
|
||||
};
|
||||
|
||||
/* ANTHROPIC'S MESSAGES API, translated into the chat request it means (`*chat`, a /v1/chat/completions
|
||||
* body) so that every refusal and default is the chat endpoint's. `*label` is the conversation's
|
||||
* label if the request carries one (metadata.user_id). Claude Code's per-request billing stamp in
|
||||
* the system prompt is held constant, as llama-server holds it, or no turn of a conversation could
|
||||
* reuse the one before it. */
|
||||
int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* label, ApiError* err);
|
||||
/* The non-streaming answer, and an error, in Anthropic's shapes. */
|
||||
std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
std::string anthropic_error_body(const ApiError& e);
|
||||
/* OPENAI'S RESPONSES API, translated into the chat request it means, as Anthropic's is. `*echo` is
|
||||
* the request's fields the response object repeats back. previous_response_id needs responses
|
||||
* stored server-side and is refused; tool types other than function have no chat equivalent and
|
||||
* are left out, as llama-server leaves them out. */
|
||||
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
|
||||
std::string* echo, ApiError* err);
|
||||
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
|
||||
|
||||
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
|
||||
const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word);
|
||||
|
||||
/* OpenAI's chat.completion.chunk. */
|
||||
class ChatDeltaStream final : public ReplyStream {
|
||||
public:
|
||||
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser)
|
||||
: ReplyStream(r, index, parser), legacy_(r.legacy_functions) {}
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
|
||||
/* llama.cpp's `timings_per_token`: the timings the next pushes' chunks carry, beside
|
||||
* `choices` as the final chunk carries them. Invalid timings carry nothing. */
|
||||
void set_timings(const TimingsOut& t) override;
|
||||
/* OpenAI's `logprobs.content` on the next chunk out: entries wait for one, because a push may
|
||||
* complete no delta (a tool call's opening, a held-back byte) and the tokens still count. */
|
||||
void add_logprobs(const std::string& elems) override;
|
||||
|
||||
private:
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string lp_; /* pending logprobs entries, comma-joined */
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
std::string timings_; /* `"timings":{...}` for every delta chunk, or "" */
|
||||
bool legacy_; /* OaiRequest::legacy_functions */
|
||||
};
|
||||
|
||||
/* ANTHROPIC'S EVENTS: message_start, then a content block a kind -- thinking, text, each tool_use
|
||||
* -- opened, filled by deltas and stopped, then message_delta with the stop reason and the usage,
|
||||
* and message_stop. The prefill a continued conversation ends in is not repeated (`continued`). */
|
||||
class AnthropicStream final : public ReplyStream {
|
||||
public:
|
||||
AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* Anthropic's `error` event, which ends the stream with no message_stop. */
|
||||
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* The stop string that cut the reply, for stop_reason and stop_sequence. */
|
||||
void set_stop_word(const std::string& w) { stop_word_ = w; }
|
||||
|
||||
private:
|
||||
enum class Block { None, Thinking, Text, Tool };
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
void open(std::string& out, Block b, const ToolCall* tc);
|
||||
void close(std::string& out);
|
||||
static void event(std::string& out, const char* type, const json& data);
|
||||
|
||||
const OaiRequest* r_;
|
||||
int64_t n_input_ = 0;
|
||||
std::string skip_; /* the prefill still to be passed over */
|
||||
std::string stop_word_;
|
||||
Block block_ = Block::None;
|
||||
int n_blocks_ = 0; /* blocks opened so far: the next one's index */
|
||||
};
|
||||
|
||||
/* THE RESPONSES API'S EVENTS: response.created and .in_progress; an output item a kind --
|
||||
* reasoning, the message, each function call -- added, its content part added, filled by deltas,
|
||||
* and done; then response.completed (or .incomplete at the token limit) with the whole response.
|
||||
* Every event carries its output_index, content_index and sequence_number, which the OpenAI SDK's
|
||||
* stream accumulator places deltas by. */
|
||||
class ResponsesStream final : public ReplyStream {
|
||||
public:
|
||||
ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser);
|
||||
std::string first_chunk() override;
|
||||
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
|
||||
/* response.failed, with the items finished so far and the error. */
|
||||
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
|
||||
|
||||
private:
|
||||
enum class Item { None, Reasoning, Message, Call };
|
||||
std::string emit(const std::vector<ReplyDelta>& ev) override;
|
||||
void open(std::string& out, Item k, size_t call);
|
||||
void close(std::string& out);
|
||||
void event(std::string& out, const char* type, json data);
|
||||
json response(const char* status) const;
|
||||
|
||||
const OaiRequest* r_;
|
||||
Item item_ = Item::None;
|
||||
std::string item_id_, text_; /* the open item's id and its text so far */
|
||||
size_t call_ = 0; /* the open call's index into last_.tool_calls */
|
||||
std::vector<std::string> items_; /* every closed item, serialised, in output order */
|
||||
int64_t seq_ = 0;
|
||||
UsageOut usage_;
|
||||
const char* incomplete_ = nullptr;
|
||||
};
|
||||
|
||||
/* The SSE terminator. Written once at the end of every stream, including a failed one, because a
|
||||
* client blocked on the reader has no other way to learn the stream is over. */
|
||||
extern const char* const SSE_DONE;
|
||||
@@ -402,6 +612,10 @@ bool token_id(const json& v, int32_t* out);
|
||||
* and either comes back holding only what fitted, which the caller refuses. See the definition
|
||||
* for why the tree is bounded rather than the body alone. */
|
||||
json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep);
|
||||
/* The body of a generation endpoint: parse_json_bounded, and a 400 saying which bound it broke or
|
||||
* that it is not one JSON object. */
|
||||
int parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
|
||||
ApiError* err);
|
||||
int64_t json_value_budget(int64_t max_ctx);
|
||||
constexpr int kJsonMaxDepth = 1024;
|
||||
|
||||
|
||||
+747
-47
File diff suppressed because it is too large.
Load diff
+27
-1
@@ -53,6 +53,14 @@ 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;
|
||||
/* What --model named, reported as the model entry's `root` the way vLLM reports the path it
|
||||
* loaded: a served name chosen for clients says nothing about which file is behind it. Empty
|
||||
* leaves the field out. */
|
||||
std::string model_path;
|
||||
std::string host = "0.0.0.0";
|
||||
int port = 8000;
|
||||
int n_threads = 0;
|
||||
@@ -187,11 +195,28 @@ private:
|
||||
HttpResponse handle_health(const HttpRequest& req);
|
||||
HttpResponse handle_ping(const HttpRequest& req);
|
||||
HttpResponse handle_version(const HttpRequest& req);
|
||||
HttpResponse handle_props(const HttpRequest& req);
|
||||
HttpResponse handle_apply_template(const HttpRequest& req);
|
||||
HttpResponse handle_input_tokens(const HttpRequest& req);
|
||||
HttpResponse handle_messages(const HttpRequest& req);
|
||||
HttpResponse handle_count_tokens(const HttpRequest& req);
|
||||
HttpResponse handle_responses(const HttpRequest& req);
|
||||
HttpResponse handle_responses_tokens(const HttpRequest& req);
|
||||
/* A request another API's shape was translated into: admitted and served like a chat one,
|
||||
* answered in `r.shape`. */
|
||||
HttpResponse serve_translated(const HttpRequest& req, OaiRequest& r);
|
||||
HttpResponse handle_native_completion(const HttpRequest& req);
|
||||
HttpResponse handle_infill(const HttpRequest& req);
|
||||
json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
|
||||
HttpResponse handle_load(const HttpRequest& req);
|
||||
HttpResponse handle_tokenize(const HttpRequest& req);
|
||||
HttpResponse handle_detokenize(const HttpRequest& req);
|
||||
HttpResponse handle_tokenizer_info(const HttpRequest& req);
|
||||
HttpResponse handle_server_info(const HttpRequest& req);
|
||||
/* What this deployment can do -- chat, tools, reasoning, grammar, media, logprobs, the
|
||||
* reasoning efforts it takes -- as /server_info's `capabilities` and the model entry both
|
||||
* report it, built in one place so the two cannot disagree. */
|
||||
json capabilities() const;
|
||||
HttpResponse handle_sessions(const HttpRequest& req);
|
||||
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
|
||||
|
||||
@@ -200,7 +225,8 @@ private:
|
||||
HttpResponse handle_stats(const HttpRequest& req);
|
||||
HttpResponse handle_graph(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer);
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
/* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
|
||||
* at the info level, so `docker logs` answers "who asked what, how long, how did it end"
|
||||
* without the engine's own levels. The debug level adds the last user message's opening. */
|
||||
|
||||
+32
-4
@@ -1,5 +1,6 @@
|
||||
#include "sink.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
@@ -57,7 +58,13 @@ void Sink::notify() {
|
||||
cv_.notify_one();
|
||||
}
|
||||
|
||||
bool Sink::push(int32_t token, float logprob) {
|
||||
void Sink::enable_logprobs(int n) {
|
||||
alt_w_ = n > 0 ? n : 0;
|
||||
alts_.assign(ring_.size() * (size_t)alt_w_, SinkAlt{});
|
||||
alt_n_.assign(ring_.size(), 0);
|
||||
}
|
||||
|
||||
bool Sink::push(int32_t token, const TokenLogprobs* lp) {
|
||||
const uint64_t h = head_.load(std::memory_order_relaxed);
|
||||
const uint64_t t = tail_.load(std::memory_order_acquire);
|
||||
if (h - t > mask_) {
|
||||
@@ -66,7 +73,14 @@ bool Sink::push(int32_t token, float logprob) {
|
||||
fail(RAD_E_FULL);
|
||||
return false;
|
||||
}
|
||||
ring_[h & mask_] = SinkToken{token, logprob};
|
||||
const size_t slot = (size_t)(h & mask_);
|
||||
ring_[slot] = SinkToken{ token, lp ? lp->logprob : 0.0f, 0 };
|
||||
if (alt_w_ > 0) {
|
||||
const int n = lp ? std::min(lp->n_top, alt_w_) : 0;
|
||||
for (int j = 0; j < n; ++j)
|
||||
alts_[slot * (size_t)alt_w_ + (size_t)j] = SinkAlt{ lp->top_id[j], lp->top_lp[j] };
|
||||
alt_n_[slot] = n;
|
||||
}
|
||||
head_.store(h + 1, std::memory_order_release);
|
||||
|
||||
const int64_t t_now = now_ns() - t_start_ns_;
|
||||
@@ -100,6 +114,13 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
|
||||
n_cached_.store(n_cached, std::memory_order_release);
|
||||
}
|
||||
|
||||
void Sink::set_prompt_progress(int32_t processed, int32_t total, int32_t cached) {
|
||||
prog_total_.store(total, std::memory_order_release);
|
||||
prog_cached_.store(cached, std::memory_order_release);
|
||||
prog_done_.store(processed, std::memory_order_release);
|
||||
notify();
|
||||
}
|
||||
|
||||
void Sink::mark_admitted() {
|
||||
if (t_admit_.load(std::memory_order_relaxed) < 0)
|
||||
t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
|
||||
@@ -112,12 +133,19 @@ void Sink::add_drafts(int32_t n, int32_t accepted) {
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
size_t Sink::read(SinkToken* out, size_t max) {
|
||||
size_t Sink::read(SinkToken* out, size_t max, SinkAlt* alts) {
|
||||
const uint64_t t = tail_.load(std::memory_order_relaxed);
|
||||
const uint64_t h = head_.load(std::memory_order_acquire);
|
||||
size_t n = (size_t)(h - t);
|
||||
if (n > max) n = max;
|
||||
for (size_t i = 0; i < n; ++i) out[i] = ring_[(t + i) & mask_];
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const size_t slot = (size_t)((t + i) & mask_);
|
||||
out[i] = ring_[slot];
|
||||
if (!alts || alt_w_ <= 0) continue;
|
||||
out[i].n_alt = alt_n_[slot];
|
||||
for (int j = 0; j < alt_n_[slot]; ++j)
|
||||
alts[i * (size_t)alt_w_ + (size_t)j] = alts_[slot * (size_t)alt_w_ + (size_t)j];
|
||||
}
|
||||
if (n) tail_.store(t + n, std::memory_order_release);
|
||||
return n;
|
||||
}
|
||||
|
||||
+49
-13
@@ -49,7 +49,14 @@ const char* finish_reason_oai(Finish f);
|
||||
|
||||
struct SinkToken {
|
||||
int32_t token = 0;
|
||||
float logprob = 0.0f; /* 0 when the sampler does not supply one; see Sink::has_logprobs */
|
||||
float logprob = 0.0f; /* the token's logprob; 0 unless the request asked for logprobs */
|
||||
int32_t n_alt = 0; /* how many alternatives read() wrote for this token */
|
||||
};
|
||||
|
||||
/* One of a token's most likely alternatives, with its logprob. */
|
||||
struct SinkAlt {
|
||||
int32_t id = 0;
|
||||
float logprob = 0.0f;
|
||||
};
|
||||
|
||||
class Sink {
|
||||
@@ -73,8 +80,9 @@ public:
|
||||
|
||||
/* ------------------------------------------------------------------ producer: scheduler */
|
||||
|
||||
/* Returns false only on overflow, which also marks the request failed. */
|
||||
bool push(int32_t token, float logprob = 0.0f);
|
||||
/* Returns false only on overflow, which also marks the request failed. `lp` is the token's
|
||||
* logprobs when the request asked for them (enable_logprobs), and null otherwise. */
|
||||
bool push(int32_t token, const TokenLogprobs* lp = nullptr);
|
||||
|
||||
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
|
||||
* produce two finish reasons. */
|
||||
@@ -97,11 +105,20 @@ public:
|
||||
/* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
|
||||
* taken. Summed over the request, the per-request half of /metrics' draft counters. */
|
||||
void add_drafts(int32_t n, int32_t accepted);
|
||||
/* HOW MUCH OF THE PROMPT IS IN THE CACHE: at admission (what the prefix cache supplied) and
|
||||
* after every prefill step, of `total`, of which `cached` came from the prefix cache. What
|
||||
* llama-server streams as `prompt_progress` when a request asks for it; wakes the consumer. */
|
||||
void set_prompt_progress(int32_t processed, int32_t total, int32_t cached);
|
||||
int32_t progress_processed() const { return prog_done_.load(std::memory_order_acquire); }
|
||||
int32_t progress_total() const { return prog_total_.load(std::memory_order_acquire); }
|
||||
int32_t progress_cached() const { return prog_cached_.load(std::memory_order_acquire); }
|
||||
|
||||
/* ------------------------------------------------------------------ consumer: HTTP */
|
||||
|
||||
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
|
||||
size_t read(SinkToken* out, size_t max);
|
||||
/* Copies up to `max` tokens out. Returns how many. Never blocks. With `alts`, each token's
|
||||
* alternatives too: token i's n_alt of them at alts[i * alt_width()], which needs room for
|
||||
* max * alt_width(). */
|
||||
size_t read(SinkToken* out, size_t max, SinkAlt* alts = nullptr);
|
||||
|
||||
/* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
|
||||
* Returns true if there is now something to look at. */
|
||||
@@ -133,15 +150,22 @@ public:
|
||||
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
|
||||
int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
|
||||
|
||||
/* The engine sets this at wiring time if its sampler returns per-token probabilities. Without
|
||||
* it the logprobs field of a response is null rather than zeros (spec: nothing unimplemented
|
||||
* returns success). */
|
||||
void set_has_logprobs(bool v) { has_logprobs_ = v; }
|
||||
bool has_logprobs() const { return has_logprobs_; }
|
||||
/* THE ALTERNATIVES' RING, sized for `n` a token, beside the token ring: allocated only for a
|
||||
* request that asks for them, because at RAD_MAX_LOGPROBS it is twenty times the token ring.
|
||||
* Called by the consumer before the request is handed to the scheduler. */
|
||||
void enable_logprobs(int n);
|
||||
int alt_width() const { return alt_w_; }
|
||||
|
||||
/* 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();
|
||||
|
||||
@@ -167,7 +191,13 @@ private:
|
||||
|
||||
std::atomic<int32_t> n_prompt_{0};
|
||||
std::atomic<int32_t> n_cached_{0};
|
||||
bool has_logprobs_ = false;
|
||||
std::atomic<int32_t> prog_done_{-1};
|
||||
std::atomic<int32_t> prog_total_{0};
|
||||
std::atomic<int32_t> prog_cached_{0};
|
||||
std::vector<SinkAlt> alts_; /* [capacity * alt_w_], parallel to ring_ */
|
||||
std::vector<int32_t> alt_n_; /* [capacity] */
|
||||
int alt_w_ = 0;
|
||||
std::vector<float> embd_;
|
||||
|
||||
std::mutex m_;
|
||||
std::condition_variable cv_;
|
||||
@@ -175,8 +205,8 @@ private:
|
||||
|
||||
/* The scheduler's call sites, so core/sched needs one include and no casts of its own. A null
|
||||
* sink is legal and means nobody is listening -- an offline or benchmark request. */
|
||||
inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) {
|
||||
return s ? static_cast<Sink*>(s)->push(token, logprob) : true;
|
||||
inline bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
|
||||
return s ? static_cast<Sink*>(s)->push(token, lp) : true;
|
||||
}
|
||||
inline void sink_finish(void* s, Finish f) {
|
||||
if (s) static_cast<Sink*>(s)->finish(f);
|
||||
@@ -193,9 +223,15 @@ inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
|
||||
inline void sink_admitted(void* s) {
|
||||
if (s) static_cast<Sink*>(s)->mark_admitted();
|
||||
}
|
||||
inline void sink_prompt_progress(void* s, int32_t processed, int32_t total, int32_t cached) {
|
||||
if (s) static_cast<Sink*>(s)->set_prompt_progress(processed, total, cached);
|
||||
}
|
||||
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 */
|
||||
@@ -193,6 +193,11 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
in.add_bos = opt.add_bos || impl_->add_bos;
|
||||
in.add_eos = opt.add_eos || impl_->add_eos;
|
||||
in.reasoning_format = common_reasoning_format_from_name(opt.reasoning_format);
|
||||
in.continue_final_message =
|
||||
opt.continue_final.empty() ? COMMON_CHAT_CONTINUATION_NONE
|
||||
: opt.continue_final == "content" ? COMMON_CHAT_CONTINUATION_CONTENT
|
||||
: opt.continue_final == "reasoning_content" ? COMMON_CHAT_CONTINUATION_REASONING
|
||||
: COMMON_CHAT_CONTINUATION_AUTO;
|
||||
|
||||
common_chat_params p;
|
||||
try {
|
||||
|
||||
@@ -54,6 +54,7 @@ struct ChatOptions {
|
||||
bool parallel_tool_calls = false;
|
||||
std::string tool_choice = "auto"; /* auto | none | required */
|
||||
std::string reasoning_format = "auto"; /* none | auto | deepseek | deepseek-legacy */
|
||||
std::string continue_final; /* "" | auto | content | reasoning_content */
|
||||
std::string grammar; /* a user-supplied GBNF, or empty */
|
||||
std::string json_schema; /* response_format json_schema, or empty */
|
||||
bool add_bos = false;
|
||||
|
||||
+45
-26
@@ -1534,6 +1534,35 @@ size_t Detokenizer::safe_prefix() const {
|
||||
* sequence, which is what browsers and every other inference server do. The alternative -- one
|
||||
* U+FFFD per bad byte -- turns a truncated three-byte character into three replacement
|
||||
* characters, which reads as three lost characters rather than the one that was actually lost. */
|
||||
/* The well-formed sequence at s[i], a lead byte: its length, or 0 with `*part` the length of the
|
||||
* ill-formed one's maximal subpart (never zero). The SECOND byte's range is what rejects overlong
|
||||
* encodings, surrogates and anything past U+10FFFF without decoding. */
|
||||
static inline size_t utf8_seq(std::string_view s, size_t i, size_t* part) {
|
||||
const unsigned char c = (unsigned char)s[i];
|
||||
size_t len; unsigned char lo, hi;
|
||||
if (c >= 0xC2 && c <= 0xDF) { len = 2; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xE0) { len = 3; lo = 0xA0; hi = 0xBF; }
|
||||
else if (c >= 0xE1 && c <= 0xEC) { len = 3; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xED) { len = 3; lo = 0x80; hi = 0x9F; } /* no surrogates */
|
||||
else if (c >= 0xEE && c <= 0xEF) { len = 3; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xF0) { len = 4; lo = 0x90; hi = 0xBF; }
|
||||
else if (c >= 0xF1 && c <= 0xF3) { len = 4; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xF4) { len = 4; lo = 0x80; hi = 0x8F; } /* <= U+10FFFF */
|
||||
else { len = 0; lo = 0; hi = 0; } /* 0x80-0xC1, 0xF5+ */
|
||||
|
||||
size_t k = 1;
|
||||
if (len) {
|
||||
for (; k < len && i + k < s.size(); ++k) {
|
||||
const unsigned char d = (unsigned char)s[i + k];
|
||||
const unsigned char l = (k == 1) ? lo : 0x80, h = (k == 1) ? hi : 0xBF;
|
||||
if (d < l || d > h) break;
|
||||
}
|
||||
}
|
||||
if (len && k == len) return len;
|
||||
*part = k;
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string utf8_sanitize(std::string_view s) {
|
||||
/* The common case is a string that is already valid, and it must not be copied byte by byte. */
|
||||
std::string out;
|
||||
@@ -1542,41 +1571,31 @@ std::string utf8_sanitize(std::string_view s) {
|
||||
auto flush_good = [&] { out.append(s.data() + good, i - good); good = i; };
|
||||
|
||||
while (i < n) {
|
||||
const unsigned char c = (unsigned char)s[i];
|
||||
if (c < 0x80) { ++i; continue; }
|
||||
|
||||
/* Length, and the range the SECOND byte is restricted to. The second-byte bounds are what
|
||||
* reject overlong encodings, surrogates and anything past U+10FFFF without decoding. */
|
||||
size_t len; unsigned char lo, hi;
|
||||
if (c >= 0xC2 && c <= 0xDF) { len = 2; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xE0) { len = 3; lo = 0xA0; hi = 0xBF; }
|
||||
else if (c >= 0xE1 && c <= 0xEC) { len = 3; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xED) { len = 3; lo = 0x80; hi = 0x9F; } /* no surrogates */
|
||||
else if (c >= 0xEE && c <= 0xEF) { len = 3; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xF0) { len = 4; lo = 0x90; hi = 0xBF; }
|
||||
else if (c >= 0xF1 && c <= 0xF3) { len = 4; lo = 0x80; hi = 0xBF; }
|
||||
else if (c == 0xF4) { len = 4; lo = 0x80; hi = 0x8F; } /* <= U+10FFFF */
|
||||
else { len = 0; lo = 0; hi = 0; } /* 0x80-0xC1, 0xF5+ */
|
||||
|
||||
size_t k = 1;
|
||||
if (len) {
|
||||
for (; k < len && i + k < n; ++k) {
|
||||
const unsigned char d = (unsigned char)s[i + k];
|
||||
const unsigned char l = (k == 1) ? lo : 0x80, h = (k == 1) ? hi : 0xBF;
|
||||
if (d < l || d > h) break;
|
||||
}
|
||||
}
|
||||
if (len && k == len) { i += len; continue; }
|
||||
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
|
||||
size_t part = 0;
|
||||
const size_t len = utf8_seq(s, i, &part);
|
||||
if (len) { i += len; continue; }
|
||||
|
||||
flush_good();
|
||||
out += "\xEF\xBF\xBD"; /* U+FFFD */
|
||||
i += k; /* the maximal subpart, never zero */
|
||||
i += part; /* the maximal subpart, never zero */
|
||||
good = i;
|
||||
}
|
||||
flush_good();
|
||||
return out;
|
||||
}
|
||||
|
||||
size_t utf8_valid_prefix(std::string_view s) {
|
||||
size_t i = 0, part = 0;
|
||||
while (i < s.size()) {
|
||||
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
|
||||
const size_t len = utf8_seq(s, i, &part);
|
||||
if (!len) break;
|
||||
i += len;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
std::string Detokenizer::push(int32_t token) {
|
||||
if (!v_ || !v_->ready() || stopped_) return {};
|
||||
|
||||
|
||||
@@ -213,6 +213,9 @@ private:
|
||||
* would hide that the model produced something undecodable. Well-formed input is returned byte for
|
||||
* byte, so this is a no-op on every normal completion. */
|
||||
std::string utf8_sanitize(std::string_view s);
|
||||
/* How much of `s` is well-formed UTF-8 from its start, by the same rules: what a JSON string can
|
||||
* carry of a byte-level token that ends inside a character. */
|
||||
size_t utf8_valid_prefix(std::string_view s);
|
||||
|
||||
|
||||
/* Byte-level BPE emits partial UTF-8 sequences -- a single token can be one byte of a
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,40 @@
|
||||
# q38-27b-fp8block-df2.recipe -- a bf16 Qwen3.8-27B checkpoint (the base model's bf16 release or a
|
||||
# finetune of it) as block fp8 with the DFlash2 drafter, the same weights in the same form as
|
||||
# Qwen's own FP8 release, so it serves exactly as q38-27b-fp8-df2.rad does.
|
||||
#
|
||||
# rad-convert <bf16 Qwen3.8-27B checkpoint> --draft-model <z-lab/Qwen3.8-27B-DFlash2> \
|
||||
# --recipe data/recipes/q38-27b-fp8block-df2.recipe \
|
||||
# --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
|
||||
# --set "quantization_config.weight_block_size=128 128" \
|
||||
# --set quantization_config.activation_scheme=dynamic -o model.rad
|
||||
#
|
||||
# The --set keys state the format the container is in, as Qwen's FP8 checkpoint's own config does:
|
||||
# they are what selects qwen35_fp8 to serve it, where a bf16 checkpoint selects qwen35.
|
||||
#
|
||||
# The trunk's linears -- attention q/gate, k, v and output, the delta net's qkv/z and output
|
||||
# projections, and the MLP's gate/up and down -- as E4M3 with one bf16 scale a 128x128 block,
|
||||
# rounded to nearest: the set and the format Qwen's FP8 checkpoint ships (its quantization_config:
|
||||
# fp8, e4m3, weight_block_size [128, 128], bf16 scales). Every fused weight's pieces end on a
|
||||
# 128-row boundary, so a block never spans two of them. The delta net's a/b projection, the
|
||||
# norms, the embedding and the vision tower stay bf16, as there. The lm_head and the drafter are
|
||||
# q38-27b-fp8-df2.recipe's.
|
||||
|
||||
blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search
|
||||
|
||||
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
|
||||
@@ -0,0 +1,88 @@
|
||||
# swift15-w4nl64-i8-hc8m.recipe -- ukisai's Swift 1.5 finetune of Qwen3.8-Flash-Next by the
|
||||
# production recipe (qwen4exp-w4nl64-i8-hc8m.recipe), with the protected experts chosen from the
|
||||
# finetune's own recording. Every rule below the protected ones is that recipe's: the routed experts
|
||||
# as rotated u4 codes into the w4nl codebook with one E4M3 scale a (row, 64 of K) under a fixed f32
|
||||
# of 2^-13 (libr4d's w4nl64a8h), the codes chosen by GPTQ and three sweeps of coordinate descent;
|
||||
# sixteen protected experts plain bf16; the trunk's block linears and the lm_head int8, served W8A8;
|
||||
# the connections' mixing matrices and the MTP head's fc matrices E4M3; the n-gram table at one
|
||||
# fixed E4M3 scale.
|
||||
#
|
||||
# The base model's KL figures are not this model's; it has not been measured against its bf16 self.
|
||||
#
|
||||
# CALIB=DIR rad-convert <Swift1.5-Qwen3.8-Flash-Next checkpoint> \
|
||||
# --recipe data/recipes/swift15-w4nl64-i8-hc8m.recipe -o swift15-w4nl64-i8lm.rad
|
||||
#
|
||||
# DIR holds the Grams recorded from the finetune's bf16 model at one million tokens of the
|
||||
# calibration corpus with the per-expert tap: each layer's pooled Grams and each expert's own down
|
||||
# Gram, side by side (docs/MOE-W4.md, "Calibration"). The finetune changed only the attention,
|
||||
# delta-net and shared-expert projections; its routed experts are the base model's bytes, so a
|
||||
# --reuse of the base container with --changed copies everything else that reads unchanged tensors
|
||||
# under unchanged rules, and quantises the experts again against these Grams.
|
||||
#
|
||||
# Everything not named here is served as the checkpoint holds it; the first rule that matches a
|
||||
# weight decides it.
|
||||
|
||||
# The protected experts, by the base recipe's rule applied to the finetune's own recording: an
|
||||
# expert whose share of its layer's down-input energy is at least 3% and at least three times its
|
||||
# share of the routing, and on each half of the layer's experts an even count, by adding that
|
||||
# half's next most energetic expert. The finetune's attention drives the early layers' super
|
||||
# experts the base model never fired on this corpus -- layer 4's expert 108 carries 15.8% of its
|
||||
# layer's down-input energy from 0.18% of the routing, layer 2's 322 6.2% -- and layers 34 and 44
|
||||
# drop below the bar; layer 47's 445 carries 67%.
|
||||
blk.2.ffn_*_exps.322.weight cast dtype=bf16
|
||||
blk.2.ffn_*_exps.413.weight cast dtype=bf16
|
||||
blk.4.ffn_*_exps.108.weight cast dtype=bf16
|
||||
blk.4.ffn_*_exps.168.weight cast dtype=bf16
|
||||
blk.4.ffn_*_exps.373.weight cast dtype=bf16
|
||||
blk.4.ffn_*_exps.426.weight cast dtype=bf16
|
||||
blk.14.ffn_*_exps.169.weight cast dtype=bf16
|
||||
blk.14.ffn_*_exps.212.weight cast dtype=bf16
|
||||
blk.42.ffn_*_exps.43.weight cast dtype=bf16
|
||||
blk.42.ffn_*_exps.124.weight cast dtype=bf16
|
||||
blk.46.ffn_*_exps.290.weight cast dtype=bf16
|
||||
blk.46.ffn_*_exps.392.weight cast dtype=bf16
|
||||
blk.47.ffn_*_exps.122.weight cast dtype=bf16
|
||||
blk.47.ffn_*_exps.143.weight cast dtype=bf16
|
||||
blk.47.ffn_*_exps.399.weight cast dtype=bf16
|
||||
blk.47.ffn_*_exps.445.weight cast dtype=bf16
|
||||
|
||||
# Every other routed expert, trunk and MTP layer alike: u4 codes into the w4nl table, rotated by
|
||||
# the 128-wide Hadamard, an E4M3 scale a group of 64 under the fixed 2^-13 searched for least error
|
||||
# as stored, the codes chosen by GPTQ against $CALIB and then swept three times by coordinate
|
||||
# descent. The experts' scales sit between 2^-15 and 2^-10.6, inside E4M3's normal range under
|
||||
# 2^-13 with four binades either side; one past its top would be held there and said on stderr.
|
||||
# The MTP layer has no recording and is rounded to nearest, which libquant says on stderr.
|
||||
blk.*.ffn_*_exps.*.weight gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB
|
||||
|
||||
# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP
|
||||
# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover
|
||||
# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is
|
||||
# [10240, 320] and takes four scales a row, 80 columns each.
|
||||
*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32
|
||||
|
||||
# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts.
|
||||
mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
|
||||
# The trunk's block linears as int8, a scale per 128 columns of a row searched for least error.
|
||||
# The QSA indexer's projection is not one of them: its top-k is a hard choice between blocks, and
|
||||
# keeping it as the checkpoint holds it costs 20 MB.
|
||||
blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
|
||||
# The lm_head, int8 with a bf16 scale a row per 128 columns (logits_gemm_i8): at E4M3 it costs
|
||||
# ~0.6 points of top-1 on its own.
|
||||
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
|
||||
# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from.
|
||||
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
|
||||
|
||||
# The MTP head's 2-bit draft head.
|
||||
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
@@ -10,7 +10,8 @@ RADIANCE_MODELS=/srv/models/rad
|
||||
# Writable directory mounted at /data: the prefix cache's disk tier lives under it.
|
||||
RADIANCE_STATE=/srv/radiance
|
||||
|
||||
# Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer <key>`.
|
||||
# Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer <key>`
|
||||
# (or `X-Api-Key: <key>`).
|
||||
RADIANCE_API_KEY=
|
||||
|
||||
# The port the server listens on.
|
||||
@@ -22,3 +23,6 @@ RADIANCE_UID=1000
|
||||
RADIANCE_GID=1000
|
||||
RENDER_GID=
|
||||
VIDEO_GID=
|
||||
|
||||
# The card a one-card model runs on (embeddinggemma2.yaml), by index.
|
||||
RADIANCE_GPU=0
|
||||
@@ -0,0 +1,15 @@
|
||||
# EmbeddingGemma 2 (google/embeddinggemma-2) in bf16 as the checkpoint ships it: one vector a text,
|
||||
# image, video, audio clip or any mix of them, on /v1/embeddings. The model is small (a 270M text
|
||||
# model and its two towers) and runs on one card, RADIANCE_GPU in .env (default 0). An input is one
|
||||
# step, so --max-num-batched-tokens is the longest input as well as the batch.
|
||||
name: radiance-embeddinggemma2
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-embeddinggemma2
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/embeddinggemma2-bf16.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1 --max-num-seqs 64 --max-num-batched-tokens 8192
|
||||
@@ -13,6 +13,7 @@ into the id an architecture plugin claims.
|
||||
| `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations |
|
||||
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
|
||||
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
|
||||
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
|
||||
|
||||
This document is the geometry of each, and the handful of readings that are **arithmetically
|
||||
silent** — wrong in a way that produces fluent output and no error anywhere.
|
||||
@@ -395,3 +396,53 @@ N = 160 — wide enough that formats which differ by less than that rank in any
|
||||
graded statistic that has thousands of samples rather than hundreds (the mean |delta| over the
|
||||
logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at N ≥ 160
|
||||
before acting on it.
|
||||
|
||||
---
|
||||
|
||||
# `embeddinggemma2` — an embedding model
|
||||
|
||||
`arch/embgemma2` declares a POOLED output (`rad_declare_pooled`) and no logits, which makes the
|
||||
program an embedding program: the engine runs it with no sampler and no KV cache, carries every
|
||||
input whole in one step, and returns each sequence's pooled row on `/v1/embeddings`
|
||||
([GUIDE §5.6](GUIDE.md)). One card (`--tp 1`).
|
||||
|
||||
```
|
||||
text 24 layers, hidden 512, ffn 2048 (gelu-tanh, gated), vocab 262144
|
||||
layer_types: five sliding (|i-j| <= 512, 4 x 256, 2 kv heads, theta 1e4) then one full
|
||||
(4 x 512, 1 kv head, theta 1e6), four times; BIDIRECTIONAL everywhere, scale 1
|
||||
q, k RMS-normed with a gain, v without; sandwich norms with plain gains
|
||||
per-layer inputs: the embedding projected to 24 x 512 and normed, gating a 512 bottleneck
|
||||
a learned scalar a layer on the residual; mean over every token, then 512 -> 768
|
||||
vision Gemma 4's: 16 layers of 768 (12 x 64), a learned row/column table, a two-block 2-D rotary
|
||||
(x on the first half of a head, y on the second, theta 100), 3 x 3 mean pooling * sqrt(768),
|
||||
an unscaled RMS norm and 768 -> 512; up to 280 soft tokens an image by default
|
||||
audio Gemma 4's USM conformer: two stride-2 3 x 3 convolutions over (time, mel), 12 blocks
|
||||
(half-weight feed-forwards, local attention 11 back with a relative-position term and a
|
||||
softcap of 50, a gated depthwise causal convolution), clipped linears; 1024 -> 1536 ->
|
||||
embedder -> 512; 4 frames (40 ms) a token, clips cut at 30 s
|
||||
```
|
||||
|
||||
The traps:
|
||||
|
||||
- **The embedding scale is the bf16 of sqrt(512)**, 22.625, because the reference stores it as a
|
||||
bf16 buffer. sqrt(512) itself is off by one part in 800 on every embedding.
|
||||
- **A media row replaces its placeholder's embedding before the per-layer inputs are projected.**
|
||||
The per-layer input of an image token is computed from its image row, not from the placeholder
|
||||
id's embedding.
|
||||
- **The vision rotary is two independent neox rotaries**, one over each half of a head (`qk_norm_rope`
|
||||
mode `blocks`). `rope` mode `axial` pairs across the halves and is a different function.
|
||||
- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`), and
|
||||
the processor lays each 3 x 3 window's patches out consecutively so the pooler is a mean of nine
|
||||
consecutive rows; attention and both position terms read each patch's own coordinates.
|
||||
- **The audio subsampler masks its input to the clip's real frames before each convolution**: the
|
||||
second convolution reads the first one's output at frame 2t's validity (`conv2d`'s `valid`
|
||||
operand, stride 2), which zeroes the one row past the real ones that the zero padding alone
|
||||
would not.
|
||||
- **The audio attention reaches 11 rows back, not 12.** The config says `attention_context_left`
|
||||
13 and the chunked layout fetches 12 keys behind each block, but the mask transformers applies
|
||||
keeps a key only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent a block
|
||||
and leaves rows at cosine 0.6 by the last one.
|
||||
- **An audio clip's tokens are ceil(real frames / 4)**, real frames being those whose last sample
|
||||
is a real one; the processor stages exactly those plus zero frames to whole rows, which
|
||||
reproduces every row the reference keeps.
|
||||
|
||||
+283
-91
@@ -66,7 +66,9 @@ lifts. There is nothing to `apt install` beyond a toolchain.
|
||||
**A machine with no GPU is a supported configuration.** The host backend is a real implementation,
|
||||
not a stub: the core, scheduler, planner, tokeniser, server and `libref` all run through it and
|
||||
the full test suite passes. It is slow, and it will not serve a production model — but it is a
|
||||
complete development and inspection environment.
|
||||
complete development and inspection environment. A build with ROCm, or the container image, runs
|
||||
the same host backend on a machine where no card is visible: the GPU library's kernels are left out
|
||||
there and every op takes its host kernel.
|
||||
|
||||
### 1.2 Build
|
||||
|
||||
@@ -201,8 +203,9 @@ library can change without a reconvert.
|
||||
|
||||
**2. Kernels are plugins, and the order matters.** The engine resolves every op in the model
|
||||
against an ordered list of kernel libraries: first one that matches an op wins. `--kernels
|
||||
mylib,libref` states that order. With no list, the loader orders what it finds and puts a
|
||||
library that declares itself a reference implementation last.
|
||||
mylib,libref` names the libraries to use and their order; a library it leaves out is not loaded.
|
||||
With no list, every library found loads, and the loader puts one that declares itself a reference
|
||||
implementation last.
|
||||
|
||||
Three ship with the tree:
|
||||
|
||||
@@ -251,6 +254,24 @@ skipped and a short one is continued. It also skips duplicate weight formats —
|
||||
|
||||
Set `HF_TOKEN` for a gated or private repo. `HFGET_JOBS` sets concurrency (default 4).
|
||||
|
||||
A complete fetch records each file's content key (its LFS sha256, or the size of a small file) in
|
||||
`.hfget-manifest`, so the next run also fetches a file that changed at the same size. The free-space
|
||||
check counts only what is still to fetch.
|
||||
|
||||
**The server can do this itself.** `--model` takes a repo id where it would take a path:
|
||||
|
||||
```sh
|
||||
radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000
|
||||
```
|
||||
|
||||
It runs the same script (installed beside the binary, in `libexec/radiance/`) into
|
||||
`--download-dir/<owner>/<name>` before bring-up, then serves the one `.rad` at the repo's top level,
|
||||
or the directory as a checkpoint (§3.4) when it holds none. A repo with several containers is
|
||||
refused by name; pass the file. Every start checks the hub and fetches what changed. A start that
|
||||
cannot read the listing, or whose update does not fit, serves the copy a complete earlier fetch
|
||||
left and says so; a transfer that fails part-way stops startup. A path that exists is always a
|
||||
path, and a name ending in `.rad`, `.safetensors`, `.gguf` or `.json` is never looked up.
|
||||
|
||||
### 3.2 Convert it
|
||||
|
||||
```sh
|
||||
@@ -306,8 +327,20 @@ rad-convert $SRC -o out.rad --draft-model ~/models/openbmb/MiniCPM5-2B-DSpark
|
||||
|
||||
# Re-quantise some weights and copy the rest from an earlier container
|
||||
rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
|
||||
|
||||
# A bf16 Qwen3.8-27B -- the base release or a finetune of it -- as Qwen's block fp8: the recipe
|
||||
# writes the linears, and --set states the format, which is what selects the fp8 plugin
|
||||
rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \
|
||||
--draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \
|
||||
--set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
|
||||
--set "quantization_config.weight_block_size=128 128" --set quantization_config.activation_scheme=dynamic
|
||||
```
|
||||
|
||||
A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read
|
||||
from. A finetune that changed only some tensors can be assembled from them and the base model: its
|
||||
changed tensors in shards of their own, links to the base model's shards for the rest, and an index
|
||||
that points each name at its copy. A name two shards hold that no index entry settles is refused.
|
||||
|
||||
The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their
|
||||
recipes in `data/recipes/`.
|
||||
|
||||
@@ -429,15 +462,15 @@ radiance --model m.rad --debug-placement # just the placement plan
|
||||
|
||||
### 4.3 Memory: how the card gets split
|
||||
|
||||
The card is split into **resident weights** and the **paged KV pool**. You can state the split
|
||||
outright:
|
||||
The card is split into **resident weights** and the **paged KV pool**, and the engine derives the
|
||||
split from the card and the model; no flag states either pool. What you move are its inputs:
|
||||
`--gpu-headroom-mib` leaves card space alone, `--max-model-len` and `--max-num-seqs` bound the
|
||||
cache, and `--host-pool-mib` decides which experts must stay on the card. The startup receipt
|
||||
prints every term. On a machine with no visible card (the host backend) half of RAM stands in for
|
||||
the card and is split the same way; the weights pool is then host memory, holding the weights a
|
||||
host kernel cannot read where the container stores them.
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --vram-weights-mib 24000 --vram-kv-mib 6000
|
||||
```
|
||||
|
||||
or leave both unset and let the engine derive it from the card. The non-expert weights come off
|
||||
the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
|
||||
The non-expert weights come off the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
|
||||
the expert slab and the KV cache, and no flag divides it:
|
||||
|
||||
- **The cache lends** under `--placement auto` or `expert_tiered`, without `--deterministic`, on a
|
||||
@@ -457,12 +490,11 @@ 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
|
||||
`expert_tiered`, 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
|
||||
would never page go to its experts all the same. 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,
|
||||
@@ -508,7 +540,7 @@ Related flags:
|
||||
--gpu-headroom-mib 96 # VRAM left unclaimed on every card
|
||||
--kv-cache-dtype fp8 # halve what a token of context costs (a real quantisation)
|
||||
--host-pool-mib 8192 # pinned host tier for weights
|
||||
--embedding-placement ram # the token embedding off the card (below)
|
||||
--embedding-placement vram # keep the token embedding on the card (below)
|
||||
--ngram-placement ram # an n-gram table in RAM instead of read from disk (below)
|
||||
--weights-disk-tier # stream what fits neither from the container; needs O_DIRECT
|
||||
```
|
||||
@@ -518,25 +550,27 @@ never the whole table, so a tier below the card serves them at little or no cost
|
||||
|
||||
| | `vram` | `ram` | `disk` |
|
||||
|---|---|---|---|
|
||||
| `--embedding-placement` | on the card, with the other weights | the pinned host pool, read over the link in place | refused |
|
||||
| `--embedding-placement` | on the card, with the other weights | pinned host memory of its own, read over the link in place (the default) | refused |
|
||||
| `--ngram-placement` | on the card, every card holding all of it | a copy in RAM made at load, read by the card over the link | read from the container through a row cache |
|
||||
|
||||
Both default to `auto`, the fastest tier that has room once every other weight is placed. Startup
|
||||
prints what each resolved to and why. A tier the flag names that cannot be honoured stops the
|
||||
server with the reason; nothing falls back quietly.
|
||||
The embedding defaults to `ram`; the n-gram table defaults to `auto`, the fastest tier that has
|
||||
room once every other weight is placed. Startup prints what each resolved to and why. A tier the
|
||||
flag names that cannot be honoured stops the server with the reason.
|
||||
|
||||
**The token embedding** is the largest model-level weight a dense model has -- 248320 x 5120 in bf16
|
||||
is 1.18 GiB a card at `--tp 2`. With `ram` it is placed in the pinned host pool before any strategy
|
||||
runs and the lookup reads it over the link in place, so it costs no VRAM and the KV pool gets its
|
||||
share. The pool must hold it (`--host-pool-mib`, every rank its own shard). `auto` keeps it on the
|
||||
card unless the card cannot hold the other weights with it, or a derived KV pool could then not
|
||||
hold one `--max-model-len` sequence; then it takes `ram` if the host pool can hold it. The table is
|
||||
found by what reads it: a model-level weight only `embed_lookup` reads. A head tied to it is read by
|
||||
a GEMM too and is never moved, since it would stream whole every step. `disk` is refused: the lookup
|
||||
writes activations the card reads, and a host kernel reading the container cannot write them.
|
||||
is 1.18 GiB a card at `--tp 2`. By default (`ram`) it is pinned in host memory of its own, every
|
||||
rank its own shard, on top of `--host-pool-mib` -- the experts' pool keeps all of that -- and the
|
||||
lookup reads a step's rows over the link in place, so the table costs no VRAM and the KV pool and
|
||||
the experts get its share. The table is found by what reads it: a model-level weight only
|
||||
`embed_lookup` reads. A head tied to it is read by a GEMM too and is never moved, since it would
|
||||
stream whole every step, so such a model keeps it on the card; so does a host that cannot pin it
|
||||
(available memory and memory cgroups, after the pools, with 4 GiB to spare). Startup says which
|
||||
and why. Naming `ram` turns either case into a refusal; `vram` keeps the table on the card.
|
||||
`disk` is refused: the lookup writes activations the card reads, and a host kernel reading the
|
||||
container cannot write them.
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --tp 2 --host-pool-mib 1280 --embedding-placement ram
|
||||
radiance --model m.rad --tp 2 --embedding-placement vram # the table on the cards
|
||||
```
|
||||
|
||||
**An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token, which is why it
|
||||
@@ -791,12 +825,13 @@ which is why it is a named flag and not a heuristic.
|
||||
`--tp-wire-min-kb` is the floor below which messages are still served exactly — 128 KiB leaves
|
||||
single-sequence decode exact and compresses prefill, which is where the win is.
|
||||
|
||||
At four ranks `wht6` selects a different lossy wire with the same floor: tiered int8 over a
|
||||
two-shot all-reduce, both hops quantised. Eight ranks have no lossy wire, and `--tp 8 --tp-wire
|
||||
wht6` stops at startup naming the all-reduce it found no kernel for. The exact wire at four and
|
||||
eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends
|
||||
2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it; the two produce the same
|
||||
bits.
|
||||
At three and four ranks `wht6` selects a different lossy wire with the same floor: tiered int8
|
||||
over a two-shot all-reduce, both hops quantised (at three the shards are whole 32-element groups,
|
||||
one group uneven where the message does not divide). Eight ranks have no lossy wire, and
|
||||
`--tp 8 --tp-wire wht6` stops at startup naming the all-reduce it found no kernel for, and
|
||||
`--tp-wire exact`. The exact wire at three, four and eight ranks is one-shot up to 1 MiB a message
|
||||
and two-shot above it, which sends 2·(ranks−1)/ranks of the message per rank instead of
|
||||
(ranks−1) times it; the two produce the same bits.
|
||||
|
||||
On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's
|
||||
write, with the MoE gather in front of it. At two ranks that holds on either wire: the rotated
|
||||
@@ -983,9 +1018,10 @@ one line naming each one the command line moved.
|
||||
|
||||
| flag | |
|
||||
|---|---|
|
||||
| `--model PATH` | the `.rad` container, or a checkpoint served as it stands (§3.4) (**required**) |
|
||||
| `--model PATH` | the `.rad` container, a checkpoint served as it stands (§3.4), or a Hugging Face repo id fetched before startup (§3.1) (**required**) |
|
||||
| `--download-dir DIR` | where a repo id is fetched to. Default `$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf` |
|
||||
| `--radiance-home DIR` | where `kernels/` and `architectures/` live |
|
||||
| `--kernels LIST` | kernel plugin hierarchy, comma-separated, first wins |
|
||||
| `--kernels LIST` | the kernel libraries to use, comma-separated, first wins; a library not named is not loaded. Default: every library found |
|
||||
|
||||
**Batch shape**
|
||||
|
||||
@@ -1001,11 +1037,9 @@ one line naming each one the command line moved.
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
|
||||
| `--vram-weights-mib N` | derive | the resident weight slab |
|
||||
| `--vram-kv-mib N` | derive | the paged KV pool |
|
||||
| `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--embedding-placement WHERE` | auto | `auto`, `vram` or `ram`: the token embedding on the card or in the pinned host pool, read in place; `disk` is refused. See §4.3 |
|
||||
| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card. See §4.3 |
|
||||
| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container. See §4.3 |
|
||||
| `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time |
|
||||
|
||||
@@ -1051,7 +1085,7 @@ one line naming each one the command line moved.
|
||||
|---|---|---|
|
||||
| `--host ADDR` | 0.0.0.0 | listen address |
|
||||
| `--port N` | 8000 | listen port |
|
||||
| `--api-key KEY` | — | require `Authorization: Bearer KEY` on every request but `/health`, `/ping` and the dashboard page (§6.6) |
|
||||
| `--api-key KEY` | — | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
|
||||
| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the one loaded serves it |
|
||||
| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card |
|
||||
| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the one the container carries. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
|
||||
@@ -1096,7 +1130,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)
|
||||
@@ -1131,13 +1166,19 @@ for a model that takes no images or video.
|
||||
| `POST /v1/chat/completions` | chat, with tools, reasoning and streaming |
|
||||
| `POST /v1/completions` | raw text completion |
|
||||
| `POST /v1/embeddings` | needs a model with an embedding head, else 501 |
|
||||
| `GET /v1/models`, `/v1/models/:id` | what is loaded |
|
||||
| `GET /health`, `/ping`, `POST /ping` | liveness |
|
||||
| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs — §5.9 |
|
||||
| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client — §5.9 |
|
||||
| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and the clients built on llama-server's own API — §5.9 |
|
||||
| `GET /v1/models`, `/v1/models/:id` | what is loaded, with `max_model_len` (the context it serves) and `root` (the `--model` path), as vLLM reports them, and `capabilities` (the same object `/server_info` reports); `:id` answers the entry itself, as OpenAI's retrieve does |
|
||||
| `GET /health`, `/v1/health`, `/ping`, `POST /ping` | liveness |
|
||||
| `GET /load` | current load |
|
||||
| `GET /version` | server version |
|
||||
| `GET /props` | llama-server's props for the clients built against it: `n_ctx`, `total_slots`, `modalities`, `model_path`, the chat template and its capabilities, `bos_token`/`eos_token`, and the request defaults under llama-server's names |
|
||||
| `POST /apply-template` | the prompt a chat request renders to, as llama-server answers it |
|
||||
| `POST /v1/chat/completions/input_tokens` | how many tokens that prompt is |
|
||||
| `GET /server_info` | the whole configuration of the running engine |
|
||||
| `GET /metrics` | Prometheus |
|
||||
| `POST /tokenize`, `POST /detokenize` | |
|
||||
| `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
|
||||
| `GET /get_tokenizer_info` | |
|
||||
| `POST /reset_prefix_cache` | drop every cached prefix |
|
||||
| `GET /` or `/dashboard` | the web dashboard |
|
||||
@@ -1145,7 +1186,9 @@ for a model that takes no images or video.
|
||||
|
||||
Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is POST because its
|
||||
input is a body, and `/ping` answers both GET and POST because different load balancers send
|
||||
different ones.
|
||||
different ones. As llama-server does, `/chat/completions`, `/embeddings` and `/models` answer without the `/v1`
|
||||
too, for a client configured with the bare host as its base URL -- and `/completions` without it is
|
||||
llama-server's native completion, as it is there. A path nothing serves is a JSON 404.
|
||||
|
||||
A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control
|
||||
tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
|
||||
@@ -1279,7 +1322,8 @@ grammar: this model's chat template produced no grammar for it, so the constrain
|
||||
be enforced
|
||||
```
|
||||
|
||||
That is the refused-not-ignored rule (§5.8) doing its job: an unconstrained 200 would leave you
|
||||
That is §5.8's rule doing its job -- a field that would change the answer is honoured or
|
||||
refused, never dropped: an unconstrained 200 would leave you
|
||||
parsing free prose against a schema you were told was enforced. `/v1/completions` has no template
|
||||
in the way, so the same grammar works there — which is why the example above uses it.
|
||||
|
||||
@@ -1300,9 +1344,54 @@ curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \
|
||||
|
||||
curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
|
||||
-d '{"tokens":[15339,1917]}'
|
||||
|
||||
curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \
|
||||
-d '{"content":"hello world","with_pieces":true}' # llama-server's shape
|
||||
```
|
||||
|
||||
`/tokenize` takes `prompt` **or** `messages`, not both.
|
||||
`/tokenize` takes one of `prompt`, `messages` or llama-server's `content` (a string, or strings and
|
||||
token ids mixed, with its `add_special` and `parse_special` and their defaults); the `content`
|
||||
form answers `tokens` as llama-server does, as `{id, piece}` objects with `with_pieces`.
|
||||
`/detokenize` answers the text as both `prompt` (vLLM) and `content` (llama-server).
|
||||
|
||||
**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
|
||||
|
||||
@@ -1310,13 +1399,13 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
|
||||
|---|---|
|
||||
| `model` | accepted and not enforced — one server serves one model |
|
||||
| `messages` / `prompt` / `input` | chat / completion / embedding |
|
||||
| `max_tokens`, `max_completion_tokens` | default: what the context leaves after the prompt (`--default-max-tokens`). Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 |
|
||||
| `max_tokens`, `max_completion_tokens`, `n_predict` | default: what the context leaves after the prompt (`--default-max-tokens`); -1 is llama-server's "no limit", the same without the default. Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 |
|
||||
| `temperature` | [0, 2] |
|
||||
| `top_p` | (0, 1] |
|
||||
| `top_k` | ≥ 0, 0 disables |
|
||||
| `min_p`, `typical_p` | |
|
||||
| `presence_penalty`, `frequency_penalty` | [-2, 2] |
|
||||
| `repetition_penalty`, `repeat_last_n` | |
|
||||
| `repetition_penalty` (or `repeat_penalty`), `repeat_last_n` | |
|
||||
| `xtc_probability`, `xtc_threshold` | |
|
||||
| `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | |
|
||||
| `seed` | absent means "pick one" — **not** seed 0 |
|
||||
@@ -1325,54 +1414,64 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
|
||||
| `stop` | a string or an array; at most 64 strings of 4096 bytes (`--max-stop-strings`, `--max-stop-bytes`) |
|
||||
| `ignore_eos` | generate to `max_tokens` whatever the model emits |
|
||||
| `stream`, `stream_options.include_usage` | |
|
||||
| `logprobs`, `top_logprobs` | **not implemented** — refused, not returned as nulls. `/server_info` reports `logprobs: false` |
|
||||
| `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
|
||||
| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC with temperature first (the default) or last (llama-server's default), so a list in either of those orders is honoured and any other is refused by name |
|
||||
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
|
||||
| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives — see §5.11. Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
|
||||
| `add_generation_prompt`, `chat_template_kwargs` | chat only |
|
||||
| `continue_final_message` | chat only. A conversation ending in an assistant message is continued rather than answered, as llama-server and the Anthropic API do -- the reply carries that message's text and what follows it. `true`, `"content"` or `"reasoning_content"` names it explicitly; `add_generation_prompt: true` opens a new turn instead |
|
||||
| `reasoning_format` | chat only, llama-server's: `none` keeps the reasoning in `content`; `auto` and `deepseek` split it into `reasoning_content`, the default |
|
||||
| `reasoning_effort`, `enable_thinking` | chat only. The levels are the template's (`capabilities.reasoning_efforts` on `/server_info`); `none` and `minimal` turn thinking off |
|
||||
| `thinking_token_budget`, `thinking_budget` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2. Default `--thinking-token-budget`, else none |
|
||||
| `thinking_token_budget`, `thinking_budget`, `thinking_budget_tokens`, `reasoning_budget_tokens` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2; -1 is none. Default `--thinking-token-budget`, else none |
|
||||
| `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it |
|
||||
| `response_format` | chat only. Mutually exclusive with `grammar` |
|
||||
| `response_format`, `json_schema` | chat only. `json_schema` is llama-server's shorthand: the schema itself. Mutually exclusive with `grammar` |
|
||||
| `functions`, `function_call` | chat only: OpenAI's deprecated spellings of `tools` and `tool_choice`. The reply answers in the old shape too: one call at most, as `message.function_call` with `finish_reason: "function_call"`; the next turn's assistant `function_call` and `function` message are read as the call and its result |
|
||||
| `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.
|
||||
|
||||
### 5.8 A parameter this server does not implement is **refused**, not ignored
|
||||
### 5.8 What a field this server does not implement does
|
||||
|
||||
This is the one place radiance deliberately differs from what an OpenAI client may expect, and it
|
||||
will be the first thing you hit pointing an existing client at it:
|
||||
Four kinds of field, and the rule they serve is that **a request that returns 200 had every field
|
||||
that could change its answer honoured**:
|
||||
|
||||
- **Accepted** — the table above, in OpenAI's, vLLM's and llama-server's spellings.
|
||||
- **Inert** — fields that change nothing about the answer, accepted and ignored: OpenAI's and
|
||||
OpenRouter's bookkeeping (`user`, `metadata`, `store`, `service_tier`, `safety_identifier`,
|
||||
`prompt_cache_key`, `prediction`), and llama-server's knobs for its own speed and slots
|
||||
(`cache_prompt`, `id_slot`, `n_cache_reuse`, `backend_sampling`, `reasoning_control`, `n_keep`,
|
||||
`n_discard`, `speculative.*`, ...). The prefix cache and speculation here are the server's own
|
||||
and never change the output.
|
||||
- **Guarded** — known, not implemented, and able to change the answer. llama-server's clients send
|
||||
every one of them on every request at its off value, so each is accepted there and refused,
|
||||
naming it, at any other:
|
||||
|
||||
```json
|
||||
{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13)", ...}}
|
||||
{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13); it is accepted only at 0, where it does nothing", ...}}
|
||||
```
|
||||
|
||||
The rule is that **a request that returns 200 means every field of it was honoured**. Silently
|
||||
dropping a sampler setting and answering 200 is how a deployment ends up serving a model at
|
||||
settings nobody chose.
|
||||
| guarded | accepted at | because |
|
||||
|---|---|---|
|
||||
| `logit_bias` | empty | the device sampler has no per-token bias stage |
|
||||
| `mirostat` | 0 | not one of the device samplers |
|
||||
| `top_n_sigma` | ≤ 0 | not one of the device samplers |
|
||||
| `dynatemp_range` | 0 | not one of the device samplers |
|
||||
| `min_keep` | 0 | the cuts keep no minimum count |
|
||||
| `post_sampling_probs` | false | logprobs are the raw distribution's; the sampler's are not returned |
|
||||
| `best_of` | 1 | not implemented |
|
||||
| `suffix` | empty | infilling through `/v1/completions` is not implemented |
|
||||
| `lora` | empty | explicitly out of scope |
|
||||
| `modalities`, `audio` | `["text"]`, null | output other than text is not implemented |
|
||||
| `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, 0, false | not implemented |
|
||||
| `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty | the chat format decides them |
|
||||
|
||||
Three lists decide it:
|
||||
|
||||
- **Accepted** — the table above.
|
||||
- **Inert** — OpenAI metadata that genuinely does nothing anywhere, accepted and ignored so the
|
||||
official SDKs work: `user`, `metadata`, `store`, `service_tier`, `safety_identifier`,
|
||||
`prompt_cache_key`.
|
||||
- **Refused with a reason** — known, not implemented, each named:
|
||||
|
||||
| refused | because |
|
||||
|---|---|
|
||||
| `logit_bias` | the device sampler has no per-token bias stage |
|
||||
| `functions`, `function_call` | deprecated — send `tools` / `tool_choice` |
|
||||
| `best_of` | sampling n candidates and returning the best is not implemented |
|
||||
| `suffix` | infilling is not implemented |
|
||||
| `mirostat`, `mirostat_tau`, `mirostat_eta` | not one of the device samplers |
|
||||
| `top_n_sigma`, `dynatemp_range`, `dynatemp_exponent` | not one of the device samplers |
|
||||
| `lora` | explicitly out of scope |
|
||||
| `modalities`, `audio`, `prediction` | not implemented |
|
||||
| `continue_final_message` | assistant prefill is not implemented |
|
||||
| `cache_prompt` | prefix caching is a server-wide setting, not per request |
|
||||
|
||||
Anything else unrecognised is refused too, naming the key.
|
||||
- **Anything else is ignored**, as llama-server and vLLM ignore it: a field this server has never
|
||||
heard of is a client's own extension far more often than a request it misunderstood. The names
|
||||
are logged at debug.
|
||||
|
||||
**The one exception is `max_tokens`.** If `prompt + max_tokens` would exceed the context, the
|
||||
server clamps `max_tokens` to what is left and serves the request:
|
||||
@@ -1404,7 +1503,56 @@ precisely without running the model.
|
||||
|
||||
---
|
||||
|
||||
### 5.9 What a response says about its own speed
|
||||
|
||||
### 5.9 Anthropic's, OpenAI's Responses and llama-server's native APIs
|
||||
|
||||
`POST /v1/messages` takes Anthropic's request and answers in Anthropic's shapes, streamed
|
||||
(`message_start`, content blocks, `message_delta`, `message_stop`) or not, so Claude Code and the
|
||||
Anthropic SDKs work against radiance as they do against llama-server:
|
||||
|
||||
```sh
|
||||
ANTHROPIC_BASE_URL=http://localhost:8000 ANTHROPIC_API_KEY="$KEY" claude
|
||||
```
|
||||
|
||||
It is translated into the chat request it means and served by the chat path, so the template
|
||||
defaults, refusals and limits are the chat endpoint's. `system` (a string or text blocks), text and
|
||||
image blocks, `tool_use` and `tool_result`, client tools and `tool_choice`, `stop_sequences`,
|
||||
`thinking` (`enabled` with a `budget_tokens`, `disabled`, `adaptive`) and `metadata.user_id` (the
|
||||
conversation's label on `/sessions`) are honoured. A conversation that ends in an assistant message
|
||||
is continued, and the answer carries what follows it. Thinking blocks come back with an empty
|
||||
`signature`. Claude Code's per-request billing stamp at the head of the system prompt is held
|
||||
constant, as llama-server holds it, or no turn could reuse the prefix of the one before.
|
||||
`document` blocks and Anthropic's server tools (`web_search_…`, `code_execution_…`) run on
|
||||
Anthropic's side and are refused by name. `POST /v1/messages/count_tokens` answers the prompt's
|
||||
length. The key may come as `X-Api-Key` (§6.6).
|
||||
|
||||
`POST /v1/responses` is OpenAI's Responses API, translated the same way: `instructions` and `input`
|
||||
(a string, or message, `function_call`, `function_call_output` and `reasoning` items) become the
|
||||
conversation, `max_output_tokens` and `reasoning.effort` and `text.format` the chat request's
|
||||
fields, and every field the Responses API does not define passes through to the chat request as it
|
||||
does in llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response object, or
|
||||
its event stream with every event's `output_index`, `content_index` and `sequence_number`; a reply
|
||||
cut at `max_output_tokens` is `incomplete`. Function tools are offered to the model; the built-in
|
||||
tools (web search, file search, computer use) and freeform custom tools have no counterpart here
|
||||
and are left out, as llama-server leaves them out. Responses are not stored, so
|
||||
`previous_response_id` is refused: send the conversation as `input`. What a response object
|
||||
cannot carry is refused rather than computed and dropped: `n` other than 1, and logprobs
|
||||
(`include` naming `message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`) --
|
||||
`/v1/chat/completions` serves those. A failed generation ends the stream in
|
||||
`response.failed`, as one on `/v1/messages` ends in Anthropic's `error` event.
|
||||
|
||||
`POST /completion` (and `/completions` without `/v1`, as llama-server names it) is llama-server's
|
||||
native completion: a prompt string, token ids, or strings and ids mixed as one prompt; the
|
||||
request fields of §5.7; and llama-server's answer -- `content`, `stop_type` (`eos`, `limit`,
|
||||
`word`), `stopping_word`, `tokens_predicted`, `tokens_evaluated`, `generation_settings`,
|
||||
`timings`, and the generated ids with `return_tokens`. A stream is its chunks with the ids that
|
||||
made each, then the final result, with no `[DONE]`. `POST /infill` completes between
|
||||
`input_prefix` and `input_suffix`, with `input_extra` (files, `{filename, text}`) and `prompt`, in
|
||||
the repository-level fill-in-the-middle layout llama-server builds, byte for byte. It needs a model
|
||||
with fill-in-the-middle tokens (the Qwen, StarCoder, DeepSeek and CodeLlama spellings are
|
||||
recognised) and answers 501 without them; the extra files give way first when the prompt does not
|
||||
fit.
|
||||
### 5.10 What a response says about its own speed
|
||||
|
||||
Every chat and completion response carries a top-level `timings` object for the request. It uses
|
||||
llama.cpp's field names, so a proxy or dashboard built against llama-server (llama-swap's activity
|
||||
@@ -1440,6 +1588,47 @@ When streaming, each choice's final chunk (the one with `finish_reason`) carries
|
||||
when asked for, carries the request's. `/metrics` stays the aggregate surface (§6.3). It sums
|
||||
the same quantities over every request, so it cannot say which request they belong to.
|
||||
|
||||
### 5.11 Logprobs
|
||||
|
||||
The numbers are the **raw distribution's** — the logits as the model wrote them, before any
|
||||
penalty, temperature, grammar mask or cut — which is what OpenAI and llama-server report. Each
|
||||
generated token carries its own logprob and its `top_logprobs` most likely alternatives, at most 20.
|
||||
|
||||
```bash
|
||||
curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{
|
||||
"messages": [{"role": "user", "content": "Say hi"}], "temperature": 0,
|
||||
"logprobs": true, "top_logprobs": 2, "max_tokens": 4 }' | jq -c '.choices[0].logprobs.content[0]'
|
||||
```
|
||||
|
||||
Qwen3.5-0.8B, thinking off:
|
||||
|
||||
```json
|
||||
{"id":9419,"token":"Hello","bytes":[72,101,108,108,111],"logprob":-0.7186,
|
||||
"top_logprobs":[{"id":9419,"token":"Hello","bytes":[72,101,108,108,111],"logprob":-0.7186},
|
||||
{"id":12675,"token":"Hi","bytes":[72,105],"logprob":-1.3188}]}
|
||||
```
|
||||
|
||||
- **Chat** answers in OpenAI's shape, with llama-server's `id` beside each token; a stream carries
|
||||
each token's entry on the chunk that carries its text.
|
||||
- **`/v1/completions`** answers OpenAI's legacy arrays (`tokens`, `token_logprobs`, `top_logprobs`
|
||||
as one `{text: logprob}` object a token, `text_offset`) and llama-server's `content` array beside
|
||||
them.
|
||||
- **`/completion`** (`n_probs`) answers llama-server's `completion_probabilities`.
|
||||
- A token that ends inside a UTF-8 character has the readable part as `token` and every byte in
|
||||
`bytes`, as llama-server does. A stop string's own tokens are not reported, since their text never
|
||||
went out.
|
||||
|
||||
Speculation is unaffected — every verified position is scored, and an accepted draft is the token
|
||||
the model drew there. The cost is a top-k's worth of work for each row that asks
|
||||
(`sample_logprobs`, docs/OPS.md): about 0.12 ms a step on an R9700 at a 248K vocabulary, on the
|
||||
card. The chosen token's logprob is exact when it is among the raw top 20; otherwise it is
|
||||
recovered from the value it was drawn at by undoing temperature, DRY and the penalties, which
|
||||
agrees to float rounding.
|
||||
|
||||
**Where llama-server differs:** `logprobs: true` without `top_logprobs` returns 20 alternatives
|
||||
there and none here, which is OpenAI's default. The values themselves agree with llama-server's to
|
||||
bf16 rounding (within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included).
|
||||
|
||||
## 6. Operate it
|
||||
|
||||
### 6.1 The dashboard
|
||||
@@ -1566,12 +1755,13 @@ any origin can call the API from a browser; `--no-cors` turns it off.
|
||||
radiance --model m.rad --api-key "$KEY"
|
||||
```
|
||||
|
||||
With a key, every request must carry `Authorization: Bearer KEY` or it is answered 401 —
|
||||
`/tokenize` and `/server_info` included, since they hand out the vocabulary, the chat template and
|
||||
the configuration. Three paths are exempt: `/health` and `/ping`, because a load balancer cannot
|
||||
carry a bearer token and an authenticated probe is a server that reports itself down, and the
|
||||
dashboard page itself (`/`, `/dashboard`), which holds no data — on a 401 it shows a key field,
|
||||
keeps the key in the browser's storage and sends it on every fetch of data it makes.
|
||||
With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's `X-Api-Key: KEY`)
|
||||
or it is answered 401 — `/tokenize` and `/server_info` included, since they hand out the
|
||||
vocabulary, the chat template and the configuration. Three paths are exempt: `/health` (and
|
||||
`/v1/health`) and `/ping`, because a load balancer cannot carry a bearer token and an
|
||||
authenticated probe is a server that reports itself down, and the dashboard page itself (`/`,
|
||||
`/dashboard`), which holds no data — on a 401 it shows a key field, keeps the key in the browser's
|
||||
storage and sends it on every fetch of data it makes.
|
||||
|
||||
The key is checked, not encrypted: on any network you do not control, bind to localhost and put a
|
||||
TLS-terminating reverse proxy in front:
|
||||
@@ -1604,6 +1794,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` |
|
||||
@@ -1627,10 +1818,11 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al
|
||||
| | |
|
||||
|---|---|
|
||||
| `RADIANCE_HOME` | where `kernels/`, `architectures/` and `quantizers/` live; a `:`-separated search path, the first home winning. Same as `--radiance-home` |
|
||||
| `RADIANCE_KERNELS` | default kernel hierarchy, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers |
|
||||
| `RADIANCE_KERNELS` | default kernel libraries, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers |
|
||||
| `RADIANCE_LOG` | `error` \| `warn` \| `info` \| `debug` \| `trace` |
|
||||
| `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` |
|
||||
| `HF_TOKEN` | for `scripts/hfget.sh` on a gated repo |
|
||||
| `HF_TOKEN` | for `scripts/hfget.sh`, and `--model <owner/name>`, on a gated or private repo |
|
||||
| `XDG_CACHE_HOME` | where `--model <owner/name>` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) |
|
||||
|
||||
**Tooling**
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ core/sample/ device sampler dispatch + the host reference chain + grammar b
|
||||
core/text/ tokeniser, chat template, tool parsing, detokenisation
|
||||
core/mm/ image and video decoding, and the processor that turns frames into patches
|
||||
core/format/ the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache
|
||||
core/server/ HTTP, OpenAI-compatible endpoints, /metrics, the dashboard
|
||||
core/server/ HTTP: the OpenAI, Anthropic and llama-server endpoints, /metrics, the dashboard
|
||||
core/kld.* the KL mode: --kld-record / --kld-ref
|
||||
core/engine* the thing that ties them together, and `radiance` the binary
|
||||
libref/ every op, naively, correct, host domain: the fallback and the oracle
|
||||
|
||||
@@ -252,6 +252,7 @@ not.
|
||||
| `sample_argmax` | yes | device | host |
|
||||
| `sample_chain` | | device | - |
|
||||
| `sample_dry` | yes | device | host |
|
||||
| `sample_logprobs` | | device | host |
|
||||
| `sample_mask` | yes | device | host |
|
||||
| `sample_merge_topk` | | device | host |
|
||||
| `sample_minp` | yes | device | host |
|
||||
|
||||
+1
-2
@@ -243,8 +243,7 @@ its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotat
|
||||
Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from
|
||||
the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so
|
||||
drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96
|
||||
requests in flight, with a KV pool that holds 64 sequences' recurrent state (`--vram-kv-mib`
|
||||
states it outright). That records ~930 tokens a second, ten million tokens in three hours.
|
||||
requests in flight, with a KV pool that holds 64 sequences' recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
|
||||
|
||||
**The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand
|
||||
tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ
|
||||
|
||||
+107
-6
@@ -158,7 +158,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `w`w → `y` |
|
||||
| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) |
|
||||
| `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` |
|
||||
| `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` |
|
||||
| `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? |
|
||||
@@ -168,6 +168,15 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
|
||||
| `add` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
|
||||
| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
|
||||
| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) |
|
||||
| `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) |
|
||||
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
|
||||
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
|
||||
| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
|
||||
| `relu` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
|
||||
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` | `x`, `w`w, `cu_seqlens`, `valid`? → `y` |
|
||||
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` |
|
||||
| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
|
||||
| `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `cast` | `M`(range) `n` `from` `to` | `x` → `y` |
|
||||
| `softmax` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
@@ -224,6 +233,54 @@ attention-zero rank's block (`docs/TP3.md`) is one `fill` of its output wire bef
|
||||
A wire shared across layers cannot be zeroed once a step, and a memset knows neither the row pitch
|
||||
nor the dtype; this does.
|
||||
|
||||
**`mul_weight`** is a learned gain on an activation: `w` is a WEIGHT of one element, a scalar for
|
||||
the whole output -- Gemma 4's per-layer `layer_scalar` on the residual stream -- or of one row,
|
||||
broadcast down the rows (a per-channel layer scale). Its own op rather than a form of `mul`
|
||||
because an operand is a weight or an activation by its schema, and `mul`'s `b` is an activation.
|
||||
`scalar` 1 states the one-element form; kernels read the form off the operand, and the parameter
|
||||
is what lets a shape description (rad-kbench's) build the right weight.
|
||||
|
||||
**`act_mul`** is `silu_mul` with its two halves in two operands, so the multiplier can be any
|
||||
tensor -- the two column slices of a fused `gate_up`, or a gate and a separate per-layer input
|
||||
(EmbeddingGemma 2's per-layer-embedding block multiplies `gelu_tanh(gate(x))` by one). `act` is
|
||||
`silu`, `gelu` (exact erf), `gelu_tanh` or `sigmoid` (a GLU's gate: `a` the gate half, `b` the
|
||||
value half); the activation is rounded to `y`'s dtype before the product, which is what the
|
||||
unfused pair stores.
|
||||
|
||||
**`seg_mean`** is a sentence embedding's mean pooling over a ragged batch: row `s` of `y` is the
|
||||
mean of `x`'s rows `[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token
|
||||
count and bands the op; the segment count is `cu_seqlens`' length less one. An empty segment is a
|
||||
zero row.
|
||||
|
||||
**`pool_rows`** is a vision pooler over windows its processor laid out consecutively: row `r` of `y`
|
||||
is the mean of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times
|
||||
`mult` and rounded again (the unfused pair stores the mean). `M` is the input row count and a
|
||||
multiple of `k`.
|
||||
|
||||
**`rmsnorm`'s `mult`** scales the normed row before its one rounding: a residual branch weighted by
|
||||
a constant -- Gemma 4's audio feed-forward adds half of its output -- with no second pass. For a
|
||||
power of two it is exactly the reference's norm-then-scale, since scaling by one commutes with the
|
||||
rounding.
|
||||
|
||||
**The audio tower's operators** (Gemma 4's USM conformer):
|
||||
|
||||
- **`relu`** is `max(x, 0)` at each operand's own row pitch.
|
||||
- **`clamp`** is `min(max(x, lo), hi)` with `lo` and `hi` WEIGHTS of one element each -- a clipped
|
||||
linear's input or output range, which the checkpoint states per projection.
|
||||
- **`conv2d`** convolves over (time, width) with channels innermost: element `(t, w, c)` of `x` is
|
||||
at row `t`, column `w * cin + c`, and `w` is PyTorch's `[cout, cin, kh, kw]`. Each `cu_seqlens`
|
||||
segment -- rows `[cu[s] / cu_div, cu[s+1] / cu_div)` -- is convolved on its own with zero padding
|
||||
`pad` at its edges on both axes, so two clips in one pass never see each other, and its output
|
||||
rows start at `cu[s] / (cu_div * stride)` (a segment whose start does not divide is refused).
|
||||
With the optional `valid`, input row `t` reads as zeros unless `valid[t * valid_stride] != 0`:
|
||||
the frame mask the subsampler multiplies in before each convolution. f32 sum, one rounding.
|
||||
- **`conv1d_dw`** is a causal depthwise convolution over time, `y[t, c] = sum_j w[c, 0, j] *
|
||||
x[t - (k - 1) + j, c]`, with the rows before the segment's start reading as zeros.
|
||||
- **`rel_sinusoid`** writes the sinusoidal relative-position table, row `d` for distance `d`:
|
||||
`sin(d * inv[i])` over the first half and `cos(d * inv[i])` over the second, `inv[i] = exp(i *
|
||||
-log(max_timescale) / max(n/2 - 1, 1))`, each step in f32 as the reference's torch expressions
|
||||
are, then rounded.
|
||||
|
||||
## Quantisation and rotation
|
||||
|
||||
| op | params | operands |
|
||||
@@ -369,11 +426,22 @@ that folds dequantisation into its epilogue still receives them.
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
|
||||
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` |
|
||||
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
|
||||
**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a
|
||||
softcap. Query row `i` of a segment sees the key rows `j` of the same segment with `0 <= i - j <=
|
||||
left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)` -- softplus
|
||||
rounded to `pds`'s dtype, as the reference evaluates it on the parameter -- and `logit = qf . k *
|
||||
(ln(1 + e) / ln 2) + qf . relk[i - j]`, then `softcap * tanh(logit / softcap)`, a softmax over the
|
||||
visible keys and the weighted sum of `v`, all in f32 and rounded once. `relk` is `[left + 1,
|
||||
n_head * head_dim]`, row `d` the projected position for distance `d`. The reference computes this
|
||||
in 12-query blocks over 24-key windows with a Transformer-XL shift; every key outside the window
|
||||
carries a `-1e9` logit there, so the sliding form is the same function.
|
||||
|
||||
`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at
|
||||
a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each
|
||||
@@ -388,11 +456,24 @@ row each — is what the scheduler builds whenever prefill and decode coexist, a
|
||||
satisfy the uniform form. `q_len` is then the batch MAXIMUM, which is what selects the band; the
|
||||
per-sequence lengths come from `cu_seqlens` alone.
|
||||
|
||||
`attn_dense` is the vision tower's: non-causal, nothing paged, `cu_seqlens` bounding one image per
|
||||
entry so a whole batch is one launch. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
|
||||
`attn_dense` is the vision tower's and an encoder's: nothing paged, `cu_seqlens` bounding one
|
||||
image or one input per entry so a whole batch is one launch. `window` is `attn_paged`'s rule over a
|
||||
segment's own positions -- causal, key `j` is visible to query `i` when `i - j < window`;
|
||||
non-causal, when `|i - j| < window` -- and 0 is no window. A bidirectional encoder's sliding layer
|
||||
of radius `r` (`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads, head_dim]` or
|
||||
`[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read
|
||||
at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy.
|
||||
|
||||
**`qk_norm_rope`'s `v_norm`** set to 1 also RMS-norms every v head of the fused row with a UNIT
|
||||
gain and does not rotate it: Gemma 4's value norm, which has no weight to name.
|
||||
|
||||
**`qk_norm_rope`'s `blocks` mode** rotates each section as its own block of channels: section `c`
|
||||
is `sections[c]` pairs over the next `2 * sections[c]` channels, paired `(start + j, start +
|
||||
sections[c] + j)` -- NeoX inside the block -- and turned by position component `comps[c]` (default
|
||||
`c`) at `theta^(-j / sections[c])`. The sections fill `rotary_dim` exactly and `positions` is
|
||||
`[C, M]`. It is Gemma 4's vision rotary: x over the first half of each head and y over the second,
|
||||
each half a complete rotary of its own; `mode` `axial` of `rope` pairs across the halves instead.
|
||||
|
||||
**`rope`'s multi-component modes.** `mrope`, `imrope` and `axial` rotate with NeoX pairing and let
|
||||
several position components drive different frequencies. `positions` is then `[C, M]`,
|
||||
component-major, and `sections` names how many of the `rotary_dim / 2` frequencies each component
|
||||
@@ -823,7 +904,7 @@ form exists, as for `ar_hc_write`.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w → `x` |
|
||||
| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt `mult`:f64/opt | `tokens`, `wte`w → `x` |
|
||||
| `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? |
|
||||
| `logits_gemm` | `M`(range) `n_vocab` `n_embd` `dtype` | `x`, `lm_head`w → `logits` |
|
||||
| `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? |
|
||||
@@ -880,6 +961,14 @@ bf16 would matter, because `libref` is the oracle for every op here and its bf16
|
||||
float, which is not guaranteed to return a NaN payload unchanged. At u8 every value is 0..255,
|
||||
float carries it exactly, and oracle and kernel agree bit for bit on any payload at all.
|
||||
|
||||
### `embed_lookup`'s `mult`
|
||||
|
||||
Every gathered row multiplied by `mult` and rounded once to `x`'s dtype; absent, the gather is a
|
||||
plain copy. Gemma scales its embedding by `sqrt(hidden)` held in a bf16 buffer, so the plugin
|
||||
passes that value rounded to bf16 (22.625 at a hidden of 512, not 22.6274) and the product is the
|
||||
reference's to the bit. `wscale` is not this: it is the scale `embed_lookup_q`'s layout quantises
|
||||
with, and `embed_lookup` reads none.
|
||||
|
||||
### `embed_lookup`'s `vocab_offset`
|
||||
|
||||
`vocab_offset` (optional, default 0) is the first vocabulary row this rank holds. With it,
|
||||
@@ -1107,10 +1196,22 @@ resolutions of one op — which is not something a batch can contain.
|
||||
| `sample_pick` | `M`(range) `n_cand` | `cand_idx`, `cand_val`, `params` → `token` |
|
||||
| `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` |
|
||||
| `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
|
||||
| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
|
||||
|
||||
`sample_mask` is where a GBNF grammar lands: the state machine stays on host and what crosses is a
|
||||
token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every step.
|
||||
|
||||
`sample_logprobs` is what an OpenAI `logprobs` field or llama-server's `n_probs` reads. It runs on
|
||||
the RAW logits, before any stage has touched them, and only for a row whose flags carry
|
||||
`RAD_SP_LOGPROBS`; other rows are not written. `stats` is `[M, 2 + 2k]` f32: the row's maximum, the
|
||||
sum of `exp(l - max)` over it, and its `k` largest as (id, logit) pairs, descending, ties to the
|
||||
lower id, the id written as a float (exact below 2^24) and GLOBAL under a split vocabulary
|
||||
(`vocab_off` added). A slot past the vocabulary is id -1, logit -infinity. `k` is geometry: the one
|
||||
width every request's `top_logprobs` fits in. The engine declares 21 -- OpenAI's bound of 20, plus
|
||||
one so that a row is 44 floats, whole 16-byte words, which the vocab-parallel `all_gather` moves. A
|
||||
token's logprob is `l - max - log(sum)`; under a split vocabulary the host merges the ranks' rows
|
||||
(the maxima and sums by the usual rescale, the pairs by value).
|
||||
|
||||
### Stages the decomposed chain does not carry
|
||||
|
||||
| op | params | operands |
|
||||
|
||||
+10
-7
@@ -344,8 +344,7 @@ can also decline it with `RAD_E_UNSUPPORTED`.
|
||||
**Which devices.** Discrete cards are used when there are any, and of those the ones sharing the
|
||||
first one's architecture; integrated graphics only when it is all there is. `ROCR_VISIBLE_DEVICES`
|
||||
chooses explicitly. On integrated graphics the device memory is the host's: the budget is bounded by
|
||||
what the host has available and leaves an eighth of the host's memory to it; `--vram-kv-mib` and
|
||||
`--vram-weights-mib` state the pools outright.
|
||||
what the host has available and leaves an eighth of the host's memory to it.
|
||||
|
||||
**What the core assumes of a card: nothing about its wave size**, its LDS, its fp8 hardware or its
|
||||
links — those are your kernels' business. Three things are worth knowing before you start:
|
||||
@@ -478,8 +477,12 @@ RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --mod
|
||||
and the container image takes one the same way, mounted:
|
||||
`-v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance`.
|
||||
|
||||
**The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list: `--kernels
|
||||
mykernels,libr4d` puts you in front. An entry matches a plugin's name or its file stem, and **the
|
||||
list is comma-separated** — the tools also accept colons, the engine's `--kernels` and
|
||||
`$RADIANCE_KERNELS` do not, so write commas everywhere. A library on the search path that nobody
|
||||
named loads after everything named, and a reference library (§1) after that.
|
||||
**The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list of the kernel
|
||||
libraries to use: `--kernels mykernels,libr4d` puts you in front of libr4d. An entry matches a
|
||||
plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library), and an
|
||||
entry that matches nothing is warned about by name. **The list is comma-separated** — the tools
|
||||
also accept colons, the engine's `--kernels` and `$RADIANCE_KERNELS` do not, so write commas
|
||||
everywhere. A kernel
|
||||
library on the search path that the list does not name is not loaded, so name every library you
|
||||
want, the host library (`libavx`) and the reference (`libref`) included. With no list every library
|
||||
found loads, a reference library (§1) last.
|
||||
+32
-6
@@ -89,7 +89,8 @@ rad-convert [options] <input> -o <model.rad>
|
||||
--list-quantizers every quantiser loaded and the options it takes
|
||||
--arch ID override the architecture id from the checkpoint
|
||||
--home DIR $RADIANCE_HOME
|
||||
--kernels A:B kernel plugin hierarchy, first wins. Default $RADIANCE_KERNELS
|
||||
--kernels A:B the kernel libraries to load, first wins. Default $RADIANCE_KERNELS,
|
||||
else every library found
|
||||
--tokenizer F tokenizer.json; its declared chain is baked instead of being
|
||||
reconstructed from a pre-tokenizer name
|
||||
--imatrix F llama.cpp imatrix: expert profile, column importances, error weighting
|
||||
@@ -214,6 +215,13 @@ CALIB=<calibration dir> rad-convert <Qwen3.8-Flash-Next checkpoint> -o flashnext
|
||||
# has is wanted (GUIDE §3.4)
|
||||
rad-convert <Qwen3.8-27B-FP8 checkpoint> -o q38-27b-fp8.rad
|
||||
|
||||
# A bf16 checkpoint of the same model, as that release's block fp8 (the recipe's header has the
|
||||
# --set keys that select the fp8 plugin)
|
||||
rad-convert <Qwen3.8-27B or a finetune> -o q38-27b-fp8.rad --recipe data/recipes/q38-27b-fp8block-df2.recipe \
|
||||
--draft-model <DFlash2 checkpoint> --set quantization_config.quant_method=fp8 \
|
||||
--set quantization_config.fmt=e4m3 --set "quantization_config.weight_block_size=128 128" \
|
||||
--set quantization_config.activation_scheme=dynamic
|
||||
|
||||
# Check the plan without writing 166 GiB
|
||||
rad-convert $SRC -o /dev/null --recipe r.recipe --plan-only -v
|
||||
|
||||
@@ -234,7 +242,10 @@ newer repos moved the template out of the JSON, and the symptom of missing it is
|
||||
|
||||
**`--set K=V` is how a convert-time choice that must also hold at serve time is stated once.** The
|
||||
key is handed to declare *and* written into the container. What a weight is stored as is not such a
|
||||
choice: the encoding is in the container, and the plugin reads it from there.
|
||||
choice: the encoding is in the container, and the plugin reads it from there. Which plugin serves
|
||||
the container is: a `quantization_config.*` key re-derives the descriptor the plugin is chosen by,
|
||||
so a bf16 checkpoint whose recipe writes Qwen's block fp8 is stated as that format and converted for
|
||||
the fp8 plugin (`data/recipes/q38-27b-fp8block-df2.recipe` has the keys).
|
||||
|
||||
**`--max-ctx`.** Some architectures' graphs depend on the context bound: Qwen4-Exp sizes its QSA
|
||||
buffers by it, and refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
|
||||
@@ -323,7 +334,7 @@ rad-kbench -m moe.rad --max-cases 1 --record data/kernels_moe.rkb
|
||||
| `--fixture FILE` | the recording to replay (default `$RADIANCE_HOME/kernels.rkb`) |
|
||||
| `--record FILE` | with `-m`: write a fixture |
|
||||
| `-m, --model FILE` | the `.rad` to read weight operands from |
|
||||
| `--home DIR`, `--kernels A:B` | plugin home and hierarchy |
|
||||
| `--home DIR`, `--kernels A:B` | plugin home, and the kernel libraries to load (default every one found) |
|
||||
| `--op NAME` | check only this op (repeatable prefix match) |
|
||||
| `--ref NAME` | the oracle plugin's name (default `libref`) |
|
||||
| `--seed N` | base seed; every case derives its own, so changing a filter does not change any other case's inputs |
|
||||
@@ -379,7 +390,7 @@ rad-tune -m <model.rad> [options]
|
||||
|
||||
-m, --model FILE the .rad whose declared graph supplies the shapes
|
||||
--home DIR $RADIANCE_HOME; the cache is written to <home>/tune/<machine>.tune
|
||||
--kernels A:B kernel plugin hierarchy, first wins
|
||||
--kernels A:B the kernel libraries to load, first wins; default every library found
|
||||
--op NAME tune only ops whose name starts with NAME
|
||||
--machine KEY override the machine key (for writing a cache for another box)
|
||||
--reps N timing reps, median reported (default 5)
|
||||
@@ -525,7 +536,7 @@ need nothing but `curl` and `jq`. Scripts resolve each other by `$(dirname "$0")
|
||||
it is on. `oracle.sh` starts its own server and stops whatever listens on its port (`P`, default
|
||||
8302). Everything else — `cstep2.sh`, `ident.sh`, `tierident.sh`, `tiercross.sh`, `mctools.sh`,
|
||||
`mcstream.sh`, `hfget.sh`, `convfn.sh`, `convdspark.sh`, `fnpf.sh`, `fnconc.sh`, `fndrop.sh`,
|
||||
`apikeys.sh`, `diskstall.py` — leaves a live serve alone.
|
||||
`apikeys.sh`, `diskstall.py`, `cardclock.py` — leaves a live serve alone.
|
||||
`fndrop.sh` is the one to read the description of first: it leaves the PROCESS alone and
|
||||
deliberately disconnects clients from it, which is not the same promise.
|
||||
|
||||
@@ -537,7 +548,7 @@ deliberately disconnects clients from it, which is not the same promise.
|
||||
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnstop.sh` | stops whichever is running and **waits for the process to go** |
|
||||
| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=<dir>`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
|
||||
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable |
|
||||
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable; a file changed at the same size is fetched again (`.hfget-manifest`). `radiance --model <owner/name>` runs it too |
|
||||
|
||||
```sh
|
||||
scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx
|
||||
@@ -562,6 +573,7 @@ deployment. `P` selects the port.
|
||||
| `cstep2.sh` | steady-state decode ms/step at concurrency | `P` `LEVELS` `MT` `WIN` |
|
||||
| `ident.sh` | run-to-run reproducibility at a fixed configuration: one hash per (temperature, question) | `P` |
|
||||
| `diskstall.py` | what restoring a conversation from the disk tier costs: the returning request's time to first token, and the longest stall it puts on a stream decoding beside it | `--port` `--session` `--fill` |
|
||||
| `cardclock.py` | what holds each card's clock under a sustained load (power limit, temperature or current limit, or the top of the voltage/frequency curve) and which card the tensor-parallel step waits for, with the engine's step counters per window beside it. Drives its own greedy load; `--watch` only samples while real traffic drives the server. Never writes to a card | `--port` `--conc` `--gen` `--seconds` `--window` `--seed` `--watch` `--json` `--compare` |
|
||||
|
||||
`fndrop.sh` exists because a disconnect reaps a request at an arbitrary point in the step loop, and
|
||||
every other harness here waits for its requests, so none of them can see what holds a reference
|
||||
@@ -586,6 +598,20 @@ C steps tok tok/step ms/step accept%
|
||||
`cstep2.sh` waits until exactly C sequences are running before sampling and re-checks at the end: a
|
||||
window whose edges carry fewer than C describes no concurrency at all.
|
||||
|
||||
`cardclock.py` exists because the same image reads several percent apart from one boot to the next
|
||||
on workstation cards. A tensor-parallel step runs at its slowest card's clock, and under a sustained
|
||||
load the firmware picks each card's clock. A throttler bit counts only when the card's clock is
|
||||
lower while it is set: some firmware keeps a bit on at idle (on Radeon AI PRO R9700,
|
||||
`TEMP_HOTSPOT`), so a bit the idle baseline also shows is listed and ignored. When it names a
|
||||
setting (power cap, fan target, voltage offset) it prints the command and changes nothing. That
|
||||
write is for a moment when no process holds `/dev/kfd`. Under load, an SMU write on gfx1201 has
|
||||
reset the machine.
|
||||
|
||||
```sh
|
||||
scripts/cardclock.py --port 8100 --conc 8 --seconds 180 --seed 7 --json before.json
|
||||
scripts/cardclock.py --compare before.json after.json
|
||||
```
|
||||
|
||||
### Measuring with a server of its own
|
||||
|
||||
| | |
|
||||
|
||||
+10
-3
@@ -49,9 +49,8 @@ difference into its weights pool, no further than every one of its weights resid
|
||||
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
|
||||
loan and the attention ranks' pools are unchanged, 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,
|
||||
@@ -127,6 +126,14 @@ radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --ma
|
||||
--num-speculative-tokens 3 --max-num-batched-tokens 2048
|
||||
```
|
||||
|
||||
The exact all-reduce at three ranks is the wide family's one-shot up to 1 MiB a message (every
|
||||
decode step) and its two-shot above it (every prefill chunk): reduce-scatter + all-gather, which
|
||||
sends 4/3 of the message per rank instead of twice it. A message rarely divides into thirds -- a
|
||||
2048-wide bf16 row is 256 16-byte words -- so the first `words % 3` shards take one word more.
|
||||
Both rows fold in fp32 in ascending rank order, so the band edge between them changes no bits.
|
||||
`--tp-wire wht6` at three ranks is the four-rank tiered-int8 wire over the same uneven two-shot,
|
||||
above `--tp-wire-min-kb`; under it, the exact one-shot.
|
||||
|
||||
The log says what the geometry did:
|
||||
|
||||
```
|
||||
|
||||
+481
-19
@@ -54,6 +54,9 @@
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace avx;
|
||||
@@ -490,6 +493,282 @@ AVX_KERNEL(attn_paged) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_dense, bf16 blocks */
|
||||
/* AN ENCODER'S ATTENTION IS ALL PREFILL, and the per-query loop below is built for a decode row:
|
||||
* it parallelises over (segment, head) -- eight units for one long input on a sixteen-core part --
|
||||
* and widens every key row to f32 again for every query that reads it, so a 2000-token segment
|
||||
* pays four million row conversions a head. Measured at 130 GFLOPS on the sliding layers.
|
||||
*
|
||||
* Where q, k and v are bf16 with unit element stride and the CPU has AVX512_BF16, this blocked
|
||||
* form runs instead. A task is (segment, KV head, 32 query positions) and holds the rows of every
|
||||
* query head that reads that KV head, so one key tile serves gqa x 32 rows. Per tile of 64 keys:
|
||||
*
|
||||
* S = Q K^T vdpbf16ps against the tile packed once as key-interleaved bf16 pairs, each
|
||||
* query pair broadcast into 16-key vectors: no score is horizontally reduced
|
||||
* the mask causal, window and segment end, on the scores
|
||||
* the softmax online, the running max moved at tile boundaries (this file's arrangement)
|
||||
* O += P V V's tile packed once for the task as key-interleaved bf16 pairs, P rounded to
|
||||
* bf16 pairs along the keys (as PyTorch's CPU flash attention does), six rows of
|
||||
* 64 output columns a block
|
||||
*
|
||||
* The key range of a task is cut to what its queries can see, so a sliding layer costs
|
||||
* O(T * window). Each output row is one task's, so the result does not depend on the thread
|
||||
* count. Same arithmetic class as the loop below: f32 scores (bf16 products are exact in f32),
|
||||
* f32 softmax and accumulator, one rounding at the store. */
|
||||
#if AVX_LEVEL == 3
|
||||
#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16")))
|
||||
|
||||
/* S[r][0..63] for MB_ query rows against a key tile packed as bf16 PAIRS INTERLEAVED BY KEY:
|
||||
* kp[d2 * 64 + j] holds key j's dims 2*d2 and 2*d2+1. Each step broadcasts one row's pair and
|
||||
* multiplies it into four 16-key vectors, so a score is never horizontally reduced -- with a
|
||||
* 64-wide head a reduction per score cost more than the two products it closed. */
|
||||
template <int MB_>
|
||||
AVX_BF16_TARGET static inline void qk_rows(const uint16_t* const* qr, const uint32_t* kp,
|
||||
int64_t D2, float scale, float* S, int64_t ldS) {
|
||||
__m512 acc[MB_][4];
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
#pragma GCC unroll 4
|
||||
for (int v = 0; v < 4; ++v) acc[i][v] = _mm512_setzero_ps();
|
||||
for (int64_t d2 = 0; d2 < D2; ++d2) {
|
||||
const uint32_t* kr = kp + d2 * 64;
|
||||
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(kr));
|
||||
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 16));
|
||||
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 32));
|
||||
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 48));
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i) {
|
||||
uint32_t pr;
|
||||
std::memcpy(&pr, qr[i] + 2 * d2, 4);
|
||||
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pr);
|
||||
acc[i][0] = _mm512_dpbf16_ps(acc[i][0], a, b0);
|
||||
acc[i][1] = _mm512_dpbf16_ps(acc[i][1], a, b1);
|
||||
acc[i][2] = _mm512_dpbf16_ps(acc[i][2], a, b2);
|
||||
acc[i][3] = _mm512_dpbf16_ps(acc[i][3], a, b3);
|
||||
}
|
||||
}
|
||||
const __m512 vs = _mm512_set1_ps(scale);
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
#pragma GCC unroll 4
|
||||
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(S + i * ldS + 16 * v, _mm512_mul_ps(acc[i][v], vs));
|
||||
}
|
||||
|
||||
/* acc[r][c0 .. c0+63] += P[r] . V for MB_ rows, in bf16 pairs: pp[r * 32 + k2] holds row r's
|
||||
* probabilities for keys 2*k2 and 2*k2+1, vp[k2 * D + d] holds those two keys' values at column
|
||||
* d. PyTorch's CPU flash attention -- the reference's -- rounds P to bf16 for this product as
|
||||
* well; the softmax's sum is kept in f32 from the unrounded P. */
|
||||
template <int MB_>
|
||||
AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t* pp,
|
||||
const uint32_t* vp, int64_t K2, int64_t c0) {
|
||||
__m512 o[MB_][4];
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
#pragma GCC unroll 4
|
||||
for (int v = 0; v < 4; ++v) o[i][v] = _mm512_loadu_ps(acc + i * D + c0 + 16 * v);
|
||||
for (int64_t k2 = 0; k2 < K2; ++k2) {
|
||||
const uint32_t* vr = vp + k2 * D + c0;
|
||||
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(vr));
|
||||
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 16));
|
||||
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 32));
|
||||
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 48));
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i) {
|
||||
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pp[i * 32 + k2]);
|
||||
o[i][0] = _mm512_dpbf16_ps(o[i][0], a, b0);
|
||||
o[i][1] = _mm512_dpbf16_ps(o[i][1], a, b1);
|
||||
o[i][2] = _mm512_dpbf16_ps(o[i][2], a, b2);
|
||||
o[i][3] = _mm512_dpbf16_ps(o[i][3], a, b3);
|
||||
}
|
||||
}
|
||||
#pragma GCC unroll 8
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
#pragma GCC unroll 4
|
||||
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]);
|
||||
}
|
||||
|
||||
AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* k,
|
||||
const RadTensor* v, const RadTensor* cu,
|
||||
const RadTensor* o, int64_t D, int64_t gqa,
|
||||
int64_t kv_heads, int causal, int64_t window,
|
||||
float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
|
||||
int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs,
|
||||
int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs,
|
||||
int64_t o_ds) {
|
||||
static const bool have = __builtin_cpu_supports("avx512bf16");
|
||||
if (!have) return false;
|
||||
if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return false;
|
||||
if (q_ds != 1 || k_ds != 1 || v_ds != 1 || o_ds != 1 || D % 64 != 0 || gqa > 16) return false;
|
||||
|
||||
constexpr int64_t QB = 32, KT = 64;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
/* The task list: (segment, kv head, query block), flattened through a prefix over segments. */
|
||||
std::vector<int64_t> first((size_t)n_seq + 1, 0);
|
||||
for (int64_t s = 0; s < n_seq; ++s) {
|
||||
const int64_t len = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s));
|
||||
first[(size_t)s + 1] = first[(size_t)s] + kv_heads * ((len + QB - 1) / QB);
|
||||
}
|
||||
const int64_t n_task = first[(size_t)n_seq];
|
||||
const uint16_t* Q = (const uint16_t*)q->data;
|
||||
const uint16_t* K = (const uint16_t*)k->data;
|
||||
const uint16_t* V = (const uint16_t*)v->data;
|
||||
const int64_t R_MAX = QB * gqa;
|
||||
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size())
|
||||
#endif
|
||||
for (int64_t t = 0; t < n_task; ++t) {
|
||||
int64_t s = (int64_t)(std::upper_bound(first.begin(), first.end(), t) - first.begin()) - 1;
|
||||
const int64_t b0 = ldi(cu, offlin(cu, s)), len = ldi(cu, offlin(cu, s + 1)) - b0;
|
||||
const int64_t local = t - first[(size_t)s];
|
||||
const int64_t nqb = (len + QB - 1) / QB;
|
||||
const int64_t kh = local / nqb, q0 = (local % nqb) * QB;
|
||||
const int64_t q1 = std::min(q0 + QB, len), nq = q1 - q0, R = nq * gqa;
|
||||
|
||||
float* frame = scratch_f32((size_t)(R_MAX * D + R_MAX * KT + 2 * R_MAX + KT * D / 2 +
|
||||
KT * D / 2 + R_MAX * KT / 2) + 64);
|
||||
float* acc = frame;
|
||||
float* S = acc + R_MAX * D;
|
||||
float* m = S + R_MAX * KT;
|
||||
float* l = m + R_MAX;
|
||||
uint32_t* kpack = reinterpret_cast<uint32_t*>(l + R_MAX);
|
||||
uint32_t* vpack = kpack + KT * D / 2;
|
||||
uint32_t* ppack = vpack + KT * D / 2;
|
||||
const int64_t D2 = D / 2;
|
||||
const uint16_t* qrow[16 * QB];
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const int64_t qi = r / gqa, g = r % gqa;
|
||||
qrow[r] = Q + (b0 + q0 + qi) * q_rs + (kh * gqa + g) * q_hs;
|
||||
m[r] = -INFINITY;
|
||||
l[r] = 0.0f;
|
||||
}
|
||||
std::memset(acc, 0, sizeof(float) * (size_t)(R * D));
|
||||
|
||||
int64_t jbeg = 0, jend = causal ? q1 : len;
|
||||
if (window > 0) {
|
||||
jbeg = std::max<int64_t>(0, q0 - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + window);
|
||||
}
|
||||
for (int64_t j0 = jbeg; j0 < jend; j0 += KT) {
|
||||
const int64_t kt = std::min(KT, jend - j0);
|
||||
/* The key tile packed once for every row of the task: pairs interleaved by key, the
|
||||
* keys past the tile's end zero (their scores are never read). */
|
||||
for (int64_t d2 = 0; d2 < D2; ++d2) {
|
||||
uint32_t* dst = kpack + d2 * KT;
|
||||
for (int64_t j = 0; j < kt; ++j)
|
||||
std::memcpy(dst + j, K + (b0 + j0 + j) * k_rs + kh * k_hs + 2 * d2, 4);
|
||||
for (int64_t j = kt; j < KT; ++j) dst[j] = 0;
|
||||
}
|
||||
|
||||
/* S, six rows a block against the whole packed tile. */
|
||||
int64_t r = 0;
|
||||
for (; r + 6 <= R; r += 6) qk_rows<6>(qrow + r, kpack, D2, scale, S + r * KT, KT);
|
||||
for (; r < R; ++r) qk_rows<1>(qrow + r, kpack, D2, scale, S + r * KT, KT);
|
||||
/* The mask, by position inside the segment. */
|
||||
if (causal || window > 0) {
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const int64_t i = q0 + r / gqa;
|
||||
for (int64_t j = 0; j < kt; ++j) {
|
||||
const int64_t d = i - (j0 + j);
|
||||
bool ok = !causal || d >= 0;
|
||||
if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window));
|
||||
if (!ok) S[r * KT + j] = -INFINITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The online softmax, row by row, four vectors a row; S becomes P in place. The keys
|
||||
* past a short tile's end score -inf, so P is zero there and every row is full width. */
|
||||
if (kt < KT)
|
||||
for (int64_t r = 0; r < R; ++r)
|
||||
for (int64_t j = kt; j < KT; ++j) S[r * KT + j] = -INFINITY;
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
float* sr = S + r * KT;
|
||||
const float tmax = _mm512_reduce_max_ps(
|
||||
_mm512_max_ps(_mm512_max_ps(_mm512_loadu_ps(sr), _mm512_loadu_ps(sr + 16)),
|
||||
_mm512_max_ps(_mm512_loadu_ps(sr + 32), _mm512_loadu_ps(sr + 48))));
|
||||
if (tmax == -INFINITY) {
|
||||
for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f;
|
||||
continue;
|
||||
}
|
||||
if (tmax > m[r]) {
|
||||
const float alpha = m[r] == -INFINITY ? 0.0f : std::exp(m[r] - tmax);
|
||||
if (alpha != 1.0f) {
|
||||
float* ar = acc + r * D;
|
||||
const __m512 va = _mm512_set1_ps(alpha);
|
||||
for (int64_t d = 0; d < D; d += 16)
|
||||
_mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), va));
|
||||
l[r] *= alpha;
|
||||
}
|
||||
m[r] = tmax;
|
||||
}
|
||||
const vf vm = vf_set1(m[r]);
|
||||
__m512 sum = _mm512_setzero_ps();
|
||||
for (int64_t j = 0; j < KT; j += 16) {
|
||||
/* exp of -inf is the clamp's floor, ~1e-38: zero to every sum it joins. */
|
||||
const vf e = vf_exp(vf_sub(vf_loadu(sr + j), vm));
|
||||
vf_storeu(sr + j, e);
|
||||
sum = _mm512_add_ps(sum, e);
|
||||
}
|
||||
l[r] += _mm512_reduce_add_ps(sum);
|
||||
}
|
||||
/* V's tile packed once for every row of the task, consecutive keys interleaved in
|
||||
* pairs (a key past the tile's end is zero), and each row's P rounded to bf16 pairs
|
||||
* along the keys. */
|
||||
const int64_t K2 = (kt + 1) / 2;
|
||||
{
|
||||
/* Two key rows' words interleaved, 32 columns a step: lanes 0..15 of the first
|
||||
* output are (k0[d], k1[d]) for d = 0..15, the second's for d = 16..31. */
|
||||
const __m512i ilo = _mm512_set_epi16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10,
|
||||
41, 9, 40, 8, 39, 7, 38, 6, 37, 5, 36, 4, 35, 3,
|
||||
34, 2, 33, 1, 32, 0);
|
||||
const __m512i ihi = _mm512_set_epi16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26,
|
||||
57, 25, 56, 24, 55, 23, 54, 22, 53, 21, 52, 20,
|
||||
51, 19, 50, 18, 49, 17, 48, 16);
|
||||
for (int64_t k2 = 0; k2 < K2; ++k2) {
|
||||
const uint16_t* v0 = V + (b0 + j0 + 2 * k2) * v_rs + kh * v_hs;
|
||||
const bool two = 2 * k2 + 1 < kt;
|
||||
uint32_t* dst = vpack + k2 * D;
|
||||
for (int64_t d = 0; d < D; d += 32) {
|
||||
const __m512i a = _mm512_loadu_si512((const void*)(v0 + d));
|
||||
const __m512i bb = two ? _mm512_loadu_si512((const void*)(v0 + v_rs + d))
|
||||
: _mm512_setzero_si512();
|
||||
_mm512_storeu_si512((void*)(dst + d), _mm512_permutex2var_epi16(a, ilo, bb));
|
||||
_mm512_storeu_si512((void*)(dst + d + 16),
|
||||
_mm512_permutex2var_epi16(a, ihi, bb));
|
||||
}
|
||||
}
|
||||
}
|
||||
/* P to bf16, round to nearest even: a row's 64 values are its 32 key pairs in order. */
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const float* sr = S + r * KT;
|
||||
uint32_t* pr = ppack + r * 32;
|
||||
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
|
||||
_mm512_loadu_ps(sr)));
|
||||
_mm512_storeu_si512((void*)(pr + 16),
|
||||
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
|
||||
_mm512_loadu_ps(sr + 32)));
|
||||
}
|
||||
for (int64_t c0 = 0; c0 < D; c0 += 64) {
|
||||
int64_t r = 0;
|
||||
for (; r + 6 <= R; r += 6) pv_rows<6>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
|
||||
for (; r < R; ++r) pv_rows<1>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
|
||||
}
|
||||
}
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const int64_t qi = r / gqa, g = r % gqa;
|
||||
const int64_t ob = (b0 + q0 + qi) * o_rs + (kh * gqa + g) * o_hs;
|
||||
float* ar = acc + r * D;
|
||||
const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r];
|
||||
const __m512 vi = _mm512_set1_ps(inv);
|
||||
for (int64_t d = 0; d < D; d += 16)
|
||||
_mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), vi));
|
||||
out_row(o, ob, D, ar);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ attn_dense */
|
||||
/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
|
||||
* attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
|
||||
@@ -505,10 +784,15 @@ AVX_KERNEL(attn_dense) {
|
||||
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
|
||||
const int64_t gqa = p_int(a, "gqa", 1);
|
||||
const int causal = (int)p_int(a, "causal", 0);
|
||||
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
|
||||
/* libref's window: causal, i - j < window; non-causal, |i - j| < window; 0 none. */
|
||||
const int64_t window = p_int(a, "window", 0);
|
||||
if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
|
||||
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] : 1;
|
||||
/* A rank-2 operand is [tokens, heads * head_dim], so its head count is its width over the
|
||||
* head; reading it as one head would take every head of a multi-head slice for one long one. */
|
||||
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
|
||||
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
|
||||
const int64_t kv_heads = q_heads / gqa;
|
||||
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
@@ -534,6 +818,11 @@ AVX_KERNEL(attn_dense) {
|
||||
const int64_t o_rs = row_stride(o, q_heads * head_dim);
|
||||
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
#if AVX_LEVEL == 3
|
||||
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, scale, q_rs,
|
||||
q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds))
|
||||
return RAD_OK;
|
||||
#endif
|
||||
|
||||
AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
|
||||
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
|
||||
@@ -550,7 +839,11 @@ AVX_KERNEL(attn_dense) {
|
||||
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
|
||||
const int64_t jend = causal ? (i + 1) : b1;
|
||||
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
|
||||
if (window > 0) {
|
||||
jbeg = std::max<int64_t>(b0, i - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(b1, i + window);
|
||||
}
|
||||
const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float m = -INFINITY, l = 0.0f;
|
||||
@@ -589,7 +882,7 @@ AVX_KERNEL(attn_dense) {
|
||||
ntile = 0;
|
||||
};
|
||||
|
||||
for (int64_t j = b0; j < jend; ++j) {
|
||||
for (int64_t j = jbeg; j < jend; ++j) {
|
||||
const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf);
|
||||
sbuf[ntile] = dotf(qv, kvr, head_dim) * scale;
|
||||
vbase[ntile] = j * v_rs + kh * v_hs;
|
||||
@@ -617,6 +910,92 @@ AVX_KERNEL(attn_dense) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_local_rel */
|
||||
/* libref's local attention with a relative-position term (Gemma 4's audio). A query sees at most
|
||||
* left + 1 keys -- thirteen at the checkpoint's geometry -- so the work is a few dot products a
|
||||
* (row, head) and the loop is libref's, vectorised along the head and parallel over (row, head). */
|
||||
AVX_KERNEL(attn_local_rel) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3];
|
||||
const RadTensor *pds = &a->t[4], *cu = &a->t[5], *o = &a->t[6];
|
||||
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
|
||||
const int64_t L = p_int(a, "left", 0), R = p_int(a, "right", 0);
|
||||
const int64_t cdiv = p_int(a, "cu_div", 1);
|
||||
const float cap = p_f32(a, "softcap", 0.0f);
|
||||
if (D <= 0 || H <= 0 || L < 0 || cdiv <= 0 || !(cap > 0.0f)) return RAD_E_SHAPE;
|
||||
if (R != 0) return RAD_E_UNSUPPORTED;
|
||||
if (D > AVX_HD_MAX || L + 1 > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t Wd = H * D;
|
||||
if (numel(pds) < D || numel(rk) < (L + 1) * Wd) return RAD_E_SHAPE;
|
||||
const int64_t S = numel(cu) - 1;
|
||||
if (S <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Mq = numel(q) / Wd, Mk = numel(k) / Wd, Mv = numel(v) / Wd, Mo = numel(o) / Wd;
|
||||
const int64_t q_rs = row_stride(q, Wd), k_rs = row_stride(k, Wd), v_rs = row_stride(v, Wd);
|
||||
const int64_t r_rs = row_stride(rk, Wd), o_rs = row_stride(o, Wd);
|
||||
const int64_t q_ds = laststride(q), k_ds = laststride(k), v_ds = laststride(v);
|
||||
const int64_t r_ds = laststride(rk), o_ds = laststride(o);
|
||||
|
||||
const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0));
|
||||
const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
|
||||
/* softplus(pds), rounded to the weight's dtype as the reference evaluates it on the bf16
|
||||
* parameter (libref's reading), and the query's whole scale folded into one vector. */
|
||||
float* spd = (float*)scratch_raw((size_t)D * sizeof(float) + 64);
|
||||
for (int64_t d = 0; d < D; ++d) {
|
||||
const float x = ldt(pds, d * laststride(pds));
|
||||
const float sp = x > 20.0f ? x : (x > 0.0f ? x + std::log1p(std::exp(-x))
|
||||
: std::log1p(std::exp(x)));
|
||||
float r = sp;
|
||||
if (pds->dtype == RAD_BF16) r = rad_bf16_to_f32(rad_f32_to_bf16(sp));
|
||||
else if (pds->dtype == RAD_F16) r = rad_f16_to_f32(rad_f32_to_f16(sp));
|
||||
spd[d] = r;
|
||||
}
|
||||
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
|
||||
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
|
||||
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
|
||||
if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE;
|
||||
|
||||
AVX_PARALLEL_FOR_IF((t1 - t0) * H * (L + 1) * D >= AVX_PAR_MIN)
|
||||
for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) {
|
||||
const int64_t i = t0 + ih / H, h = ih % H;
|
||||
float* frame = scratch_f32((size_t)(4 * D + L + 1) + 16);
|
||||
float* qf = frame;
|
||||
float* kb = frame + D;
|
||||
float* acc = frame + 2 * D;
|
||||
float* tmp = frame + 3 * D;
|
||||
float* lg = frame + 4 * D;
|
||||
const float* qv = head_f32(q, i * q_rs + h * D * q_ds, q_ds, D, 1.0f, tmp);
|
||||
for (int64_t d = 0; d < D; ++d) qf[d] = qv[d] * qs * spd[d];
|
||||
const int64_t j0 = i - L > t0 ? i - L : t0;
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = j0; j <= i; ++j) {
|
||||
const float* kv = head_f32(k, j * k_rs + h * D * k_ds, k_ds, D, 1.0f, tmp);
|
||||
for (int64_t d = 0; d < D; ++d) kb[d] = kv[d] * ks;
|
||||
float ac = dotf(qf, kb, D);
|
||||
const float* rv = head_f32(rk, (i - j) * r_rs + h * D * r_ds, r_ds, D, 1.0f, tmp);
|
||||
ac += dotf(qf, rv, D);
|
||||
const float x = cap * std::tanh(ac / cap);
|
||||
lg[j - j0] = x;
|
||||
mx = x > mx ? x : mx;
|
||||
}
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = j0; j <= i; ++j) {
|
||||
lg[j - j0] = std::exp(lg[j - j0] - mx);
|
||||
sum += lg[j - j0];
|
||||
}
|
||||
for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f;
|
||||
for (int64_t j = j0; j <= i; ++j)
|
||||
axpy(acc, head_f32(v, j * v_rs + h * D * v_ds, v_ds, D, 1.0f, tmp),
|
||||
lg[j - j0] / sum, D);
|
||||
const int64_t ob = i * o_rs + h * D * o_ds;
|
||||
if (o_ds == 1) out_row(o, ob, D, acc);
|
||||
else for (int64_t d = 0; d < D; ++d) stt(o, ob + d * o_ds, acc[d]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store */
|
||||
/* The cache operand is INOUT and not OUT: this op touches only the mapped slots and every other
|
||||
* slot in the pool must survive it, which is a liveness fact the buffer planner has to know.
|
||||
@@ -888,27 +1267,77 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
const float eps = p_f32(a, "eps", 1e-6f);
|
||||
const float rscale = p_f32(a, "scale", 1.0f);
|
||||
const float wadd = p_f32(a, "wadd", 0.0f);
|
||||
static const char* kModes[] = { "neox", "gptj" };
|
||||
const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX);
|
||||
const int v_norm = (int)p_int(a, "v_norm", 0);
|
||||
static const char* kModes[] = { "neox", "gptj", "blocks" };
|
||||
const int mode = p_enum(a, "mode", kModes, 3, ROPE_NEOX);
|
||||
if (mode < 0) return RAD_E_UNSUPPORTED;
|
||||
const bool blocks = mode == 2;
|
||||
const int64_t rot = p_int(a, "rotary_dim", head_dim);
|
||||
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
|
||||
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
|
||||
|
||||
/* BLOCKS (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
|
||||
* (start + j, start + sec[c] + j), turned by position component comps[c]. */
|
||||
int64_t sec[8] = {}, comp[8] = {};
|
||||
int n_sec = 0;
|
||||
if (blocks) {
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(v, &end, 10);
|
||||
if (end == v) break;
|
||||
if (x <= 0) return RAD_E_SHAPE;
|
||||
comp[n_sec] = n_sec;
|
||||
sec[n_sec++] = x;
|
||||
v = end;
|
||||
}
|
||||
int64_t total = 0;
|
||||
for (int c = 0; c < n_sec; ++c) total += sec[c];
|
||||
if (n_sec <= 0 || 2 * total != rot) return RAD_E_SHAPE;
|
||||
if (const char* cs = p_str(a, "comps", nullptr)) {
|
||||
int k = 0;
|
||||
for (const char* v = cs; *v && k < 8; ) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(v, &end, 10);
|
||||
if (end == v) break;
|
||||
comp[k++] = x;
|
||||
v = end;
|
||||
}
|
||||
if (k != n_sec) return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
const bool multi = pos->rank >= 2;
|
||||
const int64_t n_comp = multi ? pos->shape[0] : 1;
|
||||
if (multi && !blocks) return RAD_E_SHAPE;
|
||||
for (int c = 0; c < n_sec; ++c)
|
||||
if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE;
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
const int64_t M = numel(pos);
|
||||
const int64_t M = multi ? pos->shape[1] : numel(pos);
|
||||
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
|
||||
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
|
||||
const int64_t ds = laststride(qkv);
|
||||
const int64_t half = rot / 2;
|
||||
|
||||
/* One arena call for the launch-invariant tables: the inverse frequencies and both widened
|
||||
* gains. A second scratch_raw would reallocate under the parallel region. */
|
||||
float* tab = (float*)scratch_raw((size_t)(half + 2 * head_dim) * sizeof(float) + 64);
|
||||
/* One arena call for the launch-invariant tables: the inverse frequencies (and, for blocks,
|
||||
* each pair's component) and both widened gains. A second scratch_raw would reallocate under
|
||||
* the parallel region. */
|
||||
float* tab = (float*)scratch_raw((size_t)(2 * half + 2 * head_dim) * sizeof(float) + 64);
|
||||
float* invf = tab;
|
||||
float* gq = tab + half;
|
||||
float* gk = tab + half + head_dim;
|
||||
for (int64_t i = 0; i < half; ++i)
|
||||
invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
|
||||
float* pcomp = tab + half;
|
||||
float* gq = tab + 2 * half;
|
||||
float* gk = tab + 2 * half + head_dim;
|
||||
if (!blocks) {
|
||||
for (int64_t i = 0; i < half; ++i)
|
||||
invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
|
||||
} else {
|
||||
int64_t i = 0;
|
||||
for (int c = 0; c < n_sec; ++c)
|
||||
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
|
||||
invf[i] = 1.0f / std::pow(theta, (float)j / (float)sec[c]);
|
||||
pcomp[i] = (float)comp[c];
|
||||
}
|
||||
}
|
||||
for (int64_t d = 0; d < head_dim; ++d) {
|
||||
gq[d] = ldt(qw, d * laststride(qw)) + wadd;
|
||||
gk[d] = ldt(kw, d * laststride(kw)) + wadd;
|
||||
@@ -916,12 +1345,23 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const float p = (float)ldi(pos, offlin(pos, m)) / (rscale != 0.0f ? rscale : 1.0f);
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
float pc[8];
|
||||
if (multi)
|
||||
for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
|
||||
else
|
||||
pc[0] = (float)ldi(pos, offlin(pos, m)) / div;
|
||||
const int64_t row = m * rs;
|
||||
float* cs = scratch_f32((size_t)rot);
|
||||
float* buf = scratch_f32_b((size_t)head_dim);
|
||||
float* rbuf = scratch_f32_c((size_t)head_dim);
|
||||
angles(cs, invf, half, p);
|
||||
if (!blocks) angles(cs, invf, half, pc[0]);
|
||||
else
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float ang = pc[(int)pcomp[i]] * invf[i];
|
||||
cs[i] = std::cos(ang);
|
||||
cs[half + i] = std::sin(ang);
|
||||
}
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
|
||||
const float* g = h < n_head ? gq : gk;
|
||||
const int64_t base = row + h * head_dim * ds;
|
||||
@@ -932,11 +1372,33 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
for (; d + VF_N <= head_dim; d += VF_N)
|
||||
vf_storeu(rbuf + d, vf_mul(vf_mul(vf_loadu(xv + d), vs), vf_loadu(g + d)));
|
||||
for (; d < head_dim; ++d) rbuf[d] = xv[d] * sc * g[d];
|
||||
/* Written back through the operand's dtype, then re-read by rope_head -- the rounding
|
||||
* across the seam is the contract. */
|
||||
/* Written back through the operand's dtype, then re-read by the rotation -- the
|
||||
* rounding across the seam is the contract. */
|
||||
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
|
||||
else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
|
||||
rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
|
||||
if (!blocks) {
|
||||
rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
|
||||
continue;
|
||||
}
|
||||
int64_t i = 0, start = 0;
|
||||
for (int c = 0; c < n_sec; ++c) {
|
||||
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
|
||||
const int64_t i0 = start + j, i1 = start + sec[c] + j;
|
||||
const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds);
|
||||
stt(qkv, base + i0 * ds, x0 * cs[i] - x1 * cs[half + i]);
|
||||
stt(qkv, base + i1 * ds, x0 * cs[half + i] + x1 * cs[i]);
|
||||
}
|
||||
start += 2 * sec[c];
|
||||
}
|
||||
}
|
||||
/* v_norm: the v heads RMS-normed with a unit gain and not rotated (libref). */
|
||||
for (int64_t h = 0; v_norm && h < n_head_kv; ++h) {
|
||||
const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds;
|
||||
const float* xv = head_f32(qkv, base, ds, head_dim, 1.0f, buf);
|
||||
const float sc = 1.0f / std::sqrt(row_sumsq(xv, head_dim) / (float)head_dim + eps);
|
||||
for (int64_t d = 0; d < head_dim; ++d) rbuf[d] = xv[d] * sc;
|
||||
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
|
||||
else for (int64_t d = 0; d < head_dim; ++d) stt(qkv, base + d * ds, rbuf[d]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
|
||||
+78
-2
@@ -58,6 +58,30 @@ std::vector<Case> build_cases() {
|
||||
EB(6, 645, w, 1));
|
||||
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
|
||||
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" })
|
||||
add("act_mul", { HI("M", 6), HI("n", 645), HS("act", act), HS("dtype", dt) },
|
||||
EB(6, 645, w, 3));
|
||||
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 2));
|
||||
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt), HI("scalar", 1) },
|
||||
EB(9, 645, w, 2));
|
||||
add("seg_mean", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 1));
|
||||
add("relu", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2));
|
||||
add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2));
|
||||
add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt),
|
||||
HF("wadd", 0), HF("mult", 0.5) }, EB(5, 645, w, 2));
|
||||
/* The audio subsampler's two geometries, scaled down in time, with and without the
|
||||
* frame mask, and a segment boundary (cu_div 2: the cu counts finer than the rows). */
|
||||
add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 1), HI("cout", 24), HI("kh", 3),
|
||||
HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt) });
|
||||
add("conv2d", { HI("M", 24), HI("width", 8), HI("cin", 20), HI("cout", 12), HI("kh", 3),
|
||||
HI("kw", 3), HI("stride", 2), HI("pad", 1), HI("cu_div", 2),
|
||||
HI("valid_stride", 2), HS("dtype", dt) });
|
||||
add("conv1d_dw", { HI("M", 26), HI("n", 645), HI("k", 5), HS("dtype", dt) });
|
||||
add("conv1d_dw", { HI("M", 24), HI("n", 64), HI("k", 5), HI("cu_div", 4), HS("dtype", dt) });
|
||||
add("rel_sinusoid", { HI("M", 13), HI("n", 1024), HF("max_timescale", 10000.0),
|
||||
HS("dtype", dt) });
|
||||
add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035),
|
||||
HS("dtype", dt) }, EB(27, 645, w, 1));
|
||||
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
|
||||
EB(6, 645, w, 2));
|
||||
@@ -146,6 +170,18 @@ std::vector<Case> build_cases() {
|
||||
add("logits_gemm", { HI("M", M), HI("n_vocab", 96), HI("n_embd", 259),
|
||||
HS("dtype", dt) }, 0, fl);
|
||||
}
|
||||
/* Encoder-sized M at a width that is not a whole number of 48-column panels, with K odd and
|
||||
* even: 37 rows take the bf16 dot-product path, 133 the outer-product one -- its column edge,
|
||||
* its zero-paired last k and its five-row tail. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int M : { 37, 133 })
|
||||
for (int K : { 259, 64 }) {
|
||||
const double fl = 2.0 * M * 100 * K;
|
||||
add("gemm_nt", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt) },
|
||||
0, fl);
|
||||
add("gemm_nt_bias", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt),
|
||||
HS("act", "gelu_tanh") }, 0, fl);
|
||||
}
|
||||
/* fp8a8 and fp8a16 ARE THE ONLY TWO libref CAN DESCRIBE, and that is a real limit rather than
|
||||
* a gap in this table: `gemm_nt_q` is one op over six weight formats and the SCALE GRID is
|
||||
* what differs between them -- per row, per row-group, per output-row-block, an e8m0 exponent
|
||||
@@ -172,7 +208,9 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
|
||||
HI("vocab_offset", 0), HF("wscale", 0) });
|
||||
HI("vocab_offset", 0), HF("mult", 1) });
|
||||
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
|
||||
HI("vocab_offset", 0), HF("mult", 22.625) });
|
||||
add("embed_lookup_q", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
|
||||
HI("vocab_offset", 0), HF("wscale", 0.01) });
|
||||
}
|
||||
@@ -191,7 +229,20 @@ std::vector<Case> build_cases() {
|
||||
for (int causal : { 0, 1 })
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
|
||||
HI("max_seqlen", 24) });
|
||||
HI("max_seqlen", 24), HI("window", 0) });
|
||||
/* The sliding window both ways: bidirectional |i - j| < 5 and causal i - j < 5, over
|
||||
* segments longer than the window so both bounds bite. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int causal : { 0, 1 })
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
|
||||
HI("max_seqlen", 24), HI("window", 5) });
|
||||
/* Gemma 4's audio attention: left 12 over segments longer than the window. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int cd : { 1, 4 })
|
||||
add("attn_local_rel", { HI("M", 40), HI("head_dim", 32), HI("n_head", 3),
|
||||
HI("left", 12), HI("right", 0), HF("softcap", 50.0),
|
||||
HI("cu_div", cd), HS("dtype", dt) });
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 16), HS("kv_dtype", dt), HF("k_scale", 1.0),
|
||||
@@ -203,6 +254,18 @@ std::vector<Case> build_cases() {
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 10000.0), HF("eps", 1e-6), HF("scale", 1.0),
|
||||
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0) });
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 10000.0), HF("eps", 1e-6), HF("scale", 1.0),
|
||||
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0),
|
||||
HI("v_norm", 1) });
|
||||
}
|
||||
/* `blocks`, the two-component vision form: x over the first half, y over the second, the
|
||||
* components named in the other order from the planes. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
|
||||
HF("theta", 100.0), HF("eps", 1e-6), HS("mode", "blocks"),
|
||||
HS("sections", "16 16"), HS("comps", "1 0"), HI("v_norm", 1),
|
||||
HS("dtype", dt) });
|
||||
}
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
|
||||
HS("dtype", "f32") });
|
||||
@@ -347,6 +410,11 @@ std::vector<Case> build_cases() {
|
||||
"sample_argmax" })
|
||||
add(op, { HI("M", 5), HI("n_vocab", 517) });
|
||||
add("sample_topk", { HI("M", 5), HI("n_vocab", 517), HI("vocab_off", 0) });
|
||||
/* k 7 and 20 (OpenAI's top_logprobs bound) against 517: the one-pass set starts full after
|
||||
* seven columns, and an offset shard reports global ids. */
|
||||
for (int64_t k : { 7, 20 })
|
||||
add("sample_logprobs", { HI("M", 5), HI("n_vocab", 517), HI("k", k), HI("vocab_off", 0) });
|
||||
add("sample_logprobs", { HI("M", 3), HI("n_vocab", 517), HI("k", 5), HI("vocab_off", 1000) });
|
||||
for (const char* op : { "sample_topp", "sample_minp", "sample_typical", "sample_xtc",
|
||||
"sample_pick", "sample_merge_topk" })
|
||||
add(op, { HI("M", 5), HI("n_cand", 12) });
|
||||
@@ -383,6 +451,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") },
|
||||
@@ -425,6 +500,7 @@ std::vector<Case> build_cases() {
|
||||
speed("logits_gemm", { HI("M", 1), HI("n_vocab", 32000), HI("n_embd", 2048),
|
||||
HS("dtype", "bf16") }, (double)32000 * 2048 * 2, 2.0 * 32000 * 2048);
|
||||
speed("sample_argmax", { HI("M", 1), HI("n_vocab", 32000) }, (double)32000 * 4, 0);
|
||||
speed("sample_logprobs", { HI("M", 1), HI("n_vocab", 32000), HI("k", 20) }, (double)32000 * 4, 0);
|
||||
speed("sample_topk", { HI("M", 1), HI("n_vocab", 32000), HI("vocab_off", 0) }, 0, 0);
|
||||
/* Decode attention over a real context: 16 query heads in groups of 4, 2048 keys already in
|
||||
* the cache. This is the shape a decode step spends its time in. */
|
||||
|
||||
+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));
|
||||
|
||||
+5
-3
@@ -90,7 +90,9 @@ int avx_isa_force(int level);
|
||||
X(mul) X(silu_mul) X(gelu) X(silu) \
|
||||
X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \
|
||||
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
|
||||
X(scale_rows) X(fill) \
|
||||
X(scale_rows) X(fill) X(act_mul) X(seg_mean) \
|
||||
X(mul_weight) X(pool_rows) X(relu) X(clamp) \
|
||||
X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
|
||||
/* ---- quantisation and rotation */ \
|
||||
X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \
|
||||
X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \
|
||||
@@ -100,7 +102,7 @@ int avx_isa_force(int level);
|
||||
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
|
||||
/* ---- attention */ \
|
||||
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
|
||||
/* ---- mixture of experts */ \
|
||||
X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \
|
||||
X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \
|
||||
@@ -114,7 +116,7 @@ int avx_isa_force(int level);
|
||||
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
|
||||
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
|
||||
X(sample_merge_topk) X(sample_mask) X(sample_pick) X(sample_argmax) \
|
||||
X(dflash_select)
|
||||
X(sample_logprobs) X(dflash_select)
|
||||
|
||||
/* The table one ISA level fills. One member per op, same order as AVX_OP_LIST. A missing
|
||||
* definition is a link error against the level's own table definition in avx_table.cpp. */
|
||||
|
||||
+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) {
|
||||
|
||||
+85
-6
@@ -75,9 +75,13 @@
|
||||
#define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
|
||||
|
||||
/* ---- elementwise and norms ---------------------------------------------------------------- */
|
||||
/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */
|
||||
static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
|
||||
P_F64O("wadd") };
|
||||
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
|
||||
P_F64O("wadd") };
|
||||
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") };
|
||||
P_F64O("wadd"), P_F64O("mult") };
|
||||
/* `w` optional: absent, the gain is one. */
|
||||
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") };
|
||||
|
||||
static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"),
|
||||
P_F64("eps"), P_STR("dtype"), P_F64O("wadd"),
|
||||
@@ -126,9 +130,35 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
|
||||
static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") };
|
||||
static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
|
||||
static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
|
||||
static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
|
||||
static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") };
|
||||
/* The audio (USM conformer) tower's operators; libref's lists, field for field. */
|
||||
static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") };
|
||||
static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"),
|
||||
P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"),
|
||||
P_INTO("cu_div"), P_INTO("valid_stride"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"),
|
||||
OUT("y") };
|
||||
static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oRelSin[] = { OUT("y") };
|
||||
static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("left"), P_INT("right"), P_F64("softcap"),
|
||||
P_INTO("cu_div"), P_STR("dtype") };
|
||||
static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"),
|
||||
WGT("pds"), OPD("cu_seqlens"), OUT("out") };
|
||||
/* `fill` has no input: `value` is the whole of what it writes. */
|
||||
static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") };
|
||||
static const RadOperandSpec oFill[] = { OUT("y") };
|
||||
@@ -206,7 +236,7 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
|
||||
|
||||
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_STR("dtype"), P_F64O("scale"),
|
||||
P_INTO("max_seqlen") };
|
||||
P_INTO("max_seqlen"), P_INTO("window") };
|
||||
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OUT("out") };
|
||||
|
||||
@@ -244,7 +274,9 @@ static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page")
|
||||
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
|
||||
P_F64O("scale"), P_STRO("mode"),
|
||||
P_INTO("rotary_dim"), P_F64O("wadd") };
|
||||
P_INTO("rotary_dim"), P_F64O("wadd"),
|
||||
P_INTO("v_norm"), P_STRO("sections"),
|
||||
P_STRO("comps") };
|
||||
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"),
|
||||
WGT("k_w") };
|
||||
|
||||
@@ -391,6 +423,9 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
P_STR("dtype"), P_INTO("vocab_offset"),
|
||||
P_F64O("wscale") };
|
||||
static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
P_STR("dtype"), P_INTO("vocab_offset"),
|
||||
P_F64O("wscale"), P_F64O("mult") };
|
||||
static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") };
|
||||
static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"),
|
||||
OPD_O("ahead") };
|
||||
@@ -415,6 +450,9 @@ static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT
|
||||
static const RadOperandSpec oTopk[] = { OPD("logits"), OPD("params"),
|
||||
OUT("cand_idx"), OUT("cand_val"), OUT_O("pairs") };
|
||||
static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT("token") };
|
||||
static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"),
|
||||
P_INTO("vocab_off") };
|
||||
static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD("params"), OUT("stats") };
|
||||
static const RadOperandSpec oNarrow[] = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
|
||||
static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
|
||||
OUT("token") };
|
||||
@@ -438,7 +476,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm),
|
||||
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector "
|
||||
"reduction, so it does not sum in libref's order and does not claim to." },
|
||||
{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd),
|
||||
{ "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd),
|
||||
"residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the "
|
||||
"unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's "
|
||||
"rule and both are observable, so both are reproduced exactly." },
|
||||
@@ -460,6 +498,23 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "add", ARR(pMnD), ARR(oBinary), "elementwise sum." },
|
||||
{ "mul", ARR(pMnD), ARR(oBinary),
|
||||
"elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." },
|
||||
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
|
||||
"y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." },
|
||||
{ "act_mul", ARR(pActMul), ARR(oBinary),
|
||||
"y = act(a) * b, act silu / gelu / gelu_tanh, the activation rounded to y's dtype first." },
|
||||
{ "seg_mean", ARR(pSegMean), ARR(oSegMean),
|
||||
"y[s] = the mean of x's rows in cu_seqlens segment s, summed in double, rounded once." },
|
||||
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0)." },
|
||||
{ "clamp", ARR(pMnD), ARR(oClamp), "y = min(max(x, lo), hi), lo and hi one-element weights." },
|
||||
{ "conv2d", ARR(pConv2d), ARR(oConv2d),
|
||||
"segment-wise 2-D convolution over (time, width), channels innermost, optional row mask." },
|
||||
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
|
||||
"segment-wise causal depthwise convolution over time." },
|
||||
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." },
|
||||
{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel),
|
||||
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
|
||||
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
|
||||
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
|
||||
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
|
||||
{ "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." },
|
||||
@@ -562,7 +617,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." },
|
||||
@@ -583,6 +639,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
"stream has to come out of a host reference, a device kernel and a rerun." },
|
||||
{ "sample_merge_topk", ARR(pMCand), ARR(oMerge), "the vocab-parallel candidate merge." },
|
||||
{ "sample_argmax", ARR(pMVocab), ARR(oArgmax), "greedy, ties to the lower token id." },
|
||||
{ "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs),
|
||||
"the raw logits' max, sum of exp(l - max) and k largest (id, logit) pairs, for a row with "
|
||||
"RAD_SP_LOGPROBS." },
|
||||
{ "dflash_select", ARR(pDflashSelect), ARR(oDflashSelect),
|
||||
"a greedy walk over a candidate lattice: score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * "
|
||||
"hp[l][r] * succ[cand[l, c]][r], pid(0) the anchor and pid(l) the walk's own previous pick. "
|
||||
@@ -640,6 +699,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)),
|
||||
@@ -807,6 +884,8 @@ SIMPLE("avx_sample_mask", "sample_mask", "sample", "grammar bitmask application"
|
||||
SIMPLE("avx_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT_FLOAT,
|
||||
L(sample_pick)),
|
||||
SIMPLE("avx_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, L(sample_argmax)),
|
||||
SIMPLE("avx_sample_logprobs", "sample_logprobs", "sample", "the raw distribution's summary",
|
||||
DT_FLOAT, L(sample_logprobs)),
|
||||
SIMPLE("avx_dflash_select", "dflash_select", "draft",
|
||||
"DFlash2's greedy walk over the candidate lattice",
|
||||
"i32 candidates and tokens, float unary and codebooks", L(dflash_select)),
|
||||
|
||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user