Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89cee7ce41 | ||
|
|
6a2ee986d6 | ||
|
|
7e796642e6 | ||
|
|
9238b1f23d | ||
|
|
6b4a67f52e | ||
|
|
a97985e7c2 | ||
|
|
7c0bd03841 | ||
|
|
d5b584a4c1 | ||
|
|
3a3345951f | ||
|
|
86128c2e75 | ||
|
|
7fd2cd7fa6 | ||
|
|
7d840861af | ||
|
|
05af4db458 | ||
|
|
ac79f4dc8a | ||
|
|
6fa7707dff | ||
|
|
ee5fcf1024 | ||
|
|
432b50d7dd | ||
|
|
32cdaa5cc7 | ||
|
|
d579bd7d45 | ||
|
|
1e27172c14 | ||
|
|
76727fa050 | ||
|
|
82da8eab69 | ||
|
|
73691a1189 | ||
|
|
92eb44619b | ||
|
|
e31be583a9 | ||
|
|
33778b2b8c | ||
|
|
6fd7421f79 | ||
|
|
59d36ae928 | ||
|
|
2af7fa4022 | ||
|
|
d23c3e0d17 |
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.0 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,16 +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, and
|
||||
the fused router launch), mechkbfan (the token embedding in the pinned host pool), Code000 (the
|
||||
n-gram gather on the card and the MTP head's history-pass skip) and baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, and the request log).
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the
|
||||
MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake (the
|
||||
MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop
|
||||
strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank
|
||||
tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the
|
||||
fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana
|
||||
dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form
|
||||
and row groups, the fused router launch, the adaptive draft window, the MoE prefill forms and the
|
||||
sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000
|
||||
(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, the request log, an uneven world's
|
||||
per-rank KV and weights split, --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.
|
||||
|
||||
+49
-2
@@ -39,6 +39,10 @@ typedef struct RadModelMeta {
|
||||
|
||||
float rms_eps;
|
||||
float rope_theta;
|
||||
/* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope --
|
||||
* and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with
|
||||
* text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses
|
||||
* by name. A bare factor here would read every scheme as a linear position divide. */
|
||||
float rope_scale;
|
||||
|
||||
/* Free-form key/value from the container header, for anything the struct above does not
|
||||
@@ -130,6 +134,15 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_out_rows;
|
||||
|
||||
/* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no
|
||||
* audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way
|
||||
* max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds
|
||||
* the longest clip, since one clip is one segment. The engine takes it from
|
||||
* RadArchProbe::audio_frames, which is the plugin's statement of its longest clip.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_audio_frames;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== weights */
|
||||
@@ -439,6 +452,25 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
* the first step. An embedding-only or encoder-only plugin declares none, deliberately. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits,
|
||||
* one row a sequence of the step -- row s is sequence s's whole input pooled into one vector,
|
||||
* whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads
|
||||
* rows [0, n_seq) back after the step and hands each to its request; it does not normalise them,
|
||||
* because that is the API's choice and not the model's.
|
||||
*
|
||||
* DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is:
|
||||
*
|
||||
* - every sequence in a step is a WHOLE input. The scheduler never splits one across steps,
|
||||
* because an encoder that attends both ways cannot be fed half of its input, and it refuses
|
||||
* an input longer than one step's tokens rather than truncating it;
|
||||
* - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request
|
||||
* ends at the step that carried it.
|
||||
*
|
||||
* f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A
|
||||
* Program declares this or logits, never both -- a model that both generates and embeds is two
|
||||
* deployments. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits
|
||||
@@ -527,17 +559,21 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* the processor's (core/mm), which reads its geometry from the container: the two agree through
|
||||
* `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the
|
||||
* processor about either. */
|
||||
/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio
|
||||
* encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and
|
||||
* its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */
|
||||
enum {
|
||||
RAD_MM_IMAGE = 1u << 0,
|
||||
RAD_MM_VIDEO = 1u << 1,
|
||||
RAD_MM_AUDIO = 1u << 2,
|
||||
};
|
||||
|
||||
typedef struct RadEncoderDecl {
|
||||
const char* name; /* "vision" -- for messages */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */
|
||||
int64_t patch_dim; /* elements in one input patch row */
|
||||
int64_t merge; /* input patches per output row */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches (max_audio_frames) */
|
||||
int64_t n_embd; /* the width of an output row, the model's embedding width */
|
||||
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
|
||||
* the pass and before any other pass runs, so the planner may share its bytes with buffers
|
||||
@@ -608,6 +644,17 @@ typedef struct RadArchProbe {
|
||||
* function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the
|
||||
* core does not ask, and the activation arena is not lent. */
|
||||
int shape_probe_ok;
|
||||
|
||||
/* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin
|
||||
* declares an encoder. A pass carries whole output rows, so the core rounds the pass size it
|
||||
* picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator
|
||||
* names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */
|
||||
int64_t enc_merge;
|
||||
|
||||
/* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole
|
||||
* number of its merge), when it declares one: the engine sizes the audio pass with it
|
||||
* (RadBuildCtx::max_audio_frames). 0 is no audio. */
|
||||
int64_t audio_frames;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
+10
-4
@@ -206,10 +206,16 @@ typedef struct RadBatch {
|
||||
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
|
||||
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
|
||||
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
|
||||
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
|
||||
* resized, normalised and cut by the processor, and its output is the encoder's declared
|
||||
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO
|
||||
* for an audio encoder, the image/video mask for the other -- so a program that declared two
|
||||
* knows which to run. Its input is a list of patches, already resized, normalised and cut by
|
||||
* the processor, and its output is the encoder's declared `out` buffer, one row per `merge`
|
||||
* patches, which the core reads back after the pass.
|
||||
*
|
||||
* An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's
|
||||
* index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the
|
||||
* clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones.
|
||||
*
|
||||
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
|
||||
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
|
||||
|
||||
+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
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds using
|
||||
* the ORIGINAL training length, never the deployment/table length. Kernels share
|
||||
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
|
||||
#include "rad_plugin.h"
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_YARN_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_YARN_HD
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
|
||||
RAD_YARN_HD float frequency(float inv, int i) const {
|
||||
if (factor == 0.0f) return inv;
|
||||
const float width = high == low ? 0.001f : high - low;
|
||||
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
|
||||
/* Keep the blend order used by the reference YaRN implementation. */
|
||||
const float mask = 1.0f - ramp;
|
||||
return (inv / factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
};
|
||||
|
||||
inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
|
||||
if (factor == 0.0f) return {};
|
||||
return { factor,
|
||||
(float)rad_args_getf_or(a, "yarn_low", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_high", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
|
||||
}
|
||||
|
||||
inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
return std::isfinite(y.factor) && (y.factor == 0.0f ||
|
||||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
|
||||
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
#endif
|
||||
+126
-3
@@ -16,6 +16,7 @@
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
@@ -626,6 +627,7 @@ struct Geom {
|
||||
float wadd_qk = 0.0f;
|
||||
float theta = 1e6f;
|
||||
float rope_scale = 1.0f;
|
||||
RadYarn yarn;
|
||||
/* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several
|
||||
* position components declares `rope` with `rope_mode` and these sections and hands it
|
||||
* RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here
|
||||
@@ -789,7 +791,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
g.dtype = dtype;
|
||||
g.act_dtype = act_dtype;
|
||||
{
|
||||
@@ -1023,19 +1025,140 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
|
||||
* cannot rotate. */
|
||||
inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
|
||||
|
||||
/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
|
||||
* exactly the parameters it was given, so its op identities and tune keys are unchanged. */
|
||||
inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_F64("yarn_factor", g.yarn.factor));
|
||||
p.push_back(RAD_F64("yarn_low", g.yarn.low));
|
||||
p.push_back(RAD_F64("yarn_high", g.yarn.high));
|
||||
p.push_back(RAD_F64("yarn_magnitude", g.yarn.magnitude));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
|
||||
* target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
|
||||
* `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
|
||||
* factor without its type would be a linear position divide for a scheme that is not one.
|
||||
*
|
||||
* The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
|
||||
* `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
|
||||
* `draft.rope_scaling.`) that names a type in `rope_type` or `type`; a multimodal target's
|
||||
* text_config is authoritative. core/format/rope_override.h writes --rope-scaling into the same
|
||||
* object, found in the same order.
|
||||
*
|
||||
* default, mrope no scaling (`mrope` is the legacy Qwen2-VL spelling of default + sections)
|
||||
* linear positions divided by `factor`
|
||||
* yarn static YaRN: frequencies blended over the correction range that `factor`,
|
||||
* `original_max_position_embeddings`, `beta_fast`/`beta_slow` and `truncate`
|
||||
* give, cos/sin scaled by `attention_factor` (default 1 + 0.1 ln factor). The
|
||||
* factor is the config's, read as vLLM and transformers read it.
|
||||
*
|
||||
* Anything else -- llama3, longrope, dynamic -- is refused by name, as is YaRN's `mscale` form. A
|
||||
* refusal leaves the geometry as it was. */
|
||||
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
|
||||
const std::string root(prefix);
|
||||
const char* who = root.empty() ? "target" : "draft";
|
||||
const std::vector<std::string> homes = root.empty()
|
||||
? std::vector<std::string>{"text_config.rope_parameters.", "rope_parameters.",
|
||||
"text_config.rope_scaling.", "rope_scaling."}
|
||||
: std::vector<std::string>{root + "rope_parameters.", root + "rope_scaling."};
|
||||
std::string home, type_key;
|
||||
const char* type = nullptr;
|
||||
for (const auto& h : homes) {
|
||||
for (const char* t : {"rope_type", "type"})
|
||||
if ((type = rad_meta_gets(meta, (h + t).c_str(), nullptr))) { type_key = h + t; break; }
|
||||
if (type) { home = h; break; }
|
||||
}
|
||||
if (!type || !std::strcmp(type, "default") || !std::strcmp(type, "mrope")) {
|
||||
g.yarn = {};
|
||||
g.rope_scale = 1.0f;
|
||||
return RAD_OK;
|
||||
}
|
||||
auto get = [&](const char* key, double fallback) {
|
||||
const char* text = rad_meta_gets(meta, (home + key).c_str(), nullptr);
|
||||
if (!text) return fallback;
|
||||
char* end = nullptr;
|
||||
const double value = std::strtod(text, &end);
|
||||
if (end == text) return (double)NAN;
|
||||
while (*end == ' ' || *end == '\t' || *end == '\n') ++end;
|
||||
return *end ? (double)NAN : value;
|
||||
};
|
||||
if (!std::strcmp(type, "linear")) {
|
||||
const double factor = get("factor", 0.0);
|
||||
const float scale = (float)factor;
|
||||
if (!std::isfinite(factor) || factor <= 0.0 || !std::isfinite(scale) || scale <= 0.0f) {
|
||||
fprintf(stderr, "radiance: %s linear rotary scaling (%s) needs a finite factor > 0\n",
|
||||
who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = {};
|
||||
g.rope_scale = scale;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (std::strcmp(type, "yarn")) {
|
||||
fprintf(stderr, "radiance: %s rotary type '%s' (%s) is not implemented; default, linear "
|
||||
"and yarn are\n", who, type, type_key.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
|
||||
* out are the same answer. */
|
||||
double truncate = 1.0;
|
||||
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
|
||||
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
|
||||
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
|
||||
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
|
||||
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
|
||||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
|
||||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
|
||||
rot < 2 || (rot & 1)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) needs a finite factor >= 1, an integral "
|
||||
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
|
||||
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* mscale variants are a different contract; never silently ignore them. */
|
||||
for (const char* k : {"mscale", "mscale_all_dim"})
|
||||
if (rad_meta_gets(meta, (home + k).c_str(), nullptr)) {
|
||||
fprintf(stderr, "radiance: %s YaRN %s%s is not implemented; attention_factor is\n",
|
||||
who, home.c_str(), k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto correction = [&](double beta) {
|
||||
return rot * std::log(original / (beta * 2.0 * 3.14159265358979323846)) /
|
||||
(2.0 * std::log((double)g.theta));
|
||||
};
|
||||
double low = correction(fast), high = correction(slow);
|
||||
if (truncate != 0.0) { low = std::floor(low); high = std::ceil(high); }
|
||||
const RadYarn y = {(float)factor, (float)std::max(0.0, low),
|
||||
(float)std::min((double)rot - 1, high), (float)magnitude};
|
||||
if (!rad_yarn_valid(y)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) resolves to an empty correction range\n", who,
|
||||
home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = y;
|
||||
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
if (g.rope_mc)
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -121,7 +121,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, RAD_OP(b, "rope",
|
||||
op_rope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -65,8 +65,10 @@
|
||||
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
|
||||
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
|
||||
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Here it also buys
|
||||
* something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Its candidates
|
||||
* are then rescored against the target's own head where that head is fp8 or int8 (op_drerank), so
|
||||
* the coarseness costs only which candidates are proposed, not how they are ranked. The 2-bit head
|
||||
* also buys something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* global without an all-gather and the selector's codebooks can be indexed directly.
|
||||
*
|
||||
* ============================== THE NORMS ARE PLAIN ==============================
|
||||
@@ -230,10 +232,11 @@ struct Dflash2 {
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* THE SIX LINEARS ARE FP8 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
|
||||
* block fp8 and the recipe makes it so -- and the reason is bytes: the drafter is read WHOLE on
|
||||
* every decode step, which makes it one of the largest single items in the decode budget
|
||||
* after the trunk's own GEMMs.
|
||||
* THE SIX LINEARS ARE FP8 OR MXFP4 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares
|
||||
* each as block fp8 or OCP-MXFP4, whichever the recipe made it -- and the reason is bytes: the
|
||||
* drafter is read WHOLE on every decode step, which makes it one of the largest single items in
|
||||
* the decode budget after the trunk's own GEMMs. On Qwen3.8-27B at depth 7, MXFP4 rounded to
|
||||
* nearest accepts ~1% fewer tokens a step than fp8 and takes ~1.5 ms off a ~34 ms step.
|
||||
* Nothing it computes can change an emitted token, because every draft is verified against the
|
||||
* trunk exactly; the only thing quantising it can move is acceptance. */
|
||||
DenseFP8 w_fc{};
|
||||
@@ -284,6 +287,14 @@ struct Dflash2 {
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_drerank = 0; /* the candidates rescored against the target's head */
|
||||
/* THE TARGET'S lm_head, set by the plugin before declare when its plane is one logit_rerank
|
||||
* reads (fp8 or int8 rows); 0 leaves the coarse head's own scores as the candidates'. */
|
||||
rad_weight w_lm = 0;
|
||||
/* How many candidates the coarse head proposes for the rerank: logit_rerank's and row_topk's
|
||||
* ceiling. Rescoring is exact, so a wider set can only find more of the exact top sel_topk. */
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
@@ -471,8 +482,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
/* EVERY LINEAR HERE IS `fp8a8` -- or `mxfp4a8` where the recipe made the drafter 4-bit; DenseFP8
|
||||
* reads which off the container and declares the GEMM (`gemm()`), and either one reads the
|
||||
* same E4M3 pair -- and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The fp8 weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
|
||||
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
|
||||
* pass is `block` rows by construction.
|
||||
@@ -489,12 +502,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
|
||||
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -515,18 +523,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
|
||||
* weight its prefetch interval and its residency class, so two weights want two ops even
|
||||
* where one would issue both. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
@@ -538,7 +536,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -603,24 +601,9 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h2q, w.h2s}, {w.v});
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.h2q, w.h2s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
@@ -633,12 +616,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.atq, w.ats}, {w.h});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
@@ -650,12 +628,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h2q, w.h2s}, {w.gate_up});
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.h2q, w.h2s}, {w.gate_up});
|
||||
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
|
||||
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
|
||||
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
|
||||
@@ -667,7 +640,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* because M > 64 is a refusal in the kernel and not a slower path. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0) {
|
||||
if (hi > 0 && !w_gu[i].mx) { /* the fold is an fp8a8 tile; an MXFP4 gate_up takes the pair */
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
@@ -678,12 +651,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffq, w.ffs}, {w.h});
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
|
||||
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
|
||||
@@ -712,14 +680,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -789,31 +757,56 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
|
||||
* replicated, so that graph is the one it always was -- an optional parameter present with
|
||||
* the value 0 is not the same declaration as an absent one. */
|
||||
const bool rerank = w_lm && (dh_shard || g.world <= 1); /* see op_drerank below */
|
||||
if (!rerank) top_w = cfg.sel_topk;
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_INT("R", top_w), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_INT("R", top_w), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
/* THE CANDIDATES ARE RESCORED EXACTLY when the target's head can be read row by row. The
|
||||
* coarse head proposes its top kRerankR, `logit_rerank` scores those against the target's own
|
||||
* fp8 head and re-sorts them, and the selector reads the best sel_topk of that order -- the
|
||||
* candidate set and the unary logits the drafter was trained against, at kRerankR rows of the
|
||||
* weight a draft row instead of a second, finer copy of the head. On Qwen3.8-27B the 2-bit
|
||||
* head's own top-1 matches the exact head's on 76% of draft rows and the rescored one on all of
|
||||
* them; served at depth 7 that is the 4-bit head's speed at half its bytes (330 MiB).
|
||||
*
|
||||
* Sharded, each rank rescores only ids it owns (row_topk reports this rank's slice), and the
|
||||
* gather and merge below then rank exact values. A replicated draft head above one rank
|
||||
* proposes ids another rank owns, so it keeps its own scores. */
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("n_vocab", head_rows(g)), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("vocab_off", g.vocab_off), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
rad_buf rd[2] = { w.sel_h, w.cand };
|
||||
rad_buf wr[3] = { w.cand, w.unary, w.dpair };
|
||||
rad_op_reads (b, op_drerank, rd, 2);
|
||||
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
|
||||
}
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
|
||||
* candidate gather carries `row`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.sel_topk * 2),
|
||||
RAD_INT("numel", srows * top_w * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", cfg.sel_topk * 2)),
|
||||
RAD_INT("row", top_w * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", top_w),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -851,16 +844,16 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
* rows. */
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
@@ -898,11 +891,11 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
@@ -919,7 +912,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
|
||||
* its coefficients come from the replicated pre-attention norm, so either order is the
|
||||
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
|
||||
@@ -941,13 +934,12 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
@@ -980,15 +972,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.cand, S),
|
||||
brows(w.cand, S), brows(w.unary, S), RAD_NONE);
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
@@ -508,7 +508,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
|
||||
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
|
||||
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -667,14 +667,14 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -506,6 +506,31 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* WHETHER A CHECKPOINT SHIPS ONE LAYER'S EXPERTS STACKED OR ONE BY ONE, as the Src it fills.
|
||||
* Recent releases stack them -- `<prefix>.gate_up_proj` and `<prefix>.down_proj` -- and a
|
||||
* quantised export (AutoRound's) writes each expert on its own, `<prefix>.<e>.{gate,up,down}_proj`.
|
||||
* Each form is asked of the checkpoint through a probe name mapped to its first expert, which the
|
||||
* checkpoint answers or does not. Stacked is the answer when neither is found: a container is
|
||||
* read by declared name, the same under both maps, so it asks nothing here. `tag` keeps one
|
||||
* caller's probe name apart from another's for the same layer. */
|
||||
inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const char* prefix,
|
||||
MoeFP8::Src* src) {
|
||||
const char* gu = nm.ckpt("%s.gate_up_proj", prefix);
|
||||
const char* probe = nm.f("probe.%s.%s.0", tag, prefix);
|
||||
RadEncoding e{};
|
||||
RAD_ARCH_TRY(map_concat(b, probe, { nm.ckpt("%s.0.gate_proj.weight", prefix),
|
||||
nm.ckpt("%s.0.up_proj.weight", prefix) }));
|
||||
if (weight_enc(b, probe, &e)) {
|
||||
src->experts = nm.ckpt("%s", prefix);
|
||||
src->experts_gate_up = src->experts_down = nullptr;
|
||||
} else {
|
||||
src->experts = nullptr;
|
||||
src->experts_gate_up = gu;
|
||||
src->experts_down = nm.ckpt("%s.down_proj", prefix);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
|
||||
+55
-2
@@ -1127,11 +1127,35 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
*/
|
||||
struct DenseFP8 {
|
||||
rad_weight w = 0, s = 0;
|
||||
/* OR AN OCP-MXFP4 WEIGHT, when that is what the container holds for it (a recipe's `codes=
|
||||
* fp4_e2m1 group=32 scale=e8m0`): e2m1 codes, the E8M0 plane, and that plane again as the
|
||||
* per-row reference -- LinearFP8's mx branch, without the GEMM. A block that declares its own
|
||||
* GEMM over a DenseFP8 asks `gemm()` for it and passes `bref()` as the op's last operand, so
|
||||
* one block serves either format against the same E4M3 activation pair. */
|
||||
rad_weight ref = 0;
|
||||
bool mx = false;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts = {});
|
||||
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
|
||||
if (mx)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
}
|
||||
/* The op's trailing `b_ref` operand: the reference view for MXFP4, absent for fp8. */
|
||||
RadOperand bref() const { return mx ? RAD_W(ref) : RAD_NONE; }
|
||||
};
|
||||
|
||||
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
@@ -1139,6 +1163,36 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts) {
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---- OCP-MXFP4, read off the encoding the name map resolves to. The exponent grid is one row
|
||||
* tall, so a part needs only whole 16-row tiles; K takes whole 128s because the E4M3 activation
|
||||
* in front carries a scale per (row, 128). */
|
||||
{
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
RadEncoding enc{};
|
||||
mx = weight_enc(b, wn, &enc) && linear_is_mxfp4(enc);
|
||||
if (mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows "
|
||||
"in 16s and K in whole %d-column activation scale blocks.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t q : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, access, shard, grp, p, np);
|
||||
s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
ref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
access, shard, grp, p, np);
|
||||
return w && s && ref ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (N % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank, which is not a whole number of "
|
||||
"%dx%d scale blocks. A block-scaled fp8 weight cannot be split inside a "
|
||||
@@ -1163,8 +1217,7 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t
|
||||
}
|
||||
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sn = nm.f("%s.scale", base); /* the name map was made above */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, wp, np);
|
||||
s = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard,
|
||||
grp, sp, np);
|
||||
|
||||
@@ -269,7 +269,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
|
||||
op_bkey = g.rope_mc
|
||||
? RAD_OP(b, "qsa_block_key",
|
||||
? decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
@@ -278,7 +278,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_WEIGHTS(w_kn))
|
||||
: RAD_OP(b, "qsa_block_key",
|
||||
: decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
|
||||
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(embgemma2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -185,7 +185,6 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
|
||||
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
|
||||
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
|
||||
@@ -201,6 +200,7 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
int s;
|
||||
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
|
||||
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
|
||||
@@ -431,6 +431,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the KV cache. One group: every layer is full attention. */
|
||||
RadKVGroupDecl fd{};
|
||||
|
||||
@@ -237,6 +237,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
|
||||
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
|
||||
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
|
||||
|
||||
@@ -339,7 +339,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
/* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
|
||||
* the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
|
||||
* conventions in one process, which is exactly why this is a second Geom and not a flag. */
|
||||
@@ -493,13 +493,24 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
* vocab-sharded, asked here rather than re-derived, because a buffer that disagreed with the
|
||||
* op declared over it is a read past its end. */
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, dc.sel_topk});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, dc.sel_topk});
|
||||
/* THE CANDIDATES ARE RESCORED against the target's head when logit_rerank can read its plane
|
||||
* (fp8 or int8 rows) and every candidate a rank proposes is one it owns -- the rule the block
|
||||
* applies; the planes are then kRerankR wide and the selector reads the first sel_topk. */
|
||||
{
|
||||
const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16);
|
||||
if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) {
|
||||
m.df.w_lm = m.w_lm_head;
|
||||
m.df.top_w = Dflash2::kRerankR;
|
||||
}
|
||||
}
|
||||
const int64_t tw = m.df.w_lm ? m.df.top_w : dc.sel_topk;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
|
||||
/* The vocab-parallel candidate exchange, and only when there is one: this rank's top-R as
|
||||
* (int32 id, float value) pairs and the all-gathered world_size * R of them. */
|
||||
if (Dflash2::head_sharded(dg)) {
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, dc.sel_topk, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * dc.sel_topk, 2});
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
/* NAMED, because the engine reads the draft out of it by name: a DFlash2 pass proposes through
|
||||
* the selector and never through the sampler's token buffer. */
|
||||
@@ -635,6 +646,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
GdnFP8::Config& gc = m.gcfg;
|
||||
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
|
||||
"linear_num_key_heads", 0);
|
||||
@@ -677,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,
|
||||
@@ -952,7 +964,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
|
||||
* band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
|
||||
* prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("dtype", "f32")),
|
||||
|
||||
@@ -364,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
/* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
|
||||
* for the target device, the answer is a converter flag that writes a NAMED partial container
|
||||
* -- not an environment variable that makes a full one silently mean something else. A slice
|
||||
@@ -520,8 +521,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
? (int64_t)g.rank * (mc.n_expert / g.world) : 0;
|
||||
{
|
||||
MoeFP8::Src ps{};
|
||||
ps.experts_gate_up = nm.ckpt("model.language_model.layers.0.mlp.experts.gate_up_proj");
|
||||
ps.experts_down = nm.ckpt("model.language_model.layers.0.mlp.experts.down_proj");
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "format",
|
||||
"model.language_model.layers.0.mlp.experts", &ps));
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
|
||||
}
|
||||
/* A CHECKPOINT SERVED AS IT SHIPS IS bf16 THROUGHOUT. Plain experts mean a container
|
||||
@@ -1000,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* one step; the symptom is fluent output with one arm of the model reading the other's
|
||||
* leftovers, which nothing downstream flags.
|
||||
*/
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
|
||||
RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")),
|
||||
@@ -1205,8 +1206,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = m.moecfg;
|
||||
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
|
||||
ms.experts_gate_up = nm.ckpt("%s.%lld.mlp.experts.gate_up_proj", pre, (long long)l);
|
||||
ms.experts_down = nm.ckpt("%s.%lld.mlp.experts.down_proj", pre, (long long)l);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
|
||||
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
|
||||
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
|
||||
@@ -1367,8 +1368,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
ts.mlp.cfg = m.moecfg;
|
||||
ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre);
|
||||
ts.mlp.experts_gate_up = nm.ckpt("%s.layers.0.mlp.experts.gate_up_proj", mpre);
|
||||
ts.mlp.experts_down = nm.ckpt("%s.layers.0.mlp.experts.down_proj", mpre);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("%s.layers.0.mlp.experts", mpre),
|
||||
&ts.mlp));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ts.mlp.shared = nm.ckpt("%s.layers.0.mlp.shared_expert", mpre);
|
||||
ts.mlp.shared_gate = nm.ckpt("%s.layers.0.mlp.shared_expert_gate.weight", mpre);
|
||||
|
||||
@@ -97,6 +97,22 @@ function(rad_add_plugin name kind)
|
||||
"because the language a project compiles in is the project's own decision.")
|
||||
endif()
|
||||
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
|
||||
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
|
||||
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
|
||||
# input path, the output path and the command line, so one source built in two directories --
|
||||
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
|
||||
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
|
||||
# object's read-only data and with it every PC-relative address .text forms into it: the same
|
||||
# instructions, different bytes. Named from what identifies the unit and nothing about where it
|
||||
# was built, the ID is the same wherever the plugin is built and still differs between any two
|
||||
# sources, which is the property clang needs of it.
|
||||
foreach(src ${P_HIP_SOURCES})
|
||||
get_filename_component(_rad_abs "${src}" ABSOLUTE)
|
||||
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
|
||||
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
|
||||
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
|
||||
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
|
||||
endforeach()
|
||||
list(APPEND srcs ${P_HIP_SOURCES})
|
||||
endif()
|
||||
add_library(${name} MODULE ${srcs})
|
||||
|
||||
@@ -132,6 +132,7 @@ public:
|
||||
int op_resolved (rad_op h) const;
|
||||
int decl_name_map(const RadNameMap* m);
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
+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);
|
||||
|
||||
+33
-2
@@ -129,7 +129,7 @@ static std::vector<std::string> home_subdirs(const std::string& home, const char
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out) {
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
@@ -188,6 +188,35 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
}
|
||||
}
|
||||
|
||||
/* AN IMPORTED QUANTISATION is served by the family's quantised plugin (startup.h). */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) {
|
||||
fam.push_back(&p);
|
||||
if (!p.arch_quant.empty()) quantised.push_back(&p);
|
||||
}
|
||||
const Plugin* pick = quantised.size() == 1 ? quantised[0]
|
||||
: quantised.empty() && fam.size() == 1 ? fam[0] : nullptr;
|
||||
if (!pick && quantised.size() > 1) {
|
||||
std::string names;
|
||||
for (const Plugin* p : quantised) names += (names.empty() ? "" : ", ") + p->arch_quant;
|
||||
RAD_ERR("'%s' is quantised by %s and imported weight by weight, and '%s' has more than "
|
||||
"one quantised plugin (%s) to serve it; none is chosen for it",
|
||||
arch_id.c_str(), quant.c_str(), arch_id.c_str(), names.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (pick) {
|
||||
out->arch_plugin = pick->name;
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (out->kernels.empty()) {
|
||||
RAD_ERR("no kernel plugin loaded from %s/kernels. Every weight's layout comes from the "
|
||||
"kernel that will read it, so there is nothing to lay a container out for.",
|
||||
@@ -347,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
|
||||
|
||||
@@ -66,11 +66,19 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
* has one plugin per weight format and they all answer the same architecture id. `quant` is the
|
||||
* container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the
|
||||
* unquantised case, which matches a plugin that says "" and nothing else. */
|
||||
/*
|
||||
* `imported` is a checkpoint whose quantisation is imported weight by weight
|
||||
* (Checkpoint::imports): its descriptor names the tool that made it and no plugin claims it, so
|
||||
* the plugin is the architecture's QUANTISED one -- the one plugin of the family claiming a
|
||||
* descriptor, or the family's only plugin when that claims none. Two quantised plugins are a
|
||||
* choice this cannot make, and are refused by name. `out->arch_quant` is the descriptor chosen,
|
||||
* which is what a container converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
const std::string& quant,
|
||||
LoadedPlugins* out);
|
||||
LoadedPlugins* out,
|
||||
bool imported = false);
|
||||
|
||||
/* `also` declares into the SAME builder after the architecture plugin has. That is what puts the
|
||||
* sampler chain in the same Program: its ops resolve through the same hierarchy at the same
|
||||
|
||||
+114
-22
@@ -6,6 +6,7 @@
|
||||
* (spec §6).
|
||||
*/
|
||||
#include "rad_core.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
@@ -28,16 +29,28 @@ struct Flag {
|
||||
const char* help;
|
||||
};
|
||||
|
||||
/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
|
||||
* that points at it: the two are initialised in this order. */
|
||||
static const std::string g_draft_window_help =
|
||||
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
|
||||
" --num-speculative-tokens every step; adaptive makes that\n"
|
||||
" the ceiling and follows each sequence's acceptance and the\n"
|
||||
" measured step cost (a serial draft head only). Default ") +
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--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"
|
||||
@@ -45,17 +58,16 @@ static const Flag g_flags[] = {
|
||||
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
{ "--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"
|
||||
@@ -98,6 +110,7 @@ static const Flag g_flags[] = {
|
||||
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
@@ -123,6 +136,10 @@ static const Flag g_flags[] = {
|
||||
" set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n"
|
||||
" to xhigh, which on a short task can spend the whole token budget\n"
|
||||
" inside <think> and answer nothing. \"none\" turns thinking off" },
|
||||
{ "--reasoning-effort-map", "MAP", "FROM=TO[,FROM=TO...]: a `reasoning_effort` a request sends, replaced before\n"
|
||||
" the chat template sees it -- high=xhigh lets a client that always sends\n"
|
||||
" OpenAI's top level reach Qwen3.8's. TO is checked against the template at\n"
|
||||
" startup; none and minimal turn thinking off. Repeatable" },
|
||||
{ "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n"
|
||||
" N reasoning tokens the reasoning block is closed and the answer follows,\n"
|
||||
" so a client's max_tokens is not spent on reasoning alone. Unset is no\n"
|
||||
@@ -175,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" },
|
||||
@@ -206,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"
|
||||
@@ -356,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); }
|
||||
@@ -376,8 +406,28 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
|
||||
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
|
||||
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
|
||||
else if (S("--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); }
|
||||
else if (S("--rope-scaling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Checked here, so a typo is a refusal at the command line and not a model served
|
||||
* with its trained rotary at a length it cannot reach. */
|
||||
RopeSpec rs;
|
||||
if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
|
||||
RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
|
||||
"length, or none -- got '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->rope_scaling = v;
|
||||
}
|
||||
/* 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. */
|
||||
@@ -396,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); }
|
||||
@@ -439,6 +498,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-window")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
|
||||
else if (!std::strcmp(v, "adaptive")) c->draft_window = DraftWindow::Adaptive;
|
||||
else {
|
||||
RAD_ERR("--draft-window takes fixed or adaptive, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
|
||||
* own drafter -- or none -- would hand the caller a server that is not the one they
|
||||
@@ -480,6 +548,24 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->reasoning_effort = v; }
|
||||
else if (S("--reasoning-effort-map")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
const std::string all = v;
|
||||
size_t at = 0;
|
||||
while (at <= all.size()) {
|
||||
const size_t end = std::min(all.find(',', at), all.size());
|
||||
const std::string pair = all.substr(at, end - at);
|
||||
const size_t eq = pair.find('=');
|
||||
if (eq == std::string::npos || eq == 0 || eq + 1 == pair.size() ||
|
||||
pair.find('=', eq + 1) != std::string::npos) {
|
||||
RAD_ERR("--reasoning-effort-map takes FROM=TO pairs separated by commas, "
|
||||
"not '%s'", pair.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->reasoning_effort_map[pair.substr(0, eq)] = pair.substr(eq + 1);
|
||||
at = end + 1;
|
||||
}
|
||||
}
|
||||
else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
|
||||
!parse_int(a.c_str(), v, 0, INT32_MAX,
|
||||
&c->thinking_token_budget))
|
||||
@@ -625,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;
|
||||
@@ -670,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;
|
||||
}
|
||||
|
||||
+269
-27
@@ -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
|
||||
@@ -665,16 +667,17 @@ int Engine::step_loop() {
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ckpt_restore < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& rk = ranks_[ri];
|
||||
/* This rank's device, for its own stream and its own state slots. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
e.ckpt_restore, rk->ctx.stream());
|
||||
if (s < 0) {
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d: %s",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore,
|
||||
rad_strerror(s));
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d on "
|
||||
"rank %d: %s", (unsigned long long)e.seq,
|
||||
(int)e.ckpt_restore, (int)ri, rad_strerror(s));
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
return s;
|
||||
}
|
||||
@@ -702,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 */
|
||||
{
|
||||
@@ -804,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()) {
|
||||
@@ -863,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); }
|
||||
@@ -946,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). */
|
||||
@@ -958,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);
|
||||
@@ -1047,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. */
|
||||
@@ -1072,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
|
||||
@@ -1492,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
|
||||
@@ -2127,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;
|
||||
@@ -2138,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;
|
||||
@@ -2148,10 +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;
|
||||
@@ -2200,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",
|
||||
@@ -2230,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",
|
||||
@@ -2250,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");
|
||||
@@ -2275,6 +2491,28 @@ int Engine::run_server() {
|
||||
"that sends no reasoning effort of its own will be answered 400: %s",
|
||||
cfg_.reasoning_effort.c_str(), eff_why.c_str());
|
||||
}
|
||||
/* THE EFFORTS THE TEMPLATE TAKES, said once: a client sending another gets this set back in
|
||||
* its 400 and can read it off /server_info beforehand. A map whose target the template
|
||||
* refuses would refuse every request it maps, so it stops startup. */
|
||||
if (d.chat) {
|
||||
const std::vector<std::string> efforts = srv.probe_reasoning_efforts();
|
||||
std::string mapped;
|
||||
for (const auto& [from, to] : cfg_.reasoning_effort_map)
|
||||
mapped += fmt("%s%s -> %s", mapped.empty() ? "" : ", ", from.c_str(), to.c_str());
|
||||
if (!efforts.empty()) {
|
||||
std::string list;
|
||||
for (const std::string& e : efforts) list += (list.empty() ? "" : ", ") + e;
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
} else if (!mapped.empty()) {
|
||||
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
|
||||
}
|
||||
if (const std::string why = srv.check_reasoning_effort_map(); !why.empty()) {
|
||||
RAD_ERR("--reasoning-effort-map %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default
|
||||
* would apply to no request at all, and the operator who set it would not find out. */
|
||||
if (const std::string why = srv.check_thinking_budget(); !why.empty()) {
|
||||
@@ -2282,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.
|
||||
*
|
||||
|
||||
+26
-2
@@ -93,6 +93,15 @@ private:
|
||||
std::vector<std::thread> rank_threads_;
|
||||
|
||||
Config cfg_;
|
||||
/* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
|
||||
* token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
|
||||
* whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
|
||||
* count and the difference in its weights pool. Engine::plan fills it, and every reader of the
|
||||
* resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
|
||||
* cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
|
||||
* plan and weights pool disagree. */
|
||||
std::vector<Config> rank_cfg_;
|
||||
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
|
||||
|
||||
/* The model's source, one of the two. A container stays mapped for the life of the engine:
|
||||
* the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
|
||||
@@ -117,13 +126,15 @@ private:
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
int read_checkpoint_metadata();
|
||||
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
|
||||
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
|
||||
int apply_rope_scaling();
|
||||
int declare();
|
||||
int plan();
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
* (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
|
||||
@@ -155,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
|
||||
@@ -226,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. */
|
||||
@@ -257,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);
|
||||
|
||||
+404
-179
@@ -14,6 +14,7 @@
|
||||
#include "device/device.h"
|
||||
#include "device/directio.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "rad_plugin.h"
|
||||
@@ -51,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.
|
||||
@@ -69,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
|
||||
@@ -77,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);
|
||||
@@ -233,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,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_)
|
||||
@@ -431,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";
|
||||
@@ -512,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
|
||||
@@ -527,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";
|
||||
@@ -607,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),
|
||||
@@ -683,7 +705,9 @@ int Engine::read_metadata() {
|
||||
meta_.n_expert_shared = geti("n_expert_shared", 0);
|
||||
meta_.rms_eps = getf("rms_eps", 1e-6);
|
||||
meta_.rope_theta = getf("rope_theta", 10000.0);
|
||||
meta_.rope_scale = getf("rope_scale", 1.0);
|
||||
/* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
|
||||
* An older container's `rope_scale` key holds the factor alone and is not read. */
|
||||
meta_.rope_scale = 1.0f;
|
||||
|
||||
/* A container that says nothing about its own shape is refused HERE, by name, rather than at
|
||||
* declare as an "invalid argument" from a plugin that was handed zeros. */
|
||||
@@ -707,6 +731,7 @@ int Engine::read_metadata() {
|
||||
default: meta_kv_v_.push_back(file_->str(kv.v.s)); break;
|
||||
}
|
||||
}
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str());
|
||||
for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str());
|
||||
@@ -741,6 +766,7 @@ int Engine::read_checkpoint_metadata() {
|
||||
}
|
||||
meta_kv_k_ = mo.keys;
|
||||
meta_kv_v_ = mo.vals;
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str());
|
||||
for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str());
|
||||
@@ -754,10 +780,61 @@ int Engine::read_checkpoint_metadata() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
|
||||
* load, where the architecture's reader takes them, so an existing container serves past its
|
||||
* trained context with no reconvert -- and is checked by the same reader a converted one is. The
|
||||
* drafter, when there is one, gets the same factor over its own trained length. Then one line says
|
||||
* what the rotary is, and a context past what it covers is named. */
|
||||
int Engine::apply_rope_scaling() {
|
||||
RopeSpec spec;
|
||||
if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
|
||||
RAD_ERR("--rope-scaling '%s': yarn:FACTOR (above 1) with an optional :ORIG, or none",
|
||||
cfg_.rope_scaling.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (spec.kind != RopeSpec::Keep) {
|
||||
std::string why;
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "", meta_.n_ctx_train, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RopeKeys kv{ meta_kv_k_, meta_kv_v_ };
|
||||
if (kv.any_prefix("draft.")) {
|
||||
int64_t dtrain = meta_.n_ctx_train;
|
||||
if (const std::string* t = kv.get("draft.max_position_embeddings"))
|
||||
dtrain = std::atoll(t->c_str());
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "draft.", dtrain, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RopeResolved r = rope_resolve(meta_kv_k_, meta_kv_v_, "");
|
||||
const long long want = cfg_.max_ctx > 0 ? (long long)cfg_.max_ctx : (long long)meta_.n_ctx_train;
|
||||
if (r.type == "yarn" && r.factor > 1.0) {
|
||||
const long long reach = (long long)(r.orig * r.factor);
|
||||
RAD_INFO("rope: YaRN factor %g over %lld trained positions -- the rotary reaches %lld; "
|
||||
"--max-model-len %lld%s", r.factor, (long long)r.orig, reach, want,
|
||||
spec.kind == RopeSpec::Yarn ? " (--rope-scaling)" : " (the container's own)");
|
||||
if (want > reach)
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions YaRN factor %g covers; "
|
||||
"positions beyond them are extrapolated", want, reach, r.factor);
|
||||
} else if (meta_.n_ctx_train > 0 && want > meta_.n_ctx_train &&
|
||||
!(r.type == "linear" && r.factor > 1.0)) {
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions the model was trained on and "
|
||||
"nothing scales its rotary, so positions beyond them are extrapolated; a model "
|
||||
"card's YaRN extension is --rope-scaling yarn:FACTOR (docs/YARN.md)", want,
|
||||
(long long)meta_.n_ctx_train);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== 3 + 4. plugins, declare */
|
||||
int Engine::load_plugins() {
|
||||
int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy,
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_);
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_,
|
||||
ckpt_ && ckpt_->imports() != Checkpoint::Import::None);
|
||||
if (s < 0) {
|
||||
/* rad_tools_load_plugins has said why -- a plugin refused, or no architecture plugin for
|
||||
* this model -- each by name. What it does not know is that this was the engine's start. */
|
||||
@@ -786,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;
|
||||
@@ -845,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");
|
||||
@@ -883,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);
|
||||
@@ -903,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;
|
||||
|
||||
@@ -919,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. */
|
||||
@@ -1125,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 &&
|
||||
@@ -1140,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;
|
||||
@@ -1197,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());
|
||||
@@ -1232,9 +1336,108 @@ int Engine::plan() {
|
||||
r->program.arena_stage_bytes = vb.stage;
|
||||
r->program.arena_bytes = r->program.arena_stage_off + vb.stage;
|
||||
}
|
||||
|
||||
/* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
|
||||
*
|
||||
* The split above is the dearest rank's, applied to every card, and one block table serves
|
||||
* every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
|
||||
* costs less per token (an attention-zero rank keeps no attention cache, only what its
|
||||
* other groups cost) would reserve the common KV pool and page a fraction of it, while its
|
||||
* experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
|
||||
* KV pool that pages exactly the common token count and the difference in its weights
|
||||
* pool, up to every one of its weights resident. The token count, the carve, the loan and
|
||||
* the dearest ranks' pools are what they were.
|
||||
*
|
||||
* Only a 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
|
||||
* re-split all the same: the bytes it would never page are bytes its experts can hold, and
|
||||
* without virtual memory management they are allocated whole.
|
||||
* Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
|
||||
* on every rank, field for field. A rank that qualifies and is not re-split is named with
|
||||
* the reason, once. */
|
||||
rank_cfg_.assign(ranks_.size(), cfg_);
|
||||
kv_planned_tokens_ = 0;
|
||||
constexpr int64_t kMiB = (int64_t)1 << 20;
|
||||
int64_t kv_max = 0;
|
||||
for (const VramFacts& f : facts) kv_max = std::max(kv_max, f.kv_ceiling);
|
||||
std::vector<size_t> cheaper;
|
||||
for (size_t i = 0; i < facts.size() && i < ranks_.size(); ++i)
|
||||
if (facts[i].kv_ceiling < kv_max) cheaper.push_back(i);
|
||||
/* Why no cheaper rank is re-split, where the reason holds for the whole world. */
|
||||
std::string kept;
|
||||
std::vector<std::unique_ptr<KVManager>> probes(ranks_.size());
|
||||
int64_t T = -1;
|
||||
if (cheaper.empty()) {
|
||||
/* Every rank's cache costs the same per token: there is nothing to re-split. */
|
||||
} else if (cfg_.placement != "expert_tiered") {
|
||||
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
|
||||
cfg_.placement.c_str());
|
||||
} else {
|
||||
/* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
|
||||
* pool, the least of them. Asked of the same plan configure_kv makes, against the same
|
||||
* bytes: nothing reserves from a KV pool before its carve. */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
const int64_t t = probes[i]->paged_tokens(cfg_.vram_kv_mib * kMiB);
|
||||
if (t == KVManager::kUnboundedTokens) continue;
|
||||
if (T < 0 || t < T) T = t;
|
||||
}
|
||||
if (kept.empty() && T <= 0)
|
||||
kept = "no rank's cache pages a bounded token count in the common pool";
|
||||
}
|
||||
for (size_t i : cheaper) {
|
||||
const std::string costs =
|
||||
fmt("kv: rank %d's cache costs %s at the worst case where its dearest peer's costs "
|
||||
"%s", ranks_[i]->index, humanb(facts[i].kv_ceiling).c_str(),
|
||||
humanb(kv_max).c_str());
|
||||
if (!kept.empty()) {
|
||||
RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
|
||||
continue;
|
||||
}
|
||||
/* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
|
||||
* pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
|
||||
* a pool whose budget is exactly this many MiB. The pool's own alignment is already
|
||||
* among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
|
||||
const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
|
||||
if (need < 0) {
|
||||
RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
|
||||
"tokens in the common %lld MiB", costs.c_str(), (long long)T,
|
||||
(long long)cfg_.vram_kv_mib);
|
||||
continue;
|
||||
}
|
||||
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
|
||||
const RankSplit rs =
|
||||
vram_budget_rank_split(cfg_.vram_weights_mib, cfg_.vram_kv_mib, need, cap);
|
||||
if (!rs.resplit) {
|
||||
RAD_INFO("%s; its pools stay the common split: it needs all %lld MiB of the common "
|
||||
"pool to page the common %lld tokens", costs.c_str(),
|
||||
(long long)cfg_.vram_kv_mib, (long long)T);
|
||||
continue;
|
||||
}
|
||||
rank_cfg_[i].vram_kv_mib = rs.kv_mib;
|
||||
rank_cfg_[i].vram_weights_mib = rs.weights_mib;
|
||||
kv_planned_tokens_ = T;
|
||||
RAD_INFO("%s, so its KV pool pages the common %lld tokens in %lld MiB instead of %lld; "
|
||||
"its weights pool grows %lld -> %lld MiB (every weight resident wants %s)%s",
|
||||
costs.c_str(), (long long)T, (long long)rs.kv_mib, (long long)cfg_.vram_kv_mib,
|
||||
(long long)cfg_.vram_weights_mib, (long long)rs.weights_mib,
|
||||
humanb(cap).c_str(),
|
||||
rs.unusable_mib > 0
|
||||
? fmt(", and %lld MiB stay unclaimed", (long long)rs.unusable_mib).c_str()
|
||||
: "");
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
/* This rank's own split: cfg_ field for field unless the block above re-split it. */
|
||||
const Config& rc = rank_cfg_[ri];
|
||||
LogRank lr(r->index);
|
||||
/* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
|
||||
* reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
|
||||
@@ -1248,18 +1451,18 @@ int Engine::plan() {
|
||||
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
|
||||
* inference about what the workload will be (spec §6). Pools refuses by name and by how
|
||||
* much rather than shrinking anything. */
|
||||
int s = r->pools.configure(cfg_, props.vram_bytes);
|
||||
int s = r->pools.configure(rc, props.vram_bytes);
|
||||
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
|
||||
if (s < 0) {
|
||||
report_pool_refusal(r->index, r->device, r->pools, cfg_);
|
||||
report_pool_refusal(r->index, r->device, r->pools, rc);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
|
||||
* against its own card's budget (spec §5.3). */
|
||||
* against its own card's budget (spec §5.3) -- the same split its pools were given. */
|
||||
PlannerInput in{};
|
||||
in.program = &r->program;
|
||||
in.config = &cfg_;
|
||||
in.config = &rc;
|
||||
in.rank = r->index;
|
||||
in.world_size = cfg_.tp;
|
||||
if (file_ && file_->header().prof_count) {
|
||||
@@ -1267,11 +1470,22 @@ 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)
|
||||
fputs(r->plan.report(r->program).c_str(), stderr);
|
||||
if (s < 0) return s;
|
||||
/* The slab the planner filled is the pool the mover will fill: one split, read twice. */
|
||||
RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
|
||||
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
|
||||
* re-split rank whose grown weights pool took every weight still holds it. Said, because
|
||||
* the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
|
||||
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
|
||||
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
|
||||
"holds no weights; its %lld MiB (--host-pool-mib) stay allocated, as on every "
|
||||
"rank", r->index, (long long)cfg_.host_pool_mib);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -2144,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();
|
||||
@@ -2558,10 +2772,22 @@ int Engine::configure_kv() {
|
||||
* every rank is capped at the least before any carves. At an even split the cap is what
|
||||
* every rank would have carved anyway. */
|
||||
int64_t least = -1;
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
|
||||
* construction: its pool is the least whole MiB whose paged split reaches it, asked of the
|
||||
* same plan against the same bytes. Short of it, this rank would set every rank's count
|
||||
* under what its dearest peer pages -- a broken construction, refused by name. */
|
||||
if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
|
||||
RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
|
||||
"and pages %lld: the pool and the plan that sized it disagree", r->index,
|
||||
(long long)rank_cfg_[i].vram_kv_mib, (long long)kv_planned_tokens_,
|
||||
(long long)t);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
@@ -2737,16 +2963,20 @@ int Engine::configure_kv() {
|
||||
sc.n_ckpt_slots = ck_disk_slots;
|
||||
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
|
||||
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only
|
||||
* meaningful under the container and layout that produced it; read back under
|
||||
* another, it is a lossless function of somebody else's weights. */
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
|
||||
* everything a cached block's bytes actually depend on. Read back under a
|
||||
* different container, layout or KV width, a block is a lossless function of
|
||||
* somebody else's weights -- fluent, confident and wrong. There is no cheaper
|
||||
* check than refusing the whole store, because a block carries no evidence of
|
||||
* what produced it beyond the tokens it was keyed by. */
|
||||
* different container, layout, KV width or rotary, a block is a lossless
|
||||
* function of somebody else's weights -- fluent, confident and wrong. There is
|
||||
* no cheaper check than refusing the whole store, because a block carries no
|
||||
* evidence of what produced it beyond the tokens it was keyed by.
|
||||
*
|
||||
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
|
||||
* (rope_identity): a YaRN container converted from the same checkpoint has the
|
||||
* same name and shapes as the stock one, and every cached key and QSA block key
|
||||
* is rotated differently under it. */
|
||||
{
|
||||
char theta[32];
|
||||
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
|
||||
const std::string id =
|
||||
std::string(meta_.name ? meta_.name : "") + "|" +
|
||||
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
|
||||
@@ -2754,7 +2984,8 @@ int Engine::configure_kv() {
|
||||
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
|
||||
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
|
||||
cfg_.kv_cache_dtype + "|" +
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION;
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
|
||||
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
|
||||
sc.fingerprint = h;
|
||||
@@ -3015,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();
|
||||
@@ -3151,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 ----------------
|
||||
*
|
||||
@@ -3332,65 +3538,89 @@ int Engine::start() {
|
||||
*
|
||||
* Everything above this line allocated: the two pools, the activation arena, the step batch
|
||||
* staging, the weight tables a grouped GEMM walks. What is left on the card should now be
|
||||
* --gpu-headroom-mib and nothing else, and this is the only place that can say whether it is.
|
||||
* --gpu-headroom-mib plus what the budget kept for later, and this is the only place that can
|
||||
* say whether it is.
|
||||
*
|
||||
* Both directions are worth a line. TOO LITTLE means the terms the resolver could not compute
|
||||
* -- anything still allocated lazily, and whatever the driver took after the reading -- ate
|
||||
* into the memory the operator asked to keep, and the next thing to allocate on this card is
|
||||
* whatever fails. TOO MUCH means the budget left VRAM on the floor, which on a model whose
|
||||
* experts do not fit is milliseconds of decode step for every unspent GiB -- the exact
|
||||
* failure this resolver exists to remove.
|
||||
* TOO LITTLE is memory taken after the budget read the card that the budget did not count:
|
||||
* another process on the card (a desktop, a second server), or a driver allocation made
|
||||
* after the reading. It comes out of the room a kernel's first launch allocates its code
|
||||
* object and scratch from, and running out of that is a fault inside the HIP runtime.
|
||||
*
|
||||
* A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own
|
||||
* workspaces live in there, and naming a number this close to right would be noise. */
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
|
||||
for (auto& r : ranks_) {
|
||||
* THE WARNING IS ON THE ROOM, NOT ON THE FLAG. Raising --gpu-headroom-mib raises what is left
|
||||
* here and what this compares it with by the same amount, so a check of free memory against
|
||||
* the flag can never be satisfied by the flag: the gap is whatever was taken after the
|
||||
* reading, and it is there at every value. The room a first launch has -- what is free less
|
||||
* what the budget kept for later -- is what the flag actually moves, and it is held against
|
||||
* this engine's own allowance for its first launches (the flag's default). A card short of
|
||||
* that is warned with the value that clears it; one that kept the allowance but lost part of
|
||||
* a larger stated headroom says so on its INFO line.
|
||||
*
|
||||
* TOO MUCH means the budget left VRAM on the floor, which on a model whose experts do not
|
||||
* fit is milliseconds of decode step for every unspent GiB. A slack of 256 MiB is tolerated
|
||||
* silently: MiB rounding and a kernel plugin's own workspaces live in there. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
|
||||
const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
LogRank lr(r->index);
|
||||
RadDeviceProps props{};
|
||||
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
|
||||
|
||||
/* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free
|
||||
* here: the step staging is allocated by serve(), and the KV tiers' staging and a second
|
||||
* compute lane are built on first use. A card at exactly the headroom now would be under
|
||||
* it once those exist. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
* compute lane are built on first use. */
|
||||
const int64_t late = late_step_bytes_ + late_lazy_bytes_;
|
||||
const int64_t want = headroom + late;
|
||||
const int64_t got = props.vram_free;
|
||||
const int64_t room = got - late;
|
||||
const std::string asked =
|
||||
late > 0 ? fmt("%s (the %s --gpu-headroom-mib and %s kept for the step staging and "
|
||||
"for what is built on first use)", humanb(want).c_str(),
|
||||
humanb(headroom).c_str(), humanb(late).c_str())
|
||||
: fmt("%s --gpu-headroom-mib", humanb(want).c_str());
|
||||
if (got < want) {
|
||||
/* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code
|
||||
* object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its
|
||||
* first launch by the whole grid. Neither is knowable when the budget is resolved, and
|
||||
* running out for either is a fault inside the HIP runtime rather than an error. */
|
||||
RAD_WARN("card %d settled at %s free against %s. The difference is allocations "
|
||||
"made after the budget was resolved, and it comes out of the room a kernel's "
|
||||
"first launch allocates from. Raise --gpu-headroom-mib by at least %s so the "
|
||||
"budget is resolved against the right number.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).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. */
|
||||
if (cfg_.vram_budget_derived)
|
||||
if (room < allowance) {
|
||||
const int64_t raise_mib = (allowance - room + MiB - 1) / MiB;
|
||||
RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first "
|
||||
"launch to load its code object and size its scratch in -- under the %s this "
|
||||
"engine allows for its own. %s Set --gpu-headroom-mib to at least %lld: what "
|
||||
"is left here rises with it one for one.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(),
|
||||
got < want
|
||||
? fmt("%s of the headroom was taken after the budget read the card, by "
|
||||
"another process on it or an allocation the budget does not "
|
||||
"count.", humanb(want - got).c_str()).c_str()
|
||||
: "",
|
||||
(long long)(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib));
|
||||
} else if (got < want) {
|
||||
RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after "
|
||||
"the budget read the card, by another process on it or an allocation the "
|
||||
"budget does not count, and %s is left for first launches",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
|
||||
humanb(room).c_str());
|
||||
} else if (got > want + 256 * MiB) {
|
||||
/* "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 (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
|
||||
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());
|
||||
@@ -3407,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,
|
||||
|
||||
+392
-36
@@ -148,9 +148,15 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
|
||||
* `size.shortest_edge` means two different things in the two files. Absent is not an error: a
|
||||
* text model has neither. */
|
||||
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
|
||||
/* processor_config.json is the newer single file: one object a sub-processor
|
||||
* (`image_processor`, `video_processor`, `feature_extractor`) beside the processor's own keys
|
||||
* -- EmbeddingGemma 2's image budget and its audio token rate are only there. */
|
||||
static const struct { const char* file; const char* prefix; } kFiles[] = {
|
||||
{ "preprocessor_config.json", "preprocessor" },
|
||||
{ "video_preprocessor_config.json", "video_preprocessor" },
|
||||
{ "processor_config.json", "processor" },
|
||||
/* sentence-transformers' own: an embedding model's named prompts and its default. */
|
||||
{ "config_sentence_transformers.json", "sentence_transformers" },
|
||||
};
|
||||
for (const auto& f : kFiles) {
|
||||
const std::string path = dir + "/" + f.file;
|
||||
@@ -253,20 +259,28 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
|
||||
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
|
||||
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
|
||||
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
|
||||
|
||||
/* The 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; }
|
||||
}
|
||||
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
|
||||
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
|
||||
* be a linear position divide for llama3, longrope or YaRN. */
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
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");
|
||||
@@ -300,7 +314,48 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
m.n_expert_shared= gi("expert_shared_count", 0);
|
||||
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
|
||||
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
|
||||
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
|
||||
* those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
|
||||
* a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
|
||||
* attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
|
||||
* has no spelling for, so a file that sets one to anything but its neutral value is refused
|
||||
* here rather than served as plain YaRN. */
|
||||
{
|
||||
/* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
|
||||
* the older rope.scale_linear, and 0 or 1 is no scaling. */
|
||||
std::string type = "linear";
|
||||
g.get_str(a + ".rope.scaling.type", &type);
|
||||
const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
|
||||
const bool none = type == "none" || (type == "linear" && (factor == 0.0 || factor == 1.0));
|
||||
if (!none) {
|
||||
const struct { const char* key; double neutral; } kOff[] = {
|
||||
{ "rope.scaling.attn_factor", 1.0 }, { "rope.scaling.yarn_attn_factor", 1.0 },
|
||||
{ "rope.scaling.yarn_log_multiplier", 0.0 } };
|
||||
for (const auto& k : kOff)
|
||||
if (gf(k.key, k.neutral) != k.neutral) {
|
||||
RAD_ERR("the GGUF sets %s.%s = %g; that modifier of the rotary's scaling is "
|
||||
"not implemented", a.c_str(), k.key, gf(k.key, k.neutral));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double ext = gf("rope.scaling.yarn_ext_factor", -1.0);
|
||||
if (ext >= 0.0 && ext != 1.0) {
|
||||
RAD_ERR("the GGUF sets %s.rope.scaling.yarn_ext_factor = %g; YaRN is implemented "
|
||||
"at extrapolation factor 1", a.c_str(), ext);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->kv("rope_scaling.type", type);
|
||||
if (factor != 0.0) out->kv("rope_scaling.factor", fmt("%.17g", factor));
|
||||
const int64_t orig = gi("rope.scaling.original_context_length", 0);
|
||||
if (orig > 0) out->kv("rope_scaling.original_max_position_embeddings",
|
||||
fmt("%lld", (long long)orig));
|
||||
for (const char* beta : { "beta_fast", "beta_slow" }) {
|
||||
const double v = gf((std::string("rope.scaling.yarn_") + beta).c_str(), 0.0);
|
||||
if (v != 0.0) out->kv(std::string("rope_scaling.") + beta, fmt("%.17g", v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
@@ -364,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());
|
||||
@@ -379,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));
|
||||
}
|
||||
@@ -387,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;
|
||||
@@ -410,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;
|
||||
@@ -417,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_));
|
||||
@@ -432,10 +503,169 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
fp8_bc_ = c;
|
||||
}
|
||||
}
|
||||
detect_import();
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHICH PUBLISHED QUANTISATION THIS IS, from quantization_config alone: the tensors are checked
|
||||
* one by one when a weight is resolved (import_piece), so a file that says one thing and holds
|
||||
* another is refused at the weight that differs. */
|
||||
void Checkpoint::detect_import() {
|
||||
auto qc = [&](const std::string& k) {
|
||||
const char* v = meta_.get("quantization_config." + k);
|
||||
return v ? std::string(v) : std::string();
|
||||
};
|
||||
auto any_under = [&](const std::string& prefix) {
|
||||
for (const std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config." + prefix, 0) == 0) return true;
|
||||
return false;
|
||||
};
|
||||
const std::string qm = qc("quant_method");
|
||||
if (qm == "auto-round") {
|
||||
/* AutoRound's GPTQ-compatible export; its own `auto_round` packing is another layout. */
|
||||
const std::string pf = qc("packing_format");
|
||||
if (pf == "auto_round:auto_gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "AutoRound's packing_format '" + pf + "' is not one this reads; its "
|
||||
"auto_round:auto_gptq export is";
|
||||
} else if (qm == "gptq") {
|
||||
/* v1, the format auto_gptq writes: the zero point stored less one. gptq_v2 stores it as
|
||||
* it is, and reading it as v1 would shift every code by one. */
|
||||
const std::string cf = qc("checkpoint_format");
|
||||
if (cf.empty() || cf == "gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is";
|
||||
} else if (qm == "quark") {
|
||||
const std::string w = "global_quant_config.weight.";
|
||||
if (qc(w + "dtype") == "fp4" && qc(w + "qscheme") == "per_group" &&
|
||||
qc(w + "group_size") == "32" && qc(w + "scale_format") == "e8m0" &&
|
||||
!any_under("layer_quant_config.") && !any_under("layer_type_quant_config."))
|
||||
import_ = Import::QuarkMx;
|
||||
else
|
||||
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
|
||||
"throughout, which is the one this reads";
|
||||
}
|
||||
/* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
|
||||
* the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
|
||||
* imported checkpoint's says how a tool made it instead: every weight states its own
|
||||
* encoding. Renamed, it still travels into the container as provenance. */
|
||||
if (import_ != Import::None)
|
||||
for (std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config.", 0) == 0) k = "imported_" + k;
|
||||
}
|
||||
|
||||
int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
const SrcTensor** scale, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string m) {
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (import_ == Import::None) return RAD_E_NOTFOUND;
|
||||
if (auto hit = imported_.find(name); hit != imported_.end()) {
|
||||
*codes = hit->second.first;
|
||||
*scale = hit->second.second;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::QuarkMx) {
|
||||
/* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low
|
||||
* nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the
|
||||
* dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */
|
||||
const SrcTensor* w = find(name);
|
||||
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
|
||||
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
|
||||
if (e->rad_dtype != RAD_U8 || w->shape.size() != 2 || e->shape.size() != 2 ||
|
||||
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] exponent plane of '" +
|
||||
w->name + "'");
|
||||
SrcTensor c = *w;
|
||||
c.rad_dtype = RAD_FP4E2M1;
|
||||
c.shape = { w->shape[0], w->shape[1] * 2 };
|
||||
SrcTensor x = *e;
|
||||
x.rad_dtype = RAD_E8M0;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
sliced_.push_back(std::move(x));
|
||||
*scale = &sliced_.back();
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
|
||||
* X.g_idx. The width is read off the tensors rather than quantization_config, because a
|
||||
* release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
|
||||
const std::string suffix = ".weight";
|
||||
if (name.size() <= suffix.size() ||
|
||||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
|
||||
return RAD_E_NOTFOUND;
|
||||
const std::string base = name.substr(0, name.size() - suffix.size());
|
||||
const SrcTensor* qw = find(base + ".qweight");
|
||||
if (!qw) return RAD_E_NOTFOUND;
|
||||
const SrcTensor* sc = find(base + ".scales");
|
||||
const SrcTensor* qz = find(base + ".qzeros");
|
||||
const SrcTensor* gi = find(base + ".g_idx");
|
||||
const std::string what = "'" + qw->name + "'";
|
||||
if (qw->rad_dtype != RAD_I32 || qw->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " is not an int32 [K*bits/32, N] matrix");
|
||||
if (!sc || sc->shape.size() != 2 ||
|
||||
(sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32))
|
||||
return refuse(RAD_E_FORMAT, what + " has no float [groups, N] '" + base + ".scales' beside it");
|
||||
if (!qz || qz->rad_dtype != RAD_I32 || qz->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " has no int32 '" + base + ".qzeros' beside it");
|
||||
const int64_t N = qw->shape[1];
|
||||
const int64_t bits = N > 0 && (qz->shape[1] * 32) % N == 0 ? qz->shape[1] * 32 / N : 0;
|
||||
if (bits != 4 && bits != 8)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " packs " + std::to_string(bits) + "-bit codes "
|
||||
"(from its qzeros' width); 4 and 8 are read");
|
||||
const int64_t K = qw->shape[0] * 32 / bits;
|
||||
const int64_t G = sc->shape[0];
|
||||
if (sc->shape[1] != N || G <= 0 || K % G)
|
||||
return refuse(RAD_E_SHAPE, "'" + sc->name + "' is not a [groups, " + std::to_string(N) +
|
||||
"] scale tensor for " + std::to_string(K) + " columns");
|
||||
const int64_t group = K / G;
|
||||
/* THE SERVED SCALE COVERS 128 OF K, so a group of 128 is one scale each and a wider one --
|
||||
* per channel included -- repeats; a narrower group has no form the kernels read. */
|
||||
if (K % 128 || group % 128)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " has groups of " + std::to_string(group) +
|
||||
" columns; the imported form scales a 128 of K, so the "
|
||||
"group must be a multiple of 128");
|
||||
if (qz->shape[0] != G)
|
||||
return refuse(RAD_E_SHAPE, "'" + qz->name + "' has " + std::to_string(qz->shape[0]) +
|
||||
" rows for " + std::to_string(G) + " groups");
|
||||
/* SYMMETRIC, OR NOT READ: every zero point the v1 2^(bits-1) - 1, which is what makes a code
|
||||
* the signed value it offsets to. An asymmetric weight would need a zero plane. */
|
||||
const uint32_t zero = bits == 4 ? 0x77777777u : 0x7f7f7f7fu;
|
||||
for (int64_t i = 0; i < qz->numel(); ++i) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)qz->data + i * 4, 4);
|
||||
if (v != zero)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + qz->name + "' holds a zero point other than "
|
||||
"the symmetric one; an asymmetric weight is not read");
|
||||
}
|
||||
/* AND IN ORDER: act-order (desc_act) permutes the columns' groups, which a [1x128] scale
|
||||
* cannot follow. The identity, or none, is the only g_idx read. */
|
||||
if (gi) {
|
||||
if (gi->rad_dtype != RAD_I32 || gi->numel() != K)
|
||||
return refuse(RAD_E_FORMAT, "'" + gi->name + "' is not an int32 [K] group index");
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
int32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)gi->data + k * 4, 4);
|
||||
if (v != k / group)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + gi->name + "' reorders the columns' groups "
|
||||
"(act-order); only an in-order index is read");
|
||||
}
|
||||
}
|
||||
SrcTensor c = *qw;
|
||||
c.rad_dtype = bits == 4 ? RAD_I4 : RAD_I8;
|
||||
c.shape = { N, K };
|
||||
c.gptq_bits = (int32_t)bits;
|
||||
c.gptq_group = group;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
*scale = sc;
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::open(const std::string& path) {
|
||||
path_ = path;
|
||||
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
|
||||
@@ -460,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;
|
||||
}
|
||||
@@ -577,6 +808,22 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
for (const Src1& s1 : srcs) {
|
||||
const SrcTensor* st = ck.find(s1.name);
|
||||
const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
|
||||
/* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */
|
||||
{
|
||||
const SrcTensor *ic = nullptr, *is = nullptr;
|
||||
std::string iw;
|
||||
const int ir = ck.import_piece(s1.name, &ic, &is, &iw);
|
||||
if (ir == RAD_OK) {
|
||||
if (s1.index >= 0)
|
||||
return refuse(RAD_E_UNSUPPORTED, "it is a slice of '" + std::string(s1.name) +
|
||||
"', which the checkpoint ships quantised; an "
|
||||
"imported tensor is read whole");
|
||||
st = ic;
|
||||
sc = is;
|
||||
} else if (ir != RAD_E_NOTFOUND) {
|
||||
return refuse(ir, iw);
|
||||
}
|
||||
}
|
||||
/* A SUB-TENSOR INDEX IS TAKEN, never ignored: ignoring it gives every expert a copy of
|
||||
* the whole stack, in a model that loads and answers. Its scale plane is stacked the same
|
||||
* way and sliced at the same index. */
|
||||
@@ -604,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);
|
||||
|
||||
@@ -636,6 +890,40 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
|
||||
} else if (!same) {
|
||||
out->why = "its pieces are stored in different dtypes";
|
||||
} else if (p0.gptq_bits) {
|
||||
/* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows --
|
||||
* a column join would put two pieces' groups in one scale block. */
|
||||
out->imported = true;
|
||||
for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
|
||||
if (out->pieces[k]->gptq_bits != p0.gptq_bits ||
|
||||
out->pieces[k]->gptq_group != p0.gptq_group) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces differ in width or group";
|
||||
}
|
||||
if (out->imported && d != 0 && out->pieces.size() > 1) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces are joined along a column, across their groups";
|
||||
}
|
||||
if (out->imported) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_BF16, 1, 128);
|
||||
out->why = "it is GPTQ-packed int" + std::to_string(p0.gptq_bits) + ", which "
|
||||
"rad-convert imports with its scales rounded to bf16 -- serve the "
|
||||
"container it writes";
|
||||
}
|
||||
} else if (dt == RAD_FP4E2M1 && scaled) {
|
||||
/* QUARK'S MXFP4, byte for byte: the codes and exponents are the planes of
|
||||
* `fp4_e2m1*e8m0[1x32]`. Joined only along rows, which is how gate and up become one. */
|
||||
out->trivial = d == 0 || out->pieces.size() == 1;
|
||||
if (!out->trivial) out->why = "its MXFP4 pieces are joined along a column";
|
||||
if (out->trivial) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
|
||||
}
|
||||
} else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
|
||||
/* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
|
||||
* `fp8_e4m3*bf16[128x128]` (whatever the scale's own dtype). Joined only along rows, and
|
||||
@@ -785,6 +1073,21 @@ struct Joined {
|
||||
|
||||
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
|
||||
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
if (t.gptq_bits) {
|
||||
/* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
|
||||
* of word [k / (32/bits), row], less its zero point */
|
||||
const int64_t N = t.shape[0], K = t.shape[1];
|
||||
const int64_t per = 32 / t.gptq_bits;
|
||||
const uint32_t mask = (1u << t.gptq_bits) - 1u;
|
||||
const int zp = 1 << (t.gptq_bits - 1);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t row = (e + i) / K, k = (e + i) % K;
|
||||
uint32_t w;
|
||||
std::memcpy(&w, (const uint8_t*)t.data + ((k / per) * N + row) * 4, 4);
|
||||
out[i] = (float)((int)((w >> ((k % per) * t.gptq_bits)) & mask) - zp);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t.rad_dtype == RAD_DT_INVALID) {
|
||||
/* a GGUF block type: whole rows only, and a row is whole blocks */
|
||||
const int64_t cols = t.shape.back();
|
||||
@@ -807,7 +1110,7 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2: case RAD_FP4E2M1:
|
||||
case RAD_I8: case RAD_U8: case RAD_I16: case RAD_I32: case RAD_U32: case RAD_U16:
|
||||
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(p, t.rad_dtype, e + i);
|
||||
return RAD_OK;
|
||||
@@ -841,8 +1144,25 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
|
||||
: "?")
|
||||
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
|
||||
")");
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE: the pieces are joined along rows, so logical row
|
||||
* r is in the piece whose rows cover it, and its scales are that piece's. */
|
||||
/* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is
|
||||
* [groups, N], so row r's scales are a column of it. */
|
||||
if (w.imported) {
|
||||
int64_t base = 0;
|
||||
for (size_t k = 0; k < w.pieces.size(); ++k) {
|
||||
const SrcTensor& pk = *w.pieces[k];
|
||||
const SrcTensor& sk = *w.scales[k];
|
||||
const int64_t pr = pk.shape[0];
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
|
||||
for (int64_t c = 0; c < w.cols; ++c)
|
||||
out[(r - r0) * w.cols + c] *=
|
||||
rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base));
|
||||
base += pr;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE (and MXFP4 its code times its exponent): the pieces
|
||||
* are joined along rows, so logical row r is in the piece whose rows cover it, and its scales
|
||||
* are that piece's. */
|
||||
if (!w.scales.empty() && w.scales[0]) {
|
||||
const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
|
||||
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
|
||||
@@ -869,8 +1189,8 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (!w.trivial || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial encoding");
|
||||
if (!(w.trivial || w.imported) || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial or imported encoding");
|
||||
const std::vector<const SrcTensor*>& src = k == 0 ? w.pieces : w.scales;
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
|
||||
@@ -878,14 +1198,50 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
const uint32_t dt = w.enc.plane[k].dtype;
|
||||
const int64_t eb = rad_dtype_bits(dt) / 8;
|
||||
uint8_t* o = (uint8_t*)dst;
|
||||
if (w.imported) {
|
||||
/* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in
|
||||
* order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each
|
||||
* offset to signed by flipping the top bit of every field; a row of scales is a column of
|
||||
* the scale tensor, one a 128 of K, rounded to bf16. */
|
||||
int64_t base = 0;
|
||||
for (size_t p = 0; p < w.pieces.size(); ++p) {
|
||||
const SrcTensor& c = *w.pieces[p];
|
||||
const SrcTensor& s = *w.scales[p];
|
||||
const int64_t N = c.shape[0], K = c.shape[1];
|
||||
const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80;
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
|
||||
const int64_t n = r - base;
|
||||
if (k == 0) {
|
||||
const uint8_t* q = (const uint8_t*)c.data;
|
||||
for (int64_t wi = 0; wi < K * c.gptq_bits / 32; ++wi) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, q + (wi * N + n) * 4, 4);
|
||||
for (int b = 0; b < 4; ++b) *o++ = (uint8_t)(v >> (8 * b)) ^ flip;
|
||||
}
|
||||
} else {
|
||||
for (int64_t g = 0; g < K / 128; ++g) {
|
||||
const uint16_t h = rad_f32_to_bf16(
|
||||
rad_load_f32(s.data, s.rad_dtype, ((g * 128) / c.gptq_group) * N + n));
|
||||
std::memcpy(o, &h, 2);
|
||||
o += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
base += N;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == 0) {
|
||||
/* the codes: the pieces joined, bytes as they are */
|
||||
/* the codes: the pieces joined, bytes as they are. A sub-byte code (MXFP4) joins along
|
||||
* rows of even width, so every run starts and ends on a byte. */
|
||||
const int64_t bits = rad_dtype_bits(dt);
|
||||
Joined j;
|
||||
j.init(src, w.concat_dim);
|
||||
return j.walk(r0 * pc, (r0 + nr) * pc, [&](int p, int64_t e, int64_t n) {
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * eb, (size_t)(n * eb));
|
||||
o += n * eb;
|
||||
return RAD_OK;
|
||||
if ((e * bits) % 8 || (n * bits) % 8) return (int)RAD_E_SHAPE;
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * bits / 8, (size_t)(n * bits / 8));
|
||||
o += n * bits / 8;
|
||||
return (int)RAD_OK;
|
||||
});
|
||||
}
|
||||
/* an FP8 scale plane: the pieces' scale rows one after another */
|
||||
|
||||
@@ -10,9 +10,16 @@
|
||||
* resolves it to -- concatenations, alternatives and expert slices included -- with the
|
||||
* encoding they already are when that encoding is trivial, and the rows of it on demand.
|
||||
*
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), and block-scaled
|
||||
* FP8, where `X.weight_scale_inv` is the scale plane of `X.weight`. Anything else is a weight
|
||||
* whose served form needs quantisation work, which a recipe does ahead of time.
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
|
||||
* where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
|
||||
* (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
|
||||
* byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
|
||||
* ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
|
||||
* shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
|
||||
*
|
||||
* AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
|
||||
* (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
|
||||
* architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -42,6 +49,13 @@ struct SrcTensor {
|
||||
std::vector<int64_t> shape; /* row-major */
|
||||
const void* data = nullptr;
|
||||
int64_t bytes = 0;
|
||||
/* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
|
||||
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
|
||||
* K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
|
||||
* describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
|
||||
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
|
||||
int32_t gptq_bits = 0;
|
||||
int64_t gptq_group = 0;
|
||||
|
||||
int64_t numel() const {
|
||||
int64_t n = 1;
|
||||
@@ -70,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);
|
||||
@@ -109,10 +125,32 @@ public:
|
||||
int64_t fp8_block_rows() const { return fp8_br_; }
|
||||
int64_t fp8_block_cols() const { return fp8_bc_; }
|
||||
|
||||
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
|
||||
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
|
||||
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
|
||||
* scales, no per-layer overrides) is QuarkMx. A quantisation of one of those tools in a form
|
||||
* this does not read stays None, with the reason in import_refusal(). */
|
||||
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
|
||||
* describe the tool, not a served format, and a plugin reads the latter there. */
|
||||
enum class Import { None, Gptq, QuarkMx };
|
||||
Import imports() const { return import_; }
|
||||
const std::string& import_refusal() const { return import_why_; }
|
||||
|
||||
/* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
|
||||
* the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
|
||||
* dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
|
||||
* all; another error, with `why`, when it ships an imported form this cannot read. */
|
||||
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
|
||||
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();
|
||||
|
||||
enum Kind { None, Gguf, SafeT } kind_ = None;
|
||||
std::string path_, dir_;
|
||||
@@ -121,8 +159,13 @@ 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;
|
||||
std::string import_why_;
|
||||
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
|
||||
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
|
||||
};
|
||||
|
||||
/* ================================================================== logical weights */
|
||||
@@ -138,6 +181,11 @@ struct CkptWeight {
|
||||
int64_t rows = 0, cols = 0; /* its [rows, cols] view (rad_enc_view) */
|
||||
/* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
|
||||
bool trivial = false;
|
||||
/* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
|
||||
* ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
|
||||
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
|
||||
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
|
||||
bool imported = false;
|
||||
RadEncoding enc{};
|
||||
std::string why;
|
||||
};
|
||||
@@ -161,8 +209,8 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>&
|
||||
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
|
||||
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
|
||||
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL `w`, in the plane's own elements, dense into
|
||||
* `dst`: the bytes a container entry holds for it. */
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
|
||||
* into `dst`: the bytes a container entry holds for it. */
|
||||
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
|
||||
std::string* why);
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
/* --rope-scaling, over a container's free-form metadata.
|
||||
*
|
||||
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
|
||||
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
|
||||
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
|
||||
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
|
||||
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
|
||||
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
|
||||
* it would a converted container, so there is one reader and one set of checks.
|
||||
*
|
||||
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
|
||||
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
|
||||
* sit behind that and never be read.
|
||||
*
|
||||
* Pure functions over two parallel string vectors, so they are tested without an engine
|
||||
* (tests/yarn_test.cpp holds them to yarn_from). */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct RopeSpec {
|
||||
enum Kind { Keep, None, Yarn } kind = Keep;
|
||||
double factor = 0.0;
|
||||
int64_t orig = 0; /* 0: the container's own trained length */
|
||||
};
|
||||
|
||||
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
|
||||
* else, so a typo is refused where it was typed. */
|
||||
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
|
||||
RopeSpec r;
|
||||
if (!s || !*s) { *out = r; return true; }
|
||||
if (!std::strcmp(s, "none")) { r.kind = RopeSpec::None; *out = r; return true; }
|
||||
if (std::strncmp(s, "yarn:", 5)) return false;
|
||||
char* e = nullptr;
|
||||
r.factor = std::strtod(s + 5, &e);
|
||||
if (e == s + 5 || !(r.factor > 1.0) || r.factor > 1e6) return false;
|
||||
if (*e == ':') {
|
||||
char* e2 = nullptr;
|
||||
const long long o = std::strtoll(e + 1, &e2, 10);
|
||||
if (e2 == e + 1 || *e2 || o <= 0) return false;
|
||||
r.orig = o;
|
||||
} else if (*e) {
|
||||
return false;
|
||||
}
|
||||
r.kind = RopeSpec::Yarn;
|
||||
*out = r;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RopeKeys {
|
||||
std::vector<std::string>& k;
|
||||
std::vector<std::string>& v;
|
||||
|
||||
int find(const std::string& key) const {
|
||||
for (size_t i = 0; i < k.size(); ++i)
|
||||
if (k[i] == key) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
const std::string* get(const std::string& key) const {
|
||||
const int i = find(key);
|
||||
return i < 0 ? nullptr : &v[(size_t)i];
|
||||
}
|
||||
void set(const std::string& key, const std::string& val) {
|
||||
const int i = find(key);
|
||||
if (i >= 0) { v[(size_t)i] = val; return; }
|
||||
k.push_back(key);
|
||||
v.push_back(val);
|
||||
}
|
||||
void erase(const std::string& key) {
|
||||
const int i = find(key);
|
||||
if (i < 0) return;
|
||||
k.erase(k.begin() + i);
|
||||
v.erase(v.begin() + i);
|
||||
}
|
||||
bool any_prefix(const char* pre) const {
|
||||
const size_t n = std::strlen(pre);
|
||||
for (const auto& s : k)
|
||||
if (!s.compare(0, n, pre)) return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/* The reader's order -- yarn_from's, kept in step with it. */
|
||||
inline std::vector<std::string> rope_homes(const char* group) {
|
||||
if (!*group)
|
||||
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
|
||||
"rope_scaling." };
|
||||
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
|
||||
}
|
||||
|
||||
/* The object the reader takes and the key that names its type, or empty strings when no object
|
||||
* names one (the model's rotary is then the default). */
|
||||
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
|
||||
std::string* type_key) {
|
||||
home->clear();
|
||||
type_key->clear();
|
||||
for (const auto& h : rope_homes(group))
|
||||
for (const char* t : { "rope_type", "type" })
|
||||
if (kv.get(h + t)) { *home = h; *type_key = h + t; return; }
|
||||
}
|
||||
|
||||
struct RopeResolved {
|
||||
std::string type; /* "" when nothing names one */
|
||||
double factor = 1.0;
|
||||
double orig = 0.0;
|
||||
};
|
||||
|
||||
inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const char* group) {
|
||||
RopeKeys kv{ k, v };
|
||||
RopeResolved r;
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
if (home.empty()) return r;
|
||||
r.type = *kv.get(tk);
|
||||
if (const std::string* f = kv.get(home + "factor")) r.factor = std::strtod(f->c_str(), nullptr);
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
r.orig = std::strtod(o->c_str(), nullptr);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
|
||||
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
|
||||
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
|
||||
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const RopeSpec& spec, const char* group, int64_t trained,
|
||||
std::string* why) {
|
||||
if (spec.kind == RopeSpec::Keep) return true;
|
||||
RopeKeys kv{ k, v };
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
const std::string type = home.empty() ? std::string() : *kv.get(tk);
|
||||
if (spec.kind == RopeSpec::None) {
|
||||
if (type == "yarn") kv.set(tk, "default");
|
||||
return true;
|
||||
}
|
||||
/* `mrope` is the legacy Qwen2-VL spelling of default with sections. */
|
||||
if (!type.empty() && type != "default" && type != "mrope" && type != "yarn") {
|
||||
*why = "the " + std::string(*group ? "drafter's" : "model's") + " rotary is '" + type +
|
||||
"' (" + tk + "); YaRN over it is not --rope-scaling's to decide";
|
||||
return false;
|
||||
}
|
||||
if (home.empty()) {
|
||||
home = *group ? std::string(group) + "rope_parameters."
|
||||
: kv.any_prefix("text_config.") ? "text_config.rope_parameters."
|
||||
: "rope_parameters.";
|
||||
tk = home + "rope_type";
|
||||
}
|
||||
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
|
||||
* tied to its old factor goes, so the reader derives it for the new one. */
|
||||
int64_t orig = spec.orig;
|
||||
if (!orig && type == "yarn")
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
orig = std::atoll(o->c_str());
|
||||
if (!orig) orig = trained;
|
||||
if (orig <= 0) {
|
||||
*why = "no trained length to scale from; give one: yarn:FACTOR:ORIG";
|
||||
return false;
|
||||
}
|
||||
char buf[64];
|
||||
kv.set(tk, "yarn");
|
||||
std::snprintf(buf, sizeof buf, "%.17g", spec.factor);
|
||||
kv.set(home + "factor", buf);
|
||||
std::snprintf(buf, sizeof buf, "%lld", (long long)orig);
|
||||
kv.set(home + "original_max_position_embeddings", buf);
|
||||
for (const char* stale : { "attention_factor", "mscale", "mscale_all_dim" })
|
||||
kv.erase(home + stale);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
|
||||
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
|
||||
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
|
||||
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
|
||||
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
|
||||
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
|
||||
* angles. Key order and unrelated keys do not change it. */
|
||||
inline std::string rope_identity(const std::vector<std::string>& k,
|
||||
const std::vector<std::string>& v) {
|
||||
auto names_rotary = [](const std::string& key) {
|
||||
size_t s = 0;
|
||||
while (s <= key.size()) {
|
||||
size_t e = key.find('.', s);
|
||||
if (e == std::string::npos) e = key.size();
|
||||
const std::string part = key.substr(s, e - s);
|
||||
if (part.find("rope") != std::string::npos || part.find("rotary") != std::string::npos)
|
||||
return true;
|
||||
s = e + 1;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
std::vector<std::string> rows;
|
||||
for (size_t i = 0; i < k.size() && i < v.size(); ++i)
|
||||
if (names_rotary(k[i])) rows.push_back(k[i] + "=" + v[i]);
|
||||
std::sort(rows.begin(), rows.end());
|
||||
std::string out;
|
||||
for (const auto& r : rows) { out += r; out += ';'; }
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -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();
|
||||
|
||||
+74
-17
@@ -395,6 +395,27 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
if (max_mib <= 0) return -1;
|
||||
const auto reaches = [&](int64_t mib) {
|
||||
/* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
|
||||
* whose only paged group is zero still has to hold them. */
|
||||
if (mib * MiB < fixed_) return false;
|
||||
const int64_t t = paged_split(mib * MiB, nullptr);
|
||||
return t == kUnboundedTokens || t >= tokens;
|
||||
};
|
||||
if (!reaches(max_mib)) return -1;
|
||||
/* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
|
||||
int64_t lo = 0, hi = max_mib;
|
||||
if (reaches(lo)) return 0;
|
||||
while (hi - lo > 1) {
|
||||
const int64_t mid = lo + (hi - lo) / 2;
|
||||
if (reaches(mid)) hi = mid; else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
@@ -403,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();
|
||||
@@ -413,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;
|
||||
@@ -438,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;
|
||||
@@ -1338,6 +1359,10 @@ void KVManager::free_checkpoint(int32_t slot) {
|
||||
if (ck_store_) ck_store_->free(slot);
|
||||
}
|
||||
|
||||
bool KVManager::checkpoint_held(int32_t slot) const {
|
||||
return ck_store_ && ck_store_->in_use(slot);
|
||||
}
|
||||
|
||||
void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
if (!ck_store_) return nullptr;
|
||||
char* p = (char*)ck_store_->at(slot);
|
||||
@@ -1351,11 +1376,29 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
|
||||
bool save, RadStream s) {
|
||||
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
|
||||
* shared store rather than a list of its own. */
|
||||
if (!ck_store_ || !ck_store_->in_use(ck_slot)) return RAD_E_INVAL;
|
||||
* shared store rather than a list of its own. Each refusal says which check it is: a slot the
|
||||
* store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
|
||||
const char* dir = save ? "save into" : "restore from";
|
||||
if (!ck_store_) {
|
||||
RAD_ERR("checkpoint %s slot %d: this rank has no snapshot store", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!ck_store_->in_use(ck_slot)) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store does not hold that slot (%lld of %lld in use) -- "
|
||||
"it was given back after its id was handed out", dir, (int)ck_slot,
|
||||
(long long)ck_store_->used_slots(), (long long)ck_store_->capacity());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
char* ck = (char*)checkpoint_ptr(ck_slot);
|
||||
if (!ck) return RAD_E_INVAL;
|
||||
if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL;
|
||||
if (!ck) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store has no address for it", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!state_slots || n_slots < (int)plans_.size()) {
|
||||
RAD_ERR("checkpoint %s slot %d: %d state slot(s) named for %d group(s)", dir, (int)ck_slot,
|
||||
state_slots ? n_slots : 0, (int)plans_.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one
|
||||
* layer_stride apart in the pool and packed end to end in the slot, so a group's whole share
|
||||
@@ -1365,20 +1408,34 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.stateful()) continue;
|
||||
const int32_t slot = state_slots[g];
|
||||
if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */
|
||||
if (slot < 0) { /* no state to save, or none to restore into */
|
||||
RAD_ERR("checkpoint %s slot %d: the sequence holds no state slot in group %d", dir,
|
||||
(int)ck_slot, (int)g);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t nbytes = p.layer_bytes_per_state();
|
||||
void* st = state_ptr((int32_t)g, 0, slot);
|
||||
if (!st || p.n_layers <= 0) return RAD_E_STATE;
|
||||
if (!st || p.n_layers <= 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: group %d has no address for state slot %d", dir,
|
||||
(int)ck_slot, (int)g, (int)slot);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (off + nbytes * p.n_layers > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state "
|
||||
"needs more than that; the store was sized from the same plans, so the two "
|
||||
"have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s));
|
||||
const int cs = save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s);
|
||||
if (cs < 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: the device refused the copy of group %d (%lld rows of "
|
||||
"%lld bytes): %s", dir, (int)ck_slot, (int)g, (long long)p.n_layers,
|
||||
(long long)nbytes, rad_strerror(cs));
|
||||
return cs;
|
||||
}
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
return RAD_OK;
|
||||
|
||||
+10
-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;
|
||||
@@ -182,6 +182,11 @@ public:
|
||||
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
|
||||
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
|
||||
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
|
||||
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
|
||||
@@ -435,6 +440,8 @@ public:
|
||||
int alloc_checkpoint(int32_t* slot_out);
|
||||
void free_checkpoint(int32_t slot);
|
||||
void* checkpoint_ptr(int32_t slot) const;
|
||||
/* The store holds `slot`: it was allocated and not given back since. */
|
||||
bool checkpoint_held(int32_t slot) const;
|
||||
|
||||
/* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal
|
||||
* on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the
|
||||
|
||||
+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
|
||||
|
||||
+12
-3
@@ -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
|
||||
@@ -740,6 +740,9 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
int64_t freed = 0;
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
/* NOR ONE HANDED OUT THIS STEP, whatever the policy says of its position: the admission it
|
||||
* was handed to restores from the slot ahead of the step, and that is after this runs. */
|
||||
if (handed(a.second)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
/* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about
|
||||
@@ -793,6 +796,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of
|
||||
* the step. This chunk goes without a checkpoint, which costs a later hit some replay. */
|
||||
if (handed(prefix)) return RAD_E_FULL;
|
||||
const uint64_t vs = existing->second.session;
|
||||
retire_ckpt(existing);
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
@@ -841,6 +847,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
/* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write
|
||||
* reports, so retiring it now loses the snapshot and frees nothing yet. */
|
||||
if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue;
|
||||
/* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
* ahead of the step, and a slot freed under it restores nothing. */
|
||||
if (handed(kvp.first)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
@@ -969,7 +978,7 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.detached || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue;
|
||||
if (handed(kvp.first)) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
victim = &c;
|
||||
}
|
||||
|
||||
+14
-4
@@ -54,6 +54,7 @@
|
||||
#include "mem/kv.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
@@ -205,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
|
||||
@@ -325,7 +327,9 @@ public:
|
||||
size_t resident_prefix(const std::vector<BlockHash>& chain) const;
|
||||
void release(uint64_t req);
|
||||
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
|
||||
* by its forward, which committed before this step was planned. */
|
||||
* by its forward, which committed before this step was planned. Until then a handed snapshot
|
||||
* keeps its slot through every path that would give one up: retention, the eviction in
|
||||
* reserve_checkpoint, and free_checkpoint_for_restore. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to
|
||||
* forget. Erase the index entry and give back the slot, if it still has one. */
|
||||
@@ -339,7 +343,10 @@ public:
|
||||
bool is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; }
|
||||
|
||||
/* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot
|
||||
* pool is exhausted, never evicting a session tip. RAD_E_FULL when even that is not enough. */
|
||||
* pool is exhausted, then evicts the least recently used snapshot, a session's tip last. A
|
||||
* snapshot a lookup handed out this step is never given up: the admission it was handed to
|
||||
* restores from the slot ahead of the step, after this reservation was made. RAD_E_FULL when
|
||||
* nothing else can be given up. */
|
||||
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out);
|
||||
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
|
||||
@@ -435,8 +442,11 @@ private:
|
||||
bool released_ = false;
|
||||
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
|
||||
/* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */
|
||||
/* Snapshots lookup handed out since begin_step: kept in their slots until then (begin_step). */
|
||||
mutable std::vector<BlockHash> handed_;
|
||||
bool handed(const BlockHash& h) const {
|
||||
return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
|
||||
}
|
||||
mutable uint64_t clock_ = 0;
|
||||
std::unique_ptr<CheckpointPolicy> policy_;
|
||||
mutable Stats stats_;
|
||||
|
||||
+67
-70
@@ -47,10 +47,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
|
||||
* of one deployment normally hold the same shard shapes and the same program, so these folds
|
||||
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
|
||||
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
@@ -81,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;
|
||||
}
|
||||
@@ -97,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(
|
||||
@@ -119,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), "
|
||||
@@ -127,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;
|
||||
@@ -197,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 ---------------------------------
|
||||
*
|
||||
@@ -226,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. */
|
||||
@@ -262,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 "
|
||||
@@ -275,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
|
||||
@@ -319,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 "
|
||||
@@ -374,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;
|
||||
@@ -393,4 +371,23 @@ int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank,
|
||||
return resolve(c, per_rank, out, false);
|
||||
}
|
||||
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes) {
|
||||
RankSplit s;
|
||||
s.weights_mib = common_weights_mib;
|
||||
s.kv_mib = common_kv_mib;
|
||||
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
|
||||
const int64_t saved = common_kv_mib - need_kv_mib;
|
||||
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
|
||||
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
|
||||
* rather than allocated empty. */
|
||||
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
|
||||
const int64_t grown = std::min(common_weights_mib + saved, cap);
|
||||
s.kv_mib = need_kv_mib;
|
||||
s.weights_mib = grown;
|
||||
s.unusable_mib = saved - (grown - common_weights_mib);
|
||||
s.resplit = true;
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+32
-8
@@ -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,12 +128,12 @@ 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 */
|
||||
};
|
||||
|
||||
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree.
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
|
||||
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
|
||||
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
|
||||
* fit on every card it is applied to.
|
||||
*
|
||||
@@ -137,4 +145,20 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
|
||||
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
|
||||
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
|
||||
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
|
||||
* every one of its weights would take resident (statics + all experts + their spare slots), this
|
||||
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
|
||||
* unclaimed. Nothing changes when the need is not below the common pool. */
|
||||
struct RankSplit {
|
||||
int64_t weights_mib = 0;
|
||||
int64_t kv_mib = 0;
|
||||
int64_t unusable_mib = 0; /* saved from the KV pool but past the weights cap: never allocated */
|
||||
bool resplit = false;
|
||||
};
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -7,6 +7,18 @@ namespace rad {
|
||||
namespace mm {
|
||||
|
||||
void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
/* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real
|
||||
* frames and its staged ones. */
|
||||
if (kind == Kind::Audio) {
|
||||
for (int64_t k = 0; k < count; ++k) {
|
||||
const int64_t f = first + k;
|
||||
planes[k] = (int32_t)f;
|
||||
planes[count + k] = f < valid ? 1 : 0;
|
||||
planes[2 * count + k] = valid;
|
||||
planes[3 * count + k] = grid_h;
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* Merge-block order inverted: a patch's index within its segment is
|
||||
* ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */
|
||||
const int64_t seg = (int64_t)grid_h * grid_w;
|
||||
|
||||
+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
|
||||
|
||||
+33
-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;
|
||||
}
|
||||
@@ -113,8 +113,17 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
if (p.vram_budget == pool_bytes) return RAD_OK;
|
||||
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
|
||||
"pool holds %s (%lld bytes): the planner and the pool were given different splits",
|
||||
p.rank, humanb(p.vram_budget).c_str(), (long long)p.vram_budget,
|
||||
humanb(pool_bytes).c_str(), (long long)pool_bytes);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
TablePlacement ngram, bool host_backend, bool container) {
|
||||
if (!out) return;
|
||||
*out = WeightFootprint{};
|
||||
|
||||
@@ -137,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;
|
||||
|
||||
@@ -166,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) {
|
||||
@@ -177,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;
|
||||
@@ -275,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
|
||||
@@ -286,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. */
|
||||
@@ -610,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;
|
||||
@@ -759,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
|
||||
@@ -891,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;
|
||||
@@ -1110,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
|
||||
@@ -1234,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;
|
||||
}
|
||||
|
||||
+30
-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
|
||||
@@ -416,6 +433,13 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
|
||||
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
|
||||
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
|
||||
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
|
||||
* the rank and both sizes, when they differ. */
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
|
||||
+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_;
|
||||
|
||||
|
||||
+114
-20
@@ -122,13 +122,35 @@ 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).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; each step's head depth and each sequence's stop follow the
|
||||
* measured acceptance and the measured step cost. A serial drafter's policy only.
|
||||
* The default is kDraftWindowDefault, and the help text and the startup line read it from there.
|
||||
*
|
||||
* FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
|
||||
* two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
|
||||
*
|
||||
* concurrent sequences 1 2 4 8
|
||||
* adaptive, ceiling 3 +0.4% -0.1% +1.7% -0.3%
|
||||
* adaptive, ceiling 5 +7.1% -2.3% +7.4% -11.9%
|
||||
*
|
||||
* At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
|
||||
* 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
|
||||
* not yet timed at a load is priced on the prior. */
|
||||
enum class DraftWindow { Fixed = 0, Adaptive = 1 };
|
||||
constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
|
||||
inline const char* draft_window_name(DraftWindow w) {
|
||||
return w == DraftWindow::Adaptive ? "adaptive" : "fixed";
|
||||
}
|
||||
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
|
||||
|
||||
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
|
||||
@@ -325,6 +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
|
||||
@@ -338,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
|
||||
@@ -378,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
|
||||
@@ -455,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 */
|
||||
@@ -471,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 "" */
|
||||
@@ -577,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 */
|
||||
};
|
||||
@@ -587,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 */
|
||||
|
||||
@@ -623,9 +698,13 @@ struct Config {
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
int64_t max_seqs = 256;
|
||||
int64_t max_ctx = 0; /* 0 = the model's training context */
|
||||
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
|
||||
* model card's extension past its trained context, no reconvert); "none" takes a checkpoint's
|
||||
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
|
||||
std::string rope_scaling;
|
||||
|
||||
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
|
||||
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
|
||||
/* 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
|
||||
@@ -634,9 +713,12 @@ struct Config {
|
||||
* what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
|
||||
* that sum and writes the answer back into the two fields below, so every consumer downstream
|
||||
* -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
|
||||
* second place for them to disagree.
|
||||
* second place for them to disagree. Engine::plan derives each rank's own copy from it
|
||||
* (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
|
||||
* still one number per card, and the same number on every card whose cache costs as much per
|
||||
* token as the dearest rank's.
|
||||
*
|
||||
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
|
||||
* 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 */
|
||||
@@ -649,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
|
||||
@@ -665,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.
|
||||
@@ -721,8 +806,8 @@ struct Config {
|
||||
* code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
|
||||
* faults inside the HIP runtime rather than returning an error when there is no room. */
|
||||
|
||||
/* The speculative window, and the whole of the draft policy: the depth is constant and this
|
||||
* is it. See core/sched/draft.h. */
|
||||
/* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
|
||||
* core/sched/draft.h. */
|
||||
/* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
|
||||
* trained at, and a container with no draft head resolves to 0 with a line saying so.
|
||||
*
|
||||
@@ -732,6 +817,7 @@ struct Config {
|
||||
* paying for it again in VRAM, and then running at one token a step -- a small fraction of
|
||||
* the throughput the same container gives at its declared depth. */
|
||||
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
|
||||
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
|
||||
|
||||
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
|
||||
*
|
||||
@@ -751,11 +837,17 @@ 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.
|
||||
* Passed through verbatim: the legal set belongs to the template, not to us. */
|
||||
std::string reasoning_effort;
|
||||
/* --reasoning-effort-map FROM=TO,...: an effort a request sends, replaced before the template
|
||||
* sees it. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
/* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */
|
||||
int64_t thinking_token_budget = -1;
|
||||
int port = 8000;
|
||||
@@ -837,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]);
|
||||
|
||||
+12
-5
@@ -73,6 +73,10 @@ struct StepEntry {
|
||||
bool draft_out = false;
|
||||
bool is_prefill = false;
|
||||
bool produces_token = false; /* this entry's last token is the sequence's last */
|
||||
/* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
|
||||
* in the reported acceptance like any other, and kept out of the adaptive window's estimate,
|
||||
* which describes the draft head (DraftController, draft.h). */
|
||||
bool ngram = false;
|
||||
/* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
|
||||
* StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
|
||||
* `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
|
||||
@@ -164,9 +168,11 @@ public:
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step);
|
||||
/* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts,
|
||||
* and its modalities are RadBatch::enc. */
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc);
|
||||
bool has_encoder() const { return mm_on_; }
|
||||
int64_t encoder_patches() const { return enc_patches_; }
|
||||
|
||||
|
||||
private:
|
||||
@@ -362,9 +368,10 @@ private:
|
||||
uint16_t* mm_host_ = nullptr;
|
||||
RadEvent mm_ev_ = nullptr;
|
||||
bool mm_ev_live_ = false;
|
||||
/* ...and the encoder's inputs: patches, their coordinates and the segment boundaries, the
|
||||
* largest pass the plugin declared. One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_dim_ = 0, enc_segs_ = 0;
|
||||
/* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized
|
||||
* for the larger of the passes the plugin declared (a vision tower's and an audio encoder's
|
||||
* run one at a time and share it). One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0;
|
||||
std::vector<void*> enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
|
||||
uint16_t* enc_pix_host_ = nullptr;
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
|
||||
+255
-1
@@ -1,9 +1,46 @@
|
||||
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
|
||||
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
|
||||
* on. See draft.h for why the first is the default and what the second changes.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
|
||||
* one round of a serial head and one more verify row against a weight-bound step. It prices a
|
||||
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
|
||||
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
|
||||
constexpr double kCostSlope = 0.06;
|
||||
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
|
||||
|
||||
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
|
||||
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
|
||||
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
|
||||
* grows by a few thousand tokens over a reply. */
|
||||
constexpr double kCostHalfLife = 32.0;
|
||||
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
|
||||
* step that waited on something other than its own work -- a first recording, an allocation, a
|
||||
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
|
||||
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
|
||||
* against: its first step may itself be the odd one. */
|
||||
constexpr double kCostOutlier = 4.0;
|
||||
constexpr int64_t kCostClipAfter = 4;
|
||||
|
||||
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
|
||||
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
|
||||
* the half-life's, and from then on it is the moving average it is meant to be. Without it a
|
||||
* sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
|
||||
* a short answer. */
|
||||
constexpr double kPriorWeight = 4.0;
|
||||
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int DraftController::configure(const Params& p) {
|
||||
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
|
||||
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
|
||||
@@ -14,6 +51,24 @@ int DraftController::configure(const Params& p) {
|
||||
tot_drafted_ = tot_accepted_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
|
||||
seen_ = 0;
|
||||
|
||||
adapt_ = p.adapt && p.max_depth > 0;
|
||||
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
|
||||
step_d_ = 0;
|
||||
step_w_ = 0;
|
||||
step_held_ = 0;
|
||||
prior_n_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
|
||||
by_depth_[d] = 0;
|
||||
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
|
||||
}
|
||||
if (adapt_)
|
||||
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
|
||||
"maximises the tokens its sequences are expected to emit over the step's measured "
|
||||
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
|
||||
"time; moves at +%.0f%% and at most every %d steps",
|
||||
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -34,6 +89,205 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
if (j < accepted) ++hit_[j];
|
||||
}
|
||||
if (drafted > seen_) seen_ = drafted;
|
||||
if (adapt_) ++by_depth_[drafted];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's cost */
|
||||
int DraftController::cost_class(int n_rows) {
|
||||
int c = 0;
|
||||
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
|
||||
return c;
|
||||
}
|
||||
|
||||
void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
|
||||
!std::isfinite(ms))
|
||||
return;
|
||||
const int c = cost_class(n_rows);
|
||||
double& m = cost_ms_[depth][c];
|
||||
int64_t& n = cost_n_[depth][c];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
}
|
||||
|
||||
int64_t DraftController::cost_samples(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
|
||||
return cost_n_[depth][cost_class(n_rows)];
|
||||
}
|
||||
|
||||
double DraftController::step_cost(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
|
||||
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
|
||||
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
|
||||
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
|
||||
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
|
||||
* ONE class -- reads the prior's shape until its own depths are measured. */
|
||||
for (int dc = 0; dc < kCostClasses; ++dc) {
|
||||
for (int sgn = 0; sgn < 2; ++sgn) {
|
||||
const int k = sgn ? c + dc : c - dc;
|
||||
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
|
||||
int best = -1;
|
||||
for (int d = 1; d <= p_.max_depth; ++d) {
|
||||
if (cost_n_[d][k] <= 0) continue;
|
||||
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
|
||||
}
|
||||
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
|
||||
}
|
||||
}
|
||||
return cost_prior(depth);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one sequence */
|
||||
int DraftController::stop_of(const float* a) const {
|
||||
double p = 1.0;
|
||||
int d = 0;
|
||||
while (d < p_.max_depth) {
|
||||
p *= (double)a[d];
|
||||
if (p < kDraftMinChance) break;
|
||||
++d;
|
||||
}
|
||||
return d < kMinDepth ? kMinDepth : d;
|
||||
}
|
||||
|
||||
double DraftController::prior_at(int j) const {
|
||||
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
|
||||
}
|
||||
|
||||
void DraftController::start(DraftAdapt& s) const {
|
||||
/* Each position from the sequences that finished before it once there are enough of them
|
||||
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
|
||||
for (int j = 0; j < p_.max_depth; ++j) {
|
||||
s.a[j] = (float)prior_at(j);
|
||||
s.n[j] = 0;
|
||||
}
|
||||
s.depth = stop_of(s.a);
|
||||
s.held = 0;
|
||||
}
|
||||
|
||||
void DraftController::adapt_retire(const DraftAdapt& s) {
|
||||
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
|
||||
1.0 / (double)(prior_n_ + 1));
|
||||
for (int j = 0; j < p_.max_depth; ++j)
|
||||
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
|
||||
: s.a[j];
|
||||
++prior_n_;
|
||||
}
|
||||
|
||||
double DraftController::yield(const DraftAdapt& s, int d) const {
|
||||
if (d > p_.max_depth) d = p_.max_depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
|
||||
return e;
|
||||
}
|
||||
|
||||
int DraftController::window_of(const DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) return 0;
|
||||
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
|
||||
return s.depth < D ? s.depth : D;
|
||||
}
|
||||
|
||||
int DraftController::window_for(DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
return window_of(s);
|
||||
}
|
||||
|
||||
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
if (drafted <= 0) return s.depth;
|
||||
const int D = p_.max_depth;
|
||||
if (drafted > D) drafted = D;
|
||||
if (accepted < 0) accepted = 0;
|
||||
if (accepted > drafted) accepted = drafted;
|
||||
|
||||
/* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
|
||||
* rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
|
||||
* and never looked at, and says nothing either way. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
|
||||
const double x = j < accepted ? 1.0 : 0.0;
|
||||
s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
|
||||
if (s.n[j] < UINT16_MAX) ++s.n[j];
|
||||
}
|
||||
/* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
|
||||
* learned about them while the window is shorter -- and a sequence held at three by prose that
|
||||
* turns into code would otherwise keep pricing positions four and up at whatever they read
|
||||
* before, and never draft deep enough to find out. The guess is that acceptance decays with
|
||||
* position rather than falling off a cliff, so the window's edge stands in for what lies past
|
||||
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
|
||||
const double edge = (double)s.a[drafted - 1];
|
||||
for (int j = drafted; j < D; ++j)
|
||||
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
|
||||
|
||||
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
|
||||
if (s.held < INT32_MAX) ++s.held;
|
||||
if (s.held < kHold) return s.depth;
|
||||
const int d = stop_of(s.a);
|
||||
if (d != s.depth) {
|
||||
s.depth = d;
|
||||
s.held = 0;
|
||||
}
|
||||
return s.depth;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
if (!adapt_ || n_seq <= 0) return step_d_;
|
||||
if (n_rows < n_seq) n_rows = n_seq;
|
||||
const int M = p_.max_depth;
|
||||
|
||||
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
|
||||
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
|
||||
* sequence drafts further and the head runs no further -- so the candidates end there. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
DraftAdapt& s = *seq[i];
|
||||
if (s.depth <= 0) start(s);
|
||||
if (s.depth > top) top = s.depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int d = 1; d <= M; ++d) {
|
||||
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
|
||||
tok[d] += e;
|
||||
}
|
||||
}
|
||||
const double plain = (double)(n_rows - n_seq);
|
||||
if (top > M) top = M;
|
||||
|
||||
int best = kMinDepth;
|
||||
double best_g = -1.0;
|
||||
for (int d = kMinDepth; d <= top; ++d) {
|
||||
const double g = (tok[d] + plain) / step_cost(d, n_rows);
|
||||
if (g > best_g) { best_g = g; best = d; }
|
||||
}
|
||||
|
||||
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
|
||||
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
|
||||
if (step_d_ <= 0) {
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
} else {
|
||||
if (step_held_ < INT32_MAX) ++step_held_;
|
||||
const int cur = step_d_ < top ? step_d_ : top;
|
||||
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
|
||||
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
|
||||
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
|
||||
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
|
||||
best_g);
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
}
|
||||
}
|
||||
step_w_ = step_d_ < top ? step_d_ : top;
|
||||
return step_d_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+190
-4
@@ -1,8 +1,8 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
*
|
||||
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
|
||||
* No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
|
||||
* dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
|
||||
* decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
|
||||
* DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
|
||||
@@ -16,6 +16,42 @@
|
||||
*
|
||||
* What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
|
||||
* and because a verify that accepts nothing has to be visible.
|
||||
*
|
||||
* UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
|
||||
* weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
|
||||
* round -- a step is NOT flat in depth: each draft is one more round of the head and one more
|
||||
* verify row. And the best depth is not a property of the model pair but of the TEXT:
|
||||
* per-position acceptance stays high deep into the window on code and JSON and falls off after a
|
||||
* position or two on prose and summaries. No constant is right for all of them, and the one that
|
||||
* is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
|
||||
*
|
||||
* So the adaptive window is a policy on the host, in two halves:
|
||||
*
|
||||
* PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
|
||||
* acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
|
||||
* deepest draft whose chance of being emitted still pays for the verify row it adds
|
||||
* (kDraftMinChance).
|
||||
*
|
||||
* PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so depth is a property of the step and not of one sequence: D maximises
|
||||
* the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
|
||||
* at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
|
||||
* and T measured online (step_time). Every sequence then drafts min(D, stop_i).
|
||||
*
|
||||
* Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
|
||||
* a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
|
||||
* and everything sized for it stays sized for it.
|
||||
*
|
||||
* IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
|
||||
* prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
|
||||
* turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
|
||||
*
|
||||
* IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
|
||||
* core/sample/accept.h, so what a step emits is the target's own token at every position whatever
|
||||
* window it verified. At temperature 0 that is the same text at every window, to exactly the
|
||||
* degree a speculative run matches a plain one at all: exact given the same logits, and a verify
|
||||
* row's logits are computed at an M that now moves with the window (accept.h says what that does
|
||||
* and does not change).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -26,18 +62,148 @@ namespace rad {
|
||||
* band (spec §10), so 64 is the largest window any batch can carry. */
|
||||
enum { RAD_SCHED_MAX_SPEC = 64 };
|
||||
|
||||
/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
|
||||
* text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
|
||||
* and the controller does the arithmetic, so neither has to look the other up.
|
||||
*
|
||||
* `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
|
||||
* It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
|
||||
* it describes is still the text the request is writing -- and a recycled slot starts it over. */
|
||||
struct DraftAdapt {
|
||||
int32_t depth = 0; /* the sequence's stop; 0 = not started */
|
||||
int32_t held = 0; /* verifies since `depth` last moved */
|
||||
float a[RAD_SCHED_MAX_SPEC] = {}; /* conditional acceptance at each draft position */
|
||||
uint16_t n[RAD_SCHED_MAX_SPEC] = {}; /* verifies that evaluated each one, saturating */
|
||||
};
|
||||
|
||||
class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
/* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
|
||||
* drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
|
||||
bool adapt = false;
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------- the policy's constants
|
||||
* Named rather than configurable: each is a property of how the policy works, not of a
|
||||
* deployment, and the one property that IS a deployment's -- what a step costs -- is
|
||||
* measured (step_time). */
|
||||
|
||||
/* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
|
||||
* percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
|
||||
* a percent verify to verify; below two percent a move would flip D between two near-equal
|
||||
* neighbours and pay a recording each time. */
|
||||
static constexpr double kHyst = 0.02;
|
||||
/* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
|
||||
* second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
|
||||
* eight steps plays from the tape for most of them; and eight verifies at the half-life below
|
||||
* move an estimate by about a third of the way to a new rate, which is a trend rather than
|
||||
* one rejection. */
|
||||
static constexpr int kHold = 8;
|
||||
/* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
|
||||
* tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
|
||||
* into a code block and back, long enough that a single rejection moves an estimate by four
|
||||
* percent rather than resetting it. */
|
||||
static constexpr double kHalfLife = 16.0;
|
||||
/* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
|
||||
* deep evaluates every position and learns all of them, one that starts shallow learns nothing
|
||||
* about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
|
||||
* and on code at the first positions, so a wrong start is corrected within a hold. */
|
||||
static constexpr double kPrior = 0.8;
|
||||
/* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
|
||||
* the mean of their estimates, a running mean and then a moving average with a half-life of 32
|
||||
* sequences, so a deployment that moves from one kind of traffic to another follows it within
|
||||
* a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
|
||||
* once it has had a half-life of verifies: before that its estimate is mostly the prior it
|
||||
* started from, and folding it back would feed the prior to itself. */
|
||||
static constexpr int kPriorMinSeqs = 4;
|
||||
static constexpr double kPriorHalfLifeSeqs = 32.0;
|
||||
/* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
|
||||
* ever move its estimate off zero again. */
|
||||
static constexpr int kMinDepth = 1;
|
||||
/* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
|
||||
* and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
|
||||
* the step whatever D is, and that row is the only cost a sequence adds once the head runs D
|
||||
* rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
|
||||
* breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
|
||||
* it adds to the step, with E around two -- and a verify row alone costs less than a round
|
||||
* plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
|
||||
* measurement: a row's share of the step is not separable from the head's rounds in step
|
||||
* times keyed by depth, and the measured T(D, n) already prices the rounds. */
|
||||
static constexpr double kDraftMinChance = 0.1;
|
||||
/* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
|
||||
* step's cost moves with how many rows share its weight reads, and a class a power of two
|
||||
* wide keeps every key fed often enough to mean something. */
|
||||
static constexpr int kCostClasses = 5;
|
||||
|
||||
int configure(const Params& p);
|
||||
const Params& params() const { return p_; }
|
||||
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
|
||||
* under the adaptive policy it is the CEILING, and window_for() is the window. */
|
||||
int next_depth() const { return p_.max_depth; }
|
||||
|
||||
/* ---------------------------------------------------------- the adaptive policy */
|
||||
bool adaptive() const { return adapt_; }
|
||||
/* The window this sequence may draft into: min(D, its stop), starting its estimate on the
|
||||
* first ask; max_depth when the policy is off. Before any step has chosen D, D is the
|
||||
* ceiling. */
|
||||
int window_for(DraftAdapt& s) const;
|
||||
/* The same for a sequence whose estimate has started, without starting one: 0 when it has
|
||||
* not. For reporting. */
|
||||
int window_of(const DraftAdapt& s) const;
|
||||
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
|
||||
* estimate, and its stop past the hold. Returns the stop after. */
|
||||
int adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
|
||||
/* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
|
||||
*
|
||||
* PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
|
||||
* every verify -- are what a fixed window would want, and under this policy they are biased:
|
||||
* only a sequence whose drafts keep being accepted is given a window that reaches the deep
|
||||
* positions, so those positions are measured almost only on the texts that predict well, and
|
||||
* a new sequence would start as if every text did. Each finished sequence counts once here, at
|
||||
* every position, and at a position it never reached its estimate is the extrapolation from
|
||||
* its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
|
||||
* much as a deep one holds them up. */
|
||||
void adapt_retire(const DraftAdapt& s);
|
||||
/* The prior a sequence starting now is given at position `j`. For tests and logs. */
|
||||
double prior_at(int j) const;
|
||||
|
||||
/* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
|
||||
* draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
|
||||
* draft nothing). Started here if they have not been. Moves D past the hold and the
|
||||
* hysteresis; with no sequence to draft, D stays. Returns D. */
|
||||
int plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
|
||||
/* The step depth in force: 0 before the first step chose one. */
|
||||
int step_depth() const { return step_d_; }
|
||||
/* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
|
||||
* was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
|
||||
* any step chose one, and with the policy off. What a proposal from outside the head (prompt
|
||||
* lookup) is held to, so it adds no deeper pass shape than the head's own. */
|
||||
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
|
||||
|
||||
/* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
|
||||
* took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
|
||||
* adaptive policy reads it. */
|
||||
void step_time(int depth, int n_rows, double ms);
|
||||
/* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
|
||||
* been measured: the key's own mean when it has samples; the nearest measured key scaled by
|
||||
* the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
|
||||
* measured. */
|
||||
double step_cost(int depth, int n_rows) const;
|
||||
/* Samples behind a key: for tests and logs. */
|
||||
int64_t cost_samples(int depth, int n_rows) const;
|
||||
|
||||
/* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
|
||||
* the verified token included. For tests and logs. */
|
||||
double yield(const DraftAdapt& s, int d) const;
|
||||
/* Verifies by the window they carried, counted only under the policy: the histogram of the
|
||||
* depths it actually chose, which the mean gauge on its own cannot show. */
|
||||
int64_t verified_at(int d) const {
|
||||
return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
|
||||
}
|
||||
|
||||
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
|
||||
* taken. Feeds the reported metrics and nothing else. */
|
||||
void observe(int drafted, int accepted);
|
||||
@@ -76,6 +242,26 @@ private:
|
||||
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
|
||||
int seen_ = 0;
|
||||
|
||||
/* The adaptive policy as configure() resolved it. */
|
||||
bool adapt_ = false;
|
||||
double alpha_ = 0.0; /* the smoothing step from kHalfLife */
|
||||
int64_t by_depth_[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int32_t step_d_ = 0; /* D; 0 until a step chose one */
|
||||
int32_t step_w_ = 0; /* min(D, the deepest stop it saw) */
|
||||
int32_t step_held_ = 0; /* steps since D last moved */
|
||||
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
|
||||
float prior_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t prior_n_ = 0;
|
||||
/* T(d, class): the mean step time of each key, and the steps behind it. */
|
||||
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
|
||||
/* Fill a sequence's estimate from the prior and set its first stop. */
|
||||
void start(DraftAdapt& s) const;
|
||||
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
|
||||
int stop_of(const float* a) const;
|
||||
static int cost_class(int n_rows);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -117,6 +117,11 @@ struct IKVManager {
|
||||
* it, so the batch builder is its one caller: it keeps the device's copy of a table and
|
||||
* stages only what moved. 0 is always a correct answer -- it restages the whole table. */
|
||||
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* THE SNAPSHOT STORE STILL HOLDS `slot`: it was allocated and not given back since. A step
|
||||
* that restores from a slot the store gave back would read another session's state or
|
||||
* nothing, so the scheduler asks before it builds one. */
|
||||
virtual bool checkpoint_held(int32_t slot) const = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
@@ -307,6 +312,7 @@ struct KVBinding final : IKVManager {
|
||||
int64_t take_table_changes(uint64_t s, int32_t g) const override {
|
||||
return m->take_table_changes(s, g);
|
||||
}
|
||||
bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
|
||||
};
|
||||
|
||||
/* The prefix cache's own lookup takes tokens and content-hashed multimodal keys rather than a
|
||||
@@ -368,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. */
|
||||
|
||||
@@ -137,6 +137,13 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
|
||||
int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
|
||||
/* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
|
||||
* window it gives the sequences running now -- at one sequence, that sequence's window -- and
|
||||
* the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
|
||||
* where the policy stands, the histogram where it has been. */
|
||||
bool draft_adaptive = false;
|
||||
float draft_depth_adaptive = 0.0f;
|
||||
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+213
-13
@@ -97,7 +97,29 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
|
||||
DraftController::Params dp;
|
||||
dp.max_depth = cfg.n_spec;
|
||||
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
|
||||
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
|
||||
* pass at all, so for either the window stays fixed -- decided here, once, before any step
|
||||
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
|
||||
* like a flag that made no difference. */
|
||||
if (cfg.draft_window == DraftWindow::Adaptive) {
|
||||
const RadDrafterDecl& dd = prog.drafter;
|
||||
if (cfg.n_spec <= 0)
|
||||
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
|
||||
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
|
||||
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
|
||||
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
|
||||
"window prices the rounds of a serial draft head, which this deployment does "
|
||||
"not run", cfg.n_spec,
|
||||
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
|
||||
"pass"
|
||||
: "prompt lookup only");
|
||||
else
|
||||
dp.adapt = true;
|
||||
}
|
||||
RAD_TRY(draft_.configure(dp));
|
||||
draft_est_.clear();
|
||||
draft_est_.reserve((size_t)cfg.max_seqs);
|
||||
|
||||
RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
|
||||
/* The builder's bound and not a second derivation of it: it is what the block tables were
|
||||
@@ -155,6 +177,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
if (!r) return RAD_E_INVAL;
|
||||
if (r->prompt.empty()) return RAD_E_INVAL;
|
||||
if (by_id_.count(r->id)) return RAD_E_DUPLICATE;
|
||||
/* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a
|
||||
* step could never be admitted and would wait for good. */
|
||||
if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
|
||||
/* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step
|
||||
* that is never coming, so the sink is failed here -- it is the one thing the caller is
|
||||
* listening to -- and the refusal says why. */
|
||||
@@ -178,6 +203,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.card = -1;
|
||||
s.running = false;
|
||||
s.drafter_reset();
|
||||
/* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
|
||||
s.adapt.depth = 0;
|
||||
s.adapt.held = 0;
|
||||
s.sched_tokens = 0;
|
||||
s.entry = -1;
|
||||
s.entry_next = -1;
|
||||
@@ -221,8 +249,15 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
|
||||
/* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
|
||||
* the card already put the tokens in its batch; the host copy is what that step's commit
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped. */
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped.
|
||||
*
|
||||
* UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
|
||||
* and expect_draft() already cut this one's count to its own window -- the card verifies the
|
||||
* FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
|
||||
* count here, against the number the step was planned with: the window itself may have moved
|
||||
* at the commit in between, and the planned step is what these tokens are for. */
|
||||
if (next_open_ && s.entry_next >= 0) {
|
||||
if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
|
||||
if (n != s.draft_next) {
|
||||
RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d",
|
||||
(unsigned long long)id, n, s.draft_next);
|
||||
@@ -244,7 +279,7 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int cap = draft_.next_depth();
|
||||
int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
|
||||
for (int i = 0; i < n; ++i) s.draft[i] = tokens[i];
|
||||
@@ -353,6 +388,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
/* What the draft head did on this text is now part of what the next text starts from --
|
||||
* once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
|
||||
if (draft_.adaptive()) {
|
||||
draft_.adapt_retire(s.adapt);
|
||||
s.adapt.depth = 0;
|
||||
}
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
@@ -862,6 +903,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
int64_t target = s.seq_len();
|
||||
int64_t ckpt = -1;
|
||||
int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt);
|
||||
/* The whole input or nothing this step (Request::embed): the next step starts with a whole
|
||||
* budget, and add_locked refused an input no budget holds. */
|
||||
if (r.embed && want < target - (int64_t)r.n_computed) want = 0;
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL;
|
||||
@@ -904,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;
|
||||
@@ -924,6 +969,8 @@ void Scheduler::undo_hit(SchedReq& s) {
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
const RadBatch* Scheduler::step() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
|
||||
draft_cycle();
|
||||
|
||||
/* The drafter's snapshots describe the step before this one and nothing reads them from here
|
||||
* on. block_end() and serial_end() clear them already; this covers a drafter that stopped
|
||||
@@ -979,10 +1026,22 @@ const RadBatch* Scheduler::step() {
|
||||
/* THE LAST GATE, and it has to be here rather than only at set_draft, because the
|
||||
* n-gram fallback below fills any proposal a drafter left empty -- so refusing a
|
||||
* draft upstream and stopping there hands the request a different draft instead of
|
||||
* none. Request::may_speculate says why a request can be ineligible. */
|
||||
* none. Request::may_speculate says why a request can be ineligible.
|
||||
*
|
||||
* AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
|
||||
* policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
|
||||
* for. The n-gram fallback is not the head and that estimate says nothing about it, so
|
||||
* it is held to the step's window instead: as deep as the head drafts this step and no
|
||||
* deeper, which adds no pass shape the head's own windows do not. */
|
||||
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
|
||||
bool ngram = false;
|
||||
if (!r.may_speculate) s.n_draft = 0;
|
||||
else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth);
|
||||
if (s.n_draft > depth) s.n_draft = depth;
|
||||
else if (s.n_draft == 0) {
|
||||
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
|
||||
ngram = s.n_draft > 0;
|
||||
}
|
||||
if (!ngram && s.n_draft > cap) s.n_draft = cap;
|
||||
s.draft_ngram = ngram;
|
||||
/* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
|
||||
* .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
|
||||
* block-table column. commit() finishes a sequence before its length reaches the
|
||||
@@ -1069,6 +1128,7 @@ const RadBatch* Scheduler::step() {
|
||||
e.draft = s.draft;
|
||||
e.n_draft = s.n_draft;
|
||||
e.is_prefill = prefill;
|
||||
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
|
||||
e.produces_token = (r.n_computed + want >= target);
|
||||
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
|
||||
* sequence after this, and restoring it again on a later chunk would rewind it. */
|
||||
@@ -1263,8 +1323,23 @@ const RadBatch* Scheduler::step() {
|
||||
}();
|
||||
if (force_mixed && plan_.phase == RAD_PHASE_DECODE) plan_.phase = RAD_PHASE_MIXED;
|
||||
|
||||
/* EVERY SNAPSHOT THIS STEP RESTORES FROM IS STILL IN THE STORE. The prefix cache keeps a
|
||||
* handed-out snapshot's slot until the next step begins (PrefixCache::begin_step), so this
|
||||
* holds by construction; it is checked because a restore from a slot the store gave back
|
||||
* reads another session's state or nothing, and the engine can only stop on it. A step that
|
||||
* finds one is abandoned like a failed staging, below: the request gives its hit back and is
|
||||
* prefilled again, and the rest re-schedule unchanged. */
|
||||
bool lost_restore = false;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (e.ckpt_restore < 0 || kv_->checkpoint_held(e.ckpt_restore)) continue;
|
||||
RAD_ERR("sequence %llu was to resume from checkpoint slot %d, which the store no longer "
|
||||
"holds; its hit is given back and its prompt prefilled again",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore);
|
||||
lost_restore = true;
|
||||
}
|
||||
|
||||
step_start_ = std::chrono::steady_clock::now();
|
||||
const RadBatch* b = builder_.build(plan_, *kv_, step_);
|
||||
const RadBatch* b = lost_restore ? nullptr : builder_.build(plan_, *kv_, step_);
|
||||
if (!b) {
|
||||
/* Staging failed. Nothing was computed, so nothing is committed and n_computed did not
|
||||
* advance: the next step re-schedules the same chunks and the KV allocations already made
|
||||
@@ -1320,12 +1395,39 @@ void Scheduler::take_encodes(std::vector<std::shared_ptr<mm::Item>>* out) {
|
||||
out->swap(enc_want_);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's head depth */
|
||||
void Scheduler::draft_cycle() {
|
||||
if (!draft_.adaptive()) return;
|
||||
/* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
|
||||
* may speculate draft, and their estimates choose D; the rest emit one token each, which is
|
||||
* part of what the step yields and of what it costs. A sequence still prefilling is neither. */
|
||||
draft_est_.clear();
|
||||
int n_rows = 0;
|
||||
for (int32_t slot : running_) {
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
const Request& r = *s.req;
|
||||
if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
|
||||
++n_rows;
|
||||
if (r.may_speculate) draft_est_.push_back(&s.adapt);
|
||||
}
|
||||
(void)draft_.plan_step(draft_est_.data(), (int)draft_est_.size(), n_rows);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the next step */
|
||||
void Scheduler::expect_draft(uint64_t id, int n) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return;
|
||||
reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0;
|
||||
SchedReq& s = *reqs_[(size_t)it->second];
|
||||
/* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
|
||||
* first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
|
||||
* since: nothing commits between the two, and D is the cycle's (draft_cycle). */
|
||||
if (draft_.adaptive() && n > 0) {
|
||||
const int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
}
|
||||
s.draft_next = n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
const RadBatch* Scheduler::step_next() {
|
||||
@@ -1409,6 +1511,10 @@ const RadBatch* Scheduler::step_next_locked() {
|
||||
void Scheduler::promote_next() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!next_open_) return;
|
||||
/* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
|
||||
* called. Its proposals were counted under the last cycle's D; the next ones are drafted
|
||||
* under this one. */
|
||||
draft_cycle();
|
||||
std::swap(plan_, plan_next_);
|
||||
plan_next_.reset();
|
||||
step_prefill_tok_ = 0;
|
||||
@@ -1482,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
|
||||
@@ -1497,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));
|
||||
@@ -1552,20 +1672,48 @@ 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;
|
||||
|
||||
if (e.n_spec > 0) {
|
||||
draft_.observe(e.n_spec, a);
|
||||
/* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
|
||||
* window -- when the head drafted it. A prompt-lookup proposal is accepted on
|
||||
* different text by a different rule, and folding it in would price the head's
|
||||
* next window on what the lookup found. A move takes effect at the next draft:
|
||||
* this step's drafter has already run, sized from the estimate as it stood before
|
||||
* this commit. */
|
||||
if (draft_.adaptive() && !e.ngram) {
|
||||
const int was = s.adapt.depth;
|
||||
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
|
||||
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
|
||||
char est[8 * RAD_SCHED_MAX_SPEC];
|
||||
int o = 0;
|
||||
for (int j = 0; j < draft_.next_depth() && o < (int)sizeof est - 8; ++j)
|
||||
o += std::snprintf(est + o, sizeof est - (size_t)o, "%s%.2f",
|
||||
j ? " " : "", (double)s.adapt.a[j]);
|
||||
est[o] = 0;
|
||||
RAD_DEBUG("draft window: request %llu stops at %d, was %d (expected "
|
||||
"tokens a verify %.3f -> %.3f; acceptance by position %s)",
|
||||
(unsigned long long)r.id, now, was, draft_.yield(s.adapt, was),
|
||||
draft_.yield(s.adapt, now), est);
|
||||
}
|
||||
}
|
||||
m_.draft_tokens += e.n_spec;
|
||||
m_.draft_accepted += a;
|
||||
server::sink_drafts(r.sink, e.n_spec, a);
|
||||
@@ -1588,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. */
|
||||
@@ -1692,6 +1845,16 @@ void Scheduler::step_finished() {
|
||||
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
|
||||
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
|
||||
}
|
||||
/* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
|
||||
* which is the step's share of the loop -- the draft rounds that followed it included, and a
|
||||
* step issued ahead counted from the end of the one before rather than twice. A decode step
|
||||
* only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
|
||||
* the step verified, which is the head depth it ran at whenever D held from the step before. */
|
||||
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
|
||||
int rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
|
||||
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
|
||||
}
|
||||
last_step_at_ = step_end;
|
||||
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
|
||||
step_start_ = {};
|
||||
@@ -1725,6 +1888,27 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
if (depth > 0 && *rounds > depth) *rounds = depth;
|
||||
if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
|
||||
|
||||
/* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
|
||||
* pass of the head over every drafting row, so the step runs as many as its deepest window,
|
||||
* and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
|
||||
* round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
|
||||
* draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
|
||||
* is the history pass, and that still has to run. The reservation below is then made for the
|
||||
* rounds that will actually run, which is what it is for. */
|
||||
if (may_draft && draft_.adaptive()) {
|
||||
int want = 0;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
|
||||
SchedReq& s = *reqs_[(size_t)e.slot];
|
||||
if (!s.req || s.req->state != ReqState::Running || !s.running ||
|
||||
!s.req->may_speculate)
|
||||
continue;
|
||||
const int c = draft_cap(s);
|
||||
if (c > want) want = c;
|
||||
}
|
||||
if (want > 0 && *rounds > want) *rounds = want;
|
||||
}
|
||||
|
||||
int n_draft_rows = 0;
|
||||
int64_t cu = 0; /* this entry's first token in the step just run */
|
||||
for (size_t i = 0; i < plan_.e.size(); ++i) {
|
||||
@@ -2278,6 +2462,22 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.draft_pos_reached [j] = draft_.reached(j);
|
||||
m.draft_pos_accepted[j] = draft_.hits(j);
|
||||
}
|
||||
if (draft_.adaptive()) {
|
||||
m.draft_adaptive = true;
|
||||
/* Over the running sequences whose estimate has started; one that has not drafted yet
|
||||
* has no window to report. */
|
||||
int64_t sum = 0, n = 0;
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (s.adapt.depth <= 0) continue;
|
||||
/* The window it drafts into: its stop under the step's head depth. */
|
||||
sum += draft_.window_of(s.adapt);
|
||||
++n;
|
||||
}
|
||||
m.draft_depth_adaptive = n ? (float)((double)sum / (double)n) : 0.0f;
|
||||
const int kDepth = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
for (int d = 0; d < kDepth; ++d) m.draft_verify_depth[d] = draft_.verified_at(d);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
+42
-5
@@ -109,6 +109,14 @@ struct SchedReq {
|
||||
draft_hi = 0;
|
||||
}
|
||||
|
||||
/* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
|
||||
* deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
|
||||
* preemption does not change, rather than any cache the request holds. A recycled slot starts
|
||||
* it over in add_locked. Untouched while the policy is off. */
|
||||
DraftAdapt adapt;
|
||||
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
|
||||
bool draft_ngram = false;
|
||||
|
||||
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
|
||||
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
|
||||
/* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
|
||||
@@ -168,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,
|
||||
@@ -280,7 +292,8 @@ public:
|
||||
* the one that is stuck. Returns how many were written. */
|
||||
int requests(ReqStat* out, int max) const;
|
||||
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
|
||||
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
|
||||
int set_draft(uint64_t id, const int32_t* tokens, int n);
|
||||
|
||||
/* ---------------------------------------------------------- media the encoder owes
|
||||
@@ -292,11 +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
|
||||
@@ -318,7 +331,8 @@ public:
|
||||
* from one to the other.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* which is how many the next step verifies.
|
||||
* which is how many the next step verifies -- capped at the sequence's window,
|
||||
* which under the adaptive policy can be fewer than the rounds that ran.
|
||||
* step_next plans and builds that step: every row of this one, as a device row, at
|
||||
* the furthest context it can reach. Null -- and the engine plans with step()
|
||||
* after this one commits -- whenever the step needs a decision only a
|
||||
@@ -491,6 +505,29 @@ private:
|
||||
return hit_holes_draft_ ? ctx_len : 0;
|
||||
}
|
||||
|
||||
/* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
|
||||
* min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
|
||||
* It is the rule every site that caps a proposal applies -- step(), set_draft(),
|
||||
* expect_draft() and the rounds in serial_begin() -- and with the policy off it is
|
||||
* next_depth(), exactly as before. */
|
||||
int draft_cap(SchedReq& s) const {
|
||||
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
|
||||
}
|
||||
|
||||
/* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
|
||||
* first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
|
||||
* A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
|
||||
* draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
|
||||
* to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
|
||||
* different one. A D read live could move between them, because a commit or a client hanging
|
||||
* up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
|
||||
* proposal drafted under one D and planned under the next is only ever cut shorter.
|
||||
*
|
||||
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
|
||||
* allocate. */
|
||||
std::vector<DraftAdapt*> draft_est_;
|
||||
void draft_cycle();
|
||||
|
||||
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
|
||||
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
|
||||
* lengths it tries, longest first. */
|
||||
|
||||
+43
-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;
|
||||
@@ -280,6 +281,13 @@ public:
|
||||
o.draft_pos_reached [j] = m.draft_pos_reached [j];
|
||||
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
|
||||
}
|
||||
o.draft_adaptive = m.draft_adaptive;
|
||||
o.draft_depth_adaptive = m.draft_depth_adaptive;
|
||||
{
|
||||
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
|
||||
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
|
||||
}
|
||||
o.preemptions = m.preemptions;
|
||||
o.total_requests = m.admitted;
|
||||
o.steps = m.steps;
|
||||
@@ -312,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_;
|
||||
@@ -369,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,
|
||||
@@ -542,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 {
|
||||
@@ -552,9 +583,11 @@ 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;
|
||||
o.quiet = opt.quiet;
|
||||
|
||||
ChatPrompt p;
|
||||
const int st = t_.apply(messages, tools, o, &p);
|
||||
@@ -597,6 +630,8 @@ public:
|
||||
gq.generation_prompt = p.generation_prompt;
|
||||
gq.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
gq.extract_reasoning = opt.reasoning_format != "none";
|
||||
gq.require_call = calls && opt.tool_choice == "required";
|
||||
gq.only_tool = opt.tool_name;
|
||||
ChatGrammar g;
|
||||
std::string gerr;
|
||||
if (chat_format_grammar(f, gq, &g, &gerr) < 0) {
|
||||
@@ -688,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:
|
||||
|
||||
+200
-22
@@ -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)
|
||||
@@ -161,6 +217,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
if (kw != b.end() && kw->is_object())
|
||||
for (auto it = kw->begin(); it != kw->end(); ++it)
|
||||
opt.template_kwargs[it.key()] = json_dump(it.value());
|
||||
map_reasoning_effort(lim_, &opt);
|
||||
|
||||
json tools = json::array();
|
||||
auto t = b.find("tools");
|
||||
@@ -168,10 +225,8 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
ChatRender render;
|
||||
std::string why;
|
||||
if (deps_.chat->apply(*msgs, tools, opt, &render, &why) < 0)
|
||||
return error_response(err_bad("messages", why.empty()
|
||||
? "the chat template could not render this request"
|
||||
: why), req.peer);
|
||||
if (const int rs = deps_.chat->apply(*msgs, tools, opt, &render, &why); rs < 0)
|
||||
return error_response(template_refusal(opt, lim_, rs, why), req.peer);
|
||||
toks = deps_.tok->encode(render.prompt,
|
||||
get_bool_or(b, "add_special_tokens", false),
|
||||
/*parse_special=*/true);
|
||||
@@ -228,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));
|
||||
}
|
||||
@@ -263,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
|
||||
@@ -289,16 +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;
|
||||
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. */
|
||||
@@ -325,6 +500,9 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
defs["max_tokens"] = srv["default_max_tokens"];
|
||||
defs["reasoning_effort"] = opt_.default_reasoning_effort.empty()
|
||||
? json(nullptr) : json(opt_.default_reasoning_effort);
|
||||
json emap = json::object();
|
||||
for (const auto& [from, to] : lim_.reasoning_effort_map) emap[from] = to;
|
||||
defs["reasoning_effort_map"] = std::move(emap);
|
||||
defs["thinking_token_budget"] = opt_.default_thinking_budget < 0
|
||||
? json(nullptr) : json(opt_.default_thinking_budget);
|
||||
json kw = json::object();
|
||||
|
||||
@@ -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())
|
||||
|
||||
+61
-4
@@ -114,6 +114,11 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
|
||||
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
|
||||
* of the running sequences, and the verifies by the window they carried (index = drafts). */
|
||||
bool draft_adaptive = false;
|
||||
double draft_depth_adaptive = 0.0;
|
||||
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
|
||||
int64_t preemptions = 0;
|
||||
int64_t total_requests = 0;
|
||||
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
|
||||
@@ -155,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 */
|
||||
@@ -302,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*/) {}
|
||||
@@ -344,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
|
||||
@@ -373,10 +390,17 @@ struct ChatRenderOptions {
|
||||
bool enable_thinking = true;
|
||||
bool parallel_tool_calls = true;
|
||||
std::string tool_choice = "auto"; /* auto | none | required */
|
||||
std::string tool_name; /* a named tool_choice's function, or "" */
|
||||
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. */
|
||||
bool quiet = false;
|
||||
};
|
||||
|
||||
/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a
|
||||
@@ -429,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. */
|
||||
@@ -506,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
|
||||
@@ -527,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;
|
||||
@@ -534,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;
|
||||
};
|
||||
|
||||
|
||||
+38
-1
@@ -140,11 +140,23 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
g_draft_pos_reached_[j].set((double)r);
|
||||
g_draft_pos_accepted_[j].set((double)m.draft_pos_accepted[j]);
|
||||
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
|
||||
}
|
||||
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
|
||||
* gauge has not been written yet. */
|
||||
draft_pos_seen_.store(seen, std::memory_order_release);
|
||||
if (m.draft_adaptive) {
|
||||
g_draft_depth_adapt_.set(m.draft_depth_adaptive);
|
||||
int top = 0;
|
||||
for (int d = 1; d <= (int)MAX_DRAFT_POS; ++d) {
|
||||
g_draft_vdepth_[d].set((double)m.draft_verify_depth[d]);
|
||||
if (m.draft_verify_depth[d] > 0) top = d;
|
||||
}
|
||||
/* After the gauges, for the reason above. */
|
||||
draft_vdepth_top_.store(top, std::memory_order_release);
|
||||
draft_adapt_on_.store(true, std::memory_order_release);
|
||||
}
|
||||
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
|
||||
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
|
||||
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
|
||||
@@ -382,7 +394,9 @@ std::string Metrics::render() const {
|
||||
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
|
||||
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
|
||||
* drafter that decays from one whose later rounds are broken; these can, and the companion
|
||||
* `_reached_total` says how much evidence each position carries. */
|
||||
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
|
||||
* same ratio over any window: at a fixed depth the next position's reach would do, but an
|
||||
* adaptive window can end at j with j taken. */
|
||||
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
|
||||
if (seen > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
@@ -397,6 +411,29 @@ std::string Metrics::render() const {
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
|
||||
w.help("radiance:draft_position_accepted_total",
|
||||
"Verifies that accepted each draft position.", "counter");
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
|
||||
}
|
||||
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
|
||||
* at one sequence, that sequence's window -- and where it has been, as verifies by the
|
||||
* number of drafts they carried. */
|
||||
if (draft_adapt_on_.load(std::memory_order_acquire)) {
|
||||
w.gauge("radiance:draft_depth_adaptive",
|
||||
"Mean draft window the adaptive policy gives the running sequences.",
|
||||
L, g_draft_depth_adapt_.get());
|
||||
const int top = draft_vdepth_top_.load(std::memory_order_acquire);
|
||||
if (top > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
w.help("radiance:draft_verify_depth_total",
|
||||
"Verifies by the number of drafts they carried, under the adaptive window.",
|
||||
"counter");
|
||||
for (int d = 1; d <= top; ++d)
|
||||
w.out += "radiance:draft_verify_depth_total" + base + ",depth=\"" +
|
||||
std::to_string(d) + "\"} " + num(g_draft_vdepth_[d].get()) + '\n';
|
||||
}
|
||||
}
|
||||
w.gauge("radiance:num_requests_preempted",
|
||||
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
|
||||
|
||||
@@ -121,7 +121,15 @@ private:
|
||||
enum { MAX_DRAFT_POS = 64 };
|
||||
Gauge g_draft_pos_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
|
||||
std::atomic<int> draft_pos_seen_{0};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
|
||||
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
|
||||
* is on, so a deployment without it exposes exactly what it always did. */
|
||||
Gauge g_draft_depth_adapt_;
|
||||
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
|
||||
std::atomic<bool> draft_adapt_on_{false};
|
||||
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
|
||||
|
||||
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
|
||||
* counter and adding the difference. Two scrapes doing that at once both read the old value
|
||||
|
||||
+2225
-380
File diff suppressed because it is too large.
Load diff
+275
-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"
|
||||
@@ -37,6 +37,14 @@ struct ApiError {
|
||||
std::string message;
|
||||
std::string param; /* "" when the error is not about one field */
|
||||
std::string code; /* "" when there is nothing more specific to say */
|
||||
/* 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 */
|
||||
};
|
||||
@@ -57,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 */
|
||||
@@ -70,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;
|
||||
@@ -91,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
|
||||
@@ -111,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; }
|
||||
};
|
||||
@@ -118,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.
|
||||
@@ -147,6 +192,22 @@ struct OaiLimits {
|
||||
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
|
||||
std::string default_reasoning_effort;
|
||||
|
||||
/* THE WORDS THE CHAT TEMPLATE TAKES AS `reasoning_effort`, found at startup by rendering each
|
||||
* word this server knows of (Server::probe_reasoning_efforts). Empty when the template takes
|
||||
* any word -- it does not read the variable, or reads it without refusing one -- and when
|
||||
* nothing was probed. A request whose effort the template refuses is answered with this set
|
||||
* rather than with the template's traceback (template_refusal). */
|
||||
std::vector<std::string> reasoning_efforts;
|
||||
|
||||
/* --reasoning-effort-map: an effort a request sends, replaced by the deployment's word before
|
||||
* the template sees it. For a client that always sends a word of OpenAI's ladder ("high")
|
||||
* to a model whose template has its own ("xhigh"). */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
|
||||
/* A STARTUP PROBE, NOT A REQUEST: what the template refuses is the answer being asked for, so
|
||||
* its refusal is not logged (ChatRenderOptions::quiet). */
|
||||
bool probe = false;
|
||||
|
||||
/* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the
|
||||
* effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and
|
||||
* a reasoning block that spends the whole of max_tokens returns a turn with no answer in it.
|
||||
@@ -196,6 +257,19 @@ RequestThinking request_thinking(const json& b);
|
||||
* prompt served by the other. */
|
||||
void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* --reasoning-effort-map, on the effort chat_template_kwargs put in the render options: a mapped
|
||||
* word replaces it, and a word mapped to "none" or "minimal" turns thinking off instead. The chat
|
||||
* endpoint maps the top-level `reasoning_effort` itself, before it reads "none" and "minimal";
|
||||
* this is the kwargs spelling, for it and for /tokenize. */
|
||||
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* THE 400 FOR A TEMPLATE THAT REFUSED A RENDER. An effort outside the template's known set
|
||||
* (OaiLimits::reasoning_efforts) is named as `reasoning_effort` with the set in `supported`, the
|
||||
* way OpenAI answers an unsupported value; anything else is `messages` with the template's own
|
||||
* sentence. */
|
||||
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
|
||||
const std::string& why);
|
||||
|
||||
/* True when `v` is a legal value of the sampler field a request spells `field`; otherwise `why`
|
||||
* says what the legal set is, in the words a 400 carries. The same table checks a request and the
|
||||
* command-line flag that sets the field's default, so a default the command line accepts is one
|
||||
@@ -207,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;
|
||||
@@ -280,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
|
||||
@@ -305,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;
|
||||
@@ -349,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;
|
||||
@@ -370,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;
|
||||
|
||||
|
||||
+793
-47
File diff suppressed because it is too large.
Load diff
+38
-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;
|
||||
@@ -85,6 +93,8 @@ struct ServerOptions {
|
||||
bool default_dry_breakers_set = false;
|
||||
/* The deployment's chat template variables and reply format. See OaiLimits. */
|
||||
std::map<std::string, std::string> default_template_kwargs;
|
||||
/* --reasoning-effort-map. See OaiLimits::reasoning_effort_map. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
std::string reasoning_format = "auto";
|
||||
bool allow_image = false;
|
||||
bool allow_video = false;
|
||||
@@ -148,6 +158,15 @@ public:
|
||||
* would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a
|
||||
* request naming the budget would get, which says why. */
|
||||
std::string check_thinking_budget() const;
|
||||
/* THE EFFORTS THE CHAT TEMPLATE TAKES, found by parsing a one-message chat with each word this
|
||||
* server knows of (low, medium, high, xhigh, max) the way a request would send it, with no
|
||||
* deployment defaults. A template that takes a word nobody uses takes any word, and the answer
|
||||
* is empty. Kept for the refusal of a word outside the set and for /server_info; called once,
|
||||
* before run(). */
|
||||
std::vector<std::string> probe_reasoning_efforts();
|
||||
/* --reasoning-effort-map's targets, each rendered as a request's effort would be. Empty when
|
||||
* the template takes every one; otherwise the first refusal, naming the target. */
|
||||
std::string check_reasoning_effort_map() const;
|
||||
void stop();
|
||||
int port() const { return transport_.port(); } /* 0 until run() is accepting */
|
||||
|
||||
@@ -176,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);
|
||||
|
||||
@@ -189,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 */
|
||||
+6
-1
@@ -193,12 +193,17 @@ 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 {
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -54,11 +54,13 @@ 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;
|
||||
bool add_eos = false;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
bool quiet = false; /* a refusal is not logged: a startup probe */
|
||||
};
|
||||
|
||||
/* Everything the scheduler and the sampler need for one request, produced in one pass. */
|
||||
|
||||
+32
-8
@@ -577,6 +577,13 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
const ojson& tools = req.tools ? *req.tools : none;
|
||||
const bool has_tools = f.has_tools() && tools.is_array() && !tools.empty();
|
||||
const bool has_rf = req.json_schema && req.json_schema->is_object() && !req.json_schema->empty();
|
||||
if (req.require_call && (has_rf || !has_tools)) {
|
||||
if (why)
|
||||
*why = has_rf ? "a required tool call and a response format cannot both be the "
|
||||
"whole reply"
|
||||
: "a tool call is required, but there are no tools this format can call";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!has_rf && !(has_tools && !f.triggers.empty())) return RAD_OK;
|
||||
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
@@ -598,12 +605,9 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.resolve_refs(schema);
|
||||
}
|
||||
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
/* A grammar that is the whole reply starts where the generation prompt does, so the
|
||||
* prompt's assistant prefix and the reasoning block come first. */
|
||||
auto whole_reply = [&]() {
|
||||
std::string gp = req.generation_prompt;
|
||||
if (f.has_reasoning() && !f.reasoning_open.empty()) {
|
||||
const size_t at = gp.find(f.reasoning_open);
|
||||
@@ -612,6 +616,15 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
std::vector<G> root{ gp.empty() ? eps() : lit(gp), space() };
|
||||
if (f.has_reasoning() && req.extract_reasoning) root.push_back(reasoning_expr(f, breaks));
|
||||
root.push_back(space());
|
||||
return root;
|
||||
};
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(alt({ seq({ lit("```json"), space(), rule_ref("response-format"), space(),
|
||||
lit("```") }),
|
||||
rule_ref("response-format") }));
|
||||
@@ -630,6 +643,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
continue;
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
if (!req.only_tool.empty() && name != req.only_tool) continue;
|
||||
auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
const auto properties = params.contains("properties") ? params.at("properties")
|
||||
: ojson::object();
|
||||
@@ -687,6 +701,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.add_rule(rule_name("tool-" + name), render(func));
|
||||
choices.push_back(rule_ref(rule_name("tool-" + name)));
|
||||
}
|
||||
if (choices.empty() && !req.only_tool.empty())
|
||||
throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call");
|
||||
if (typed) add_json_rules(b);
|
||||
if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
|
||||
@@ -704,13 +720,21 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
}
|
||||
b.add_rule("tool-call", render(calls));
|
||||
b.add_rule("root", "tool-call");
|
||||
if (req.require_call) {
|
||||
/* The calls and nothing after them: a complete grammar admits only the end of
|
||||
* the turn, so the reply stops at the last call's closer. */
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(rule_ref("tool-call"));
|
||||
b.add_rule("root", render(seq(std::move(root))));
|
||||
} else {
|
||||
b.add_rule("root", "tool-call");
|
||||
}
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
if (why) *why = e.what();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->lazy = !has_rf;
|
||||
out->lazy = !has_rf && !req.require_call;
|
||||
if (out->lazy) out->trigger_words = f.triggers;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+8
-2
@@ -146,14 +146,20 @@ std::string chat_format_describe(const ChatFormat& f);
|
||||
* The GBNF that constrains a reply to the format, generated from the description. For a tool
|
||||
* request it is LAZY: the reply is free until one of `triggers` appears, and from there the
|
||||
* grammar admits the call syntax with each argument constrained by its schema. For a response
|
||||
* format it is the whole reply. Rule names and structure follow the vendored generator so the
|
||||
* two produce the same grammar for a template-analysed format. */
|
||||
* format, and for a request that requires a call, it is the whole reply. Rule names and structure
|
||||
* follow the vendored generator so the two produce the same grammar for a template-analysed
|
||||
* format. */
|
||||
struct ChatGrammarRequest {
|
||||
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
||||
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
||||
std::string generation_prompt;
|
||||
bool parallel_tool_calls = true;
|
||||
bool extract_reasoning = true; /* reasoning_format != "none" */
|
||||
/* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
|
||||
* the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
|
||||
* narrows the calls to that one function. */
|
||||
bool require_call = false;
|
||||
std::string only_tool;
|
||||
};
|
||||
|
||||
struct ChatGrammar {
|
||||
|
||||
+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
|
||||
@@ -0,0 +1,30 @@
|
||||
# q38-27b-quark-mxfp4-df2.recipe -- AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter.
|
||||
#
|
||||
# rad-convert <amd/Qwen3.8-27B-Quark-AWQ-MXFP4> --draft-model <z-lab/Qwen3.8-27B-DFlash2> \
|
||||
# --recipe q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
|
||||
#
|
||||
# Quark's MXFP4 linears are read as `fp4_e2m1*e8m0[1x32]`, byte for byte, so no rule names them:
|
||||
# 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 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 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
|
||||
@@ -0,0 +1,38 @@
|
||||
# qwen4exp-autoround-i8-hc8m.recipe -- a Qwen3.8-Flash-Next released as AutoRound int4
|
||||
# (`auto_round:auto_gptq`, symmetric, group 128), such as
|
||||
# ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound, arranged as the production container is
|
||||
# around its experts.
|
||||
#
|
||||
# rad-convert <AutoRound checkpoint> --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe \
|
||||
# -o swift-autoround.rad
|
||||
#
|
||||
# The routed experts are named by no rule: rad-convert imports the release's int4 codes and group
|
||||
# scales as `i4*bf16[1x128]` (the scales rounded from f16 to bf16), served on the four-bit expert
|
||||
# GEMM. The release ships its block linears in int4 as well, which the trunk's W8A8 GEMMs do not
|
||||
# read, so they are made int8 from the int4 values the release holds -- a 128 of K each, as their
|
||||
# groups are. Everything the release keeps in bf16 is quantised as qwen4exp-w4nl64-i8-hc8m.recipe
|
||||
# quantises it, the MTP layer's experts rounded to the experts' own format.
|
||||
|
||||
# The MTP layer's experts, bf16 in the release (blk.48 is the MTP layer).
|
||||
blk.48.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16
|
||||
|
||||
# The connections' mixing matrices and the MTP head's fc matrices, as in production.
|
||||
*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32
|
||||
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 searched for least error.
|
||||
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
|
||||
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
|
||||
# The n-gram table at one fixed E4M3 scale, and the MTP head's 2-bit draft head.
|
||||
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
|
||||
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user