radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+7 -1
View File
@@ -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.3.0 LANGUAGES C CXX)
project(radiance VERSION 1.4.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -22,6 +22,10 @@ set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video
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)
# Whether the HIP compiler's VOPD pairing is repeatable. LLVM 24's is not unless it carries the
# fix the image builds (docker/llvm-vopd-pairing.patch); without this the build turns pairing off
# on LLVM 24, see rad_hip_repeatable in cmake/RadAddPlugin.cmake.
option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF)
# ---------------------------------------------------------------- HIP detection
@@ -455,3 +459,5 @@ install(FILES vendor/nlohmann/LICENSE.MIT
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE)
install(FILES vendor/cpp-httplib/LICENSE
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE)
install(FILES core/server/LICENSE.lfm
DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE)
+105 -18
View File
@@ -13,8 +13,14 @@
# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their
# 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
# llvm ROCm's libLLVM rebuilt from ROCm's own llvm-project at the commit the image's clang
# reports, with docker/llvm-vopd-pairing.patch -- the fix that makes LLVM 24's device
# code repeatable from build to build (cmake/RadAddPlugin.cmake, rad_hip_repeatable)
# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage, every
# device source compiled by ROCm's clang from a shadow of the ROCm tree whose libLLVM
# is the llvm stage's
# test docker/llvm-check.sh, then `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
# by ldd, copied into one directory and checked from inside a chroot
# runtime FROM scratch + rootfs. This is the image that ships
@@ -31,9 +37,10 @@
# docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance
#
# The ROCm userspace in the image must be one the host's amdgpu kernel driver supports. It is
# pinned to the version the serving host runs; move both together.
# pinned to the version the serving host runs; move both together. From ROCm 10 on, the dev image
# is published only as the -full tag.
ARG ROCM_VERSION=7.2.4
ARG ROCM_VERSION=10.1.0-full
ARG UBUNTU_VERSION=24.04
ARG FFMPEG_VERSION=8.1.3
ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
@@ -73,6 +80,52 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
&& echo "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}" \
> /opt/ffmpeg/share/doc/ffmpeg/SOURCE
# ------------------------------------------------------------------------------------------- llvm
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm
ARG JOBS=
# THE ONE LIBRARY OF THE HIP COMPILER THAT CHANGES. clang, lld and the offload tools all load
# lib/llvm/lib/libLLVM.so, so this stage rebuilds that file and nothing else: the source is ROCm's
# llvm-project at exactly the commit `clang --version` names (a different commit refuses, as does
# a patch that no longer applies), configured as ROCm's lib/cmake/llvm/LLVMConfig.cmake says it
# was -- Release without assertions, AMDGPU;SPIRV;X86, every component in the dylib, no RTTI or
# exceptions, zlib and zstd from rocm_sysdeps -- and compiled by ROCm's own clang and lld. With
# VOPD pairing off it produces ROCm's code byte for byte; docker/llvm-check.sh holds the build
# stage to that. A sparse, depth-one fetch: llvm/, the cmake/, libc/ and third-party/ directories
# its configure reads, and none of its tests or documentation.
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
git cmake ninja-build ca-certificates \
&& rm -rf /var/lib/apt/lists/*
COPY docker/llvm-vopd-pairing.patch /tmp/
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
set -e; L=/opt/rocm/lib/llvm; S=/opt/rocm/lib/rocm_sysdeps; \
rev=$($L/bin/clang --version | sed -n 's|.*ROCm/llvm-project.git \([0-9a-f]\{40\}\).*|\1|p'); \
[ -n "$rev" ] || { echo "llvm: no ROCm/llvm-project commit in: $($L/bin/clang --version | head -1)" >&2; exit 1; }; \
git init -q /llvm-project; cd /llvm-project; \
git remote add origin https://github.com/ROCm/llvm-project.git; \
git sparse-checkout set --no-cone '/*' '!/*/' /cmake/ /libc/ /llvm/ /third-party/ \
'!/llvm/test/' '!/llvm/unittests/' '!/llvm/docs/' '!/llvm/benchmarks/'; \
git fetch -q --depth 1 --filter=blob:none origin "$rev"; \
git checkout -q FETCH_HEAD; \
git apply /tmp/llvm-vopd-pairing.patch; \
cmake -G Ninja -S llvm -B /build-llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=OFF \
-DLLVM_TARGETS_TO_BUILD="AMDGPU;SPIRV;X86" -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON \
-DLLVM_DYLIB_COMPONENTS=all -DLLVM_ENABLE_RTTI=OFF -DLLVM_ENABLE_EH=OFF -DLLVM_ENABLE_FFI=OFF \
-DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_CURL=OFF \
-DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_TELEMETRY=ON -DLLVM_ENABLE_PLUGINS=ON \
-DLLVM_ENABLE_LIBPFM=OFF \
-DLLVM_ENABLE_ZLIB=FORCE_ON -DZLIB_INCLUDE_DIR=$S/include -DZLIB_LIBRARY=$S/lib/librocm_sysdeps_z.so.1 \
-DLLVM_ENABLE_ZSTD=FORCE_ON -Dzstd_INCLUDE_DIR=$S/include -Dzstd_LIBRARY=$S/lib/librocm_sysdeps_zstd.so.1 \
-DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF \
-DLLVM_INCLUDE_DOCS=OFF -DLLVM_BUILD_TOOLS=OFF -DLLVM_USE_LINKER=lld -DLLVM_PARALLEL_LINK_JOBS=2 \
-DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \
|| { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \
ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \
|| { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \
so=$(basename $(readlink -f $L/lib/libLLVM.so)); \
mkdir -p /out; cp /build-llvm/lib/$so /out/; \
rm -rf /build-llvm /llvm-project
# ------------------------------------------------------------------------------------------ build
FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build
ARG GPU_TARGETS=gfx1201
@@ -91,11 +144,41 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf && ldconfig
# ROCm's library directory is registered with the loader beside FFmpeg's because the ROCm 10 images
# register none, and the rootfs stage resolves every library the installed binaries load with ldd.
RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \
&& echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig
ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \
PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig
# THE HIP COMPILER: ROCm's clang, loading the llvm stage's libLLVM. ROCm's tools find their
# libraries through RPATHs relative to themselves -- $ORIGIN/../lib for libLLVM, which
# LD_LIBRARY_PATH cannot override, and $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib,
# which leave lib/llvm -- so the compiler lives in a shadow of the whole ROCm tree at the same
# depth: /opt/rocm-repeatable, every entry a link back into /opt/rocm except lib/llvm/bin, which
# holds real copies of the executables, and lib/llvm/lib's libLLVM, which is the rebuilt one.
# Only compiling uses it. The build names /opt/rocm with --rocm-path, so the headers and device
# libraries are ROCm's and the runtime path clang records in a linked plugin is /opt/rocm/lib;
# without it clang takes the tree it sits in as ROCm, and a loader that follows that path from
# the HIP runtime to comgr reaches the rebuilt libLLVM, which lacks the libstdc++ symbols ROCm's
# GCC-built one re-exports for comgr. The rootfs stage refuses any library resolved through it.
COPY --from=llvm /out/ /tmp/llvm-out/
RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \
so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \
[ -f /tmp/llvm-out/$so ] || { echo "the llvm stage built no $so" >&2; exit 1; }; \
mkdir -p $D/$L/lib; \
for e in $R/*; do n=${e##*/}; [ $n = lib ] || ln -s $e $D/$n; done; \
for e in $R/lib/*; do n=${e##*/}; [ $n = llvm ] || ln -s $e $D/lib/$n; done; \
for e in $R/$L/*; do n=${e##*/}; [ $n = bin ] || [ $n = lib ] || ln -s $e $D/$L/$n; done; \
cp -a $R/$L/bin $D/$L/; \
for e in $R/$L/lib/*; do n=${e##*/}; \
if [ $n = $so ]; then mv /tmp/llvm-out/$so $D/$L/lib/; \
elif [ -L $e ] && [ "$(readlink $e)" = $so ]; then ln -s $so $D/$L/lib/$n; \
else ln -s $e $D/$L/lib/$n; fi; \
done; \
rm -rf /tmp/llvm-out
WORKDIR /src
COPY . .
@@ -108,6 +191,9 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
-DCMAKE_INSTALL_PREFIX=/opt/radiance \
-DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \
"-DRAD_GPU_TARGETS=${GPU_TARGETS}" \
-DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \
-DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \
-DRAD_HIP_VOPD_REPEATABLE=ON \
&& cmake --build /build ${JOBS:+-j${JOBS}} \
&& DESTDIR=/stage cmake --install /build \
&& mkdir -p /stage/opt/radiance/share/radiance/recipes \
@@ -126,7 +212,8 @@ FROM build AS test
# rebuilt against the installed package, libr4d included -- is the development tree's to run
# (tests/oot_plugins.sh): it re-does this stage's whole compile.
RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
bash /src/docker/llvm-check.sh /build \
&& ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \
&& touch /build/host-tests-passed
# ----------------------------------------------------------------------------------------- rootfs
@@ -142,32 +229,32 @@ RUN apt-get update \
COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed
# Every library the binaries and plugins load, plus comgr, which the HIP runtime opens at run time
# and cannot initialise a device without, goes into one directory the dynamic loader searches by
# default: no ld.so.cache, no LD_LIBRARY_PATH. libdrm_amdgpu names the card from amdgpu.ids. A
# static busybox provides the health check's wget and a shell for `docker exec`; curl, jq and the
# CA bundle are hfget.sh's, and the bundle is ca-certificates' Mozilla set, which is the directory
# named for it in the license list. docker/licenses.sh
# traces each of those files to its package and records its license and source in
# /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing can
# depend on a library the image lacks.
# default: no ld.so.cache, no LD_LIBRARY_PATH. ROCm's own libdrm_amdgpu carries the card name table
# compiled in, so no amdgpu.ids is copied. A static busybox provides the health check's wget and a
# shell for `docker exec`; curl, jq and the CA bundle are hfget.sh's, and the bundle is
# ca-certificates' Mozilla set, which is the directory named for it in the license list.
# docker/licenses.sh traces each of those files to its package and records its license and source
# in /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing
# can depend on a library the image lacks.
RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/usr/share/libdrm $R/etc/ssl/certs $R/data $R/tmp; \
mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \
chmod 1777 $R/tmp; \
cp -a /stage/opt/radiance $R/opt/; \
elves=$(find $R/opt/radiance -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); \
strip --strip-unneeded $elves; \
libs=$(for f in $elves /usr/bin/curl /usr/bin/jq /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
| awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \
if echo "$libs" | grep /opt/rocm-repeatable/; then \
echo "these resolve through the compiler's shadow ROCm tree, not /opt/rocm" >&2; exit 1; fi; \
for lib in $libs; do \
case "$lib" in */ld-linux-x86-64.so.2) cp -L "$lib" $R/lib64/ ;; *) cp -L "$lib" $L/ ;; esac; \
done; \
cp -L /opt/rocm/lib/libamd_comgr.so.3 $L/; \
cp /usr/share/libdrm/amdgpu.ids $R/usr/share/libdrm/; \
cp /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \
cp /usr/bin/curl /usr/bin/jq $R/usr/bin/; \
cp /etc/ssl/certs/ca-certificates.crt $R/etc/ssl/certs/; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \
/usr/share/libdrm/amdgpu.ids /bin/busybox /usr/bin/curl /usr/bin/jq \
/usr/share/ca-certificates/mozilla; \
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 /bin/busybox \
/usr/bin/curl /usr/bin/jq /usr/share/ca-certificates/mozilla; \
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print) \
usr/bin/curl usr/bin/jq; do \
out=$(chroot $R /lib64/ld-linux-x86-64.so.2 --list "/$f" 2>&1) || { echo "$f: $out" >&2; exit 1; }; \
+10 -2
View File
@@ -14,8 +14,10 @@ sorted operand's decode kernel), mechkbfan (the token embedding in the pinned ho
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).
the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle
in the image with hfget.sh under its busybox), hazyumps (static YaRN for the Qwen rotary paths),
redxherring (--model taking a Hugging Face repo id) and zivius (LiquidAI's LFM2 and LFM2-VL and
d1's /v1/systemone, after the design of their Codeberg PR 50).
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
@@ -26,3 +28,9 @@ license text is in the file named beside each.
libquant/lq_ggml_*
nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT
cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE
core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the
LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their
fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid
AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use --
apply to it; the license is in core/server/LICENSE.lfm.
+10 -2
View File
@@ -37,7 +37,8 @@ curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/
## Run with Docker
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The
The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The
card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The
image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its
kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a
model from one of them:
@@ -62,7 +63,8 @@ in the clone (it needs `docker buildx` and tests the build as it goes). Then set
## Build from source
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it:
ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and
build in it:
```sh
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
@@ -72,6 +74,12 @@ cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards thi
cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/radiance/
```
With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its
LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ.
The Docker image builds its compiler with the fix and keeps the pairing, which is 1-3% faster on
the fp8 prefill GEMMs; a compiler that has the same fix is declared with
`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected.
## Run without Docker
```sh
+22 -1
View File
@@ -95,7 +95,8 @@ typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_
typedef void (*RadFiniFn) (void* instance);
/* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative
* return aborts the step and fails the requests in it, naming the kernel and the geometry. */
* return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch
* handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */
typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream);
/* ================================================================== the described launch */
@@ -597,6 +598,26 @@ typedef void (*RadPluginCloseFn)(void);
* before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */
typedef int (*RadKernelConcurrentFn)(int i);
/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE --
* its launches exchange data with the other ranks' cards, so the interconnect carries their bytes
* for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on
* the same links (weights it streams onto the card while the card computes) out of their way for
* that time. A plugin that does not export the symbol, or answers 0, has only the conventional
* `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`.
*
* 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the
* other ranks send this card for it has landed -- a kernel that reduces after the exchange has the
* link to spare for the rest of its run. The engine then hands each launch it holds the link for
* the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system
* scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on
* the device as it starts -- not the host in the launch call, where the hold has not taken effect
* yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was
* odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other
* success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not
* know the word is always safe. */
typedef int (*RadKernelCollectiveFn)(int i);
#define RAD_LINK_ENDED 1
/* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be
* plainly correct rather than fast. Three things follow, for any library that says so and for no
* other, whatever it is called:
+6 -1
View File
@@ -152,9 +152,14 @@ typedef struct RadVocabHeader {
int32_t bos, eos, eot, pad_id, unk, sep;
uint32_t add_bos, add_eos;
rad_stroff chat_template;
uint64_t reserved[4];
uint64_t flags; /* RAD_VOCAB_*; zero in a file written before the field existed */
uint64_t reserved[3];
} RadVocabHeader;
/* BPE: a pre-token that is already a vocabulary entry is emitted whole instead of merged
* (tokenizers' `ignore_merges`). LFM2's vocabulary sets it. */
enum { RAD_VOCAB_IGNORE_MERGES = 1u << 0 };
enum { RAD_TT_NORMAL = 1, RAD_TT_UNKNOWN = 2, RAD_TT_CONTROL = 3,
RAD_TT_USER_DEFINED = 4, RAD_TT_BYTE = 6 };
+36
View File
@@ -376,6 +376,42 @@ int rad_route_report(RadCtx* c, int layer, const RadRouting* r);
* `n_expert` -- the router then writes its own buffer and reports that. */
int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert);
/* THE NEXT-LAYER EXPERT PREFETCH, at decode. A routed layer names the next routed layer at its router
* input; the core applies that layer's router to this layer's input rows, takes the experts the next
* layer is likeliest to route that sit in the pinned host pool, and copies them onto the card while
* the rest of this layer runs. Just before the next layer's routed GEMMs it points their weight-table
* entries at the copies, where the copies have landed and the entries still name the pool slots they
* were made from. It changes no result: a copy holds the bytes of its slot. It is on where the
* placement keeps experts in a pinned pool and the device backend can spare a DMA engine for it, and
* a pass of more than 16 rows makes no prediction; the three calls are no-ops otherwise.
*
* `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four,
* e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs
* read them through weight tables; 0 where an expert has fewer or none. An expert is prefetched only
* where each of its weights is in exactly one table and all of them sit in one pool slot. The arrays
* must outlive the context; the core reads the routing counts only to rank and count, never to choose
* an expert's bytes. `layer` is the next layer's index as rad_route_report and
* rad_expert_prefetch_step name it; `router` is its router, [n_expert, n_embd] bf16. */
typedef struct RadPrefetchNext {
int layer;
rad_weight router;
int64_t n_expert, top_k;
int64_t n_parts;
const rad_weight* parts; /* [n_expert * n_parts] */
const int32_t* count_at; /* [n_expert]: where the expert's count is in the layer's routing
counts (rad_route_counts), -1 for nowhere; null when at its index */
} RadPrefetchNext;
/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another
* stream -- the block must not overwrite them before this layer's routed GEMMs. */
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
int64_t n_embd);
/* After this layer's routed down GEMM: the copies cross the link from here, under the next layer's
* attention rather than under this layer's own streamed experts. */
int rad_expert_prefetch_mark(RadCtx* c);
/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */
int rad_expert_prefetch_step(RadCtx* c, int layer);
/* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked
* outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability
* to move that weight while the pointer is live, so it is legal only within one issue. */
+19
View File
@@ -168,6 +168,11 @@ struct AttnGatedFP8 {
bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The pass's K and V into the cache and nothing else: no query, no attention, no output. What a
* pass that only leaves the layer's state behind asks for -- the MTP head's history pass over
* a prompt chunk with no row that drafts. The keys are the ones step() stores: the same
* projection, norm, rotation and store. */
void store_kv(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -470,6 +475,20 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
return RAD_OK;
}
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (!ext_in) nq_h.step(c, T);
if (op_fill) return; /* the attention-zero rank holds no heads to store */
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
+2
View File
@@ -90,6 +90,8 @@ struct MlpFP8 {
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (MoeFP8::step_rows says who asks). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
};
+49 -1
View File
@@ -387,6 +387,16 @@ struct MoeFP8 {
* `pff`, and down into the same `edn` rows the quantised down left zero. */
std::vector<int64_t> prot;
const char* prot_list = nullptr;
/* THE NEXT-LAYER EXPERT PREFETCH (rad_expert_prefetch). `xp_next` is the next routed layer, which
* this one predicts for at its router input -- the architecture links them once every layer is
* declared. `xp` is what this layer is to the one before it: its router, and each of the model's
* experts' unit -- the four handles its place's tables hold, and its place in the routing counts.
* Quantised experts only: a bf16 layer and the protected experts are not described, and a layer
* with no description is predicted for by nobody. */
const MoeFP8* xp_next = nullptr;
RadPrefetchNext xp{};
std::vector<rad_weight> xp_parts;
std::vector<int32_t> xp_count_at;
int64_t n_reg = 0;
/* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
@@ -461,6 +471,10 @@ struct MoeFP8 {
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers, which a pass that runs it for fewer rows
* than its batch has asks for: the MTP head's history pass, which reads the head's output only
* at its drafting rows. */
void step_rows(RadCtx* c, int64_t T) const;
/* One pass of at most `c.rows` tokens. */
void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const;
@@ -1469,6 +1483,29 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, by the model's expert number -- what the router ranks. */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
for (int64_t s = 0; s < n_reg; ++s) {
const int64_t e = c.expert_base + reg[(size_t)s];
if (e < 0 || e >= na) continue;
xp_parts[(size_t)(e * 4 + 0)] = w_gu[(size_t)s];
xp_parts[(size_t)(e * 4 + 1)] = w_gus[(size_t)s];
xp_parts[(size_t)(e * 4 + 2)] = w_dn[(size_t)s];
xp_parts[(size_t)(e * 4 + 3)] = w_dns[(size_t)s];
xp_count_at[(size_t)e] = (int32_t)s;
}
xp.layer = layer;
xp.router = w_router;
xp.n_expert = na;
xp.top_k = c.top_k;
xp.n_parts = 4;
xp.parts = xp_parts.data();
xp.count_at = xp_count_at.data();
}
return RAD_OK;
}
@@ -1516,6 +1553,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* sharing pool (see declare), so issuing it ahead of its declared position moves no byte. */
/* THE ROUTED ARM. */
/* THE NEXT ROUTED LAYER'S PREDICTION, from this router's input, read in place behind the router
* on the compute stream (rad_expert_prefetch). A failure there costs the prediction, nothing else. */
if (xp_next && xp_next->xp.n_parts > 0)
(void)rad_expert_prefetch(c_, &xp_next->xp, w.h.x, r0, rows, g.n_embd);
/* THE COUNTS GO STRAIGHT INTO THE CORE'S ROW for this layer when it keeps one, so the
* report at the end of step() hands them over with no copy -- otherwise a card-local blit
* a routed layer, a whole dependent dispatch for a kilobyte. */
@@ -1564,6 +1605,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* 2 * i + q, and each parity is its own pair of table operands; at four classes expert
* 4 * i + q, class q holding ceil((n_reg - q) / 4). */
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
/* The layer before predicted for this one: its copies go into the tables here, where they landed. */
(void)rad_expert_prefetch_step(c_, layer);
if (c.expert_bf16)
RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
@@ -1608,6 +1651,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
brows(w.edn, rows * k));
/* This layer's streamed experts are read: the next one's copies cross the link from here. */
(void)rad_expert_prefetch_mark(c_);
/* THE PROTECTED EXPERTS, over the trailing run of the offsets: their sorted rows are the
* ones the quantised down GEMM above zeroed as past its live count, and the down GEMM
* here writes them -- after it, which the shared `edn` orders. */
@@ -1733,7 +1778,10 @@ inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const {
}
inline void MoeFP8::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
step_rows(c_, batch->n_tok);
}
inline void MoeFP8::step_rows(RadCtx* c_, int64_t T) const {
for (int64_t r0 = 0; r0 < T; r0 += c.rows) {
const int64_t n = (T - r0 < c.rows) ? (T - r0) : c.rows;
pass(c_, T, r0, n);
+39 -32
View File
@@ -288,6 +288,24 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
{w.c}, {w.x});
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of the residual stream `x` -- before the feed-forward,
* which then runs over those rows alone. Through `hout`, which is dead from the fc's read to
* the norm's write, because a gather in place could overwrite a row another sequence has yet to
* read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
op_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -297,22 +315,6 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of `hout` -- where the lm_head reads a round's rows
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
* rather than at `rows`: it runs over one row a drafting sequence. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
@@ -435,27 +437,32 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES K AND V BEHIND, and they come from the
* block's input. The query, the attention, its output, the feed-forward, the norm and the
* lm_head compute the head's output, which only a drafting row reads -- and every prefill
* chunk but a prompt's last drafts nothing. `n_draft_out` is the batch's and the same on every
* rank, so a collective skipped here is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
attn.store_kv(c, batch);
return;
}
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
* attention above has stored them. The feed-forward, the norm and the lm_head compute the
* head's output, which only a drafting row reads -- and every prefill chunk but a prompt's
* last drafts nothing. `n_draft_out` is the batch's and the same on every rank, so a
* collective the feed-forward would run is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
mlp.step(c, batch);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
/* A history pass that drafts brings round 1's rows to the front first. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's output at any other row: the feed-forward, the norm and the lm_head
* would run over a whole prompt chunk for a handful of rows. So round 1's rows come to the
* front of `x` first, and everything after runs as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.x, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, L));
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.x), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hout, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hout, L), brows(w.x, L));
}
mlp.step_rows(c, L);
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
* whole: there is no row slice of it that means anything. */
+46 -34
View File
@@ -292,6 +292,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
false, false, kArNone, hc_attn.op_ar_write != 0));
if (src.qsa.qk_proj)
RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids), before the
* feed-forward, which then runs over them alone: gathered into `hin`, one row a drafting
* sequence in round order, and copied back to the front of `hw`. Two ops and not one because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The rotated expert input rides in this read, as it does on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
@@ -321,21 +337,6 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
* the mixer. Two ops and not one because a gather in place could overwrite a row another
* sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* ---- the head's own mixer: the connection with no write half, which collapses its wide
* stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
@@ -523,40 +524,51 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
hc_attn.read(c, T, 0, T);
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES THE HEAD'S STATE BEHIND: the K and V of its
* rows and the indexer's block keys and tail, all of which come from the block's input. The
* query, the indexer's scores and selection, the attention, its output and everything after
* compute the head's stream, which only a drafting row reads. Every prefill chunk but a
* prompt's last is such a pass. `n_draft_out` is the batch's and the same on every rank, so
* the collectives skipped here are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
}
/* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
* input is normed and quantised by the connection above, so `w.h` is already what it will be
* when the attention runs. */
qsa.step(c, attn.w.h, batch);
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
* written above. Everything below computes the head's stream, which only a drafting row
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
* but a prompt's last is such a pass, so on those the head costs its attention alone.
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
* are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
hc_attn.write(c, T, 0, T);
hc_mlp.read(c, T, 0, T);
mlp.step(c, batch);
hc_mlp.write(c, T, 0, T);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step. A history pass that drafts takes round 1's rows out of its own
* -- into the carry, and back to the front of `hw` for the mixer below. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's stream at any other row: the experts, their connection and the
* lm_head would run over a whole prompt chunk for a handful of rows. So round 1's rows come out
* of `hw` first -- gathered into `hin` and copied back to its front, two ops because a gather
* in place could overwrite a row another sequence has yet to read -- and everything after runs
* as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
} else if (r < depth) {
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
}
hc_mlp.read(c, L, 0, L);
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step; a history pass is round 1, followed by round 2 when the
* deployment drafts deeper. */
if (r < 0 ? depth > 1 : r < depth)
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
mixer.read(c, L, 0, L);
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
+51 -28
View File
@@ -154,6 +154,11 @@ struct QsaIndexer {
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
/* The block keys and the tail of the pass's rows and nothing else: no query, no score, no
* selection. What a pass that only leaves the layer's state behind asks for (see
* AttnGatedFP8::store_kv); the stores are the ones step() makes. */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -314,38 +319,16 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
return RAD_OK;
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
/* THE KEYS A PASS LEAVES BEHIND: the block keys of the blocks its rows complete and the tail of
* raw keys after them, out of the projection's raw-key head. False when the step carries no batch
* for the indexer's groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = qw; /* the raw-key head, after the query heads */
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
if (!bkb || !atb || !tlb) return;
if (!bkb || !tlb) return false;
/* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
* deployment speculates -- the manager gives every linear group a second copy then, because
* the kernel that needed one asked for it -- and this op wants the committed slot in every
@@ -389,6 +372,46 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
return true;
}
inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
proj.step(c_, in, w.qk, batch->n_tok);
(void)store_keys(c_, batch);
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
/* The keys first: the selection below reads the blocks they complete. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
/* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
* even though a block table is: both ops take `cu`, the block table stays the sequence's, and
+10
View File
@@ -0,0 +1,10 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(lfm2_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(lfm2_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm2_bf16.cpp)
+489
View File
@@ -0,0 +1,489 @@
/* lfm2_bf16 -- LiquidAI's LFM2 and LFM2-VL, bf16 weights and activations, one rank.
*
* ============================== THE SHAPE ==============================
*
* A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them -- d1-3B's
* schedule is irregular (attention at 2, 5, 9, 13, ...), so it is read, never derived:
*
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
* depthwise causal convolution of width `conv_L_cache` with no activation
* full_attention GQA with per-head RMS norms on q and k, NeoX rotary over the whole head
*
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
* plain RMSNorm -- `x_hat * w`, not Gemma's `1 + w` -- and the final one is `embedding_norm`. At
* d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
* vocabulary 128000 with the lm_head TIED to the embedding, conv width 3.
*
* LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
* projector (siglip2.h), declared when the container carries their weights and the deployment
* asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
* at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
* under `model`. Which one this is is read off the config (a VL checkpoint has a `text_config`),
* not off the model's name.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism: one rank. A 3B model has no need of a second card, and the vocabulary
* shard, the head split and the all-reduces would be code no deployment runs. A drafter, MoE
* (LFM2-8B-A1B), conv bias, or a checkpoint without the rotary: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include "siglip2.h"
#include <sstream>
#include <string>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Layer {
bool attention = false;
MlpBF16 mlp;
rad_weight w_norm = 0, w_in = 0, w_out = 0;
/* conv */
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention: w_in is q, these are k, v and the two head norms */
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0;
/* both */
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t width = 0; /* conv_L_cache: the convolution's taps */
rad_kvgroup kv_attn = 0, kv_conv = 0;
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
std::vector<Layer> layers;
/* LFM2-VL's images: the tower and the scatter of its rows over the embeddings. */
bool media = false;
Siglip2 vit{};
MediaRows mrows{};
};
static Model g_model[MAX_RANKS];
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
* and a text checkpoint does not. */
static const char* text_key(const RadModelMeta* m, const char* key) {
const std::string nested = std::string("text_config.") + key;
const char* v = rad_meta_gets(m, nested.c_str(), nullptr);
return v ? v : rad_meta_gets(m, key, nullptr);
}
static int64_t text_int(const RadModelMeta* m, const char* key, int64_t dflt) {
const char* v = text_key(m, key);
return v ? std::strtoll(v, nullptr, 10) : dflt;
}
static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
const char* v = text_key(m, key);
if (!v) return dflt;
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
}
/* `layer_types`, one word a layer. The container flattens the list space-separated. */
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
const char* s = text_key(m, "layer_types");
if (!s || !*s) {
fprintf(stderr, "radiance: lfm2: the container has no layer_types; this family's schedule "
"is irregular and is not derived\n");
return RAD_E_FORMAT;
}
std::istringstream in(s);
std::string kind;
while (in >> kind) {
if (kind != "conv" && kind != "full_attention") {
fprintf(stderr, "radiance: lfm2: layer_types[%zu] is '%s'; this plugin knows 'conv' "
"and 'full_attention'\n", out->size(), kind.c_str());
return RAD_E_UNSUPPORTED;
}
Layer l;
l.attention = kind == "full_attention";
out->push_back(l);
}
if ((int64_t)out->size() != n_layer) {
fprintf(stderr, "radiance: lfm2: layer_types names %zu layers and the model has %lld\n",
out->size(), (long long)n_layer);
return RAD_E_FORMAT;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
return RAD_E_UNSUPPORTED;
}
if (meta->n_expert > 0 || text_bool(meta, "conv_bias", false) ||
!text_bool(meta, "block_use_swiglu", true) || !text_bool(meta, "use_pos_enc", true)) {
fprintf(stderr, "radiance: lfm2_bf16 serves the dense SwiGLU model with rotary "
"attention and bias-free convolutions; this checkpoint is not that\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
/* The FFN width as stated, unless the config asks for LFM2's sizing rule (the 1.2B and
* smaller releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
RadModelMeta dims = *meta;
if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
int64_t ff = 2 * dims.n_ff / 3;
if (const char* mult = text_key(meta, "block_ffn_dim_multiplier")) {
const int64_t of = text_int(meta, "block_multiple_of", 256);
const double f = std::strtod(mult, nullptr);
if (!(f > 0.0) || of <= 0) return RAD_E_FORMAT;
ff = (int64_t)(f * (double)ff);
ff = of * ((ff + of - 1) / of);
}
dims.n_ff = ff;
}
RAD_ARCH_TRY(geom_from(m.g, &dims, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
m.width = text_int(meta, "conv_L_cache", 0);
if (m.width < 2 || m.width > 8) {
fprintf(stderr, "radiance: lfm2: conv_L_cache %lld is outside the 2..8 the convolution "
"kernels serve\n", (long long)m.width);
return RAD_E_UNSUPPORTED;
}
const char* pre = rad_meta_gets(meta, "text_config.num_hidden_layers", nullptr)
? "model.language_model" : "model";
/* ---- the two state groups: paged KV for the attention layers, and a rolling window of the
* convolution's last width-1 inputs (plus the speculative slack the manager adds) for the
* conv layers. The conv group's channels are n_head_kv * head_dim: one "head" of n_embd. */
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.kv_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = RAD_BF16;
cd.n_head_kv = 1;
cd.head_dim = g.n_embd;
cd.conv_width = m.width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
if (!m.kv_attn || !m.kv_conv) return RAD_E_INVAL;
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd});
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
/* ---- the vocabulary edges. The lm_head is tied in every release so far, and declared as a
* weight of its own anyway: the embedding lives in host memory (--embedding-placement) and the
* head on the card, and a kernel may ask the head for a layout the lookup does not read. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("%s.embed_tokens.weight", pre)));
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* The encoder's rows, over the lookup: one rank, so nothing is reduced after it. */
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
MlpBF16::Wire mw{};
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
uint32_t dtype) {
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
};
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (L.attention) {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
const char* a = "%s.layers.%d.self_attn.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
nm.ckpt(a, pre, l, "q_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
nm.ckpt(a, pre, l, "k_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt(a, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
* T * heads such rows. */
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
"neox"), {m.b_q}, {m.b_q});
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"), {m.b_k}, {m.b_k});
/* attn_paged before kv_store: the cache's block size is read off the resolved
* attention kernel. */
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
RAD_INT("causal", 1), RAD_INT("window", 0),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_q}, {m.b_attn});
L.op_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, m.kv_attn)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
const char* c = "%s.layers.%d.conv.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as the gated delta net's conv1d is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
L.op_gate_in = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx}, {m.b_conv_in});
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_conv)),
{m.b_conv_in}, {m.b_conv_out});
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
}
L.op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x, m.b_h}, {m.b_x});
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
}
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
* lm_head reads. */
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_x}, {m.b_hout});
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout);
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(m.w_lm_head)),
{m.b_hout}, {m.b_logits});
/* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
int64_t n_attn = 0;
for (const Layer& L : m.layers) n_attn += L.attention ? 1 : 0;
rad_note(b, "lfm2: %lld layers, %lld attention + %lld short convolution of width %lld; "
"%lld heads over %lld at head_dim %lld, ffn %lld, vocab %lld",
(long long)g.n_layer, (long long)n_attn, (long long)(g.n_layer - n_attn),
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
return RAD_OK;
}
/* THE CONVOLUTION IS ISSUED ONCE PER HALF OF THE STEP, as the PLE's and the gated delta net's
* are: the decode rows [0, D) with `num_accepted`, which leaves the window in the layout a
* partly rejected verify reads back from, and the prefill chunks [D, S) without it, each leaving
* its tail at offset zero. `has_init` is `ctx_lens`: a sequence with tokens behind it has a
* history. The per-sequence arrays of the prefill half move to `+ D`; the token operands stay at
* their base, because the kernel reads rows at the absolute offsets in `cu`. */
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
const int32_t* idx = cv ? cv->state_index : nullptr;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t P = S - D;
if (D > 0)
RAD_ISSUE_N(c, L.op_conv, DT,
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
brows(m.b_conv_out, DT));
if (P > 0)
RAD_ISSUE_N(c, L.op_conv, T,
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
praw(idx ? idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
brows(m.b_conv_out, T));
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent ||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
rad_step_fail(c, "lfm2_bf16: this step asks for an encoder, a draft pass or media rows, "
"and the program declares none of them");
return;
}
/* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
const int64_t T = batch->n_tok, n = g.n_embd;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
m.mrows.step(c, batch, m.b_x, T);
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (L.attention) {
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
brows(m.b_q, T));
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
brows(m.b_k, T));
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(m.kv_attn, l));
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(m.kv_attn, l),
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
kv ? kv->block_table_pitch : 0),
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(m.b_attn, T));
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
brows(m.b_conv_in, T));
conv_step(m, L, c, batch, l);
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
}
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
L.mlp.step(c, batch);
}
/* The lm_head runs on the rows the sampler asked for and on nothing else; a prefill chunk
* that finishes no sequence issues none of it. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out));
}
}
} /* namespace lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
#endif
+329
View File
@@ -0,0 +1,329 @@
/* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the patch embedding, a linear layer over a patch
* row (y, x, channel)
* x += pos_table resampled to each segment's grid torch's antialiased half-pixel bilinear
* (grid_embed_aa), rounded before the add
* depth times:
* x += out(attn(qkv(LN1(x)))) full attention within a segment (one tile or the
* thumbnail), no rotary
* x += fc2(gelu_tanh(fc1(LN2(x))))
* y = post_LN(x)
* out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width])))) the projector
*
* which is transformers' Siglip2VisionModel (no pooling head) followed by Lfm2VlMultiModalProjector.
* The projector's pixel unshuffle is a VIEW here: the processor stores each segment's patches in
* merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
* consecutive rows, dy then dx -- the order the unshuffle concatenates them in. The tower itself
* does not care about the order: attention within a segment is permutation-equivariant and every
* other layer is per patch, and the position table is resampled at each patch's own (row, column).
*
* q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
* GEMM; the attention reads the three as column slices.
*
* Replicated, per-request weights and pass-sized activations, as arch/common/rad_block_vit.h's
* tower: see the notes there.
*/
#ifndef LFM2_SIGLIP2_H
#define LFM2_SIGLIP2_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Siglip2 {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0;
int64_t head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0;
float eps = 1e-6f;
bool proj_norm = false, on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_pos = 0, pn_w = 0, pn_b = 0;
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
rad_op op_patch = 0, op_pos = 0, op_post = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mn = 0, b_mf = 0;
rad_buf b_out = 0;
/* A tower to declare: the container is an LFM2-VL one, whose vision_config is SigLIP2's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
/* Input patches an output row: the projector's unshuffle. */
static int64_t merge_of(const RadModelMeta* m) {
const int64_t d = rad_meta_geti(m, "downsample_factor", 0);
return d * d;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
const int64_t npos = rad_meta_geti(m, "vision_config.num_patches", 0);
merge = rad_meta_geti(m, "downsample_factor", 0);
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
side = (int64_t)std::llround(std::sqrt((double)npos));
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || merge <= 0 ||
proj_hidden <= 0 || side <= 0 || side * side != npos || width % heads || chans != 3) {
fprintf(stderr, "radiance: lfm2: the container's SigLIP2 vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"positions %lld, channels %lld; downsample_factor %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)npos, (long long)chans, (long long)merge,
(long long)proj_hidden);
return RAD_E_INVAL;
}
/* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, and a
* checkpoint that ships a head would load weights nothing runs. Refused by name. */
if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
"not read and this plugin does not serve\n");
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
if (std::strcmp(act, "gelu_pytorch_tanh") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: lfm2: the tower's activation '%s' and the projector's '%s' are "
"not gelu_pytorch_tanh and gelu, which is what this plugin serves\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
const char* pb = rad_meta_gets(m, "projector_bias", "true");
if (std::strcmp(pb, "true") && std::strcmp(pb, "1")) {
fprintf(stderr, "radiance: lfm2: a projector without biases is not served\n");
return RAD_E_UNSUPPORTED;
}
proj_norm = !std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "true") ||
!std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "1");
head_dim = width / heads;
patch_dim = chans * patch * patch;
const int64_t mm = merge * merge, mw = mm * width;
P = ctx->max_enc_patches;
/* The longest segment attention sees: a tile or the largest thumbnail, which the processor
* keeps within max_num_patches. A bound that picks the attention kernel's block height, so it
* is the real one in a sizing declare too. */
const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
rad_meta_geti(m, "max_num_patches", P));
const int64_t max_seg = std::min<int64_t>(P, seg);
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* tw = "model.vision_tower.vision_model.";
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("%sembeddings.patch_embedding.weight", tw),
{ width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%sembeddings.patch_embedding.bias", tw),
{ width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%sembeddings.position_embedding.weight", tw),
{ npos, width }, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
const char* e = "%sencoder.layers.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, tw, li, "layer_norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, tw, li, "layer_norm1.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, tw, li, "layer_norm2.bias"), { width }, g);
/* q, k, v fused at convert: one GEMM a layer. */
const char* qw = nm.f("v.blk.%d.qkv.weight", li);
const char* qb = nm.f("v.blk.%d.qkv.bias", li);
if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.k_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.v_proj.weight") }) < 0 ||
map_concat(b, qb, { nm.ckpt(e, tw, li, "self_attn.q_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.k_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, qw, RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
l.qkv_b = decl_w(b, qb, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, tw, li, "self_attn.out_proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, tw, li, "self_attn.out_proj.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, tw, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, tw, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, tw, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, tw, li, "mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
pn_w = bw(nm.f("v.post_norm.weight"), nm.ckpt("%spost_layernorm.weight", tw), { width }, grp_model());
pn_b = bw(nm.f("v.post_norm.bias"), nm.ckpt("%spost_layernorm.bias", tw), { width }, grp_model());
const char* pj = "model.multi_modal_projector.";
if (proj_norm) {
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("%slayer_norm.weight", pj), { mw }, grp_model());
mn_b = bw(nm.f("v.proj.norm.bias"), nm.ckpt("%slayer_norm.bias", pj), { mw }, grp_model());
if (!mn_w || !mn_b) return RAD_E_INVAL;
}
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("%slinear_1.weight", pj), { proj_hidden, mw }, grp_model());
m1_b = bw(nm.f("v.proj.fc1.bias"), nm.ckpt("%slinear_1.bias", pj), { proj_hidden }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("%slinear_2.weight", pj), { n_embd, proj_hidden }, grp_model());
m2_b = bw(nm.f("v.proj.fc2.bias"), nm.ckpt("%slinear_2.bias", pj), { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
/* ---- activations. `mh` is the post-norm's output declared at the MERGED width: the norm
* writes P rows of `width` and the projector reads P/mm rows of mm * width, the same bytes. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mw });
if (proj_norm) b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || (proj_norm && !b_mn) || !b_mf ||
!b_out)
return RAD_E_INVAL;
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_aa",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, width, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm(P, ff, width, "gelu_tanh", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, lnorm(P, width, pn_w, pn_b), { b_x }, { b_mh });
if (proj_norm) op_mln = rw(b, lnorm(R, mw, mn_w, mn_b), { b_mh }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, "gelu", m1_w, m1_b), { proj_norm ? b_mn : b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, "none", m2_w, m2_b), { b_mf }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "SigLIP2 tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"%lld x %lld position table; projector %lld -> %lld -> %lld%s; %lld patches a "
"pass -> %lld rows",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)side, (long long)side,
(long long)mw, (long long)proj_hidden, (long long)n_embd,
proj_norm ? " behind a layer norm" : "", (long long)P, (long long)R);
}
on = true;
return RAD_OK;
}
inline void Siglip2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || batch->enc != RAD_MM_IMAGE || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "lfm2: an encoder pass this program's SigLIP2 tower cannot serve: no "
"tower, not images, more patches than it was declared for, or not whole "
"merged rows");
return;
}
/* The patches, their coordinates -- a dense [4, P] of row, column, segment height and width,
* which is what the position resample reads -- and the segment boundaries. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.attn, Pn,
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The post-norm writes Pn rows of `width` into a buffer declared at the merged width: the
* same bytes the projector reads as Pn/mm rows -- the pixel unshuffle. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
if (proj_norm)
RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(proj_norm ? b_mn : b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b),
RAD_NONE, brows(b_mf, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
brows(b_out, Rn));
}
} /* namespace lfm2_bf16 */
#endif /* LFM2_SIGLIP2_H */
+4
View File
@@ -1097,6 +1097,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, mlp_fold, mlp_add,
mlp_ar_in, mlp_ar_out));
}
#if QWEN35_MOE
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp;
#endif
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
+3
View File
@@ -1232,6 +1232,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (size_t l = 0; l + 1 < m.layers.size(); ++l) m.layers[l].mlp.xp_next = &m.layers[l + 1].mlp;
/* ---- the 97th connection. No write half, no fp8 twin: it produces the one hidden state the
* lm_head reads, as a bf16 input. Its `hc_norm` is what a pre-norm model calls the
* final norm -- this checkpoint has no `model.language_model.norm.weight` at all. */
+22
View File
@@ -32,6 +32,8 @@
# the tree, where a plugin installs beside the engine under the same prefix;
# radiance-config.cmake sets it to the found installation's home, so a plugin
# built out of tree installs where that engine's loader scans.
# RAD_HIP_VOPD_REPEATABLE ON when the HIP compiler's VOPD pairing is repeatable; unset is OFF,
# which turns the pairing off on LLVM 24 (rad_hip_repeatable, below).
# For CMAKE_INSTALL_DATADIR, below. Idempotent, and included here rather than left to the includer
# because this file is what needs it: a consumer project has no reason to have included it, and the
@@ -154,6 +156,25 @@ function(rad_add_plugin name kind)
endif()
endfunction()
# REPEATABLE DEVICE CODE ON LLVM 24. ROCm 10.1's clang (AMD clang 24) does not compile the same
# source to the same code twice. Its post-RA scheduler pairs VALU instructions for dual issue
# (VOPD), and the pairing pass (GCNVOPDUtils.cpp) caches each load's transitive load dependencies;
# fusing a pair adds edges behind that cache, and which entries were cached before a fusion
# follows the iteration order of a pointer-keyed set -- heap addresses. So every compile can pair
# differently: r4d_hc_bf16.hip came out with a different .text on each of three builds, a kernel's
# speed depends on which build it came from, and no comparison between two builds can be trusted.
# LLVM 22 (ROCm 7.2) pairs without that cache and is repeatable.
#
# The image builds its compiler's libLLVM with the cache dropped after every fusion
# (docker/llvm-vopd-pairing.patch) and says so with RAD_HIP_VOPD_REPEATABLE=ON. Any other LLVM 24
# has the pairing turned off: repeatable, at a price -- 1.4 to 3.5% on the fp8 prefill tiles.
function(rad_hip_repeatable tgt)
if(CMAKE_HIP_COMPILER_ID STREQUAL "Clang" AND CMAKE_HIP_COMPILER_VERSION VERSION_GREATER_EQUAL 24
AND NOT RAD_HIP_VOPD_REPEATABLE)
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:-mllvm=-amdgpu-enable-vopd=false>)
endif()
endfunction()
# Mark a target's device sources as HIP and pin the architecture. -ffp-contract=off is mandatory
# for any quantised cross-rank op: two ranks see the two dequantised products in the opposite order
# and contracting either into an FMA makes them disagree by ~1 ULP, which breaks the
@@ -196,6 +217,7 @@ function(rad_hipify tgt)
target_compile_options(${tgt} PRIVATE $<$<COMPILE_LANGUAGE:HIP>:--no-offload-compress>)
target_link_options(${tgt} PRIVATE $<$<LINK_LANGUAGE:HIP>:--no-offload-compress>)
target_link_libraries(${tgt} PRIVATE ${RAD_HIP_RUNTIME})
rad_hip_repeatable(${tgt})
endfunction()
# Narrow RAD_GPU_TARGETS to the architectures ONE kernel library actually serves. A library states
+14 -1
View File
@@ -3,7 +3,7 @@
#
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS so that adding a file to a component
# does not mean editing a file another component owns. Re-run cmake if a new file does not appear.
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm)
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag)
set(RAD_CORE_SRC "")
foreach(d ${RAD_CORE_DIRS})
@@ -40,6 +40,15 @@ endif()
if(RAD_HIP_FOUND)
target_compile_definitions(rad_core PUBLIC RAD_HAVE_HIP=1)
target_link_libraries(rad_core PUBLIC ${RAD_HIP_RUNTIME} ${RAD_HSA_RUNTIME})
# AN EXECUTABLE RUNS THE ROCm IT WAS BUILT AGAINST. The runtime is linked by its full path, but the
# HIP driver reports that directory among its implicit link directories, so CMake writes no RPATH
# for it: the engine, the tools and the tests loaded whichever libamdhip64.so.7 the system's loader
# cache names, and a tree built against a second ROCm beside /opt/rocm ran /opt/rocm's runtime
# under its own kernels. A linker flag and not CMake's RPATH, because install rewrites CMake's, and
# rewriting it beside the entry ROCm 10's clang gives a shared library left an empty element -- the
# current directory -- in the installed plugin.
get_filename_component(RAD_HIP_LIBDIR "${RAD_HIP_RUNTIME}" DIRECTORY)
target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_HIP_LIBDIR}")
# THE AQL BACKEND'S OWN KERNELS: the copies and fills it dispatches for rad_memcpy_async and
# rad_memset_async.
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/device/aql_blit.hip)
@@ -50,6 +59,9 @@ if(RAD_HIP_FOUND)
# WEIGHT-TABLE ENTRIES WRITTEN IN STREAM ORDER, their values carried in the arguments (runtime/wtab.h).
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/wtab.hip PROPERTIES LANGUAGE HIP)
# THE NEXT-LAYER EXPERT PREFETCH's prediction, plan and table patches (runtime/xprefetch.h).
target_sources(rad_core PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip)
set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/runtime/xprefetch.hip PROPERTIES LANGUAGE HIP)
# THE CORE'S OWN KERNELS ARE BUILT FOR EVERY AMD GPU FAMILY, not only for the cards this build
# targets. They are what every copy and fill on a card runs, so an engine without a code object
# for a card cannot start on it -- whatever kernel plugin is installed for that card, and a plugin
@@ -60,6 +72,7 @@ if(RAD_HIP_FOUND)
gfx9-generic gfx9-4-generic gfx10-1-generic gfx10-3-generic gfx11-generic gfx12-generic)
list(REMOVE_DUPLICATES RAD_CORE_GPU_TARGETS)
set_target_properties(rad_core PROPERTIES HIP_ARCHITECTURES "${RAD_CORE_GPU_TARGETS}")
rad_hip_repeatable(rad_core)
# EVERY EXECUTABLE THAT LINKS THE CORE EXPORTS THE HIP ENTRY POINTS THE BACKEND DEFINES. A kernel
# plugin is dlopen'ed and its hipLaunchKernel binds to the first definition in the global scope,
# which is the executable's only if the executable exports it. Without this a plugin would launch
+13 -3
View File
@@ -19,10 +19,20 @@ namespace rad {
/* One Registry for the life of the process. A Resolved, a Band and a KernelRow all point into a
* plugin's static tables, and the Program outlives the call that built it, so the registry cannot
* be a local. registry.h says the same thing about the engine. */
* be a local. registry.h says the same thing about the engine.
*
* NEVER DESTROYED, because exit destroys in the wrong order for it. A function-local static is
* constructed before the first plugin is loaded, so its destructor runs AFTER every plugin's own
* static destructors -- and closing from there calls each instance's fini into plugin state that
* no longer exists. libr4d's router keeps its per-device counter blocks in a global map; fini
* looked up and erased a node of the destroyed map, a double free that glibc reported as
* "corrupted size vs. prev_size" or "free(): invalid pointer" on whichever exit the heap layout
* exposed it. A caller that needs the finis to run closes the registry itself while the plugins
* are alive, as Engine's shutdown does; at exit the process is ending and what the instances
* hold goes with it. */
Registry& rad_tools_registry() {
static Registry r;
return r;
static Registry* r = new Registry();
return *r;
}
/* ------------------------------------------------------------------ the reference-kernel gate */
+196 -1
View File
@@ -9,6 +9,7 @@
#include "format/rope_override.h"
#include "sample/host_ref.h"
#include "server/oai.h"
#include "diag/diag.h"
#include <nlohmann/json.hpp>
@@ -755,11 +756,16 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("unknown option '%s'", a.c_str());
return RAD_E_INVAL;
}
/* WHERE EACH OPTION CAME FROM, for the startup report (core/diag/diag.h): every branch
* above that returned refused the option, so reaching here is the option taken. Under the
* table's spelling, so an alias reports as the option it is. */
c->given[S("--gpu-headroom") ? "--gpu-headroom-mib" : a] = "command line";
}
if (c->radiance_home.empty()) {
const char* h = getenv("RADIANCE_HOME");
c->radiance_home = h ? h : RAD_DEFAULT_HOME;
if (h) c->given["--radiance-home"] = "environment (RADIANCE_HOME)";
}
if (c->kernel_hierarchy.empty()) {
/* RADIANCE_KERNELS, ahead of the built-in default.
@@ -769,7 +775,10 @@ int config_parse(int argc, char** argv, Config* c) {
* plugin with rad-kbench or rad-tune has no way to serve with it short of editing every
* launcher's command line. Same spelling, same separator. */
const char* e = getenv("RADIANCE_KERNELS");
if (e && *e) c->kernel_hierarchy = split_commas(e);
if (e && *e) {
c->kernel_hierarchy = split_commas(e);
c->given["--kernels"] = "environment (RADIANCE_KERNELS)";
}
}
/* AND THERE IS NO BUILT-IN DEFAULT, deliberately. Naming a library here -- the RDNA4 one, say
* -- would make the core carry the name of one card's kernels, and on any other machine that
@@ -850,4 +859,190 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_OK;
}
/* ------------------------------------------------------------------ the startup report's rows */
namespace {
std::string onoff(bool b) { return b ? "on" : "off"; }
std::string num(int64_t v) { return std::to_string(v); }
std::string or_none(const std::string& s, const char* none) { return s.empty() ? std::string(none) : s; }
std::string fnum(double v) {
char b[48];
snprintf(b, sizeof b, "%g", v);
return b;
}
template <class T>
std::string opt(const std::optional<T>& v, const char* unset) {
if (!v) return unset;
if constexpr (std::is_floating_point_v<T>) return fnum((double)*v);
else return std::to_string(*v);
}
std::string joined(const std::map<std::string, std::string>& m, const char* sep) {
std::string s;
for (const auto& [k, v] : m) s += (s.empty() ? "" : ",") + k + sep + v;
return s.empty() ? "none" : s;
}
using Show = std::string (*)(const Config&);
struct ShowRow { const char* flag; Show show; };
/* HOW EACH OPTION'S VALUE IS SHOWN, one entry an option of the table above, under the same
* spelling. config_rows walks the TABLE, so an option missing here still appears in the report --
* as "(not shown)" -- and diag_test fails naming it. A sentinel a field uses for "resolved at
* startup" (-1, 0, empty) is shown as what it means; the engine's decisions replace it with the
* value it resolved to. */
const ShowRow kShow[] = {
{ "--model", [](const Config& c) { return c.model; } },
{ "--download-dir", [](const Config& c) { return or_none(c.download_dir, "the XDG cache (~/.cache/radiance/hf)"); } },
{ "--radiance-home", [](const Config& c) { return c.radiance_home; } },
{ "--kernels", [](const Config& c) {
std::string s;
for (const std::string& k : c.kernel_hierarchy) s += (s.empty() ? "" : ",") + k;
return or_none(s, "every library found"); } },
{ "--tp", [](const Config& c) { return num(c.tp); } },
{ "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } },
{ "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } },
{ "--p2p", [](const Config& c) {
return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } },
{ "--max-num-batched-tokens", [](const Config& c) { return num(c.max_tok); } },
{ "--busy-prefill-chunk", [](const Config& c) {
return c.busy_prefill_chunk < 0 ? std::string("auto")
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
{ "--max-model-len", [](const Config& c) {
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-host-mib", [](const Config& c) {
return c.prefix_cache_host_mib ? num(c.prefix_cache_host_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-dir", [](const Config& c) { return or_none(c.prefix_cache_dir, "none"); } },
{ "--prefix-cache-disk-mib", [](const Config& c) {
return c.prefix_cache_disk_mib ? num(c.prefix_cache_disk_mib) : std::string("0 (off)"); } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
{ "--checkpoint-slots", [](const Config& c) { return num(c.checkpoint_slots); } },
{ "--no-prefix-cache", [](const Config& c) {
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
{ "--host", [](const Config& c) { return c.host; } },
{ "--port", [](const Config& c) { return num(c.port); } },
/* A SECRET IS NOT A VALUE. Whether one is set is what a reader of the log needs. */
{ "--api-key", [](const Config& c) { return std::string(c.api_key.empty() ? "not set" : "set"); } },
{ "--served-model-name", [](const Config& c) { return or_none(c.served_model_name, "the container's name"); } },
{ "--mm-max-patches", [](const Config& c) { return c.mm_max_patches < 0 ? std::string("auto") : num(c.mm_max_patches); } },
{ "--generation-config", [](const Config& c) { return or_none(c.generation_config, "none"); } },
{ "--override-chat-template", [](const Config& c) { return or_none(c.override_chat_template, "none (the container's)"); } },
{ "--temp", [](const Config& c) { return c.sample_temp < 0 ? std::string("unset") : fnum(c.sample_temp); } },
{ "--top-k", [](const Config& c) { return c.sample_top_k < 0 ? std::string("unset") : num(c.sample_top_k); } },
{ "--top-p", [](const Config& c) { return c.sample_top_p < 0 ? std::string("unset") : fnum(c.sample_top_p); } },
{ "--min-p", [](const Config& c) { return c.sample_min_p < 0 ? std::string("unset") : fnum(c.sample_min_p); } },
{ "--reasoning-effort", [](const Config& c) { return or_none(c.reasoning_effort, "the template's default"); } },
{ "--reasoning-effort-map", [](const Config& c) { return joined(c.reasoning_effort_map, "="); } },
{ "--thinking-token-budget", [](const Config& c) {
return c.thinking_token_budget < 0 ? std::string("none") : num(c.thinking_token_budget); } },
{ "--typical-p", [](const Config& c) { return opt(c.sample_typical_p, "the request default"); } },
{ "--presence-penalty", [](const Config& c) { return opt(c.sample_pres_penalty, "the request default"); } },
{ "--frequency-penalty", [](const Config& c) { return opt(c.sample_freq_penalty, "the request default"); } },
{ "--repetition-penalty", [](const Config& c) { return opt(c.sample_rep_penalty, "the request default"); } },
{ "--repeat-last-n", [](const Config& c) { return opt(c.sample_penalty_last_n, "the request default"); } },
{ "--dry-multiplier", [](const Config& c) { return opt(c.sample_dry_multiplier, "the request default"); } },
{ "--dry-base", [](const Config& c) { return opt(c.sample_dry_base, "the request default"); } },
{ "--dry-allowed-length", [](const Config& c) { return opt(c.sample_dry_allowed_length, "the request default"); } },
{ "--dry-penalty-last-n", [](const Config& c) { return opt(c.sample_dry_penalty_last_n, "the request default"); } },
{ "--dry-sequence-breakers", [](const Config& c) {
/* Replaced, not thrown on, like every dump in the report: the strings reach Config from
* outside the engine, and a serialiser that throws would end a startup that is otherwise
* sound over one line of its log. */
return c.sample_dry_seq_breakers
? nlohmann::json(*c.sample_dry_seq_breakers)
.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace)
: std::string("the request default"); } },
{ "--xtc-probability", [](const Config& c) { return opt(c.sample_xtc_probability, "the request default"); } },
{ "--xtc-threshold", [](const Config& c) { return opt(c.sample_xtc_threshold, "the request default"); } },
{ "--default-max-tokens", [](const Config& c) {
return c.default_max_tokens > 0 ? num(c.default_max_tokens)
: std::string("auto (what the context leaves after the prompt)"); } },
{ "--max-tokens-cap", [](const Config& c) { return c.max_tokens_cap > 0 ? num(c.max_tokens_cap) : std::string("none"); } },
{ "--max-n", [](const Config& c) {
return c.max_n > 0 ? num(c.max_n)
: std::string("auto (the larger of 8 and --max-num-seqs)"); } },
{ "--max-queued-requests", [](const Config& c) {
return c.max_queued_requests > 0 ? num(c.max_queued_requests)
: std::string("auto (8 x --max-num-seqs)"); } },
{ "--max-stop-strings", [](const Config& c) { return num(c.max_stop_strings); } },
{ "--max-stop-bytes", [](const Config& c) { return num(c.max_stop_bytes); } },
{ "--chat-template-kwargs", [](const Config& c) { return joined(c.chat_template_kwargs, "="); } },
{ "--reasoning-format", [](const Config& c) { return c.reasoning_format; } },
{ "--http-threads", [](const Config& c) {
return c.http_threads > 0 ? num(c.http_threads)
: std::string("auto (one a hardware thread, at least 4)"); } },
{ "--read-timeout", [](const Config& c) { return num(c.http_read_timeout_s) + " s"; } },
{ "--write-timeout", [](const Config& c) { return num(c.http_write_timeout_s) + " s"; } },
{ "--keep-alive-timeout", [](const Config& c) { return num(c.http_keep_alive_timeout_s) + " s"; } },
{ "--max-body-mib", [](const Config& c) { return num(c.http_max_body_mib); } },
{ "--retry-after", [](const Config& c) { return num(c.retry_after_s) + " s"; } },
{ "--no-cors", [](const Config& c) {
return std::string(c.cors ? "not given: CORS headers sent" : "no CORS headers"); } },
{ "--image-min-pixels", [](const Config& c) { return opt(c.image_min_pixels, "the container's"); } },
{ "--image-max-pixels", [](const Config& c) { return opt(c.image_max_pixels, "the container's"); } },
{ "--video-min-pixels", [](const Config& c) { return opt(c.video_min_pixels, "the container's"); } },
{ "--video-max-pixels", [](const Config& c) { return opt(c.video_max_pixels, "the container's"); } },
{ "--video-fps", [](const Config& c) { return opt(c.video_fps, "the container's"); } },
{ "--video-min-frames", [](const Config& c) { return opt(c.video_min_frames, "the container's"); } },
{ "--video-max-frames", [](const Config& c) { return opt(c.video_max_frames, "the container's"); } },
{ "--video-max-frame-tokens", [](const Config& c) { return opt(c.video_max_frame_tokens, "the container's"); } },
{ "--image-tokens", [](const Config& c) { return opt(c.image_tokens, "the container's"); } },
{ "--max-source-pixels", [](const Config& c) { return opt(c.max_source_pixels, "67108864"); } },
{ "--kld-record", [](const Config& c) { return or_none(c.kld_record, "none"); } },
{ "--kld-ref", [](const Config& c) { return or_none(c.kld_ref, "none"); } },
{ "--kld-corpus", [](const Config& c) { return or_none(c.kld_corpus, "none"); } },
{ "--kld-out", [](const Config& c) { return or_none(c.kld_out, "none"); } },
{ "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } },
{ "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } },
{ "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } },
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
{ "--live", [](const Config& c) { return onoff(c.live_view); } },
{ "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } },
{ "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } },
};
} /* namespace */
namespace diag {
std::vector<ConfigRow> config_rows(const Config& c) {
std::vector<ConfigRow> out;
for (const Flag& f : g_flags) {
/* --help asks for this text and serves nothing; it is not a setting. */
if (!std::strcmp(f.name, "--help")) continue;
ConfigRow r;
r.flag = f.name;
r.value = "(not shown)";
for (const ShowRow& s : kShow)
if (!std::strcmp(s.flag, f.name)) { r.value = s.show(c); break; }
auto g = c.given.find(f.name);
r.source = g != c.given.end() ? g->second : "default";
out.push_back(std::move(r));
}
return out;
}
std::vector<std::string> config_option_names() {
std::vector<std::string> out;
for (const Flag& f : g_flags)
if (std::strcmp(f.name, "--help")) out.push_back(f.name);
return out;
}
} /* namespace diag */
} /* namespace rad */
+974 -2
View File
File diff suppressed because it is too large. Load diff
+108
View File
@@ -58,6 +58,79 @@ struct RadCopyRange {
extern "C" int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s);
/* ONE COPY OF A LIST: `bytes` from `src` to `dst`, both absolute addresses. */
struct RadCopySeg {
const void* src;
void* dst;
int64_t bytes;
};
/* MANY UNRELATED COPIES, IN LIST ORDER ON THE STREAM, on the card's DMA engine where the backend
* has one. The list is read at the call, so it need not outlive it; the bytes it names do, like
* any copy's. A backend without a DMA engine copies the segments one by one, in order. An empty
* list puts nothing on the stream, and readies what the backend's first list on that stream's card
* would otherwise set up, so a caller can take that cost at bring-up.
*
* It exists for bulk copies across the link while the card computes -- the prefill stager's,
* a layer's pooled experts a call. A copy as a kernel holds a compute unit's slot for as long as
* the link takes, and waits for one to free up at every launch: beside kernels that keep every unit
* busy, 1.3 MB copies from pinned host memory ran at 2.3 GB/s as kernels and at 28.7 GB/s -- the
* link -- on the DMA engine, which cost those kernels nothing (aql.cpp, "the DMA lane").
*
* RAD_COPY_YIELD makes the list give way to the card's collectives: it waits, between pieces of
* about a megabyte, while a stream of that card holds the link (rad_link_hold). */
#define RAD_COPY_YIELD 1u
extern "C" int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
/* THE CARD'S LINK, HELD BY A STREAM FOR WHAT IT ISSUES BETWEEN TWO CALLS: `on` 1 at the point in
* `s` where traffic the step waits on starts to cross the card's link -- a collective -- and 0
* where it ends, or 2 where the work in between ended the hold itself (rad_link_gate). Lists issued
* RAD_COPY_YIELD for that card stop between pieces while it is held. The holds of one card
* alternate, on then off, in the order they are issued across all its streams: they never nest or
* overlap. And the holding stream must not wait, between the two
* calls, on anything behind a yielding list -- the list would wait for the hold to end, and the
* hold for the list. A backend without a DMA engine holds nothing.
*
* WHY: a card's inbound link carries a collective's peer bytes and the stager's copies alike, and
* the DMA engine takes its share at the link's full rate. A 4 MB all-reduce message that crosses in
* 165 us on its own took 301 us beside a layer's copies, and the step waits on every one; the
* copies have the rest of the layer to finish in. */
extern "C" int rad_link_hold(RadStream s, int on);
/* THE WORD THE HOLD IS KEPT IN, for a launch that ends its own: a 64-bit word in memory every
* engine and kernel of the card reaches, odd while the link is held. rad_link_hold(s, 2) after a
* launch that was handed this address records that the launch released the hold itself, by taking
* one off the word -- once, and only if it found it odd -- as soon as the bytes it waited for had
* landed. Null where the backend holds nothing. */
extern "C" void* rad_link_gate(RadStream s);
/* THE EXPERT PREFETCH'S DEVICE HALF (core/runtime/xprefetch.cpp). A backend that cannot make a
* dispatch complete a signal, or has no DMA engine to spare for it, leaves these out:
* rad_xp_supported is then 0 and the prefetch is off.
*
* A RIDE is a signal the next dispatch issued on a stream completes -- that dispatch keeps its
* ordering bit, so the signal stands for everything before it on the stream -- in place of a
* barrier packet of its own between two kernels. rad_ride_wait puts a barrier on another stream
* that waits for it and gives the signal back behind that barrier; a ride the DMA engine polls
* instead goes back with rad_ride_release once nothing can poll it: at once (`after` null) when the
* list that polled it has finished, else once `after` is `packets` dispatches further on, which is
* long after the ridden dispatch has completed it.
*
* rad_xp_list hands the card's prefetch DMA queue a list: wait for `mark` (a ride, or null), copy
* the `n` ranges, then write `done_val` to `done` (pinned host memory, or null). rad_xp_behind is how
* many lists the queue has been handed and not yet finished. The prefetch's ring is uncached device
* memory (rad_dev_alloc_uncached): the engine writes it and kernels read it, and no cache may hold
* what a slot held before. */
extern "C" int rad_xp_supported(int device);
extern "C" int rad_xp_stream_create(RadStream* out);
extern "C" int rad_ride(RadStream s, void** token);
extern "C" int rad_ride_wait(RadStream s, void* token);
extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets);
extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
extern "C" int64_t rad_xp_behind(int device);
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
extern "C" void rad_dev_free_uncached(void* p);
namespace rad {
/* A recorded pass, owned by the backend that recorded it. See DeviceBackend::tape_begin. */
@@ -128,6 +201,9 @@ struct DeviceBackend {
int (*memset_async)(void* dst, int value, int64_t bytes, RadStream s);
int (*memcpy_ranges_async)(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s);
int (*memcpy_list_async)(const RadCopySeg* segs, int n, unsigned flags, RadStream s);
int (*link_hold)(RadStream s, int on);
void* (*link_gate)(RadStream s);
/* ---- recorded passes. A backend with none leaves these null, and the run phase then issues
* every pass; see Ctx::run_step for what a tape is for and when one is kept.
@@ -228,6 +304,32 @@ struct DeviceBackend {
* the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
* memory. Null on a backend whose devices share one address space, which answers 1. */
int (*peer_access)(int self, int peer);
/* ---- the card's PCI address, "0000:03:00.0", into `out`; RAD_E_UNSUPPORTED from a backend
* whose devices are not PCI devices. It is what joins the runtime's device index to the
* kernel's description of the same card -- its link, its power limits, its IOMMU group -- in
* the startup report (core/diag/diag.h). */
int (*pci_address)(int device, char* out, int cap);
/* ---- the device runtime's name and version, "HIP 7.2.25403", into `out`. Null on a backend
* with no runtime behind it. */
int (*runtime_version)(char* out, int cap);
/* ---- what carries the engine's copy lists for `device` (rad_memcpy_list_async), into `out`:
* the card's DMA engine on a queue of the process's own, or why not. Null on a backend that
* copies every list segment by segment. */
int (*dma_lane)(int device, char* out, int cap);
/* ---- the expert prefetch's device half: see rad_xp_supported. Last in the table, so a backend
* listing its entries in order leaves them null. */
int (*xp_supported)(int device);
int (*xp_stream_create)(RadStream* out);
int (*ride)(RadStream s, void** token);
int (*ride_wait)(RadStream s, void* token);
void (*ride_release)(void* token, RadStream after, int64_t packets);
int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst,
const uint64_t* bytes, uint32_t* done, uint32_t done_val);
int64_t (*xp_behind)(int device);
void* (*alloc_uncached)(int64_t bytes);
void (*free_uncached)(void* p);
};
@@ -260,6 +362,12 @@ int dev_code_runs(size_t from, size_t to, int device, std::string* why);
/* The current backend's DeviceBackend::integrated. */
bool dev_integrated(int device);
/* The current backend's DeviceBackend::pci_address and runtime_version, "" where it has none. */
std::string dev_pci_address(int device);
std::string dev_runtime_version();
/* The current backend's DeviceBackend::dma_lane, "" where it has none. */
std::string dev_dma_lane(int device);
/* THE LONGEST RUN OF DISPATCHES A PLAYED TAPE LEAVES UNORDERED. Of any kTapeOverlapRun + 1
* consecutive packets on a queue, one carries the barrier bit, so a packet having been launched
* still proves that everything more than that many packets before it has completed -- which is
+86 -2
View File
@@ -67,13 +67,16 @@ static std::string device_inventory(const DeviceBackend* b) {
return s;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
/* 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. */
* that hang from a kernel bug -- and said here, as the backend comes up, and not only in the
* startup report: a hang during the load ends the process before the report prints, and the
* tools that bring a backend up (rad-kbench, rad-tune) print no report at all. */
static void warn_cwsr_off() {
FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r");
if (!f) return;
@@ -87,7 +90,6 @@ static void warn_cwsr_off() {
"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
@@ -535,6 +537,39 @@ int tape_set_overlap(RadTape t, int i, bool on) {
return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
}
bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
/* A FAILURE ANSWERED HERE, as "", is not one for the next reader of rad_dev_last_error: that
* reader is reporting a failure of its own and would name this one instead. The slot is put back
* as the call found it. */
std::string dev_pci_address(int device) {
char buf[64] = { 0 };
if (!dev()->pci_address) return std::string();
const std::string before = t_last_error;
if (dev()->pci_address(device, buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
std::string dev_dma_lane(int device) {
char buf[256] = { 0 };
if (!dev()->dma_lane) return std::string();
const std::string before = t_last_error;
if (dev()->dma_lane(device, buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
std::string dev_runtime_version() {
char buf[128] = { 0 };
if (!dev()->runtime_version) return std::string();
const std::string before = t_last_error;
if (dev()->runtime_version(buf, (int)sizeof buf) < 0) {
t_last_error = before;
return std::string();
}
return buf;
}
int dev_peer_access(int self, int peer) {
if (self == peer) return 1;
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
@@ -589,6 +624,55 @@ int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix,
const RadCopyRange* ranges, int n, RadStream s) {
return dev()->memcpy_ranges_async(dst, src, prefix, ranges, n, s);
}
int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s) {
if (const auto f = dev()->memcpy_list_async) return f(segs, n, flags, s);
for (int i = 0; i < n; ++i) RAD_TRY(dev()->memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, s));
return RAD_OK;
}
int rad_link_hold(RadStream s, int on) {
if (const auto f = dev()->link_hold) return f(s, on);
return RAD_OK;
}
void* rad_link_gate(RadStream s) {
if (const auto f = dev()->link_gate) return f(s);
return nullptr;
}
int rad_xp_supported(int device) {
const auto* d = dev();
return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list &&
d->xp_behind && d->alloc_uncached && d->free_uncached && d->xp_supported(device);
}
int rad_xp_stream_create(RadStream* out) {
if (const auto f = dev()->xp_stream_create) return f(out);
return RAD_E_UNSUPPORTED;
}
int rad_ride(RadStream s, void** token) {
if (const auto f = dev()->ride) return f(s, token);
return RAD_E_UNSUPPORTED;
}
int rad_ride_wait(RadStream s, void* token) {
if (const auto f = dev()->ride_wait) return f(s, token);
return RAD_E_UNSUPPORTED;
}
void rad_ride_release(void* token, RadStream after, int64_t packets) {
if (const auto f = dev()->ride_release) f(token, after, packets);
}
int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes,
uint32_t* done, uint32_t done_val) {
if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val);
return RAD_E_UNSUPPORTED;
}
int64_t rad_xp_behind(int device) {
if (const auto f = dev()->xp_behind) return f(device);
return 0;
}
void* rad_dev_alloc_uncached(int64_t bytes) {
if (const auto f = dev()->alloc_uncached) return f(bytes);
return nullptr;
}
void rad_dev_free_uncached(void* p) {
if (const auto f = dev()->free_uncached) f(p);
}
/* Cleared by reading it, per the header. Never null: a caller printing "%s" on a path where
* nothing failed should get an empty line, not a segfault. */
+27 -1
View File
@@ -258,6 +258,30 @@ int d_peer_access(int self, int peer) {
return can ? 1 : 0;
}
/* The runtime's bus id, rewritten in the kernel's spelling (lower case, four-digit domain) so it
* names the same directory under /sys/bus/pci/devices. */
int d_pci_address(int device, char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
char bus[64] = { 0 };
HIP_TRY(hipDeviceGetPCIBusId(bus, (int)sizeof bus, device));
unsigned dom = 0, b = 0, d = 0, f = 0;
if (std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) {
device_set_error("hipDeviceGetPCIBusId(%d): '%s' is not a PCI address", device, bus);
return RAD_E_IO;
}
std::snprintf(out, (size_t)cap, "%04x:%02x:%02x.%x", dom, b, d, f);
return RAD_OK;
}
/* HIP_VERSION's encoding: major * 10^7 + minor * 10^5 + patch. */
int d_runtime_version(char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
int v = 0;
HIP_TRY(hipRuntimeGetVersion(&v));
std::snprintf(out, (size_t)cap, "HIP %d.%d.%d", v / 10000000, (v / 100000) % 100, v % 100000);
return RAD_OK;
}
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
int can = 0;
@@ -360,7 +384,7 @@ const DeviceBackend g_hip = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
/* Recorded passes: likewise the AQL backend's. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
@@ -373,6 +397,8 @@ const DeviceBackend g_hip = {
nullptr, nullptr,
d_integrated,
d_peer_access,
d_pci_address,
d_runtime_version,
};
} /* namespace */
+14
View File
@@ -663,6 +663,18 @@ int h_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC
return stream_push((HostStream*)st, t);
}
/* A copy a segment, queued in list order: this stream has no dispatch to save, and a task holds
* no list, so the list is read here, at the call, as the device backend reads it. */
int h_memcpy_list_async(const RadCopySeg* segs, int n, unsigned, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_list_async"));
if (n < 0 || (n > 0 && !segs)) {
device_set_error("rad_memcpy_list_async: %d segments at %p", n, (const void*)segs);
return RAD_E_INVAL;
}
for (int i = 0; i < n; ++i) RAD_TRY(h_memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, st));
return RAD_OK;
}
int h_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
@@ -775,6 +787,8 @@ const DeviceBackend g_host = {
h_event_query, h_event_sync, h_event_elapsed_ms,
h_host_wrote,
h_memcpy_async, h_memcpy_2d_async, h_memset_async, h_memcpy_ranges_async,
h_memcpy_list_async,
nullptr, nullptr, /* no DMA engine, so no link to hold */
/* No recorded passes: a host stream runs its work as it is issued, so there is no queue to
* write a recording into, and every pass is issued. */
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
+446
View File
@@ -0,0 +1,446 @@
/* checks.cpp -- what in the configuration or on the machine costs speed or correctness, and what to
* do about it.
*
* EACH CHECK IS A FUNCTION OF THE FACTS AND NOTHING ELSE: no file is read here and no device is
* asked, so every one of them is tested by handing it a machine described in a struct. A check
* says what it saw with the numbers, why that matters, and the change that addresses it -- a
* warning without a fix is a worry handed to the reader.
*
* WARN is a cost or a risk the operator should act on; NOTE is a setting that is a trade-off or
* worth knowing when reading a benchmark. A finding that depends on load (a parked link) is only
* raised when the card was busy when the facts were read: at startup the cards are idle and a
* PCIe link at rest parks at its lowest speed, which is the power management doing its job.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <algorithm>
#include <cstdlib>
#include <map>
#include <set>
namespace rad {
namespace diag {
namespace {
constexpr int64_t kGiB = (int64_t)1 << 30;
constexpr int64_t kMiB = (int64_t)1 << 20;
/* A card this busy when its link was read is under load, so a link below its maximum is not the
* idle parking every PCIe link does. */
constexpr int kBusyPercent = 30;
void add(std::vector<Finding>* out, Finding::Level lv, const char* id, std::string what,
std::string why, std::string fix) {
Finding f;
f.level = lv;
f.id = id;
f.what = std::move(what);
f.why = std::move(why);
f.fix = std::move(fix);
out->push_back(std::move(f));
}
std::vector<const CardFacts*> served(const Facts& f) {
std::vector<const CardFacts*> out;
for (const CardFacts& c : f.cards)
if (c.rank >= 0) out.push_back(&c);
std::sort(out.begin(), out.end(),
[](const CardFacts* a, const CardFacts* b) { return a->rank < b->rank; });
return out;
}
/* WHETHER THE SERVING CARDS' DMA IS TRANSLATED, from their own IOMMU groups where the kernel
* says, and from the machine's mode where it does not. */
bool translated(const Facts& f) {
bool any = false, dma = false;
for (const CardFacts* c : served(f)) {
if (c->iommu_type.empty()) continue;
any = true;
if (c->iommu_type != "identity") dma = true;
}
return any ? dma : f.host.iommu == "translated";
}
/* A GPU the engine could serve on: an amdgpu device with VRAM of its own worth the name. An
* integrated GPU's carve-out of a few hundred MiB is not one; an APU set up with tens of GiB is. */
bool servable_gpu(const CardFacts& c) {
return c.vendor == "0x1002" && c.driver == "amdgpu" && c.vram_total >= ((int64_t)4 << 30);
}
std::string card_name(const CardFacts& c) {
return c.rank >= 0 ? fmt("card %s (rank %d)", c.bdf.c_str(), c.rank) : "card " + c.bdf;
}
std::string hop_link(const PciHop& h, bool cur) {
const std::string& s = cur ? h.cur_speed : h.max_speed;
const int w = cur ? h.cur_width : h.max_width;
std::string sp = s;
const size_t p = sp.find(" PCIe");
if (p != std::string::npos) sp.erase(p);
return w > 0 ? fmt("%s x%d", sp.c_str(), w) : sp;
}
/* ---- the link ------------------------------------------------------------------------------ */
/* A HOP BELOW ITS OWN MAXIMUM WHILE THE CARD IS BUSY: the SMU's link power management stuck a
* level down, or a link that retrained narrower. The card's own endpoint can read full speed
* while the root port above it runs at half (a card with a switch on it), so every hop is read. */
void check_link_under_load(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->busy_percent < kBusyPercent) continue;
for (const PciHop& h : c->chain) {
const double cur = link_gts(h.cur_speed), mx = link_gts(h.max_speed);
const bool slow = cur > 0 && mx > 0 && cur < mx;
const bool narrow = h.cur_width > 0 && h.max_width > 0 && h.cur_width < h.max_width;
if (!slow && !narrow) continue;
add(out, Finding::Warn, "link-below-max",
fmt("%s: the PCIe link at %s runs %s of its %s while the card is %d%% busy",
card_name(*c).c_str(), h.bdf.c_str(), hop_link(h, true).c_str(),
hop_link(h, false).c_str(), c->busy_percent),
"every copy between host memory and the card -- experts streamed from the host "
"pool, the all-reduce through host memory, the embedding read in place -- and "
"every kernel launch's packet fetch cross this link, so the card serves at the "
"slower link's rate and a tensor-parallel step waits for it",
"a link stuck one level down after long uptime has been cleared by a reboot; "
"check that it recovers under load (GET /diagnostics during a long prefill), and "
"reseat or move the card if it trains narrow");
break;
}
if (c->dpm_pcie_cur >= 0 && c->dpm_pcie_cur + 1 < (int)c->dpm_pcie.size())
add(out, Finding::Warn, "link-dpm-below-top",
fmt("%s: the card's PCIe power level is %s, not its top level %s, while it is "
"%d%% busy", card_name(*c).c_str(), c->dpm_pcie[(size_t)c->dpm_pcie_cur].c_str(),
c->dpm_pcie.back().c_str(), c->busy_percent),
"the SMU picks the link's speed from this table; a level below the top under load "
"is half the host bandwidth or less",
"a reboot has cleared a level stuck after long uptime; pp_dpm_pcie can pin a level "
"(echo 2 | sudo tee /sys/class/drm/CARD/device/pp_dpm_pcie with "
"power_dpm_force_performance_level manual), with the server stopped");
}
}
/* A LINK THAT CANNOT REACH THE CARD'S SPEED, whatever the load: a hop whose own maximum is below
* the card's -- a slot one generation older, a riser, a lane split. Not a fault, and often the
* board's design; worth knowing when two machines measure differently. */
void check_link_capped(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->chain.size() < 2) continue;
const PciHop& ep = c->chain.back();
const double card = link_gts(ep.max_speed);
for (size_t i = 0; i + 1 < c->chain.size(); ++i) {
const PciHop& h = c->chain[i];
const double mx = link_gts(h.max_speed);
const bool slower = mx > 0 && card > 0 && mx < card;
const bool narrower = h.max_width > 0 && ep.max_width > 0 && h.max_width < ep.max_width;
if (!slower && !narrower) continue;
add(out, Finding::Note, "link-capped",
fmt("%s: the card's link is %s at most, and %s above it is %s at most",
card_name(*c).c_str(), hop_link(ep, false).c_str(), h.bdf.c_str(),
hop_link(h, false).c_str()),
"the host side of the link bounds what the card can move to and from host memory: "
"streamed experts, the host pool and the all-reduce when it goes through host memory",
"a slot with the card's full width and speed (the board manual says which slots "
"share lanes), or no riser; nothing to do if the board has no faster slot");
break;
}
}
}
/* ---- the cards against each other ----------------------------------------------------------- */
/* A TENSOR-PARALLEL STEP ENDS WHEN ITS SLOWEST RANK DOES, so cards set up differently serve at
* the slower one's pace, and a difference in a setting nobody remembers making is the usual
* reason one card is the slow one. */
void check_cards_differ(const Facts& f, std::vector<Finding>* out) {
const auto cs = served(f);
if (cs.size() < 2) return;
std::vector<std::string> diffs;
auto field = [&](const char* what, auto get, auto show) {
std::map<std::string, std::vector<std::string>> by;
for (const CardFacts* c : cs) by[show(get(*c))].push_back(c->bdf);
if (by.size() < 2) return;
std::string d = std::string(what) + ":";
for (const auto& [v, bdfs] : by) {
d += " " + v + " on";
for (const std::string& b : bdfs) d += " " + b;
d += ";";
}
d.pop_back();
diffs.push_back(d);
};
auto str = [](const std::string& s) { return s.empty() ? std::string("unknown") : s; };
field("root port link", [](const CardFacts& c) {
return c.chain.empty() ? std::string() : hop_link(c.chain.front(), false); }, str);
field("power cap", [](const CardFacts& c) { return c.power_cap_uw; },
[](int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); });
field("voltage offset", [](const CardFacts& c) { return c.vddgfx_offset; }, str);
field("top PCIe power level", [](const CardFacts& c) {
return c.dpm_pcie.empty() ? std::string() : c.dpm_pcie.back(); }, str);
field("runtime power management", [](const CardFacts& c) { return c.runtime_control; }, str);
field("target", [](const CardFacts& c) { return c.gfx; }, str);
if (diffs.empty()) return;
std::string what = "the cards serving this model are not set up alike -- ";
for (size_t i = 0; i < diffs.size(); ++i) what += (i ? "; " : "") + diffs[i];
add(out, Finding::Warn, "cards-differ", what,
"a tensor-parallel step waits for its slowest rank in every all-reduce, so the whole "
"server runs at the pace of the card with the lower limit or the slower link",
"make the settings match (the power cap and voltage offset are per card under "
"/sys/class/drm/cardN/device; set them with the server stopped)");
}
/* A CAP LOWERED BELOW THE CARD'S OWN DEFAULT. The default, not the maximum, is the yardstick: a
* stock card ships below the most its board allows (300 W of 330 W on an R9700), and a finding on
* every stock card is one nobody reads. A cap someone lowered -- or one a reset left at a value a
* tool set before it -- is the one that changes what the card does under load. */
void check_power_cap(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->power_cap_uw <= 0 || c->power_cap_default_uw <= 0) continue;
if (c->power_cap_uw >= c->power_cap_default_uw) continue;
add(out, Finding::Note, "power-cap-below-default",
fmt("%s: the power cap is %lld W, below the card's default of %lld W",
card_name(*c).c_str(), (long long)(c->power_cap_uw / 1000000),
(long long)(c->power_cap_default_uw / 1000000)),
"under a sustained load the power cap is what sets the clock on these cards "
"(scripts/cardclock.py shows which limit binds)",
fmt("echo %lld | sudo tee /sys/class/drm/%s/device/hwmon/hwmon*/power1_cap restores "
"the default, with the server stopped; nothing to do if the cap was lowered on "
"purpose", (long long)c->power_cap_default_uw,
c->drm.empty() ? "cardN" : c->drm.c_str()));
}
}
void check_small_bar(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vram_visible <= 0 || c->vram_total <= 0) continue;
if (c->vram_visible * 10 >= c->vram_total * 9) continue;
add(out, Finding::Warn, "small-bar",
fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(),
humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()),
"without Resizable BAR a peer can address only a window of the card's memory, which "
"limits peer-to-peer collectives and copies into VRAM from the host",
"enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the "
"firmware setup");
}
}
/* AN OVERDRIVE SETTING AND RUNTIME SUSPEND. The driver holds the offset and uploads it again
* whenever the card resumes from runtime suspend; on RDNA4 that upload has been seen to fail in
* the kernel log ("Failed to upload customized OD settings") at every resume. Whether the
* firmware still holds the offset afterwards is not readable here, and a card that lost it runs a
* lower clock at the same power cap. Keeping the card out of runtime suspend keeps the question
* from arising. */
void check_od_runtime_pm(const Facts& f, std::vector<Finding>* out) {
for (const CardFacts* c : served(f)) {
if (c->vddgfx_offset.empty() || c->vddgfx_offset == "0 mV") continue;
if (c->runtime_control != "auto") continue;
add(out, Finding::Note, "od-runtime-suspend",
fmt("%s: a voltage offset of %s is set and the card runtime-suspends when idle "
"(power/control auto)", card_name(*c).c_str(), c->vddgfx_offset.c_str()),
"the driver re-uploads overdrive settings on every resume and can fail to (\"Failed "
"to upload customized OD settings\" in the kernel log); a card that resumed without "
"its offset clocks lower at the same power cap, and in a tensor-parallel world sets "
"the pace for every card",
fmt("echo on | sudo tee /sys/bus/pci/devices/%s/power/control keeps it resumed; check "
"`journalctl -k | grep -i overdrive` for failed uploads", c->bdf.c_str()));
}
}
/* ---- the host ------------------------------------------------------------------------------- */
void check_cwsr(const Facts& f, std::vector<Finding>* out) {
if (f.host.cwsr_enable != 0) return;
add(out, Finding::Warn, "cwsr-off", "amdgpu cwsr_enable is 0",
"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",
"amdgpu.cwsr_enable=1 as a module option, then rebuild the initramfs and reboot");
}
void check_huge_pages(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.thp_enabled != "never") return;
if (r.host_pool_mib <= 0 && r.pinned_bytes < kGiB) return;
const bool tr = translated(f);
add(out, tr ? Finding::Warn : Finding::Note, "thp-never",
"transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled is never), so "
"every pinned range is 4 KiB pages",
tr ? "with an IOMMU translating the cards' reads each page is a translation of its "
"own; a host pool streamed at 4 KiB pages measured 10-21% slower prefill"
: "with the IOMMU in passthrough the page size has not measured slower; it "
"matters as soon as the IOMMU translates",
"echo madvise | sudo tee /sys/kernel/mm/transparent_hugepage/enabled (or "
"transparent_hugepage=madvise on the kernel command line)");
}
void check_iommu(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (!translated(f)) return;
if (r.host_weight_bytes <= 0 && r.host_pool_mib <= 0 && r.tp < 2) return;
std::string groups;
for (const CardFacts* c : served(f))
if (!c->iommu_type.empty()) groups += (groups.empty() ? "" : ", ") + c->bdf + " " + c->iommu_type;
add(out, Finding::Note, "iommu-translated",
"the IOMMU translates the cards' DMA (" + (groups.empty() ? f.host.iommu_why : groups) + ")",
"every read a card makes of host memory -- the host pool, the embedding in RAM, the "
"all-reduce through host memory -- goes through an IOMMU translation; with huge pages that "
"is cheap, at 4 KiB pages it measured 10-21% prefill",
std::string("iommu=pt on the kernel command line (amd_iommu=pt / intel_iommu=pt), if "
"nothing on the machine needs DMA isolation; otherwise keep transparent huge "
"pages at madvise or always") +
(r.tp > 1 ? "; with more than one card, check that peer access survives the change "
"(--p2p on refuses to start without it): iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2)"
: ""));
}
void check_memory(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.mem_available >= 0 && h.mem_total > 0 &&
(h.mem_available < 2 * kGiB || h.mem_available * 20 < h.mem_total))
add(out, Finding::Warn, "memory-low",
fmt("%s of %s of RAM is available after startup", humanb(h.mem_available).c_str(),
humanb(h.mem_total).c_str()),
"the page cache is what a container read in place and the n-gram rows read from disk "
"come through; with it starved every step waits on the drive, and the kernel starts "
"reclaiming and swapping",
"lower --host-pool-mib or --prefix-cache-host-mib, or stop what else holds memory");
if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB)
add(out, Finding::Note, "swap-in-use",
fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()),
"a host thread that faults on a swapped page stalls the step it is part of",
"free memory, or turn swap off on a machine that only serves");
if (h.cgroup_mem_limit > 0 && h.mem_total > 0 && h.cgroup_mem_limit < h.mem_total &&
r.pinned_bytes > 0 && r.pinned_bytes * 10 > h.cgroup_mem_limit * 8)
add(out, Finding::Warn, "cgroup-limit",
fmt("the container's memory limit is %s and the process pins %s",
humanb(h.cgroup_mem_limit).c_str(), humanb(r.pinned_bytes).c_str()),
"pinned memory counts against the limit and cannot be reclaimed; what is left is all "
"the page cache and the process's own allocations get before the OOM killer",
"raise the container's memory limit or lower the pools");
}
void check_memlock(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
if (f.host.memlock_soft == -2 || f.host.memlock_soft < 0) return;
if (r.locked_bytes > 0 || r.ngram_placement != "disk") return;
add(out, Finding::Note, "memlock-limited",
fmt("RLIMIT_MEMLOCK is %s and the n-gram table is read from the container on disk",
humanb(f.host.memlock_soft).c_str()),
"a locked copy of the table in RAM is one of the faster tiers, and the memlock limit is "
"one of the things that keeps --ngram-placement auto off it",
"Docker: ulimits memlock -1 (--ulimit memlock=-1); systemd: LimitMEMLOCK=infinity");
}
void check_cpu(const Facts& f, std::vector<Finding>* out) {
const HostFacts& h = f.host;
if (h.cpu_governor.empty() || h.cpu_governor == "performance") return;
if (h.cpu_governor == "powersave" && h.cpu_epp == "performance") return;
if (h.cpu_governor == "schedutil") return;
add(out, Finding::Note, "cpu-governor",
fmt("the CPU governor is %s%s", h.cpu_governor.c_str(),
h.cpu_epp.empty() ? "" : (" with energy preference " + h.cpu_epp).c_str()),
"the host side of a step -- scheduling, sampling, the n-gram gather, launch bookkeeping -- "
"is single-threaded per rank, and a core that ramps slowly shows as host gap between steps",
"cpupower frequency-set -g performance, or echo performance | sudo tee "
"/sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference");
}
/* ---- the engine ----------------------------------------------------------------------------- */
void check_engine(const Facts& f, const RunFacts& r, std::vector<Finding>* out) {
std::string gpus;
for (const CardFacts& c : f.cards)
if (servable_gpu(c))
gpus += (gpus.empty() ? "" : ", ") + c.bdf + (c.gfx.empty() ? "" : " " + c.gfx);
if (r.host_backend && !gpus.empty())
add(out, Finding::Warn, "host-backend",
"the engine serves on the CPU although this machine has an AMD GPU (" + gpus + ")",
r.device_build ? "the device runtime found no card it could use, so every op runs on the host"
: "this build has no device runtime (built without HIP), so every op runs "
"on the host",
r.device_build
? "the device lines at the top of the log say why: /dev/kfd and /dev/dri must be "
"passed to a container with the render and video groups, ROCm must support the "
"card, and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES must not hide it"
: "build with ROCm (RAD_WITH_HIP=ON, hipcc on the PATH), or run the image");
for (const std::string& why : r.ignored)
add(out, Finding::Note, "device-ignored", "a device was left out: " + why,
"a rank placed on a slower or different card would set the pace of every step",
"ROCR_VISIBLE_DEVICES names the cards to use explicitly");
if (r.tp > 1 && r.p2p == 0 && !r.p2p_forced_off)
add(out, Finding::Note, "p2p-off",
"the cards cannot reach each other's memory directly" +
(r.p2p_blocked.empty() ? std::string() : " (" + r.p2p_blocked + ")"),
"the collectives exchange through pinned host memory, which crosses each card's link "
"twice",
"peer access needs Resizable BAR and the cards under one root complex; whether the "
"IOMMU's mode allows it depends on the platform -- iommu=pt removed it on an Intel "
"VT-d host (GUIDE §7.2) -- so check `--p2p on`, which refuses to start without it, "
"before and after changing the mode");
if (r.tp > 1 && r.tp_wire_lossy)
add(out, Finding::Note, "tp-wire-lossy",
fmt("--tp-wire wht6: all-reduce messages from %lld KiB up carry a quantised payload",
(long long)r.tp_wire_min_kb),
"faster prefill, but the model does not compute the exact function; two runs on "
"different world sizes are not comparable token for token",
"--tp-wire exact when exactness matters more than prefill speed");
/* Only when the operator turned it off: where the engine did (the KL mode, an embedding
* model) there is no cache to have, and the configuration line says why. */
if (!r.prefix_cache && r.prefix_cache_off_why.empty())
add(out, Finding::Note, "prefix-cache-off", "prefix caching is off (--no-prefix-cache)",
"every request prefills its whole prompt, including the conversation it shares with "
"the turn before",
"drop --no-prefix-cache");
if (r.host_weight_bytes > 0)
add(out, Finding::Note, "experts-from-host",
fmt("%s of weights a rank live in the pinned host pool and cross PCIe when they are "
"used", humanb(r.host_weight_bytes).c_str()),
"a prefill step streams every routed layer's pooled experts onto the card, so its speed "
"is bounded by the link; decode reads the ones it routes to",
"more VRAM for the experts: a shorter --max-model-len or fewer --max-num-seqs, "
"--embedding-placement ram, --kv-cache-dtype fp8, or more cards (--tp)");
if (r.file_weight_bytes > 0)
add(out, Finding::Warn, "weights-from-disk",
fmt("%s of weights a rank are read from the container on disk as they are needed",
humanb(r.file_weight_bytes).c_str()),
"a step that needs them is paced by the drive",
"a larger --host-pool-mib (if RAM allows) or more VRAM for the weights");
if (r.reference_kernels)
add(out, Finding::Warn, "reference-kernels",
"--debug-accept-reference-kernels: ops may run on the reference implementation",
"the reference library is an oracle, orders of magnitude slower than a device kernel",
"install a kernel library for this card and drop the flag");
if (r.profile_ops)
add(out, Finding::Warn, "profile-ops",
"--profile-ops times every op, which restores synchronisations",
"the run is slower and its numbers are not comparable against an unprofiled one",
"drop --profile-ops for anything measured");
}
} /* namespace */
std::vector<Finding> check(const Facts& f, const RunFacts& r) {
std::vector<Finding> out;
check_engine(f, r, &out);
check_link_under_load(f, &out);
check_cards_differ(f, &out);
check_link_capped(f, &out);
check_small_bar(f, &out);
check_power_cap(f, &out);
check_od_runtime_pm(f, &out);
check_cwsr(f, &out);
check_memory(f, r, &out);
check_huge_pages(f, r, &out);
check_iommu(f, r, &out);
check_memlock(f, r, &out);
check_cpu(f, &out);
/* Warnings first, each group in the order above: what to act on before what to know. */
std::stable_sort(out.begin(), out.end(),
[](const Finding& a, const Finding& b) { return a.level > b.level; });
return out;
}
double link_gts(const std::string& speed) {
return speed.empty() ? 0.0 : std::strtod(speed.c_str(), nullptr);
}
} /* namespace diag */
} /* namespace rad */
+216
View File
@@ -0,0 +1,216 @@
/* diag.h -- the startup report: what was configured, what it runs on, and what looks wrong.
*
* WHY ONE REPORT AND NOT THE LINES ALREADY IN THE LOG. Every decision startup makes is said
* somewhere on the way up, in the order it was made, between a hundred other lines. A log a user
* pastes into an issue is read by someone who has to find the line about the embedding, the one
* about the VRAM split and the one about the card's link, and cannot find the line that was never
* printed because the value was a default. The report puts all of it in one block at the end of
* startup: every option the command line takes with the value in force and where it came from,
* the machine as the kernel describes it, and a list of the things on it that cost speed or
* correctness with what to do about each.
*
* THREE PARTS, each built from data rather than from a list kept beside the code:
*
* CONFIGURATION every row of the option table (core/config.cpp), so an option added there
* appears here without anyone remembering to; a value startup resolved carries
* the reason it was resolved that way (Decision).
* HARDWARE read from /proc and /sys under a ROOT, so a test can hand the collector a
* directory tree of its own and a container built FROM scratch -- no shell, no
* lspci, no rocm-smi -- reads the same files the host does.
* FINDINGS each a small function over the two above (checks.cpp), unit-testable without
* a card.
*
* Unknown is a value. A field that could not be read is reported as unknown rather than left out:
* a report that silently drops a line reads as a machine that does not have the thing.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
struct Config;
namespace diag {
/* ------------------------------------------------------------------ decisions */
/* ONE VALUE STARTUP RESOLVED, and why. `key` is the option it resolves (`--placement`) when there
* is one, so the configuration table can show it on that option's row, or a topic of its own
* (`vram split`) for what no single option states. Recording the same key again replaces the
* earlier answer: a later stage that revises a choice (the n-gram copy that could not be made)
* is the answer in force. */
struct Decision {
std::string key;
std::string value;
std::string why;
};
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why);
/* ------------------------------------------------------------------ the configuration table */
/* One option as the report shows it: the value in force, where it came from (`default`, `command
* line`, an environment variable, or `auto` for a value startup derived), and the reason when
* startup derived it. */
struct ConfigRow {
std::string flag;
std::string value;
std::string source;
std::string why;
};
/* Every option in the command line's table (core/config.cpp), in its order, with the value `c`
* holds and its source from Config::given. Secrets are not values: --api-key is "set" or "not
* set". */
std::vector<ConfigRow> config_rows(const Config& c);
/* The options the table holds, for a test that every one reaches the report. */
std::vector<std::string> config_option_names();
/* ------------------------------------------------------------------ hardware */
/* One PCIe link on the way from the root port to a card. Speeds are the kernel's strings
* ("32.0 GT/s PCIe"), widths lanes; -1 / "" where the file is absent, as it is on a bridge
* internal to a card's own switch on some boards. */
struct PciHop {
std::string bdf;
std::string cur_speed, max_speed;
int cur_width = -1, max_width = -1;
};
struct CardFacts {
std::string bdf; /* 0000:03:00.0 */
std::string vendor, pci_device; /* 0x1002, 0x7551 */
std::string driver; /* the bound kernel driver, "" for none */
std::string drm; /* card1, "" when the driver made no DRM node */
std::string gfx; /* gfx1201, from the KFD topology; "" when unknown */
int simd = -1; /* SIMDs the KFD topology reports */
int numa_node = -1;
int64_t vram_total = -1, vram_visible = -1; /* the BAR the host and the peers see */
int busy_percent = -1;
std::string runtime_status; /* active | suspended, "" when unknown */
std::string runtime_control; /* auto | on */
std::string iommu_type; /* the card's IOMMU group: identity, DMA, DMA-FQ */
std::vector<PciHop> chain; /* root port first, the card's own link last */
std::vector<std::string> dpm_pcie; /* the SMU's link levels, as listed */
int dpm_pcie_cur = -1; /* the level marked current, -1 unknown */
std::string sclk, mclk; /* "500-2350 MHz", the lowest and highest DPM level */
int64_t power_cap_uw = -1, power_cap_default_uw = -1, power_cap_max_uw = -1;
std::string vddgfx_offset; /* "-75 mV" from pp_od_clk_voltage, "" when unknown */
bool integrated = false; /* the KFD topology's node has no local memory of its own */
/* What the engine knows and the kernel does not: filled by the engine for its own cards. */
std::string name; /* the runtime's product name */
int rank = -1; /* the tensor-parallel rank it serves, -1 none */
int device = -1; /* the backend's device index, -1 none */
std::string dma; /* what carries its copy lists (dev_dma_lane), "" unknown */
};
struct HostFacts {
std::string cpu_model;
int cores = -1, threads = -1;
int64_t mem_total = -1, mem_available = -1, swap_total = -1, swap_free = -1;
std::string kernel, distro;
std::string container; /* "docker", "podman", "" for none seen */
int64_t cgroup_mem_limit = -1; /* bytes; -2 is "max", -1 unknown */
int64_t memlock_soft = -1; /* bytes; -2 is unlimited, -1 unknown */
std::string thp_enabled, thp_defrag, thp_shmem; /* the selected word of each */
std::string iommu; /* passthrough | translated | off | unknown */
std::string iommu_why; /* what that was read from */
std::string cmdline; /* the boot parameters that bear on a card, space separated */
int64_t ttm_pages_limit = -1; /* pages; TTM's limit on the system memory it allocates */
int64_t page_size = 4096;
int cwsr_enable = -1;
std::string io_uring; /* available | refused (why) | unknown */
std::string cpu_governor, cpu_epp, cpu_driver;
std::string runtime; /* the device runtime's version, "" for none */
};
struct Facts {
HostFacts host;
std::vector<CardFacts> cards; /* every display-class PCI device, in address order */
};
/* Reads /proc and /sys under `root` ("" is the live system). Never fails: what cannot be read is
* left unknown.
*
* `managed`, when given, names the cards (by PCI address) whose power-management files are read
* -- the DPM tables, the overdrive block, the busy percentage and the hwmon power limits; every
* other card is described from its PCI and memory files alone. The driver answers those files
* from the card's SMU under its power-management lock, and wakes a card that was runtime-
* suspended to do it, so a server reading the machine again while it serves reads them for the
* cards it serves on and no others. Null reads them for every card. */
Facts collect(const std::string& root, const std::vector<std::string>* managed = nullptr);
/* What only a system call answers, filled for the live process: the memlock limit and whether
* io_uring is allowed here (a container's seccomp profile refuses it). */
void probe_process(HostFacts* h);
/* The names of the variables in `env` (an environ-shaped, null-terminated array) that start with
* `prefix`, sorted. Names only: a value can be a path, a host name or a token, and the report is
* written to be pasted into an issue. */
std::vector<std::string> env_names(char* const* env, const char* prefix);
/* ------------------------------------------------------------------ what the engine did */
struct RunFacts {
std::string version; /* the engine's, for the report's first line */
bool device_build = true; /* built with a device runtime (HIP) */
int tp = 1;
bool host_backend = false;
bool failed = false; /* startup stopped; the report is what it got to */
int p2p = -1; /* 1 peer to peer, 0 through host memory, -1 n/a */
bool p2p_forced_off = false; /* --p2p off */
std::string p2p_blocked; /* the pairs the driver refused */
std::vector<std::string> ignored; /* devices left out, each with the reason */
bool tp_wire_lossy = false;
int64_t tp_wire_min_kb = 0;
bool prefix_cache = true;
/* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when
* it is on or the operator turned it off. */
std::string prefix_cache_off_why;
int64_t prefix_host_mib = 0, prefix_disk_mib = 0;
int64_t host_pool_mib = 0; /* a rank, as configured */
int64_t pinned_bytes = -1; /* every pinned host allocation the process made */
int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */
int64_t file_weight_bytes = 0; /* and from the container on disk */
int64_t locked_bytes = 0; /* memory locked for a host gather (an n-gram copy) */
std::string ngram_placement; /* where an n-gram table went, "" for a model without one */
bool reference_kernels = false;
bool profile_ops = false;
bool deterministic = false;
/* The RADIANCE_* variables set in the environment, by name (env_names). The option table
* covers what the command line takes; these change behaviour beside it -- the log level, a
* pinned tuning, an instrument left on -- and a report of every setting in force names them. */
std::vector<std::string> environment;
};
/* ------------------------------------------------------------------ findings */
struct Finding {
enum Level { Note = 0, Warn = 1 };
Level level = Note;
std::string id; /* stable, for a test or a grep: "link-below-max" */
std::string what; /* what was seen, with the numbers */
std::string why; /* what it costs */
std::string fix; /* what to do: a flag, a setting, a command */
};
std::vector<Finding> check(const Facts& f, const RunFacts& r);
/* ------------------------------------------------------------------ the report */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* The same, as a JSON object in text: {"configuration", "derived", "hardware", "findings"}. */
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings);
/* Merges the decisions into the option rows: a decision whose key is an option's flag supplies
* that row's value and reason (and `auto` as its source when the option was not given). The
* decisions no row took are returned in `derived`, in the order they were made. */
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived);
/* "32.0 GT/s PCIe" -> 32.0; 0 when it does not parse. */
double link_gts(const std::string& speed);
} /* namespace diag */
} /* namespace rad */
+296
View File
@@ -0,0 +1,296 @@
/* report.cpp -- the startup report, as text for the log and as JSON for /diagnostics.
*
* ONE LAYOUT FOR A READER WHO DID NOT RUN THE SERVER: every option on its own line with the value
* in force and where it came from, the reason under any value startup derived, the machine in a
* few dense lines and a block a card, and the findings last with what to do about each. The text
* and the JSON are rendered from the same structs, so neither can say something the other does
* not.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
namespace rad {
namespace diag {
void decide(std::vector<Decision>* list, const std::string& key, const std::string& value,
const std::string& why) {
for (Decision& d : *list)
if (d.key == key) { d.value = value; d.why = why; return; }
list->push_back({ key, value, why });
}
void merge(std::vector<ConfigRow>* rows, const std::vector<Decision>& decisions,
std::vector<Decision>* derived) {
derived->clear();
for (const Decision& d : decisions) {
auto it = std::find_if(rows->begin(), rows->end(),
[&](const ConfigRow& r) { return r.flag == d.key; });
if (it == rows->end()) { derived->push_back(d); continue; }
it->value = d.value;
it->why = d.why;
if (it->source == "default") it->source = "auto";
}
}
namespace {
std::string or_unknown(const std::string& s) { return s.empty() ? "unknown" : s; }
std::string bytes_or_unknown(int64_t b) { return b < 0 ? "unknown" : humanb(b); }
/* Continuation lines of a multi-line value, indented under the column they belong to. */
void indented(std::string* out, const std::string& text, int indent) {
size_t at = 0;
while (at <= text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
const std::string l = text.substr(at, nl - at);
if (!l.empty()) *out += std::string((size_t)indent, ' ') + l + "\n";
at = nl + 1;
}
}
std::string short_bdf(const std::string& b) {
return b.rfind("0000:", 0) == 0 ? b.substr(5) : b;
}
std::string link(const std::string& speed, int width) {
std::string s = speed;
const size_t p = s.find(" PCIe");
if (p != std::string::npos) s.erase(p);
if (s.empty()) s = "?";
return width > 0 ? fmt("%s x%d", s.c_str(), width) : s;
}
std::string watts(int64_t uw) { return uw < 0 ? std::string("unknown") : fmt("%lld W", (long long)(uw / 1000000)); }
std::string host_lines(const HostFacts& h, const RunFacts& r) {
std::string o;
o += fmt(" host %s | %s cores, %s threads | RAM %s, %s available | swap %s\n",
or_unknown(h.cpu_model).c_str(),
h.cores > 0 ? std::to_string(h.cores).c_str() : "?",
h.threads > 0 ? std::to_string(h.threads).c_str() : "?",
bytes_or_unknown(h.mem_total).c_str(), bytes_or_unknown(h.mem_available).c_str(),
h.swap_total == 0 ? "none"
: h.swap_total < 0 ? "unknown"
: fmt("%s, %s used", humanb(h.swap_total).c_str(),
humanb(h.swap_total - std::max<int64_t>(h.swap_free, 0)).c_str()).c_str());
o += fmt(" system kernel %s | %s | %s | cgroup memory %s | memlock %s\n",
or_unknown(h.kernel).c_str(), or_unknown(h.distro).c_str(),
h.container.empty() ? "no container seen" : ("in a " + h.container + " container").c_str(),
h.cgroup_mem_limit == -2 ? "unlimited" : bytes_or_unknown(h.cgroup_mem_limit).c_str(),
h.memlock_soft == -2 ? "unlimited" : bytes_or_unknown(h.memlock_soft).c_str());
o += fmt(" memory huge pages %s (defrag %s, shmem %s) | ttm.pages_limit %s "
"| pinned by this process %s\n",
or_unknown(h.thp_enabled).c_str(), or_unknown(h.thp_defrag).c_str(),
or_unknown(h.thp_shmem).c_str(),
h.ttm_pages_limit > 0 ? humanb(h.ttm_pages_limit * h.page_size).c_str() : "unknown",
bytes_or_unknown(r.pinned_bytes).c_str());
o += fmt(" iommu %s (%s)\n", or_unknown(h.iommu).c_str(), or_unknown(h.iommu_why).c_str());
o += fmt(" amdgpu cwsr_enable %s | boot parameters: %s\n",
h.cwsr_enable < 0 ? "unknown" : std::to_string(h.cwsr_enable).c_str(),
h.cmdline.empty() ? "none that bear on a card" : h.cmdline.c_str());
o += fmt(" cpu governor %s%s%s | io_uring %s\n", or_unknown(h.cpu_governor).c_str(),
h.cpu_epp.empty() ? "" : (", energy preference " + h.cpu_epp).c_str(),
h.cpu_driver.empty() ? "" : (" (" + h.cpu_driver + ")").c_str(),
or_unknown(h.io_uring).c_str());
o += fmt(" runtime %s | backend %s\n",
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
r.host_backend ? "host (CPU)" : "device");
return o;
}
std::string card_lines(const CardFacts& c) {
std::string o;
std::string who = c.rank >= 0 ? fmt("rank %d (device %d)", c.rank, c.device)
: c.device >= 0 ? fmt("device %d, not serving", c.device) : "not serving";
o += fmt(" card %s %s %s%s%s %s VRAM",
c.bdf.c_str(), who.c_str(), c.gfx.empty() ? (c.vendor + ":" + c.pci_device).c_str() : c.gfx.c_str(),
c.name.empty() ? "" : " ", c.name.empty() ? "" : ("\"" + c.name + "\"").c_str(),
bytes_or_unknown(c.vram_total).c_str());
if (c.vram_visible > 0 && c.vram_visible != c.vram_total)
o += fmt(" (BAR %s)", humanb(c.vram_visible).c_str());
o += fmt(" NUMA %d driver %s%s%s\n", c.numa_node, or_unknown(c.driver).c_str(),
c.drm.empty() ? "" : " ", c.drm.c_str());
std::string chain;
for (const PciHop& h : c.chain)
chain += fmt("%s%s %s (max %s)", chain.empty() ? "" : " -> ", short_bdf(h.bdf).c_str(),
link(h.cur_speed, h.cur_width).c_str(), link(h.max_speed, h.max_width).c_str());
o += fmt(" link %s [read at %s%% busy%s]\n", chain.empty() ? "unknown" : chain.c_str(),
c.busy_percent < 0 ? "?" : std::to_string(c.busy_percent).c_str(),
c.busy_percent >= 0 && c.busy_percent < 30 ? ": a link at rest parks below its maximum" : "");
if (!c.dpm_pcie.empty()) {
std::string t;
for (size_t i = 0; i < c.dpm_pcie.size(); ++i)
t += fmt("%s%s%s", i ? " | " : "", (int)i == c.dpm_pcie_cur ? "*" : "", c.dpm_pcie[i].c_str());
o += " pcie " + t + "\n";
}
if (!c.dma.empty()) o += " dma " + c.dma + "\n";
o += fmt(" power cap %s (default %s, max %s) | voltage offset %s | sclk %s | mclk %s | "
"runtime pm %s (control %s) | iommu group %s\n",
watts(c.power_cap_uw).c_str(), watts(c.power_cap_default_uw).c_str(),
watts(c.power_cap_max_uw).c_str(), or_unknown(c.vddgfx_offset).c_str(),
or_unknown(c.sclk).c_str(), or_unknown(c.mclk).c_str(),
or_unknown(c.runtime_status).c_str(), or_unknown(c.runtime_control).c_str(),
c.iommu_type.empty() ? "none" : c.iommu_type.c_str());
return o;
}
} /* namespace */
std::string render(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
std::string o;
o += "STARTUP REPORT" + (r.version.empty() ? std::string() : " -- radiance " + r.version) +
(r.failed ? " -- STARTUP STOPPED; this is what it had resolved when it did\n" : "\n");
o += "CONFIGURATION -- every option, the value in force, and where it came from\n";
size_t w = 0;
for (const ConfigRow& c : config) w = std::max(w, c.flag.size());
w = std::min<size_t>(w + 2, 34);
for (const ConfigRow& c : config) {
const std::string v = c.value.empty() ? "\"\"" : c.value;
const std::string first = v.substr(0, v.find('\n'));
std::string l = fmt(" %-*s %s", (int)w, c.flag.c_str(), first.c_str());
const size_t col = 2 + w + 1 + 44;
l += l.size() < col ? std::string(col - l.size(), ' ') : std::string(" ");
o += l + "[" + c.source + "]\n";
if (first.size() != v.size()) indented(&o, v.substr(first.size() + 1), (int)(3 + w));
if (!c.why.empty()) indented(&o, c.why, (int)(5 + w));
}
o += "ENVIRONMENT -- the RADIANCE_* variables set, by name; their values are not shown\n";
if (r.environment.empty()) o += " none\n";
for (const std::string& n : r.environment) o += " " + n + "\n";
if (!derived.empty()) {
o += "DERIVED -- what startup worked out that no single option states\n";
for (const Decision& d : derived) {
o += fmt(" %-*s %s\n", (int)w, d.key.c_str(), d.value.c_str());
if (!d.why.empty()) indented(&o, d.why, (int)(5 + w));
}
}
o += "HARDWARE\n";
o += host_lines(f.host, r);
for (const CardFacts& c : f.cards) o += card_lines(c);
if (f.cards.empty()) o += " no display-class PCI device is visible\n";
int nw = 0, nn = 0;
for (const Finding& x : findings) (x.level == Finding::Warn ? nw : nn)++;
o += fmt("FINDINGS -- %d warning%s, %d note%s\n", nw, nw == 1 ? "" : "s", nn, nn == 1 ? "" : "s");
if (findings.empty()) o += " nothing found that costs speed or correctness\n";
for (const Finding& x : findings) {
o += fmt(" %s %s: %s\n", x.level == Finding::Warn ? "WARN" : "note", x.id.c_str(),
x.what.c_str());
o += " why: " + x.why + "\n";
o += " fix: " + x.fix + "\n";
}
return o;
}
std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Decision>& derived,
const Facts& f, const RunFacts& r, const std::vector<Finding>& findings) {
using J = nlohmann::ordered_json;
J o;
o["startup_failed"] = r.failed;
J cfg = J::array();
for (const ConfigRow& c : config) {
J e;
e["option"] = c.flag;
e["value"] = c.value;
e["source"] = c.source;
if (!c.why.empty()) e["why"] = c.why;
cfg.push_back(std::move(e));
}
o["configuration"] = std::move(cfg);
o["environment"] = r.environment;
J der = J::array();
for (const Decision& d : derived) der.push_back({ { "topic", d.key }, { "value", d.value }, { "why", d.why } });
o["derived"] = std::move(der);
const HostFacts& h = f.host;
J host;
host["cpu"] = h.cpu_model;
host["cores"] = h.cores;
host["threads"] = h.threads;
host["mem_total"] = h.mem_total;
host["mem_available"] = h.mem_available;
host["swap_total"] = h.swap_total;
host["swap_free"] = h.swap_free;
host["kernel"] = h.kernel;
host["distro"] = h.distro;
host["container"] = h.container;
host["cgroup_mem_limit"] = h.cgroup_mem_limit;
host["memlock"] = h.memlock_soft;
host["thp"] = { { "enabled", h.thp_enabled }, { "defrag", h.thp_defrag },
{ "shmem_enabled", h.thp_shmem } };
host["iommu"] = { { "mode", h.iommu }, { "why", h.iommu_why } };
host["boot_parameters"] = h.cmdline;
host["ttm_pages_limit"] = h.ttm_pages_limit;
host["page_size"] = h.page_size;
host["cwsr_enable"] = h.cwsr_enable;
host["io_uring"] = h.io_uring;
host["cpu_governor"] = h.cpu_governor;
host["cpu_epp"] = h.cpu_epp;
host["cpu_driver"] = h.cpu_driver;
host["runtime"] = h.runtime;
J cards = J::array();
for (const CardFacts& c : f.cards) {
J e;
e["bdf"] = c.bdf;
e["rank"] = c.rank;
e["device"] = c.device;
e["name"] = c.name;
e["vendor"] = c.vendor;
e["pci_device"] = c.pci_device;
e["gfx"] = c.gfx;
e["simd"] = c.simd;
e["driver"] = c.driver;
e["drm"] = c.drm;
e["numa_node"] = c.numa_node;
e["vram_total"] = c.vram_total;
e["vram_visible"] = c.vram_visible;
e["busy_percent"] = c.busy_percent;
e["runtime_status"] = c.runtime_status;
e["runtime_control"] = c.runtime_control;
e["iommu_group_type"] = c.iommu_type;
e["dma"] = c.dma;
J chain = J::array();
for (const PciHop& hp : c.chain)
chain.push_back({ { "bdf", hp.bdf }, { "speed", hp.cur_speed }, { "width", hp.cur_width },
{ "max_speed", hp.max_speed }, { "max_width", hp.max_width } });
e["link_chain"] = std::move(chain);
e["pcie_dpm"] = c.dpm_pcie;
e["pcie_dpm_current"] = c.dpm_pcie_cur;
e["sclk"] = c.sclk;
e["mclk"] = c.mclk;
e["power_cap_uw"] = c.power_cap_uw;
e["power_cap_default_uw"] = c.power_cap_default_uw;
e["power_cap_max_uw"] = c.power_cap_max_uw;
e["vddgfx_offset"] = c.vddgfx_offset;
cards.push_back(std::move(e));
}
J run;
run["version"] = r.version;
run["device_build"] = r.device_build;
run["tp"] = r.tp;
run["host_backend"] = r.host_backend;
run["p2p"] = r.p2p;
run["p2p_blocked"] = r.p2p_blocked;
run["ignored_devices"] = r.ignored;
run["pinned_bytes"] = r.pinned_bytes;
run["host_weight_bytes"] = r.host_weight_bytes;
run["file_weight_bytes"] = r.file_weight_bytes;
o["hardware"] = { { "host", std::move(host) }, { "cards", std::move(cards) }, { "run", std::move(run) } };
J fs = J::array();
for (const Finding& x : findings)
fs.push_back({ { "level", x.level == Finding::Warn ? "warn" : "note" }, { "id", x.id },
{ "what", x.what }, { "why", x.why }, { "fix", x.fix } });
o["findings"] = std::move(fs);
/* REPLACE, NOT THROW, on bytes that are not UTF-8. Values here come from the operator and the
* filesystem -- a --model path, a boot parameter, a product name -- and none of them is
* promised to be UTF-8; the strict default would make the whole answer an exception. */
return o.dump(-1, ' ', false, J::error_handler_t::replace);
}
} /* namespace diag */
} /* namespace rad */
+473
View File
@@ -0,0 +1,473 @@
/* sysinfo.cpp -- the machine, as /proc and /sys describe it.
*
* EVERY READ IS A FILE UNDER A ROOT. No tool is run and no library beyond the C++ runtime is
* asked: the production image is built FROM scratch and has no shell, no lspci and no rocm-smi,
* and a test hands the collector a directory tree of its own to stand for a machine with two cards
* behind a switch, a parked link, or an IOMMU that translates. What a file does not say is left
* unknown, never guessed.
*/
#include "diag/diag.h"
#include "rad_internal.h"
#include <cerrno>
#include <cctype>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace rad {
namespace diag {
namespace fs = std::filesystem;
namespace {
std::string slurp(const std::string& path) {
std::ifstream f(path);
if (!f) return std::string();
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
std::string trim(std::string s) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ' || s.back() == '\t' || s.back() == '\r'))
s.pop_back();
size_t i = 0;
while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i;
return s.substr(i);
}
/* The first line of a sysfs attribute, trimmed; "" when it cannot be read. */
std::string line(const std::string& path) {
const std::string s = slurp(path);
const size_t nl = s.find('\n');
return trim(nl == std::string::npos ? s : s.substr(0, nl));
}
int64_t num(const std::string& path, int64_t dflt = -1) {
const std::string s = line(path);
if (s.empty()) return dflt;
char* end = nullptr;
const long long v = std::strtoll(s.c_str(), &end, 0);
return end && end != s.c_str() ? (int64_t)v : dflt;
}
/* The bracketed word of a sysfs choice list: "always [madvise] never" -> "madvise". */
std::string selected(const std::string& path) {
const std::string s = line(path);
const size_t a = s.find('['), b = s.find(']');
if (a == std::string::npos || b == std::string::npos || b < a) return s;
return s.substr(a + 1, b - a - 1);
}
bool exists(const std::string& p) {
std::error_code ec;
return fs::exists(p, ec);
}
std::vector<std::string> list(const std::string& dir) {
std::vector<std::string> out;
std::error_code ec;
for (fs::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec))
out.push_back(it->path().filename().string());
std::sort(out.begin(), out.end());
return out;
}
bool is_bdf(const std::string& s) {
unsigned d, b, dv, f;
char tail;
return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4;
}
/* "0x7551" from a sysfs id file, which the kernel writes with its prefix. */
std::string hexid(const std::string& path) { return line(path); }
/* The lowest and highest level of a pp_dpm_* table, "500-2350 MHz"; the levels are listed in
* order, one a line, as "N: 2350Mhz *". */
std::string dpm_range(const std::string& path) {
std::istringstream in(slurp(path));
std::string l;
long lo = -1, hi = -1;
while (std::getline(in, l)) {
const size_t c = l.find(':');
const char* p = l.c_str() + (c == std::string::npos ? 0 : c + 1);
long v = std::strtol(p, nullptr, 10);
if (v <= 0) continue;
if (lo < 0 || v < lo) lo = v;
if (v > hi) hi = v;
}
if (lo < 0) return std::string();
return fmt("%ld-%ld MHz", lo, hi);
}
/* `pm`: whether the power-management files are read as well (collect's `managed`). */
void read_card(const std::string& root, const std::string& bdf, bool pm, CardFacts* c) {
const std::string dev = root + "/sys/bus/pci/devices/" + bdf;
c->bdf = bdf;
c->vendor = hexid(dev + "/vendor");
c->pci_device = hexid(dev + "/device");
{
std::error_code ec;
const fs::path drv = fs::read_symlink(dev + "/driver", ec);
if (!ec) c->driver = drv.filename().string();
}
c->numa_node = (int)num(dev + "/numa_node", -1);
c->runtime_status = line(dev + "/power/runtime_status");
c->runtime_control = line(dev + "/power/control");
c->iommu_type = line(dev + "/iommu_group/type");
for (const std::string& d : list(dev + "/drm"))
if (d.rfind("card", 0) == 0 && d.size() > 4 && std::isdigit((unsigned char)d[4])) c->drm = d;
/* THE WHOLE PATH TO THE ROOT PORT, not the card's own link alone. A card with a switch on it
* reports its own endpoint link at full speed whatever the slot does upstream: a root port
* parked one speed down shows only at the root port (and in the card's DPM table). */
std::error_code ec;
const fs::path real = fs::canonical(dev, ec);
if (!ec) {
for (const fs::path& part : real) {
const std::string p = part.string();
if (!is_bdf(p)) continue;
const std::string hd = root + "/sys/bus/pci/devices/" + p;
PciHop h;
h.bdf = p;
h.cur_speed = line(hd + "/current_link_speed");
h.max_speed = line(hd + "/max_link_speed");
h.cur_width = (int)num(hd + "/current_link_width", -1);
h.max_width = (int)num(hd + "/max_link_width", -1);
c->chain.push_back(h);
}
}
if (c->chain.empty()) {
PciHop h;
h.bdf = bdf;
h.cur_speed = line(dev + "/current_link_speed");
h.max_speed = line(dev + "/max_link_speed");
h.cur_width = (int)num(dev + "/current_link_width", -1);
h.max_width = (int)num(dev + "/max_link_width", -1);
c->chain.push_back(h);
}
c->vram_total = num(dev + "/mem_info_vram_total", -1);
c->vram_visible = num(dev + "/mem_info_vis_vram_total", -1);
if (!pm) return;
c->busy_percent = (int)num(dev + "/gpu_busy_percent", -1);
{
std::istringstream in(slurp(dev + "/pp_dpm_pcie"));
std::string l;
while (std::getline(in, l)) {
l = trim(l);
if (l.empty()) continue;
if (l.find('*') != std::string::npos) c->dpm_pcie_cur = (int)c->dpm_pcie.size();
l.erase(std::remove(l.begin(), l.end(), '*'), l.end());
c->dpm_pcie.push_back(trim(l));
}
}
c->sclk = dpm_range(dev + "/pp_dpm_sclk");
c->mclk = dpm_range(dev + "/pp_dpm_mclk");
for (const std::string& h : list(dev + "/hwmon")) {
const std::string hp = dev + "/hwmon/" + h;
if (!exists(hp + "/power1_cap")) continue;
c->power_cap_uw = num(hp + "/power1_cap", -1);
c->power_cap_default_uw = num(hp + "/power1_cap_default", -1);
c->power_cap_max_uw = num(hp + "/power1_cap_max", -1);
break;
}
{
/* "OD_VDDGFX_OFFSET:\n-75mV": the offset the driver holds for the card, which is the one
* it uploads; whether the firmware took it is not in this file. */
const std::string od = slurp(dev + "/pp_od_clk_voltage");
const size_t at = od.find("OD_VDDGFX_OFFSET:");
if (at != std::string::npos) {
const char* p = od.c_str() + at + std::strlen("OD_VDDGFX_OFFSET:");
char* end = nullptr;
const long v = std::strtol(p, &end, 10);
if (end && end != p) c->vddgfx_offset = fmt("%ld mV", v);
}
}
}
/* The KFD topology knows what the PCI files do not: each GPU node's target and SIMD count, keyed
* by its PCI location -- `location_id` is (bus << 8) | (device << 3) | function. */
void read_kfd(const std::string& root, std::vector<CardFacts>* cards) {
const std::string nodes = root + "/sys/class/kfd/kfd/topology/nodes";
for (const std::string& n : list(nodes)) {
/* A LINE AT A TIME, and only the four keys this needs parsed: the file holds values no
* signed 64-bit integer takes (unique_id is a full 64-bit hash), and a stream extraction
* that meets one fails and stops reading every key after it. */
std::istringstream in(slurp(nodes + "/" + n + "/properties"));
std::string l;
long long loc = -1, dom = 0, gfx = 0, simd = -1;
while (std::getline(in, l)) {
const size_t sp = l.find_first_of(" \t");
if (sp == std::string::npos) continue;
const std::string k = l.substr(0, sp);
long long* into = k == "location_id" ? &loc
: k == "domain" ? &dom
: k == "gfx_target_version" ? &gfx
: k == "simd_count" ? &simd
: nullptr;
if (!into) continue;
const char* p = l.c_str() + sp + 1;
char* end = nullptr;
errno = 0;
const long long v = std::strtoll(p, &end, 10);
if (end != p && errno == 0) *into = v;
}
if (gfx <= 0 || loc < 0) continue;
const std::string bdf = fmt("%04llx:%02llx:%02llx.%llx", dom, (loc >> 8) & 0xff,
(loc >> 3) & 0x1f, loc & 7);
for (CardFacts& c : *cards) {
if (c.bdf != bdf) continue;
c.gfx = fmt("gfx%lld%llx%llx", gfx / 10000, (gfx / 100) % 100, gfx % 100);
c.simd = (int)simd;
}
}
}
/* Of two memory limits in HostFacts' encoding (bytes, -2 unlimited, -1 unknown), the one that
* binds: the smaller number, else unlimited over unknown. */
int64_t tighter(int64_t a, int64_t b) {
if (a >= 0 && b >= 0) return std::min(a, b);
if (a >= 0 || b >= 0) return std::max(a, b);
return a == -2 || b == -2 ? -2 : -1;
}
/* THE TIGHTEST MEMORY LIMIT FROM A CGROUP UP TO THE MOUNT'S ROOT. A limit binds every cgroup
* below it, so the process's own group can say "max" while the systemd slice or the container's
* group above it holds the limit that counts. `rel` is the path /proc/self/cgroup names, under
* `mount`; every level on the way up is read, the mount's root included -- inside a container's
* cgroup namespace that root is the container's own group. */
int64_t cgroup_limit(const std::string& mount, std::string rel, const char* file) {
int64_t lim = -1;
while (!rel.empty() && rel.back() == '/') rel.pop_back();
for (;;) {
const std::string v = line(mount + rel + "/" + file);
if (v == "max") {
lim = tighter(lim, -2);
} else if (!v.empty()) {
char* end = nullptr;
errno = 0;
const long long n = std::strtoll(v.c_str(), &end, 10);
/* Version 1 writes "no limit" as the largest page-aligned number below 2^63. */
if (end != v.c_str() && errno == 0 && n >= 0)
lim = tighter(lim, n >= ((long long)1 << 62) ? -2 : (int64_t)n);
}
if (rel.empty()) break;
const size_t up = rel.rfind('/');
rel.erase(up == std::string::npos ? 0 : up);
}
return lim;
}
void read_host(const std::string& root, HostFacts* h) {
{
std::istringstream in(slurp(root + "/proc/cpuinfo"));
std::string l;
std::set<std::pair<std::string, std::string>> cores;
std::string phys;
int threads = 0;
while (std::getline(in, l)) {
const size_t c = l.find(':');
if (c == std::string::npos) continue;
const std::string k = trim(l.substr(0, c)), v = trim(l.substr(c + 1));
if (k == "processor") ++threads;
else if (k == "model name" && h->cpu_model.empty()) h->cpu_model = v;
else if (k == "physical id") phys = v;
else if (k == "core id") cores.insert({ phys, v });
}
if (threads > 0) h->threads = threads;
if (!cores.empty()) h->cores = (int)cores.size();
}
{
std::istringstream in(slurp(root + "/proc/meminfo"));
std::string k;
long long v;
std::string unit;
while (in >> k >> v) {
std::getline(in, unit);
const int64_t b = (int64_t)v * 1024;
if (k == "MemTotal:") h->mem_total = b;
else if (k == "MemAvailable:") h->mem_available = b;
else if (k == "SwapTotal:") h->swap_total = b;
else if (k == "SwapFree:") h->swap_free = b;
}
}
h->kernel = line(root + "/proc/sys/kernel/osrelease");
{
std::istringstream in(slurp(root + "/etc/os-release"));
std::string l;
while (std::getline(in, l))
if (l.rfind("PRETTY_NAME=", 0) == 0) {
h->distro = l.substr(12);
if (h->distro.size() >= 2 && h->distro.front() == '"') h->distro = h->distro.substr(1, h->distro.size() - 2);
}
}
if (exists(root + "/.dockerenv")) h->container = "docker";
else if (exists(root + "/run/.containerenv")) h->container = "podman";
else {
const std::string cg = slurp(root + "/proc/1/cgroup");
if (cg.find("docker") != std::string::npos) h->container = "docker";
else if (cg.find("kubepods") != std::string::npos) h->container = "kubernetes";
else if (cg.find("containerd") != std::string::npos) h->container = "containerd";
}
{
/* THE PROCESS'S OWN CGROUP, which inside a container is "/" under its namespace, and
* every one above it: cgroup_limit says why. Version 2 is the "0::" line; version 1's
* memory controller is the ":memory:" one, where "unlimited" is a number near 2^63. */
std::istringstream in(slurp(root + "/proc/self/cgroup"));
std::string l;
int64_t lim = -1;
while (std::getline(in, l)) {
int64_t v = -1;
if (l.rfind("0::", 0) == 0)
v = cgroup_limit(root + "/sys/fs/cgroup", l.substr(3), "memory.max");
else if (l.find(":memory:") != std::string::npos)
v = cgroup_limit(root + "/sys/fs/cgroup/memory", l.substr(l.find(":memory:") + 8),
"memory.limit_in_bytes");
lim = tighter(lim, v);
}
h->cgroup_mem_limit = lim;
}
const std::string thp = root + "/sys/kernel/mm/transparent_hugepage";
h->thp_enabled = selected(thp + "/enabled");
h->thp_defrag = selected(thp + "/defrag");
h->thp_shmem = selected(thp + "/shmem_enabled");
{
std::istringstream in(line(root + "/proc/cmdline"));
std::string t;
static const char* const kKeep[] = { "iommu", "amd_iommu", "intel_iommu", "amdgpu.", "ttm.",
"transparent_hugepage", "hugepages", "pcie_aspm",
"pci=", "default_hugepagesz" };
while (in >> t)
for (const char* k : kKeep)
if (t.rfind(k, 0) == 0) { h->cmdline += (h->cmdline.empty() ? "" : " ") + t; break; }
}
{
/* PASSTHROUGH OR TRANSLATED, from what decides it for the cards: their IOMMU groups' type
* (identity is passthrough) is the kernel's own answer; the boot parameters and the
* presence of an IOMMU are what is left when a card has no group. */
const bool any_iommu = !list(root + "/sys/class/iommu").empty();
const bool groups = !list(root + "/sys/kernel/iommu_groups").empty();
const std::string cl = " " + h->cmdline + " ";
if (!any_iommu && !groups) {
h->iommu = "off";
h->iommu_why = "no IOMMU is registered (/sys/class/iommu is empty)";
} else if (cl.find(" iommu=pt ") != std::string::npos ||
cl.find(" amd_iommu=pt ") != std::string::npos ||
cl.find(" intel_iommu=pt ") != std::string::npos) {
h->iommu = "passthrough";
h->iommu_why = "iommu=pt on the kernel command line";
} else if (cl.find("iommu=off") != std::string::npos) {
h->iommu = "off";
h->iommu_why = "the kernel command line turns it off";
} else {
h->iommu = "unknown";
h->iommu_why = "an IOMMU is present; its mode is read from the cards' groups below";
}
}
{
int64_t lim = num(root + "/sys/module/ttm/parameters/pages_limit", -1);
/* 0 IS THE DRIVER'S DEFAULT, which is half of RAM. */
if (lim == 0 && h->mem_total > 0) lim = h->mem_total / 2 / h->page_size;
h->ttm_pages_limit = lim;
}
h->cwsr_enable = (int)num(root + "/sys/module/amdgpu/parameters/cwsr_enable", -1);
{
const int64_t d = num(root + "/proc/sys/kernel/io_uring_disabled", -1);
h->io_uring = d == 0 ? "available" : d == 1 ? "restricted to a group (io_uring_disabled 1)"
: d == 2 ? "refused (io_uring_disabled 2)" : "unknown";
}
const std::string cpu = root + "/sys/devices/system/cpu/cpu0/cpufreq";
h->cpu_governor = line(cpu + "/scaling_governor");
h->cpu_epp = line(cpu + "/energy_performance_preference");
h->cpu_driver = line(cpu + "/scaling_driver");
}
} /* namespace */
Facts collect(const std::string& root, const std::vector<std::string>* managed) {
Facts f;
if (root.empty()) {
const long ps = sysconf(_SC_PAGE_SIZE);
if (ps > 0) f.host.page_size = ps;
}
read_host(root, &f.host);
/* EVERY DISPLAY-CLASS DEVICE, the engine's or not: an integrated GPU beside the cards, or a
* card the engine was told not to use, is part of the answer to "what is in this machine". */
for (const std::string& d : list(root + "/sys/bus/pci/devices")) {
const std::string cls = line(root + "/sys/bus/pci/devices/" + d + "/class");
if (cls.rfind("0x03", 0) != 0) continue;
const bool pm =
!managed || std::find(managed->begin(), managed->end(), d) != managed->end();
CardFacts c;
read_card(root, d, pm, &c);
f.cards.push_back(std::move(c));
}
read_kfd(root, &f.cards);
/* THE IOMMU'S MODE AS THE CARDS SEE IT, which beats the command line where both exist: each
* card's group says identity (passthrough) or DMA / DMA-FQ (translated), and a machine can
* hold both -- an integrated GPU left identity-mapped beside a translated discrete card. */
if (f.host.iommu == "unknown") {
std::map<std::string, std::string> by;
for (const CardFacts& c : f.cards)
if (!c.iommu_type.empty()) by[c.iommu_type] += (by[c.iommu_type].empty() ? "" : ", ") + c.bdf;
if (by.size() == 1) {
const bool id = by.begin()->first == "identity";
f.host.iommu = id ? "passthrough" : "translated";
f.host.iommu_why = "the display devices' IOMMU groups are of type " + by.begin()->first;
} else if (by.size() > 1) {
f.host.iommu = "mixed";
f.host.iommu_why.clear();
for (const auto& [t, bdfs] : by)
f.host.iommu_why += (f.host.iommu_why.empty() ? "" : "; ") + t + " for " + bdfs;
}
}
return f;
}
void probe_process(HostFacts* h) {
struct rlimit rl{};
if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0)
h->memlock_soft = rl.rlim_cur == RLIM_INFINITY ? -2 : (int64_t)rl.rlim_cur;
#ifdef SYS_io_uring_setup
/* ASKED, NOT INFERRED: a seccomp profile (Docker's default) refuses the call whatever the
* sysctl says, and the answer is the error the call returns. One entry, closed at once. */
struct { uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle, features,
wq_fd, resv[3]; uint64_t sq_off[5]; uint64_t cq_off[5]; } p{};
static_assert(sizeof(p) == 120, "io_uring_params is 120 bytes");
const long fd = syscall(SYS_io_uring_setup, 1, &p);
if (fd >= 0) {
close((int)fd);
h->io_uring = "available";
} else {
h->io_uring = fmt("refused (%s)", std::strerror(errno));
}
#endif
}
std::vector<std::string> env_names(char* const* env, const char* prefix) {
std::vector<std::string> out;
const size_t n = std::strlen(prefix);
for (char* const* e = env; e && *e; ++e) {
if (std::strncmp(*e, prefix, n) != 0) continue;
const char* eq = std::strchr(*e, '=');
out.emplace_back(*e, eq ? (size_t)(eq - *e) : std::strlen(*e));
}
std::sort(out.begin(), out.end());
return out;
}
} /* namespace diag */
} /* namespace rad */
+187 -12
View File
@@ -34,12 +34,16 @@
#include <utility>
#include <vector>
#include <thread>
#include <unistd.h>
namespace rad {
Engine::Engine(Config cfg) : cfg_(std::move(cfg)) {}
/* The RADIANCE_* names are taken here, before start(): bring-up sets one of its own
* (RADIANCE_GDN_ANCHOR, Engine::configure_kv), and the report lists what the operator set. */
Engine::Engine(Config cfg)
: cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
int32_t* Engine::Readback::reserve(int64_t count) {
if (count <= n) return p;
@@ -61,6 +65,7 @@ Engine::~Engine() {
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);
for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_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();
@@ -79,6 +84,13 @@ Engine::~Engine() {
(unsigned long long)r->ctx.route_dropped());
RAD_INFO("%s", r->mover.report().c_str());
}
/* THE TRANSFER STREAM BEFORE THE CONTEXTS. Ctx::shutdown drains the compute streams and then
* frees the arena, but the mover's stream copies into the arena too -- the prefill stager's
* ring is its top, and an idle arena lends its slots to the expert slab -- and is drained only
* when the mover goes, after it. A fill still landing in a lent arena slot at that moment is
* a GPU memory fault on the way out. */
for (auto& r : ranks_)
if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s);
for (auto& r : ranks_) r->ctx.shutdown();
step_state_fini();
ranks_.clear();
@@ -259,8 +271,13 @@ void Engine::tiering_dispatch(Rank& r, int step) {
++r.heat_credited;
}
/* NO SWAPS BEHIND A PASS THE STAGER ARMED. Such a step is bound by its own copies -- every
* pooled expert of every routed layer crosses the link on the transfer stream a swap would
* share -- and the turnover slots a swap would land in are filled for it (below). The
* histograms are credited all the same, and the next step that stages nothing swaps on what
* they said. */
std::vector<Swap> swaps;
if (r.heat.step(&swaps) < 0) return;
if (!r.stager.staged() && r.heat.step(&swaps) < 0) return;
for (const Swap& s : swaps) {
/* CONTRACT: every unit the engine named is BUSY on the way out, and a proposal that is
* silently dropped leaves the pair busy forever. `issue` clears it; `abandon` is what
@@ -270,8 +287,25 @@ void Engine::tiering_dispatch(Rank& r, int step) {
/* AFTER the swaps, because a swap is what the policy asked for and a fill is what the memory
* allows: spending a move record on a fill that the next swap then needs would let a
* boundary the arbiter happens to be moving reorder the engine's own decisions. */
(void)r.mover.balance(&r.heat);
* boundary the arbiter happens to be moving reorder the engine's own decisions.
*
* Behind a staged pass the turnover slots are filled too: that step swaps nothing, and kept
* free they are residents its stager copies instead -- at TP2 a 160K-token prompt staged
* 9.6% more and ran 3-5% slower.
*
* AND THEY STAY FILLED UNTIL kTurnoverAfter STEPS IN A ROW HAVE STAGED NOTHING, idle ticks
* included. A prompt answered in a token or two -- or a pause before the next one -- would
* otherwise drop them and copy them straight back at the next prompt's first chunk, across the
* link the chunk stages over, and each round trip scatters the lent residents through the
* pool runs the stager coalesces its copies on: at TP2, 26K-token prompts back to back ran
* 33 copies a staged layer that way against 16 held, and the first prompt after a pause up to
* 0.4% slower. A decode run reaches the count in a few steps, and its swaps land in the working
* slots until it does. */
constexpr int kTurnoverAfter = 4;
r.unstaged_steps = r.stager.staged() ? 0 : r.unstaged_steps + 1;
const bool hold = r.unstaged_steps < kTurnoverAfter;
r.mover.hold_turnover(hold);
(void)r.mover.balance(&r.heat, !hold);
}
/* ------------------------------------------------------------------ the rank thread */
void Engine::rank_loop(int index) {
@@ -318,7 +352,9 @@ void Engine::rank_loop(int index) {
* host synchronisation between them: it is more ops on the compute stream and not
* a second phase (spec §13). */
if (bst >= 0) {
s = r.sampler.run(&r.ctx, r.program.logits_buf, r.tok_buf);
/* The scored rows first: the sampler may rewrite a row in place. */
if (b->draft_pass == 0 && !score_rows_.empty()) s = issue_scored_rows(r);
if (s >= 0) s = r.sampler.run(&r.ctx, r.program.logits_buf, r.tok_buf);
if (s < 0) {
RAD_ERR("rank %d step %d: sampler: %s", index, b->step, rad_strerror(s));
step_status_.store(s, std::memory_order_release);
@@ -574,6 +610,7 @@ int Engine::step_loop() {
so.reqs.push_back(const_cast<Request*>(e.req));
}
so.n_rows = logit_row;
if (const int ss = stage_scored_rows(plan, so); ss < 0) return fail_loop(ss);
/* THE SAMPLER'S HOST WORK, staged by this lambda either in front of the ranks or -- by
* default, see build_mu_ in engine.h -- underneath them. It touches request state and the
@@ -1004,6 +1041,76 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
return RAD_OK;
}
/* THE SCORED ROWS (Request::token_scores): the logits row at a scored prompt's last position, on
* its way to the host before the sampler can rewrite it in place. Three parts, on three threads'
* turns: which rows, decided with the rows themselves and while every rank is parked
* (stage_scored_rows); one copy a row on each rank's own stream, right ahead of its sampler
* (issue_scored_rows); and each request's ids read out of the staging after the step's one wait
* (collect_scored_rows), which is ahead of the commit that finishes the request. A whole row
* crosses, not the ids: one copy of 512 KB at a 128K vocabulary is cheaper than a copy an id. */
int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) {
score_rows_.clear();
if (embedding_) return RAD_OK;
for (size_t i = 0; i < plan.e.size(); ++i) {
const Request* r = plan.e[i].req;
if (so.first_row[i] < 0 || !r || !r->token_scores || !r->output.empty()) continue;
score_rows_.push_back({ so.first_row[i], r->token_scores.get() });
}
if (score_rows_.empty()) return RAD_OK;
const int64_t n = (int64_t)score_rows_.size();
for (auto& rk : ranks_) {
if (n <= rk->score_rows_cap) continue;
if (ranks_.size() > 1) RAD_TRY(rad_dev_set(rk->device));
if (rk->score_host) rad_dev_free(rk->score_host, RAD_MEM_HOST_PINNED);
const int64_t width = rk->sampler.config().n_vocab_local;
rk->score_host = static_cast<float*>(
rad_dev_alloc(n * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED));
rk->score_rows_cap = rk->score_host ? n : 0;
if (!rk->score_host) {
RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)n);
return RAD_E_NOMEM;
}
}
if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device));
return RAD_OK;
}
int Engine::issue_scored_rows(Rank& r) {
const int64_t width = r.sampler.config().n_vocab_local;
const char* logits = static_cast<const char*>(r.ctx.buf_ptr(r.program.logits_buf));
if (!logits || !r.score_host) return RAD_E_STATE;
for (size_t k = 0; k < score_rows_.size(); ++k)
RAD_TRY(rad_memcpy_async(r.score_host + (int64_t)k * width,
logits + (int64_t)score_rows_[k].first * width * 4,
width * 4, r.ctx.stream()));
return RAD_OK;
}
int Engine::collect_scored_rows() {
if (score_rows_.empty()) return RAD_OK;
/* step_end_ fences rank 0's stream; every other rank's copies are fenced here. */
for (size_t i = 1; i < ranks_.size(); ++i) {
RAD_TRY(rad_dev_set(ranks_[i]->device));
RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream()));
}
if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device));
for (size_t k = 0; k < score_rows_.size(); ++k) {
TokenScores& ts = *score_rows_[k].second;
ts.logits.assign(ts.tokens.size(), 0.0f);
for (size_t j = 0; j < ts.tokens.size(); ++j) {
const int64_t t = ts.tokens[j];
for (auto& rk : ranks_) {
const SamplerConfig& sc = rk->sampler.config();
if (t < sc.vocab_off || t >= sc.vocab_off + sc.n_vocab_local) continue;
ts.logits[j] = rk->score_host[(int64_t)k * sc.n_vocab_local + (t - sc.vocab_off)];
break;
}
}
}
score_rows_.clear();
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
@@ -1035,6 +1142,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
RAD_TRY(rad_event_sync(step_end_));
std::memcpy(so.rows.data(), so.rb, (size_t)so.n_rows * sizeof(int32_t));
so.rb = nullptr;
RAD_TRY(collect_scored_rows());
const std::vector<float>& lg = so.lg;
const int64_t nv = meta_.n_vocab;
if (!lg.empty()) {
@@ -1281,6 +1389,10 @@ int Engine::arena_step(const RadBatch* b) {
const uint64_t now = rad_mono_ns();
arena_last_ = arena_rows_[(size_t)level];
if (arena_last_ >= arena_floor_) { arena_floor_ = arena_last_; arena_floor_ns_ = now; }
/* Whether the step after this one goes on with a prompt, for the stager to stage that step's
* first layers at this one's end. A step issued ahead is a decode step and the plan the
* scheduler holds is not its own, so it never says so. */
const bool more = b->phase != RAD_PHASE_DECODE && sched_.prefill_continues();
for (auto& r : ranks_) {
const int64_t allow = r->arena_lent[(size_t)level];
if (r->mover.loan(Mover::kLendArena) > allow ||
@@ -1296,6 +1408,7 @@ int Engine::arena_step(const RadBatch* b) {
RAD_TRY(r->ctx.set_level(level));
/* The full plan lends nothing, so its top -- the staging region -- is the step's. */
r->stager.set_full_arena(level == 0);
r->stager.set_next_prefill(more && level == 0);
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
return RAD_OK;
@@ -1602,6 +1715,9 @@ int Engine::serve() {
/* 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;
prefix_off_why_ = "an embedding model: an encoder keeps no KV to reuse, and attending both "
"ways means a shared prefix does not compute to the same rows";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
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);
}
@@ -1771,6 +1887,7 @@ int Engine::serve() {
for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); });
std::thread stepper([this] { step_loop(); });
if (cfg_.kld()) print_startup_report(RAD_OK);
int s = cfg_.kld() ? run_kld() : run_server();
/* Stop the step loop before anything the server owns is destroyed: Request::sink is a raw
@@ -1952,9 +2069,13 @@ void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); }
* SamplingParams' own defaults the untruncated floor
*
* Each source is consulted only if the one above it said nothing at all, so a deployment that
* names a file gets that file's sampler and not a blend of it with the container's. */
* names a file gets that file's sampler and not a blend of it with the container's.
*
* `stated` and `source`, when given, receive what the source in force read and its name ("" for
* none): gen_sampling_sources turns the two into the reason for each field. */
SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool container,
const Config& cfg) {
const Config& cfg, GenSampling* stated = nullptr,
std::string* source = nullptr) {
GenSampling g;
std::string src;
@@ -1999,6 +2120,8 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe
const std::string from = src.empty() ? (over.empty() ? "nothing stated it" : "the command line")
: src;
if (stated) *stated = g;
if (source) *source = src;
RAD_INFO("sampling defaults for requests that send none: %s (from %s%s%s)",
GenSampling::describe(sp).c_str(), from.c_str(),
over.empty() || src.empty() ? "" : ", overridden by", over.c_str());
@@ -2166,6 +2289,7 @@ int Engine::run_server() {
s.experts.staged_units = (int64_t)ms.staged_units;
s.experts.staged_bytes = (int64_t)ms.staged_bytes;
s.experts.stage_overflow = (int64_t)ms.stage_overflow;
s.experts.stage_copies = (int64_t)ms.stage_copies;
s.experts.flex_bytes = ranks_[0]->mover.flex_used_bytes();
s.experts.flex_capacity = ranks_[0]->mover.flex_offered_bytes();
/* THE HEAT ENGINE'S OWN TALLY, which answers a different question from the
@@ -2290,6 +2414,7 @@ int Engine::run_server() {
server::ServerOptions o{};
o.embedding_model = embedding_;
o.decision_type = rad_meta_gets(&meta_, "decision.type", "");
o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name
: meta_.name && *meta_.name ? meta_.name : "radiance";
o.host = cfg_.host;
@@ -2299,12 +2424,27 @@ int Engine::run_server() {
/* `n` fans one request out over the batch, so a server that runs more sequences a step takes
* 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);
if (cfg_.max_n <= 0)
decide("--max-n", std::to_string(o.max_n), "the larger of 8 and --max-num-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_);
{
/* THE FOUR SAMPLER DEFAULTS A FILE CAN STATE, where no flag set them: the value served and,
* field by field, the file or metadata it came from. */
GenSampling stated;
std::string src;
o.default_sampling =
resolve_sampling_defaults(meta_, file_ != nullptr, cfg_, &stated, &src);
for (const GenFieldSource& f : gen_sampling_sources(stated, src, o.default_sampling, cfg_))
decide(f.flag, f.value, f.why);
}
if (cfg_.served_model_name.empty())
decide("--served-model-name", o.model_id,
meta_.name && *meta_.name ? "the name the container states"
: "the container states no name");
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();
@@ -2323,7 +2463,10 @@ int Engine::run_server() {
o.max_stop_bytes = cfg_.max_stop_bytes;
o.default_template_kwargs = cfg_.chat_template_kwargs;
o.reasoning_format = cfg_.reasoning_format;
o.n_threads = cfg_.http_threads;
o.n_threads = server::idle_workers(cfg_.http_threads);
if (cfg_.http_threads <= 0)
decide("--http-threads", std::to_string(o.n_threads),
"one a hardware thread, at least 4");
o.read_timeout_s = cfg_.http_read_timeout_s;
o.write_timeout_s = cfg_.http_write_timeout_s;
o.keep_alive_timeout_s = cfg_.http_keep_alive_timeout_s;
@@ -2339,6 +2482,9 @@ int Engine::run_server() {
/* Per request, not once: the dump carries OpInfo::issued, which only becomes true once the
* run phase has run. See ServerOptions::graph_json. */
o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); };
/* Read again for a request, from a reading at most a second old (Engine::diagnostics_json):
* the links and clocks it reports are only telling under load. */
o.diagnostics_json = [this] { return diagnostics_json(); };
/* MEDIA, WHEN THE PROGRAM DECLARED AN ENCODER. The processor reads its geometry from the
* container and the encoder states the one it was built for; the two meet at the patch width
@@ -2361,6 +2507,14 @@ int Engine::run_server() {
* 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. */
/* LFM2-VL's processor takes pictures only, so the video flags would do nothing on it. */
if (vc.family == mm::Family::Lfm2 &&
(cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames ||
cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) {
RAD_ERR("media: this model's processor takes pictures, not video, so the --video-* "
"flags do nothing on it");
return RAD_E_INVAL;
}
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) {
@@ -2417,15 +2571,33 @@ int Engine::run_server() {
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);
}));
const int pi = mm_proc->init(
vc,
[&tok_bridge](const std::string& t) {
return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false);
},
[this](const std::string& t) { return vocab_->find(t); });
if (pi < 0) {
RAD_ERR("media: the container's processor configuration does not fit this deployment "
"or this vocabulary (a marker it names is missing, or a segment is larger "
"than one encoder pass): %s", rad_strerror(pi));
return pi;
}
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::Lfm2)
RAD_INFO("media: images through '%s'; a picture resizes to %lld..%lld pixels, or one "
"past %g times that is cut into %d..%d tiles of %d pixels a side plus a "
"thumbnail; %lld patches a pass", ranks_[0]->program.encoder_name.c_str(),
(long long)mm_proc->config().image_min_pixels,
(long long)mm_proc->config().image_max_pixels,
mm_proc->config().max_pixels_tolerance, mm_proc->config().min_tiles,
mm_proc->config().max_tiles, mm_proc->config().tile,
(long long)encd.max_patches);
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 "
@@ -2483,6 +2655,8 @@ int Engine::run_server() {
: "takes no images or video");
server::Server srv(d, o);
if (cfg_.max_queued_requests <= 0)
decide("--max-queued-requests", std::to_string(srv.queue_cap()), "8 x --max-num-seqs");
/* A TEMPLATE DEFAULT THE TEMPLATE REFUSES is a 400 on every chat request that leaves it to
* the default, found by the first caller rather than the operator. --chat-template-kwargs
@@ -2530,6 +2704,7 @@ int Engine::run_server() {
why.c_str());
return RAD_E_INVAL;
}
print_startup_report(RAD_OK);
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");
+66
View File
@@ -22,6 +22,7 @@
#pragma once
#include "rad_core.h"
#include "build/startup.h"
#include "diag/diag.h"
#include "mem/hostarena.h"
#include "sched/mem_iface.h"
#include "sched/scheduler.h"
@@ -70,6 +71,20 @@ public:
const Program& program() const;
const Config& config() const { return cfg_; }
/* THE STARTUP REPORT (core/diag/diag.h): every option with the value in force and its source,
* the machine, and what on it costs speed or correctness. serve() prints it before it starts
* listening with `status` RAD_OK; main prints it with the error start() or serve() stopped
* with, so a log of a server that never came up still says what it was running on and what
* it had decided -- and ends with that error again on an E line, because the report's lines
* now follow the one that said it and a reader of the log's tail would see only them. */
void print_startup_report(int status);
/* The same, as JSON, with the hardware read again -- a card's link and clock are only
* meaningful under load, and /diagnostics is how they are read while a request runs. The
* reading is reused for a second, and covers the power-management files of the serving
* cards only (hardware_facts). */
std::string diagnostics_json() const;
bool startup_report_printed() const { return report_printed_; }
private:
/* One thread per tensor-parallel rank, each owning one device. No IPC, no shared-memory
* handshake, no serialisation between ranks -- which is most of what a Python engine spends
@@ -218,6 +233,14 @@ private:
* the device cannot reach until the whole forward pass has run, and that pass is the time the
* walk hides inside. This is a one-shot gate per step, reset while the ranks are parked at the
* release, so there is no window in which a rank can read a stale ready flag. */
/* THIS STEP'S SCORED ROWS (Request::token_scores): a logits row and the result it fills.
* Written by the scheduler thread while the ranks are parked, read by them during the step,
* consumed by collect_step. */
std::vector<std::pair<int32_t, TokenScores*>> score_rows_;
int stage_scored_rows(const StepPlan& plan, const StepOut& so);
int issue_scored_rows(Rank& r);
int collect_scored_rows();
std::mutex build_mu_;
std::condition_variable build_cv_;
bool build_ready_ = false;
@@ -384,6 +407,49 @@ private:
/* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */
std::string engine_info() const;
/* ---- what the startup report says about the run (engine_diag.cpp). `decisions_` holds each
* value startup resolved and why, recorded where it was resolved; the rest are the facts a
* check needs that only startup saw. */
std::vector<diag::Decision> decisions_;
void decide(const std::string& key, const std::string& value, const std::string& why) {
diag::decide(&decisions_, key, value, why);
}
std::string devnote_; /* the devices usable_devices left out, and why */
int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */
std::string p2p_blocked_;
bool has_ngram_ = false; /* the model carries an n-gram table */
std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */
std::vector<std::string> env_set_; /* the RADIANCE_* names set when the engine was made */
bool report_printed_ = false;
/* THE RUNTIME'S DEVICES, ASKED ONCE, in start() beside usable_devices, which reads every
* device's properties anyway. A report printed after start() failed -- possibly after a device
* fault -- then makes no runtime call at all, and /diagnostics, on an HTTP thread, makes none
* either: a runtime call there can wait on a lock the launch path holds
* (DeviceBackend::vram_used says the same of the dashboard). What only the runtime knows --
* each device's PCI address, its name, whether it is integrated, and the runtime's version --
* is kept from that one reading. */
struct DevId { int device = -1; std::string bdf, name; bool integrated = false; };
std::vector<DevId> dev_ids_;
std::string runtime_version_;
void identify_devices(const std::vector<std::string>& names);
/* WHAT ONLY A SYSTEM CALL ANSWERS (diag::probe_process), asked once when the report is first
* printed: the memlock limit cannot change under a running process, and the io_uring probe is
* a syscall that /diagnostics has no reason to repeat on every request. */
bool probed_ = false;
int64_t memlock_soft_ = -1;
std::string io_uring_;
/* THE MACHINE AS /diagnostics LAST READ IT, kept for kDiagReuseNs. The card files are answered
* by the SMU under the driver's power-management lock, so a client polling the endpoint must
* not turn into a stream of SMU requests beside the serving process; a second's staleness is
* nothing to a reading of links and clocks. */
mutable std::mutex diag_mu_;
mutable diag::Facts diag_facts_;
mutable uint64_t diag_read_ns_ = 0;
/* `serving`: read the power-management files of the cards the ranks serve on only
* (diag::collect's `managed`), which is how a running server reads them. */
diag::Facts hardware_facts(bool serving) const;
diag::RunFacts run_facts(bool failed) const;
/* One dispatch of the tiering seam: retire what landed, credit last step's routing and issue
* what the heat engine proposes. A member because Rank is private, and a no-op on a static
* plan. See the long note at the definition for why a step is the unit. */
+152 -7
View File
@@ -20,6 +20,7 @@
#include "rad_plugin.h"
#include "mem/vram_budget.h"
#include "runtime/arena.h"
#include "runtime/xprefetch.h"
#include "sample/gbnf.h"
#include "sched/scheduler.h"
#include "text/tokenizer.h"
@@ -166,9 +167,14 @@ static MissReport miss_report(const Program& p, bool host_backend) {
* an APU machine -- and of those the ones sharing the first one's arch, and prints only what that
* choice DID, rather than reprinting the backend's inventory. Which devices the backend shows at
* all is the runtime's to say: ROCR_VISIBLE_DEVICES and HIP_VISIBLE_DEVICES pick them. */
static int usable_devices(std::vector<int>* out, std::string* inventory, std::string* note) {
/* `names` receives every device's product name, indexed by device ("" where its properties could
* not be read), for the startup report's identification of the cards (Engine::identify_devices):
* the properties are read here once, and reading them again visits each device. */
static int usable_devices(std::vector<int>* out, std::string* inventory, std::string* note,
std::vector<std::string>* names) {
const int n = rad_dev_count();
if (n <= 0) return RAD_E_DEVICE;
names->assign((size_t)n, std::string());
struct D { int i; std::string arch; bool igpu; };
std::vector<D> all;
@@ -177,6 +183,7 @@ static int usable_devices(std::vector<int>* out, std::string* inventory, std::st
for (int i = 0; i < n; ++i) {
RadDeviceProps p{};
if (rad_dev_props(i, &p) < 0) continue;
(*names)[(size_t)i] = p.name;
const bool igpu = dev_integrated(i);
inv += fmt("%s%d:%s%s", i ? " " : "", i, p.arch, igpu ? "(integrated)" : "");
all.push_back({ i, p.arch, igpu });
@@ -635,6 +642,13 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(),
table_placement_name(ng),
cfg_.ngram_placement == TablePlacement::Auto ? " (auto)" : "", ng_why.c_str());
decide("--embedding-placement", table_placement_name(emb),
emb_max > 0 ? fmt("the table is %s a rank: %s", humanb(emb_max).c_str(), emb_why.c_str())
: emb_why);
has_ngram_ = ngram_bytes > 0;
decide("--ngram-placement", ngram_bytes > 0 ? table_placement_name(ng) : "n/a",
ngram_bytes > 0 ? fmt("the table is %s: %s", humanb(ngram_bytes).c_str(), ng_why.c_str())
: std::string("this model has no n-gram table"));
return RAD_OK;
}
@@ -906,6 +920,10 @@ int Engine::declare() {
cfg_.n_spec = 0;
cfg_.prefix_cache = false;
if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0;
decide("--num-speculative-tokens", "0", "the KL mode scores the trunk's own rows");
prefix_off_why_ =
"the KL mode: a prefix hit would start a document past positions the reference holds";
decide("--no-prefix-cache", "prefix caching off", prefix_off_why_);
}
if (cfg_.n_spec < 0) {
RadArchProbe pb{};
@@ -916,6 +934,9 @@ int Engine::declare() {
"(--num-speculative-tokens N overrides it)", cfg_.n_spec);
else
RAD_INFO("speculation: off -- this container carries no draft head");
decide("--num-speculative-tokens", std::to_string(cfg_.n_spec),
cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
: "this container carries no draft head");
}
/* THE ENCODER'S PASS SIZE, resolved the same way and for the same reason: whether there is a
* tower to size is a property of the model file. A container says so (`radiance.encoder`,
@@ -946,6 +967,13 @@ int Engine::declare() {
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");
decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches),
cfg_.mm_max_patches > 0
? "the model carries a vision tower: 16384 patches is a 2048 x 2048 image, the "
"largest one encoder pass takes"
: tower ? "the checkpoint has a vision tower but this container was converted "
"without its weights"
: "the model carries no vision tower");
}
std::vector<int> st(ranks_.size(), RAD_OK);
@@ -1217,6 +1245,21 @@ int Engine::plan() {
for (RadStream s : q) if (s) rad_stream_destroy(s);
}
f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0);
/* THE EXPERT PREFETCH'S STREAM, RING AND BUFFERS, where it can be on: a placement that
* keeps experts in a pinned pool, not --deterministic, on a backend with a DMA engine to
* spare for it (asked before the free figure below, so its queue there is already held). */
WeightFootprint xwf;
weight_footprint(r->program, &xwf, TablePlacement::Vram, TablePlacement::Disk, device_is_host(),
file_ != nullptr);
if (xwf.routed && xwf.expert_unit_max > 0 && !cfg_.deterministic &&
(cfg_.placement == "auto" || cfg_.placement == "expert_tiered") && rad_xp_supported(r->device)) {
/* Counted as Ctx::bind_routing counts the routed layers: past the trunk where a head is. */
int64_t nl = r->program.meta.n_layers;
for (const WeightInfo& w : r->program.weights)
if (w.decl.group.expert >= 0) nl = std::max(nl, (int64_t)w.decl.group.layer + 1);
f.n_queues += 1;
f.prefetch = xp_device_bytes(xwf.expert_unit_max, nl);
}
RadDeviceProps props{};
rad_dev_props(r->device, &props);
f.capacity = props.vram_bytes;
@@ -1326,6 +1369,10 @@ int Engine::plan() {
VramBudget vb;
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
decide("vram split",
fmt("weights %s (experts %s of it), KV cache %s, a card", humanb(vb.weights).c_str(),
humanb(vb.experts).c_str(), humanb(vb.kv).c_str()),
vb.report);
/* The staging region the budget took out of the experts, above everything the buffer plan
* placed -- so it is at the top of the arena, the part the smaller levels lend. */
if (vb.stage > 0)
@@ -1478,6 +1525,21 @@ int Engine::plan() {
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()));
if (r->index == 0) {
decide("--placement", strategy_name(r->plan.strategy),
r->plan.strategy_why.empty() ? std::string("as asked") : r->plan.strategy_why);
const int64_t host = r->plan.totals.bytes[(int)Tier::HostPinned] +
r->plan.totals.bytes[(int)Tier::HostPageable];
decide("weights by tier",
fmt("VRAM %s, host pool %s, container on disk %s, mapped %s (rank 0)",
humanb(r->plan.totals.bytes[(int)Tier::VRAM]).c_str(), humanb(host).c_str(),
humanb(r->plan.totals.bytes[(int)Tier::SSD]).c_str(),
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
r->plan.embedding_host_used > 0
? fmt("the host pool holds the token embedding's %s beside the weights "
"placed there", humanb(r->plan.embedding_host_used).c_str())
: std::string());
}
/* --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. */
@@ -2511,6 +2573,10 @@ int Engine::load_weights() {
"(%s); it is read from the container%s", w.name.c_str(), into,
why.c_str(), card ? " by the host gather" : "");
cfg_.ngram_resolved = TablePlacement::Disk;
decide("--ngram-placement", "disk",
fmt("auto chose a %s copy in RAM, which could not be made (%s); the "
"rows are read from the container%s", into, why.c_str(),
card ? " by the host gather" : ""));
}
/* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows
* out of it, and the only reason a weight is on this tier at all is that it is far
@@ -2765,6 +2831,14 @@ int Engine::configure_kv() {
/* Resolved once, for the cache below and for Scheduler::init later. Resolving it separately in
* each is how the two come to disagree, and the interval is the field where that shows. */
RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_));
if (geo_.checkpoint_interval != cfg_.checkpoint_interval)
decide("--checkpoint-interval",
geo_.checkpoint_interval ? std::to_string(geo_.checkpoint_interval) : "0 (none)",
geo_.checkpoint_interval
? fmt("rounded up to a multiple of %lld tokens, the step quantum (the attention "
"block and the linear-state chunk), so a checkpoint is a legal chunk split",
(long long)geo_.quantum)
: std::string("the model keeps no linear state to checkpoint"));
/* ONE BLOCK TABLE SERVES EVERY RANK (serve() checks it), so every rank carves the SAME number
* of paged blocks. The ranks' pools are not the same size under an uneven tensor-parallel
* split -- a rank with more delta-net heads holds more recurrent state, a rank with zero
@@ -3231,8 +3305,13 @@ int Engine::start() {
* are each attributed to the card they are about. At tp 1 there is nothing to disambiguate. */
log_rank_tags(cfg_.tp > 1);
int s = usable_devices(&devs, &inventory, &devnote);
std::vector<std::string> dev_names;
int s = usable_devices(&devs, &inventory, &devnote, &dev_names);
/* Before any refusal below, so a report printed for a startup that stopped here still joins
* the runtime's devices to the machine's cards. */
identify_devices(dev_names);
if (!devnote.empty()) RAD_WARN("device: %s", devnote.c_str());
devnote_ = devnote;
if (s < 0) { RAD_ERR("no usable device"); return s; }
if ((int)devs.size() < cfg_.tp) {
@@ -3242,12 +3321,29 @@ int Engine::start() {
}
RAD_TRY(read_metadata());
if (cfg_.max_ctx == 0)
decide("--max-model-len", std::to_string(meta_.n_ctx_train),
"the model's training context (--max-model-len 0)");
RAD_TRY(load_vocab());
/* 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());
{
/* THE LIBRARIES THAT LOADED, in the order that decides selection: what --kernels named, or
* every library the home holds when it named none. */
std::string libs;
for (const PluginId& p : plugins_.kernels)
libs += (libs.empty() ? "" : ",") + p.name + (p.version.empty() ? "" : "@" + p.version);
decide("--kernels", libs.empty() ? "none" : libs,
cfg_.kernel_hierarchy.empty()
? "every kernel library under --radiance-home, in the loader's order (a reference "
"implementation last); architecture plugin " + plugins_.arch_plugin +
(plugins_.arch_version.empty() ? "" : "@" + plugins_.arch_version)
: "the libraries named, in that order; architecture plugin " + plugins_.arch_plugin +
(plugins_.arch_version.empty() ? "" : "@" + plugins_.arch_version));
}
ranks_.clear();
for (int i = 0; i < cfg_.tp; ++i) {
@@ -3291,6 +3387,15 @@ int Engine::start() {
const bool forced_off = cfg_.p2p == RAD_P2P_OFF;
if (forced_off) p2p = 0;
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
p2p_measured_ = (int)p2p;
p2p_blocked_ = blocked;
if (cfg_.tp > 1)
decide("--p2p", p2p ? "peer to peer" : "through pinned host memory",
p2p ? "the driver reports every pair of the ranks' cards can reach the other's memory"
: forced_off ? "--p2p off"
: "the driver reports no peer access between cards " + blocked);
else
decide("--p2p", "n/a", "one rank: no collective crosses a card");
if (cfg_.tp > 1) {
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
"peer)", cfg_.tp);
@@ -3317,6 +3422,27 @@ int Engine::start() {
* implementation is a container that will serve at reference speed, and that is a decision the
* operator makes rather than one the engine discovers three minutes into a load. */
RAD_TRY(rad_gate_reference_kernels(ranks_[0]->program, cfg_.accept_reference_kernels, "serve"));
{
/* WHAT SELECTION CHOSE, in two lines a reader can compare across machines: how many of the
* declared op bands each library serves, and the attention rows by name -- the family whose
* choice moves with the card, the head width and the context. */
std::map<std::string, int> by_lib;
std::set<std::string> attn;
for (const OpInfo& op : ranks_[0]->program.ops)
for (const Band& b : op.bands)
for (int dm = 0; dm < RAD_N_DOMAINS; ++dm) {
const KernelRow* row = b.dom[dm].row;
if (!row || !row->info) continue;
++by_lib[row->plugin + (dm == RAD_DOMAIN_HOST ? " (host)" : "")];
if (row->info->family && !std::strcmp(row->info->family, "attn"))
attn.insert(op.op + " -> " + row->info->name);
}
std::string libs, rows;
for (const auto& [lib, n] : by_lib) libs += fmt("%s%s %d", libs.empty() ? "" : ", ", lib.c_str(), n);
for (const std::string& a : attn) rows += (rows.empty() ? "" : "\n") + a;
decide("kernel selection", libs.empty() ? "none" : libs + " op bands",
rows.empty() ? std::string() : "attention:\n" + rows);
}
RAD_TRY(plan());
RAD_TRY(load_weights());
@@ -3360,11 +3486,11 @@ int Engine::start() {
(char*)r->ctx.arena_base() + r->program.arena_stage_off,
r->program.arena_stage_bytes, top_level + 1));
if (r->stager.enabled() && r->index == 0)
RAD_INFO("prefill staging: two %s buffers at the top of the arena; a step of "
"more than %lld tokens copies the next of %zu routed layers' pooled "
"experts onto the card while the one before it runs",
humanb(r->stager.buffer_bytes()).c_str(), (long long)top_level,
r->stager.n_layers());
RAD_INFO("prefill staging: a %s ring at the top of the arena; a step of more "
"than %lld tokens copies the pooled experts of %zu routed layers onto "
"the card up to %d layers ahead of the layers that read them",
humanb(r->stager.ring_bytes()).c_str(), (long long)top_level,
r->stager.n_layers(), (int)PrefillStager::lead());
}
/* THE FILE STAGER, wherever the plan put a routed expert on the file tier -- static plan
* or dynamic, since a file-tier unit has no other address. */
@@ -3411,6 +3537,16 @@ int Engine::start() {
RAD_TRY(r->mover.lend_from(Mover::kLendKV, strips));
if (r->mover.flex_capacity() > 0) lending_ = true;
}
/* THE NEXT-LAYER EXPERT PREFETCH, wherever the placement left experts in a pinned pool for a
* routed layer's GEMMs to read across the link (core/runtime/xprefetch.h). Its stream and ring are
* in the VRAM budget (xp_device_bytes, Engine::plan). Not under --deterministic, where nothing moves. */
if (!cfg_.deterministic)
for (auto& r : ranks_) {
RAD_TRY(rad_dev_set(r->device));
uint64_t lo[kXpMaxPools], hi[kXpMaxPools], st[kXpMaxPools];
const int n = r->mover.pool_ranges(lo, hi, st, kXpMaxPools);
if (n > 0) r->ctx.xp_open(lo, hi, st, n);
}
(void)rad_dev_set(ranks_[0]->device);
/* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends
@@ -3430,6 +3566,15 @@ int Engine::start() {
}
const int64_t mlen = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train;
const int64_t lent = lending_ ? ranks_[0]->mover.flex_capacity() : 0;
if (bytes > 0)
decide("kv cache",
fmt("%s a card: %lld tokens, %.1f sessions at %lld", humanb(bytes).c_str(),
(long long)tokens, mlen > 0 ? (double)tokens / (double)mlen : 0.0,
(long long)mlen),
fmt("%s of it is per-sequence state; %s", humanb(state).c_str(),
lent > 0 ? fmt("up to %s is lent to the experts while no request holds it",
humanb(lent).c_str()).c_str()
: "nothing is lent: it is all the cache's"));
if (bytes > 0)
RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at "
"%lld -- with every block it lends the experts taken back; %s of that is "
+160
View File
@@ -0,0 +1,160 @@
/* engine_diag.cpp -- the startup report's engine half: the facts only a started engine has, joined
* to the machine's (core/diag/diag.h).
*
* THE CARDS ARE JOINED BY PCI ADDRESS. The runtime numbers its devices its own way -- a visible-
* device mask renumbers them, an integrated GPU may come first -- and the kernel describes them by
* bus address; the backend's pci_address is the one key both sides agree on.
*/
#include "engine_priv.h"
#include "device/device.h"
#include <algorithm>
namespace rad {
namespace {
/* How long /diagnostics reuses a reading of the machine. */
constexpr uint64_t kDiagReuseNs = 1000000000ull;
} /* namespace */
void Engine::identify_devices(const std::vector<std::string>& names) {
dev_ids_.clear();
runtime_version_ = dev_runtime_version();
for (int d = 0; d < (int)names.size(); ++d) {
DevId id;
id.device = d;
id.bdf = dev_pci_address(d);
if (id.bdf.empty()) continue;
id.name = names[(size_t)d];
id.integrated = dev_integrated(d);
dev_ids_.push_back(std::move(id));
}
}
diag::Facts Engine::hardware_facts(bool serving) const {
std::vector<std::string> mine;
for (const DevId& id : dev_ids_)
for (const auto& r : ranks_)
if (r->device == id.device) mine.push_back(id.bdf);
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
f.host.runtime = runtime_version_;
if (probed_) {
f.host.memlock_soft = memlock_soft_;
f.host.io_uring = io_uring_;
}
for (const DevId& id : dev_ids_)
for (diag::CardFacts& c : f.cards) {
if (c.bdf != id.bdf) continue;
c.name = id.name;
c.device = id.device;
c.integrated = id.integrated;
for (const auto& r : ranks_)
if (r->device == id.device) c.rank = r->index;
if (c.rank >= 0) c.dma = dev_dma_lane(id.device);
}
return f;
}
diag::RunFacts Engine::run_facts(bool failed) const {
diag::RunFacts r;
r.version = RAD_VERSION;
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
r.device_build = true;
#else
r.device_build = false;
#endif
r.tp = cfg_.tp;
r.host_backend = device_is_host();
r.failed = failed;
r.p2p = cfg_.tp > 1 ? p2p_measured_ : -1;
r.p2p_forced_off = cfg_.p2p == RAD_P2P_OFF;
r.p2p_blocked = p2p_blocked_;
if (!devnote_.empty()) r.ignored.push_back(devnote_);
r.tp_wire_lossy = !cfg_.tp_wire_exact;
r.tp_wire_min_kb = cfg_.tp_wire_min_kb;
r.prefix_cache = cfg_.prefix_cache;
r.prefix_cache_off_why = prefix_off_why_;
r.prefix_host_mib = cfg_.prefix_cache_host_mib;
r.prefix_disk_mib = cfg_.prefix_cache_disk_mib;
r.host_pool_mib = cfg_.host_pool_mib;
{
int64_t pinned = 0, mapped = 0, n = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, &n);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, &n);
r.pinned_bytes = pinned + mapped;
}
/* THE MOST ANY RANK READS FROM THE HOST: the ranks step together, so the one that streams most
* is the one each step waits for. The embedding the placement flag put in host memory is read
* a few rows a step and is not what this counts. */
for (const auto& rk : ranks_) {
const Plan& p = rk->plan;
const int64_t host = p.totals.bytes[(int)Tier::HostPinned] +
p.totals.bytes[(int)Tier::HostPageable] - p.embedding_host_used;
r.host_weight_bytes = std::max(r.host_weight_bytes, std::max<int64_t>(host, 0));
r.file_weight_bytes = std::max(r.file_weight_bytes, p.totals.bytes[(int)Tier::SSD]);
}
for (const TableCopy& t : table_copies_) r.locked_bytes += (int64_t)t.bytes;
r.ngram_placement = has_ngram_ ? table_placement_name(cfg_.ngram_resolved) : "";
r.reference_kernels = cfg_.accept_reference_kernels;
r.profile_ops = cfg_.profile_ops;
r.deterministic = cfg_.deterministic;
r.environment = env_set_;
return r;
}
void Engine::print_startup_report(int status) {
report_printed_ = true;
if (!probed_) {
diag::HostFacts h;
diag::probe_process(&h);
memlock_soft_ = h.memlock_soft;
io_uring_ = h.io_uring;
probed_ = true;
}
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
std::vector<diag::Decision> derived;
diag::merge(&rows, decisions_, &derived);
const diag::Facts f = hardware_facts(false);
const diag::RunFacts r = run_facts(status < 0);
const std::vector<diag::Finding> found = diag::check(f, r);
/* A LINE A LOG CALL: the logger formats into a fixed buffer, and one line each keeps every line
* of the report on the same level tag a grep for the startup reads. */
const std::string text = diag::render(rows, derived, f, r, found);
size_t at = 0;
while (at < text.size()) {
size_t nl = text.find('\n', at);
if (nl == std::string::npos) nl = text.size();
RAD_INFO("%s", text.substr(at, nl - at).c_str());
at = nl + 1;
}
/* AND EACH WARNING ON A W LINE OF ITS OWN, because the warnings are what a reader filtering a
* production log for W and E lines is looking for. */
for (const diag::Finding& x : found)
if (x.level == diag::Finding::Warn)
RAD_WARN("startup report: %s: %s. Fix: %s", x.id.c_str(), x.what.c_str(), x.fix.c_str());
/* THE FAILURE LAST. The line that said what stopped startup is above the report now, and
* `docker logs --tail` or a terminal's last screen shows only what is below it. */
if (status < 0)
RAD_ERR("startup stopped: %s (the reason is said above the startup report)",
rad_strerror(status));
}
std::string Engine::diagnostics_json() const {
std::vector<diag::ConfigRow> rows = diag::config_rows(cfg_);
std::vector<diag::Decision> derived;
diag::merge(&rows, decisions_, &derived);
diag::Facts f;
{
std::lock_guard<std::mutex> lk(diag_mu_);
const uint64_t now = rad_mono_ns();
if (diag_read_ns_ == 0 || now - diag_read_ns_ >= kDiagReuseNs) {
diag_facts_ = hardware_facts(true);
diag_read_ns_ = now;
}
f = diag_facts_;
}
const diag::RunFacts r = run_facts(false);
return diag::to_json(rows, derived, f, r, diag::check(f, r));
}
} /* namespace rad */
+15 -13
View File
@@ -83,18 +83,19 @@ int Engine::run_encodes() {
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 int32_t first = seg;
for (; seg < it.n_seg; ++seg) {
const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg);
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;
}
if (np + seg_p > max_p) break;
np += seg_p;
}
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 == first) break;
parts.push_back({ &it, first, seg - first });
if (seg == it.n_seg) { ++i; seg = 0; }
}
if (parts.empty()) break;
@@ -127,9 +128,10 @@ int Engine::run_encodes() {
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 first = it.row_at(p.seg0);
const int64_t rows = it.row_at(p.seg0 + p.n_seg) - first;
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,
RAD_TRY(rad_memcpy_async(it.embd.data() + first * n_embd,
static_cast<const char*>(out) +
row * n_embd * (int64_t)sizeof(uint16_t),
bytes, r0.ctx.stream()));
+6
View File
@@ -58,6 +58,8 @@ struct Engine::Rank {
* Without the split, a placement engine starved of evidence reads exactly like a model whose
* layers are idle. */
uint64_t heat_credited = 0, heat_idle = 0;
/* Trunk steps in a row whose pass the prefill stager did not arm (Engine::tiering_dispatch). */
int unstaged_steps = 0;
Residency residency;
KVManager kv;
PrefixCache prefix;
@@ -84,6 +86,10 @@ struct Engine::Rank {
StagerChain stagers;
Ctx ctx;
Sampler sampler; /* one per rank: each samples its own vocab shard (spec §9) */
/* THE SCORED ROWS' LOGITS (Request::token_scores), this rank's vocabulary shard of each,
* copied into pinned memory ahead of the sampler. Grown to the most rows a step has scored. */
float* score_host = nullptr;
int64_t score_rows_cap = 0;
rad_buf tok_buf = 0; /* where the chain writes the sampled ids */
/* THE CARD'S STEP STATE (sched/advance.h): one StepSlot a scheduler slot, and the
* end-of-generation ids acceptance stops at, sorted. Every rank keeps its own and computes the
+5 -1
View File
@@ -234,6 +234,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
if (const char* mt = gs("model_type")) {
out->arch.clear();
for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p;
/* LFM2-VL is LFM2 with a vision tower, and unlike Qwen's VL releases it names the wrapper
* rather than the text model. One plugin serves both, the way one serves a Qwen3.5 with
* or without its tower; `model_type` itself stays in the free-form keys. */
if (out->arch == "lfm2vl") out->arch = "lfm2";
}
if (const char* nm = gs("_name_or_path")) out->name = nm;
@@ -257,7 +261,7 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
m.n_expert = gi("num_experts", gi("num_local_experts", 0));
m.n_expert_used = gi("num_experts_per_tok", 0);
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
m.rms_eps = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6)); /* LFM2: norm_eps */
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
+23
View File
@@ -41,6 +41,29 @@ std::string GenSampling::describe(const SamplingParams& sp) {
return buf;
}
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
const SamplingParams& served, const Config& cfg) {
std::vector<GenFieldSource> out;
auto field = [&](const char* flag, const char* name, bool given, bool said, std::string value) {
if (given) return; /* the option's own row says "command line" */
std::string why = said ? "from " + src
: src.empty() ? std::string("the model states no sampling of its own, so "
"this is the built-in default")
: src + " states no " + name +
", so this is the built-in default";
out.push_back({ flag, std::move(value), std::move(why) });
};
field("--temp", "temperature", cfg.sample_temp >= 0.0f, stated.temp >= 0.0f,
fmt("%g", (double)served.temp));
field("--top-k", "top_k", cfg.sample_top_k >= 0, stated.top_k >= 0,
std::to_string(served.top_k));
field("--top-p", "top_p", cfg.sample_top_p >= 0.0f, stated.top_p >= 0.0f,
fmt("%g", (double)served.top_p));
field("--min-p", "min_p", cfg.sample_min_p >= 0.0f, stated.min_p >= 0.0f,
fmt("%g", (double)served.min_p));
return out;
}
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out) {
nlohmann::json j;
try { j = nlohmann::json::parse(json_text); }
+11
View File
@@ -25,6 +25,7 @@
#include <functional>
#include <string>
#include <vector>
namespace rad {
@@ -49,6 +50,16 @@ struct GenSampling {
static std::string describe(const SamplingParams& sp);
};
/* WHERE EACH OF THE FOUR FIELDS SERVED CAME FROM, for the startup report (core/diag/diag.h): one
* entry a field no flag set, with the option that would have set it, the value served and why.
* `stated` is what the source in force read and `src` that source's name ("" for none). A source
* can state some fields and not others -- a generation_config.json with a temperature and no
* top_k -- and a field it left out is served SamplingParams' own value, so the reason is per field:
* one reason for all four would name the file for values that never came from it. */
struct GenFieldSource { std::string flag, value, why; };
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
const SamplingParams& served, const Config& cfg);
/* Parse the sampler fields out of generation_config.json TEXT. `src` names the origin in any
* warning. Returns whether anything was taken. Unparseable text warns and takes nothing. */
bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampling* out);
+14 -2
View File
@@ -15,8 +15,20 @@ int main(int argc, char** argv) {
rad::Engine engine(std::move(cfg));
s = engine.start();
if (s < 0) return 1; /* start() already said what and why */
if (s < 0) {
/* start() already said what and why; the report adds what it was running on and what it
* had decided by then, which is what a log of a server that never came up is read for. */
engine.print_startup_report(s);
return 1;
}
if (engine.config().debug_graph) return engine.dump();
return engine.serve() < 0 ? 1 : 0;
s = engine.serve();
if (s < 0) {
/* A refusal between start() and listening (a chat template the defaults cannot render, a
* thinking budget the model cannot hold) also ends a server that never came up. */
if (!engine.startup_report_printed()) engine.print_startup_report(s);
return 1;
}
return 0;
}
+7 -4
View File
@@ -60,6 +60,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
freeb = std::min(freeb, f.free);
b.arena = std::max(b.arena, f.arena);
b.staging = std::max(b.staging, f.staging);
b.prefetch = std::max(b.prefetch, f.prefetch);
if ((int64_t)f.n_queues * f.queue_bytes > b.queues) {
b.queues = (int64_t)f.n_queues * f.queue_bytes;
b.n_queues = f.n_queues;
@@ -111,7 +112,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
/* What is left after the terms nobody gets to spend. */
b.drift = kDriverDrift;
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
b.queues);
b.queues + b.prefetch);
if (b.claimable < 0) {
b.report = fmt(
@@ -123,6 +124,7 @@ 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"
" expert prefetch %10s (its ring of expert units and buffers)\n"
" ------------------------------\n"
" SHORT BY %10s\n"
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
@@ -130,7 +132,7 @@ 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(),
humanb(-b.claimable).c_str());
humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str());
if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b;
return RAD_E_NOMEM;
@@ -271,7 +273,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* the headroom. */
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues -
b.stage - granted;
b.prefetch - b.stage - granted;
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
b.report = fmt(
"VRAM budget, per card:\n"
@@ -282,6 +284,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" step staging %10s the step batch's block tables and media staging, and the\n"
" KV tiers' copy staging\n"
" hardware queues %10s %d a card at %s each, measured: the engine's streams\n"
" expert prefetch %10s the next-layer prefetch's ring of expert units and buffers\n"
" %-18s %10s %s\n"
" ------------------------------\n"
" claimable %10s\n"
@@ -299,7 +302,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" could not place\n",
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).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(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), humanb(b.prefetch).c_str(),
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
shared ? "integrated graphics: this memory is the host's"
: "left unclaimed on purpose",
+4
View File
@@ -81,6 +81,9 @@ struct VramFacts {
* times the ring). */
int n_queues = 0;
int64_t queue_bytes = 0;
/* THE NEXT-LAYER EXPERT PREFETCH's ring of expert units and its buffers (xprefetch.h), where it
* will be on; its stream is one of `n_queues`. */
int64_t prefetch = 0;
int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
@@ -111,6 +114,7 @@ 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 */
int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */
int64_t prefetch = 0; /* the expert prefetch's ring and buffers */
int n_queues = 0;
int64_t queue_bytes = 0;
int64_t claimable = 0; /* after the fixed terms above */
+7 -5
View File
@@ -21,11 +21,13 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
}
/* 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;
const int32_t merge = grid_h / rows_h;
const int64_t bw = grid_w / merge;
int32_t s = 0;
while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s;
for (int64_t k = 0; k < count; ++k) {
const int64_t within = (first + k) % seg;
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
const int64_t within = first + k - patch_at(s);
const int64_t bw = seg_w(s) / merge;
const int64_t in_col = within % merge;
const int64_t in_row = (within / merge) % merge;
const int64_t blk = within / (merge * merge);
@@ -33,8 +35,8 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
const int64_t col = (blk % bw) * merge + in_col;
planes[k] = (int32_t)row;
planes[count + k] = (int32_t)col;
planes[2 * count + k] = grid_h;
planes[3 * count + k] = grid_w;
planes[2 * count + k] = seg_h(s);
planes[3 * count + k] = seg_w(s);
}
}
+285 -28
View File
@@ -30,7 +30,65 @@ static bool soft_budget_ok(int32_t n) {
return n == 70 || n == 140 || n == 280 || n == 560 || n == 1120;
}
/* A flag a container flattened from JSON: `true`/`false`, or a number. */
static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
const char* v = rad_meta_gets(&m, key, nullptr);
if (!v || !*v) return dflt;
if (!std::strcmp(v, "true")) return true;
if (!std::strcmp(v, "false")) return false;
return std::strtol(v, nullptr, 10) != 0;
}
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
/* LFM2-VL states its processor twice, in config.json and in processor_config.json's
* image_processor; the latter is what the reference processor reads, so it goes first. */
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) {
family = Family::Lfm2;
auto key = [](const char* k) { return std::string("processor.image_processor.") + k; };
auto geti = [&](const char* k, int64_t dflt) {
return rad_meta_geti(&m, key(k).c_str(), rad_meta_geti(&m, k, dflt));
};
auto getb = [&](const char* k, bool dflt) {
return meta_bool(m, key(k).c_str(), meta_bool(m, k, dflt));
};
patch = (int32_t)geti("encoder_patch_size", rad_meta_geti(&m, "vision_config.patch_size", 0));
merge = (int32_t)geti("downsample_factor", 0);
temporal = 1;
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
if (patch <= 0 || merge <= 0 || tok_image < 0) {
if (why) *why = "the container states no LFM2-VL processor geometry (encoder_patch_size, "
"downsample_factor, image_token_id)";
return RAD_E_NOTFOUND;
}
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = geti("min_image_tokens", 64) * f2;
image_max_pixels = geti("max_image_tokens", 256) * f2;
video_min_pixels = image_min_pixels; /* no video; consistent for check() */
video_max_pixels = image_max_pixels;
/* The markers around a picture and before each tile are what the model was trained on;
* a checkpoint that turns them off spells its pictures differently, which is not served. */
if (!meta_bool(m, "use_image_special_tokens", true)) {
if (why) *why = "use_image_special_tokens is off; this processor writes LFM2-VL's "
"picture markers and serves only the checkpoints that read them";
return RAD_E_UNSUPPORTED;
}
const bool split = getb("do_image_splitting", true);
min_tiles = split ? (int32_t)geti("min_tiles", 2) : 1;
max_tiles = split ? (int32_t)geti("max_tiles", 10) : 1;
tile = (int32_t)geti("tile_size", 512);
use_thumbnail = getb("use_thumbnail", true);
max_pixels_tolerance = rad_meta_getf(&m, key("max_pixels_tolerance").c_str(),
rad_meta_getf(&m, "max_pixels_tolerance", 2.0));
max_segment_patches = geti("max_num_patches", 1024);
if (!read_triple(m, key("image_mean").c_str(), mean)) read_triple(m, "preprocessor.image_mean", mean);
if (!read_triple(m, key("image_std").c_str(), stdv)) read_triple(m, "preprocessor.image_std", stdv);
std::string bad;
if (check(&bad) < 0) {
if (why) *why = "the container's LFM2-VL processor configuration is inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
const char* mt = rad_meta_gets(&m, "vision_config.model_type", "");
if (mt && !std::strcmp(mt, "gemma4_vision")) {
family = Family::Gemma4;
@@ -138,6 +196,16 @@ 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::Lfm2) {
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
return no("the tiling (min_tiles " + std::to_string(min_tiles) + ", max_tiles " +
std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) +
") is not a range of whole merged patches");
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
return no("max_pixels_tolerance and max_num_patches must be positive");
for (int c = 0; c < 3; ++c)
if (!(stdv[c] > 0.0f)) return no("image_std must be positive");
}
if (family == Family::Gemma4) {
if (!soft_budget_ok(image_soft_tokens))
return no("the image soft-token budget " + std::to_string(image_soft_tokens) +
@@ -307,20 +375,21 @@ inline double bicubic(double x) {
return 0.0;
}
inline uint8_t clip8(int32_t v) {
const int32_t s = v >> kPrec;
inline uint8_t clip8(int32_t v, int prec) {
const int32_t s = v >> prec;
return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
}
/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize`
* a row. */
* a row, `*prec` their fraction bits: PIL's fixed 22, or -- `torch` -- ATen's per-axis choice, the
* most bits at which the largest weight still fits an int16. */
int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
std::vector<int32_t>* kk) {
std::vector<int32_t>* kk, bool torch, int* prec) {
const double scale = (double)in_size / (double)out_size;
const double fscale = scale < 1.0 ? 1.0 : scale;
const double support = 2.0 * fscale;
const int ksize = (int)std::ceil(support) * 2 + 1;
std::vector<double> k((size_t)ksize);
std::vector<double> k((size_t)ksize), w((size_t)out_size * (size_t)ksize, 0.0);
bounds->assign((size_t)out_size * 2, 0);
kk->assign((size_t)out_size * (size_t)ksize, 0);
for (int xx = 0; xx < out_size; ++xx) {
@@ -341,24 +410,32 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
for (x = 0; x < xmax; ++x)
if (ww != 0.0) k[(size_t)x] /= ww;
for (; x < ksize; ++x) k[(size_t)x] = 0.0;
for (x = 0; x < ksize; ++x) {
const double v = k[(size_t)x];
(*kk)[(size_t)xx * ksize + x] = v < 0 ? (int32_t)(-0.5 + v * (1 << kPrec))
: (int32_t)(0.5 + v * (1 << kPrec));
}
for (x = 0; x < ksize; ++x) w[(size_t)xx * ksize + x] = k[(size_t)x];
(*bounds)[(size_t)xx * 2] = xmin;
(*bounds)[(size_t)xx * 2 + 1] = xmax;
}
*prec = kPrec;
if (torch) {
double largest = 0.0;
for (double v : w) largest = std::max(largest, v);
for (*prec = 0; *prec < 22; ++*prec)
if ((int)(0.5 + largest * (1 << (*prec + 1))) >= (1 << 15)) break;
}
for (size_t i = 0; i < w.size(); ++i) {
const double v = w[i];
(*kk)[i] = v < 0 ? (int32_t)(-0.5 + v * (1 << *prec)) : (int32_t)(0.5 + v * (1 << *prec));
}
return ksize;
}
} /* namespace */
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
if (in.w == w && in.h == h) { *out = in; return; }
std::vector<int32_t> bh, kh, bv, kv;
const int ksh = coeffs(in.w, w, &bh, &kh);
const int ksv = coeffs(in.h, h, &bv, &kv);
int ph = kPrec, pv = kPrec;
const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph);
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv);
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
const int y_first = bv[0];
@@ -380,16 +457,16 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
for (int xx = 0; xx < w; ++xx) {
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const int32_t* k = kh.data() + (size_t)xx * ksh;
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0;
for (int x = 0; x < xmax; ++x) {
const uint8_t* p = row + (size_t)(x + xmin) * 3;
s0 += p[0] * k[x];
s1 += p[1] * k[x];
s2 += p[2] * k[x];
}
o[xx * 3 + 0] = clip8(s0);
o[xx * 3 + 1] = clip8(s1);
o[xx * 3 + 2] = clip8(s2);
o[xx * 3 + 0] = clip8(s0, ph);
o[xx * 3 + 1] = clip8(s1, ph);
o[xx * 3 + 2] = clip8(s2, ph);
}
}
src = &tmp;
@@ -404,20 +481,34 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
const int32_t* k = kv.data() + (size_t)yy * ksv;
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
for (int xx = 0; xx < src->w; ++xx) {
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0;
for (int y = 0; y < ymax; ++y) {
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
s0 += p[0] * k[y];
s1 += p[1] * k[y];
s2 += p[2] * k[y];
}
o[xx * 3 + 0] = clip8(s0);
o[xx * 3 + 1] = clip8(s1);
o[xx * 3 + 2] = clip8(s2);
o[xx * 3 + 0] = clip8(s0, pv);
o[xx * 3 + 1] = clip8(s1, pv);
o[xx * 3 + 2] = clip8(s2, pv);
}
}
}
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
resize_bicubic_impl(in, w, h, out, false);
}
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) {
resize_bicubic_impl(in, w, h, out, true);
}
void cap_area(const Frame& in, int64_t max_pixels, Frame* out) {
if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; }
const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h));
resize_bicubic(in, std::max(1, (int)(in.w * scale)), std::max(1, (int)(in.h * scale)), out);
}
/* ================================================================== patches */
namespace {
@@ -437,6 +528,10 @@ void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
(uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
uint64_t b = 0xbb67ae8584caa73bull ^
mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u);
/* The tiling, when the segments have sizes of their own: the same patches cut differently
* are different encoder inputs. */
for (const Item::Segment& sg : it.segments)
a = mix64(a ^ ((uint64_t)(uint32_t)sg.h << 32 | (uint32_t)sg.w)) + (uint64_t)sg.patch0;
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;
@@ -536,10 +631,34 @@ void finish_item(const VisionConfig& c, Item* it) {
/* ================================================================== the processor */
int Processor::init(const VisionConfig& cfg,
std::function<std::vector<int32_t>(const std::string&)> encode_text) {
std::function<std::vector<int32_t>(const std::string&)> encode_text,
std::function<int32_t(const std::string&)> token_id) {
if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0)
return RAD_E_INVAL;
cfg_ = cfg;
if (cfg.family == Family::Lfm2) {
/* The markers are named, not numbered, in the config: resolved here, every one, so a
* vocabulary missing one is refused at startup rather than on the first large picture. */
if (!token_id) return RAD_E_INVAL;
cfg_.tok_start = token_id("<|image_start|>");
cfg_.tok_end = token_id("<|image_end|>");
tok_thumbnail_ = token_id("<|img_thumbnail|>");
if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || tok_thumbnail_ < 0) return RAD_E_NOTFOUND;
tok_tiles_.assign((size_t)cfg.max_tiles * cfg.max_tiles, -1);
for (int32_t r = 1; r <= cfg.max_tiles; ++r)
for (int32_t c = 1; r * c <= cfg.max_tiles; ++c) {
const int32_t id = token_id("<|img_row_" + std::to_string(r) + "_col_" +
std::to_string(c) + "|>");
if (id < 0) return RAD_E_NOTFOUND;
tok_tiles_[(size_t)(r - 1) * cfg.max_tiles + (c - 1)] = id;
}
/* A tile and the largest thumbnail are one segment each: of the tower and of a pass. */
const int64_t seg = std::max<int64_t>((int64_t)(cfg.tile / cfg.patch) * (cfg.tile / cfg.patch),
cfg.image_max_pixels / ((int64_t)cfg.patch * cfg.patch));
if (seg > cfg.max_patches || seg > cfg.max_segment_patches) return RAD_E_INVAL;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
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 ||
@@ -559,9 +678,133 @@ int Processor::init(const VisionConfig& cfg,
return RAD_OK;
}
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
int64_t* oh, int64_t* ow) {
const double f = factor;
int64_t hb = std::max<int64_t>(factor, pyround((double)h / f) * factor);
int64_t wb = std::max<int64_t>(factor, pyround((double)w / f) * factor);
if (hb * wb > max_px) {
const double beta = std::sqrt((double)(h * w) / (double)max_px);
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
} else if (hb * wb < min_px) {
const double beta = std::sqrt((double)min_px / (double)(h * w));
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
}
*oh = hb;
*ow = wb;
}
bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t max_px,
double tolerance) {
const int64_t hb = std::max<int64_t>(patch, pyround((double)h / factor) * factor);
const int64_t wb = std::max<int64_t>(patch, pyround((double)w / factor) * factor);
return (double)(hb * wb) > (double)max_px * tolerance;
}
/* The reference walks the ratios sorted by tile count; within one count it orders them as a
* Python set happens to, which this walks by columns. The two can differ only on an exact tie
* between two grids of one count, both nearest. */
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows) {
const double aspect = (double)w / (double)h;
double best = INFINITY;
*cols = *rows = 1;
for (int32_t n = min_tiles; n <= max_tiles; ++n)
for (int32_t c = 1; c <= n; ++c) {
if (n % c) continue;
const int32_t r = n / c;
const double diff = std::fabs(aspect - (double)c / (double)r);
if (diff < best) {
best = diff; *cols = c; *rows = r;
} else if (diff == best && (double)(w * h) > 0.5 * tile * tile * (double)n) {
*cols = c; *rows = r;
}
}
}
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
* in row-major order, then the thumbnail; within one, patches in merge-block order (each
* merge x merge block's patches consecutive, dy then dx -- which is how the projector's pixel
* unshuffle reads them, so its merge is a view), each patch (y, x, channel). */
int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
const int32_t F = c.factor(), P = c.patch, M = c.merge;
int64_t th = 0, tw = 0;
lfm2_size(f.h, f.w, F, c.image_min_pixels, c.image_max_pixels, &th, &tw);
const bool large = lfm2_too_large(f.h, f.w, P, F, c.image_max_pixels, c.max_pixels_tolerance);
int32_t cols = 1, rows = 1;
if (large && !(c.min_tiles == 1 && c.max_tiles == 1))
lfm2_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows);
const bool tiled = cols * rows > 1;
if (th / P * (tw / P) > std::min(c.max_patches, c.max_segment_patches)) {
if (why) *why = "the picture's aspect ratio needs more patches than one encoder segment holds";
return RAD_E_INVAL;
}
uint16_t lut[3][256];
for (int ch = 0; ch < 3; ++ch)
for (int v = 0; v < 256; ++v)
lut[ch][v] = rad_f32_to_bf16(((float)v - 255.0f * c.mean[ch]) / (255.0f * c.stdv[ch]));
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->patch_dim = c.patch_dim();
it->rope_1d = true;
it->expand.push_back(c.tok_start);
/* One segment of `frame`'s gh x gw patches from (x0, y0), its placeholders after `marker`. */
auto append = [&](const Frame& frame, int x0, int y0, int gh, int gw, int32_t marker) {
it->segments.push_back({ gh, gw, it->n_patch });
it->n_patch += (int64_t)gh * gw;
if (marker >= 0) it->expand.push_back(marker);
it->seg_at.push_back((int32_t)it->expand.size());
it->expand.insert(it->expand.end(), (size_t)gh * gw / (M * M), c.tok_image);
const size_t at = it->pixels.size();
it->pixels.resize(at + (size_t)gh * gw * it->patch_dim);
uint16_t* dst = it->pixels.data() + at;
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)
for (int y = 0; y < P; ++y) {
const uint8_t* row = frame.rgb.data() +
((size_t)(y0 + (bh * M + mh) * P + y) * frame.w +
x0 + (bw * M + mw) * P) * 3;
for (int x = 0; x < 3 * P; ++x) *dst++ = lut[x % 3][row[x]];
}
};
if (tiled) {
Frame big;
resize_bicubic_torch(f, cols * c.tile, rows * c.tile, &big);
const int g = c.tile / P;
for (int32_t r = 0; r < rows; ++r)
for (int32_t col = 0; col < cols; ++col)
append(big, col * c.tile, r * c.tile, g, g,
tok_tiles_[(size_t)r * c.max_tiles + col]);
}
if (!tiled || c.use_thumbnail) {
Frame small;
resize_bicubic_torch(f, (int32_t)tw, (int32_t)th, &small);
append(small, 0, 0, (int)(th / P), (int)(tw / P), tiled ? tok_thumbnail_ : -1);
}
it->expand.push_back(c.tok_end);
it->n_seg = it->grid_t = (int32_t)it->segments.size();
it->grid_h = it->segments[0].h;
it->grid_w = it->segments[0].w;
it->rows_h = it->grid_h / M;
it->rows_w = it->grid_w / M;
it->seg_rows = it->rows_h * it->rows_w;
if (it->n_seg == 1) it->segments.clear(); /* one segment is the uniform form */
content_key(*it, &it->key_hi, &it->key_lo);
*out = std::move(it);
return RAD_OK;
}
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);
if (c.family == Family::Lfm2) return image_lfm2(f, 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));
@@ -745,7 +988,7 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
}
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
std::shared_ptr<Item>* out, std::string* why) const {
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) 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 "
@@ -762,6 +1005,11 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
}
Frame f;
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
if (max_pixels > 0 && (int64_t)f.w * f.h > max_pixels) {
Frame capped;
cap_area(f, max_pixels, &capped);
f = std::move(capped);
}
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);
@@ -778,6 +1026,10 @@ std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
std::string* why) const {
if (cfg_.family == Family::Lfm2) {
if (why) *why = "this model's processor takes pictures, not video";
return RAD_E_UNSUPPORTED;
}
Video v;
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames,
cfg_.family == Family::Gemma4 };
@@ -1056,19 +1308,24 @@ void PromptMedia::layout() {
for (size_t pi = 0; pi < items.size(); ++pi) {
const Placed& p = items[pi];
const Item& it = *p.item;
const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1;
for (int32_t s = 0; s < it.n_seg; ++s) {
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
pos += run_tok - tok; /* the text in front of the run counts up */
const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m;
const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m;
RopeLayout::Run r;
r.tok = (int32_t)run_tok;
r.n = it.seg_rows;
r.w = it.rows_w;
r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s));
r.w = rw;
r.base = (int32_t)pos;
pos += std::max(it.rows_h, it.rows_w);
tok = run_tok + it.seg_rows;
r.flat = it.rope_1d;
/* A grid advances the rotary by its longer side; a 1-D run by its length. */
pos += it.rope_1d ? r.n : std::max(rh, rw);
tok = run_tok + r.n;
r.shift = (int32_t)(pos - tok);
r.item = (int32_t)pi;
r.row0 = s * it.seg_rows;
r.row0 = (int32_t)it.row_at(s);
rope.runs.push_back(r);
}
}
+69 -8
View File
@@ -49,8 +49,14 @@ enum class Kind { Image, Video, Audio };
* 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 };
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
* Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole --
* sides multiples of patch * merge, pixels within the budget's band -- and one past it
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
* fixed-point bicubic; images only, and the tokens rotate at their positions. */
enum class Family { QwenVL, Gemma4, Lfm2 };
struct VisionConfig {
Family family = Family::QwenVL;
@@ -69,6 +75,11 @@ struct VisionConfig {
float mean[3] = { 0.5f, 0.5f, 0.5f };
float stdv[3] = { 0.5f, 0.5f, 0.5f };
int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1;
/* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */
int32_t min_tiles = 0, max_tiles = 0, tile = 0;
bool use_thumbnail = false;
double max_pixels_tolerance = 0.0;
int64_t max_segment_patches = 0;
/* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an
* image is one segment and a segment is never split, so no image may resize past it, and the
@@ -139,7 +150,30 @@ struct Item {
/* 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; }
/* SEGMENTS OF THEIR OWN SIZE, when an item's segments differ -- an LFM2-VL picture is its
* tiles and a thumbnail -- each `h` x `w` patches from patch `patch0` on. Empty, every segment
* is grid_h x grid_w (a picture, a video's temporal groups, an audio clip). The accessors
* below are the only way the rest of the engine reads a segment, so both forms look alike. */
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
std::vector<Segment> segments;
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
bool rope_1d = false;
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
int64_t patch_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
return s >= n_seg ? n_patch : segments[(size_t)s].patch0;
}
int64_t row_at(int32_t s) const {
if (segments.empty()) return (int64_t)s * seg_rows;
const int64_t m = rows_h > 0 ? grid_h / rows_h : 1;
return patch_at(s) / (m * m);
}
int64_t n_rows() const { return row_at(n_seg); }
/* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of
* placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one:
@@ -175,6 +209,7 @@ struct RopeLayout {
int32_t shift = 0; /* rotary minus token index for the text AFTER the run */
int32_t item = 0; /* which of PromptMedia::items the run belongs to */
int32_t row0 = 0; /* the item's encoder row that its first token takes */
bool flat = false; /* Item::rope_1d: the run's tokens rotate at their positions */
};
std::vector<Run> runs; /* ascending */
@@ -195,7 +230,7 @@ struct RopeLayout {
const Run* r = last_at(i);
if (!r) { out[0] = out[1] = out[2] = (int32_t)i; return; }
const int64_t k = i - r->tok;
if (k < r->n) {
if (k < r->n && !r->flat) {
out[0] = r->base;
out[1] = r->base + (int32_t)(k / r->w);
out[2] = r->base + (int32_t)(k % r->w);
@@ -231,14 +266,18 @@ struct PromptMedia {
class Processor {
public:
/* `encode_text` tokenises the timestamp text between a video's groups: plain text, no
* special tokens added and none parsed. */
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text);
* special tokens added and none parsed. `token_id` is the id of the vocabulary entry spelled
* exactly so, or -1: how a family whose markers the config does not number (LFM2-VL's tile
* and thumbnail markers) finds them. */
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text,
std::function<int32_t(const std::string&)> token_id = {});
const VisionConfig& config() const { return cfg_; }
/* `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. */
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
* scales a larger picture down to that area (PIL's bicubic), as a caller's own pipeline may. */
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
std::string* why) const;
std::string* why, int64_t max_pixels = 0) 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. */
@@ -257,6 +296,10 @@ public:
private:
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const;
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
int video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
VisionConfig cfg_{};
@@ -288,6 +331,24 @@ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_p
/* 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);
/* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the
* coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */
void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out);
/* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels
* within [min_px, max_px] where the rounding left them outside. */
void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
int64_t* oh, int64_t* ow);
/* LFM2-VL's test for a picture to tile: its sides rounded to whole merged patches cover more than
* `max_px` times `tolerance` pixels. */
bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t max_px,
double tolerance);
/* A picture over `max_pixels` scaled down to that area with PIL's bicubic, sides truncated; any
* other picture as it is. */
void cap_area(const Frame& in, int64_t max_pixels, Frame* out);
/* LFM2-VL's tile grid for a w x h picture: (columns, rows) of the min..max-tile ratio nearest its
* aspect, the larger grid of two equally near when the picture fills over half of it. */
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows);
} /* namespace mm */
} /* namespace rad */
+20 -12
View File
@@ -139,11 +139,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
return RAD_OK;
}
enabled_ = true;
RAD_INFO("heat engine: %lld movable units, %d move%s a dispatch, "
"decay %.3f hysteresis %.2f min-gain %.2f",
(long long)movable, params_.moves_per_dispatch,
params_.moves_per_dispatch == 1 ? "" : "s",
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain);
RAD_INFO("heat engine: %lld movable units, %d move%s a step, "
"decay %.3f hysteresis %.2f min-gain %.2f credit cap %.0f",
(long long)movable, params_.moves_per_step,
params_.moves_per_step == 1 ? "" : "s",
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain,
(double)params_.credit_cap);
return RAD_OK;
}
@@ -206,6 +207,13 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
* (prefetch()), which makes this a no-op. */
prefetch(counts, n);
/* The credit cap (HeatParams::credit_cap) scales the whole histogram, so its experts keep
* their order. The pricing below counts every pass whatever the credit is. */
int64_t total = 0;
for (int32_t j = 0; j < n; ++j) total += counts[j] > 0 ? counts[j] : 0;
const float cap = params_.credit_cap;
const float w = cap > 0.0f && (float)total > cap ? weight * cap / (float)total : weight;
float* __restrict h = heat_.data() + lo;
for (int32_t j = 0; j < len; ++j) h[j] *= d;
@@ -219,7 +227,7 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
const int32_t c = counts[j];
const size_t q = (size_t)(lo + j);
const float was = h[j];
const float x = was + (float)c * weight;
const float x = was + (float)c * w;
h[j] = x;
routed += routed_as_[q] != 0;
resident += routed_as_[q] == 2;
@@ -380,12 +388,12 @@ bool HeatEngine::pick(Swap* out) const {
return true;
}
/* THE WHOLE DISPATCH'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat
* nor any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_dispatch` best of each
/* THE WHOLE STEP'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat nor
* any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_step` best of each
* end; the proposals, and the counters that say why the list stopped, are the ones the repeated
* picks produce. This runs before every pass a rank issues -- draft passes included, where the
* device waits for the issue -- so a scan per proposed move would be most of its cost. */
* picks produce. This runs once a step on the thread that issues the next one, and the budget is
* dozens of swaps, so a scan per proposed move would be most of its cost. */
namespace {
using Ranked = HeatRanked;
/* Hotter first, then the layer with fewer residents, then the lower index. */
@@ -414,7 +422,7 @@ int HeatEngine::step(std::vector<Swap>* out) {
if (!out) return RAD_E_INVAL;
out->clear();
if (!enabled_) return RAD_OK;
const int k = params_.moves_per_dispatch;
const int k = params_.moves_per_step;
if (k <= 0) return RAD_OK;
/* THE BEST PAIR FROM THE LAYERS' ENDS FIRST. If it fails the guard every pair does -- the
+48 -33
View File
@@ -35,14 +35,15 @@
* ---- WHY LFU-WITH-DECAY AND NOT SOMETHING CLEVERER --------------------------------------------
*
* Replaying real routing traces against cache policies settles the shape of this. Runtime
* placement beats static profile placement by a wide margin, so it is worth building; LFU-with-
* decay and LRU score the same, so the decay constant is not where the wins are and this does not
* need to be subtle. Belady is a few points of hit rate above both -- but an oracle restricted to
* a disjoint sample of the future keeps most of that gap, so the remainder is knowledge of the
* realised future and is not reachable. Of what is left, no statistic of PAST USE captures any of
* it: an expert never selected has count zero, no age and no history, and most of the space is in
* that state. The router's own gate value does separate those cases, so a scorer built on it is
* the one direction here that measurement has not refuted.
* placement beats static profile placement by a wide margin, so it is worth building. What bounds
* it is the MOVE RATE, not the ranking: held to the same swaps a step at the same step boundaries,
* an oracle that knows every future routing scores no better than this policy (78.0% against 78.4%
* at 64 swaps a step, Qwen3.8-Flash-Next TP1 with 40% of the experts resident). The unrestricted
* Belady figure is far higher -- 92% on the same trace -- because it admits every miss the moment
* it happens, and a miss admitted here is a second copy of bytes the GEMM has just streamed. So
* the decay constant and the guards are not where the wins are, and this does not need to be
* subtle; the budget (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's
* routing from swamping the answer's (HeatParams::credit_cap) are.
*/
#pragma once
#include "planner.h"
@@ -53,14 +54,15 @@
namespace rad {
struct HeatParams {
/* Applied to a layer's whole plane each time that layer is dispatched. Every layer is
* dispatched exactly once per forward, so all planes decay in lockstep and heats stay
* comparable ACROSS layers -- which the global ranking below depends on.
/* Applied to a layer's whole plane each time that layer's histogram is credited. Every layer is
* credited once a step, so all planes decay in lockstep and heats stay comparable ACROSS
* layers -- which the global ranking below depends on.
*
* 0.98 is a half-life of a few dozen dispatches: long enough to survive a paragraph, short
* enough to follow a change of subject. Nearby values are not distinguishable from each other
* above the run-to-run spread, which is what the offline replay predicts. */
float decay = 0.98f;
* 0.95 is a half-life of about fourteen steps. At 64 swaps a step the replay is flat from 0.8
* to 0.95 (77.96% to 78.37%) and falls off above it -- 77.1% at 0.98, 74.2% at 0.99 -- because
* a heat that remembers longer ranks the experts a conversation has moved past above the ones
* it routes to now. */
float decay = 0.95f;
/* Promote only when the candidate beats the victim by this ratio. Without it the two ends of
* the ranking trade places on noise and the engine spends the whole link on churn that
@@ -79,27 +81,40 @@ struct HeatParams {
* MISS, and a miss is a shard streamed over the same link on the same budget. A tighter bar
* then gives up hit rate and buys no traffic back.
*
* The exchange rate behind the value: the two link directions share one budget, so
* a demotion costs about what a promotion does, and a swap therefore has to repay about 1.4
* future hits rather than the 0.74 a half-price demotion would imply. */
* What a swap costs is its promotion. The link is close to full duplex -- on an R9700, 28.5
* GB/s up and 25.0 down at once, against 28.8 up alone -- so a demotion's copy rides the idle
* direction, while a promotion shares the upstream one with every miss the GEMM streams. At
* the default budget lower values replay within 0.2 points of hit rate and promote a fifth
* more. */
float min_gain = 1.5f;
/* A BOUNDED MOVE BUDGET PER LAYER DISPATCH. The apparent risk is that a high budget makes the
* mover compete with the tier it is trying to shrink -- a promotion and a streamed miss are
* the same bytes over the same link. At this scale that does not bind: a larger budget pays
* even though it moves considerably more bytes, because converging sooner is worth more than
* the traffic costs. The benefit then SATURATES, and this sits where the knob stops mattering
* rather than at the largest value that still helps. Past that point the guard, not the
* budget, is what declines the extra opportunities -- so raising this alone is worth nothing
* until min_gain moves with it.
/* A BOUNDED MOVE BUDGET PER STEP: step() is called once a step, after every layer's histogram
* has been credited, and proposes at most this many swaps a slab class. The value and why it
* is that are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands in
* (the shadow and turnover slots); a budget raised here without them is spent on
* `starved_slab`.
*
* The apparent risk is that a high budget makes the mover compete with the tier it is trying
* to shrink -- a promotion and a streamed miss are the same bytes over the same link. At this
* scale that does not bind: each swap moves an expert the ranking says will be read again
* soon, and the misses it saves are many times its own bytes.
*
* IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert
* classes -- the wider slice of one parity's experts and the narrower slice of the other's --
* each about half a whole expert, and a budget shared between them would move half the bytes
* a dispatch that whole experts do: residency would converge half as fast, and a fresh server
* would run about 2% slower for its first minute. Per class, the two together move about as
* many whole experts as one class of whole experts does. */
int moves_per_dispatch = 8;
* a step that whole experts do: residency would converge half as fast. Per class, the two
* together move about as many whole experts as one class of whole experts does. */
int moves_per_step = RAD_PLACE_MOVES_PER_STEP;
/* THE MOST ONE HISTOGRAM CREDITS, in selections: a histogram that routed more is credited
* at this total, each expert in proportion to its count. A decode step routes a few rows a
* sequence and stays under it; a prefill chunk routes thousands, and at full weight one chunk
* outweighs dozens of decode steps, so for that many steps after a prompt the resident set is
* the prompt's rather than the answer's. What the resident set buys a prefill is little in
* any case: a chunk reads nearly every expert of a layer, and the stager copies whichever are
* not resident. Replaying a mixed workload at Qwen3.8-Flash-Next TP1, decode rows hit 77.3%
* uncapped, 78.9% at 1024 and 79.0% at 512 or 256. */
float credit_cap = 512.0f;
/* Dispatches to watch before moving anything, and it is 0 because THE GUARD ALREADY DOES THIS
* JOB. min_gain means a promotion needs `hot >= cold*hysteresis + 1.5`, and against a
@@ -195,7 +210,7 @@ public:
/* The best swap available, or false when the guards refuse. */
bool pick(Swap* out) const;
/* One layer dispatch's worth of proposals, at most `moves_per_dispatch` of them a class.
/* One step's worth of proposals, at most `moves_per_step` of them a class.
*
* CONTRACT: every unit named in the result is marked busy on the way out. The caller must
* either issue the transfer -- in which case set_tier() on publish and set_busy(false) after
@@ -284,8 +299,8 @@ private:
* unit's class as a dense index, -1 for a unit that cannot move. */
std::vector<int32_t> cls_;
int32_t n_cls_ = 1;
/* step()'s two ends of the ranking, `moves_per_dispatch` entries a class, kept between calls
* so a dispatch allocates nothing. */
/* step()'s two ends of the ranking, `moves_per_step` entries a class, kept between calls so a
* step allocates nothing. */
std::vector<HeatRanked> rank_hot_, rank_cold_;
std::vector<int32_t> n_hot_, n_cold_, m_of_;
/* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
+369 -69
View File
@@ -90,6 +90,7 @@ Mover::~Mover() {
* that name the events below and the copies into and out of the memory below, so each of
* those goes only once nothing queued refers to it. */
if (mover_) {
(void)flush_moves();
rad_stream_sync(mover_);
rad_stream_destroy(mover_);
}
@@ -138,6 +139,11 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
"it is a test path and not a deployment.");
unit_.assign(plan.units.size(), UnitState{});
copying_.assign(plan.units.size(), 0);
pool_layer_.assign(plan.classes.size(), {});
donors_.assign(plan.classes.size(), DonorRank{});
n_layers_ = 0;
for (const MoveUnit& mu : plan.units) n_layers_ = std::max(n_layers_, mu.layer + 1);
pools_.clear();
pools_.resize(plan.classes.size());
@@ -162,6 +168,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
static_need = us.static_off + mu.bytes;
} else if (mu.tier == Tier::HostPinned) {
us.pool_slot = n_pool[(size_t)mu.slab_class]++;
pool_layer_[(size_t)mu.slab_class].push_back(mu.layer);
} else if (mu.tier == Tier::HostPageable) {
us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT);
pageable_need = us.static_off + mu.bytes;
@@ -170,7 +177,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
}
/* ---- allocate ------------------------------------------------------------------------- */
int64_t total_shadow = 0;
int64_t total_shadow = 0, total_turn = 0;
for (size_t c = 0; c < plan.classes.size(); ++c) {
const SlabClass& sc = plan.classes[c];
ClassPools& cp = pools_[c];
@@ -193,6 +200,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
* lend_from() adds them once it is. */
cp.n_fixed = slab_slots;
cp.n_work = shadow + sc.n_stage;
cp.n_turn = std::min<int64_t>(std::max(cfg.turnover_slots, 0),
shadow * RAD_PLACE_TURNOVER_SLOTS / RAD_PLACE_SHADOW_SLOTS);
total_turn += cp.n_turn;
cp.slab.init(slab_slots, sc.stride);
if (slab_slots > 0) {
/* Tail padding: a kernel that assembles a packed code window from a wide read
@@ -366,13 +376,13 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
lead_.assign((size_t)lead + 1, nullptr);
for (RadEvent& e : lead_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
/* TWO records per shadow slot, not one. A promotion holds a slab slot for its whole life, so
* there can never be more promotions in flight than there are shadows -- but a swap is two
* transfers, and the matching demotion needs a record of its own or the pair can never be in
* flight together and the engine never issues a demotion at all. That failure is silent: it
* shows up as `no_record` where the real symptom is a resident set that only ever grows.
* The floor is what makes a one-shadow plan still able to hold a swap. */
const int64_t n_records = std::max<int64_t>(2 * total_shadow, 4);
/* TWO records per free slot, shadow or turnover, not one. A promotion holds a slab slot for
* its whole life, so there can never be more promotions in flight than there are free slots --
* but a swap is two transfers, and the matching demotion needs a record of its own or the pair
* can never be in flight together and the engine never issues a demotion at all. That failure
* is silent: it shows up as `no_record` where the real symptom is a resident set that only ever
* grows. The floor is what makes a one-shadow plan still able to hold a swap. */
const int64_t n_records = std::max<int64_t>(2 * (total_shadow + total_turn), 4);
moves_.assign((size_t)n_records, Move{});
for (Move& m : moves_) RAD_TRY(rad_event_create_local(&m.ev));
@@ -383,9 +393,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
republish(u);
}
RAD_INFO("mover: %lld slab slots (%lld shadow), %lld pinned pool slots, %s static vram%s",
RAD_INFO("mover: %lld slab slots (%lld shadow, %lld more kept free out of a loan), %lld pinned "
"pool slots, %s static vram%s",
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.slab.size(); return n; }(),
(long long)total_shadow,
(long long)total_shadow, (long long)total_turn,
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.pool.size(); return n; }(),
humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : "");
/* The pageable host region is allocated here and charged to no budget -- Pools has no
@@ -436,9 +447,7 @@ void Mover::republish(int32_t unit) {
* a record past Copying has its bytes in place, and treating it as in-flight holds the slot for
* as long as the record takes to recycle rather than as long as the copy takes to land. */
bool Mover::unit_in_flight(int32_t unit) const {
for (const Move& m : moves_)
if (m.state == Move::State::Copying && m.unit == unit) return true;
return false;
return unit >= 0 && (size_t)unit < copying_.size() && copying_[(size_t)unit] > 0;
}
int Mover::free_move_record() const {
@@ -577,6 +586,7 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
m.state = Move::State::Copying;
m.kind = Move::Kind::Stage;
m.unit = unit;
++copying_[(size_t)unit];
m.slab_slot = slab_slot;
m.pool_slot = -1;
stats_.h2d_bytes += (uint64_t)us.bytes;
@@ -602,42 +612,76 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
/* ---- staging within a pass (see mover.h) ---------------------------------------------------- */
int Mover::stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
RadEvent done, std::vector<int32_t>* staged) {
if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL;
const StageSpan one{dst, cap};
return stage_units(units, &one, 1, after, done, staged);
}
int Mover::stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
RadEvent after, RadEvent done, std::vector<int32_t>* staged) {
if (!plan_ || !spans || n_spans < 1 || n_spans > 2 || !staged || !done) return RAD_E_INVAL;
for (int k = 0; k < n_spans; ++k)
if (!spans[k].dst) return RAD_E_INVAL;
staged->clear();
std::vector<int64_t> at;
at.reserve(units.size());
int64_t off = 0;
bool waited = false;
stage_picks_.clear();
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
const UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
continue;
if (unit_in_flight(u)) continue;
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
if (off + need > cap) { ++stats_.stage_overflow; continue; }
if (!waited) {
if (after) RAD_TRY(rad_event_wait(mover_, after));
waited = true;
}
const ClassPools& cp = pools_[(size_t)us.klass];
const char* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
RAD_TRY(rad_memcpy_async(dst + off, src, us.bytes, mover_));
staged->push_back(u);
at.push_back(off);
stats_.h2d_bytes += (uint64_t)us.bytes;
stats_.staged_bytes += (uint64_t)us.bytes;
off += need;
stage_picks_.push_back(StagePick{src, u, us.bytes, align_up(us.bytes, RAD_ALIGN_UNIT),
nullptr});
}
if (staged->empty()) return RAD_OK;
if (stage_picks_.empty()) return RAD_OK;
/* THE SPANS ARE FILLED IN POOL ORDER, so units on neighbouring pool slots land side by side
* and go as one copy. A layer's pooled experts were given their slots together and mostly
* still hold them, so a layer's ~90 units go as fewer copies -- each one a launch or a DMA
* packet whatever its size. A class's stride is its units' aligned size, so a run's source and
* destination advance alike, padding included. A unit the span in hand has no room left for
* goes to the start of the next; one that no span has room for is read across the link in
* place. */
std::sort(stage_picks_.begin(), stage_picks_.end(),
[](const StagePick& a, const StagePick& b) { return a.src < b.src; });
int k = 0;
int64_t off = 0;
size_t taken = 0;
for (StagePick& p : stage_picks_) {
if (off + p.need > spans[k].cap && k + 1 < n_spans && p.need <= spans[k + 1].cap) {
++k;
off = 0;
}
if (off + p.need > spans[k].cap) { ++stats_.stage_overflow; continue; }
p.dst = spans[k].dst + off;
off += p.need;
++taken;
}
if (taken == 0) return RAD_OK;
if (after) RAD_TRY(rad_event_wait(mover_, after));
stage_segs_.clear();
for (const StagePick& p : stage_picks_) {
if (!p.dst) continue;
RadCopySeg* run = stage_segs_.empty() ? nullptr : &stage_segs_.back();
if (run && p.src - (const char*)run->src == p.dst - (char*)run->dst)
run->bytes = (int64_t)(p.dst - (char*)run->dst) + p.bytes;
else
stage_segs_.push_back(RadCopySeg{p.src, p.dst, p.bytes});
staged->push_back(p.u);
stats_.h2d_bytes += (uint64_t)p.bytes;
stats_.staged_bytes += (uint64_t)p.bytes;
}
RAD_TRY(rad_memcpy_list_async(stage_segs_.data(), (int)stage_segs_.size(), RAD_COPY_YIELD,
mover_));
RAD_TRY(rad_event_record(done, mover_));
for (size_t k = 0; k < staged->size(); ++k) {
const MoveUnit& mu = plan_->units[(size_t)(*staged)[k]];
for (size_t i = 0; i < mu.weights.size(); ++i)
res_.publish(mu.weights[i], dst + at[k] + mu.offset[i]);
for (const StagePick& p : stage_picks_) {
if (!p.dst) continue;
const MoveUnit& mu = plan_->units[(size_t)p.u];
for (size_t i = 0; i < mu.weights.size(); ++i) res_.publish(mu.weights[i], p.dst + mu.offset[i]);
}
++stats_.stage_layers;
stats_.staged_units += (uint64_t)staged->size();
stats_.stage_copies += (uint64_t)stage_segs_.size();
return RAD_OK;
}
@@ -645,6 +689,23 @@ void Mover::unstage_units(const std::vector<int32_t>& staged) {
for (int32_t u : staged) republish(u);
}
/* The same choice of units as stage_units, without a cap. */
int64_t Mover::stage_need(const std::vector<int32_t>& units, int64_t* largest) const {
int64_t total = 0, most = 0;
for (int32_t u : units) {
if (u < 0 || (size_t)u >= unit_.size()) continue;
const UnitState& us = unit_[(size_t)u];
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
continue;
if (unit_in_flight(u)) continue;
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
total += need;
most = std::max(most, need);
}
if (largest) *largest = most;
return total;
}
/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */
namespace {
@@ -817,7 +878,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
if (record_gate() < 0) return false;
Move& m = moves_[(size_t)rec];
{
const int64_t g = cp.pool.take();
const int64_t g = pool_slot_for(unit, heat);
if (g < 0) { ++stats_.starved_pool; return false; }
char* dst = (char*)cp.pool_base + g * cp.stride;
if (us.slab_slot < 0) { cp.pool.add_free(g); return false; }
@@ -829,11 +890,10 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
* demotion costs about what a promotion does. That is the exchange rate heat.h's
* min_gain is tuned against. */
if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; }
if (rad_memcpy_async(dst, src, us.bytes, mover_) < 0) {
if (queue_move_copy(dst, src, us.bytes, (int)(&m - moves_.data())) < 0) {
cp.pool.add_free(g);
return false;
}
(void)rad_event_record(m.ev, mover_);
m.kind = Move::Kind::Demote;
m.slab_slot = us.slab_slot;
m.pool_slot = g;
@@ -841,6 +901,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
}
m.state = Move::State::Copying;
m.unit = unit;
++copying_[(size_t)unit];
return true;
};
@@ -1042,6 +1103,133 @@ int Mover::drop(int32_t unit, HeatEngine* heat) {
return RAD_OK;
}
/* THE POOL IS SIZED TO THE UNITS THAT LIVE IN IT, so it has a slot free only while a promotion
* into a budgeted slot is on its way through the quarantine -- and the budgeted range turns over
* only as fast as those few slots come round. A budgeted unit that goes cold then stays, and the
* engine's swap drops the coldest lent unit in its place, which is warmer: replaying a mixed
* workload's routing at TP1, the hit rate is 72.7% that way against 76.7% with up to n_turn
* donors a class, and 78.5% for one resident set with no regions at all.
*
* A unit in a lent slot keeps its host copy only so that a recall is a change of address. Giving
* the copy to the victim costs that for this one unit: a recall moves it, into a free budgeted
* slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way
* (balance). There is always somewhere for it to go -- each donor's copy went to a unit
* whose budgeted slot it left free, so the free budgeted slots and the free pool slots together
* number at least the donors. The donors are bounded by the turnover slots, and they come out of
* the KV cache's loan only: the arena takes its loan back at every prompt's first chunk, and that
* recall stays a change of address.
*
* THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one --
* because a donor the engine later demotes needs a pool slot of its own where it would have been a
* drop. Its pool slot has no reader: the unit has been resident since its promotion retired, and
* the copy into the slot waits on the gate besides. */
int64_t Mover::donor_slot(size_t klass, int32_t layer, HeatEngine* heat) {
ClassPools& cp = pools_[klass];
if (cp.n_donated >= cp.n_turn) return -1;
/* NOT WHILE THE TURNOVER SLOTS ARE HELD: through a prompt and the few steps after it
* (Engine::tiering_dispatch). A donation lets a starved demotion go and the swap behind it
* with it, two copies on the stream the next prompt stages on; at TP2, where the resident set
* is nine tenths of the experts and a donor buys no decode at all, 26K-token prompts back to
* back ran 0.3% slower with them. A decode run reaches the count in a few steps. */
if (hold_turnover_) return -1;
DonorRank& d = donors_[klass];
if (d.at != dispatch_) {
d.at = dispatch_;
d.by_layer.assign((size_t)std::max(n_layers_, 1), {});
for (const ClassPools::Lent& l : cp.lent) {
if (l.lender != kLendKV) continue;
const int64_t lo = cp.slab.seg_lo(l.seg), hi = cp.slab.target(l.seg);
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
const UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)klass || us.slab_slot < lo || us.slab_slot >= hi) continue;
const int32_t ul = plan_->units[(size_t)u].layer;
if (ul < 0 || ul >= n_layers_) continue;
d.by_layer[(size_t)ul].push_back({ heat ? heat->heat(u) : 0.0f, u });
}
}
for (auto& v : d.by_layer) std::sort(v.begin(), v.end());
}
for (;;) {
/* The hottest candidate of the layer asked for, or of every layer. */
std::vector<std::pair<float, int32_t>>* pick = nullptr;
if (layer >= 0) {
if (layer < (int32_t)d.by_layer.size() && !d.by_layer[(size_t)layer].empty())
pick = &d.by_layer[(size_t)layer];
} else {
for (auto& v : d.by_layer)
if (!v.empty() && (!pick || v.back() > pick->back())) pick = &v;
}
if (!pick) return -1;
const int32_t u = pick->back().second;
pick->pop_back();
UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)klass || us.pool_slot < 0 || us.slab_slot < 0) continue;
if (us.tier != Tier::VRAM || us.site != Site::Device || !cp.slab.covered(us.slab_slot))
continue;
if ((heat && heat->busy(u)) || unit_in_flight(u)) continue;
const int64_t g = us.pool_slot;
us.pool_slot = -1;
++cp.n_donated;
++stats_.donated;
return g;
}
}
/* THE STAGER COPIES A LAYER'S POOLED UNITS IN RUNS OF NEIGHBOURING POOL SLOTS (stage_units), and
* the pool is laid out in unit order, so a layer's pooled units start out side by side. A demotion
* that lands in a slot another layer's unit left breaks one run in that layer and starts a run of
* one in its own, a copy more in each, for every prompt after it. So a slot one of the unit's own
* layer started out in comes first, then a donor of the same layer -- its slot most likely one of
* those -- and only then any free slot, or any donor. At TP1, 26K-token prompts with 256 tokens
* decoded between them staged a layer in 162 copies without the preference and 112 with it (95
* when the budget was 8 swaps a step). */
int64_t Mover::pool_slot_for(int32_t unit, HeatEngine* heat) {
const UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
const int32_t layer = plan_->units[(size_t)unit].layer;
const std::vector<int32_t>& home = pool_layer_[(size_t)us.klass];
int64_t g = -1;
if (layer >= 0) {
g = cp.pool.take_where([&](int64_t p) { return (size_t)p < home.size() && home[(size_t)p] == layer; });
if (g < 0) g = donor_slot((size_t)us.klass, layer, heat);
}
if (g < 0) g = cp.pool.take();
if (g < 0) g = donor_slot((size_t)us.klass, -1, heat);
return g;
}
bool Mover::migrate(int32_t unit, HeatEngine* heat) {
UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
const int64_t to = cp.slab.take();
if (to < 0) return false;
if (to >= cp.n_fixed) {
cp.slab.add_free(to);
return false;
}
const int rec = free_move_record();
if (rec < 0 || record_gate() < 0) {
if (rec < 0) ++stats_.no_record;
cp.slab.add_free(to);
return false;
}
Move& m = moves_[(size_t)rec];
if (rad_event_wait(mover_, gate_) < 0 ||
queue_move_copy(cp.slot_ptr(to), cp.slot_ptr(us.slab_slot), us.bytes, rec) < 0) {
cp.slab.add_free(to);
return false;
}
m.state = Move::State::Copying;
m.kind = Move::Kind::Migrate;
m.unit = unit;
m.slab_slot = us.slab_slot;
m.pool_slot = -1;
m.to_slot = to;
++copying_[(size_t)unit];
if (heat) heat->set_busy(unit, true);
return true;
}
int Mover::promote_to(int32_t unit, int64_t slot) {
UnitState& us = unit_[(size_t)unit];
ClassPools& cp = pools_[(size_t)us.klass];
@@ -1052,8 +1240,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
const void* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
Move& m = moves_[(size_t)rec];
RAD_TRY(rad_event_wait(mover_, gate_));
RAD_TRY(rad_memcpy_async(cp.slot_ptr(slot), src, us.bytes, mover_));
(void)rad_event_record(m.ev, mover_);
RAD_TRY(queue_move_copy(cp.slot_ptr(slot), src, us.bytes, rec));
m.kind = Move::Kind::Promote;
m.slab_slot = slot;
/* INTO A LENT SLOT, THE HOST COPY STAYS. The loan can be recalled at any time and a unit that
@@ -1063,6 +1250,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
m.pool_slot = cp.is_flex(slot) ? -1 : us.pool_slot;
m.state = Move::State::Copying;
m.unit = unit;
++copying_[(size_t)unit];
stats_.h2d_bytes += (uint64_t)us.bytes;
return RAD_OK;
}
@@ -1125,7 +1313,7 @@ int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) {
return RAD_OK;
}
int Mover::balance(HeatEngine* heat) {
int Mover::balance(HeatEngine* heat, bool turnover) {
if (!plan_ || !plan_->dynamic) return RAD_OK;
for (size_t c = 0; c < pools_.size(); ++c) {
@@ -1149,6 +1337,20 @@ int Mover::balance(HeatEngine* heat) {
left = true;
continue;
}
/* A donor has no host copy to drop to: it moves into a free budgeted slot, or
* else back across the link, and stays past the loan until the copy lands. */
if (us.pool_slot < 0) {
if (migrate(u, heat)) {
drained = true;
} else {
if (heat) heat->set_busy(u, true);
Swap s;
s.demote = u;
if (issue(s, heat) >= 0) drained = true;
}
left = true;
continue;
}
if (drop(u, heat) < 0) { left = true; break; }
drained = true;
}
@@ -1160,36 +1362,54 @@ int Mover::balance(HeatEngine* heat) {
* slots that were serving as the reserve leaves the slab too full by that many, and the
* coldest lent units go -- drops, never copies. A slot already on its way back below the
* target counts as free, because it is, a barrier from now; draining against it again is
* how a slab empties itself. */
* how a slab empties itself.
*
* THE TURNOVER SLOTS ARE REBUILT THE SAME WAY, out of the lent units alone. They are the
* top of the lent range, which is exactly what a cache that wants memory back takes first,
* and the loan grows back only a prefill chunk at a time: left to the fill, they would be
* gone for as long as requests keep arriving. Dropping the coldest lent units costs
* nothing on the link -- each still has its host copy -- and gives up the same residents
* the slots would have cost anyway. A swap whose demotion found no pool slot is completed
* the same way, by the coldest lent unit instead. */
int64_t pending = 0;
for (const Move& m : moves_) {
if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue;
if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue;
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Release)
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
++pending;
}
int64_t short_by = cp.n_work - (cp.slab.n_free() + pending);
while (short_by > 0) {
int32_t victim = -1;
float coldest = 0.0f;
const int64_t turn = turnover ? cp.n_turn : 0;
int64_t short_by = cp.n_work + turn - (cp.slab.n_free() + pending);
if (short_by > 0) {
drop_cand_.clear();
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
const UnitState& us = unit_[(size_t)u];
if (us.klass != (int32_t)c || us.slab_slot < 0 || !cp.is_flex(us.slab_slot)) continue;
if (us.tier != Tier::VRAM || us.site != Site::Device || us.pool_slot < 0) continue;
if (heat && heat->busy(u)) continue;
const float h = heat ? heat->heat(u) : 0.0f;
if (victim < 0 || h < coldest) { victim = u; coldest = h; }
drop_cand_.push_back({ heat ? heat->heat(u) : 0.0f, u });
}
/* The coldest first, and on a tie the lower unit, so the choice is the same every run. */
auto colder = [](const std::pair<float, int32_t>& a, const std::pair<float, int32_t>& b) {
return a.first != b.first ? a.first < b.first : a.second < b.second;
};
const size_t k = std::min(drop_cand_.size(), (size_t)short_by);
std::partial_sort(drop_cand_.begin(), drop_cand_.begin() + (ptrdiff_t)k, drop_cand_.end(),
colder);
for (size_t i = 0; i < k; ++i) {
if (drop(drop_cand_[i].second, heat) < 0) break;
drained = true;
--short_by;
}
if (victim < 0 || drop(victim, heat) < 0) break;
drained = true;
--short_by;
}
/* AND WITH NO LENT UNIT LEFT TO DROP, THE COLDEST BUDGETED ONE GOES BACK TO THE POOL -- a
* real demotion, one a call. A swap can leave the free slots in the lent range, and a loan
* that then shrinks away takes them with it; the reserve has to be rebuilt out of the
* real demotion, one a call, and for the working reserve only: the turnover slots are the
* loan's to give, and a copy across the link to keep them would spend the very link they
* exist to save. A swap can leave the free slots in the lent range, and a loan that then
* shrinks away takes them with it; the working reserve has to be rebuilt out of the
* budgeted slots or the mover stops turning over. */
if (short_by > 0) {
if (short_by > turn) {
int32_t victim = -1;
float coldest = 0.0f;
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
@@ -1212,17 +1432,17 @@ int Mover::balance(HeatEngine* heat) {
* trying to hand back. */
if (drained) continue;
/* ---- THEN FILL, every free slot past the working reserve. */
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work, heat));
/* ---- THEN FILL, every free slot past the working reserve and the turnover slots. */
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work - turn, heat));
}
count_flex();
return RAD_OK;
return flush_moves();
}
int Mover::idle_tick(HeatEngine* heat) {
if (!plan_ || !plan_->dynamic) return RAD_OK;
RAD_TRY(retire(heat));
return balance(heat);
return balance(heat, !hold_turnover_);
}
int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
@@ -1235,20 +1455,56 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
}
/* NO COPY IS STILL WRITING A SLOT: everything the mover issued has landed, and retiring it
* publishes the promotions that landed in slots about to be taken back. */
RAD_TRY(flush_moves());
RAD_TRY(rad_stream_sync(mover_));
RAD_TRY(retire(heat));
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address. */
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or,
* for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside
* the card, or else back across the link into a free pool slot. One of the two is free for
* every donor (donor_slot says why). Nothing is published until the copies have landed. */
std::vector<std::pair<size_t, int64_t>> freed;
std::vector<int32_t> moved;
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
UnitState& us = unit_[(size_t)u];
if (us.klass < 0 || us.slab_slot < 0) continue;
const ClassPools& cp = pools_[(size_t)us.klass];
ClassPools& cp = pools_[(size_t)us.klass];
if (!cp.is_flex(us.slab_slot) || cp.slab.covered(us.slab_slot)) continue;
if (us.pool_slot < 0) {
RAD_ERR("mover: unit %d sits in lent slot %lld with no host copy to go back to",
(int)u, (long long)us.slab_slot);
return RAD_E_STATE;
const int64_t from = us.slab_slot;
int64_t to = cp.slab.take();
if (to >= cp.n_fixed) {
cp.slab.add_free(to);
to = -1;
}
if (to >= 0) {
RAD_TRY(rad_memcpy_async(cp.slot_ptr(to), cp.slot_ptr(from), us.bytes, mover_));
us.slab_slot = to;
} else {
const int64_t g = cp.pool.take();
if (g < 0) {
RAD_ERR("mover: unit %d gave its host copy away and neither a budgeted slot nor "
"a pool slot is free to move it to", (int)u);
return RAD_E_STATE;
}
RAD_TRY(rad_memcpy_async((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(from),
us.bytes, mover_));
us.pool_slot = g;
us.slab_slot = -1;
us.tier = Tier::HostPinned;
us.site = Site::DeviceZeroCopy;
stats_.d2h_bytes += (uint64_t)us.bytes;
++stats_.demotions;
if (heat) {
heat->set_tier(u, Tier::HostPinned);
heat->set_busy(u, false);
}
}
--cp.n_donated;
++stats_.relocated;
freed.push_back({ (size_t)us.klass, from });
moved.push_back(u);
continue;
}
freed.push_back({ (size_t)us.klass, us.slab_slot });
us.slab_slot = -1;
@@ -1263,6 +1519,11 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
}
}
if (!moved.empty()) {
RAD_TRY(rad_stream_sync(mover_));
for (int32_t u : moved) republish(u);
}
/* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the
* quarantine barrier rests on the same fact -- so once it has drained, nothing already issued
* can reach a slot past the loan, and everything issued from here reads the host copies. */
@@ -1279,13 +1540,14 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
ClassPools& cp = pools_[(size_t)klass];
if (!cp.is_flex(m.slab_slot) || cp.slab.covered(m.slab_slot)) continue;
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Release)
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
cp.slab.add_free(m.slab_slot);
if (heat && m.kind != Move::Kind::Stage && m.kind != Move::Kind::Release)
heat->set_busy(m.unit, false);
if (m.state == Move::State::Copying) --copying_[(size_t)m.unit];
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
}
count_flex();
if (loan_held(lender) > loan_[lender]) {
@@ -1297,13 +1559,38 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
return RAD_OK;
}
int Mover::queue_move_copy(void* dst, const void* src, int64_t bytes, int rec) {
move_segs_.push_back(RadCopySeg{ src, dst, bytes });
move_recs_.push_back((int32_t)rec);
return RAD_OK;
}
/* THE DMA ENGINE AND NOT COPY KERNELS. A copy kernel runs on the compute units beside the step's
* kernels: at the heat engine's budget of 64 swaps a step, Qwen3.8-Flash-Next at one card spent 10 ms
* a step in about 68 of them while the step took 36. The engine moves the same bytes at the link's
* rate and takes nothing from the kernels; decode at one sequence went 34.1 -> 33.0 ms a step, and
* two cards, prefill and the output were unchanged. A card with no DMA queue of this process's own
* gets the list as copy kernels (rad_memcpy_list_async), as before. The list yields to the link's
* collectives like the prefill stager's. */
int Mover::flush_moves() {
if (move_segs_.empty()) return RAD_OK;
const int rc = rad_memcpy_list_async(move_segs_.data(), (int)move_segs_.size(), RAD_COPY_YIELD,
mover_);
for (int32_t rec : move_recs_) (void)rad_event_record(moves_[(size_t)rec].ev, mover_);
move_segs_.clear();
move_recs_.clear();
return rc;
}
int Mover::retire(HeatEngine* heat) {
RAD_TRY(flush_moves());
for (Move& m : moves_) {
if (m.state != Move::State::Copying) continue;
const int q = rad_event_query(m.ev);
if (q < 0) return RAD_E_DEVICE;
if (q == 0) continue;
--copying_[(size_t)m.unit];
UnitState& us = unit_[(size_t)m.unit];
switch (m.kind) {
case Move::Kind::Promote:
@@ -1317,6 +1604,9 @@ int Mover::retire(HeatEngine* heat) {
if (heat) heat->set_tier(m.unit, Tier::VRAM);
break;
case Move::Kind::Demote:
/* Out of a lent slot, the unit was a donor (donor_slot): any other unit there is
* dropped, not demoted. */
if (pools_[(size_t)us.klass].is_flex(m.slab_slot)) --pools_[(size_t)us.klass].n_donated;
us.pool_slot = m.pool_slot;
us.slab_slot = -1;
us.tier = Tier::HostPinned;
@@ -1348,8 +1638,13 @@ int Mover::retire(HeatEngine* heat) {
* and the pipeline simply stops turning over. */
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
continue;
case Move::Kind::Migrate:
us.slab_slot = m.to_slot;
--pools_[(size_t)us.klass].n_donated;
++stats_.relocated;
break;
case Move::Kind::Release:
case Move::Kind::Drop:
break;
@@ -1393,14 +1688,15 @@ int Mover::retire(HeatEngine* heat) {
case Move::Kind::Demote: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Release: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Drop: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Migrate: cp.slab.add_free(m.slab_slot); break;
case Move::Kind::Stage: break; /* never reaches here; freed as soon as it lands */
}
if (heat && (m.kind == Move::Kind::Promote || m.kind == Move::Kind::Demote ||
m.kind == Move::Kind::Drop))
m.kind == Move::Kind::Drop || m.kind == Move::Kind::Migrate))
heat->set_busy(m.unit, false);
m.state = Move::State::Free;
m.unit = -1;
m.slab_slot = m.pool_slot = -1;
m.slab_slot = m.pool_slot = m.to_slot = -1;
}
count_flex();
return RAD_OK;
@@ -1421,6 +1717,10 @@ std::string Mover::report() const {
"slot; %llu slots quarantined\n",
(unsigned long long)stats_.no_record, (unsigned long long)stats_.starved_slab,
(unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined);
if (stats_.donated)
s += fmt(" %llu host copies given by lent units to budgeted victims, %llu such units moved "
"by a recall\n",
(unsigned long long)stats_.donated, (unsigned long long)stats_.relocated);
if (stats_.ssd_reads)
s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle "
"of a dispatch. Raise --host-pool-mib.\n",
+125 -8
View File
@@ -45,6 +45,7 @@
* the slot has retired.
*/
#pragma once
#include "../device/device.h"
#include "../device/directio.h"
#include "../mem/pools.h"
#include "heat.h"
@@ -212,6 +213,25 @@ public:
}
return got;
}
/* take(), restricted to the free slots `want` accepts: the lowest of them, or -1. A scan of
* the free list, which holds the slots on their way back through a swap -- a few dozen. */
template <class Want> int64_t take_where(Want want) {
size_t best = free_.size();
for (size_t i = 0; i < free_.size(); ++i) {
const int64_t s = free_[i];
if (!covered(s) || held_[(size_t)s] || !want(s)) continue;
if (best == free_.size() || s < free_[best]) best = i;
}
if (best == free_.size()) return -1;
const int64_t s = free_[best];
free_[best] = free_.back();
free_.pop_back();
std::make_heap(free_.begin(), free_.end(), std::greater<int64_t>());
held_[(size_t)s] = 1;
++n_held_;
--n_usable_;
return s;
}
/* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
* quarantine -- or -1. A scan down from the segment's mark. */
int64_t top_held(int k = 0) const {
@@ -356,6 +376,13 @@ struct MoverConfig {
* layer. */
int max_lead_dispatches = 2;
/* Lent slots kept free for swaps to land in, a slab class (planner.h's
* RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges
* nothing for them: they are the KV cache's memory, free only while it lends. A class whose
* shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a
* small loan is not left emptier than it is filled. */
int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
/* The container, for the file tier. Empty means there is no file tier and a unit the planner
* put there is an error rather than a slow path. */
std::string container_path;
@@ -393,10 +420,16 @@ struct MoverStats {
/* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going
* back to the host tier was a change of address. Counted inside `demotions` as well. */
uint64_t dropped = 0;
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
* or shrank. */
uint64_t donated = 0, relocated = 0;
uint64_t ssd_reads = 0, ssd_bytes = 0;
/* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
* pooled units a buffer had no room left for -- those were read across the link in place. */
* pooled units a buffer had no room left for -- those were read across the link in place.
* `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */
uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
uint64_t stage_copies = 0;
/* The file stager's reads (stage_file_units): routed layers read from the container, the
* units and bytes they carried, the preads that carried them, and the host time spent inside
* those reads and waiting for a window's copies to drain -- the two halves of what a step
@@ -547,6 +580,13 @@ public:
int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
int64_t flex_capacity() const;
/* The lent slots the fill leaves free for the engine to swap into
* (MoverConfig::turnover_slots), summed over the slab classes. */
int64_t turnover_slots() const {
int64_t n = 0;
for (const ClassPools& cp : pools_) n += cp.n_turn;
return n;
}
/* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that
* covers every slot carved from it. The slots were carved no deeper than the units the host
* pool holds, so a loan this size already has room for every unit that could move -- more VRAM
@@ -556,14 +596,38 @@ public:
/* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the
* half-swaps the heat engine never proposes, because its decision is a COMPARISON and a
* comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams
* across the link is VRAM bought and wasted on every step, so every free slot is filled in
* one call, hottest units first, and the copies run at the rate the link carries them. */
int balance(HeatEngine* heat);
* across the link is VRAM bought and wasted on every step, so every free slot past the
* turnover slots is filled in one call, hottest units first, and the copies run at the rate
* the link carries them. The turnover slots are left free because the engine's swaps land in
* them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer
* than the working and turnover slots are free, the coldest lent units are dropped until
* enough are -- a change of address, never a copy.
*
* `turnover` false treats the turnover slots as room, filled like any other: a step bound by
* its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is
* one its stager does not copy. The next call with it true drops them back out. */
int balance(HeatEngine* heat, bool turnover = true);
/* balance() for a rank with no step to ride on. Retires what has landed and fills what is
* free, so a loan made while the server is idle is filled before the next request rather
* than by it. Only while the rank thread is parked. */
* than by it -- the turnover slots too while they are held. Only while the rank thread is
* parked. */
int idle_tick(HeatEngine* heat);
/* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt
* and the few steps after it (Engine::tiering_dispatch). */
void hold_turnover(bool held) { hold_turnover_ = held; }
/* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
int pool_ranges(uint64_t* lo, uint64_t* hi, uint64_t* stride, int max) const {
int n = 0;
for (const ClassPools& cp : pools_)
if (cp.pool_dev && cp.stride > 0 && n < max) {
lo[n] = (uint64_t)(uintptr_t)cp.pool_dev;
hi[n] = lo[n] + (uint64_t)cp.pool.size() * (uint64_t)cp.stride;
stride[n] = (uint64_t)cp.stride;
++n;
}
return n;
}
/* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier
* unit that has not been staged. */
@@ -587,10 +651,20 @@ public:
* unstage_units publish those units at their pool slots again. The caller must already have
* ordered the next writer of `dst` behind every op that read the copies; this
* only moves the address the NEXT issue resolves.
* stage_need the room stage_units would fill with `units` given room for all of them, so
* a caller packing several layers into one region can size each one's share;
* `largest`, when not null, gets the room the largest of those units takes.
*
* The span form packs into up to two stretches, the second taking what the first has no
* room left for: a ring's place that wraps past the region's end is two.
*/
struct StageSpan { char* dst; int64_t cap; };
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
RadEvent done, std::vector<int32_t>* staged);
int stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
RadEvent after, RadEvent done, std::vector<int32_t>* staged);
void unstage_units(const std::vector<int32_t>& staged);
int64_t stage_need(const std::vector<int32_t>& units, int64_t* largest = nullptr) const;
/* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) --------
*
@@ -629,18 +703,22 @@ private:
* mid-layer, because placement would then depend on host timing and stop being reproducible. */
struct Move {
enum class State { Free, Copying, Published, Quarantine };
/* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
/* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
* the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
* going back once the declared order says nothing will read it again this step -- it
* copies nothing and still needs the quarantine, because the barrier is about kernels
* already issued and not about bytes in flight. Drop is a unit in a lent slot going back
* to the host copy it kept: no copy either, and the same quarantine for the same reason. */
enum class Kind { Promote, Demote, Stage, Release, Drop };
* to the host copy it kept: no copy either, and the same quarantine for the same reason.
* Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers
* for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and
* `to_slot` the one it lands in. */
enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
State state = State::Free;
Kind kind = Kind::Promote;
int32_t unit = -1;
int64_t slab_slot = -1;
int64_t pool_slot = -1;
int64_t to_slot = -1;
RadEvent ev = nullptr;
};
@@ -672,6 +750,11 @@ private:
int64_t stride = 0;
int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */
int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */
int64_t n_turn = 0; /* lent slots kept free past those: the fill stops short
* of them and balance() drops lent units to rebuild them
* (MoverConfig::turnover_slots) */
int64_t n_donated = 0; /* units in lent slots that gave their host copy away
* (Mover::donor_slot); at most n_turn of them */
std::vector<char*> flex_ptr;
/* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the
* loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a
@@ -703,11 +786,36 @@ private:
RadStream mover_ = nullptr;
RadStream compute_ = nullptr;
RadEvent gate_ = nullptr; /* recorded on compute, waited on by the mover stream */
std::vector<RadCopySeg> stage_segs_; /* stage_units' list, kept so a layer allocates nothing */
struct StagePick { const char* src; int32_t u; int64_t bytes, need; char* dst; };
std::vector<StagePick> stage_picks_; /* the units stage_units may take, in pool order */
int gate_dispatch_ = -1;
/* A DISPATCH'S SWAP COPIES -- demotions, promotions and migrations -- GO TO THE CARD'S DMA ENGINE
* AS ONE LIST (flush_moves), sent at the end of balance() and before anything reads their events.
* Each move's event is recorded behind the list, so a move lands with its list. */
std::vector<RadCopySeg> move_segs_;
std::vector<int32_t> move_recs_;
int queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
int flush_moves();
std::vector<ClassPools> pools_;
std::vector<UnitState> unit_;
std::vector<Move> moves_;
/* Per unit, how many records are Copying it: unit_in_flight() without a walk of the records.
* The prefill stager asks for every pooled unit of every layer it stages, and the records
* number twice the slots a swap can hold, so a walk would grow with the move budget. */
std::vector<uint16_t> copying_;
/* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
std::vector<std::pair<float, int32_t>> drop_cand_;
bool hold_turnover_ = false;
/* donor_slot()'s candidates a class, by layer, each layer's coldest first so its hottest is at
* the back; ranked once a dispatch, `at` being the dispatch they were ranked for. */
struct DonorRank { int at = -1; std::vector<std::vector<std::pair<float, int32_t>>> by_layer; };
std::vector<DonorRank> donors_;
/* The layer whose unit each pool slot held when the pool was laid out, a class: the pool is
* filled in unit order, so a layer's pooled units start out side by side (pool_slot_for). */
std::vector<std::vector<int32_t>> pool_layer_;
int32_t n_layers_ = 0;
void* static_vram_ = nullptr;
int64_t static_bytes_ = 0;
@@ -756,6 +864,15 @@ private:
bool unit_in_flight(int32_t unit) const;
/* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
int drop(int32_t unit, HeatEngine* heat);
/* The pool slot a demotion copies `unit` into: one its layer's units started out in, else a
* same-layer donor's, else any free one, else any donor's; -1 when there is none. */
int64_t pool_slot_for(int32_t unit, HeatEngine* heat);
/* A pool slot for a budgeted victim when the pool has none free: the host copy of a unit in a
* slot the KV cache lent, which keeps its place in VRAM without one -- a unit of `layer`, or
* of any layer when it is negative. -1 when no unit may give one. See the definition. */
int64_t donor_slot(size_t klass, int32_t layer, HeatEngine* heat);
/* A donor out of a lent slot into a free budgeted one, if one is free: false when none is. */
bool migrate(int32_t unit, HeatEngine* heat);
/* One promotion out of the unit's pool slot into `slot`, which the caller has taken. */
int promote_to(int32_t unit, int64_t slot);
/* Promote the hottest pooled units of one class into up to `room` free slots. */
+11
View File
@@ -1243,6 +1243,17 @@ int Planner::assign(Plan* p) {
else if (has_conditional) s = Strategy::ExpertTiered;
else s = Strategy::LayerOffload;
p->strategy = s;
p->strategy_why =
s == Strategy::AllVram
? fmt("%s of weights fit the %s weights pool", humanb(total).c_str(),
humanb(p->vram_budget).c_str())
: s == Strategy::ExpertTiered
? fmt("%s of weights against a %s weights pool: routed experts, read only when "
"selected, are what spills to host memory", humanb(total).c_str(),
humanb(p->vram_budget).c_str())
: fmt("%s of weights against a %s weights pool and no routed experts to spill: "
"whole layers are offloaded", humanb(total).c_str(),
humanb(p->vram_budget).c_str());
RAD_DEBUG("placement: auto chose %s (%s of weights against a %s budget)",
strategy_name(s), humanb(total).c_str(), humanb(p->vram_budget).c_str());
}
+34 -4
View File
@@ -176,6 +176,18 @@ struct SlabClass {
#define RAD_PLACE_FILE_WINDOWS 4
#define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20)
/* THE HEAT ENGINE'S MOVE BUDGET: swaps a STEP, a slab class. HeatParams::moves_per_step defaults
* to it, and the free slots below are sized from it, because the two are one quantity: a swap
* that finds no free slot does not happen.
*
* The engine proposes once a step (Engine::tiering_dispatch), and a step routes every layer, so
* the budget has to cover the whole model's turnover. Replaying the routing of a mixed workload
* through the engine's policy at Qwen3.8-Flash-Next TP1 (40% of the experts resident), the hit
* rate on decode rows is 63.8% at 8 a step, 74.1% at 32, 77.1% at 64 and 77.8% at 128 -- and an
* oracle that knows every future routing, held to the same 64 swaps a step, reaches 78.0%. Past
* this the move rate, not the ranking, is what bounds the hit rate. */
#define RAD_PLACE_MOVES_PER_STEP 64
/* 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).
*
@@ -184,12 +196,28 @@ struct SlabClass {
* 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.
*
* 32 is far past where the knob stops mattering, and MORE is the wrong end of the problem: extra
* shadows raise the move rate and run SLOWER, because more copies in flight contend with the
* zero-copy tier for the same link. The quarter-of-the-slab cap only ever binds on a slab too
* small for the number to be meaningful. */
* THESE ARE THE SLOTS THE ENGINE CAN ALWAYS COUNT ON, and the expert floor charges for them
* (expert_vram_floor), so every slot here is one the KV cache can never have. The rest of what the
* move budget needs is RAD_PLACE_TURNOVER_SLOTS, taken out of the cache's loan instead. The
* quarter-of-the-slab cap only ever binds on a slab too small for the number to be meaningful. */
#define RAD_PLACE_SHADOW_SLOTS 32
/* THE TURNOVER SLOTS: free slab slots the mover keeps out of a loan (Mover::lend_from), past the
* shadow slots, by filling the loan's slots only up to them. A swap holds a slot for about three
* steps -- the copies go out behind the step that proposed them, the next step's retire publishes
* them, and the slot the demotion left comes back only once the compute stream has passed the
* quarantine recorded after that publish -- so a budget of RAD_PLACE_MOVES_PER_STEP needs three
* times as many free slots, and with fewer the budget is smaller than it says. At 64 a step,
* replaying the routing with 32 slots in all reaches 65.9% against 77.9% with 192.
*
* Out of the loan because that costs the cache nothing: a lent slot left free is one the experts
* were borrowing anyway, and charged to the expert floor instead the same slots would come out of
* the cache's largest size. When the cache takes memory back, the free slots at the loan's top go
* first and the mover rebuilds them by dropping its coldest lent units, which still have their
* host copies (Mover::balance); only once nothing is lent does the move rate fall back to what
* the shadow slots alone allow. */
#define RAD_PLACE_TURNOVER_SLOTS (3 * RAD_PLACE_MOVES_PER_STEP - RAD_PLACE_SHADOW_SLOTS)
/* ------------------------------------------------------------------ per-weight result */
struct Placement {
Tier tier = Tier::VRAM;
@@ -206,6 +234,8 @@ class Plan {
public:
int rank = 0, world_size = 1;
Strategy strategy = Strategy::Auto;
/* Why `strategy` is the one it is, when `auto` chose it; empty when it was asked for. */
std::string strategy_why;
/* False under Config::deterministic. Dynamic placement sets which experts are resident and
* residency sets the summation order, so identical inputs do not give identical outputs
+217 -77
View File
@@ -6,10 +6,12 @@
namespace rad {
PrefillStager::~PrefillStager() {
for (int b = 0; b < 2; ++b) {
if (done_[b]) rad_event_destroy(done_[b]);
if (free_[b]) rad_event_destroy(free_[b]);
for (Place& p : place_) {
if (p.done) rad_event_destroy(p.done);
if (p.free) rad_event_destroy(p.free);
}
for (RadEvent& g : gate_)
if (g) rad_event_destroy(g);
}
int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region,
@@ -19,11 +21,16 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
/* A ROUTED LAYER IS ITS EXPERT UNITS, and the ops that read it are the span their declared
* uses cover: the first is the one that must find the copies, the last the one after which
* nothing reads them again -- once the block's last pass of rows has issued it (after_op). */
* nothing reads them again -- once the block's last pass of rows has issued it (after_op).
* A declared draft head's layer, numbered past the trunk's, is not one (see the top of
* stager.h). */
const int32_t trunk = prog.drafter.kind != RAD_DRAFT_NONE && prog.meta.n_layers > 0
? (int32_t)prog.meta.n_layers : INT32_MAX;
std::map<int32_t, Layer> by_layer;
for (size_t u = 0; u < plan.units.size(); ++u) {
const MoveUnit& mu = plan.units[u];
if (mu.expert < 0 || mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0) continue;
if (mu.layer >= trunk) continue;
Layer& L = by_layer[mu.layer];
L.layer = mu.layer;
L.units.push_back((int32_t)u);
@@ -33,8 +40,8 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
for (auto& kv : by_layer) layers_.push_back(std::move(kv.second));
std::sort(layers_.begin(), layers_.end(),
[](const Layer& a, const Layer& b) { return a.first_op < b.first_op; });
/* Two layers' spans must not overlap: a layer's copies are released at its last op, and the
* next layer's buffer is the one the layer before it released. */
/* Two layers' spans must not overlap: a layer's copies are given back at the next layer's
* first op, which must be past every op that reads them. */
for (size_t i = 1; i < layers_.size(); ++i)
if (layers_[i].first_op <= layers_[i - 1].last_op) {
RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d "
@@ -54,130 +61,263 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
}
mover_ = mover;
cap_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
buf_[0] = region;
buf_[1] = region + cap_;
region_ = region;
ring_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT * 2;
head_ = 0;
min_rows_ = min_rows;
for (int b = 0; b < 2; ++b) {
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
n_early_ = 0;
ring_order_.clear();
spare_.clear();
for (int i = kPlaces - 1; i >= 0; --i) {
Place& p = place_[i];
if (rad_event_create_local(&p.done) < 0 || rad_event_create_local(&p.free) < 0) {
layers_.clear();
return RAD_E_DEVICE;
}
spare_.push_back(i);
}
started_.assign(layers_.size(), 0);
return RAD_OK;
for (int i = 0; i < kGates; ++i) {
if (rad_event_create_local(&gate_[i]) < 0) {
layers_.clear();
return RAD_E_DEVICE;
}
gate_li_[i] = -1;
}
/* The backend opens what its first list needs -- the card's DMA queue -- here at bring-up, not
* inside the first long prompt's first step. */
return rad_memcpy_list_async(nullptr, 0, 0, mover_->transfer_stream());
}
/* A TRUNK PASS AT THE FULL PLAN AND LARGE ENOUGH, and only that (see the top of stager.h). The
* next trunk pass's first layers, staged at the end of the last one, are this pass's if it arms
* and go back to the pool if it does not. */
bool PrefillStager::begin_pass(const RadBatch* b) {
armed_ = full_ && enabled() && b && b->n_tok >= min_rows_;
if (!armed_) return false;
std::fill(started_.begin(), started_.end(), (uint8_t)0);
holds_[0] = holds_[1] = -1;
if (!b || b->draft_pass != 0) return false;
armed_ = full_ && enabled() && b->n_tok >= min_rows_;
staged_ = armed_;
if (!armed_) {
withdraw_early();
return false;
}
first_op_ = true;
pass_kind_ = b->draft_pass;
last_issued_ = -1;
next_ = 0;
first_li_ = -1;
for (int32_t& g : gate_li_) g = -1;
return true;
}
bool PrefillStager::will_issue(int32_t li) const {
const auto it = pass_last_.find(pass_kind_);
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
/* The early layers' copies back to the pool: nothing has read them, so there is no `free` to
* record and the next copy over their places needs no wait for them. */
void PrefillStager::withdraw_early() {
for (int32_t i : ring_order_) {
Place& p = place_[i];
if (!p.retired) retire(p);
}
n_early_ = 0;
}
int PrefillStager::start(int32_t li) {
started_[(size_t)li] = 1;
const int b = li & 1;
if (holds_[b] >= 0) return RAD_OK; /* the layer before still holds it: stream this one */
const int rc = mover_->stage_units(layers_[(size_t)li].units, buf_[b], cap_,
free_rec_[b] ? free_[b] : nullptr, done_[b], &staged_[b]);
if (rc < 0) return rc;
if (!staged_[b].empty()) { holds_[b] = li; read_[b] = false; }
/* The host half of giving a place back: its units are published at their pool slots again, which
* the next residency sync hands to the weight tables. The device half is `free`, which the copy
* that laps the place waits on. */
void PrefillStager::retire(Place& p) {
mover_->unstage_units(p.staged);
p.staged.clear();
p.retired = true;
}
/* The oldest place leaves the ring, and the mover's stream waits on its last reader: whatever is
* copied there later goes out behind that wait. */
int PrefillStager::recycle_front() {
const int32_t i = ring_order_.front();
Place& p = place_[i];
if (p.free_rec) RAD_TRY(rad_event_wait(mover_->transfer_stream(), p.free));
p.li = -1;
p.free_rec = p.read = p.retired = false;
ring_order_.pop_front();
spare_.push_back(i);
return RAD_OK;
}
/* The host half of letting a buffer go: its units are published at their pool slots again, which
* the next residency sync hands to the weight tables. The device half is `free_`. */
void PrefillStager::release(int32_t b) {
mover_->unstage_units(staged_[b]);
staged_[b].clear();
holds_[b] = -1;
read_[b] = false;
/* A PLACE OF `want` BYTES at the head of the ring, or -- `partial` -- all the room the head can
* reach when `want` does not fit. The head may write over retired places only: the oldest place
* still published bounds it a whole ring ahead of where that place starts. *out is -1 when
* nothing fits. */
int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
*out = -1;
int64_t limit = head_ + ring_;
for (int32_t i : ring_order_)
if (!place_[i].retired) { limit = place_[i].beg + ring_; break; }
int64_t len = std::min(want, limit - head_);
if (len < want && !partial) return RAD_OK;
if (len < RAD_ALIGN_UNIT) return RAD_OK;
const int64_t end = head_ + len;
/* Every place the new one laps leaves the ring first; then, with the table full, the oldest
* retired ones -- their waits only order the mover's stream behind reads long finished. */
while (!ring_order_.empty() && place_[ring_order_.front()].beg + ring_ < end)
RAD_TRY(recycle_front());
while (spare_.empty() && !ring_order_.empty() && place_[ring_order_.front()].retired)
RAD_TRY(recycle_front());
if (spare_.empty()) return RAD_OK;
const int32_t i = spare_.back();
spare_.pop_back();
Place& p = place_[i];
p.beg = head_;
p.end = end;
*out = i;
return RAD_OK;
}
int PrefillStager::finish(int32_t b, RadStream s) {
RAD_TRY(rad_event_record(free_[b], s));
free_rec_[b] = true;
release(b);
/* ONE LAYER INTO THE RING, behind `gate` when it is not null. `now` is the layer the run reaches
* next, which takes whatever room there is up to all it needs; any other goes only whole and at
* most half the ring -- so the next layer never finds less room than two buffers of half the ring
* gave it, and a heavy layer is not cut short for having been reached early. *got is kStaged, kNone
* when nothing of the layer is pooled, or kLater when the ring has no room for it yet. */
int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
*got = kLater;
const Layer& L = layers_[(size_t)li];
int64_t unit = 0;
const int64_t need = mover_->stage_need(L.units, &unit);
if (need <= 0) { *got = kNone; return RAD_OK; }
if (!now && need > ring_ / 2) return RAD_OK;
/* A place that runs past the region's end is two stretches, and the first can end in less
* room than a unit: it asks for one unit more than the layer needs. */
const int64_t want = head_ % ring_ + need > ring_ ? need + unit : need;
int32_t i = -1;
RAD_TRY(take(want, now, &i));
if (i < 0) return RAD_OK;
Place& p = place_[i];
p.li = li;
if (gate) RAD_TRY(rad_event_wait(mover_->transfer_stream(), gate));
/* A place that runs past the region's end goes on at its start. */
const int64_t off = p.beg % ring_, len = p.end - p.beg;
Mover::StageSpan sp[2] = { { region_ + off, std::min(len, ring_ - off) },
{ region_, len - std::min(len, ring_ - off) } };
RAD_TRY(mover_->stage_units(L.units, sp, sp[1].cap > 0 ? 2 : 1, nullptr, p.done, &p.staged));
if (p.staged.empty()) {
p.li = -1;
spare_.push_back(i);
*got = kNone;
return RAD_OK;
}
head_ = p.end;
ring_order_.push_back(i);
*got = kStaged;
return RAD_OK;
}
/* STAGE THE LAYERS AFTER `cur` as far as the pace lets them go and the ring has room. A layer
* nothing of which is pooled is passed over; one the ring has no room for yet, or whose pace
* layer the run has not reached, stops the walk until a later op. */
int PrefillStager::stage_ahead(int32_t cur, bool* resync) {
while ((size_t)next_ < layers_.size()) {
const int32_t g = next_ - kLead;
RadEvent gate = nullptr;
if (g >= first_li_) {
if (gate_li_[g % kGates] != g) break;
gate = gate_[g % kGates];
}
int got = kLater;
RAD_TRY(stage_layer(next_, next_ <= cur + 1, gate, &got));
if (got == kLater) break;
*resync = *resync || got == kStaged;
++next_;
}
return RAD_OK;
}
int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
*resync = false;
if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
/* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copy runs behind
* whatever the pass issues before the layer. */
/* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copies run behind
* whatever the pass issues before the layer -- and the layers after it as far as the pace and
* the ring allow. The layers the pass before staged for it are its own from here. */
if (first_op_) {
first_op_ = false;
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
[](const Layer& L, int32_t op) { return L.first_op < op; });
if (it != layers_.end()) {
const int32_t li = (int32_t)(it - layers_.begin());
if (!started_[(size_t)li] && will_issue(li)) {
RAD_TRY(start(li));
next_ = (int32_t)(it - layers_.begin());
first_li_ = next_;
if (n_early_ > 0 && next_ != 0) {
withdraw_early();
*resync = true;
}
next_ = std::max(next_, n_early_);
n_early_ = 0;
RAD_TRY(stage_ahead(first_li_ - 1, resync));
}
}
if ((size_t)h >= first_of_.size()) return RAD_OK;
const int32_t li = first_of_[(size_t)h];
if (li < 0) return RAD_OK;
/* This layer's copies were published a layer ago: the one wait that orders its ops behind
* them. */
for (int b = 0; b < 2; ++b)
if (holds_[b] == li) RAD_TRY(rad_event_wait(s, done_[b]));
/* The layer before is done with its buffer: every pass of rows issued its last op, the last
* of them recorded `free_`, and a layer's ops do not interleave with the next one's. Released
* here and not at that op, whose next run would read copies already overwritten. */
for (int b = 0; b < 2; ++b)
if (holds_[b] >= 0 && holds_[b] != li && read_[b]) release(b);
/* And the next layer's copies go out now, behind it. */
const int32_t next = li + 1;
if ((size_t)next < layers_.size() && !started_[(size_t)next] && will_issue(next)) {
RAD_TRY(start(next));
*resync = true;
/* The run's arrival at this layer, which the copies kLead layers on are paced by. */
RAD_TRY(rad_event_record(gate_[li % kGates], s));
gate_li_[li % kGates] = li;
/* This layer's copies were published when they went out: the one wait that orders its ops
* behind them. */
for (int32_t i : ring_order_) {
Place& p = place_[i];
if (!p.retired && p.li == li) RAD_TRY(rad_event_wait(s, p.done));
}
/* The layers before are done with their places: every pass of rows issued their last op, the
* last of them recorded `free`, and a layer's ops do not interleave with the next one's. Given
* back here and not at that op, whose next run would read copies already overwritten. */
for (int32_t i : ring_order_) {
Place& p = place_[i];
if (!p.retired && p.li < li && p.read) retire(p);
}
/* And the copies go on ahead of it into the room that gave back. */
if (next_ <= li) next_ = li + 1;
const bool was = *resync;
RAD_TRY(stage_ahead(li, resync));
*resync = *resync || was;
return RAD_OK;
}
/* THE LAYER'S LAST OP: `free_` goes behind it, so the copies two layers on can start as early as
* they could before -- and goes behind it again if the block issues the op for another pass of
* rows, which is why the copies themselves are not released until the next layer starts. */
/* THE LAYER'S LAST OP: `free` goes behind it, so a copy that laps its place can start as early as
* it could -- and goes behind it again if the block issues the op for another pass of rows, which
* is why the copies themselves are not given back until the next layer starts. */
int PrefillStager::after_op(rad_op h, RadStream s) {
if ((size_t)h >= last_of_.size()) return RAD_OK;
const int32_t li = last_of_[(size_t)h];
if (li < 0) return RAD_OK;
for (int b = 0; b < 2; ++b)
if (holds_[b] == li) {
RAD_TRY(rad_event_record(free_[b], s));
free_rec_[b] = true;
read_[b] = true;
}
for (int32_t i : ring_order_) {
Place& p = place_[i];
if (p.retired || p.li != li) continue;
RAD_TRY(rad_event_record(p.free, s));
p.free_rec = true;
p.read = true;
}
return RAD_OK;
}
/* Nothing this pass staged outlives it. Then, when the next step goes on with a prompt, its trunk
* pass's first layers go into the ring behind this pass's last ones -- layer k paced on this
* pass's layer n - kLead + k, as the run would pace it if the two passes were one. */
int PrefillStager::end_pass(RadStream s) {
if (!armed_) return RAD_OK;
armed_ = false;
pass_last_[pass_kind_] = last_issued_;
int rc = RAD_OK;
for (int b = 0; b < 2; ++b)
if (holds_[b] >= 0) {
const int r = finish(b, s);
if (r < 0 && rc >= 0) rc = r;
}
return rc;
for (int32_t i : ring_order_) {
Place& p = place_[i];
if (p.retired) continue;
const int r = rad_event_record(p.free, s);
if (r < 0 && rc >= 0) rc = r;
p.free_rec = r >= 0 || p.free_rec;
retire(p);
}
if (rc < 0 || !next_prefill_) return rc;
const int32_t n = (int32_t)layers_.size();
for (int32_t k = 0; k < kLead && k < n; ++k) {
const int32_t g = n - kLead + k;
if (g < first_li_ || gate_li_[g % kGates] != g) break;
int got = kLater;
RAD_TRY(stage_layer(k, /*now=*/false, gate_[g % kGates], &got));
if (got == kLater) break;
n_early_ = k + 1;
}
return RAD_OK;
}
/* ================================================================== the file stager */
+128 -50
View File
@@ -1,5 +1,5 @@
/* stager.h -- the prefill stager: a routed layer's non-resident experts copied onto the card one
* layer ahead of the layer that reads them.
/* stager.h -- the prefill stager: routed layers' non-resident experts copied onto the card ahead
* of the layers that read them.
*
* ---- WHY A PREFILL NEEDS IT -------------------------------------------------------------------
*
@@ -12,44 +12,86 @@
* work leaves the link idle. Measured with r4d_selftest --perfmoe, the gate_up GEMM of a 2048-token
* chunk is 1.53 ms with every expert on the card and 4.34 ms with the coldest 13% in host memory.
*
* So at a step large enough, the stager copies layer L+1's pooled experts into a VRAM buffer while
* layer L runs, publishes the copies for layer L+1's ops, and publishes the host addresses again
* once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
* So at a step large enough, the stager copies the pooled experts of the layers ahead into a VRAM
* ring while the layers before them run, publishes the copies for each layer's ops, and publishes
* the host addresses again once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
* is bit-identical; only when the link carries them moves.
*
* ---- WHERE THE BUFFERS ARE, AND WHEN THEY ARE ITS ---------------------------------------------
* ---- WHERE THE RING IS, AND WHEN IT IS ITS ---------------------------------------------------
*
* Two buffers, each one layer's share of the experts the budget leaves off the card, at the top of
* the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step smaller
* than the arena's full plan LENDS that top to the expert slab, so the buffers are the stager's
* only in a step at the full plan -- which is exactly the steps worth staging for -- and the rest of
* the time they hold resident experts like any other lent slot. The scheduler says which it is,
* pass by pass (set_full_arena).
* One region, the size of two layers' share of the experts the budget leaves off the card, at the
* top of the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step
* smaller than the arena's full plan LENDS that top to the expert slab, so the region is the
* stager's only in a step at the full plan -- which is exactly the steps worth staging for -- and
* the rest of the time it holds resident experts like any other lent slot. The scheduler says
* which it is, pass by pass (set_full_arena).
*
* ---- WHY A RING AND NOT TWO BUFFERS ------------------------------------------------------------
*
* Layers do not leave equal parts off the card: at depth, with the KV cache's loan taken back, the
* last third of a Qwen3.8-Flash-Next stack pools about twice the median layer. With two buffers of
* one share each, layer L+1's copy waits for layer L-1's last op, so the engine idled once a light
* layer's copy was done -- 60 to 80 ms of a ~280 ms step -- and a heavy layer's copy, longer than
* the layer before it, made every layer after it wait. The ring packs each layer at its own size,
* so the copies run as far ahead as the light layers leave room for and the heavy ones start
* early. A layer staged further ahead than the next one takes at most half the ring, so the next
* layer always has the room two buffers gave it; the next one takes whatever is free.
*
* ---- THE ORDER, AND WHAT KEEPS IT SAFE ---------------------------------------------------------
*
* the pass's first op stage the first routed layer the pass issues, into buffer 0 or 1
* a layer's first op stage the NEXT layer into the other buffer; re-read the residency
* table so this layer's ops resolve the copies made one layer ago
* a layer's last op record "buffer free" on the op's stream; publish the host addresses
* the pass's end the same for anything still staged: nothing outlives its pass
* the pass's first op stage the first routed layer the pass issues, and the ones after it
* as far as the pace and the ring allow
* a layer's first op wait on its copies; publish the host addresses of the layers before
* it again; stage further layers into the room that gave back
* a layer's last op record "free" behind it on the op's stream
* the pass's end the same for anything still staged -- and, when the next step goes on
* with a prompt, stage the first layers of its trunk pass
*
* A copy into a buffer waits on that buffer's "free" event, recorded behind the last op that read
* the layer it held -- in this pass or an earlier one. The layer's ops wait on the copies' event
* through ONE stream wait, issued before the layer's first op: the copies are published settled
* (Mover::stage_units says why), and nothing but the layer's own ops ever resolves them.
* A layer's place in the ring is counted in bytes the ring has handed out since bring-up, so a
* place laps the region and a copy finds the places it overwrites from the count alone. Before a
* copy goes out, the mover's stream waits on the "free" event of every earlier place it laps --
* recorded behind the last op that read it, in this pass or an earlier one. The layer's ops wait on
* the copies' event through ONE stream wait, issued before the layer's first op: the copies are
* published settled (Mover::stage_units says why), and nothing but the layer's own ops ever
* resolves them.
*
* A LAYER IS STAGED AHEAD ONLY WHEN THE PASS WILL ISSUE IT. A step issues its routed layers across
* more than one pass -- the trunk in one, the MTP head's in the next -- and the last layer a trunk
* pass stages ahead would otherwise be the head's, copied for a pass that never reads it and thrown
* away at its end. The stager learns the last op each kind of pass issues (by draft_pass) and stages
* a layer ahead only when its first op is at or below it.
* ---- HOW FAR AHEAD ----------------------------------------------------------------------------
*
* A layer's copies go out once the compute stream has reached the MoE of the layer kLead before it,
* through an event recorded at that layer's first op. Not as soon as the ring has room: copies that
* land long before their layer is read cost the layers they overlap more than they save. Measured at
* TP2 on Qwen3.8-Flash-Next, released as soon as there was room, every class of op ran slower and a
* 26K-token prompt lost 0.6%; held to one layer ahead, the heavy late layers of a 160K-token prompt
* waited again and it lost 2.4%. Three layers ahead covered the late layers at the smallest cost
* to the short prompt.
*
* ---- THE NEXT STEP'S FIRST LAYERS -------------------------------------------------------------
*
* A step that carries a chunk of a prompt is issued only once the step before it has been read
* back, so the copies of its first layers would start with it and its first layer would wait for
* all of them. When the engine says the next step goes on with a prompt (set_next_prefill), the
* pass's end stages the first layers of the next trunk pass instead, paced on this pass's last
* layers as if the two passes were one. They are published at once. The next trunk pass adopts them
* when it is armed; a trunk pass that is not publishes their host addresses again in begin_pass,
* which the run phase calls before it brings the weight tables up to date. A draft pass in between
* reads none of the trunk's layers and leaves them be. With both, against two buffers at TP2: 160K
* 1.0-1.4% faster, 26K unchanged; at TP1, where the link carries every pooled expert each step,
* 26K 0.6% faster.
*
* ---- ONLY THE TRUNK ---------------------------------------------------------------------------
*
* A draft head's routed layer is not the stager's. The head runs in passes of its own -- over a
* prefill chunk, the history pass, which needs the head's experts on a prompt's last chunk alone
* and there only for the rows that draft, a handful however long the chunk -- so its pooled
* experts are read in place like a decode step's. The head's layer is numbered past the
* trunk's layers (RadModelMeta::n_layers), left out at bring-up, and a draft pass is never armed.
*/
#pragma once
#include "../runtime/stager.h"
#include "mover.h"
#include "planner.h"
#include <deque>
#include <map>
#include <vector>
@@ -60,22 +102,29 @@ public:
~PrefillStager() override;
/* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at
* `region` as two buffers. `min_rows` is the smallest pass it arms for. Leaves it disabled --
* `region` as the ring. `min_rows` is the smallest pass it arms for. Leaves it disabled --
* enabled() false -- when the plan has no routed layer with a pooled unit to stage. */
int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes,
int64_t min_rows);
/* Per pass, before it is released: whether the step runs at the arena's full plan, which is
* when the buffers are not lent. */
* when the region is not lent. */
void set_full_arena(bool full) { full_ = full; }
/* Per step, before it is released: whether the step after it goes on with a prompt in a pass
* this stager arms for, so this step's trunk pass stages that pass's first layers. */
void set_next_prefill(bool more) { next_prefill_ = more; }
bool enabled() const { return !layers_.empty(); }
int64_t buffer_bytes() const { return cap_; }
int64_t ring_bytes() const { return ring_; }
/* The smallest pass (in tokens) the stager arms for: a step under it reads every pooled
* expert of a routed layer synchronously. The scheduler keeps a held-back prefill chunk at
* or above it (Scheduler::set_stage_rows). */
int64_t min_rows() const { return min_rows_; }
size_t n_layers() const { return layers_.size(); }
/* Whether the last trunk pass armed: its routed layers' pooled experts were copied onto the
* card through the ring. A draft pass leaves it as the trunk pass set it. */
bool staged() const { return staged_; }
static constexpr int32_t lead() { return kLead; }
bool begin_pass(const RadBatch* b) override;
int before_op(rad_op h, RadStream s, bool* resync) override;
@@ -92,33 +141,62 @@ private:
std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */
std::vector<int32_t> last_of_; /* by op: the layer whose last op it is, or -1 */
/* ONE LAYER'S PLACE IN THE RING. [beg, end) is in bytes handed out since bring-up; the
* offset in the region is beg modulo its size, and a place never straddles the region's end. */
struct Place {
int32_t li = -1; /* index into layers_ */
int64_t beg = 0, end = 0;
RadEvent done = nullptr; /* behind its copies, on the mover stream */
RadEvent free = nullptr; /* behind its last reader */
bool free_rec = false;
/* Its last op has been issued at least once and `free` is recorded behind it. A step
* longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
* last op can run again: the copies are published away at the NEXT layer's first op,
* which is past every pass, while each run of the last op moves `free` behind itself. */
bool read = false;
bool retired = false; /* its units are published at their pool slots */
std::vector<int32_t> staged;
};
/* More places than a ring of two shares can hold layers of the smallest share a pass stages;
* a full table only stops the copies going further ahead. */
static constexpr int kPlaces = 16;
Place place_[kPlaces];
std::deque<int32_t> ring_order_; /* places in the ring, oldest first; retired ones stay until lapped */
std::vector<int32_t> spare_; /* places not in the ring */
Mover* mover_ = nullptr;
char* buf_[2] = { nullptr, nullptr };
int64_t cap_ = 0;
char* region_ = nullptr;
int64_t ring_ = 0;
int64_t head_ = 0; /* bytes handed out since bring-up */
int64_t min_rows_ = 0;
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
RadEvent free_[2] = { nullptr, nullptr }; /* behind a buffer's last reader */
bool free_rec_[2] = { false, false };
std::vector<int32_t> staged_[2];
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
/* The holder's last op has been issued at least once, and `free_` is recorded behind it. A
* step longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
* last op can run again: the copies are released at the NEXT layer's first op, which is past
* every pass, while each run of the last op moves `free_` behind itself. */
bool read_[2] = { false, false };
/* THE PACE (see the top of this file): layer k's copies wait on the event recorded at the
* first op of layer k - kLead, on the compute stream. A layer within kLead of the pass's first
* routed layer has no such layer in its pass and goes at once. */
static constexpr int32_t kLead = 3;
static constexpr int kGates = 64;
RadEvent gate_[kGates] = {};
int32_t gate_li_[kGates] = {}; /* the layer each gate was recorded at this pass, or -1 */
int32_t first_li_ = -1; /* the pass's first routed layer */
bool full_ = false;
bool armed_ = false;
bool first_op_ = false; /* the pass has issued nothing yet */
std::vector<uint8_t> started_; /* by layer: staged (or tried) this pass */
int32_t pass_kind_ = 0;
int32_t last_issued_ = -1;
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
/* armed_ as the last trunk pass's begin_pass set it, which end_pass leaves alone: the engine
* asks after the pass has ended. */
bool staged_ = false;
bool next_prefill_ = false;
bool first_op_ = false; /* the pass has issued nothing yet */
int32_t next_ = 0; /* the next layer to stage this pass */
/* The next trunk pass's first layers, staged at this pass's end: layers [0, n_early_). */
int32_t n_early_ = 0;
bool will_issue(int32_t li) const;
int start(int32_t li);
int finish(int32_t b, RadStream s);
void release(int32_t b);
enum { kStaged, kNone, kLater };
int stage_ahead(int32_t cur, bool* resync);
int stage_layer(int32_t li, bool now, RadEvent gate, int* got);
void withdraw_early();
int take(int64_t want, bool partial, int32_t* out);
int recycle_front();
void retire(Place& p);
};
/* ---- THE FILE STAGER: routed layers read from the container -------------------------------------
+4
View File
@@ -455,6 +455,7 @@ int Registry::commit_(Staged& s, int order) {
if (q->decode) enc_add_decoder(q->decode);
}
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
const auto collective = dl_fn<RadKernelCollectiveFn>(s.handle, "rad_kernel_collective");
for (const auto& sr : staged_rows) {
KernelRow row;
row.info = sr.first;
@@ -462,6 +463,9 @@ int Registry::commit_(Staged& s, int order) {
row.plugin_order = order;
row.index = sr.second;
row.concurrent = concurrent && concurrent(sr.second) != 0;
const int coll = collective ? collective(sr.second) : 0;
row.collective = coll != 0;
row.releases_link = coll == 2;
row.reference = p.reference;
rows_.push_back(row);
}
+35
View File
@@ -53,6 +53,11 @@ struct KernelRow {
* their operands and their scratch, so one may run beside another that shares none of those
* bytes. False when the plugin does not say. */
bool concurrent = false;
/* The plugin's rad_kernel_collective answer for this row: its launches exchange data with
* the other ranks' cards, and -- `releases_link` -- end the engine's hold on the link
* themselves, through `link_gate`. False when the plugin does not say. */
bool collective = false;
bool releases_link = false;
/* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */
bool reference = false;
};
@@ -573,6 +578,17 @@ struct SamplingParams {
std::shared_ptr<const GbnfProgram> grammar_program;
};
/* THE RAW LOGITS AT CHOSEN VOCABULARY IDS, read at the prompt's last position: what a caller
* that answers from a distribution over a handful of tokens needs (/v1/systemone), and nothing
* more of the vocabulary. The caller fills `tokens` before submission; the engine writes `logits`
* in the same order, from the logits row BEFORE the sampler touches it, and before the request's
* sink finishes. Read them only after a successful finish. Shared, so the result outlives a
* caller that left mid-step. */
struct TokenScores {
std::vector<int32_t> tokens;
std::vector<float> logits;
};
struct Request {
uint64_t id = 0;
std::vector<int32_t> prompt;
@@ -640,6 +656,19 @@ struct Request {
* it; the logits buffer is sized for it there and nowhere else. */
bool score = false;
/* THE END OF A PREFIX OTHER REQUESTS WILL START FROM, in prompt tokens; 0 for none. On a
* model with linear state (convolutions, a recurrence) a prefix hit resumes from a state
* checkpoint, and those are written only on the checkpoint interval and at a long prompt's
* tail -- neither is where a shared head of a few hundred tokens ends. The scheduler ends a
* prefill chunk here, rounded down to its quantum, and writes a checkpoint as it does on the
* interval (Scheduler::plan_chunk), so the requests that follow reuse the whole head.
* /v1/systemone sets it on the first question of several over one state. */
int64_t checkpoint_at = 0;
/* NON-NULL: read the raw logits at these ids at the prompt's last position (TokenScores).
* The request still samples the one token max_tokens allows; the caller discards it. */
std::shared_ptr<TokenScores> token_scores;
/* 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
@@ -964,6 +993,12 @@ struct Config {
* output to say so, so it is refused unless this says otherwise -- deliberately, and by a
* flag with `debug` in its name (startup.h, rad_gate_reference_kernels). */
bool accept_reference_kernels = false;
/* WHERE EACH OPTION THE OPERATOR SET CAME FROM, keyed by the option table's spelling:
* "command line", or the environment variable that supplied it. An option absent here took
* its default or was resolved at startup -- the distinction the startup report
* (core/diag/diag.h) prints beside every value. */
std::map<std::string, std::string> given;
};
} /* namespace rad */
+80 -11
View File
@@ -4,6 +4,7 @@
*/
#include <vector>
#include "ctx.h"
#include "xp_state.h"
#include "../device/device.h"
#include <algorithm>
@@ -15,6 +16,7 @@ namespace rad {
/* ================================================================== lifecycle */
Ctx::Ctx() = default;
Ctx::~Ctx() { shutdown(); }
int Ctx::init(const CtxDesc& d) {
@@ -53,6 +55,7 @@ int Ctx::init(const CtxDesc& d) {
void Ctx::shutdown() {
oracle_close();
xp_close();
/* The one host synchronisation in the whole component, and it is at teardown rather than on
* the step path. Everything below frees memory the stream may still be reading or writing --
* the routing staging is the destination of a copy nobody waited on by design (spec §5.5), and
@@ -342,6 +345,7 @@ int Ctx::bind_ops() {
op_domain_ = std::vector<std::atomic<uint8_t>>(P.ops.size());
band_table_.clear();
issue_table_.clear();
gate_params_.clear();
int64_t n_bands_total = 0, n_plans = 0;
for (auto& o : P.ops) { n_bands_total += (int64_t)o.bands.size(); }
@@ -357,9 +361,9 @@ int Ctx::bind_ops() {
p.n_bands = (int32_t)oi.bands.size();
p.plan_off = (int32_t)issue_table_.size();
p.n_opd_schema = oi.schema ? (int32_t)oi.schema->n_operands : -1;
/* The one op whose issue costs interconnect bytes. Matched by name once, here, rather
* than on the issue path -- see OpPlan::collective. */
p.collective = (oi.op == "all_reduce");
/* Matched by name once, here, rather than on the issue path -- see OpPlan::billed. */
p.billed = (oi.op == "all_reduce");
p.collective = p.billed;
for (const Band& b : oi.bands) band_table_.push_back(b.hi);
@@ -370,6 +374,7 @@ int Ctx::bind_ops() {
if (r && r.row && r.row->info && r.row->info->launch) {
ip.row = r.row;
ip.launch = r.row->info->launch;
if (r.row->collective) p.collective = true;
/* Bound once. args.p views the frozen geometry inside Program::ops, which is
* why declare must not touch a Resolved after this point: the vector would
@@ -383,6 +388,20 @@ int Ctx::bind_ops() {
ip.args.instance = r.instance;
ip.args.rank = rank_;
ip.args.world_size = world_size_;
/* A launch that ends its own hold on the link is handed the word the hold is
* kept in, as one parameter more after the geometry's -- when it holds one. */
if (r.row->releases_link)
if (void* g = rad_link_gate(stream_)) {
std::vector<RadParam>& v =
gate_params_.emplace_back(ip.args.p, ip.args.p + ip.args.n_p);
RadParam q{};
q.key = "link_gate";
q.kind = RAD_P_INT;
q.ival = (long long)(uintptr_t)g;
v.push_back(q);
ip.gate_p = v.data();
ip.gate_n_p = (int)v.size();
}
if (r.scratch_bytes > arena_.scratch_bytes()) {
RAD_ERR("op '%s' band %lld kernel %s wants %s of scratch but the plan "
@@ -847,6 +866,7 @@ int Ctx::bind_profiling() {
prof_calls_.assign(program_->ops.size(), 0);
prof_host_.assign(program_->ops.size(), 0);
prof_join_ms_.assign(program_->ops.size(), 0.0);
prof_wait_ms_.assign(program_->ops.size(), 0.0);
if (!profiling_) return RAD_OK;
/* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the
@@ -888,12 +908,21 @@ void Ctx::profile_collect() {
++n_host_syncs_; /* counted, so the caveat is a number and not a claim */
if (rad_stream_sync(stream_) < 0) prof_n_ = 0;
}
/* The idle time before each op, per lane: the first op a lane runs in the step has nothing
* before it on that lane, and the gap from the last step is mostly this collection's own
* synchronisation, so it is not charged. */
const ProfSlot* prev[2] = { nullptr, nullptr };
for (size_t i = 0; i < prof_n_; ++i) {
ProfSlot& s = prof_ring_[i];
float ms = 0.0f;
if (rad_event_elapsed_ms(s.a, s.b, &ms) < 0) continue;
prof_ms_[(size_t)s.op] += (double)ms;
prof_calls_[(size_t)s.op] += 1;
const ProfSlot*& p = prev[s.lane & 1];
float gap = 0.0f;
if (p && rad_event_elapsed_ms(p->b, s.a, &gap) >= 0 && gap > 0.0f)
prof_wait_ms_[(size_t)s.op] += (double)gap;
p = &s;
}
if (prof_overflowed_) {
RAD_WARN("per-op timing: the step issued more than %zu ops; the tail was not timed",
@@ -912,9 +941,10 @@ void Ctx::dump_profile() const {
"enabling this restores synchronisations that change the mover's slot supply.\n"
"A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n"
"includes everything that call waited on -- page faults, link reads. The rest are\n"
"device event pairs around a kernel.\n\n"
" %10s %12s %10s %5s %10s %s\n", rank_, "calls", "total ms", "us/call", "site",
"join us", "op / geometry");
"device event pairs around a kernel. `wait us` is how long, a call, the op's lane\n"
"sat idle before it started -- stream waits and issue delays, in no op's time.\n\n"
" %10s %12s %10s %5s %10s %10s %s\n", rank_, "calls", "total ms", "us/call", "site",
"join us", "wait us", "op / geometry");
/* Slowest first: the only ordering anybody reads this table in. */
std::vector<size_t> order;
@@ -922,7 +952,7 @@ void Ctx::dump_profile() const {
std::sort(order.begin(), order.end(),
[&](size_t a, size_t b) { return prof_ms_[a] > prof_ms_[b]; });
double total = 0.0;
double total = 0.0, waited = 0.0;
for (size_t i : order) {
const OpInfo& o = program_->ops[i];
const bool ho = i < prof_host_.size() && prof_host_[i];
@@ -936,13 +966,16 @@ void Ctx::dump_profile() const {
* tied to anything. */
const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size()
? program_->weights[o.weights[0]].name.c_str() : "-";
fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %s %s #%d %s\n",
const double wait = i < prof_wait_ms_.size() ? prof_wait_ms_[i] : 0.0;
fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %10.2f %s %s #%d %s\n",
(long long)prof_calls_[i], prof_ms_[i],
prof_ms_[i] * 1000.0 / (double)prof_calls_[i], ho ? "host" : "dev", jbuf,
wait * 1000.0 / (double)prof_calls_[i],
o.op.c_str(), o.base.str().c_str(), (int)o.index, wname);
total += prof_ms_[i];
waited += wait;
}
fprintf(stderr, " %10s %12.3f\n\n", "total", total);
fprintf(stderr, " %10s %12.3f (waited %.3f ms besides)\n\n", "total", total, waited);
}
/* ================================================================== the step driver */
@@ -1200,6 +1233,22 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) {
same = std::memcmp(&x.t[k], &y.t[k], sizeof(RadTensor)) == 0;
if (!same) { *why = fmt("host op %zu (op %u) differs", i, (unsigned)x.h); return false; }
}
if (a.xp.size() != b.xp.size()) {
*why = fmt("%zu prefetch calls against %zu", a.xp.size(), b.xp.size());
return false;
}
for (size_t i = 0; i < a.xp.size(); ++i) {
const TapeXp& x = a.xp[i];
const TapeXp& y = b.xp[i];
const RadPrefetchNext& u = x.next;
const RadPrefetchNext& v = y.next;
if (u.layer != v.layer || u.router != v.router || u.n_expert != v.n_expert || u.top_k != v.top_k ||
u.n_parts != v.n_parts || u.parts != v.parts || u.count_at != v.count_at || x.h != y.h ||
x.r0 != y.r0 || x.rows != y.rows || x.n_embd != y.n_embd) {
*why = fmt("prefetch call %zu (for layer %d) differs", i, x.next.layer);
return false;
}
}
for (size_t i = 0; i < a.route.size(); ++i)
if (a.route[i].first != b.route[i].first ||
std::memcmp(&a.route[i].second, &b.route[i].second, sizeof(RadRouting)) != 0) {
@@ -1248,6 +1297,23 @@ int Ctx::play_pass(PassTape& t) {
rc = route_report_impl(t.route[(size_t)st.a].first, &t.route[(size_t)st.a].second,
false);
break;
case kTapeXp: {
const TapeXp& p = t.xp[(size_t)st.a];
lane_ = st.lane;
rc = xp_ ? xp_predict_run(p.next, p.h, p.r0, p.rows, p.n_embd) : RAD_OK;
lane_ = l0;
break;
}
case kTapeXpMark:
lane_ = st.lane;
rc = xp_ ? xp_mark_run() : RAD_OK;
lane_ = l0;
break;
case kTapeXpStep:
lane_ = st.lane;
rc = xp_ ? xp_step_run(st.a) : RAD_OK;
lane_ = l0;
break;
}
if (rc < 0) {
if (step_status_ >= 0) step_status_ = rc;
@@ -1350,6 +1416,11 @@ int Ctx::run_step(const RadBatch* b) {
return RAD_E_STATE;
}
/* BEFORE THE RESIDENCY SYNC: a stager may give back weights it published for this pass when
* it turns the pass down (runtime/stager.h), and the sync is what carries that into the
* tables the pass resolves. */
staging_ = stager_ != nullptr && stager_->begin_pass(b);
/* The mover relocates between steps, never during one. Honouring WeightInfo::generation here
* costs one relaxed atomic load per step instead of one per weight per issue. */
if (weights_dirty_.exchange(false, std::memory_order_acq_rel))
@@ -1361,8 +1432,6 @@ int Ctx::run_step(const RadBatch* b) {
step_fail_.clear();
prof_n_ = 0;
in_step_ = true;
staging_ = stager_ != nullptr && stager_->begin_pass(b);
{
const int rc = run_pass(b);
if (rc < 0 && step_status_ >= 0) step_status_ = rc;
+57 -6
View File
@@ -33,7 +33,9 @@
#include "device/device.h"
#include <atomic>
#include <memory>
#include <string>
#include <deque>
#include <vector>
#include <unordered_map>
@@ -45,6 +47,9 @@ struct RadCtx { };
namespace rad {
struct XpState;
struct XpLayer;
/* The widest op in the conventional vocabulary is gdn_conv_prep at sixteen operands, with
* gdn_recurrent_update behind it at fourteen -- both grew when the two kernel plugins' schemas
* were reconciled (docs/OPS.md, "How a schema is written"). Thirty-two leaves room for an
@@ -64,6 +69,11 @@ struct IssuePlan {
RadArgs args{};
RadLaunchFn launch = nullptr;
const KernelRow* row = nullptr;
/* The parameters a launch that holds the link is handed: the geometry's and `link_gate`, for a
* row that ends the hold itself; null for every other. Only such a launch takes them, so a
* step that holds nothing -- every decode step -- never pays the kernel's read of the word. */
const RadParam* gate_p = nullptr;
int gate_n_p = 0;
};
/* Per declared op. Trivially copyable on purpose: the bucket table and the issue plans live in two
@@ -79,10 +89,14 @@ struct OpPlan {
int32_t n_opd_schema = -1;
bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */
/* IS THIS OP A COLLECTIVE -- i.e. does issuing it put bytes on the interconnect? Set once at
* bind, so the accounting on the issue path is a predicted branch and not a string compare.
* The link is shared with the expert mover, so separating "how much of it is the all-reduce"
* needs the collective's own traffic counted. */
* bind, from the rows it resolved to (rad_kernel_collective) and the conventional all_reduce,
* so the issue path tests a predicted branch and not a string. The weight stager's copies
* share the link, and give way to it while it runs (Ctx::issue_body). */
bool collective = false;
/* The conventional all_reduce, whose `n` IS the message's element count -- the one collective
* the link bill can be charged for without guessing its wire format. The link is shared with
* the expert mover, so separating "how much of it is the all-reduce" needs this counted. */
bool billed = false;
};
/* ------------------------------------------------------------------ routing handoff */
@@ -203,7 +217,7 @@ struct CtxDesc {
/* ------------------------------------------------------------------ Ctx */
class Ctx : public RadCtx {
public:
Ctx() = default;
Ctx(); /* out of line, beside ~Ctx: xp_ points to a type this header only names */
~Ctx();
Ctx(const Ctx&) = delete;
Ctx& operator=(const Ctx&) = delete;
@@ -266,6 +280,16 @@ public:
* dense model, where nothing routes and bind_routing allocated nothing. */
int n_route_layers() const { return (int)route_.size(); }
int64_t route_n_expert() const { return route_n_expert_; }
/* ---------------------------------------------------- the next-layer expert prefetch
* (xprefetch.h). xp_open at bringup, once the placement has made its pinned pools: their device
* ranges and unit strides; it stays off -- and the three calls no-ops -- where the backend or the
* placement gives it nothing to do. */
void xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n);
void xp_close();
int xp_predict(const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
int xp_mark();
int xp_step(int layer);
/* DRAIN, DO NOT SAMPLE. `next_histogram` returns the oldest staging bank holding a LANDED
* histogram for a step past `after_step` and before `before_step`, or -1; a caller loops on it
* with the step of the last one it credited and so sees every histogram the device produced,
@@ -489,7 +513,14 @@ private:
* fresh issue again every kAuditPlays plays. A difference means the pass depends on something
* the key does not carry, and it fails the step naming the first dispatch that differs -- a
* silent difference would be wrong output. */
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3 };
enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3,
kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 };
/* A prefetch call (Ctx::xp_predict), run again where the pass made it. */
struct TapeXp {
RadPrefetchNext next{};
rad_buf h = 0;
int64_t r0 = 0, rows = 0, n_embd = 0;
};
struct TapeStep {
uint8_t kind = kTapePlay;
uint8_t lane = 0; /* the lane the host work ran on */
@@ -510,6 +541,7 @@ private:
std::vector<TapeStep> steps;
std::vector<TapeHost> host;
std::vector<std::pair<int, RadRouting>> route;
std::vector<TapeXp> xp;
/* What the recording added to the Ctx's counters, and the bookkeeping it ended on. */
int64_t issues = 0, ar_calls = 0, ar_bytes = 0, stream_waits = 0, host_syncs = 0;
bool touch_pending[2] = {};
@@ -633,6 +665,16 @@ private:
int issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n);
ArchStepFn arch_step_ = nullptr;
/* The expert prefetch's state (xp_state.h), null while it is off. */
std::unique_ptr<XpState> xp_;
void xp_free(XpState& x);
void xp_serve(XpState& x);
void xp_judge(XpState& x);
bool xp_bind(XpLayer& L, int layer);
int xp_predict_run(const RadPrefetchNext& next, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd);
int xp_mark_run();
int xp_step_run(int layer);
int rank_ = 0;
int world_size_ = 1;
int device_ = 0;
@@ -752,6 +794,9 @@ private:
std::vector<uint32_t> unflushed_;
std::vector<int64_t> band_table_;
std::vector<IssuePlan> issue_table_;
/* The parameter lists of the launches handed `link_gate`: the geometry's and that one. A deque,
* so a plan's pointer into one stays good as the next is added. */
std::deque<std::vector<RadParam>> gate_params_;
std::vector<std::atomic<uint8_t>> op_domain_; /* sized once, never resized */
std::vector<RouteSlot> route_;
@@ -771,7 +816,7 @@ private:
/* Profiling. Off by default; when on it restores synchronisations that change the mover's slot
* supply, so a profiled run is not comparable against an unprofiled one (spec §16). */
bool profiling_ = false;
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; };
struct ProfSlot { RadEvent a = nullptr, b = nullptr; int32_t op = 0; uint8_t lane = 0; };
std::vector<ProfSlot> prof_ring_;
size_t prof_n_ = 0;
bool prof_overflowed_ = false;
@@ -785,6 +830,12 @@ private:
* the pipeline the op STOPS, not of the arithmetic it does, and the two differ by two orders
* of magnitude on the PLE gather. */
std::vector<double> prof_join_ms_;
/* How long each op's lane sat idle before the op started: from the end of the op before it on
* that lane to this one's start. A stream wait (a staged layer's copies, the other lane, a
* host op's output) and a host that has not issued the op yet both land here, and neither is
* in any op's own time -- so a step whose ops sum to less than its wall time says where the
* rest went. */
std::vector<double> prof_wait_ms_;
std::atomic<bool> weights_dirty_{false};
/* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one
+42 -6
View File
@@ -873,7 +873,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* operand 0 carries the dtype it is sent in, which is the ACTIVATION's dtype and not the op's
* `dtype` key -- that key is the architecture's operand-combination spelling ("w4a8"), which
* is not an element width. Two relaxed adds on seventeen issues a step. */
if (p.collective && n_opd > 0) {
if (p.billed && n_opd > 0) {
const int bits = rad_dtype_bits(t[0].dtype);
ar_calls_.fetch_add(1, std::memory_order_relaxed);
if (bits > 0) ar_bytes_.fetch_add(n * bits / 8, std::memory_order_relaxed);
@@ -991,6 +991,24 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (host_paused) tape_pause(true);
const int rec0 = rec_ && !host_paused ? tape_mark() : 0;
/* A COLLECTIVE HAS THE CARD'S LINK TO ITSELF in a pass the stager copies weights through: the
* stager's lists yield while the hold is in force (rad_link_hold says why). Taken here, after
* every wait this op's operands put on the stream, so the stream waits on nothing between the
* hold and its release -- a weight it waited on could be behind a yielding list. */
const bool hold = staging_ && p.collective && dom == RAD_DOMAIN_DEVICE;
const RadArgs* la = &ip.args;
RadArgs gate_args;
if (hold) {
const int hs = rad_link_hold(cur_stream(), 1);
if (hs < 0) return abort_step(h, b, dom, ip, n, hs);
if (ip.gate_p) {
gate_args = ip.args;
gate_args.p = ip.gate_p;
gate_args.n_p = ip.gate_n_p;
la = &gate_args;
}
}
int s;
if (profiling_ && dom == RAD_DOMAIN_HOST) {
@@ -1007,7 +1025,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* Wall clock and not a device event, so it includes whatever the host call waits on:
* page faults, the link read of its input, everything. That is the number that matters. */
const auto t0 = std::chrono::steady_clock::now();
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
const auto t1 = std::chrono::steady_clock::now();
prof_ms_[(size_t)h] +=
std::chrono::duration<double, std::milli>(t1 - t0).count();
@@ -1020,12 +1038,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
if (prof_n_ < prof_ring_.size()) {
ProfSlot& ps = prof_ring_[prof_n_++];
ps.op = (int32_t)h;
ps.lane = (uint8_t)lane_;
rad_event_record(ps.a, cur_stream());
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
rad_event_record(ps.b, cur_stream());
} else {
prof_overflowed_ = true;
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
}
/* RANK 0 ONLY, FOR THE SECOND TIME IN THIS FILE. `Ctx::issue` runs on every rank thread, so a
* file-scope accumulator is written by both. Unguarded, the digest above gives wrong NUMBERS
@@ -1034,7 +1053,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
* race at all. Anything this instrument accumulates belongs to one thread. */
} else if (g_dbg_issue && rank() == 0) {
const auto ta = std::chrono::steady_clock::now();
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
const auto tb = std::chrono::steady_clock::now();
using us = std::chrono::duration<double, std::micro>;
g_iss_own += us(ta - t_iss0).count();
@@ -1081,7 +1100,13 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
g_iss_lau_p = g_iss_lau;
}
} else {
s = ip.launch(&ip.args, cur_stream());
s = ip.launch(la, cur_stream());
}
if (hold) {
/* Released whatever the launch said, by a barrier unless the launch said it ended the hold
* itself (RAD_LINK_ENDED): a list waiting on the hold would otherwise never end. */
const int hr = rad_link_hold(cur_stream(), la != &ip.args && s == RAD_LINK_ENDED ? 2 : 0);
if (hr < 0 && s >= 0) s = hr;
}
if (host_paused) tape_pause(false);
@@ -1315,6 +1340,17 @@ int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) {
return c ? static_cast<rad::Ctx*>(c)->route_counts(layer, n_expert) : nullptr;
}
int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows,
int64_t n_embd) {
return c ? static_cast<rad::Ctx*>(c)->xp_predict(next, h, r0, rows, n_embd) : RAD_E_INVAL;
}
int rad_expert_prefetch_mark(RadCtx* c) {
return c ? static_cast<rad::Ctx*>(c)->xp_mark() : RAD_E_INVAL;
}
int rad_expert_prefetch_step(RadCtx* c, int layer) {
return c ? static_cast<rad::Ctx*>(c)->xp_step(layer) : RAD_E_INVAL;
}
void* rad_weight_ptr(RadCtx* c, rad_weight w) {
return c ? static_cast<rad::Ctx*>(c)->weight_ptr(w) : nullptr;
}
+6 -2
View File
@@ -21,7 +21,9 @@ class OpStager {
public:
virtual ~OpStager() = default;
/* The pass is about to be issued: whether the stager takes part in it. */
/* The pass is about to be issued: whether the stager takes part in it. Called before the
* run phase brings the weight tables up to date, so a stager turning down a pass may give back
* weights it published ahead for it (see end_pass). */
virtual bool begin_pass(const RadBatch* b) = 0;
/* Before op `h` is issued on stream `s`. `*resync` is set when the residency table changed,
@@ -31,7 +33,9 @@ public:
/* After op `h` was issued on stream `s`: the point a staged weight's last reader is behind. */
virtual int after_op(rad_op h, RadStream s) = 0;
/* The pass has been issued, on `s`: nothing the stager published may outlive it. */
/* The pass has been issued, on `s`: nothing the stager published for it may outlive it. It
* may publish weights for a later pass it expects to arm for, which that pass's begin_pass
* keeps or gives back. */
virtual int end_pass(RadStream s) = 0;
};
+82
View File
@@ -0,0 +1,82 @@
/* xp_state.h -- the expert prefetch's host state, held by the Ctx (Ctx::xp_). See xprefetch.h. */
#pragma once
#include "xprefetch.h"
#include "rad_runtime.h"
#include "../device/device.h"
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace rad {
/* A routed layer as the prefetch knows it: the next-layer description a plugin hands over, and the
* device map from expert to its table entries, built at the first call after the layer's tables are
* bound. `want` is the request made for it this pass, which its step patches in. */
struct XpLayer {
RadPrefetchNext next{};
void** map = nullptr; /* device [kXpMaxNe][kXpParts]: entry addresses, null for none */
int32_t* place = nullptr; /* device [kXpMaxNe]: the expert's place in the routing counts */
bool bound = false;
bool want = false;
int g = 0;
uint32_t seq = 0;
};
/* A request: the group's mailbox the plan writes, and the mark the DMA list waits for. */
struct XpReq {
int g = 0;
uint32_t seq = 0;
void* mark = nullptr;
RadStream ms = nullptr; /* the stream the mark rides */
bool valid = false;
};
struct XpState {
int device = 0;
RadStream stream = nullptr; /* logits and plan, behind rides on the compute stream */
RadEvent tail = nullptr; /* the pass start waits for the stream's work of the last */
RadEvent sync = nullptr; /* the router input's readiness, where a ride is refused */
bool tail_live = false;
char* ring = nullptr; /* uncached: kXpGroups x kXpSlots slots of `slot` bytes */
uint64_t slot = 0;
XpPools pools{};
XpRec* rec = nullptr; /* [kXpGroups][kXpSlots] */
int32_t* nrec = nullptr; /* [kXpGroups] */
XpBox* box = nullptr; /* [kXpGroups], pinned host */
uint32_t* done = nullptr; /* [kXpGroups], pinned host: the last request whose copies landed */
XpStats* stats = nullptr; /* device */
XpStats* stats_h = nullptr; /* pinned host, read at the end */
float* logits = nullptr; /* [kXpGroups][kXpMaxRows][kXpMaxNe] */
void** maps = nullptr; /* [layers][kXpMaxNe][kXpParts] */
int32_t* places = nullptr; /* [layers][kXpMaxNe] */
std::vector<XpLayer> layers;
uint32_t seq[kXpGroups] = {};
int last_layer = -1; /* the last layer predicted for: a lower one starts a pass */
/* WHETHER IT PAYS: the share of its copies the steps use, judged every kXpWindow predictions from
* the counters (stats_h, one window on their way to the host); under kXpMinUse it rests. */
int64_t passes = 0, rest_until = 0, rests = 0;
int64_t calls = 0;
uint32_t snap_copied = 0, snap_routed = 0;
bool have_snap = false, judge = false;
int restore_g = -1; /* the group the next step puts back */
XpReq pend; /* made at a router, waiting for its mark */
/* The host thread: each mailbox, once the plan has written it, to the DMA queue. */
std::thread thr;
std::mutex mu;
std::condition_variable cv;
std::deque<XpReq> q;
std::atomic<bool> stop{false};
std::deque<std::pair<void*, int64_t>> marks; /* thread only: a mark and the list that polls it */
int64_t lists = 0; /* thread only: lists handed over */
std::atomic<int64_t> dropped{0}; /* requests the queue was too far behind for */
};
} /* namespace rad */
+439
View File
@@ -0,0 +1,439 @@
/* xprefetch.cpp -- the expert prefetch's host half: Ctx::xp_*. See xprefetch.h for what it does. */
#include "ctx.h"
#include "xp_state.h"
#include "rad_internal.h"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <immintrin.h>
#if !(defined(RAD_HAVE_HIP) && RAD_HAVE_HIP)
/* A build without HIP has no kernels to launch: rad_xp_supported is 0 there, so nothing calls these. */
extern "C" int rad_xp_logits_launch(const uint16_t*, const uint16_t*, float*, uint32_t, uint32_t, uint32_t, void*) {
return -1;
}
extern "C" int rad_xp_plan_launch(const float*, uint32_t, uint32_t, uint32_t, void** const*, const int32_t*,
const int32_t*, rad::XpPools, uint64_t, uint64_t, rad::XpRec*, int32_t*,
rad::XpBox*, uint32_t, rad::XpStats*, void*) {
return -1;
}
extern "C" int rad_xp_step_launch(const rad::XpRec*, const int32_t*, const rad::XpRec*, const int32_t*,
const uint32_t*, uint32_t, void*) {
return -1;
}
#endif
namespace rad {
namespace {
/* A pool class wider than this holds whole tables (the token embedding read in place), not experts. */
constexpr uint64_t kXpMaxUnit = (uint64_t)64 << 20;
/* Lists the queue may be behind before a request is dropped. Nothing waits for these lists, so
* nothing slows a queue that falls behind but this: its copies could not land in time anyway, and a
* queue that only grows would end up polling marks that have long gone back to the pool. */
constexpr int64_t kXpBehind = 3;
/* Dispatches past a dropped request's mark before the signal can be made again: far more than the
* pass that completes it. */
constexpr int64_t kXpMarkHold = 4096;
/* WHETHER IT PAYS. A copy the step uses saves the link time of reading that expert under the GEMM;
* one it does not use costs link time the GEMMs wanted, and the prediction costs a little whatever
* comes of it. Measured on Qwen3.8-Flash-Next, the two balance near a quarter of the copies used: at
* --tp 1 the steps used half of them and the decode step was 3.6% faster, at --tp 2 -- where each card
* keeps most experts and its pool holds the ones the steps rarely route -- a sixth, and it was 4-6%
* slower. So every kXpWindow predictions the prefetch looks at the share of its copies used over the
* last window, and under kXpMinUse it rests for kXpRest passes -- no prediction, no copy -- and then
* measures again. */
constexpr int64_t kXpWindow = 2048;
constexpr double kXpMinUse = 0.30;
constexpr uint32_t kXpMinJudged = 512;
constexpr int64_t kXpRest = 8192;
} // namespace
void Ctx::xp_free(XpState& x) {
if (x.stream) rad_stream_sync(x.stream);
if (x.ring) rad_dev_free_uncached(x.ring);
for (void* p : {(void*)x.rec, (void*)x.nrec, (void*)x.stats, (void*)x.logits, (void*)x.maps,
(void*)x.places})
if (p) rad_dev_free(p, RAD_MEM_DEVICE);
for (void* p : {(void*)x.box, (void*)x.done, (void*)x.stats_h})
if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
if (x.tail) rad_event_destroy(x.tail);
if (x.sync) rad_event_destroy(x.sync);
if (x.stream) rad_stream_destroy(x.stream);
}
/* At bringup, once the placement has made its pinned pools: everything the prefetch needs, or nothing
* and a line saying why it is off. */
void Ctx::xp_open(const uint64_t* lo, const uint64_t* hi, const uint64_t* stride, int n) {
if (xp_ || device_is_host() || route_.empty()) return;
if (!rad_xp_supported(device_)) {
RAD_INFO("rank %d: expert prefetch off: the device backend has no DMA engine to spare for it",
rank_);
return;
}
auto x = std::make_unique<XpState>();
x->device = device_;
for (int i = 0; i < n && x->pools.n < kXpMaxPools; ++i) {
if (stride[i] == 0 || stride[i] > kXpMaxUnit || hi[i] <= lo[i]) continue;
x->pools.lo[x->pools.n] = lo[i];
x->pools.hi[x->pools.n] = hi[i];
x->pools.stride[x->pools.n] = stride[i];
x->slot = std::max(x->slot, stride[i]);
++x->pools.n;
}
if (x->pools.n == 0) return;
const int64_t nl = (int64_t)route_.size();
const int64_t ring = (int64_t)(kXpGroups * kXpSlots * x->slot);
if (rad_dev_set(device_) < 0) return;
x->ring = (char*)rad_dev_alloc_uncached(ring);
x->rec = (XpRec*)rad_dev_alloc((int64_t)sizeof(XpRec) * kXpGroups * kXpSlots, RAD_MEM_DEVICE);
x->nrec = (int32_t*)rad_dev_alloc(4 * kXpGroups, RAD_MEM_DEVICE);
x->stats = (XpStats*)rad_dev_alloc((int64_t)sizeof(XpStats), RAD_MEM_DEVICE);
x->logits = (float*)rad_dev_alloc(4 * (int64_t)kXpGroups * kXpMaxRows * kXpMaxNe, RAD_MEM_DEVICE);
x->maps = (void**)rad_dev_alloc(nl * kXpMaxNe * kXpParts * (int64_t)sizeof(void*), RAD_MEM_DEVICE);
x->places = (int32_t*)rad_dev_alloc(nl * kXpMaxNe * 4, RAD_MEM_DEVICE);
x->box = (XpBox*)rad_dev_alloc((int64_t)sizeof(XpBox) * kXpGroups, RAD_MEM_HOST_PINNED);
x->done = (uint32_t*)rad_dev_alloc(4 * kXpGroups, RAD_MEM_HOST_PINNED);
x->stats_h = (XpStats*)rad_dev_alloc((int64_t)sizeof(XpStats), RAD_MEM_HOST_PINNED);
const bool ok = x->ring && x->rec && x->nrec && x->stats && x->logits && x->maps && x->places && x->box &&
x->done && x->stats_h && rad_xp_stream_create(&x->stream) >= 0 &&
rad_event_create_local(&x->tail) >= 0 && rad_event_create_local(&x->sync) >= 0 &&
rad_memset_async(x->nrec, 0, 4 * kXpGroups, stream_) >= 0 &&
rad_memset_async(x->stats, 0, sizeof(XpStats), stream_) >= 0 && rad_stream_sync(stream_) >= 0;
if (!ok) {
const char* why = rad_dev_last_error();
RAD_WARN("rank %d: expert prefetch off: %s", rank_, why && *why ? why : "no memory for it");
xp_free(*x);
return;
}
std::memset((void*)x->box, 0, sizeof(XpBox) * kXpGroups);
std::memset(x->done, 0, 4 * kXpGroups);
x->layers.resize((size_t)nl);
XpState* xs = x.get();
x->thr = std::thread([this, xs] { xp_serve(*xs); });
RAD_INFO("rank %d: expert prefetch on: %d copies a routed layer by DMA, ring %s", rank_, kXpSlots,
humanb(ring).c_str());
xp_ = std::move(x);
}
void Ctx::xp_close() {
if (!xp_) return;
XpState& x = *xp_;
/* NOTHING MAY READ OR WRITE THE RING WHEN IT GOES: the compute work issued so far can read it
* through entries still pointed at it, and the queue's lists write it until they finish. */
if (stream_) rad_stream_sync(stream_);
if (lane1_) rad_stream_sync(lane1_);
{
std::lock_guard<std::mutex> lk(x.mu);
x.stop = true;
}
x.cv.notify_all();
if (x.thr.joinable()) x.thr.join();
const auto t0 = std::chrono::steady_clock::now();
while (rad_xp_behind(x.device) > 0) {
if (std::chrono::steady_clock::now() - t0 > std::chrono::seconds(5)) {
RAD_WARN("rank %d: the prefetch DMA queue still has %lld lists after 5 s; its ring is freed anyway",
rank_, (long long)rad_xp_behind(x.device));
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
/* What it came to: copies planned, and of the restored ones how many the step routed. */
if (x.stream && rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0 &&
rad_stream_sync(x.stream) >= 0 && x.stats_h->planned)
RAD_INFO("rank %d: expert prefetch: %u copies planned, %u of %u looked back on routed (%.1f%%), %lld "
"requests dropped behind a slow queue, %lld rests", rank_, x.stats_h->planned, x.stats_h->routed,
x.stats_h->copied, x.stats_h->copied ? 100.0 * x.stats_h->routed / x.stats_h->copied : 0.0,
(long long)x.dropped.load(), (long long)x.rests);
xp_free(x);
xp_.reset();
}
/* The host thread: each request's mailbox, once the plan has written it, to the DMA queue. */
void Ctx::xp_serve(XpState& x) {
for (;;) {
XpReq r;
{
std::unique_lock<std::mutex> lk(x.mu);
x.cv.wait(lk, [&] { return x.stop.load() || !x.q.empty(); });
if (x.stop) return;
r = x.q.front();
x.q.pop_front();
}
/* The marks of finished lists go back to the pool. */
const int64_t behind = rad_xp_behind(x.device);
while (!x.marks.empty() && x.marks.front().second <= x.lists - behind) {
rad_ride_release(x.marks.front().first, nullptr, 0);
x.marks.pop_front();
}
/* The mailbox reaches the request's number once the plan has run; a number past it means it
* was written over by a later request and this one is stale. */
volatile XpBox* b = x.box + r.g;
const auto t0 = std::chrono::steady_clock::now();
bool got = true;
while ((int32_t)(b->seq - r.seq) < 0) {
_mm_pause();
if (x.stop || std::chrono::steady_clock::now() - t0 > std::chrono::seconds(5)) {
got = false;
break;
}
}
if (got && b->seq != r.seq) got = false;
std::atomic_thread_fence(std::memory_order_acquire);
uint64_t src[kXpSlots], dst[kXpSlots], bytes[kXpSlots];
int n = 0;
if (got) {
n = std::min<int>((int)b->n, kXpSlots);
for (int i = 0; i < n && got; ++i) {
/* A job seen before its own stores landed carries an older tag. */
const auto t1 = std::chrono::steady_clock::now();
while (b->jobs[i].tag != r.seq &&
std::chrono::steady_clock::now() - t1 < std::chrono::milliseconds(100))
_mm_pause();
if (b->jobs[i].tag != r.seq) { got = false; break; }
std::atomic_thread_fence(std::memory_order_acquire);
src[i] = b->jobs[i].src;
dst[i] = b->jobs[i].dst;
bytes[i] = b->jobs[i].bytes;
}
}
if (!got || n == 0 || behind > kXpBehind) {
if (got && n > 0) ++x.dropped;
if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold);
continue;
}
if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq) == RAD_OK) {
++x.lists;
if (r.mark) x.marks.emplace_back(r.mark, x.lists);
} else {
if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold);
RAD_WARN("rank %d: the prefetch DMA queue refused a list", rank_);
}
}
}
/* The layer's map from expert to table entries, once all its tables are bound; false until then. An
* expert whose weights are not each in exactly one table stays out of the map. */
bool Ctx::xp_bind(XpLayer& L, int layer) {
const RadPrefetchNext& nx = L.next;
std::vector<void**> hm((size_t)kXpMaxNe * kXpParts, nullptr);
std::vector<int32_t> hp((size_t)kXpMaxNe, -1);
for (int64_t e = 0; e < nx.n_expert; ++e) {
void** ent[kXpParts] = {};
bool usable = true;
for (int64_t k = 0; k < nx.n_parts && usable; ++k) {
const rad_weight w = nx.parts[e * nx.n_parts + k];
if (!w) continue;
if ((size_t)w >= wmemb_head_.size() || wmemb_head_[w] < 0) { usable = false; break; }
const WMemb& m = wmemb_[(size_t)wmemb_head_[w]];
if (m.next >= 0) { usable = false; break; }
const WeightTable& t = wtabs_[(size_t)m.slot];
if (!t.dev) return false;
ent[k] = (void**)t.dev + m.entry;
}
if (usable)
for (int k = 0; k < kXpParts; ++k) hm[(size_t)(e * kXpParts + k)] = ent[k];
hp[(size_t)e] = nx.count_at ? nx.count_at[e] : (int32_t)e;
}
XpState& x = *xp_;
void** map = x.maps + (size_t)layer * kXpMaxNe * kXpParts;
int32_t* place = x.places + (size_t)layer * kXpMaxNe;
/* Once a layer, at its first issue: the one host wait here is not on the step path. */
if (rad_memcpy_async(map, hm.data(), (int64_t)hm.size() * (int64_t)sizeof(void*), stream_) < 0 ||
rad_memcpy_async(place, hp.data(), (int64_t)hp.size() * 4, stream_) < 0 || rad_stream_sync(stream_) < 0)
return false;
L.map = map;
L.place = place;
L.bound = true;
return true;
}
/* The counters the last judgement sent to the host are a window old: the share of copies used is
* judged from them, then the next window's are sent. A window that follows a rest is not judged --
* its counters left before the rest -- so a rest is followed by one full window measured afresh. */
void Ctx::xp_judge(XpState& x) {
if (x.have_snap) {
const volatile XpStats* h = x.stats_h;
const uint32_t copied = h->copied, routed = h->routed;
const uint32_t dc = copied - x.snap_copied, dr = routed - x.snap_routed;
x.snap_copied = copied;
x.snap_routed = routed;
if (x.judge && dc >= kXpMinJudged && (double)dr < kXpMinUse * (double)dc) {
x.rest_until = x.passes + kXpRest;
x.judge = false;
if (x.rests++ == 0)
RAD_INFO("rank %d: expert prefetch resting: the steps used %.0f%% of its last %u copies, under the "
"%.0f%% that pays for them; it measures again every %lld passes", rank_,
100.0 * dr / dc, dc, 100.0 * kXpMinUse, (long long)kXpRest);
} else {
x.judge = true;
}
}
if (rad_memcpy_async(x.stats_h, x.stats, sizeof(XpStats), x.stream) >= 0) x.have_snap = true;
}
/* A pass being recorded keeps each of the three calls as a step of its own, run again where the tape
* plays it: what a call issues -- on its own stream, or a ride on the next played dispatch -- is
* issued again at every play rather than recorded. */
int Ctx::xp_predict(const RadPrefetchNext* nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
/* A pass this wide predicts nothing, and its tape is better without a step that does nothing. */
if (!xp_ || !nx || rows <= 0 || rows > kXpMaxRows) return RAD_OK;
if (!rec_) return xp_predict_run(*nx, h, r0, rows, n_embd);
tape_cut();
TapeXp p;
p.next = *nx;
p.h = h;
p.r0 = r0;
p.rows = rows;
p.n_embd = n_embd;
TapeStep st;
st.kind = kTapeXp;
st.lane = (uint8_t)lane_;
st.a = (int32_t)rec_->xp.size();
rec_->xp.push_back(p);
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_predict_run(*nx, h, r0, rows, n_embd);
tape_pause(false);
return rc;
}
int Ctx::xp_mark() {
if (!xp_) return RAD_OK;
if (!rec_) return xp_mark_run();
tape_cut();
TapeStep st;
st.kind = kTapeXpMark;
st.lane = (uint8_t)lane_;
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_mark_run();
tape_pause(false);
return rc;
}
int Ctx::xp_step(int layer) {
if (!xp_) return RAD_OK;
if (!rec_) return xp_step_run(layer);
tape_cut();
TapeStep st;
st.kind = kTapeXpStep;
st.lane = (uint8_t)lane_;
st.a = layer;
rec_->steps.push_back(st);
tape_pause(true);
const int rc = xp_step_run(layer);
tape_pause(false);
return rc;
}
int Ctx::xp_predict_run(const RadPrefetchNext& nx, rad_buf h, int64_t r0, int64_t rows, int64_t n_embd) {
XpState& x = *xp_;
const int layer = nx.layer;
if (rows <= 0 || rows > kXpMaxRows || nx.top_k <= 0 || nx.top_k > kXpMaxK || nx.n_expert <= 0 ||
nx.n_expert > kXpMaxNe || nx.n_parts <= 0 || nx.n_parts > kXpParts || !nx.parts || n_embd % 256 ||
n_embd > 4096 || layer < 0 || layer >= (int)x.layers.size())
return RAD_OK;
XpLayer& L = x.layers[(size_t)layer];
if (!L.bound) {
L.next = nx;
if (!xp_bind(L, layer)) return RAD_OK;
}
const void* w = weight_ptr(nx.router);
const char* hb = (const char*)buf_ptr(h);
if (!w || !hb) return RAD_OK;
const RadStream cs = cur_stream();
/* A NEW PASS waits for the prefetch stream's work of the last one, so that stream is never a pass
* behind the compute stream: the records and mailboxes a request reuses are three layers old. */
if (layer <= x.last_layer) {
if (x.tail_live) {
RAD_TRY(rad_event_record(x.tail, x.stream));
RAD_TRY(rad_event_wait(cs, x.tail));
x.tail_live = false;
}
++x.passes;
}
x.last_layer = layer;
if (x.passes < x.rest_until) return RAD_OK;
/* THE ROUTER INPUT IS READ IN PLACE, behind the next dispatch on the compute stream -- the router,
* which reads it -- by a ride rather than a barrier packet between two kernels. */
void* rt = nullptr;
if (rad_ride(cs, &rt) == RAD_OK) {
RAD_TRY(rad_ride_wait(x.stream, rt));
} else {
RAD_TRY(rad_event_record(x.sync, cs));
RAD_TRY(rad_event_wait(x.stream, x.sync));
}
/* An earlier request still waiting for its mark goes now, unmarked. */
if (x.pend.valid) {
{
std::lock_guard<std::mutex> lk(x.mu);
x.q.push_back(x.pend);
}
x.cv.notify_one();
x.pend.valid = false;
}
const int g = layer % kXpGroups;
const uint32_t seq = ++x.seq[g];
const uint16_t* hg = (const uint16_t*)(hb + r0 * n_embd * 2);
float* lg = x.logits + (size_t)g * kXpMaxRows * kXpMaxNe;
const int32_t* cnt = route_n_expert_ > 0 && nx.n_expert <= route_n_expert_
? route_dev_ + (int64_t)layer * route_n_expert_ : nullptr;
const uint64_t ring = (uint64_t)(uintptr_t)(x.ring + (size_t)g * kXpSlots * x.slot);
if (rad_xp_logits_launch(hg, (const uint16_t*)w, lg, (uint32_t)rows, (uint32_t)n_embd, (uint32_t)nx.n_expert,
(void*)x.stream) ||
rad_xp_plan_launch(lg, (uint32_t)rows, (uint32_t)nx.n_expert, (uint32_t)nx.top_k, (void** const*)L.map,
L.place, cnt, x.pools, ring, x.slot, x.rec + (size_t)g * kXpSlots, x.nrec + g,
(XpBox*)rad_dev_device_ptr(x.box + g), seq, x.stats, (void*)x.stream))
return RAD_E_DEVICE;
x.tail_live = true;
if (++x.calls % kXpWindow == 0) xp_judge(x);
x.pend.g = g;
x.pend.seq = seq;
x.pend.mark = nullptr;
x.pend.ms = nullptr;
x.pend.valid = true;
L.want = true;
L.g = g;
L.seq = seq;
return RAD_OK;
}
int Ctx::xp_mark_run() {
XpState& x = *xp_;
if (!x.pend.valid) return RAD_OK;
/* Refused only while another ride waits on the stream: the list then starts without one. */
void* mark = nullptr;
if (rad_ride(cur_stream(), &mark) == RAD_OK) {
x.pend.mark = mark;
x.pend.ms = cur_stream();
}
{
std::lock_guard<std::mutex> lk(x.mu);
x.q.push_back(x.pend);
}
x.cv.notify_one();
x.pend.valid = false;
return RAD_OK;
}
int Ctx::xp_step_run(int layer) {
XpState& x = *xp_;
XpLayer* L = layer >= 0 && (size_t)layer < x.layers.size() ? &x.layers[(size_t)layer] : nullptr;
const bool patch = L && L->want;
if (!patch && x.restore_g < 0) return RAD_OK;
const XpRec* rrec = x.restore_g >= 0 ? x.rec + (size_t)x.restore_g * kXpSlots : nullptr;
const int32_t* rn = x.restore_g >= 0 ? x.nrec + x.restore_g : nullptr;
const XpRec* prec = patch ? x.rec + (size_t)L->g * kXpSlots : nullptr;
const int32_t* pn = patch ? x.nrec + L->g : nullptr;
const uint32_t* done = patch ? (const uint32_t*)rad_dev_device_ptr(x.done + L->g) : nullptr;
if (rad_xp_step_launch(rrec, rn, prec, pn, done, patch ? L->seq : 0, (void*)cur_stream())) return RAD_E_DEVICE;
x.restore_g = patch ? L->g : -1;
if (L) L->want = false;
return RAD_OK;
}
} /* namespace rad */
+93
View File
@@ -0,0 +1,93 @@
/* xprefetch.h -- the next-layer expert prefetch at decode: what the host half (xprefetch.cpp) and the
* kernels (xprefetch.hip) share.
*
* WHAT IT DOES. Under expert-tiered placement a routed layer's GEMMs read the experts that are not on
* the card from the pinned host pool, across the link, while they run. A layer's router input predicts
* the NEXT routed layer's choice well: that layer's router applied to it ranks the experts the next
* layer will route. So at each routed layer the prefetch applies the next layer's router to this
* layer's router input, takes the likeliest experts that sit in the pinned pool, copies them onto the
* card with the DMA engine while the rest of this layer runs, and points the next layer's weight tables
* at the copies just before its GEMMs. The GEMMs then read those experts from the card.
*
* NOTHING IT DOES CHANGES A RESULT. A copy holds the bytes of the pool slot it was made from, and an
* entry is pointed at it only where it still names that slot (a compare-and-swap: a heat-engine move
* since then wins) and only once the copy has landed. Late copies are not used; nothing waits for them.
*
* THE PIECES, per routed layer l predicting layer l+1:
* - at l's router input (Ctx::xp_predict): on a stream of its own, behind the compute stream's
* dispatch that reads the input (a ride), xp_logits applies l+1's router to the input rows and
* xp_plan picks the copies and writes them to a mailbox in pinned host memory;
* - after l's routed down GEMM (Ctx::xp_mark): a ride on the compute stream that the DMA list polls,
* so the copies cross the link under l+1's attention rather than under l's own streamed experts;
* - a host thread hands each mailbox to the card's prefetch DMA queue: wait for the mark, copy, then
* write the request's number to the group's done word;
* - ahead of l+1's routed GEMMs (Ctx::xp_step, on the compute stream): xp_step puts the previous
* layer's entries back (its GEMMs are behind it in the stream) and points l+1's at the copies if
* the done word says they have landed.
* The ring holds kXpGroups layers' copies, kXpSlots each; a group is copied into again three layers
* later, after the step that put its entries back. */
#pragma once
#include <cstdint>
namespace rad {
constexpr int kXpSlots = 2; /* copies a layer: the link fits about two units between the marks */
constexpr int kXpGroups = 3;
constexpr int kXpMaxRows = 16; /* decode passes; a wider pass makes no prediction */
constexpr int kXpMaxK = 16;
constexpr int kXpMaxNe = 512;
constexpr int kXpMaxPools = 4;
constexpr int kXpParts = 4; /* the weights one expert's unit is made of */
/* One copied unit: its table entries, what they held and what they hold while patched, and where the
* layer's routing counts say whether the step used it. */
struct XpRec {
void** ent[kXpParts];
void* oldv[kXpParts];
void* newv[kXpParts];
const int32_t* cnt;
int32_t place;
int32_t pad;
};
struct XpJob {
uint64_t src, dst, bytes, tag; /* tag: the request's number, written after the rest */
};
/* A group's mailbox, in pinned host memory: xp_plan writes the jobs, then `seq`. */
struct XpBox {
XpJob jobs[kXpSlots];
int32_t n;
volatile uint32_t seq;
};
struct XpPools {
uint64_t lo[kXpMaxPools], hi[kXpMaxPools], stride[kXpMaxPools];
int32_t n;
};
/* Restored records: [0] units copied, [1] of them the step routed; [2] units planned. */
struct XpStats {
unsigned int copied, routed, planned, pad;
};
/* What the prefetch takes on the card for a model of `layers` routed layers whose largest expert unit
* is `unit` bytes: the ring and the buffers beside it (Ctx::xp_open allocates exactly these), in the
* 2 MiB grains the card's allocations come in -- the ring its own, the small buffers sharing theirs. */
inline int64_t xp_device_bytes(int64_t unit, int64_t layers) {
constexpr int64_t kGrain = (int64_t)2 << 20;
auto grains = [](int64_t b) { return (b + kGrain - 1) / kGrain * kGrain; };
const int64_t ring = (int64_t)kXpGroups * kXpSlots * unit;
const int64_t small = (int64_t)sizeof(XpRec) * kXpGroups * kXpSlots + 4 * kXpGroups + (int64_t)sizeof(XpStats) +
4 * (int64_t)kXpGroups * kXpMaxRows * kXpMaxNe + layers * kXpMaxNe * kXpParts * 8 +
layers * kXpMaxNe * 4;
return grains(ring) + grains(small);
}
} /* namespace rad */
extern "C" int rad_xp_logits_launch(const uint16_t* h, const uint16_t* w, float* logits, uint32_t rows,
uint32_t n_embd, uint32_t ne, void* stream);
extern "C" int rad_xp_plan_launch(const float* logits, uint32_t rows, uint32_t ne, uint32_t k,
void** const* map, const int32_t* place, const int32_t* cnt,
rad::XpPools pools, uint64_t ring, uint64_t ring_stride, rad::XpRec* rec,
int32_t* nrec, rad::XpBox* box, uint32_t seq, rad::XpStats* stats,
void* stream);
extern "C" int rad_xp_step_launch(const rad::XpRec* rrec, const int32_t* rn, const rad::XpRec* prec,
const int32_t* pn, const uint32_t* done, uint32_t seq, void* stream);
+314
View File
@@ -0,0 +1,314 @@
/* xprefetch.hip -- the expert prefetch's kernels. See xprefetch.h. */
#include <hip/hip_runtime.h>
#include <math.h>
#include "xprefetch.h"
namespace {
__device__ __forceinline__ float xp_bf(uint32_t x) { return __uint_as_float(x << 16); }
/* logits[r, e] = h[r, :] . w[e, :], h and w bf16. A block takes 16 experts, two a 32-lane group. Every
* lane issues all of its weight loads first -- n_embd / 256 sixteen-byte loads an expert, kept in
* registers -- so the kernel waits on memory once rather than once a K chunk; the rows are staged in
* LDS in as few chunks as 40 KiB allows (one at sixteen rows of 2560 needs two). fp32 accumulation.
* Requires n_embd % 256 == 0 and n_embd <= 4096 (rad_xp_logits_launch checks). WIDE ON PURPOSE: the
* router input is read in place and the block overwrites it once its GEMMs are done, so a narrower
* grid that waits longer for CUs beside the compute stream reads it too late and predicts badly. */
constexpr uint32_t kLgE = 16, kLgJ = 16, kLgLds = 40u << 10;
/* For gfx9-4-generic, one of rad_core's portable targets, LLVM leaves the row loop inside the
* unrolled K loop a loop and warns once a copy; every other target unrolls it. The warning is
* silenced for this kernel only, which changes no code. */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpass-failed"
__global__ __launch_bounds__(256) void xp_logits(const uint16_t* __restrict__ h,
const uint16_t* __restrict__ w, float* __restrict__ lg,
uint32_t rows, uint32_t n_embd, uint32_t ne) {
__shared__ uint4 s_h[kLgLds / 16];
const uint32_t lane = threadIdx.x % 32u, grp = threadIdx.x / 32u;
const uint32_t e0 = blockIdx.x * kLgE + grp * 2u;
const uint32_t J = n_embd / 256u;
uint4 wv[2][kLgJ];
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (uint32_t j = 0; j < kLgJ; ++j)
if (j < J && e0 + a < ne) wv[a][j] = ((const uint4*)(w + (size_t)(e0 + a) * n_embd))[j * 32u + lane];
float acc[2][rad::kXpMaxRows];
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (int r = 0; r < rad::kXpMaxRows; ++r) acc[a][r] = 0.f;
/* A chunk is a whole number of 32-unit columns (one j) for every row. */
const uint32_t jc = max(1u, min(J, (kLgLds / 16u) / (rows * 32u)));
for (uint32_t j0 = 0; j0 < J; j0 += jc) {
const uint32_t j1 = min(J, j0 + jc), w32 = (j1 - j0) * 32u;
__syncthreads();
for (uint32_t i = threadIdx.x; i < rows * w32; i += blockDim.x) {
const uint32_t r = i / w32, c = i % w32;
s_h[r * w32 + c] = ((const uint4*)(h + (size_t)r * n_embd))[j0 * 32u + c];
}
__syncthreads();
#pragma unroll
for (uint32_t j = 0; j < kLgJ; ++j) {
if (j < j0 || j >= j1) continue;
float wf[2][8];
#pragma unroll
for (int a = 0; a < 2; ++a) {
const uint32_t x[4] = { wv[a][j].x, wv[a][j].y, wv[a][j].z, wv[a][j].w };
#pragma unroll
for (int t = 0; t < 4; ++t) { wf[a][2 * t] = xp_bf(x[t] & 0xffffu); wf[a][2 * t + 1] = xp_bf(x[t] >> 16); }
}
#pragma unroll
for (int r = 0; r < rad::kXpMaxRows; ++r) {
if ((uint32_t)r >= rows) break;
const uint4 hv = s_h[r * w32 + (j - j0) * 32u + lane];
const uint32_t y[4] = { hv.x, hv.y, hv.z, hv.w };
float hf[8];
#pragma unroll
for (int t = 0; t < 4; ++t) { hf[2 * t] = xp_bf(y[t] & 0xffffu); hf[2 * t + 1] = xp_bf(y[t] >> 16); }
#pragma unroll
for (int a = 0; a < 2; ++a) {
float d = 0.f;
#pragma unroll
for (int t = 0; t < 8; ++t) d += wf[a][t] * hf[t];
acc[a][r] += d;
}
}
}
}
#pragma unroll
for (int a = 0; a < 2; ++a) {
const uint32_t e = e0 + (uint32_t)a;
/* No unroll pragma: the exit at `rows` keeps this a loop, and the compiler refuses one. */
for (int r = 0; r < rad::kXpMaxRows; ++r) {
if ((uint32_t)r >= rows) break;
float v = acc[a][r];
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor(v, o, 32);
if (lane == 0 && e < ne) lg[(size_t)r * ne + e] = v;
}
}
}
#pragma clang diagnostic pop
/* One block. Count what the group's previous records came to (whether the step routed them), take each
* row's top-k with its softmax probability, keep the distinct experts whose entries all sit in one
* pinned pool slot, score each by its highest probability -- half as much again where the previous
* pass routed it at this layer -- and write the kXpSlots best into the ring's group as jobs, then the
* mailbox's number. The previous records' entries are back already: xp_step puts them back. */
constexpr float kXpPrevBoost = 0.5f;
__global__ __launch_bounds__(256) void xp_plan(const float* __restrict__ lg, uint32_t rows, uint32_t ne,
uint32_t k, void** const* __restrict__ map,
const int32_t* __restrict__ place,
const int32_t* __restrict__ cnt, rad::XpPools pools,
uint64_t ring, uint64_t rs, rad::XpRec* rec, int32_t* nrec,
rad::XpBox* box, uint32_t seq, rad::XpStats* stats) {
constexpr int NC = rad::kXpMaxRows * rad::kXpMaxK;
__shared__ int s_e[NC];
__shared__ float s_pr[NC];
__shared__ int s_pool[NC];
__shared__ uint64_t s_p[NC];
__shared__ float s_sc[NC]; /* the candidate's score, or -1 */
__shared__ int s_sel[rad::kXpSlots];
__shared__ int s_n;
const uint32_t tid = threadIdx.x, lane = tid % warpSize, wave = tid / warpSize;
const uint32_t nw = blockDim.x / warpSize;
if (tid == 0) {
const int nr = *nrec;
for (int t = 0; t < nr; ++t) {
const rad::XpRec& rc = rec[t];
atomicAdd(&stats->copied, 1u);
if (rc.cnt && rc.place >= 0 && rc.cnt[rc.place] > 0) atomicAdd(&stats->routed, 1u);
}
}
/* Rank-major order: o = j * rows + r, every row's first choice before any second one. */
for (uint32_t r = wave; r < rows; r += nw) {
float v[16];
float m = -INFINITY;
#pragma unroll
for (uint32_t i = 0; i < 16; ++i) {
const uint32_t e = lane + i * warpSize;
v[i] = e < ne ? lg[(size_t)r * ne + e] : -INFINITY;
m = fmaxf(m, v[i]);
}
for (int o = warpSize / 2; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor(m, o));
float sum = 0.f;
#pragma unroll
for (uint32_t i = 0; i < 16; ++i) sum += v[i] > -INFINITY ? __expf(v[i] - m) : 0.f;
for (int o = warpSize / 2; o > 0; o >>= 1) sum += __shfl_xor(sum, o);
for (uint32_t j = 0; j < k; ++j) {
float bv = -INFINITY;
int bi = -1;
#pragma unroll
for (int i = 0; i < 16; ++i)
if (v[i] > bv) { bv = v[i]; bi = i; }
const int be = bi >= 0 ? (int)(lane + (uint32_t)bi * warpSize) : 0x7fffffff;
float rv = bv;
int re = be;
for (int o = warpSize / 2; o > 0; o >>= 1) {
const float ov = __shfl_xor(rv, o);
const int oe = __shfl_xor(re, o);
if (ov > rv || (ov == rv && oe < re)) { rv = ov; re = oe; }
}
if (lane == 0) {
s_e[j * rows + r] = re;
s_pr[j * rows + r] = __expf(rv - m) / sum;
}
#pragma unroll
for (int i = 0; i < 16; ++i)
if (i == bi && re == be) v[i] = -INFINITY;
}
}
__syncthreads();
const uint32_t nc = rows * k;
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const int e = s_e[o];
s_pool[o] = -1;
s_p[o] = 0;
if (e >= 0 && (uint32_t)e < ne) {
void** ent = map[(size_t)e * rad::kXpParts];
if (ent) {
const uint64_t p = (uint64_t)*(void* volatile*)ent;
s_p[o] = p;
int pi = -1;
for (int i = 0; i < pools.n; ++i)
if (p >= pools.lo[i] && p < pools.hi[i]) { pi = i; break; }
/* Every entry of the unit in the same pool slot: the mover patches a layer's tables
* one at a time, and a unit caught between two of its patches is left alone. */
if (pi >= 0) {
const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
const uint64_t base = lo + ((p - lo) / st) * st;
for (int q = 1; q < rad::kXpParts && pi >= 0; ++q) {
void** eq = map[(size_t)e * rad::kXpParts + q];
if (!eq) continue;
const uint64_t v = (uint64_t)*(void* volatile*)eq;
if (v < base || v >= base + st) pi = -1;
}
}
s_pool[o] = pi;
}
}
}
__syncthreads();
/* The first occurrence of an expert carries its highest probability; the rest drop out. */
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const int e = s_e[o];
float best = s_pr[o];
bool first = true;
for (uint32_t u = 0; u < nc; ++u)
if (s_e[u] == e) {
if (u < o) first = false;
best = fmaxf(best, s_pr[u]);
}
/* The previous pass routed it here: the counts row still holds that pass until this layer's
* router runs. */
if (first && cnt && place && e >= 0 && (uint32_t)e < ne) {
const int pl = place[e];
if (pl >= 0 && cnt[pl] > 0) best *= 1.f + kXpPrevBoost;
}
s_sc[o] = (first && s_pool[o] >= 0) ? best : -1.f;
}
if (tid == 0) s_n = 0;
__syncthreads();
for (uint32_t o = tid; o < nc; o += blockDim.x) {
const float sc = s_sc[o];
if (sc < 0.f) continue;
uint32_t rank = 0;
for (uint32_t u = 0; u < nc; ++u) {
const float su = s_sc[u];
if (su > sc || (su == sc && u < o)) ++rank;
}
if (rank < (uint32_t)rad::kXpSlots) { s_sel[rank] = (int)o; atomicAdd(&s_n, 1); }
}
__syncthreads();
const int n = s_n;
for (int t = (int)tid; t < n * rad::kXpParts; t += (int)blockDim.x) {
const int j = t / rad::kXpParts, q = t % rad::kXpParts, o = s_sel[j], e = s_e[o], pi = s_pool[o];
const uint64_t lo = pools.lo[pi], st = pools.stride[pi];
const uint64_t base = lo + ((s_p[o] - lo) / st) * st;
const uint64_t dst = ring + (uint64_t)j * rs;
if (q == 0) {
/* System-scope stores write through to host memory themselves, so the tag needs only their
* completion, not a writeback of the whole L2 -- which would take the compute stream's dirty
* lines with it, every layer. */
__hip_atomic_store(&box->jobs[j].src, base, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
__hip_atomic_store(&box->jobs[j].dst, dst, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
__hip_atomic_store(&box->jobs[j].bytes, st, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
rec[j].cnt = cnt;
rec[j].place = place ? place[e] : -1;
}
void** ent = map[(size_t)e * rad::kXpParts + q];
rec[j].ent[q] = ent;
if (ent) {
const uint64_t old = (uint64_t)*(void* volatile*)ent;
rec[j].oldv[q] = (void*)old;
rec[j].newv[q] = (void*)(dst + (old - base));
}
/* The tag after the job's own stores have completed: a tag the host sees vouches for them. */
if (q == 0) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__hip_atomic_store(&box->jobs[j].tag, (uint64_t)seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
}
__syncthreads();
if (tid == 0) {
*nrec = n;
__hip_atomic_store(&box->n, n, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
atomicAdd(&stats->planned, (unsigned)n);
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__hip_atomic_store((uint32_t*)&box->seq, seq, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
}
/* On the compute stream ahead of a layer's routed GEMMs. The previous layer's patches go back -- its
* GEMMs are behind this in the stream -- then this layer's units point at the ring, only where an entry
* still holds what the plan read (a heat-engine move since wins) and only if the copies have landed:
* the list's last write before its number puts the request's number in `done`. */
__global__ __launch_bounds__(128) void xp_step(const rad::XpRec* __restrict__ rrec, const int32_t* __restrict__ rn,
const rad::XpRec* __restrict__ prec, const int32_t* __restrict__ pn,
const uint32_t* done, uint32_t seq) {
const int t = (int)threadIdx.x;
if (rrec && t < *rn * rad::kXpParts) {
const rad::XpRec& r = rrec[t / rad::kXpParts];
const int q = t % rad::kXpParts;
if (r.ent[q])
atomicCAS((unsigned long long*)r.ent[q], (unsigned long long)r.newv[q], (unsigned long long)r.oldv[q]);
}
if (!prec) return;
if (__hip_atomic_load((uint32_t*)done, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) != seq) return;
if (t >= *pn * rad::kXpParts) return;
const rad::XpRec& r = prec[t / rad::kXpParts];
const int q = t % rad::kXpParts;
if (r.ent[q])
atomicCAS((unsigned long long*)r.ent[q], (unsigned long long)r.oldv[q], (unsigned long long)r.newv[q]);
}
} // namespace
extern "C" int rad_xp_logits_launch(const uint16_t* h, const uint16_t* w, float* logits, uint32_t rows,
uint32_t n_embd, uint32_t ne, void* stream) {
if (rows == 0 || rows > (uint32_t)rad::kXpMaxRows || n_embd % 256u || n_embd > 256u * kLgJ) return -1;
hipLaunchKernelGGL(xp_logits, dim3((ne + kLgE - 1) / kLgE), dim3(256), 0, (hipStream_t)stream, h, w,
logits, rows, n_embd, ne);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_xp_plan_launch(const float* logits, uint32_t rows, uint32_t ne, uint32_t k,
void** const* map, const int32_t* place, const int32_t* cnt,
rad::XpPools pools, uint64_t ring, uint64_t ring_stride, rad::XpRec* rec,
int32_t* nrec, rad::XpBox* box, uint32_t seq, rad::XpStats* stats,
void* stream) {
if (k == 0 || k > (uint32_t)rad::kXpMaxK || ne > (uint32_t)rad::kXpMaxNe) return -1;
hipLaunchKernelGGL(xp_plan, dim3(1), dim3(256), 0, (hipStream_t)stream, logits, rows, ne, k, map, place,
cnt, pools, ring, ring_stride, rec, nrec, box, seq, stats);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_xp_step_launch(const rad::XpRec* rrec, const int32_t* rn, const rad::XpRec* prec,
const int32_t* pn, const uint32_t* done, uint32_t seq, void* stream) {
hipLaunchKernelGGL(xp_step, dim3(1), dim3(128), 0, (hipStream_t)stream, rrec, rn, prec, pn, done, seq);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
+1
View File
@@ -221,6 +221,7 @@ public:
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; }
const SamplerConfig& config() const { return cfg_; }
/* 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. */
+13 -9
View File
@@ -1287,24 +1287,29 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
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 (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) {
RAD_ERR("encoder pass: segments [%d, %d) of an item of %d", p.seg0, p.seg0 + p.n_seg,
it.n_seg);
return nullptr;
}
const int64_t np = it.patch_at(p.seg0 + p.n_seg) - it.patch_at(p.seg0);
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) {
n_seg + p.n_seg > max_segs) {
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.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,
it.pixels.data() + it.patch_at(p.seg0) * enc_dim,
(size_t)(np * enc_dim) * sizeof(uint16_t));
n_patch += np;
for (int32_t q = 0; q < p.n_seg; ++q) {
for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) {
const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q);
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
++n_seg;
if (seg_p > max_seg) max_seg = seg_p;
}
if (seg_p > max_seg) max_seg = seg_p;
}
/* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */
{
@@ -1312,10 +1317,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
int64_t at = 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;
const int64_t np = it.patch_at(p.seg0 + p.n_seg) - it.patch_at(p.seg0);
tmp.resize((size_t)(4 * np));
it.coords((int64_t)p.seg0 * seg_p, np, tmp.data());
it.coords(it.patch_at(p.seg0), np, tmp.data());
for (int c = 0; c < 4; ++c)
std::memcpy(enc_coord_host_ + c * n_patch + at, tmp.data() + c * np,
(size_t)np * sizeof(int32_t));
+35 -6
View File
@@ -180,6 +180,14 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
/* 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;
/* A SCORED PROMPT names real vocabulary rows, and one step's decision is all it needs:
* drafts would be proposed for a continuation nobody reads. */
if (r->token_scores) {
if (r->embed || r->token_scores->tokens.empty()) return RAD_E_INVAL;
for (int32_t t : r->token_scores->tokens)
if (t < 0 || t >= prog_->meta.n_vocab) return RAD_E_INVAL;
r->may_speculate = false;
}
/* 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. */
@@ -708,7 +716,7 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const {
* second clamp is a no-op on it. Reversing them would round a chunk PAST the checkpoint down and
* then miss the boundary, which is the exact failure this is written to avoid. */
int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
int64_t* checkpoint_pos) const {
int64_t* checkpoint_pos, int64_t keep_at) const {
if (checkpoint_pos) *checkpoint_pos = -1;
int64_t remaining = n_target - n_computed;
if (remaining <= 0 || budget <= 0) return 0;
@@ -735,6 +743,13 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
if (checkpoint_pos) *checkpoint_pos = tail;
}
}
/* AND ONE WHERE THE REQUEST ASKED (Request::checkpoint_at), on its quantum: the end of a
* prefix other requests are about to start from. Same split as the interval's. */
const int64_t keep = keep_at / geo_.quantum * geo_.quantum;
if (keep > n_computed && keep <= n_computed + want && keep <= n_target) {
want = keep - n_computed;
if (checkpoint_pos) *checkpoint_pos = keep;
}
}
if (want < remaining) {
@@ -998,8 +1013,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* for nothing; the hit above is known by now, so the cap is on what really has to run. */
const int64_t cap = r.embed ? budget /* whole input or nothing: never held back (below) */
: busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt);
if (cap < budget && want > 0) admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr);
int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
if (cap < budget && want > 0)
admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
/* 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;
@@ -1149,9 +1165,10 @@ const RadBatch* Scheduler::step() {
const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
/*rows_only=*/shares == 0);
want = plan_chunk(r.n_computed, target, cap, &ckpt);
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
if (cap < budget && want > 0 && capped_at < 0) {
const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr);
const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr,
r.checkpoint_at);
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
}
/* A PREFILL WITH NO ROOM LEFT DOES NOT STOP THE WALK. Under a quantum of budget it can
@@ -1411,7 +1428,7 @@ const RadBatch* Scheduler::step() {
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
int64_t ckpt = -1;
const int64_t grown = e.ckpt_slot < 0 && limit > had
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt) : had;
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had;
if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) {
e.n_tokens = (int32_t)grown;
e.produces_token = (r.n_computed + grown >= s.seq_len());
@@ -1557,6 +1574,18 @@ const RadBatch* Scheduler::step() {
}
/* ------------------------------------------------------------------ media */
bool Scheduler::prefill_continues() const {
std::lock_guard<std::mutex> lk(mu_);
if (stage_rows_ <= 0) return false;
for (const StepEntry& e : plan_.e) {
if (!e.is_prefill || e.slot < 0 || (size_t)e.slot >= reqs_.size() || !reqs_[(size_t)e.slot])
continue;
const int64_t left = reqs_[(size_t)e.slot]->seq_len() - ((int64_t)e.ctx_len + e.n_tokens);
if (left >= stage_rows_) return true;
}
return false;
}
bool Scheduler::media_ready(SchedReq& s) {
bool ready = true;
for (mm::Placed& p : s.req->media->items) {
+7 -3
View File
@@ -457,18 +457,22 @@ public:
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). */
/* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */
bool last_checkpoint(int64_t pos, int64_t target) const;
int64_t tail_checkpoint(int64_t target) const;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
int64_t* checkpoint_pos) const;
int64_t* checkpoint_pos, int64_t keep_at = 0) const;
/* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS, in tokens (0 = no stager), set once by the
* engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it; see
* busy_cap. Also where the resolved policy is stated at startup. */
void set_stage_rows(int64_t rows);
/* Whether the step just planned leaves a prompt with at least the stager's smallest pass still
* to prefill, so the next step most likely carries a chunk the stager arms for. */
bool prefill_continues() const;
/* Visible for tests: the most a prefill chunk at `n_computed` of a `n_target`-token sequence
* may take of `budget` when `reserve` tokens of other work are still to be planned in the step
* and `shared` says rows are already planned ahead of it. Returns `budget` when
+71
View File
@@ -0,0 +1,71 @@
LFM Open License v1.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
"Licensor" shall mean Liquid AI, Inc.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
"Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
"Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
"Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Commercial Use Limitation.
(a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
(b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
(c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
END OF TERMS AND CONDITIONS
+2 -1
View File
@@ -733,7 +733,8 @@ public:
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
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_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels)
: p_->video(bytes.data(), bytes.size(), out, why);
}
+26
View File
@@ -534,6 +534,32 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /diagnostics */
/* The startup report, read again for this request (ServerOptions::diagnostics_json). Behind the
* bearer key like /server_info: it names the machine's devices and boot parameters.
*
* AND WITHOUT A KEY, ONLY TO THIS MACHINE. /server_info without a key describes the model a
* client is already talking to; this describes the host -- its kernel, its boot parameters, its
* PCI layout, its memory limits -- which a server bound to 0.0.0.0 with no key would otherwise
* hand to anyone who can reach the port. A key is the operator's statement of who may ask. */
HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
if (!opt_.diagnostics_json)
return error_response(err_not_implemented(
"the server was not given a diagnostics provider; this build has no engine attached"),
req.peer);
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
ApiError e;
e.status = 403;
e.type = "permission_error";
e.message = "/diagnostics describes this machine, and a server started without --api-key "
"answers it only to a client on the same machine (a loopback address); start "
"it with --api-key to read it from elsewhere";
return error_response(e, req.peer);
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, opt_.diagnostics_json());
}
/* ================================================================== /reset_prefix_cache */
/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an
* empty body whether or not anything happened, so a benchmark that thinks it started cold has no
+1
View File
@@ -313,6 +313,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
e["staged_units"] = s.experts.staged_units;
e["staged_bytes"] = (double)s.experts.staged_bytes;
e["stage_overflow"] = s.experts.stage_overflow;
e["stage_copies"] = s.experts.stage_copies;
o["experts"] = std::move(e);
}
+24 -2
View File
@@ -5,6 +5,9 @@
* translation unit so that nothing above the transport seam pays for it. */
#include "cpp-httplib/httplib.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <algorithm>
#include <atomic>
#include <cctype>
@@ -37,6 +40,26 @@ std::string HttpRequest::param(const std::string& k, const std::string& def) con
return q == query.end() ? def : q->second;
}
bool HttpRequest::peer_is_loopback() const {
if (peer.empty()) return true;
/* "addr:port", where an IPv6 address carries colons of its own: the port is after the last. */
const size_t colon = peer.rfind(':');
std::string addr = colon == std::string::npos ? peer : peer.substr(0, colon);
if (addr.size() >= 2 && addr.front() == '[' && addr.back() == ']')
addr = addr.substr(1, addr.size() - 2);
in_addr v4{};
if (inet_pton(AF_INET, addr.c_str(), &v4) == 1) return (ntohl(v4.s_addr) >> 24) == 127;
in6_addr v6{};
if (inet_pton(AF_INET6, addr.c_str(), &v6) != 1) return false;
if (IN6_IS_ADDR_LOOPBACK(&v6)) return true;
return IN6_IS_ADDR_V4MAPPED(&v6) && v6.s6_addr[12] == 127;
}
int idle_workers(int n_threads) {
const int n = n_threads > 0 ? n_threads : (int)std::thread::hardware_concurrency();
return std::max(n, 4);
}
HttpResponse HttpResponse::json_body(int status, std::string body) {
HttpResponse r;
r.status = status;
@@ -326,8 +349,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
svr.set_keep_alive_timeout(o.keep_alive_timeout_s);
svr.set_payload_max_length(o.max_body_bytes);
int nt = o.n_threads > 0 ? o.n_threads : (int)std::thread::hardware_concurrency();
if (nt < 4) nt = 4;
const int nt = idle_workers(o.n_threads);
const size_t most = (size_t)std::max<int64_t>(o.max_threads, nt);
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
+8
View File
@@ -41,6 +41,9 @@ struct HttpRequest {
std::string header(const std::string& k, const std::string& def = "") const;
std::string param(const std::string& k, const std::string& def = "") const;
bool peer_gone() const { return closed && closed(); }
/* True when the peer is this machine: 127.0.0.0/8, ::1, or either written as an IPv4-mapped
* IPv6 address -- and for a request made in-process, which has no peer. */
bool peer_is_loopback() const;
};
struct HttpResponse {
@@ -129,6 +132,11 @@ struct TransportOptions {
bool cors = true;
};
/* The workers the pool keeps while idle for TransportOptions::n_threads: that many, one a
* hardware thread for 0, and never fewer than 4. One definition, so the number the startup
* report states is the number the transport runs. */
int idle_workers(int n_threads);
class HttpTransport {
public:
HttpTransport();
+3
View File
@@ -583,6 +583,9 @@ 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;
/* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides
* truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */
int64_t max_pixels = 0;
};
class IMultimodal {
+3 -1
View File
@@ -89,8 +89,10 @@ struct ExpertPlane {
int64_t routed = 0, routed_resident = 0;
int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0;
/* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes
* copied onto the card, and pooled units a buffer had no room for. */
* copied onto the card, pooled units a buffer had no room for, and the copies that carried
* the units. */
int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
int64_t stage_copies = 0;
/* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache
* lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says
* whether the boundary between the two pools is moving, and whether what was lent is being
+5 -5
View File
@@ -1190,8 +1190,8 @@ static const char* const MEDIA_MARKER = RAD_MEDIA_MARKER;
* arbitrary http(s) URL on a caller's behalf turns the inference server into an SSRF proxy with
* network access to everything the deployment can reach, and no amount of allowlisting makes
* that a good default. */
static int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err) {
int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err) {
if (url.rfind("data:", 0) != 0) {
*err = err_bad(field, "only data: URLs are accepted; the server does not fetch remote URLs "
"on a request's behalf");
@@ -1462,9 +1462,9 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits
* Each media part is processed HERE, on the request's own worker, because decoding a video and
* resizing its frames is the most expensive host work a request can bring: it must not reach the
* scheduler's thread, where every other request's step would wait on it. */
static int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err) {
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err) {
out->text = rendered;
auto pm = std::make_shared<mm::PromptMedia>();
const std::string marker = MEDIA_MARKER;
+8
View File
@@ -291,6 +291,14 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
* 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, bool native = false);
/* A media part's bytes out of a data: URL; any other URL is refused, never fetched. */
int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err);
/* A prompt holding RAD_MEDIA_MARKER once a media part, tokenised with each marker replaced by its
* part's processed token run; `media` is consumed in order. */
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
const MediaOpts& opts, PromptInput* out, ApiError* err);
/* 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);
+155
View File
@@ -2,6 +2,7 @@
#include <cstdio>
#include "json_partial.h"
#include "systemone.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
@@ -136,6 +137,7 @@ void Server::register_routes() {
router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); });
router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); });
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); });
/* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the
@@ -175,6 +177,7 @@ void Server::register_routes() {
router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); });
router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); });
router_.get ("/props", [this](const HttpRequest& q) { return handle_props(q); });
router_.get ("/diagnostics", [this](const HttpRequest& q) { return handle_diagnostics(q); });
router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); });
router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); });
@@ -1723,6 +1726,158 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
return HttpResponse::json_body(200, embeddings_body(r, vecs, u));
}
/* /v1/systemone (systemone.h): one request a question, each reading its answer's candidates at
* the prompt's last position (Request::token_scores) and sampling one token nobody reads.
*
* SEVERAL QUESTIONS SHARE THE STATE THEY ARE ASKED OVER, and it is read once. The first question
* runs alone and leaves the state at the end of that shared head in the prefix cache -- its
* attention blocks, and a checkpoint of the convolutions there (Request::checkpoint_at) -- and the
* rest are submitted together once it has finished, each starting from that head and computing
* only its own tail. d1's own runner shares the head the same way, as one batched tree. */
HttpResponse Server::handle_systemone(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (opt_.decision_type != "d1")
return error_response(err_not_implemented(
"/v1/systemone serves a decision model; this container does not declare one "
"(convert d1 with --set decision.type=d1)"), req.peer);
DecisionRequest r;
ApiError err;
if (parse_decision_request(req.body, odeps_, lim_, opt_.model_id, &r, &err) < 0)
return error_response(err, req.peer);
sweep_abandoned();
const int n = (int)r.questions.size();
if (!admit(n)) {
metrics_.observe_rejected();
return error_response(err_overloaded(
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
"s. The server refuses rather than queueing without bound"), req.peer);
}
RAD_INFO("systemone admitted%s questions=%d prompt=%lld tok", from_peer(req.peer).c_str(), n,
(long long)r.input_tokens);
std::vector<Generation> gens;
std::vector<Request> rqs;
std::vector<std::shared_ptr<TokenScores>> scores;
for (int i = 0; i < n; ++i) {
Generation g;
g.index = i;
g.sink = std::make_shared<Sink>(16);
auto ts = std::make_shared<TokenScores>();
ts->tokens = r.questions[(size_t)i].candidates;
Request rq;
rq.prompt = r.questions[(size_t)i].tokens;
rq.media = r.media;
rq.token_scores = ts;
rq.max_tokens = 1;
rq.sp.temp = 0.0f;
rq.sink = g.sink.get();
if (i == 0 && n > 1) rq.checkpoint_at = r.trunk;
rqs.push_back(std::move(rq));
gens.push_back(std::move(g));
scores.push_back(std::move(ts));
}
/* The questions handed to the scheduler so far: an early exit retires those and drops the
* rest, whose sinks nothing will ever finish. */
size_t submitted = 0;
auto fail = [&](const std::string& why) {
gens.resize(submitted);
retire(gens);
release(n);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return error_response(e, req.peer);
};
/* Questions [first, last) submitted together and waited for. A non-null response is the
* call's answer already: the scheduler refused one, the client left, or the server stops. */
std::unique_ptr<HttpResponse> early;
auto run = [&](int first, int last) {
std::vector<Request> part(std::make_move_iterator(rqs.begin() + first),
std::make_move_iterator(rqs.begin() + last));
std::vector<uint64_t> ids;
deps_.sched->submit_all(part, &ids);
submitted = (size_t)last;
for (size_t k = 0; k < ids.size(); ++k) {
Generation& g = gens[(size_t)first + k];
g.id = ids[k];
g.sink->id = ids[k];
if (!ids[k]) {
early = std::make_unique<HttpResponse>(
fail("the scheduler refused question " + r.questions[(size_t)first + k].name));
return;
}
}
for (;;) {
bool all = true;
for (int i = first; i < last; ++i) {
Generation& g = gens[(size_t)i];
if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); }
all = all && g.closed;
}
if (all) return;
if (req.peer_gone()) {
gens.resize(submitted);
cancel_all(gens, true);
retire(gens);
release(n);
metrics_.observe_http(499);
early = std::make_unique<HttpResponse>(
HttpResponse::text(499, "client closed request\n"));
return;
}
if (stopping_.load()) {
gens.resize(submitted);
cancel_all(gens, false);
retire(gens);
release(n);
early = std::make_unique<HttpResponse>(
error_response(err_overloaded("the server is shutting down"), req.peer));
return;
}
for (int i = first; i < last; ++i)
if (!gens[(size_t)i].closed) { gens[(size_t)i].sink->wait(); break; }
}
};
run(0, 1);
if (early) return std::move(*early);
/* A first question that failed fails the call; the rest would only repeat it. */
if (gens[0].finish == Finish::Error || gens[0].finish == Finish::Cancelled)
return fail(gens[0].finish == Finish::Error ? engine_failure(*gens[0].sink)
: "the engine cancelled question " +
r.questions[0].name);
if (n > 1) {
run(1, n);
if (early) return std::move(*early);
}
json answers = json::object();
for (size_t i = 0; i < gens.size(); ++i) {
const Generation& g = gens[i];
if (g.finish == Finish::Error || g.finish == Finish::Cancelled)
return fail(g.finish == Finish::Error ? engine_failure(*g.sink)
: "the engine cancelled question " +
r.questions[i].name);
json a;
if (decision_answer(r.questions[i], scores[i]->logits, &a, &err) < 0) {
retire(gens);
release(n);
return error_response(err, req.peer);
}
answers[r.questions[i].name] = std::move(a);
}
retire(gens);
release(n);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
}
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
if (!id.empty() && id != opt_.model_id) {
+14
View File
@@ -57,6 +57,9 @@ struct ServerOptions {
* /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;
/* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`:
* "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
/* 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. */
@@ -121,6 +124,13 @@ struct ServerOptions {
* showing an op as unissued one step before it flips. Registry::select is asked with
* record = false and mutates nothing else. */
std::function<std::string()> graph_json;
/* THE STARTUP REPORT READ AGAIN, as JSON (core/diag/diag.h): the options in force, the machine
* as it is now (the provider may reuse a reading for a second), and what on it costs speed.
* Without a key it is answered to loopback clients only (Server::handle_diagnostics). A
* provider like the graph's, because a card's link speed and clock only say anything under
* load -- a request made during a long prefill is how a link parked below its maximum is told
* from one at rest. */
std::function<std::string()> diagnostics_json;
std::string api_key;
bool cors = true;
@@ -171,6 +181,8 @@ public:
int port() const { return transport_.port(); } /* 0 until run() is accepting */
int64_t in_flight() const { return in_flight_.load(std::memory_order_relaxed); }
/* The admission ceiling as resolved: ServerOptions::queue_depth, or 8 x max_seqs for 0. */
int64_t queue_cap() const { return queue_depth_; }
private:
struct Generation;
@@ -185,6 +197,7 @@ private:
HttpResponse handle_chat(const HttpRequest& req);
HttpResponse handle_completion(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);
@@ -213,6 +226,7 @@ private:
HttpResponse handle_detokenize(const HttpRequest& req);
HttpResponse handle_tokenizer_info(const HttpRequest& req);
HttpResponse handle_server_info(const HttpRequest& req);
HttpResponse handle_diagnostics(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. */
+404
View File
@@ -0,0 +1,404 @@
/* systemone.cpp -- d1's prompt and readout (systemone.h).
*
* EVERY STRING BELOW IS d1's OWN, from prompt.py in the model's repository: the user turn, the
* state block, the three question blocks, the option codes and their fallback codebook, the
* yes/no spellings. The model was trained on exactly these, so a reworded instruction or a
* different code for an option is a different (and worse-calibrated) question.
*
* THAT TEXT IS LIQUID AI'S, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE):
* this file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
* strings kept as they are.
*
* AND SO IS THE TOKENISATION SPLIT. d1 tokenises a single question's prompt as one text, and a
* request with several as the shared head (the state and the pictures) followed by each question's
* tail, tokenised separately -- its runner reads the head once and branches. The two are not the
* same ids where BPE would merge across the join, so each case is tokenised the way the model's
* own runner does.
*/
#include "systemone.h"
#include "llama/src/unicode.h"
#include "mm/processor.h"
#include <nlohmann/json.hpp>
#include <cmath>
#include <limits>
#include <unordered_set>
namespace rad {
namespace server {
namespace {
const char* const kImStart = "<|im_start|>";
const char* const kImEnd = "<|im_end|>";
bool only_keys(const json& o, std::initializer_list<const char*> allowed, const std::string& path,
ApiError* err) {
for (const auto& kv : o.items()) {
bool ok = false;
for (const char* k : allowed) ok = ok || kv.key() == k;
if (!ok) {
*err = err_unsupported(path + kv.key(), "not a field of a System One request");
return false;
}
}
return true;
}
/* The one id `text` encodes to, or -1 when it is not a single token. */
int32_t one_token(const ITokenizer& tok, const std::string& text) {
const std::vector<int32_t> ids = tok.encode(text, false, true);
return ids.size() == 1 ? ids[0] : -1;
}
/* An answer's spellings: the distinct single-token ones among `texts` (prompt.py, _ids). */
void add_answer(DecisionQuestion* q, const ITokenizer& tok, const std::vector<std::string>& texts) {
std::vector<size_t> group;
for (const std::string& t : texts) {
const int32_t id = one_token(tok, t);
if (id < 0) continue;
size_t at = 0;
while (at < q->candidates.size() && q->candidates[at] != id) ++at;
if (at == q->candidates.size()) q->candidates.push_back(id);
bool have = false;
for (size_t g : group) have = have || g == at;
if (!have) group.push_back(at);
}
q->groups.push_back(std::move(group));
}
/* Python's str.strip() and str.isalpha() over one stripped label. */
std::string strip(const std::string& s) {
const std::vector<uint32_t> c = unicode_cpts_from_utf8(s);
size_t a = 0, b = c.size();
while (a < b && unicode_cpt_flags_from_cpt(c[a]).is_whitespace) ++a;
while (b > a && unicode_cpt_flags_from_cpt(c[b - 1]).is_whitespace) --b;
std::string out;
for (size_t i = a; i < b; ++i) out += unicode_cpt_to_utf8(c[i]);
return out;
}
bool one_letter(const std::string& s) {
const std::vector<uint32_t> c = unicode_cpts_from_utf8(s);
return c.size() == 1 && unicode_cpt_flags_from_cpt(c[0]).is_letter;
}
std::string two_digits(size_t i) { return (i < 10 ? "0" : "") + std::to_string(i); }
/* prompt.py, option_codes: the labels themselves when every one is a single letter, else A..Z,
* else 00, 01, ... */
std::vector<std::string> option_codes(const std::vector<std::string>& labels) {
std::vector<std::string> codes;
bool letters = !labels.empty();
for (const std::string& l : labels) letters = letters && one_letter(strip(l));
for (size_t i = 0; i < labels.size(); ++i)
codes.push_back(letters ? strip(labels[i])
: labels.size() <= 26 ? std::string(1, (char)('A' + i)) : two_digits(i));
return codes;
}
/* prompt.py, _FALLBACK_POOL: where a code is not one token of its own, or is already taken. */
const std::vector<std::string>& fallback_pool() {
static const std::vector<std::string> pool = [] {
std::vector<std::string> v;
for (char c = 'A'; c <= 'Z'; ++c) v.emplace_back(1, c);
for (size_t i = 0; i < 100; ++i) v.push_back(two_digits(i));
for (char c = 'a'; c <= 'z'; ++c) v.emplace_back(1, c);
for (size_t i = 0; i < 200; ++i) v.push_back("#" + std::to_string(i));
for (char a = 'A'; a <= 'Z'; ++a)
for (char b = 'A'; b <= 'Z'; ++b) v.push_back(std::string{ a, b });
return v;
}();
return pool;
}
/* A string criterion, or null (Python's None, which a question block writes as "None"). */
bool text_or_null(const json& v, const std::string& path, ApiError* err) {
if (v.is_string() || v.is_null()) return true;
*err = err_bad(path, "must be a string or null");
return false;
}
std::string py_str(const json& v) { return v.is_null() ? "None" : v.get<std::string>(); }
/* One question: its block (prompt.py, question_block), the assistant header behind it, and the
* ids its answers are read at (readout_ids). */
int parse_question(const std::string& name, const json& src, const ITokenizer& tok,
DecisionQuestion* q, std::string* suffix, ApiError* err) {
const std::string path = "questions." + name;
auto bad = [&](const std::string& field, const std::string& why) {
*err = err_bad(path + field, why);
return RAD_E_INVAL;
};
if (!src.is_object()) return bad("", "must be an object");
if (!only_keys(src, { "type", "instructions", "criteria" }, path + ".", err)) return RAD_E_INVAL;
auto it = src.find("instructions");
if (it == src.end() || !it->is_string()) return bad(".instructions", "must be a string");
const std::string instructions = it->get<std::string>();
auto ty = src.find("type");
if (ty != src.end() && !ty->is_string()) return bad(".type", "must be noul, choice or score");
q->name = name;
q->type = ty == src.end() ? "choice" : ty->get<std::string>(); /* prompt.py's default */
const json criteria = src.contains("criteria") ? src.at("criteria") : json();
std::string block;
if (q->type == "noul") {
if (!criteria.is_null() && !criteria.is_object())
return bad(".criteria", "must be an object with `true` and `false`, or absent");
if (criteria.is_object()) {
if (!only_keys(criteria, { "true", "false" }, path + ".criteria.", err)) return RAD_E_INVAL;
for (const auto& kv : criteria.items())
if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL;
}
block = instructions;
if (criteria.is_object() && !criteria.empty())
block += "\nYes: " + py_str(criteria.value("true", json())) +
"\nNo: " + py_str(criteria.value("false", json()));
block += "\n\nReply with yes or no only.";
q->labels = { "true", "false" };
add_answer(q, tok, { "yes", "Yes", "YES" });
add_answer(q, tok, { "no", "No", "NO" });
if (q->groups[0].empty() || q->groups[1].empty()) {
*err = err_not_implemented("this vocabulary has no single-token yes or no");
return RAD_E_UNSUPPORTED;
}
} else if (q->type == "choice") {
if (!criteria.is_object() || criteria.empty())
return bad(".criteria", "must be a non-empty object of option names to descriptions");
std::vector<std::string> descs;
for (const auto& kv : criteria.items()) {
if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL;
q->labels.push_back(kv.key());
std::string d = kv.value().is_null() ? std::string() : kv.value().get<std::string>();
if (d.empty()) { /* `desc or label.replace("_", " ")` */
d = kv.key();
for (char& c : d) if (c == '_') c = ' ';
}
descs.push_back(std::move(d));
}
/* prompt.py, aliases: each option's code if it is one token nobody has, else the first
* fallback that is. Then readout_ids: the code, and " code" where that is one token. */
std::unordered_set<int32_t> used;
block = instructions + "\n\nOptions:\n";
const std::vector<std::string> codes = option_codes(q->labels);
for (size_t i = 0; i < codes.size(); ++i) {
std::string code;
int32_t id = one_token(tok, codes[i]);
if (id >= 0 && !used.count(id)) code = codes[i];
else {
id = -1;
for (const std::string& f : fallback_pool()) {
const int32_t t = one_token(tok, f);
if (t >= 0 && !used.count(t)) { id = t; code = f; break; }
}
}
if (id < 0) return bad(".criteria", "more options than this vocabulary has distinct "
"single-token codes for");
used.insert(id);
if (i) block += "\n";
block += code + " " + descs[i];
add_answer(q, tok, { code, " " + code });
}
block += "\n\nReply with the option code only.";
} else if (q->type == "score") {
if (!criteria.is_array() || criteria.size() < 2 || criteria.size() > 10)
return bad(".criteria", "must be an array of 2 to 10 level descriptions, lowest first");
block = instructions + "\n\n";
for (size_t i = 0; i < criteria.size(); ++i) {
if (!criteria[i].is_string()) return bad(".criteria", "each level must be a string");
q->labels.push_back(std::to_string(i));
q->legend.push_back(criteria[i].get<std::string>());
if (i) block += "\n";
block += q->labels.back() + " " + q->legend.back();
add_answer(q, tok, { q->labels.back() });
if (q->groups.back().empty()) {
*err = err_not_implemented("this vocabulary has no single-token digit " +
q->labels.back());
return RAD_E_UNSUPPORTED;
}
}
block += "\n\nReply with a single digit 0-" + std::to_string(criteria.size() - 1) + " only.";
} else {
return bad(".type", "must be noul, choice or score");
}
*suffix = block + kImEnd + "\n" + kImStart + "assistant\n";
return RAD_OK;
}
/* prompt.py, state_block at its default style: a string as it is, anything else as indented JSON
* in the order the request gave its keys. */
std::string state_block(const json& state) {
return (state.is_string() ? state.get<std::string>() : state.dump(2)) + "\n\n";
}
} /* namespace */
int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, DecisionRequest* out, ApiError* err) {
*out = DecisionRequest{};
json b;
RAD_TRY(parse_request_object(body, lim, &b, err));
if (!only_keys(b, { "model", "state", "questions", "images" }, "", err)) return RAD_E_INVAL;
if (b.contains("model") && (!b["model"].is_string() || b["model"] != model_id)) {
*err = err_bad("model", "must name the loaded model, " + model_id);
return RAD_E_INVAL;
}
if (!b.contains("state")) {
*err = err_bad("state", "required: a string, any JSON value, or null with images");
return RAD_E_INVAL;
}
const json& qs = b.contains("questions") ? b["questions"] : json();
if (!qs.is_object() || qs.empty()) {
*err = err_bad("questions", "must be a non-empty object of named questions");
return RAD_E_INVAL;
}
/* THE PICTURES, decoded here and processed when the head is tokenised. */
std::vector<std::pair<MediaKind, std::vector<uint8_t>>> media;
if (b.contains("images")) {
const json& im = b["images"];
if (!im.is_array()) { *err = err_bad("images", "must be an array of data: URLs"); return RAD_E_INVAL; }
if (!im.empty() && (!d.mm || !d.mm->accepts(MediaKind::Image))) {
*err = err_not_implemented("images need the model's image encoder, and this deployment "
"has none loaded");
return RAD_E_UNSUPPORTED;
}
for (size_t i = 0; i < im.size(); ++i) {
const std::string field = "images[" + std::to_string(i) + "]";
if (!im[i].is_string()) { *err = err_bad(field, "must be a data: URL"); return RAD_E_INVAL; }
std::vector<uint8_t> bytes;
RAD_TRY(decode_media_url(im[i].get<std::string>(), field, &bytes, err));
media.push_back({ MediaKind::Image, std::move(bytes) });
}
}
/* prompt.py, prefix_text: BOS, the user turn, the pictures as the chat template writes them
* (one marker each, which the processor expands), then the state. A null state leaves the
* question right behind the pictures. */
const std::string marker = RAD_MEDIA_MARKER;
std::string head;
if (d.tok->bos() >= 0) head += d.tok->token_bytes(d.tok->bos());
head += std::string(kImStart) + "user\n";
for (size_t i = 0; i < media.size(); ++i) head += marker;
std::string body_text;
if (!b["state"].is_null()) body_text = state_block(b["state"]) + "\nQUESTION:\n";
if (body_text.find(marker) != std::string::npos) {
*err = err_bad("state", "contains \"" + marker + "\", which this server reserves");
return RAD_E_INVAL;
}
head += body_text;
std::vector<std::string> suffixes;
for (const auto& kv : qs.items()) {
DecisionQuestion q;
std::string suffix;
RAD_TRY(parse_question(kv.key(), kv.value(), *d.tok, &q, &suffix, err));
if (!media.empty() && suffix.find(marker) != std::string::npos) {
*err = err_bad("questions." + kv.key(), "contains \"" + marker + "\", which this "
"server reserves");
return RAD_E_INVAL;
}
out->questions.push_back(std::move(q));
suffixes.push_back(std::move(suffix));
}
/* runner.py, VISION_MAX_PIXELS: d1 bounds every picture at 1024 x 1024 pixels' area before
* its processor, so a larger one is a different input unless it is bounded here too. */
MediaOpts opts;
opts.max_pixels = 1024 * 1024;
auto tokenize = [&](const std::string& text, std::vector<int32_t>* ids) -> int {
if (media.empty()) { *ids = d.tok->encode(text, false, true); return RAD_OK; }
PromptInput in;
RAD_TRY(tokenize_with_media(text, d, media, opts, &in, err));
*ids = std::move(in.tokens);
out->media = std::move(in.media);
return RAD_OK;
};
if (out->questions.size() == 1) {
RAD_TRY(tokenize(head + suffixes[0], &out->questions[0].tokens));
out->input_tokens = (int64_t)out->questions[0].tokens.size();
} else {
std::vector<int32_t> trunk;
RAD_TRY(tokenize(head, &trunk));
out->trunk = (int32_t)trunk.size();
out->input_tokens = (int64_t)trunk.size();
for (size_t i = 0; i < out->questions.size(); ++i) {
std::vector<int32_t>& t = out->questions[i].tokens;
const std::vector<int32_t> tail = d.tok->encode(suffixes[i], false, true);
t = trunk;
t.insert(t.end(), tail.begin(), tail.end());
out->input_tokens += (int64_t)tail.size();
}
}
/* One position stays free: the request samples a token, which nobody reads. */
for (const DecisionQuestion& q : out->questions)
if (lim.max_ctx > 0 && (int64_t)q.tokens.size() >= lim.max_ctx) {
ApiError e = err_bad("questions." + q.name,
"the prompt is " + std::to_string(q.tokens.size()) +
" tokens; this deployment's context holds " +
std::to_string(lim.max_ctx - 1) + " for a decision");
e.code = "context_length_exceeded";
*err = e;
return RAD_E_INVAL;
}
return RAD_OK;
}
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
ApiError* err) {
if (logits.size() != q.candidates.size() || q.groups.size() != q.labels.size()) {
*err = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "the engine returned no scores for question " + q.name;
return RAD_E_STATE;
}
std::vector<double> p;
for (const std::vector<size_t>& g : q.groups) {
double best = -std::numeric_limits<double>::infinity();
for (size_t i : g) best = std::max(best, (double)logits[i]);
if (!std::isfinite(best)) {
*err = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "question " + q.name + " scored a non-finite logit";
return RAD_E_STATE;
}
p.push_back(best);
}
const double peak = *std::max_element(p.begin(), p.end());
double total = 0.0;
for (double& v : p) total += (v = std::exp(v - peak));
for (double& v : p) v /= total;
/* api.py, answer. */
json a = json::object();
a["type"] = q.type;
if (q.type == "noul") {
a["noul"] = p[0];
*out = std::move(a);
return RAD_OK;
}
const size_t best = (size_t)(std::max_element(p.begin(), p.end()) - p.begin());
json probs = json::object();
for (size_t i = 0; i < p.size(); ++i) probs[q.labels[i]] = p[i];
if (q.type == "choice") {
a["choice"] = q.labels[best];
} else {
double expected = 0.0;
for (size_t i = 0; i < p.size(); ++i) expected += (double)i * p[i];
a["score"] = expected;
}
a["confidence"] = p[best];
a["probabilities"] = std::move(probs);
if (q.type == "score") {
json legend = json::object();
for (size_t i = 0; i < q.legend.size(); ++i) legend[q.labels[i]] = q.legend[i];
a["legend"] = std::move(legend);
}
*out = std::move(a);
return RAD_OK;
}
} /* namespace server */
} /* namespace rad */
+59
View File
@@ -0,0 +1,59 @@
/* systemone.h -- POST /v1/systemone: LiquidAI d1's decisions, a distribution read off one position.
*
* d1 is a decision model. It is given a state (text, any JSON value, pictures, or a mix) and named
* questions, and each answer is a softmax over a handful of tokens at the position right after the
* assistant header: `yes` / `no` for a noul, one code a option for a choice, a digit a level for a
* score. Nothing is generated. The API and the prompt are the model's own (its prompt.py and api.py
* on the Hub); this file is that adapter, and the engine knows nothing of it beyond
* Request::token_scores -- "read these ids' raw logits at the prompt's last position".
*
* A container serves it only when it says it is d1 (`decision.type` = `d1`, set at convert with
* `--set decision.type=d1`); the HF config does not declare it.
*/
#pragma once
#include "oai.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace server {
struct DecisionQuestion {
std::string name, type; /* type: noul | choice | score */
/* One entry an answer, in the response's order: "true"/"false", the option names, the
* levels "0".."n-1". */
std::vector<std::string> labels;
std::vector<std::string> legend; /* score: each level's description */
/* The ids read at the answer slot, and for each answer the indices into them of the
* spellings it scores as: an answer's score is its best spelling's. */
std::vector<int32_t> candidates;
std::vector<std::vector<size_t>> groups;
std::vector<int32_t> tokens; /* the whole prompt */
};
struct DecisionRequest {
std::vector<DecisionQuestion> questions;
/* The pictures, placed in the shared head of every question's prompt. */
std::shared_ptr<mm::PromptMedia> media;
/* How many leading tokens every question's prompt shares: the state, tokenised once. 0 for
* a single question, which d1 tokenises as one text. */
int32_t trunk = 0;
/* What the model reads, as d1 counts it: the shared head once and each question's own tail. */
int64_t input_tokens = 0;
};
/* Parse and render. `max_ctx` bounds every question's prompt (one position stays free for the
* token the request samples and discards). */
int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, DecisionRequest* out, ApiError* err);
/* One answer from its candidates' raw logits: each answer scores its best spelling, a softmax over
* the answers is the distribution. Non-finite logits are an error, not a distribution. */
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
ApiError* err);
} /* namespace server */
} /* namespace rad */
+11 -8
View File
@@ -379,6 +379,7 @@ struct TokEncoder {
uint32_t kind = RAD_TOK_BPE;
bool bytelevel = false; /* the chain has a ByteLevel pre-tokeniser */
bool byte_fallback = false;
bool ignore_merges = false; /* VocabBuild::ignore_merges */
/* The ByteLevel step at this index is the last step that rewrites text, so the mapping is
* never materialised: the BPE merges raw bytes against `raw` instead. -1 when that does not
* hold (no ByteLevel, or a step after it that reads the mapped text). */
@@ -407,6 +408,7 @@ struct TokEncoder {
int TokEncoder::build(const VocabBuild& b, const std::vector<int32_t>& special) {
kind = b.kind;
ignore_merges = b.ignore_merges;
types = b.types;
unk = b.unk;
@@ -1029,15 +1031,16 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector<int32_t>& out
* the vocabulary promises to round-trip; decomposing one into codepoints and merging back
* can land on a different sequence, because the merge table was never fitted over them.
*
* ORDINARY VOCABULARY ENTRIES STILL GO THROUGH THE MERGE LOOP, which is HuggingFace's
* behaviour at `ignore_merges: false` and is what every checkpoint in scope declares. A
* vocabulary setting it TRUE wants the same short-circuit for any word that is already a
* token, and this engine does not honour the flag: core/text/tokenizer_json.cpp only warns
* when it is set, and the vocabulary has nowhere to carry it. Such a model would tokenise
* differently here than it does in transformers, mostly on rare words. Supporting it is a
* vocabulary field, not a change to this loop. */
* ORDINARY VOCABULARY ENTRIES GO THROUGH THE MERGE LOOP unless the vocabulary sets
* `ignore_merges`, which is HuggingFace's short-circuit for a word that is already a token:
* the merge table can reach a different split of a rare word than the entry it ships. The
* word is the pre-token after the declared chain, and the raw-byte table looks the same entry
* up under its byte spelling. A CONTROL entry is not taken whole even then: one that reaches
* this loop is text the caller asked to have read as text, and the flag must not turn it back
* into the marker. */
const int32_t whole = table.find(w);
if (whole >= 0 && e.types[whole] == RAD_TT_USER_DEFINED) {
if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED ||
(e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) {
out.push_back(whole);
return;
}
+1
View File
@@ -70,6 +70,7 @@ inline bool step_is_dec (uint32_t k) { return k >= 64 && k < 96; }
* milliseconds at load, against a model measured in gigabytes -- which is not a cost. */
struct VocabBuild {
uint32_t kind = RAD_TOK_BPE;
bool ignore_merges = false; /* BPE: a whole pre-token in the vocab is not merged */
std::vector<std::string> tokens; /* id -> text, in the vocab's own encoding */
std::vector<float> scores; /* unigram only; empty otherwise */
+3 -11
View File
@@ -335,17 +335,7 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l
if (type == "BPE") {
out.kind = RAD_TOK_BPE;
/* `ignore_merges` SHORT-CIRCUITS THE MERGE LOOP for any word that is already a token, and
* this reader does not carry it: the vocabulary has no field for it and tokenizer.cpp
* applies the short-circuit only to added tokens. A vocabulary that sets it would tokenise
* differently here than in transformers, on rare words, with nothing in the output to say
* so -- so it is said here instead of being discovered from a quality regression. */
if (const json* im = get(m, "ignore_merges"))
if (im->is_boolean() && im->get<bool>())
RAD_WARN("%s: the vocabulary sets ignore_merges, which this tokeniser does not "
"implement. Words that are already tokens will be re-split through the "
"merge table and may tokenise differently than they do in transformers.",
origin);
out.ignore_merges = bool_or(m, "ignore_merges", false);
RAD_TRY(read_text_to_id("BPE"));
} else if (type == "Unigram") {
out.kind = RAD_TOK_UNIGRAM;
@@ -942,6 +932,7 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off,
h.add_bos = in.add_bos ? 1u : 0u;
h.add_eos = in.add_eos ? 1u : 0u;
h.chat_template = tmpl;
h.flags = in.ignore_merges ? RAD_VOCAB_IGNORE_MERGES : 0;
out.resize(sizeof(RadVocabHeader), 0);
/* Each array is aligned to its own element so a mapped reader can point a typed pointer at
@@ -1004,6 +995,7 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab
out.pad = h->pad_id; out.unk = h->unk; out.sep = h->sep;
out.add_bos = h->add_bos != 0;
out.add_eos = h->add_eos != 0;
out.ignore_merges = (h->flags & RAD_VOCAB_IGNORE_MERGES) != 0;
out.chat_template = S(h->chat_template);
if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff)))
+1 -1
View File
@@ -1,7 +1,7 @@
# The service every model file in this directory extends. It holds what any radiance container
# needs on an AMD host; a model file adds only its container and its flags.
#
# Each model takes both cards (--tp 2) and the same port, so run one at a time:
# Each model takes both cards (--tp 2; a -tp1 file one) and the same port, so run one at a time:
# docker compose -f flashnext.yaml up -d start (it comes back after a reboot)
# docker compose -f flashnext.yaml logs -f follow the log
# docker compose -f flashnext.yaml down stop
+24
View File
@@ -0,0 +1,24 @@
# Qwen3.8-Flash-Next on one card: the production container of flashnext.yaml at --tp 1. The routed
# experts that do not fit the card sit in a 42 GiB pinned host pool, so the process pins about
# 49 GiB of host memory and wants a host with 64 GB of RAM; the n-gram table is read from the
# model file on the drive.
#
# A prefill step copies every pooled expert across the link once, so on one card prefill is bound
# by the link, and a 4096-token step pays that once for twice the tokens of a 2048-token one: 26K
# prompts prefill at 2545 tok/s against 1413. The checkpoint interval matches the step, since a
# prefill chunk never crosses a checkpoint. At 4 sequences the cache holds 301K tokens, one and a
# half 200K-token sessions.
name: radiance-flashnext-tp1
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-flashnext-tp1
command: >
--model /models/qwen3.8-next-flash-fp8-iq4r-moe.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 1 --max-num-seqs 4 --max-model-len 200000
--placement expert_tiered --host-pool-mib 43000 --gpu-headroom-mib 96
--kv-cache-dtype fp8
--prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext-tp1
--prefix-cache-disk-mib 131072
--num-speculative-tokens 3 --max-num-batched-tokens 4096 --checkpoint-interval 4096
+2 -2
View File
@@ -3,8 +3,8 @@
# did not write.
#
# FILE... are the paths, in the build image, of every file copied into ROOT from outside the
# radiance install: the shared libraries, comgr, busybox, the GPU name table. Each is traced to the
# package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files
# radiance install: the shared libraries, comgr, busybox, curl, jq and the CA bundle's directory.
# Each is traced to the package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files
# are copied to ROOT/usr/share/doc/<package>/, the license texts Debian's copyright files refer to
# go to ROOT/usr/share/common-licenses/, and ROOT/usr/share/doc/THIRD-PARTY lists each component
# with its version, its license files and where its source is. A file that no package owns, or a
+61
View File
@@ -0,0 +1,61 @@
#!/bin/bash
# docker/llvm-check.sh BUILD -- the image's HIP compiler held to the two things it is for, on one of
# the build's own compile commands: r4d_hc_bf16.hip, the file whose code varied from build to build
# under ROCm's own clang. The command is run again four ways, outputs in a scratch directory:
# 1. pairing off, by ROCm's clang and by the image's: the device code must match byte for byte,
# so the llvm stage's libLLVM is ROCm's but for the patch;
# 2. pairing on, exactly as the build ran it, twice more by the image's clang: both must match
# the build's own object, so the pairing is repeatable.
# A mismatch fails the image build.
set -euo pipefail
B=$1
STOCK=/opt/rocm/lib/llvm/bin/clang++
IMAGE=/opt/rocm-repeatable/lib/llvm/bin/clang++
OBJCOPY=/opt/rocm/lib/llvm/bin/llvm-objcopy
O=libr4d/CMakeFiles/libr4d.dir/r4d_hc_bf16.hip.o
fail() { echo "llvm-check: $*" >&2; exit 1; }
T=$(mktemp -d)
trap 'rm -rf "$T"' EXIT
cd "$B"
cmds=$(ninja -t commands libr4d)
line=$(grep -m1 -F -- "-o $O " <<< "$cmds") || fail "no compile command for $O"
eval "set -- $line"
args=("$@")
[ "${args[0]}" = "$IMAGE" ] || fail "the build compiled with ${args[0]}, not $IMAGE"
for a in "${args[@]}"; do
case "$a" in *amdgpu-enable-vopd*) fail "the build turned VOPD pairing off ($a)" ;; esac
done
# variant NAME COMPILER [FLAG]: the build's command with this compiler, its object and depfile in
# the scratch directory, and FLAG appended; then the object's device code as NAME.fb.
variant() {
local name=$1 cc=$2 extra=${3:-} i=1
local v=("$cc")
while [ $i -lt ${#args[@]} ]; do
case "${args[$i]}" in
-o) v+=(-o "$T/$name.o"); i=$((i + 2)); continue ;;
-MF) v+=(-MF "$T/$name.d"); i=$((i + 2)); continue ;;
*) v+=("${args[$i]}") ;;
esac
i=$((i + 1))
done
[ -z "$extra" ] || v+=("$extra")
"${v[@]}" > "$T/$name.log" 2>&1 || { cat "$T/$name.log" >&2; return 1; }
"$OBJCOPY" --dump-section=.hip_fatbin="$T/$name.fb" "$T/$name.o" /dev/null
}
OFF=-mllvm=-amdgpu-enable-vopd=false
pids=()
variant stock_off "$STOCK" "$OFF" & pids+=($!)
variant image_off "$IMAGE" "$OFF" & pids+=($!)
variant image_on1 "$IMAGE" & pids+=($!)
variant image_on2 "$IMAGE" & pids+=($!)
for p in "${pids[@]}"; do wait "$p" || fail "a compile of $O failed"; done
"$OBJCOPY" --dump-section=.hip_fatbin="$T/build.fb" "$O" /dev/null
cmp -s "$T/stock_off.fb" "$T/image_off.fb" \
|| fail "with pairing off the image's clang and ROCm's emit different device code: the llvm stage did not rebuild ROCm's libLLVM"
cmp -s "$T/build.fb" "$T/image_on1.fb" && cmp -s "$T/build.fb" "$T/image_on2.fb" \
|| fail "with pairing on, three compiles of $O emitted different device code"
echo "llvm-check: r4d_hc_bf16.hip -- pairing off, ROCm's clang and the image's agree; pairing on, three compiles agree"
+23
View File
@@ -0,0 +1,23 @@
The VOPD pairing fix the image's HIP compiler is built with (Dockerfile, stage `llvm`).
VOPDPairingMutation caches each load's transitive load dependencies (LoadPredsCache), and
fuseInstructionPair adds edges after entries were filled, so they go stale. loadsMayOverlap stops
at the first witness while iterating a SmallPtrSet<SUnit *, 8>, whose order past eight entries is
the order of the pointers, so WHICH loads were cached before a fusion depends on heap addresses and
the pair decisions with it: the same source compiles to different code from run to run. A stale
entry can only miss dependencies and so only refuses pairs; dropping the cache after every fusion
makes every answer come from the current DAG.
diff --git a/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp b/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp
index 29dec3b8b..b241a2f24 100644
--- a/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp
@@ -486,6 +486,8 @@ struct VOPDPairingMutation : ScheduleDAGMutation {
continue;
if (fuseInstructionPair(*DAG, *ISUI, *JSUI)) {
+ // Fusion adds edges, so cached transitive load dependencies are stale.
+ LoadPredsComputed.reset();
// Clear to prevent future checks/fusing
VOPDCapable[JIdx] = false;
break;
+13 -9
View File
@@ -3,7 +3,7 @@
The repository builds into one Docker image that holds the engine, its plugins, its tools and the
recipes, and nothing else: it is assembled from scratch out of the install tree and exactly the
shared libraries that tree loads. The host needs Docker, an AMD GPU and an `amdgpu` kernel driver
that supports ROCm 7.2. It does not need ROCm itself, a compiler, or ffmpeg.
that supports ROCm 10.1. It does not need ROCm itself, a compiler, or ffmpeg.
The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance),
with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for
@@ -32,26 +32,29 @@ committed: no build directory, no uncommitted edit, no model file. It builds wit
(`docker buildx`), which runs independent stages side by side and caches each one; with `-s` only
the remote machine needs buildx.
The `Dockerfile` has three stages:
The `Dockerfile` has these stages:
| stage | what it does |
|---|---|
| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits and the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263). The distribution's build brings about 200 packages of encoders, filters and display libraries the engine never calls |
| `build` | `rocm/dev-ubuntu-24.04:7.2.4` plus cmake, ninja and g++-14. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
| `test` | `ctest -LE gpu`: every suite that runs without a card. The image is only produced if they pass |
| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, `amdgpu.ids`, and a static busybox. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's own llvm-project, at the exact commit the image's `clang --version` names, with `docker/llvm-vopd-pairing.patch` applied and configured as ROCm ships it. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. The library is the only file of the compiler that changes |
| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Every device source is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image stay ROCm's own. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
| `test` | `docker/llvm-check.sh`, then `ctest -LE gpu`: every suite that runs without a card. The check recompiles one kernel file four ways -- with pairing off the image's compiler must emit ROCm's device code byte for byte, with pairing on three compiles must agree. The image is only produced if both pass |
| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, and a static busybox. ROCm's `libdrm_amdgpu` carries the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
| `runtime` | `FROM scratch` and the rootfs. This is the image that ships |
The largest single file is comgr (about 150 MB), which the HIP runtime cannot initialise a device
without. There is no distribution in the shipped image: no package manager and no shell beyond busybox
(`docker exec -it <name> sh`). JPEG XL input is refused by name, since its decoder needs libjxl.
The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), which the
HIP runtime cannot initialise a device without. There is no distribution in the shipped image: no
package manager and no shell beyond busybox (`docker exec -it <name> sh`). JPEG XL input is refused
by name, since its decoder needs libjxl.
A build container has no card to enumerate, so the GPU architecture must be named. A bare-metal
`./build.sh` detects it instead. `libr4d` builds for gfx12 targets only; any other target in the
list just gets no RDNA4 kernels.
The ROCm version in the image has to be one the host's kernel driver supports. It is a build
argument (`ROCM_VERSION`, default 7.2.4).
argument (`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published
only with the `-full` suffix).
The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from
the `build` stage:
@@ -120,6 +123,7 @@ the cards the engine runs on.
| file | container | what it is |
|---|---|---|
| `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; idle sessions kept in host memory and on disk |
| `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences |
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
+158 -1
View File
@@ -57,6 +57,7 @@ driver on the host. [`DOCKER.md`](DOCKER.md) covers it, along with ready compose
|---|---|
| **Required** | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads |
| **Optional** | ROCm with `hipcc`, for AMD device kernels. Without it you get the host backend. Set `ROCM_PATH` if it is not at `/opt/rocm` |
| **With a card** | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup): the host writes every dispatch's arguments into VRAM, and startup refuses a card whose memory the CPU cannot reach |
| **Optional** | OpenMP, used by the host kernel libraries if present |
| **For the shell harnesses** | `curl` and `jq` |
@@ -487,6 +488,27 @@ The cache never gets less than one `--max-model-len` sequence, and when both sid
whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
off the card and gives the cache more.
**The next layer's experts are fetched ahead at decode.** The experts kept only in the pinned host
pool are read across the link by the routed GEMMs that need them, while those GEMMs run. At each
routed layer of a decode pass of up to 16 rows, the engine applies the *next* routed layer's router
to this layer's router input -- it predicts that layer's choice well -- and the card's second DMA
engine copies the two likeliest experts that are only in the pool onto the card while the rest of
this layer runs. Just before the next layer's GEMMs, their weight tables point at the copies that
have landed, so those GEMMs read them from VRAM. A copy holds the bytes of the pool slot it was made
from, so this changes no output; a copy that lands late is not used. It is on wherever the pool
holds experts (`--placement expert_tiered` or `auto`), off under `--deterministic` and where the
device backend has no second DMA engine, and the startup log says which (`expert prefetch on` /
`off`). It costs one hardware queue and a ring of six expert units on the card, both in the VRAM
receipt (`hardware queues`, `expert prefetch`).
It pays only where the steps use enough of what it copies, so it measures that: every 2048
predictions it looks at the share of its copies the steps routed, and under 30% it rests -- no
prediction, no copy -- for 8192 passes before measuring again (`expert prefetch resting`, once, in
the log). On Qwen3.8-Flash-Next at `--tp 1` with the `flashnext-tp1` flags the steps use about half
of the copies, and the decode step goes from 29.0 to 28.0 ms at one sequence and from 101.3 to 95.3
ms at four. At `--tp 2` each card keeps most of its experts and the pool holds the ones the steps
rarely route; under a quarter of the copies were used, it was a loss, and the prefetch rests there.
**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
@@ -1185,6 +1207,7 @@ for a model that takes no images or video.
| `POST /v1/chat/completions` | chat, with tools, reasoning and streaming |
| `POST /v1/completions` | raw text completion |
| `POST /v1/embeddings` | needs a model with an embedding head, else 501 |
| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 — §5.12 |
| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs — §5.9 |
| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client — §5.9 |
| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and the clients built on llama-server's own API — §5.9 |
@@ -1196,6 +1219,7 @@ for a model that takes no images or video.
| `POST /apply-template` | the prompt a chat request renders to, as llama-server answers it |
| `POST /v1/chat/completions/input_tokens` | how many tokens that prompt is |
| `GET /server_info` | the whole configuration of the running engine |
| `GET /diagnostics` | the startup report as JSON — every option and its source, the hardware read again now, the findings — §7.1. Without `--api-key` it answers only a client on the same machine (§6.6) |
| `GET /metrics` | Prometheus |
| `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
| `GET /get_tokenizer_info` | |
@@ -1648,6 +1672,69 @@ agrees to float rounding.
there and none here, which is OpenAI's default. The values themselves agree with llama-server's to
bf16 rounding (within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included).
### 5.12 Decisions: `/v1/systemone`
LiquidAI's d1-3B is a decision model on LFM2-VL. It is given a state — text, any JSON value,
pictures, or a mix — and named questions, and each answer is read off the model's distribution at
the position after the assistant header: `yes`/`no` for a `noul`, one code an option for a
`choice`, a digit a level for a `score`. Nothing is generated, so an answer is always in its
schema. The request and response are d1's own (`api.py` in the model's repository), and the
prompt it renders is d1's `prompt.py` string for string, since the model was trained on exactly
those.
The endpoint answers only a container that says it is d1, which the checkpoint does not: convert
it with `--set decision.type=d1`. d1's prompt text, which radiance carries, is Liquid AI's under the
LFM Open License v1.0, as the model is (NOTICE).
```sh
rad-convert ~/models/LiquidAI/d1-3B -o d1-3b-bf16.rad --set decision.type=d1
radiance --model d1-3b-bf16.rad --port 8000
curl -s localhost:8000/v1/systemone -H 'Content-Type: application/json' -d '{
"state": "I was charged twice this month, please refund one of them.",
"questions": {
"refund": {"type": "noul", "instructions": "Is the customer asking for a refund?"},
"team": {"type": "choice", "instructions": "Which team should handle this?",
"criteria": {"billing": "Charges, refunds, invoices", "technical": "App or site faults"}},
"urgency": {"type": "score", "instructions": "How urgent is this?",
"criteria": ["Can wait", "Today", "Blocking the customer now"]}}}'
```
The answer is an object of the same names, in the same order:
```
{"answers": {
"refund": {"type": "noul", "noul": P(yes)},
"team": {"type": "choice", "choice": "billing", "confidence": P(billing),
"probabilities": {"billing": ..., "technical": ...}},
"urgency": {"type": "score", "score": the expected level, "confidence": P(likeliest level),
"probabilities": {"0": ..., "1": ..., "2": ...},
"legend": {"0": "Can wait", "1": "Today", "2": "Blocking the customer now"}}},
"usage": {"input_tokens": N, "output_tokens": 0}}
```
- **`state`** is required: a string, any JSON value (rendered as indented JSON, keys in the order
sent), or `null` with pictures alone.
- **`questions`** is an object of named questions, answered in the order sent. A question is
`type` (`noul`, `choice` — the default — or `score`), `instructions`, and `criteria`: for a
`noul` optionally `{"true": ..., "false": ...}`; for a `choice` the options, name to description;
for a `score` 2 to 10 level descriptions, lowest first.
- **`images`** is an array of `data:` URLs, placed ahead of the state. Each picture is first
scaled down to at most 1024 x 1024 pixels' area, as d1's runner does, then cut as LFM2-VL's
processor cuts it: whole when it is small, else into 512-pixel tiles plus a thumbnail.
- **`noul`** is P(yes); a `choice` names its most probable option; a `score` is the expected level.
Each answer is a softmax over its options' raw logits, an option scoring its best spelling.
- **`usage.input_tokens`** counts what the model read as d1 counts it: the shared state once and
each question's own tail.
**Several questions read the state once.** The first runs alone and leaves the state's end in the
prefix cache — its attention blocks and a checkpoint of LFM2's convolutions there — and the rest
start from it together, each computing only its own question. A single question is one pass of
the whole prompt, tokenised as one text, as d1 does.
Against d1's own runner in float32, on eight text cases (one and several questions, JSON and long
log states): every choice and every `input_tokens` equal, worst probability difference 0.0044.
## 6. Operate it
### 6.1 The dashboard
@@ -1688,6 +1775,7 @@ curl -s localhost:8000/stats | jq # counters, memory, throughput
curl -s localhost:8000/sessions | jq # what is stored and where
curl -s localhost:8000/graph | jq # the resolved kernel graph
curl -s localhost:8000/server_info | jq # model, cards, KV, draft depth, wire
curl -s localhost:8000/diagnostics | jq # the startup report, hardware read again now (§7.1)
```
`/server_info` is the operator's first question asked of a process that is already running: which
@@ -1782,6 +1870,11 @@ authenticated probe is a server that reports itself down, and the dashboard page
`/dashboard`), which holds no data — on a 401 it shows a key field, keeps the key in the browser's
storage and sends it on every fetch of data it makes.
Without a key, `/diagnostics` answers only a client on the same machine (a loopback address) and
every other one 403: it describes the host — kernel, boot parameters, PCI layout, memory limits —
and not just the model. Read it with `curl localhost:8000/diagnostics` on the machine, or start
the server with `--api-key` to read it from elsewhere.
The key is checked, not encrypted: on any network you do not control, bind to localhost and put a
TLS-terminating reverse proxy in front:
@@ -1801,6 +1894,70 @@ released until it does.
## 7. When something goes wrong
### 7.1 Start with the startup report
The last thing startup prints before `serving on` is one block, `STARTUP REPORT`, in three parts.
A startup that stops prints it too, after the error, with what it had resolved by then, and ends
it with an `E` line that repeats the error, so the tail of the log still shows it. It is the part
of a log to paste into an issue.
- **CONFIGURATION** lists every option the command line takes, from the same table `--help`
prints. Each line shows the value in force and where it came from: `default`, `command line`,
an environment variable, or `auto`. An `auto` line carries the reason under it: the drafter's
depth, where the embedding and the n-gram table went and why, the VRAM split, the placement
strategy, and each sampler default with the file it came from, or the built-in default the
file left it at. `--api-key` shows only `set` or `not set`.
- **ENVIRONMENT** names the `RADIANCE_*` variables that are set (§8). It shows only the names,
never the values.
- **DERIVED** shows what startup worked out that no single option states: the VRAM split with the
budget report under it, the weights by tier, the KV cache, and the kernel libraries selection
used, with the attention rows by name.
- **HARDWARE** reads the machine from `/proc` and `/sys`, the same files inside the image. It
covers the CPU, RAM, swap, kernel, container, cgroup and memlock limits, transparent huge
pages, the IOMMU mode from the cards' own groups, TTM's page limit (`ttm.pages_limit`) and
`cwsr_enable`. Each display device gets its gfx target, VRAM and BAR, and its PCIe link **at
every hop up to the root port**. A card with a switch on it reports its own link at full speed
whatever the slot does, so a root port parked at half speed only shows here. The block also
shows the card's PCIe power levels, its power cap against its default and its maximum, any
voltage offset, and its runtime power management. The cgroup limit is the tightest one from
the process's own cgroup up to the root.
- **FINDINGS** lists warnings first, then notes. Each says what was seen, what it costs, and the
fix. Every warning is also printed as a `W` line of its own.
```
I STARTUP REPORT -- radiance 1.4.0
I CONFIGURATION -- every option, the value in force, and where it came from
I --model /models/flashnext.rad [command line]
I --tp 2 [command line]
I --num-speculative-tokens 3 [auto]
I the depth the drafter in this container states as its operating point
I --embedding-placement ram [auto]
I the table is 606.25 MiB a rank: pinned in host memory and read over the link in place, ...
I ...
I HARDWARE
I card 0000:07:00.0 rank 1 (device 1) gfx1201 "AMD Radeon AI PRO R9700" 31.86 GiB VRAM NUMA -1 driver amdgpu card1
I link 00:01.3 16.0 GT/s x8 (max 32.0 GT/s x8) -> 05:00.0 32.0 GT/s x16 (max 32.0 GT/s x16) -> ... -> 07:00.0 32.0 GT/s x16 (max 32.0 GT/s x16) [read at 90% busy]
I pcie 0: 2.5GT/s, x8 250Mhz | *1: 16.0GT/s, x8 616Mhz | 2: 32.0GT/s, x8 1143Mhz
I power cap 280 W (default 300 W, max 330 W) | voltage offset -75 mV | sclk 500-2350 MHz | ...
I FINDINGS -- 3 warnings, 4 notes
I WARN link-below-max: card 0000:07:00.0 (rank 1): the PCIe link at 0000:00:01.3 runs 16.0 GT/s x8 of its 32.0 GT/s x8 while the card is 90% busy
I why: every copy between host memory and the card ... cross this link, so ... a tensor-parallel step waits for it
I fix: a link stuck one level down after long uptime has been cleared by a reboot; ...
```
A PCIe link at rest parks at its lowest speed, so a link below its maximum is only a finding when
the card was busy as it was read. At startup the cards are mostly idle. `GET /diagnostics` reads
the hardware again and runs the same checks, so call it during a long prefill to see the links and
power levels under load. A reading is reused for a second, and the power-management files (DPM
levels, power caps, busy percentage) are read only for the cards the server runs on: the driver
answers them from the card's firmware under a lock, and wakes a sleeping card to do it.
```sh
curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findings'
```
### 7.2 Messages and what they mean
| What you see | What it means | What to do |
|---|---|---|
| `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement |
@@ -1813,7 +1970,7 @@ released until it does.
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` |
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
| `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the engine warns at startup when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended |
| `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception … GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended |
| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
+18
View File
@@ -165,6 +165,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
| `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout |
| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` |
| `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `add` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) |
@@ -493,6 +494,12 @@ is `[4, M]` (row, column, grid height, grid width), sampled bilinearly with the
table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s dtype
before the add.
**`grid_embed_aa`** is the same addition with SigLIP2's resample: torch's
`F.interpolate(mode="bilinear", align_corners=False, antialias=True)`. Per axis a triangle filter on
half-pixel centres, widened by the scale when the grid is smaller than the table, its taps inside the
table normalised to sum to one; separable, f32, rounded once. A different function from
`grid_embed`'s, and so a different op rather than a mode a library could ignore.
| op | params | operands |
|---|---|---|
| `attn_paged_gate_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `gate` → `q8`, `q8_scale` |
@@ -910,6 +917,7 @@ form exists, as for `ar_hc_write`.
| `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? |
| `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w → `gv`, `gvn` |
| `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? → `y` |
| `causal_conv1d` | `M`(range) `n` `width` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `cache_idx`?, `has_init`?, `num_accepted`? → `y` |
Separate from `gemm_nt` because `lm_head` is its own access class (`RAD_ACCESS_VOCAB`) and because
the sampler wants to fuse against it: at a 151K vocab and batch 256 the logits are ~77 MiB a step,
@@ -1172,6 +1180,16 @@ it takes the union of the two contracts instead: `has_init` is prefill's questio
The residual add is folded in because the reference is `gv + silu(conv(gvn))` and the two tensors
are both `[M, hc*n]` — 10240 wide here. `resid` absent leaves the plain convolution.
### `causal_conv1d`: `ple_conv` without the PLE
y[t] = sum_j w[c][j] * x[t - (width-1-j)]
LFM2's short convolution: depthwise, causal, undilated, with no activation and no residual — the
gates around it are separate `mul`s in the architecture. The window and its three optional operands
are `ple_conv`'s at dilation one, so an architecture issues it the same way, once over its decode
rows with `num_accepted` and once over its prefill rows without. libr4d, libref and libavx each
serve both ops from one implementation.
## Sampling
Every sampler is a kernel, not a host lift. `llama.cpp`'s chain is kept as a **host reference**
+2 -1
View File
@@ -52,13 +52,14 @@ any shape change in a header a plugin compiles against (`rad_abi.h` says which).
both in-tree host libraries say — or `""` for a plugin that really is portable. It is printed, not
trusted: what the engine checks is the code objects your library actually carries (§10).
Four more exports are optional, each looked up by exactly this name:
Five more exports are optional, each looked up by exactly this name:
| symbol | says |
|---|---|
| `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` **declines this machine** — the library is unloaded and the rest of the installation carries on; any other negative status refuses it as an error |
| `void rad_plugin_close(void)` | called once at shutdown |
| `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap |
| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic out of the way while it runs. 2: each launch ends that itself once the other ranks' bytes have landed, through the `link_gate` parameter (rad_abi.h). Without it only the `all_reduce` op counts as one |
| `int rad_plugin_reference(void)` | nonzero: this library is a **reference implementation** — ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref says so through this, as any library would |
---
+13 -2
View File
@@ -348,6 +348,8 @@ rad-kbench -m moe.rad --max-cases 1 --record data/kernels_moe.rkb
| `--bench` | time each case that passes, on the same bytes |
| `--bench-iters N`, `--bench-reps N` | launches per rep (20), timed reps (3) |
| `--bench-warm-ms N` | untimed launches before each timed window (default 500) |
| `--bench-flush MIB` | time cold: read MIB through the caches before every timed launch (256 empties an R9700's 8 MiB L2 and 64 MiB last level) and time each launch alone between two device events. Implies `--bench` |
| `--timing-only` | time every device kernel and check nothing: no reference run, read-back, margins or fusion chain, host rows skipped. For comparing builds a checked run has already passed; refuses `--record`. Implies `--bench` |
| `--report FILE` | write the markdown report |
| `--analysis FILE` | splice in a fragment from `tools/kbench-analysis.sh` |
| `--num-speculative-tokens N` | draft depth to declare at |
@@ -365,8 +367,17 @@ running on the same box, pass something small explicitly:
rad-kbench --home $RADIANCE_HOME --max-cases 1 --max-bytes 1024
```
**`--bench` is cache-warm.** It cannot rank a bandwidth-bound kernel the way production runs it.
Read the caveat the report prints about the GB/s column.
**`--bench` is cache-warm.** Every launch of a timed window reuses one set of operands, so a weight
that fits in the last-level cache is read from it after the first launch: a 52 MB bf16 decode weight
times at 1.45 TB/s warm and at 565 GB/s, the card's DRAM rate, cold. The engine streams its weights
cold every step. `--bench-flush 256` measures that; use it whenever the comparison is about how a
kernel waits on memory. Its numbers are device time per launch and are not comparable with a warm
run's, which divide a window's wall time by its launches.
**`--timing-only` runs the card hotter.** With no host-side check between cases the card is busy
almost all of the run, and on the same binary its times come out 0.3-0.8% above a checked run's in
total, compute-bound kernels 1-2%. Compare builds within one mode, interleaved; the ratio between
two builds matched the checked mode's to within half a percent.
**`--max-cases`.** A 62-layer model presents the same kernel at the same shape sixty times and only
the weights differ. The default of 4 is not a sample of anything interesting; `--max-cases 1` is
+5
View File
@@ -117,6 +117,7 @@ std::vector<Case> build_cases() {
HF("wadd", 1), HF("gate_eps", 1e-6) });
add("ple_conv", { HI("M", 9), HI("n", 128), HI("width", 4), HI("dilation", 2),
HS("dtype", dt) });
add("causal_conv1d", { HI("M", 9), HI("n", 128), HI("width", 3), HS("dtype", dt) });
}
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
@@ -309,6 +310,10 @@ std::vector<Case> build_cases() {
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"),
HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) });
add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) });
/* Two table sides. A drawn grid is never larger than the table, so enlarging is
* avx_check's hand-built case. */
add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) });
add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) });
}
/* MoE. `a_order` exists because the two grouped GEMMs of one routed block disagree about it,
+25
View File
@@ -624,6 +624,31 @@ static bool hand_cases(const Lib& ref, const Lib& avx, bool verbose, int* n_chec
.pi("M", BAND).pi("n", N).pi("width", WIDTH).pi("dilation", DIL).ps("dtype", "f32");
hs.push_back(std::move(c));
/* LFM2's form of the same window: width 3, undilated, no residual and no activation. */
const int64_t CW = 3, CHIST = CW - 1, CSL = CHIST + 2;
Hand k("M = 64 over 5 rows, verifies of 3 and 2", "causal_conv1d", 1e-5);
k.dense(RAD_F32, { T, N }, hfill(55))
.dense(RAD_F32, { N, CW }, hfill(56, 0.5f))
.dense(RAD_F32, { 2, N, CSL }, hfill(57), true)
.idx({ 0, 3, 5 })
.idx({ 1, 0 })
.idx({ 7, 9 })
.idx({ 2, 3 })
.dense(RAD_F32, { T, N }, hfill(58), true)
.pi("M", BAND).pi("n", N).pi("width", CW).ps("dtype", "f32");
hs.push_back(std::move(k));
/* The antialiased resample ENLARGING a 4 x 4 table (a drawn case's grid is never larger
* than the table), one row shrinking it, and a 1 x 1 grid. */
static const int32_t kAaCrd[4][6] = { { 0, 6, 3, 1, 0, 5 }, { 0, 8, 4, 2, 0, 1 },
{ 7, 7, 7, 2, 1, 7 }, { 9, 9, 9, 3, 1, 9 } };
Hand ga("a 4 x 4 table onto 7 x 9, 2 x 3 and 1 x 1 grids", "grid_embed_aa", 1e-6);
ga.dense(RAD_F32, { 6, N }, hfill(59), true)
.dense(RAD_F32, { 16, N }, hfill(60))
.dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kAaCrd[i / 6][i % 6]; })
.pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32");
hs.push_back(std::move(ga));
Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0);
n.idx({ 11, 12, 13, 21, 22 })
.dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true)
+1 -1
View File
@@ -86,7 +86,7 @@ int avx_isa_force(int level);
/* ---- elementwise and norms */ \
X(rmsnorm) X(rmsnorm_add) X(hc_enter) X(hc_read) \
X(hc_write) X(mtp_enter) X(layernorm) X(add) \
X(grid_embed) \
X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \
X(mul) X(silu_mul) X(gelu) X(silu) \
X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
+27 -12
View File
@@ -176,17 +176,16 @@ AVX_KERNEL(ple_gate) {
* Absent, every token commits and the last (width-1)*dilation inputs land at offset zero. The
* write happens in a SECOND pass after every read is done, because a sequence longer than the
* window would otherwise overwrite history it is still reading. */
AVX_KERNEL(ple_conv) {
if (a->n_t < 9) return RAD_E_INVAL;
const RadTensor* x = rad_arg_in(a, 0);
const RadTensor* w = rad_arg_in(a, 1);
const RadTensor* cs = rad_arg_in(a, 2);
const RadTensor* cu = rad_arg_in(a, 3);
const RadTensor* resid = rad_arg_in(a, 4);
const RadTensor* sidx = rad_arg_in(a, 5);
const RadTensor* hini = rad_arg_in(a, 6);
const RadTensor* nacc = rad_arg_in(a, 7);
const RadTensor* y = rad_arg_in(a, 8);
/* ONE BODY FOR ple_conv AND causal_conv1d (LFM2's short convolution: undilated, no activation, no
* residual), as in libref, so the two cannot disagree about the window's layout. */
struct ConvOps {
const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y;
bool silu;
};
static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid;
const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y;
if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
@@ -260,7 +259,7 @@ AVX_KERNEL(ple_conv) {
acc += vv * tap[j];
}
const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f;
stt(y, (bos + t) * yrow + c * ycol, r + acc / (1.0f + std::exp(-acc)));
stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + std::exp(-acc)) : acc));
}
}
@@ -298,6 +297,22 @@ AVX_KERNEL(ple_conv) {
return RAD_OK;
}
AVX_KERNEL(ple_conv) {
if (a->n_t < 9) return RAD_E_INVAL;
return depthwise_causal_conv(a, { rad_arg_in(a, 0), rad_arg_in(a, 1), rad_arg_in(a, 2),
rad_arg_in(a, 3), rad_arg_in(a, 4), rad_arg_in(a, 5),
rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true });
}
/* ple_conv's operands without `resid`, at dilation one and with no activation. */
AVX_KERNEL(causal_conv1d) {
if (a->n_t < 8) return RAD_E_INVAL;
if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL;
return depthwise_causal_conv(a, { rad_arg_in(a, 0), rad_arg_in(a, 1), rad_arg_in(a, 2),
rad_arg_in(a, 3), nullptr, rad_arg_in(a, 4),
rad_arg_in(a, 5), rad_arg_in(a, 6), rad_arg_in(a, 7), false });
}
/* ------------------------------------------------------------------ ngram_ids
*
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h].
+64
View File
@@ -284,3 +284,67 @@ AVX_KERNEL(grid_embed) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ grid_embed_aa */
/* The table resampled as torch's F.interpolate(bilinear, align_corners=False, antialias=True) does
* it -- SigLIP2's position embedding -- and added in: libref's grid_embed_aa, operation for
* operation. Per axis a triangle filter on half-pixel centres, widened by the scale when
* shrinking, its taps inside the table normalised; the rows summed first, f32, rounded once
* before the add. A coordinate outside its grid is clamped into it. */
static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) {
if (size < 1) size = 1;
at = at < 0 ? 0 : (at >= size ? size - 1 : at);
const float scale = (float)side / (float)size;
const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support;
const float center = scale * ((float)at + 0.5f);
int64_t a = (int64_t)(center - support + 0.5f), b = (int64_t)(center + support + 0.5f);
if (a < 0) a = 0;
if (b > side) b = side;
float total = 0.0f;
for (int64_t j = a; j < b; ++j) {
const float d = std::fabs(((float)j - center + 0.5f) * inv);
w[j - a] = d < 1.0f ? 1.0f - d : 0.0f;
total += w[j - a];
}
for (int64_t j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f;
*lo = a;
*cnt = b > a ? b - a : 0;
}
AVX_KERNEL(grid_embed_aa) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ldi(crd, c * cs + r * ms);
float* wh = scratch_f32((size_t)(2 * side));
float* ww = wh + side;
int64_t h0 = 0, nh = 0, w0 = 0, nw = 0;
aa_taps(g[0], g[2], side, wh, &h0, &nh);
aa_taps(g[1], g[3], side, ww, &w0, &nw);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t y = 0; y < nh; ++y) {
float row = 0.0f;
for (int64_t c = 0; c < nw; ++c)
row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) * ww[c];
acc += row * wh[y];
}
float pe = acc;
if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe));
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff. Show more