Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc339b4cd2 | ||
|
|
d5b65cddc6 | ||
|
|
4ab587a8a2 | ||
|
|
04405089cb | ||
|
|
89cee7ce41 | ||
|
|
6a2ee986d6 | ||
|
|
7e796642e6 | ||
|
|
9238b1f23d | ||
|
|
6b4a67f52e | ||
|
|
a97985e7c2 | ||
|
|
7c0bd03841 | ||
|
|
d5b584a4c1 | ||
|
|
3a3345951f | ||
|
|
86128c2e75 | ||
|
|
7fd2cd7fa6 | ||
|
|
7d840861af |
No files matched your search
+22
-7
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
|
||||
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
|
||||
# a plugin contract and a server release do not move together.
|
||||
project(radiance VERSION 1.2.3 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.4.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -18,10 +18,14 @@ endif()
|
||||
# cache STRING.
|
||||
set(RAD_WITH_HIP "AUTO" CACHE STRING "ON | OFF | AUTO -- build the HIP backend and device kernels")
|
||||
set_property(CACHE RAD_WITH_HIP PROPERTY STRINGS ON OFF AUTO)
|
||||
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image and video parts with libavformat/libavcodec/libswscale")
|
||||
set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
|
||||
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
|
||||
option(RAD_BUILD_TESTS "Build the test suite" ON)
|
||||
option(RAD_ASAN "Build with AddressSanitizer" OFF)
|
||||
# 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
|
||||
@@ -219,6 +223,14 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb)
|
||||
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb
|
||||
DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance)
|
||||
endif()
|
||||
# THE DOWNLOADER `radiance --model <owner/name>` RUNS (core/hf_model.cpp). The engine finds it at
|
||||
# <bin>/../libexec/radiance/, so the build puts a copy at the same place under the build tree and
|
||||
# a binary run from either tree finds it without a path to configure.
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY)
|
||||
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh
|
||||
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance)
|
||||
|
||||
# rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package
|
||||
# config includes that same file: a third party building a plugin from their own repository needs
|
||||
# the function, and a second copy of it in the package config would drift from this one. The file
|
||||
@@ -316,22 +328,23 @@ endif()
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# ---------------------------------------------------------------- media decoding
|
||||
# An image or video part of a chat request is decoded by libavformat/libavcodec and converted by
|
||||
# libswscale (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
|
||||
# An image, video or audio part of a request is decoded by libavformat/libavcodec and converted by
|
||||
# libswscale or libswresample (core/mm/media.cpp). Without them the engine builds and serves text, and refuses a
|
||||
# media part by name -- the same tri-state as HIP, because a machine that has the libraries should
|
||||
# not silently build without them.
|
||||
set(RAD_FFMPEG_FOUND OFF)
|
||||
if(NOT RAD_WITH_FFMPEG STREQUAL "OFF")
|
||||
find_package(PkgConfig QUIET)
|
||||
if(PkgConfig_FOUND)
|
||||
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale)
|
||||
pkg_check_modules(RAD_FFMPEG QUIET IMPORTED_TARGET libavformat libavcodec libavutil libswscale
|
||||
libswresample)
|
||||
endif()
|
||||
if(RAD_FFMPEG_FOUND)
|
||||
message(STATUS "radiance: media decoding via libavformat ${RAD_FFMPEG_libavformat_VERSION}")
|
||||
elseif(RAD_WITH_FFMPEG STREQUAL "ON")
|
||||
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale were not found.")
|
||||
message(FATAL_ERROR "RAD_WITH_FFMPEG=ON but libavformat/libavcodec/libavutil/libswscale/libswresample were not found.")
|
||||
else()
|
||||
message(STATUS "radiance: no libavformat -- image and video input will be refused")
|
||||
message(STATUS "radiance: no libavformat -- image, video and audio input will be refused")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
@@ -446,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)
|
||||
+124
-23
@@ -11,10 +11,16 @@
|
||||
#
|
||||
# Stages:
|
||||
# ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their
|
||||
# streams need; the distribution's build brings ~200 packages of encoders, filters and
|
||||
# display libraries the engine never calls
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
@@ -59,11 +66,11 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \
|
||||
&& tar -xJf ffmpeg.tar.xz && cd "ffmpeg-${FFMPEG_VERSION}" \
|
||||
&& ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \
|
||||
--disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \
|
||||
--disable-avdevice --disable-avfilter --disable-swresample \
|
||||
--disable-avdevice --disable-avfilter --enable-swresample \
|
||||
--enable-zlib --enable-libdav1d \
|
||||
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe \
|
||||
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263 \
|
||||
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl \
|
||||
--enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \
|
||||
--enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \
|
||||
--enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \
|
||||
&& make -j"${JOBS:-$(nproc)}" \
|
||||
&& make install \
|
||||
&& mkdir -p /opt/ffmpeg/share/doc/ffmpeg \
|
||||
@@ -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,41 +212,56 @@ 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
|
||||
FROM build AS rootfs
|
||||
# hfget.sh, which fetches the Hugging Face repo a --model id names, runs curl and jq, and curl needs
|
||||
# a CA bundle to reach the hub over TLS. Installed in this stage, not in `build`, so adding them does
|
||||
# not recompile the engine.
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
curl jq ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# The marker makes this stage, and so the shipped image, depend on the test stage.
|
||||
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`. 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/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 /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \
|
||||
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; \
|
||||
sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \
|
||||
/usr/share/libdrm/amdgpu.ids /bin/busybox; \
|
||||
for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); do \
|
||||
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 /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; }; \
|
||||
if echo "$out" | grep -q 'not found'; then echo "$f: $out" >&2; exit 1; fi; \
|
||||
done; \
|
||||
chroot $R /opt/radiance/bin/radiance --help > /dev/null; \
|
||||
chroot $R /usr/bin/curl --version > /dev/null; chroot $R /usr/bin/jq --version > /dev/null; \
|
||||
du -sh $R $L $R/opt/radiance
|
||||
|
||||
# ---------------------------------------------------------------------------------------- runtime
|
||||
|
||||
@@ -12,8 +12,12 @@ and row groups, the fused router launch, the adaptive draft window, the MoE pref
|
||||
sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000
|
||||
(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, the request log, an uneven world's
|
||||
per-rank KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary
|
||||
paths).
|
||||
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, 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.
|
||||
@@ -24,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.
|
||||
@@ -1,7 +1,8 @@
|
||||
# radiance
|
||||
|
||||
An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. Model
|
||||
architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
|
||||
An LLM inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's chat, completions
|
||||
and Responses APIs, Anthropic's Messages API and llama-server's native one, so their clients and
|
||||
SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built
|
||||
and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)).
|
||||
|
||||
The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags
|
||||
@@ -23,6 +24,7 @@ If you wish to support the developement of the radiance engine you can do so [he
|
||||
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
|
||||
| Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` |
|
||||
| Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` |
|
||||
| EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` |
|
||||
|
||||
A container holds everything the server needs: the weights, the tokeniser, the chat template and
|
||||
any drafter. Each download link's repository has the recipe and the exact command that made the
|
||||
@@ -35,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:
|
||||
@@ -60,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
|
||||
@@ -70,13 +74,25 @@ 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
|
||||
export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own
|
||||
build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 <flags>
|
||||
build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 <flags>
|
||||
```
|
||||
|
||||
`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl`
|
||||
and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it
|
||||
holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy
|
||||
it has. The Docker image has neither tool, so with Docker download the file as shown above.
|
||||
|
||||
These are the flags each model is served with. They match its compose file, minus Flash-Next's
|
||||
prefix-cache tiers:
|
||||
|
||||
@@ -99,10 +115,10 @@ At `--tp 4` the gated residual's write carries the exact all-reduce, with the Mo
|
||||
of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes
|
||||
on a prefill chunk; both produce the same bits. The row above runs exact.
|
||||
`--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot,
|
||||
above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at
|
||||
startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against
|
||||
`--tp 2` on the same cards has not been measured. The
|
||||
`--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the
|
||||
two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6`
|
||||
stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate
|
||||
against `--tp 2` on the same cards has not been measured. The
|
||||
tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of
|
||||
every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the
|
||||
odd block alternates with the parity, so every rank's share is whole blocks and every block has
|
||||
@@ -113,7 +129,7 @@ above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `tt
|
||||
of RAM by default: that row needs 96 GiB of RAM or a raised limit
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op
|
||||
and the kernel it resolved to, then exit without serving. Then:
|
||||
|
||||
```sh
|
||||
|
||||
+24
-2
@@ -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,12 +598,33 @@ 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:
|
||||
* - the loader ranks it below every unnamed kernel library, because a reference matches every
|
||||
* op it declares and would otherwise answer for them ahead of the library serving the card
|
||||
* (naming it in --kernels still puts it where it is named);
|
||||
* (naming it in --kernels still puts it where it is named, and a --kernels list that does
|
||||
* not name it leaves it out);
|
||||
* - the engine refuses to serve a model with an op only a reference library implements, unless
|
||||
* told to with --debug-accept-reference-kernels;
|
||||
* - rad-kbench checks every other library against it.
|
||||
|
||||
+45
-2
@@ -134,6 +134,15 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_out_rows;
|
||||
|
||||
/* THE MOST FRAMES ONE AUDIO ENCODER PASS MAY CARRY, and 0 means this deployment serves no
|
||||
* audio: the plugin declares no audio encoder. An audio encoder's `max_tok`, the way
|
||||
* max_enc_patches is a vision tower's -- its activations are sized against it -- and it bounds
|
||||
* the longest clip, since one clip is one segment. The engine takes it from
|
||||
* RadArchProbe::audio_frames, which is the plugin's statement of its longest clip.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int64_t max_audio_frames;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== weights */
|
||||
@@ -443,6 +452,25 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m);
|
||||
* the first step. An embedding-only or encoder-only plugin declares none, deliberately. */
|
||||
int rad_declare_logits(RadBuilder* b, rad_buf logits);
|
||||
|
||||
/* WHICH BUFFER HOLDS THIS STEP'S POOLED VECTORS: what an EMBEDDING model returns instead of logits,
|
||||
* one row a sequence of the step -- row s is sequence s's whole input pooled into one vector,
|
||||
* whatever pooling the model was trained with (a mean, the last token, a CLS row). The core reads
|
||||
* rows [0, n_seq) back after the step and hands each to its request; it does not normalise them,
|
||||
* because that is the API's choice and not the model's.
|
||||
*
|
||||
* DECLARING IT MAKES THE PROGRAM AN EMBEDDING PROGRAM, and that changes what a step is:
|
||||
*
|
||||
* - every sequence in a step is a WHOLE input. The scheduler never splits one across steps,
|
||||
* because an encoder that attends both ways cannot be fed half of its input, and it refuses
|
||||
* an input longer than one step's tokens rather than truncating it;
|
||||
* - there is no sampler, no drafter and no prefix cache, and nothing is generated: a request
|
||||
* ends at the step that carried it.
|
||||
*
|
||||
* f32, device, [>= max_seqs, dim]: `dim` is the vector's width and the extent the core reads. A
|
||||
* Program declares this or logits, never both -- a model that both generates and embeds is two
|
||||
* deployments. */
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled);
|
||||
|
||||
|
||||
/* ================================================================== the drafter */
|
||||
/* WHAT THE PLUGIN'S DRAFT HEAD IS, declared the same way and for the same reason the logits
|
||||
@@ -531,17 +559,21 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
* the processor's (core/mm), which reads its geometry from the container: the two agree through
|
||||
* `patch_dim` and `merge`, and the core refuses a program whose encoder disagrees with the
|
||||
* processor about either. */
|
||||
/* A PROGRAM DECLARES AT MOST TWO: one serving images and video, one serving audio. An audio
|
||||
* encoder's "patch" is one feature frame (a mel row), its `merge` is frames per output row, and
|
||||
* its `max_patches` is RadBuildCtx::max_audio_frames. RadBatch::enc names which one a pass runs. */
|
||||
enum {
|
||||
RAD_MM_IMAGE = 1u << 0,
|
||||
RAD_MM_VIDEO = 1u << 1,
|
||||
RAD_MM_AUDIO = 1u << 2,
|
||||
};
|
||||
|
||||
typedef struct RadEncoderDecl {
|
||||
const char* name; /* "vision" -- for messages */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves */
|
||||
uint32_t modalities; /* RAD_MM_* this encoder serves: IMAGE|VIDEO, or AUDIO alone */
|
||||
int64_t patch_dim; /* elements in one input patch row */
|
||||
int64_t merge; /* input patches per output row */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches */
|
||||
int64_t max_patches; /* must equal RadBuildCtx::max_enc_patches (max_audio_frames) */
|
||||
int64_t n_embd; /* the width of an output row, the model's embedding width */
|
||||
/* [max_patches / merge, n_embd] bf16: where a pass leaves its rows. The core reads it after
|
||||
* the pass and before any other pass runs, so the planner may share its bytes with buffers
|
||||
@@ -612,6 +644,17 @@ typedef struct RadArchProbe {
|
||||
* function reads untouched. Zero -- what a plugin that never heard of it leaves -- means the
|
||||
* core does not ask, and the activation arena is not lent. */
|
||||
int shape_probe_ok;
|
||||
|
||||
/* THE ENCODER'S MERGE: input patches a output row (RadEncoderDecl::merge), when the plugin
|
||||
* declares an encoder. A pass carries whole output rows, so the core rounds the pass size it
|
||||
* picks itself (`--mm-max-patches auto`) down to a multiple of this; a size the operator
|
||||
* names is the operator's, and a plugin refuses one that does not divide. 0 is no opinion. */
|
||||
int64_t enc_merge;
|
||||
|
||||
/* THE LONGEST AUDIO CLIP THE PLUGIN'S AUDIO ENCODER TAKES, in feature frames (a whole
|
||||
* number of its merge), when it declares one: the engine sizes the audio pass with it
|
||||
* (RadBuildCtx::max_audio_frames). 0 is no audio. */
|
||||
int64_t audio_frames;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
+6
-1
@@ -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 };
|
||||
|
||||
|
||||
+46
-4
@@ -206,10 +206,16 @@ typedef struct RadBatch {
|
||||
const int32_t* mm_rows; /* [n_mm_rows] device: index into this pass's tokens */
|
||||
const void* mm_embd; /* [n_mm_rows, n_embd] bf16 device */
|
||||
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs the plugin's declared encoder (rad_declare_encoder)
|
||||
* and nothing else: no token rows, no KV, no logits. Its input is a list of patches, already
|
||||
* resized, normalised and cut by the processor, and its output is the encoder's declared
|
||||
* `out` buffer, one row per `merge` patches, which the core reads back after the pass.
|
||||
/* THE ENCODER PASS. Non-zero `enc` runs a declared encoder (rad_declare_encoder) and nothing
|
||||
* else: no token rows, no KV, no logits. It is that encoder's `modalities` -- RAD_MM_AUDIO
|
||||
* for an audio encoder, the image/video mask for the other -- so a program that declared two
|
||||
* knows which to run. Its input is a list of patches, already resized, normalised and cut by
|
||||
* the processor, and its output is the encoder's declared `out` buffer, one row per `merge`
|
||||
* patches, which the core reads back after the pass.
|
||||
*
|
||||
* An AUDIO pass's patches are feature frames and its coordinates are 1-D: plane 0 the frame's
|
||||
* index in its clip, plane 1 whether the frame is real (1) or the zero padding that makes the
|
||||
* clip whole output rows (0), plane 2 the clip's real frames and plane 3 its staged ones.
|
||||
*
|
||||
* Patches are grouped into SEGMENTS -- one per image, and one per temporal group of a video
|
||||
* -- and attention runs within a segment. `enc_coord` gives each patch its place in its
|
||||
@@ -370,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. */
|
||||
|
||||
+2
-1
@@ -44,7 +44,8 @@ enum {
|
||||
RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */
|
||||
RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */
|
||||
RAD_SP_XTC = 1 << 3,
|
||||
RAD_SP_DRY = 1 << 4
|
||||
RAD_SP_DRY = 1 << 4,
|
||||
RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */
|
||||
};
|
||||
|
||||
/* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/embgemma2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
|
||||
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(embgemma2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(embgemma2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/embgemma2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
@@ -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
|
||||
@@ -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 */
|
||||
@@ -689,7 +689,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state
|
||||
* instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of
|
||||
* what depth costs at that concurrency, and halving the width halves it. It also halves what a
|
||||
* sequence costs in --vram-kv-mib, which is context and batch size as well as time.
|
||||
* sequence costs in the KV pool, which is context and batch size as well as time.
|
||||
*
|
||||
* IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a
|
||||
* long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge,
|
||||
@@ -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),
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -132,6 +132,7 @@ public:
|
||||
int op_resolved (rad_op h) const;
|
||||
int decl_name_map(const RadNameMap* m);
|
||||
int declare_logits(rad_buf b);
|
||||
int declare_pooled(rad_buf b);
|
||||
int declare_drafter(const RadDrafterDecl* d);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
void note_v (const char* f, va_list ap);
|
||||
|
||||
+98
-29
@@ -10,6 +10,7 @@
|
||||
* and have fusion be a selection rather than a compiler pass (spec §2.3).
|
||||
*/
|
||||
#include "rad_build.h"
|
||||
#include "../device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
@@ -45,6 +46,26 @@ std::string Program::Miss::line() const {
|
||||
why.c_str());
|
||||
}
|
||||
|
||||
std::vector<const Program::Miss*> Program::device_holes(bool host_backend) const {
|
||||
/* By INSTANCE, because bands are: two declarations of one op can differ in geometry and in
|
||||
* whether they carry a weight, and only the instance that missed decides whether the planner
|
||||
* can move it to the host. */
|
||||
std::set<std::pair<int32_t, std::string>> no_host;
|
||||
for (const Miss& m : misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
|
||||
std::vector<const Miss*> out;
|
||||
for (const Miss& m : misses) {
|
||||
if (m.domain == RAD_DOMAIN_HOST) continue;
|
||||
const bool host_kernel = no_host.count(std::make_pair(m.index, m.span)) == 0;
|
||||
/* An instance with no weight has nothing the planner places, so nothing moves it. */
|
||||
const bool weightless = m.index > 0 && (size_t)m.index < ops.size() &&
|
||||
ops[(size_t)m.index].weights.empty();
|
||||
if (host_kernel && (host_backend || !weightless)) continue;
|
||||
out.push_back(&m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const char* bld_access_name(int a) {
|
||||
switch (a) {
|
||||
case RAD_ACCESS_PER_TOKEN: return "per-token";
|
||||
@@ -565,7 +586,7 @@ void Builder::resolve_bands(OpInfo& oi) {
|
||||
* reports the list whole (spec §3.1). */
|
||||
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
|
||||
b.miss[d].empty() ? "no kernel matched" : b.miss[d],
|
||||
d });
|
||||
d, oi.index });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -616,7 +637,7 @@ void Builder::finish_instances() {
|
||||
r.geom.str().c_str(), rad_strerror(s));
|
||||
b.miss[d] = fmt("init() refused the instance: %s", rad_strerror(s));
|
||||
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
|
||||
b.miss[d], d });
|
||||
b.miss[d], d, oi.index });
|
||||
r = Resolved{};
|
||||
}
|
||||
}
|
||||
@@ -1036,10 +1057,50 @@ int Builder::declare_logits(rad_buf b) {
|
||||
prog_.buffers[prog_.logits_buf].name.c_str(), prog_.buffers[b].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.pooled_buf != RAD_NULL_HANDLE) {
|
||||
err(RAD_E_STATE, "declare_logits: this program already declared '%s' as its pooled "
|
||||
"output; a program generates or embeds, not both",
|
||||
prog_.buffers[prog_.pooled_buf].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
prog_.logits_buf = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The embedding program's output (rad_declare_pooled). Checked here for the logits buffer's
|
||||
* reasons, and for shape: the core reads `n_seq` f32 rows of it from the device after every step,
|
||||
* so a buffer narrower than a step's sequences, or in another dtype or domain, is refused now
|
||||
* rather than read past or misread at the first request. */
|
||||
int Builder::declare_pooled(rad_buf b) {
|
||||
if (finished_) { err(RAD_E_STATE, "declare_pooled after declare finished"); return RAD_E_STATE; }
|
||||
if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) {
|
||||
err(RAD_E_INVAL, "declare_pooled: %u is not a declared buffer", (unsigned)b);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (prog_.pooled_buf != RAD_NULL_HANDLE && prog_.pooled_buf != b) {
|
||||
err(RAD_E_STATE, "declare_pooled: '%s' was already named as the pooled output; '%s' is a "
|
||||
"second one", prog_.buffers[prog_.pooled_buf].name.c_str(),
|
||||
prog_.buffers[b].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.logits_buf != RAD_NULL_HANDLE) {
|
||||
err(RAD_E_STATE, "declare_pooled: this program already declared '%s' as its logits; a "
|
||||
"program generates or embeds, not both",
|
||||
prog_.buffers[prog_.logits_buf].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const RadBufDecl& d = prog_.buffers[b].decl;
|
||||
if (d.dtype != RAD_F32 || d.domain != RAD_DOMAIN_DEVICE || d.rank != 2 ||
|
||||
d.shape[0] < prog_.ctx.max_seqs || d.shape[1] <= 0) {
|
||||
err(RAD_E_INVAL, "declare_pooled: '%s' must be a device f32 buffer of [>= %lld, dim] -- "
|
||||
"one row a sequence of the step",
|
||||
prog_.buffers[b].name.c_str(), (long long)prog_.ctx.max_seqs);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.pooled_buf = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
/* WHAT THE ENCODER IS. Checked here, at declare, for the drafter's reason: an encoder is exercised
|
||||
* only when a request carries media, so a declaration the engine cannot drive would otherwise
|
||||
@@ -1054,30 +1115,36 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
if (!d) { err(RAD_E_INVAL, "declare_encoder: null declaration"); return RAD_E_INVAL; }
|
||||
if (d->modalities == 0) return RAD_OK; /* declaring nothing is declaring nothing */
|
||||
const char* nm = d->name && *d->name ? d->name : "(unnamed)";
|
||||
if (prog_.encoder.modalities != 0) {
|
||||
err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's encoder; '%s' is "
|
||||
"a second one", prog_.encoder_name.c_str(), nm);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if ((d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) {
|
||||
/* One vision encoder (images and video) and one audio encoder, each at most once. */
|
||||
const bool audio = d->modalities == RAD_MM_AUDIO;
|
||||
if (!audio && (d->modalities & ~(uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)) != 0) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': modalities 0x%x names a kind this engine has no "
|
||||
"processor for", nm, (unsigned)d->modalities);
|
||||
"processor for (an audio encoder serves audio alone)", nm,
|
||||
(unsigned)d->modalities);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RadEncoderDecl& slot = audio ? prog_.audio_encoder : prog_.encoder;
|
||||
std::string& slot_name = audio ? prog_.audio_encoder_name : prog_.encoder_name;
|
||||
if (slot.modalities != 0) {
|
||||
err(RAD_E_STATE, "declare_encoder: '%s' already declared this program's %s encoder; '%s' "
|
||||
"is a second one", slot_name.c_str(), audio ? "audio" : "image and video",
|
||||
nm);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t want = audio ? prog_.ctx.max_audio_frames : prog_.ctx.max_enc_patches;
|
||||
if (d->patch_dim <= 0 || d->merge <= 0 || d->n_embd <= 0) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': patch_dim %lld, merge %lld, n_embd %lld -- all "
|
||||
"three must be positive", nm, (long long)d->patch_dim,
|
||||
(long long)d->merge, (long long)d->n_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->max_patches <= 0 || d->max_patches != prog_.ctx.max_enc_patches ||
|
||||
d->max_patches % d->merge != 0) {
|
||||
if (d->max_patches <= 0 || d->max_patches != want || d->max_patches % d->merge != 0) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': max_patches %lld, but this program was declared "
|
||||
"with max_enc_patches %lld and a merge of %lld. The plugin sized its "
|
||||
"activations with max_enc_patches and the core stages up to that many "
|
||||
"patches a pass; they cannot differ, and a pass's patches must divide into "
|
||||
"whole output rows.", nm, (long long)d->max_patches,
|
||||
(long long)prog_.ctx.max_enc_patches, (long long)d->merge);
|
||||
"with %s %lld and a merge of %lld. The plugin sized its activations with "
|
||||
"that and the core stages up to that many patches a pass; they cannot "
|
||||
"differ, and a pass's patches must divide into whole output rows.", nm,
|
||||
(long long)d->max_patches, audio ? "max_audio_frames" : "max_enc_patches",
|
||||
(long long)want, (long long)d->merge);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->out == RAD_NULL_HANDLE || (size_t)d->out >= prog_.buffers.size()) {
|
||||
@@ -1096,9 +1163,9 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
(long long)d->n_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.encoder = *d;
|
||||
prog_.encoder_name = nm;
|
||||
prog_.encoder.name = nullptr; /* the plugin's storage; encoder_name is the copy */
|
||||
slot = *d;
|
||||
slot_name = nm;
|
||||
slot.name = nullptr; /* the plugin's storage; the name is the copy */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1526,6 +1593,8 @@ void Builder::finish_buffer_liveness() {
|
||||
* empty and nothing that shared with logits before is prevented from doing so. The
|
||||
* undeclared-use guard in core/runtime/issue.cpp is what refuses the untruthful version. */
|
||||
if ((rad_buf)i == prog_.logits_buf && last_op > b.last_use) b.last_use = last_op;
|
||||
/* The pooled output for the same reason: the engine reads it after the last op. */
|
||||
if ((rad_buf)i == prog_.pooled_buf && last_op > b.last_use) b.last_use = last_op;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1573,16 +1642,11 @@ int Builder::finish() {
|
||||
* SPLIT BY DOMAIN, because the two counts mean different things and one total means
|
||||
* neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert
|
||||
* -- reads this line and nothing else, so it has to say which kind it found. */
|
||||
/* A device miss whose op resolved on the HOST for the same band is not a hole -- the
|
||||
* planner runs it there (engine_bringup.cpp's miss_report says the same thing at more
|
||||
* length). Counting it as a device miss makes a deliberately host-only op open every run
|
||||
* with a warning that names a hole there is not. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
for (const Program::Miss& m : prog_.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
size_t dev = 0;
|
||||
for (const Program::Miss& m : prog_.misses)
|
||||
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) ++dev;
|
||||
/* A device miss a host kernel stands in for is not a hole -- the planner runs it there
|
||||
* (Program::device_holes has the rule, engine_bringup.cpp's miss_report the longer
|
||||
* account). Counting it as a device miss makes a deliberately host-only op open every
|
||||
* run with a warning that names a hole there is not. */
|
||||
const size_t dev = prog_.device_holes(device_is_host()).size();
|
||||
/* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp --
|
||||
* so it does not get warned about here either. The device count is the one that means
|
||||
* something to a tool reading this line and nothing else. */
|
||||
@@ -1688,6 +1752,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) {
|
||||
return B(b)->declare_logits(logits);
|
||||
}
|
||||
|
||||
int rad_declare_pooled(RadBuilder* b, rad_buf pooled) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_pooled(pooled);
|
||||
}
|
||||
|
||||
int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_drafter(d);
|
||||
|
||||
+16
-4
@@ -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 */
|
||||
@@ -376,7 +386,9 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
|
||||
* the same resolution as the plugin's. A sampler op that does not resolve is deliberately NOT
|
||||
* a declare failure -- a deployment that never sends `typical_p` does not need a typical
|
||||
* kernel -- so this returning negative means something structural, not a miss. */
|
||||
if (also) {
|
||||
/* NOT FOR AN EMBEDDING PROGRAM (rad_declare_pooled): it samples nothing, so a sampler chain
|
||||
* in it would be ops and buffers no step ever issues. */
|
||||
if (also && b.program().pooled_buf == RAD_NULL_HANDLE) {
|
||||
/* THE WIDTH THE PLUGIN ACTUALLY DECLARED, handed over rather than re-derived. The sampler
|
||||
* needs to know how much vocabulary THIS RANK produces, and the one place that is a fact
|
||||
* is the logits buffer the plugin just named. Computing it a second time from n_vocab and
|
||||
|
||||
+269
-23
@@ -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>
|
||||
|
||||
@@ -39,35 +40,38 @@ static const std::string g_draft_window_help =
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--model", "PATH", "the .rad container, a checkpoint served as it stands, or a\n"
|
||||
"Hugging Face repo id (owner/name), fetched before startup" },
|
||||
{ "--download-dir", "DIR", "where a repo id is fetched to; default\n"
|
||||
"$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
"homes separated by ':' are searched in order, the first winning" },
|
||||
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
|
||||
{ "--kernels", "LIST", "the kernel libraries to use, comma-separated, first wins; unnamed ones are not loaded. Default: every library found" },
|
||||
|
||||
{ "--tp", "N", "tensor-parallel ranks" },
|
||||
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
|
||||
"none at 8" },
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n"
|
||||
"and 4, none at 8" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
|
||||
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
|
||||
"asks the driver, on requires peer access and stops without\n"
|
||||
"it, off exchanges through pinned host memory" },
|
||||
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
|
||||
{ "--busy-prefill-chunk", "MODE", "a prefill chunk's share of a step that has other work: auto\n"
|
||||
"(default) leaves decode rows and new requests their room,\n"
|
||||
"off takes the whole step, N holds the chunk to N tokens" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
|
||||
" keeps it in the pinned host pool, read over the link in place;\n"
|
||||
" auto keeps it on the card unless the KV cache could then not\n"
|
||||
" hold one --max-model-len sequence. disk is refused: the lookup\n"
|
||||
" writes the card's activations, which no host read can reach" },
|
||||
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
|
||||
" pins it in host memory beside --host-pool-mib, read over the\n"
|
||||
" link in place; by default a model whose output head reads the\n"
|
||||
" table, or a host without the memory, keeps it on the card" },
|
||||
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
|
||||
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
|
||||
" vram puts all of it on every card; ram copies it into\n"
|
||||
@@ -192,7 +196,10 @@ static const Flag g_flags[] = {
|
||||
{ "--video-fps", "F", "frames sampled per second of video" },
|
||||
{ "--video-min-frames", "N", "the fewest frames sampled from a video" },
|
||||
{ "--video-max-frames", "N", "the most frames sampled from a video" },
|
||||
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" },
|
||||
{ "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n"
|
||||
" budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" },
|
||||
{ "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n"
|
||||
" default the container's); a request's `image_tokens` overrides it" },
|
||||
{ "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n"
|
||||
" (default 67108864). The media flags above default to what the container\n"
|
||||
" states, and do nothing for a model that takes no media" },
|
||||
@@ -223,10 +230,19 @@ static const Flag g_flags[] = {
|
||||
|
||||
void config_usage(const char* argv0) {
|
||||
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
|
||||
/* A help text's continuation lines start under its first line, whatever indentation the
|
||||
* string itself carries. */
|
||||
for (const Flag& f : g_flags) {
|
||||
char left[64];
|
||||
snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
|
||||
fprintf(stderr, " %-32s %s\n", left, f.help);
|
||||
std::string help;
|
||||
for (const char* p = f.help; *p; ++p) {
|
||||
help += *p;
|
||||
if (*p != '\n') continue;
|
||||
help.append(35, ' ');
|
||||
while (p[1] == ' ') ++p;
|
||||
}
|
||||
fprintf(stderr, " %-32s %s\n", left, help.c_str());
|
||||
}
|
||||
fprintf(stderr,
|
||||
"\nEvery pool is budgeted explicitly. The trade between KV blocks and resident weights\n"
|
||||
@@ -373,6 +389,7 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (S("-v")) log_set_level(Log::Debug);
|
||||
else if (S("-vv")) log_set_level(Log::Trace);
|
||||
else if (S("--model")) { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
|
||||
else if (S("--download-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
|
||||
else if (S("--radiance-home")) { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
|
||||
else if (S("--kernels")) { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = split_commas(v); }
|
||||
else if (S("--tp")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp = atoi(v); }
|
||||
@@ -391,6 +408,18 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
|
||||
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
|
||||
else if (S("--busy-prefill-chunk")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
char* end = nullptr;
|
||||
const long long n = std::strtoll(v, &end, 10);
|
||||
if (!std::strcmp(v, "auto")) c->busy_prefill_chunk = -1;
|
||||
else if (!std::strcmp(v, "off")) c->busy_prefill_chunk = 0;
|
||||
else if (end && end != v && *end == '\0' && n > 0) c->busy_prefill_chunk = n;
|
||||
else {
|
||||
RAD_ERR("--busy-prefill-chunk takes auto, off or a positive token count, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
|
||||
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
|
||||
else if (S("--rope-scaling")) {
|
||||
@@ -405,8 +434,16 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->rope_scaling = v;
|
||||
}
|
||||
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
|
||||
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
|
||||
/* THE TWO POOLS ARE THE BUDGET RESOLVER'S, always (core/mem/vram_budget.h). A launch
|
||||
* line that tries to size them is told which flags move the split, rather than "unknown
|
||||
* option". */
|
||||
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
|
||||
RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
|
||||
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
|
||||
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay "
|
||||
"on the card", a.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
|
||||
* "-mib" is the unit, which every other size flag in this list also spells out. Both
|
||||
* parse to the same field. */
|
||||
@@ -425,11 +462,20 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
TablePlacement p;
|
||||
if (!parse_table_placement(v, &p)) {
|
||||
/* The embedding has two tiers: its lookup writes activations the card reads, which a
|
||||
* host kernel reading the container cannot reach, so there is no disk -- and with
|
||||
* ram the default wherever it can be honoured, nothing left for auto to choose. */
|
||||
if (emb && (!parse_table_placement(v, &p) ||
|
||||
(p != TablePlacement::Ram && p != TablePlacement::Vram))) {
|
||||
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!emb && !parse_table_placement(v, &p)) {
|
||||
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
(emb ? c->embedding_placement : c->ngram_placement) = p;
|
||||
if (emb) c->embedding_placement_given = true;
|
||||
}
|
||||
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
|
||||
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
|
||||
@@ -681,6 +727,12 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
if (!(d > 0.0)) { RAD_ERR("--video-fps must be > 0, not '%s'", v); return RAD_E_INVAL; }
|
||||
c->video_fps = d;
|
||||
}
|
||||
else if (S("--image-tokens")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
int64_t n = 0;
|
||||
if (!parse_int(a.c_str(), v, 1, INT32_MAX, &n)) return RAD_E_INVAL;
|
||||
c->image_tokens = (int32_t)n;
|
||||
}
|
||||
else if (S("--video-min-frames") || S("--video-max-frames") || S("--video-max-frame-tokens")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
int64_t n = 0;
|
||||
@@ -704,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.
|
||||
@@ -718,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
|
||||
@@ -726,12 +786,12 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
* rank the one that IS installed behind the reference implementation, which matches every op
|
||||
* and would answer for all of them.
|
||||
*
|
||||
* An empty hierarchy is not "no order". The loader orders what it finds: everything named by
|
||||
* --kernels or RADIANCE_KERNELS first, then every other plugin, then the reference library
|
||||
* last by construction because it matches anything (core/plugin/loader.cpp). So dropping a
|
||||
* kernel library into $RADIANCE_HOME/kernels is enough to be used, on any card, with no
|
||||
* configuration -- and naming one ahead of another is what settles a tie between two that
|
||||
* both serve an op. */
|
||||
* An empty hierarchy is not "no order". The loader loads everything it finds and orders it,
|
||||
* the reference library last by construction because it matches anything
|
||||
* (core/plugin/loader.cpp). So dropping a kernel library into $RADIANCE_HOME/kernels is
|
||||
* enough to be used, on any card, with no configuration. A list names the libraries to use:
|
||||
* only those load, in its order, so naming one ahead of another settles a tie between two that
|
||||
* both serve an op and leaving one out keeps it out. */
|
||||
if (c->model.empty()) {
|
||||
RAD_ERR("--model is required");
|
||||
return RAD_E_INVAL;
|
||||
@@ -799,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 */
|
||||
+1040
-13
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -376,6 +484,10 @@ const DeviceBackend* hip_backend_if_present(void);
|
||||
const DeviceBackend* aql_backend_if_present(void);
|
||||
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
|
||||
int64_t aql_pageable_bytes(void);
|
||||
/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
|
||||
* this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
|
||||
* no card. The host backend's code_mark in a HIP build. */
|
||||
size_t aql_code_registered(void);
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ the error slot */
|
||||
|
||||
+119
-1
@@ -67,16 +67,52 @@ 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 -- 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;
|
||||
int v = -1;
|
||||
const int got = std::fscanf(f, "%d", &v);
|
||||
std::fclose(f);
|
||||
if (got == 1 && v == 0)
|
||||
RAD_WARN("device: amdgpu cwsr_enable is 0, so the driver cannot preempt a running queue: "
|
||||
"any queue eviction (host memory the card maps, moved under memory pressure) waits "
|
||||
"for a queue a serve never lets drain, and ends in a GPU hang and reset. Set "
|
||||
"amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
|
||||
}
|
||||
|
||||
/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
|
||||
* registration hooks are this build's own exported symbols and see every dlopen'ed kernel
|
||||
* library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
|
||||
* which library brought device code. An engine serving here leaves that library's device rows out
|
||||
* of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
|
||||
static DeviceBackend g_host_beside_hip;
|
||||
#endif
|
||||
|
||||
static const DeviceBackend* select_backend() {
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
if (const DeviceBackend* b = aql_backend_if_present()) {
|
||||
RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(),
|
||||
device_inventory(b).c_str());
|
||||
warn_cwsr_off();
|
||||
return b;
|
||||
}
|
||||
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
|
||||
#endif
|
||||
g_host_beside_hip = *host_backend();
|
||||
g_host_beside_hip.code_mark = aql_code_registered;
|
||||
const DeviceBackend* b = &g_host_beside_hip;
|
||||
#else
|
||||
const DeviceBackend* b = host_backend();
|
||||
#endif
|
||||
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
|
||||
return b;
|
||||
}
|
||||
@@ -501,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;
|
||||
@@ -555,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
@@ -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 */
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
+438
-35
@@ -17,6 +17,7 @@
|
||||
#include "sched/scheduler.h"
|
||||
#include "server/adapters.h"
|
||||
#include "server/server.h"
|
||||
#include "server/sink.h"
|
||||
#include "server/liveview.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
@@ -33,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;
|
||||
@@ -59,6 +64,8 @@ Engine::~Engine() {
|
||||
* says nothing is worse than no flag at all. */
|
||||
if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile();
|
||||
for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
|
||||
if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED);
|
||||
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();
|
||||
@@ -77,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();
|
||||
@@ -257,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
|
||||
@@ -268,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) {
|
||||
@@ -316,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);
|
||||
@@ -408,7 +446,7 @@ int Engine::step_loop() {
|
||||
std::vector<uint64_t> cancel;
|
||||
/* Not in the KL mode: its scored rows are copied out of the logits buffer after the step is
|
||||
* collected, and a pass issued ahead would have overwritten them by then. */
|
||||
pipelining_ = !cfg_.kld() && drafter_.kind != RAD_DRAFT_BLOCK &&
|
||||
pipelining_ = !cfg_.kld() && !embedding_ && drafter_.kind != RAD_DRAFT_BLOCK &&
|
||||
(serial_drafting() || cfg_.n_spec <= 0);
|
||||
const bool t_on = (int)log_level() >= (int)Log::Debug;
|
||||
/* Read once. See the block in the idle branch below for what it is for. */
|
||||
@@ -572,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
|
||||
@@ -582,7 +621,7 @@ int Engine::step_loop() {
|
||||
* rank threads are reading through batch_for() while this runs; they are applied after the
|
||||
* join, ahead of collect_step. */
|
||||
auto stage_sampler = [&]() -> int {
|
||||
if (!so.reqs.empty()) {
|
||||
if (!so.reqs.empty() && !embedding_) {
|
||||
/* PER-REQUEST SAMPLER STATE IS BUILT HERE, ON FIRST SIGHT. A grammar arrives compiled
|
||||
* from admission and is only positioned here; a DRY sequence-breaker set is resolved
|
||||
* against the vocabulary once. Both belong off the step path, and this is the first
|
||||
@@ -703,7 +742,8 @@ int Engine::step_loop() {
|
||||
build_status_ = RAD_OK;
|
||||
}
|
||||
if (const int ps = prepare_release(b); ps < 0) return fail_loop(ps);
|
||||
issue_what_.store(kIssueAll, std::memory_order_release);
|
||||
/* An embedding program has no sampler to issue behind its pass. */
|
||||
issue_what_.store(embedding_ ? kIssueModel : kIssueAll, std::memory_order_release);
|
||||
step_batch_.store(b, std::memory_order_release);
|
||||
barrier_->arrive_and_wait(); /* release the ranks */
|
||||
{
|
||||
@@ -805,7 +845,7 @@ int Engine::step_loop() {
|
||||
* wait, commit and staging all happen while it runs. */
|
||||
st = issue_ahead(&ahead);
|
||||
if (st < 0) return fail_loop(st);
|
||||
st = collect_step(b, so);
|
||||
st = embedding_ ? collect_pooled(b, so) : collect_step(b, so);
|
||||
if (t_on) phase_mark(PH_COLLECT);
|
||||
if (st < 0) return fail_loop(st);
|
||||
if (cfg_.kld()) {
|
||||
@@ -864,6 +904,10 @@ int Engine::step_loop() {
|
||||
res.n_accepted = so.accepted.data();
|
||||
res.token = so.token.data();
|
||||
res.eos = so.eos.data();
|
||||
if (!so.lp.empty()) {
|
||||
res.lp = so.lp.data();
|
||||
res.first_row = so.first_row.data();
|
||||
}
|
||||
st = sched_.commit(res);
|
||||
if (t_on) phase_mark(PH_COMMIT);
|
||||
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
|
||||
@@ -947,10 +991,140 @@ int Engine::collect_issue(const RadBatch* b, StepOut& so) {
|
||||
}
|
||||
|
||||
int Engine::mark_step_end(const RadBatch* b, StepOut& so) {
|
||||
if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so));
|
||||
if (embedding_) RAD_TRY(collect_pooled_issue(b, so));
|
||||
else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(b, so));
|
||||
return rad_event_record(step_end_, ranks_[0]->ctx.stream());
|
||||
}
|
||||
|
||||
/* AN EMBEDDING STEP'S ANSWER, ON ITS WAY TO THE HOST: the pooled buffer's first n_seq rows, copied
|
||||
* into pinned memory behind the pass on rank 0's stream -- every rank holds the same vectors, so
|
||||
* one copy is the answer. Nothing waits here; collect_pooled does, once. */
|
||||
int Engine::collect_pooled_issue(const RadBatch* b, StepOut& /*so*/) {
|
||||
if (b->n_seq <= 0) return RAD_OK;
|
||||
Rank& r0 = *ranks_[0];
|
||||
const void* src = r0.ctx.buf_ptr(r0.program.pooled_buf);
|
||||
if (!src) {
|
||||
RAD_ERR("the pooled output was declared but never planned");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
return rad_memcpy_async(pooled_host_, src,
|
||||
(int64_t)b->n_seq * pooled_dim_ * (int64_t)sizeof(float),
|
||||
r0.ctx.stream());
|
||||
}
|
||||
|
||||
/* Each sequence's vector to its request's sink, and the step's three per-sequence arrays set so
|
||||
* the commit FINISHES every request it carried: an embedding request is one step long. The token
|
||||
* is never emitted (Request::embed), so its value is irrelevant; eos is what ends the request. */
|
||||
int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
|
||||
const StepPlan& plan = sched_.plan();
|
||||
so.token.assign(plan.e.size(), 0);
|
||||
so.accepted.assign(plan.e.size(), 0);
|
||||
so.eos.assign(plan.e.size(), 1);
|
||||
if (plan.e.empty()) return RAD_OK;
|
||||
RAD_TRY(rad_event_sync(step_end_));
|
||||
if ((int64_t)plan.e.size() != (int64_t)b->n_seq) {
|
||||
RAD_ERR("an embedding step planned %zu sequences and its batch carries %lld",
|
||||
plan.e.size(), (long long)b->n_seq);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
for (size_t i = 0; i < plan.e.size(); ++i) {
|
||||
const StepEntry& e = plan.e[i];
|
||||
if (!e.req) continue;
|
||||
if (!e.produces_token) {
|
||||
RAD_ERR("an embedding step carried part of request %llu's input; an encoder must see "
|
||||
"the whole of it in one step", (unsigned long long)e.req->id);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const float* row = pooled_host_ + (int64_t)i * pooled_dim_;
|
||||
server::sink_embedding(e.req->sink, row, pooled_dim_);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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
|
||||
* answers by failing that request with the reason, and every other sequence in the batch goes on.
|
||||
* A row outside the step, or one that was never staged for logprobs, is the engine's own fault. */
|
||||
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
|
||||
if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
|
||||
if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
|
||||
TokenLogprobs& lp = so.lp[(size_t)row];
|
||||
const int s = ranks_[0]->sampler.logprobs_for(row, token, &lp);
|
||||
if (s == RAD_E_INVAL) { lp = TokenLogprobs{}; return RAD_OK; }
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Wait for the sampled ids and turn them into the three per-sequence arrays the scheduler wants.
|
||||
* This is the ONE host synchronisation on the step path: the host needs the tokens to commit them
|
||||
* and to stream them. Everything else in a step is enqueued and never waited on (spec §5.4). */
|
||||
@@ -959,6 +1133,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
so.token.assign(plan.e.size(), 0);
|
||||
so.accepted.assign(plan.e.size(), 0);
|
||||
so.eos.assign(plan.e.size(), 0);
|
||||
so.lp.clear();
|
||||
if (so.n_rows <= 0) return RAD_OK;
|
||||
|
||||
so.rows.resize((size_t)so.n_rows);
|
||||
@@ -967,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()) {
|
||||
@@ -1048,6 +1224,11 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
so.accepted[i] = acc;
|
||||
so.token[i] = out[acc];
|
||||
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
|
||||
/* Each emitted token's logprobs from its own row: an accepted draft is the token the
|
||||
* target drew at its position, so its row is the distribution it came from. */
|
||||
if (e.req && e.req->sp.n_probs >= 0)
|
||||
for (int32_t j = 0; j <= acc; ++j)
|
||||
RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
|
||||
/* EVERY token that leaves, in order: the grammar's state has to advance over the
|
||||
* accepted drafts too, or the next step's mask is built n_accepted tokens behind.
|
||||
* Bounded by the truncated `acc`, so it sees exactly the tokens the client does. */
|
||||
@@ -1073,6 +1254,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
|
||||
}
|
||||
so.token[i] = so.rows[(size_t)so.first_row[i]];
|
||||
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
|
||||
if (e.req && e.req->sp.n_probs >= 0)
|
||||
RAD_TRY(row_logprobs(so, so.first_row[i], so.token[i]));
|
||||
/* The grammar must see the token it just emitted, or the next step's mask is built from a
|
||||
* state one token behind the sequence. EVERY rank, not just rank 0: each rank builds the
|
||||
* mask for its own vocabulary shard from its own automaton, so a rank whose grammar did
|
||||
@@ -1206,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 ||
|
||||
@@ -1221,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;
|
||||
@@ -1493,12 +1681,46 @@ int Engine::serve() {
|
||||
RAD_ERR("serve: start() has not run, or stopped at --debug-graph");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE) {
|
||||
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits), so there is "
|
||||
"nothing to sample. An encoder-only plugin cannot serve completions.",
|
||||
plugins_.arch_plugin.c_str());
|
||||
embedding_ = ranks_[0]->program.pooled_buf != RAD_NULL_HANDLE;
|
||||
if (ranks_[0]->program.logits_buf == RAD_NULL_HANDLE && !embedding_) {
|
||||
RAD_ERR("the '%s' plugin declared no logits buffer (rad_declare_logits) and no pooled "
|
||||
"output (rad_declare_pooled), so a step produces nothing anyone can read. An "
|
||||
"encoder-only plugin cannot serve.", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (embedding_) {
|
||||
if (cfg_.kld() || cfg_.n_spec > 0) {
|
||||
RAD_ERR("the '%s' plugin is an embedding model: it generates nothing, so --kld and "
|
||||
"speculative decoding have nothing to work on", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const Program& p0 = ranks_[0]->program;
|
||||
pooled_dim_ = p0.buffers[p0.pooled_buf].decl.shape[1];
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) {
|
||||
const Program& pi = ranks_[i]->program;
|
||||
if (pi.pooled_buf == RAD_NULL_HANDLE ||
|
||||
pi.buffers[pi.pooled_buf].decl.shape[1] != pooled_dim_) {
|
||||
RAD_ERR("rank %zu declared a different pooled output from rank 0's", i);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
pooled_host_ = static_cast<float*>(
|
||||
rad_dev_alloc(cfg_.max_seqs * pooled_dim_ * (int64_t)sizeof(float),
|
||||
RAD_MEM_HOST_PINNED));
|
||||
if (!pooled_host_) {
|
||||
RAD_ERR("no pinned host memory for a step's pooled rows (%lld x %lld f32)",
|
||||
(long long)cfg_.max_seqs, (long long)pooled_dim_);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
/* NO PREFIX CACHE: an encoder keeps no KV to reuse, and attending both ways means a
|
||||
* shared prefix does not even compute to the same rows. */
|
||||
cfg_.prefix_cache = false;
|
||||
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);
|
||||
}
|
||||
|
||||
/* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on
|
||||
* every rank: every rank carves the same block count (Engine::configure_kv caps each at the
|
||||
@@ -1642,6 +1864,16 @@ int Engine::serve() {
|
||||
for (auto& rk : ranks_)
|
||||
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
|
||||
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
|
||||
/* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS. A prefill chunk the scheduler holds back for
|
||||
* other work in the step (--busy-prefill-chunk) is kept at or above it: under it every routed
|
||||
* layer reads its pooled experts synchronously, which costs a long prefill far more than the
|
||||
* step it shares saves. The largest over the ranks, since the step waits for the slowest. */
|
||||
{
|
||||
int64_t stage_rows = 0;
|
||||
for (auto& rk : ranks_)
|
||||
if (rk->stager.enabled()) stage_rows = std::max(stage_rows, rk->stager.min_rows());
|
||||
sched_.set_stage_rows(stage_rows);
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
|
||||
|
||||
@@ -1655,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
|
||||
@@ -1836,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;
|
||||
|
||||
@@ -1883,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());
|
||||
@@ -2050,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
|
||||
@@ -2128,8 +2368,42 @@ int Engine::run_server() {
|
||||
/* load_from_vocab warns on its own when the template is missing or will not compile; all we
|
||||
* decide here is whether the endpoint exists. The reply format is the architecture plugin's
|
||||
* when it declares one, and the template's otherwise. */
|
||||
/* WHAT AN EMBEDDING MODEL SERVES: /v1/embeddings, and no chat. */
|
||||
/* Its named prompts are the checkpoint's sentence-transformers configuration
|
||||
* (`sentence_transformers.prompts.*`), and a `messages` input renders through its chat
|
||||
* template. */
|
||||
struct EmbedInfo final : server::IEmbedder {
|
||||
int64_t d = 0, n = 0;
|
||||
const RadModelMeta* meta = nullptr;
|
||||
server::IChatTemplate* tpl = nullptr;
|
||||
int64_t dim() const override { return d; }
|
||||
int64_t max_input() const override { return n; }
|
||||
bool prompt(const std::string& name, std::string* text) const override {
|
||||
const std::string key = "sentence_transformers.prompts." + name;
|
||||
const char* v = rad_meta_gets(meta, key.c_str(), nullptr);
|
||||
if (!v) return false;
|
||||
*text = v;
|
||||
return true;
|
||||
}
|
||||
std::string default_prompt() const override {
|
||||
const char* v = rad_meta_gets(meta, "sentence_transformers.default_prompt_name", "");
|
||||
return v ? std::string(v) : std::string();
|
||||
}
|
||||
server::IChatTemplate* message_template() const override { return tpl; }
|
||||
} embed_info;
|
||||
embed_info.d = pooled_dim_;
|
||||
embed_info.n = cfg_.max_tok;
|
||||
embed_info.meta = &meta_;
|
||||
if (embedding_) d.embed = &embed_info;
|
||||
|
||||
const RadChatFormat* declared_format = rad_tools_chat_format(plugins_, meta_);
|
||||
if (vocab_ && !vocab_->chat_template().empty() &&
|
||||
if (embedding_) {
|
||||
/* No chat endpoint: the model's template, when it has one, renders a `messages` input. */
|
||||
if (vocab_ && !vocab_->chat_template().empty() &&
|
||||
chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
|
||||
chat_bridge.ready())
|
||||
embed_info.tpl = &chat_bridge;
|
||||
} else if (vocab_ && !vocab_->chat_template().empty() &&
|
||||
chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 &&
|
||||
chat_bridge.ready()) {
|
||||
d.chat = &chat_bridge;
|
||||
@@ -2139,6 +2413,8 @@ 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;
|
||||
@@ -2148,12 +2424,30 @@ 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();
|
||||
/* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request
|
||||
* against the context, so it needs one to resolve against. */
|
||||
if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens;
|
||||
@@ -2169,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;
|
||||
@@ -2185,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
|
||||
@@ -2202,15 +2502,45 @@ int Engine::run_server() {
|
||||
}
|
||||
vc.max_patches = encd.max_patches;
|
||||
/* THE COMMAND LINE OVER THE CONTAINER, field by field, and the result checked as a whole:
|
||||
* a minimum stated alone can land above the maximum the container states. */
|
||||
if (cfg_.image_min_pixels) vc.image_min_pixels = *cfg_.image_min_pixels;
|
||||
if (cfg_.image_max_pixels) vc.image_max_pixels = *cfg_.image_max_pixels;
|
||||
if (cfg_.video_min_pixels) vc.video_min_pixels = *cfg_.video_min_pixels;
|
||||
if (cfg_.video_max_pixels) vc.video_max_pixels = *cfg_.video_max_pixels;
|
||||
* a minimum stated alone can land above the maximum the container states.
|
||||
*
|
||||
* A TOKEN-BUDGET PROCESSOR (Gemma 4's) sizes images and frames by soft tokens, not pixel
|
||||
* bands: the band flags would do nothing on it, so they are refused by name, and the
|
||||
* budgets come from --image-tokens and --video-max-frame-tokens. */
|
||||
/* 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) {
|
||||
RAD_ERR("media: this model's processor sizes images and video frames by a token "
|
||||
"budget, so --image-min/max-pixels, --video-min/max-pixels and "
|
||||
"--video-min-frames do nothing; use --image-tokens and "
|
||||
"--video-max-frame-tokens");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cfg_.image_tokens) vc.image_soft_tokens = *cfg_.image_tokens;
|
||||
if (cfg_.video_max_frame_tokens) vc.video_soft_tokens = *cfg_.video_max_frame_tokens;
|
||||
} else {
|
||||
if (cfg_.image_tokens) {
|
||||
RAD_ERR("media: --image-tokens is a token budget, and this model's processor "
|
||||
"sizes images by pixels (--image-min-pixels, --image-max-pixels)");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (cfg_.image_min_pixels) vc.image_min_pixels = *cfg_.image_min_pixels;
|
||||
if (cfg_.image_max_pixels) vc.image_max_pixels = *cfg_.image_max_pixels;
|
||||
if (cfg_.video_min_pixels) vc.video_min_pixels = *cfg_.video_min_pixels;
|
||||
if (cfg_.video_max_pixels) vc.video_max_pixels = *cfg_.video_max_pixels;
|
||||
if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames;
|
||||
if (cfg_.video_max_frame_tokens) vc.max_frame_rows = *cfg_.video_max_frame_tokens;
|
||||
}
|
||||
if (cfg_.video_fps) vc.fps = *cfg_.video_fps;
|
||||
if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames;
|
||||
if (cfg_.video_max_frames) vc.max_frames = *cfg_.video_max_frames;
|
||||
if (cfg_.video_max_frame_tokens) vc.max_frame_rows = *cfg_.video_max_frame_tokens;
|
||||
if (cfg_.max_source_pixels) vc.max_source_pixels = *cfg_.max_source_pixels;
|
||||
if (cfg_.media_flags_set() && vc.check(&why) < 0) {
|
||||
RAD_ERR("media: the media flags and what the container states disagree: %s",
|
||||
@@ -2232,18 +2562,50 @@ int Engine::run_server() {
|
||||
(long long)encd.patch_dim, (long long)encd.merge);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (vc.family == mm::Family::Gemma4 &&
|
||||
(int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge >
|
||||
encd.max_patches) {
|
||||
RAD_ERR("media: an image of %d soft tokens or a video frame of %d is more patches than "
|
||||
"one encoder pass holds (--mm-max-patches %lld)", vc.image_soft_tokens,
|
||||
vc.video_soft_tokens, (long long)encd.max_patches);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
mm_proc = std::make_unique<mm::Processor>();
|
||||
RAD_TRY(mm_proc->init(vc, [&tok_bridge](const std::string& t) {
|
||||
return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false);
|
||||
}));
|
||||
mm_bridge = std::make_unique<server::MultimodalBridge>(mm_proc.get(), encd.modalities);
|
||||
d.mm = mm_bridge.get();
|
||||
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 "
|
||||
"frames a second, at most %d frames; %lld patches a pass",
|
||||
o.allow_image ? "images" : "", o.allow_video ? " and video" : "",
|
||||
ranks_[0]->program.encoder_name.c_str(), mm_proc->config().image_soft_tokens,
|
||||
mm_proc->config().video_soft_tokens, mm_proc->config().fps,
|
||||
mm_proc->config().max_frames, (long long)encd.max_patches);
|
||||
else
|
||||
RAD_INFO("media: %s%s through '%s'; an image resizes to at most %lld pixels (%lld "
|
||||
"patches a pass), a video to %lld pixels over all its frames",
|
||||
@@ -2252,13 +2614,49 @@ int Engine::run_server() {
|
||||
(long long)mm_proc->config().image_max_pixels, (long long)encd.max_patches,
|
||||
(long long)mm_proc->config().video_max_pixels);
|
||||
}
|
||||
/* AUDIO, WHEN THE PROGRAM DECLARED AN AUDIO ENCODER: the feature extractor reads its framing
|
||||
* from the container, and the encoder states the frame width and the frames an output row. */
|
||||
const RadEncoderDecl& aend = ranks_[0]->program.audio_encoder;
|
||||
if (aend.modalities != 0) {
|
||||
mm::AudioConfig ac;
|
||||
std::string why;
|
||||
if (ac.from_meta(meta_, &why) < 0) {
|
||||
RAD_ERR("the '%s' encoder has no feature extractor: %s",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (ac.n_mels != aend.patch_dim) {
|
||||
RAD_ERR("the container's feature extractor makes %d-bin frames; the '%s' encoder takes "
|
||||
"%lld", ac.n_mels, ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
(long long)aend.patch_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
ac.merge = (int32_t)aend.merge;
|
||||
ac.max_frames = aend.max_patches;
|
||||
if (!mm_proc) mm_proc = std::make_unique<mm::Processor>();
|
||||
RAD_TRY(mm_proc->init_audio(ac));
|
||||
o.allow_audio = true;
|
||||
if (mm::decoder_available())
|
||||
RAD_INFO("media: audio through '%s'; a clip is cut at %.3g s, %d mel bins a %d ms frame, "
|
||||
"%d frames a token; %lld frames a pass",
|
||||
ranks_[0]->program.audio_encoder_name.c_str(),
|
||||
(double)ac.max_samples / (double)ac.rate, ac.n_mels,
|
||||
ac.hop * 1000 / ac.rate, ac.merge, (long long)aend.max_patches);
|
||||
}
|
||||
if (mm_proc) {
|
||||
mm_bridge = std::make_unique<server::MultimodalBridge>(
|
||||
mm_proc.get(), encd.modalities | aend.modalities);
|
||||
d.mm = mm_bridge.get();
|
||||
}
|
||||
|
||||
if (encd.modalities == 0 && cfg_.media_flags_set())
|
||||
if (encd.modalities == 0 && aend.modalities == 0 && cfg_.media_flags_set())
|
||||
RAD_WARN("media: the media flags do nothing here -- this model %s",
|
||||
cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)"
|
||||
: "takes no images or video");
|
||||
|
||||
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
|
||||
@@ -2306,9 +2704,14 @@ int Engine::run_server() {
|
||||
why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port,
|
||||
d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
|
||||
o.api_key.empty() ? "" : " -- a bearer key is required");
|
||||
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");
|
||||
else
|
||||
RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port,
|
||||
d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
|
||||
o.api_key.empty() ? "" : " -- a bearer key is required");
|
||||
|
||||
/* THE LIVE VIEW (spec §16), constructed here and nowhere else.
|
||||
*
|
||||
|
||||
+80
-2
@@ -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
|
||||
@@ -134,8 +149,7 @@ private:
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
* (engine_bringup.cpp says how auto chooses). */
|
||||
int resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
|
||||
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
|
||||
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
|
||||
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
|
||||
@@ -167,6 +181,9 @@ private:
|
||||
std::vector<int32_t> token; /* [n_seq] */
|
||||
std::vector<int32_t> accepted; /* [n_seq] */
|
||||
std::vector<uint8_t> eos; /* [n_seq] */
|
||||
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
|
||||
* empty on a step with none. */
|
||||
std::vector<TokenLogprobs> lp;
|
||||
};
|
||||
|
||||
/* The text frontend, loaded out of the container. `vocab_view_` is what the sampler's
|
||||
@@ -216,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;
|
||||
@@ -238,6 +263,7 @@ private:
|
||||
* wait left until after them. */
|
||||
int collect_issue(const RadBatch* b, StepOut& so);
|
||||
int collect_step(const RadBatch* b, StepOut& so);
|
||||
int row_logprobs(StepOut& so, int32_t row, int32_t token);
|
||||
/* WHERE THE STEP ENDS ON THE CARD: after its last draft pass and the copies the host reads,
|
||||
* and before the step issued ahead of it. collect_step waits for this and not for the
|
||||
* stream, so the card runs the next step while the host commits this one. */
|
||||
@@ -269,6 +295,15 @@ private:
|
||||
~Readback();
|
||||
};
|
||||
Readback readback_;
|
||||
/* AN EMBEDDING PROGRAM (rad_declare_pooled): no sampler, and a step's answer is the pooled
|
||||
* buffer's first n_seq rows rather than sampled ids. `pooled_host_` is their pinned landing
|
||||
* place, [max_seqs, pooled_dim_] f32; collect_pooled copies them there behind the step and
|
||||
* hands each row to its request's sink after the step's one wait. */
|
||||
bool embedding_ = false;
|
||||
int64_t pooled_dim_ = 0;
|
||||
float* pooled_host_ = nullptr;
|
||||
int collect_pooled_issue(const RadBatch* b, StepOut& so);
|
||||
int collect_pooled(const RadBatch* b, StepOut& so);
|
||||
bool serial_drafting() const;
|
||||
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
|
||||
int issue_serial_drafter(int step, const RadBatch* b, StepOut& so);
|
||||
@@ -372,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. */
|
||||
|
||||
+304
-150
@@ -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"
|
||||
@@ -52,15 +53,17 @@ namespace rad {
|
||||
/* ================================================================== the miss report */
|
||||
/* WHAT DID NOT RESOLVE, in the three shapes the three answers want.
|
||||
*
|
||||
* A DEVICE miss WITH NO HOST KERNEL EITHER is a hole. The band exists, a request can land in it,
|
||||
* and the step that does fails at ISSUE rather than here -- declare completes either way -- so
|
||||
* every one gets a line of its own carrying the geometry and the constraint that refused it.
|
||||
* A DEVICE miss NO HOST KERNEL STANDS IN FOR is a hole (Program::device_holes has the rule). The
|
||||
* band exists and a request can land in it, so the engine refuses to start on one rather than
|
||||
* serve until the first step that does -- and every one gets a line of its own carrying the
|
||||
* geometry and the constraint that refused it.
|
||||
*
|
||||
* A DEVICE miss whose op DID resolve on the host is not a hole at all. The planner puts that op's
|
||||
* A DEVICE miss a host kernel stands in for is not a hole at all. The planner puts that op's
|
||||
* arithmetic on the host and its weights in the container's mapping, which is how `embed_lookup_q`
|
||||
* serves a table too large to copy into VRAM when no device kernel for it is loaded. Reporting
|
||||
* that as fatal produces an error nobody believes, and an error nobody believes is how a real one
|
||||
* goes unread.
|
||||
* goes unread. An op with no weights has nothing to place, so on a card its host kernel does not
|
||||
* stand in: paged attention reads a cache in VRAM, and only a device kernel can.
|
||||
*
|
||||
* A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU
|
||||
* it is the ordinary case rather than news: most ops have no host implementation and never will.
|
||||
@@ -70,7 +73,7 @@ namespace rad {
|
||||
* with thousands of lines of `E` that are all host misses, and a real device hole is invisible
|
||||
* among them. */
|
||||
struct MissReport {
|
||||
std::vector<std::string> device; /* one line each; fatal at issue */
|
||||
std::vector<std::string> device; /* one line each; the engine does not start */
|
||||
std::string host; /* one line, or empty */
|
||||
/* Device bands whose op DOES have a host kernel. Not a hole: the planner runs such an op on
|
||||
* the host and pins its weights there (Tier::Mapped), which is the whole of how a table too
|
||||
@@ -78,29 +81,43 @@ struct MissReport {
|
||||
* operator has to learn to ignore -- and an error nobody believes is how a real one goes
|
||||
* unread. */
|
||||
std::string host_only;
|
||||
/* A hole is an all-reduce instance declared on the lossy wire (`exact` 0, which the model
|
||||
* plugin derives from --tp-wire, rad_builder.h). The libraries may serve that world size on
|
||||
* the exact wire, so the refusal names the flag that asks for it. */
|
||||
bool lossy_wire = false;
|
||||
|
||||
bool operator==(const MissReport& o) const {
|
||||
return device == o.device && host == o.host && host_only == o.host_only;
|
||||
return device == o.device && host == o.host && host_only == o.host_only &&
|
||||
lossy_wire == o.lossy_wire;
|
||||
}
|
||||
};
|
||||
|
||||
static MissReport miss_report(const Program& p) {
|
||||
static MissReport miss_report(const Program& p, bool host_backend) {
|
||||
MissReport r;
|
||||
std::vector<std::string> host_ops; /* in first-seen order */
|
||||
std::map<std::string, std::string> host_spans; /* op -> "M <= 64, M in (64, 512]" */
|
||||
|
||||
/* (op, band) pairs the HOST could not serve either. A device miss that is in this set is a
|
||||
* hole; one that is not has a host kernel standing behind it. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
const std::vector<const Program::Miss*> holes = p.device_holes(host_backend);
|
||||
std::set<std::pair<int32_t, std::string>> no_host; /* (instance, band) with no host kernel */
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
|
||||
for (const Program::Miss* m : holes) {
|
||||
long long exact = 1;
|
||||
if (m->index > 0 && (size_t)m->index < p.ops.size() &&
|
||||
p.ops[(size_t)m->index].base.get_i("exact", &exact) && exact == 0)
|
||||
r.lossy_wire = true;
|
||||
r.device.push_back(m->line());
|
||||
if (!no_host.count(std::make_pair(m->index, m->span)))
|
||||
r.device.back() += " (its host kernel cannot stand in: the op has no weights for "
|
||||
"the planner to place on the host)";
|
||||
}
|
||||
|
||||
std::vector<std::string> host_only_ops;
|
||||
for (const Program::Miss& m : p.misses) {
|
||||
if (m.domain != RAD_DOMAIN_HOST) {
|
||||
if (no_host.count(std::make_pair(m.op, m.span))) r.device.push_back(m.line());
|
||||
else if (std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
|
||||
host_only_ops.end()) host_only_ops.push_back(m.op);
|
||||
if (std::find(holes.begin(), holes.end(), &m) == holes.end() &&
|
||||
std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
|
||||
host_only_ops.end()) host_only_ops.push_back(m.op);
|
||||
continue;
|
||||
}
|
||||
auto it = host_spans.find(m.op);
|
||||
@@ -150,9 +167,14 @@ static MissReport miss_report(const Program& p) {
|
||||
* 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;
|
||||
@@ -161,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 });
|
||||
@@ -234,20 +257,27 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
|
||||
}
|
||||
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
|
||||
* would send the reader after the wrong cause: the device's reason above is the answer. */
|
||||
const int64_t want = (int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024 + pinned + mapped;
|
||||
const int64_t pool = (cfg.host_pool_mib + cfg.embedding_host_mib) * 1024 * 1024;
|
||||
const int64_t want = (int64_t)cfg.tp * pool + pinned + mapped;
|
||||
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
|
||||
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
RAD_ERR("host: --host-pool-mib %lld%s is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
|
||||
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
|
||||
"raised), and %s of RAM is available. %s",
|
||||
(long long)cfg.host_pool_mib, cfg.tp,
|
||||
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
|
||||
(long long)cfg.host_pool_mib,
|
||||
cfg.embedding_host_mib
|
||||
? fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib).c_str()
|
||||
: "",
|
||||
cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(),
|
||||
humanb(pinned + mapped).c_str(), rank,
|
||||
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
|
||||
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
|
||||
"the device gave is above"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
: cfg.embedding_host_mib
|
||||
? "Lower --host-pool-mib, keep the embedding on the card with "
|
||||
"--embedding-placement vram, or raise the cap"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,7 +447,8 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
|
||||
bool Engine::ngram_gather_to_host() {
|
||||
for (auto& r : ranks_) {
|
||||
WeightFootprint f;
|
||||
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk);
|
||||
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk,
|
||||
device_is_host(), file_ != nullptr);
|
||||
if (!f.ngram_host) return false;
|
||||
}
|
||||
for (auto& r : ranks_)
|
||||
@@ -432,78 +463,79 @@ bool Engine::ngram_gather_to_host() {
|
||||
/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every
|
||||
* rank before the card is split, and written into Config for the planner and the load phase.
|
||||
*
|
||||
* THE EMBEDDING: Auto keeps it on the card -- where every other weight a step reads lives --
|
||||
* unless that leaves the split unable to hold the fixed weights, or leaves a derived KV pool
|
||||
* unable to hold one --max-model-len sequence (`kv_floor`); then the pinned host pool takes it if
|
||||
* --host-pool-mib can, the card's lookup reading it over the link in place. Disk is refused: the
|
||||
* THE EMBEDDING: Ram, the default, pins it in host memory of its own beside --host-pool-mib
|
||||
* (Config::embedding_host_mib), the card's lookup reading its M rows a step over the link in
|
||||
* place, so its VRAM goes to the KV cache and the experts. Where it cannot -- a model whose output
|
||||
* head is tied to the table reads it whole every step, and a host without the memory has nowhere
|
||||
* to pin it -- the default keeps it on the card and says why, and a named `ram` stops the server.
|
||||
* Vram keeps it on the card with every other weight a step reads. There is no third tier: the
|
||||
* lookup writes the activations a card reads, which a host kernel reading the container cannot
|
||||
* reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
|
||||
*
|
||||
* THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy,
|
||||
* pinned for that kernel to read over the link or locked for the host gather; Disk in the
|
||||
* container, read by the host gather. Each tier is refused where no kernel reads it there. Auto
|
||||
* takes the first that holds the table, in that order: the card's test is the embedding's, and
|
||||
* RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated,
|
||||
* and the memlock limit for a locked copy. */
|
||||
* takes the first that holds the table, in that order: the card's test is the fixed weights and a
|
||||
* KV pool for one --max-model-len sequence (`kv_floor`) beside it, and RAM's is lockable_room's --
|
||||
* the memory and every cgroup after the pools still to be allocated, and the memlock limit for a
|
||||
* locked copy. */
|
||||
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
|
||||
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host) {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t emb_max = 0;
|
||||
for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b);
|
||||
|
||||
TablePlacement emb = cfg_.embedding_placement;
|
||||
const bool emb_asked = cfg_.embedding_placement_given;
|
||||
std::string emb_why;
|
||||
if (emb == TablePlacement::Disk) {
|
||||
RAD_ERR("--embedding-placement disk: the token embedding's lookup writes activations the "
|
||||
"card reads, and a host kernel reading the container cannot write them -- the "
|
||||
"architecture declares that buffer on the device. Use vram, ram or auto.");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* THE HOST MEMORY THE TABLE WOULD PIN, every rank its own shard, after the pools and the prefix
|
||||
* cache's host tier still to be allocated: lockable_room's test, without the memlock limit,
|
||||
* which a pin the cards read is not charged to. */
|
||||
const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB);
|
||||
const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
|
||||
cfg_.prefix_cache_host_mib * MiB;
|
||||
std::string emb_room_why;
|
||||
auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
|
||||
if (emb_max == 0) {
|
||||
if (emb == TablePlacement::Ram) {
|
||||
if (emb == TablePlacement::Ram && emb_asked) {
|
||||
RAD_ERR("--embedding-placement ram: this model has no token embedding table that only "
|
||||
"embed_lookup reads. An output head tied to the table reads it too, and would "
|
||||
"stream it over the link every step.");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = "no table only embed_lookup reads";
|
||||
} else if (emb == TablePlacement::Auto) {
|
||||
VramBudget tb;
|
||||
const int st = vram_budget_trial(cfg_, facts, &tb);
|
||||
const bool holds = st == RAD_OK && (!tb.derived_kv || tb.kv >= kv_floor);
|
||||
const bool host = cfg_.host_pool_mib * MiB >= emb_max;
|
||||
if (holds) {
|
||||
emb_why = "no table only embed_lookup reads (an output head tied to it reads it too, "
|
||||
"whole, every step)";
|
||||
} else if (emb == TablePlacement::Ram) {
|
||||
if (!emb_room()) {
|
||||
if (emb_asked) {
|
||||
RAD_ERR("--embedding-placement ram: the token embedding (%s a rank, pinned on "
|
||||
"every rank) cannot be held in host memory: %s. Use vram.",
|
||||
humanb(emb_max).c_str(), emb_room_why.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = "the card holds it beside the other weights and a KV pool for one "
|
||||
"--max-model-len sequence";
|
||||
} else if (host) {
|
||||
emb = TablePlacement::Ram;
|
||||
emb_why = st != RAD_OK
|
||||
? "the card cannot hold the other weights with it, and the pinned host pool can"
|
||||
: fmt("with it on the card the KV pool is %s, short of the %s one --max-model-len "
|
||||
"sequence needs, and the pinned host pool can hold it",
|
||||
humanb(tb.kv).c_str(), humanb(kv_floor).c_str());
|
||||
emb_why = "the host cannot pin it: " + emb_room_why;
|
||||
} else {
|
||||
emb = TablePlacement::Vram;
|
||||
emb_why = fmt("the card is short of room for it, and --host-pool-mib %lld cannot hold "
|
||||
"%s either", (long long)cfg_.host_pool_mib, humanb(emb_max).c_str());
|
||||
emb_why = emb_asked ? "as asked"
|
||||
: "pinned in host memory and read over the link in place, so its "
|
||||
"VRAM goes to the KV cache and the experts";
|
||||
}
|
||||
} else {
|
||||
emb_why = "as asked";
|
||||
}
|
||||
cfg_.embedding_resolved = emb;
|
||||
cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0;
|
||||
|
||||
TablePlacement ng = cfg_.ngram_placement;
|
||||
std::string ng_why;
|
||||
/* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding
|
||||
* all of it (a lookup is not sharded), with the fixed weights and a KV pool for one
|
||||
* --max-model-len sequence beside it, as the embedding's test is; then a copy in RAM -- pinned
|
||||
* --max-model-len sequence beside it; then a copy in RAM -- pinned
|
||||
* for a device kernel to read over the link, or locked for the host gather; then the
|
||||
* container, which only the host gather reads. Each is open only where a kernel reads it. */
|
||||
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
|
||||
const int64_t still = (int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib) * MiB +
|
||||
cfg_.prefix_cache_host_mib * MiB;
|
||||
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
|
||||
@@ -513,10 +545,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
for (size_t i = 0; i < with.size(); ++i) {
|
||||
VramFacts& f = with[i];
|
||||
f.statics += ngram_bytes;
|
||||
if (emb == TablePlacement::Ram) {
|
||||
f.statics -= emb_max;
|
||||
f.expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
if (emb == TablePlacement::Ram) f.statics -= emb_bytes[i];
|
||||
fixed = std::max(fixed, f.statics);
|
||||
}
|
||||
/* `fixed` and not the trial's own statics: the split clamps those to what the card can give
|
||||
@@ -528,7 +557,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
* only the card, and a table that took their room would leave them nowhere. */
|
||||
const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
|
||||
tb.experts < tb.expert_floor;
|
||||
if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor))
|
||||
if (st == RAD_OK && !over && !starved && tb.kv >= kv_floor)
|
||||
return true;
|
||||
if (st != RAD_OK)
|
||||
*why = "the card cannot hold the other weights with it";
|
||||
@@ -608,12 +637,18 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
|
||||
if (emb_max > 0)
|
||||
RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(),
|
||||
table_placement_name(emb),
|
||||
cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str());
|
||||
table_placement_name(emb), emb_asked ? "" : " (default)", emb_why.c_str());
|
||||
if (ngram_bytes > 0)
|
||||
RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(),
|
||||
table_placement_name(ng),
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -842,6 +877,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
|
||||
bc.scope = "";
|
||||
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
|
||||
bc.max_audio_frames = cfg_.mm_audio_frames > 0 ? cfg_.mm_audio_frames : 0;
|
||||
/* A row at every token of the step and the sampler's row a sequence before them
|
||||
* (core/kld.h); the KL mode has no speculation, so a sequence samples one. */
|
||||
bc.max_out_rows = cfg_.kld() ? max_tok + cfg_.max_seqs : 0;
|
||||
@@ -884,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{};
|
||||
@@ -894,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`,
|
||||
@@ -901,13 +944,36 @@ int Engine::declare() {
|
||||
* vision_config is a tower whose weights are in it. 16384 patches is a 2048 x 2048 image, the
|
||||
* largest one pass takes; the reference processor allows sixteen times that area, which would
|
||||
* need an activation region sixteen times as large on every card for one picture. */
|
||||
/* THE AUDIO ENCODER'S PASS: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment did not ask for text only. */
|
||||
if (cfg_.mm_audio_frames < 0) {
|
||||
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
|
||||
const bool named = enc && std::strstr(enc, "audio") != nullptr;
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
const bool text_only = cfg_.mm_max_patches == 0;
|
||||
cfg_.mm_audio_frames = !text_only && pb.audio_frames > 0 && (named || !file_)
|
||||
? pb.audio_frames : 0;
|
||||
}
|
||||
if (cfg_.mm_max_patches < 0) {
|
||||
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
|
||||
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0;
|
||||
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
|
||||
/* Whole output rows a pass: the plugin's merge, when it states one. */
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
if (cfg_.mm_max_patches > 0 && pb.enc_merge > 1)
|
||||
cfg_.mm_max_patches -= cfg_.mm_max_patches % pb.enc_merge;
|
||||
if (cfg_.mm_max_patches == 0 && tower)
|
||||
RAD_INFO("media: off -- the checkpoint has a vision tower but this container was "
|
||||
"converted without its weights; convert again to serve images and video");
|
||||
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);
|
||||
@@ -939,9 +1005,9 @@ int Engine::declare() {
|
||||
const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1;
|
||||
RAD_WARN("tp wire: LOSSY (--tp-wire wht6) at %lld KiB a message and above. A cross-rank "
|
||||
"all-reduce of that size carries a quantised payload instead of bf16 (libr4d's "
|
||||
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at four), so this "
|
||||
"process does not compute the same function the exact wire does. Steps of at "
|
||||
"most %lld rows are exact: single-sequence decode, and a "
|
||||
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at three and "
|
||||
"four), so this process does not compute the same function the exact wire does. "
|
||||
"Steps of at most %lld rows are exact: single-sequence decode, and a "
|
||||
"decode step until sequences x (1 + speculative depth) passes that; prefill and "
|
||||
"a busy decode step are lossy. --tp-wire-min-kb moves the floor.",
|
||||
(long long)cfg_.tp_wire_min_kb, (long long)exact_rows);
|
||||
@@ -959,7 +1025,7 @@ int Engine::declare() {
|
||||
* rank whose report differs is itself worth seeing, and gets its own. */
|
||||
{
|
||||
std::vector<MissReport> rep;
|
||||
for (auto& r : ranks_) rep.push_back(miss_report(r->program));
|
||||
for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host()));
|
||||
bool same = true;
|
||||
for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false;
|
||||
|
||||
@@ -975,6 +1041,23 @@ int Engine::declare() {
|
||||
if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str());
|
||||
if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str());
|
||||
}
|
||||
/* A HOLE IS A REFUSAL HERE, not an error the first request finds. Every band is one a
|
||||
* request can land in -- the bands are cut from the limits this run was started with --
|
||||
* and the step that lands in one fails at issue and takes the engine down with it. A
|
||||
* kernel library that serves the op (--kernels), or a model whose geometry the installed
|
||||
* one covers, is the remedy; serving until then is not. --debug-graph serves nothing, so
|
||||
* it goes on to print the graph the holes are in, and its exit status says they are there
|
||||
* (Engine::dump). */
|
||||
for (const MissReport& m : rep)
|
||||
if (!m.device.empty() && !cfg_.debug_graph) {
|
||||
if (m.lossy_wire)
|
||||
RAD_ERR("the band(s) above include the lossy wire --tp-wire wht6 asks for, "
|
||||
"which the loaded kernel libraries do not implement at --tp %d; "
|
||||
"--tp-wire exact asks for the exact one", cfg_.tp);
|
||||
RAD_ERR("not starting: the kernel libraries loaded have no kernel for the device "
|
||||
"band(s) above, and this model needs them");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* A CHECKPOINT WEIGHT THAT IS NOT SERVED AS IT STANDS was declared as plain and nothing can
|
||||
* load it: every one is named, with the remedy, whatever declare made of the rest. */
|
||||
@@ -1162,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;
|
||||
@@ -1181,11 +1279,10 @@ int Engine::plan() {
|
||||
* already this card's even share of the static weights: declare ran once per rank
|
||||
* with every dimension divided. */
|
||||
WeightFootprint wf;
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk);
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk,
|
||||
device_is_host(), file_ != nullptr);
|
||||
f.statics = wf.statics;
|
||||
f.experts = wf.experts;
|
||||
/* The expert floor waits for the tables' placement: the embedding may take its share
|
||||
* of the host pool first. */
|
||||
wfs.push_back(wf);
|
||||
/* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
|
||||
f.lends = VMem::supported() && !cfg_.deterministic &&
|
||||
@@ -1196,8 +1293,8 @@ int Engine::plan() {
|
||||
ngram_host = ngram_host || wf.ngram_host;
|
||||
/* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single
|
||||
* sequence, which is the least a KV pool can hold and still serve every request the
|
||||
* API accepts (configure_kv warns below it). --embedding-placement auto keeps the
|
||||
* table off the card only to stay above it. */
|
||||
* API accepts (configure_kv warns below it). --ngram-placement auto puts the table
|
||||
* on the card only where the pool stays above it. */
|
||||
{
|
||||
Config one = cfg_;
|
||||
one.max_seqs = 1;
|
||||
@@ -1253,31 +1350,29 @@ int Engine::plan() {
|
||||
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
|
||||
facts.push_back(f);
|
||||
}
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it
|
||||
* before any expert: the embedding when it is placed there, and the file tier's staging.
|
||||
* Both floors are known before the tables are placed, so placing them can ask whether the
|
||||
* experts would still have a tier. */
|
||||
std::vector<int64_t> floor_emb_ram(facts.size(), 0);
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less the file tier's staging, which
|
||||
* Planner::plan takes out of it before any expert. The embedding placed in host memory
|
||||
* brings its own room (Config::embedding_host_mib), so it leaves this floor as it is. */
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
|
||||
floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max<int64_t>(room - emb_bytes[i], 0));
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host));
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
|
||||
ngram_host));
|
||||
/* The n-gram table was counted off the card; on it, it is every rank's whole table. */
|
||||
if (cfg_.ngram_resolved == TablePlacement::Vram)
|
||||
for (VramFacts& f : facts) f.statics += ngram_bytes;
|
||||
if (cfg_.embedding_resolved == TablePlacement::Ram)
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
facts[i].statics -= emb_bytes[i];
|
||||
facts[i].expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
|
||||
VramBudget vb;
|
||||
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
|
||||
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
|
||||
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)
|
||||
@@ -1300,8 +1395,7 @@ int Engine::plan() {
|
||||
* pool, up to every one of its weights resident. The token count, the carve, the loan and
|
||||
* the dearest ranks' pools are what they were.
|
||||
*
|
||||
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
|
||||
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
|
||||
* Only a split under expert_tiered is re-split: under `auto` a rank whose grown pool covers all of
|
||||
* its weights would choose all_vram while its peers spill -- one strategy per world is the
|
||||
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
|
||||
* does not lend (--deterministic, or a device without virtual memory management) is
|
||||
@@ -1324,8 +1418,6 @@ int Engine::plan() {
|
||||
int64_t T = -1;
|
||||
if (cheaper.empty()) {
|
||||
/* Every rank's cache costs the same per token: there is nothing to re-split. */
|
||||
} else if (!vb.derived_kv || !vb.derived_weights) {
|
||||
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
|
||||
} else if (cfg_.placement != "expert_tiered") {
|
||||
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
|
||||
cfg_.placement.c_str());
|
||||
@@ -1425,6 +1517,7 @@ int Engine::plan() {
|
||||
in.n_profile = (int64_t)file_->header().prof_count;
|
||||
}
|
||||
in.container = file_ != nullptr;
|
||||
in.host_backend = device_is_host();
|
||||
Planner planner(in);
|
||||
s = planner.plan(&r->plan);
|
||||
if (cfg_.debug_placement || s < 0)
|
||||
@@ -1432,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. */
|
||||
@@ -2312,7 +2420,7 @@ int Engine::load_weights() {
|
||||
* past the end of the weights pool is a write to device memory the process does not own,
|
||||
* and on this driver that does not fault -- the copy is accepted, never completes, and
|
||||
* the host thread spins inside the runtime with the copy engine idle and no I/O. It looks
|
||||
* exactly like a hang, and it moves with --vram-weights-mib because a bigger pool is a
|
||||
* exactly like a hang, and it moves with the weights pool's size because a bigger pool is a
|
||||
* later overrun. Cheap enough to check on every copy, and checked before any of them
|
||||
* start rather than as each one is issued. */
|
||||
const uint8_t* wp_lo = (const uint8_t*)r->pools.weights().base();
|
||||
@@ -2465,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
|
||||
@@ -2719,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
|
||||
@@ -3185,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) {
|
||||
@@ -3196,11 +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) {
|
||||
@@ -3244,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);
|
||||
@@ -3270,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());
|
||||
@@ -3313,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. */
|
||||
@@ -3336,32 +3509,6 @@ int Engine::start() {
|
||||
r->ctx.set_stager(&r->fstager);
|
||||
}
|
||||
|
||||
/* RADIANCE_HOST_DOMAIN puts EVERY op on the host domain, which is how you run the whole
|
||||
* model on libref. The oracle the entire correctness story leans on is a per-op
|
||||
* one -- it compares one kernel against ref on the operands the device handed it -- and
|
||||
* that can never answer "is the GRAPH right", because both sides read the same graph. A
|
||||
* whole forward pass on the reference implementation can, and it is the only thing that
|
||||
* can be diffed against another engine's.
|
||||
*
|
||||
* The site is a per-op property already (spec §5.1) and set_op_domain refuses by name
|
||||
* where a band has no host kernel, so this is the existing seam and not a new one. It
|
||||
* belongs with HIP_VISIBLE_DEVICES=-1, which drops the backend to host so the arena is
|
||||
* host memory a host kernel may dereference; without that this asks ref to read VRAM. */
|
||||
if (std::getenv("RADIANCE_HOST_DOMAIN")) {
|
||||
if (!device_is_host())
|
||||
RAD_WARN("RADIANCE_HOST_DOMAIN on the %s backend: the arena is device memory and "
|
||||
"a host kernel cannot read it. Set HIP_VISIBLE_DEVICES=-1 as well.",
|
||||
device_backend_name());
|
||||
int moved = 0;
|
||||
for (size_t i = 1; i < r->program.ops.size(); ++i) {
|
||||
const int st = r->ctx.set_op_domain((rad_op)i, RAD_DOMAIN_HOST);
|
||||
if (st < 0) return st;
|
||||
++moved;
|
||||
}
|
||||
RAD_WARN("RADIANCE_HOST_DOMAIN: %d op(s) on the host. This is the reference "
|
||||
"implementation running the whole model, and it is as slow as that sounds.",
|
||||
moved);
|
||||
}
|
||||
}
|
||||
/* ---- THE LOAN: the cache's idle blocks, lent to the expert slab in place ----------------
|
||||
*
|
||||
@@ -3390,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
|
||||
@@ -3409,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 "
|
||||
@@ -3579,34 +3745,27 @@ int Engine::start() {
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
|
||||
humanb(room).c_str());
|
||||
} else if (got > want + 256 * MiB) {
|
||||
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
|
||||
* made the split, what is left is left because neither pool could address another
|
||||
* byte -- a small dense model already at the largest context its cache can hold
|
||||
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
|
||||
* Warning here would contradict that receipt and send the reader looking for a flag
|
||||
* to set. A rank plan() re-split for the common token count also leaves what its
|
||||
* weights could not use, and the `kv: rank N ...` line said how much. */
|
||||
/* "TOO MUCH" IS NOT A FAULT: the resolver made the split, and what is left is left
|
||||
* because neither pool could address another byte -- a small dense model already at
|
||||
* the largest context its cache can hold leaves most of the card -- and vram_budget.cpp
|
||||
* printed it on the `unusable` line. A rank plan() re-split for the common token count
|
||||
* also leaves what its weights could not use, and the `kv: rank N ...` line said how
|
||||
* much. */
|
||||
const int64_t unclaimed_mib =
|
||||
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
|
||||
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
|
||||
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
|
||||
if (unclaimed_mib > 0)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
|
||||
"MiB are what rank %d's weights could not use of what its KV pool did not "
|
||||
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
|
||||
"line of the VRAM budget.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
|
||||
r->index, r->index);
|
||||
else if (cfg_.vram_budget_derived)
|
||||
else
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
|
||||
"neither pool could address another byte, which is the `unusable` line of "
|
||||
"the VRAM budget above.",
|
||||
r->device, humanb(got).c_str(), asked.c_str());
|
||||
else
|
||||
RAD_WARN("card %d settled at %s free against %s, so %s is unused. On a model that "
|
||||
"does not fit in VRAM every unused GiB is weight that has to be moved "
|
||||
"instead of read, and that is decode step time.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(got - want).c_str());
|
||||
} else
|
||||
RAD_INFO("card %d settled at %s free, against %s",
|
||||
r->device, humanb(got).c_str(), asked.c_str());
|
||||
@@ -3623,17 +3782,12 @@ int Engine::dump() {
|
||||
Program& p = ranks_[0]->program;
|
||||
fputs(dump_graph_str(p, nullptr).c_str(), stdout);
|
||||
if (cfg_.debug_selection) fputs(rad_tools_registry().selection_table().c_str(), stdout);
|
||||
/* A HOST miss is not a failure -- see miss_report(). The exit code answers "is there a
|
||||
* hole a request can fall into", and a host miss is not one. NOR IS A DEVICE MISS WHOSE OP
|
||||
* HAS A HOST KERNEL: the planner places that op on the host and pins its weights in the
|
||||
* container's mapping, which is how a table too large to copy into VRAM is served at all. A
|
||||
* hole is a band NEITHER domain resolved. */
|
||||
std::set<std::pair<std::string, std::string>> no_host;
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
|
||||
for (const Program::Miss& m : p.misses)
|
||||
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span)))
|
||||
return RAD_E_NOKERNEL;
|
||||
/* The exit code answers "is there a hole a request can fall into", by the rule declare()
|
||||
* refuses to serve on (Program::device_holes, miss_report()): a device band no kernel
|
||||
* resolved, unless a host kernel stands in for an op whose weights the planner can place on
|
||||
* the host. A host miss is not one. */
|
||||
for (auto& r : ranks_)
|
||||
if (!r->program.device_holes(device_is_host()).empty()) return RAD_E_NOKERNEL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 */
|
||||
+87
-61
@@ -11,6 +11,9 @@
|
||||
* inside one; the processor has already kept every segment within a pass. Several items share a
|
||||
* pass when they fit, which is what a request with a handful of small pictures wants.
|
||||
*
|
||||
* AN AUDIO CLIP IS ONE SEGMENT OF THE AUDIO ENCODER, whose passes are separate from the vision
|
||||
* tower's: a program declares one of each at most, and an item goes to the one its kind names.
|
||||
*
|
||||
* EVERY RANK RUNS THE WHOLE TOWER on its own card from its own copy of the patches. The rows are
|
||||
* needed on every rank anyway -- each rank embeds every token -- and running it everywhere costs the
|
||||
* encoder's compute once per card instead of a transfer of its output between them.
|
||||
@@ -29,16 +32,6 @@ int Engine::run_encodes() {
|
||||
sched_.take_encodes(&items);
|
||||
if (items.empty()) return RAD_OK;
|
||||
|
||||
const RadEncoderDecl& enc = ranks_[0]->program.encoder;
|
||||
const int64_t max_p = sched_.encoder_patches();
|
||||
const int64_t n_embd = enc.n_embd;
|
||||
Rank& r0 = *ranks_[0];
|
||||
void* out = r0.ctx.buf_ptr(enc.out);
|
||||
if (!out) {
|
||||
RAD_ERR("encoder '%s': its output buffer was declared but never planned",
|
||||
ranks_[0]->program.encoder_name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
/* A DIAGNOSTIC: RADIANCE_DEBUG_MM_DUMP=<dir> writes each item's patches (`.pix.bf16`, the
|
||||
* processor's output in merge-block order) and its rows (`.bf16`) there as raw bf16, named by
|
||||
* its content key -- the tower's input and output, for comparison against a reference encoder
|
||||
@@ -56,65 +49,98 @@ int Engine::run_encodes() {
|
||||
}
|
||||
};
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
const Program& prog = r0.program;
|
||||
for (auto& ip : items) {
|
||||
if (ip->encoded) continue;
|
||||
ip->embd.assign((size_t)(ip->n_rows() * n_embd), 0);
|
||||
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
|
||||
ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0);
|
||||
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
|
||||
}
|
||||
|
||||
size_t i = 0;
|
||||
int32_t seg = 0;
|
||||
while (i < items.size()) {
|
||||
std::vector<BatchBuilder::EncoderPart> parts;
|
||||
int64_t np = 0;
|
||||
while (i < items.size()) {
|
||||
mm::Item& it = *items[i];
|
||||
if (it.encoded) { ++i; seg = 0; continue; }
|
||||
const int64_t seg_p = (int64_t)it.grid_h * it.grid_w;
|
||||
if (seg_p > max_p) {
|
||||
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
|
||||
(long long)seg_p, (long long)max_p);
|
||||
/* THE PASSES, ENCODER BY ENCODER: an audio clip goes through the audio encoder and a picture
|
||||
* or a video through the other, each with its own pass size and output buffer. */
|
||||
for (int which = 0; which < 2; ++which) {
|
||||
const bool audio = which == 1;
|
||||
const RadEncoderDecl& enc = audio ? prog.audio_encoder : prog.encoder;
|
||||
const std::string& enc_name = audio ? prog.audio_encoder_name : prog.encoder_name;
|
||||
std::vector<mm::Item*> mine;
|
||||
for (auto& ip : items)
|
||||
if (!ip->encoded && (ip->kind == mm::Kind::Audio) == audio) mine.push_back(ip.get());
|
||||
if (mine.empty()) continue;
|
||||
if (enc.modalities == 0) {
|
||||
RAD_ERR("encoder: a %s item reached the encoder and this program declares no %s "
|
||||
"encoder", audio ? "audio" : "picture", audio ? "audio" : "image");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t max_p = enc.max_patches;
|
||||
const int64_t n_embd = enc.n_embd;
|
||||
|
||||
size_t i = 0;
|
||||
int32_t seg = 0;
|
||||
while (i < mine.size()) {
|
||||
std::vector<BatchBuilder::EncoderPart> parts;
|
||||
int64_t np = 0;
|
||||
while (i < mine.size()) {
|
||||
mm::Item& it = *mine[i];
|
||||
const 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;
|
||||
}
|
||||
if (seg == first) break;
|
||||
parts.push_back({ &it, first, seg - first });
|
||||
if (seg == it.n_seg) { ++i; seg = 0; }
|
||||
}
|
||||
if (parts.empty()) break;
|
||||
|
||||
const RadBatch* b = sched_.build_encoder(parts, enc_step_++, enc);
|
||||
if (!b) return RAD_E_STATE;
|
||||
RAD_TRY(prepare_release(b));
|
||||
/* THE OUTPUT'S ADDRESS IS THE PASS'S LEVEL'S, read after prepare_release: a pass runs
|
||||
* at the arena's full plan (Engine::arena_step), and a buffer sits at another offset
|
||||
* in every level. An address taken at the level the last step left would read some
|
||||
* other buffer, or memory lent to the expert slab, in place of the rows. */
|
||||
void* out = r0.ctx.buf_ptr(enc.out);
|
||||
if (!out) {
|
||||
RAD_ERR("encoder '%s': its output buffer was declared but never planned",
|
||||
enc_name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t room = (max_p - np) / seg_p;
|
||||
const int32_t can = (int32_t)std::min<int64_t>(it.n_seg - seg, room);
|
||||
if (can <= 0) break;
|
||||
parts.push_back({ &it, seg, can });
|
||||
np += (int64_t)can * seg_p;
|
||||
seg += can;
|
||||
if (seg == it.n_seg) { ++i; seg = 0; }
|
||||
/* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick,
|
||||
* which belongs to steps. */
|
||||
issue_what_.store(kIssueModel, std::memory_order_release);
|
||||
step_batch_.store(b, std::memory_order_release);
|
||||
barrier_->arrive_and_wait();
|
||||
barrier_->arrive_and_wait();
|
||||
const int st = step_status_.load(std::memory_order_acquire);
|
||||
if (st < 0) {
|
||||
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
|
||||
return st;
|
||||
}
|
||||
/* The rows, in pass order: each part's segments are consecutive rows of its item. */
|
||||
int64_t row = 0;
|
||||
for (const BatchBuilder::EncoderPart& p : parts) {
|
||||
mm::Item& it = *const_cast<mm::Item*>(p.item);
|
||||
const int64_t 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() + first * n_embd,
|
||||
static_cast<const char*>(out) +
|
||||
row * n_embd * (int64_t)sizeof(uint16_t),
|
||||
bytes, r0.ctx.stream()));
|
||||
row += rows;
|
||||
}
|
||||
/* Every rank's stream, not only rank 0's: the next pass rewrites the staging every
|
||||
* rank's copy reads, and the arena every rank's tower wrote. */
|
||||
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
}
|
||||
if (parts.empty()) break;
|
||||
|
||||
const RadBatch* b = sched_.build_encoder(parts, enc_step_++);
|
||||
if (!b) return RAD_E_STATE;
|
||||
RAD_TRY(prepare_release(b));
|
||||
/* kIssueModel: the pass and nothing behind it -- no sampler, and no tiering tick, which
|
||||
* belongs to steps. */
|
||||
issue_what_.store(kIssueModel, std::memory_order_release);
|
||||
step_batch_.store(b, std::memory_order_release);
|
||||
barrier_->arrive_and_wait();
|
||||
barrier_->arrive_and_wait();
|
||||
const int st = step_status_.load(std::memory_order_acquire);
|
||||
if (st < 0) {
|
||||
RAD_ERR("encoder pass failed: %s -- the engine cannot continue", rad_strerror(st));
|
||||
return st;
|
||||
}
|
||||
/* The rows, in pass order: each part's segments are consecutive rows of its item. */
|
||||
int64_t row = 0;
|
||||
for (const BatchBuilder::EncoderPart& p : parts) {
|
||||
mm::Item& it = *const_cast<mm::Item*>(p.item);
|
||||
const int64_t rows = (int64_t)p.n_seg * it.seg_rows;
|
||||
const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t);
|
||||
RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd,
|
||||
static_cast<const char*>(out) +
|
||||
row * n_embd * (int64_t)sizeof(uint16_t),
|
||||
bytes, r0.ctx.stream()));
|
||||
row += rows;
|
||||
}
|
||||
/* Every rank's stream, not only rank 0's: the next pass rewrites the staging every rank's
|
||||
* copy reads, and the arena every rank's tower wrote. */
|
||||
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
}
|
||||
|
||||
for (auto& ip : items) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -114,9 +114,10 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
|
||||
* WHY THAT IS ENOUGH FOR A KL DIVERGENCE, with no log-sum-exp anywhere. Renormalised over a
|
||||
* fixed candidate set S, p~_i = exp(l_i) / sum_{j in S} exp(l_j) -- the partition function
|
||||
* over the WHOLE vocabulary cancels, in both engines independently. So a top-K KLD against
|
||||
* another engine's top-K logprobs needs only these logits. An OpenAI `logprobs` FIELD would
|
||||
* need the normaliser, and `supports_logprobs` is false; this is a probe, and it says so by
|
||||
* being an environment variable at -vv rather than a response field. */
|
||||
* another engine's top-K logprobs needs only these logits. The OpenAI `logprobs` field carries
|
||||
* the normaliser (sample_logprobs) and only the RAW distribution's top 20; this reads the
|
||||
* plane the pick drew from, which is a probe, and it says so by being an environment variable
|
||||
* at -vv rather than a response field. */
|
||||
static const int head = [] {
|
||||
const char* s = std::getenv("RADIANCE_DUMP_HEAD");
|
||||
const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
|
||||
@@ -156,8 +157,8 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
|
||||
* writing different code -- so the question a LOSSY LEVER asks ("how much worse, if at all")
|
||||
* needs an instrument of its own.
|
||||
*
|
||||
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server returns no logprobs (`supports_logprobs` is
|
||||
* never set, so it refuses them) and a served prefill produces logits only at the rows
|
||||
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server's logprobs are the generated positions'
|
||||
* only -- never the prompt's -- and a served prefill produces logits only at the rows
|
||||
* `out_ids` names; the teacher-forced scoring pass is the KL mode's (core/kld.h), which runs in
|
||||
* place of the server. What a serving engine offers: send N distinct prompts at max_tokens = 1,
|
||||
* and every build under comparison sees IDENTICAL inputs at one row each. The top of that row,
|
||||
|
||||
+65
-26
@@ -148,9 +148,15 @@ int meta_merge_generation_config(const std::string& dir, MetaOwn* out) {
|
||||
* `size.shortest_edge` means two different things in the two files. Absent is not an error: a
|
||||
* text model has neither. */
|
||||
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out) {
|
||||
/* processor_config.json is the newer single file: one object a sub-processor
|
||||
* (`image_processor`, `video_processor`, `feature_extractor`) beside the processor's own keys
|
||||
* -- EmbeddingGemma 2's image budget and its audio token rate are only there. */
|
||||
static const struct { const char* file; const char* prefix; } kFiles[] = {
|
||||
{ "preprocessor_config.json", "preprocessor" },
|
||||
{ "video_preprocessor_config.json", "video_preprocessor" },
|
||||
{ "processor_config.json", "processor" },
|
||||
/* sentence-transformers' own: an embedding model's named prompts and its default. */
|
||||
{ "config_sentence_transformers.json", "sentence_transformers" },
|
||||
};
|
||||
for (const auto& f : kFiles) {
|
||||
const std::string path = dir + "/" + f.file;
|
||||
@@ -228,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;
|
||||
|
||||
@@ -251,25 +261,30 @@ 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
|
||||
* be a linear position divide for llama3, longrope or YaRN. */
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
|
||||
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
|
||||
* rather than by a flag. */
|
||||
if (const char* qm = gs("quantization_config.quant_method")) {
|
||||
out->quant = qm;
|
||||
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
|
||||
}
|
||||
|
||||
out->quant = quant_descriptor(*out);
|
||||
out->finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
|
||||
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
|
||||
* rather than by a flag. */
|
||||
std::string quant_descriptor(const MetaOwn& m) {
|
||||
std::string q;
|
||||
if (const char* qm = m.get("quantization_config.quant_method")) {
|
||||
q = qm;
|
||||
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
if (!g.get_str("general.architecture", &out->arch)) {
|
||||
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
|
||||
@@ -408,10 +423,24 @@ int Checkpoint::open_gguf(const std::string& path) {
|
||||
return meta_from_gguf(gguf_, &meta_);
|
||||
}
|
||||
|
||||
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
|
||||
const std::unordered_map<std::string, std::string>* owner) {
|
||||
shards_.push_back(std::make_unique<SafeTensorsFile>());
|
||||
RAD_TRY(shards_.back()->open(p));
|
||||
const std::string file = p.substr(p.find_last_of('/') + 1);
|
||||
for (const auto& t : shards_.back()->tensors()) {
|
||||
/* THE INDEX SAYS WHICH SHARD A TENSOR IS READ FROM. A directory that merges two
|
||||
* checkpoints -- a finetune's changed tensors in its own shards beside links to the base
|
||||
* model's -- holds some names in two shards, and only the index tells the copies apart. */
|
||||
if (owner) {
|
||||
auto it = owner->find(t.name);
|
||||
if (it != owner->end() && it->second != file) continue;
|
||||
}
|
||||
if (index_.count(prefix + t.name)) {
|
||||
RAD_ERR("%s: '%s' is also in %s, and no index entry says which copy to read", p.c_str(),
|
||||
t.name.c_str(), shards_[index_shard_[prefix + t.name]]->path().c_str());
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if (t.dtype == RAD_DT_INVALID) {
|
||||
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
|
||||
t.name.c_str(), t.dtype_str.c_str());
|
||||
@@ -423,6 +452,7 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
s.shape = t.shape; /* safetensors is already row-major */
|
||||
s.data = t.data;
|
||||
s.bytes = (int64_t)t.bytes;
|
||||
index_shard_.emplace(s.name, shards_.size() - 1);
|
||||
index_.emplace(s.name, tensors_.size());
|
||||
tensors_.push_back(std::move(s));
|
||||
}
|
||||
@@ -431,13 +461,13 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
|
||||
|
||||
namespace {
|
||||
|
||||
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
|
||||
/* Every shard an index names, once each and in name order, or the one model.safetensors; `map`
|
||||
* is the index's weight_map, empty without one. */
|
||||
int shard_list(const std::string& dir, const std::string& index, bool index_given,
|
||||
std::vector<std::string>* out) {
|
||||
std::unordered_map<std::string, std::string> map;
|
||||
const int s = st_load_index(index, &map);
|
||||
std::vector<std::string>* out, std::unordered_map<std::string, std::string>* map) {
|
||||
const int s = st_load_index(index, map);
|
||||
if (s == RAD_OK) {
|
||||
for (auto& [t, f] : map)
|
||||
for (auto& [t, f] : *map)
|
||||
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
|
||||
std::sort(out->begin(), out->end());
|
||||
for (auto& f : *out) f = dir + "/" + f;
|
||||
@@ -454,6 +484,7 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
kind_ = SafeT;
|
||||
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
|
||||
std::vector<std::string> shards;
|
||||
std::unordered_map<std::string, std::string> owner;
|
||||
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
|
||||
const bool is_file = path.size() > 12 &&
|
||||
path.compare(path.size() - 12, 12, ".safetensors") == 0;
|
||||
@@ -461,9 +492,9 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
shards.push_back(path);
|
||||
} else {
|
||||
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
|
||||
is_index, &shards));
|
||||
is_index, &shards, &owner));
|
||||
}
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
|
||||
|
||||
RAD_TRY(meta_from_config_json(dir_, &meta_));
|
||||
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
|
||||
@@ -663,8 +694,9 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
|
||||
? prefix
|
||||
: prefix.substr(0, prefix.size() - 1), &meta_));
|
||||
std::vector<std::string> shards;
|
||||
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
|
||||
std::unordered_map<std::string, std::string> owner;
|
||||
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
|
||||
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -823,23 +855,30 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
" holds none of them");
|
||||
}
|
||||
|
||||
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. */
|
||||
/* THE LOGICAL SHAPE: the pieces joined along concat_dim, every other extent agreeing. A
|
||||
* rank-0 tensor is one element and is read as shape [1]: safetensors stores a scalar
|
||||
* parameter (Gemma 4's clipped-linear bounds) with an empty shape. */
|
||||
const SrcTensor& p0 = *out->pieces[0];
|
||||
const int d = out->concat_dim;
|
||||
if (p0.shape.empty() || p0.shape.size() > RAD_MAX_RANK || d < 0 || d >= (int)p0.shape.size())
|
||||
auto shape_of = [](const SrcTensor& t) {
|
||||
return t.shape.empty() ? std::vector<int64_t>{ 1 } : t.shape;
|
||||
};
|
||||
const std::vector<int64_t> s0 = shape_of(p0);
|
||||
if (s0.size() > RAD_MAX_RANK || d < 0 || d >= (int)s0.size())
|
||||
return refuse(RAD_E_SHAPE, "'" + p0.name + "' cannot be joined along dim " +
|
||||
std::to_string(d));
|
||||
out->rank = (uint32_t)p0.shape.size();
|
||||
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = p0.shape[i];
|
||||
out->rank = (uint32_t)s0.size();
|
||||
for (uint32_t i = 0; i < out->rank; ++i) out->shape[i] = s0[i];
|
||||
for (size_t k = 1; k < out->pieces.size(); ++k) {
|
||||
const SrcTensor& pk = *out->pieces[k];
|
||||
bool fits = pk.shape.size() == p0.shape.size();
|
||||
const std::vector<int64_t> sk = shape_of(pk);
|
||||
bool fits = sk.size() == s0.size();
|
||||
for (uint32_t i = 0; fits && i < out->rank; ++i)
|
||||
if ((int)i != d && pk.shape[i] != p0.shape[i]) fits = false;
|
||||
if ((int)i != d && sk[i] != s0[i]) fits = false;
|
||||
if (!fits)
|
||||
return refuse(RAD_E_SHAPE, "'" + pk.name + "' and '" + p0.name +
|
||||
"' do not join along dim " + std::to_string(d));
|
||||
out->shape[d] += pk.shape[(size_t)d];
|
||||
out->shape[d] += sk[(size_t)d];
|
||||
}
|
||||
rad_enc_view(out->rank, out->shape, &out->rows, &out->cols);
|
||||
|
||||
|
||||
@@ -84,6 +84,8 @@ struct MetaOwn {
|
||||
};
|
||||
|
||||
int meta_from_config_json(const std::string& dir, MetaOwn* out);
|
||||
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
|
||||
std::string quant_descriptor(const MetaOwn& m);
|
||||
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
|
||||
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
|
||||
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
|
||||
@@ -142,7 +144,10 @@ public:
|
||||
std::string* why);
|
||||
|
||||
private:
|
||||
int add_shard(const std::string& p, const std::string& prefix = "");
|
||||
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
|
||||
* another shard is not read from this one. */
|
||||
int add_shard(const std::string& p, const std::string& prefix = "",
|
||||
const std::unordered_map<std::string, std::string>* owner = nullptr);
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
@@ -154,6 +159,7 @@ private:
|
||||
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
|
||||
std::vector<SrcTensor> tensors_;
|
||||
std::unordered_map<std::string, size_t> index_;
|
||||
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
|
||||
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* hf_model.cpp -- resolve a --model that is a Hugging Face repo id (hf_model.h).
|
||||
*
|
||||
* The entry point (main.cpp) calls resolve_hf_model() once, between config_parse and the Engine,
|
||||
* and the rest of bring-up sees a plain file or directory. The fetching is scripts/hfget.sh (curl
|
||||
* and jq, no Python), run as a child process; it is installed to libexec/radiance/ and the build
|
||||
* copies it to the same place under the build tree, so it is found beside the binary either way.
|
||||
*
|
||||
* WHERE IT GOES. Not under $RADIANCE_HOME: that is a ':'-separated search path for plugins, and
|
||||
* its default is the install's share/ directory, which a user cannot write. A model is a cache --
|
||||
* the XDG cache directory by default, --download-dir (vLLM's name) to put it on another disk.
|
||||
*
|
||||
* A HUB THAT CANNOT BE REACHED DOES NOT STOP A RESTART. hfget.sh exits 3 when it changed nothing
|
||||
* on disk (the listing failed, or an update does not fit), and the copy a complete fetch left --
|
||||
* marked by the manifest it writes only on success -- is then served with a warning. Any other
|
||||
* failure may have left a file half-transferred, so it is not served. */
|
||||
#include "hf_model.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
bool repo_part(const std::string& p) {
|
||||
if (p.empty() || p.front() == '.' || p.front() == '-') return false;
|
||||
for (char ch : p) {
|
||||
const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') || ch == '.' || ch == '_' || ch == '-';
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* suf) {
|
||||
const size_t n = std::strlen(suf);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
|
||||
}
|
||||
|
||||
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
|
||||
* copies it. */
|
||||
std::string hfget_path() {
|
||||
char buf[4096];
|
||||
const ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
|
||||
if (n <= 0) return std::string();
|
||||
buf[n] = '\0';
|
||||
const fs::path p = fs::path(buf).parent_path() / ".." / "libexec" / "radiance" / "hfget.sh";
|
||||
std::error_code ec;
|
||||
return fs::is_regular_file(p, ec) ? p.lexically_normal().string() : std::string();
|
||||
}
|
||||
|
||||
/* The script's exit status, or -1 when it could not be run. */
|
||||
int run_hfget(const std::string& script, const std::string& repo, const std::string& dest) {
|
||||
const pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
RAD_ERR("hfget: fork: %s", std::strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pid == 0) {
|
||||
const char* argv[] = { "sh", script.c_str(), repo.c_str(), dest.c_str(), nullptr };
|
||||
execv("/bin/sh", const_cast<char* const*>(argv));
|
||||
std::fprintf(stderr, "hfget: /bin/sh: %s\n", std::strerror(errno));
|
||||
_exit(127);
|
||||
}
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, 0) < 0)
|
||||
if (errno != EINTR) return -1;
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
bool hf_repo_id(const std::string& s) {
|
||||
std::error_code ec;
|
||||
if (s.empty() || fs::exists(s, ec)) return false;
|
||||
const size_t slash = s.find('/');
|
||||
if (slash == std::string::npos || s.find('/', slash + 1) != std::string::npos) return false;
|
||||
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
|
||||
if (!repo_part(owner) || !repo_part(name)) return false;
|
||||
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
|
||||
if (ends_with(name, suf)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hf_default_download_dir() {
|
||||
if (const char* x = std::getenv("XDG_CACHE_HOME"); x && *x)
|
||||
return std::string(x) + "/radiance/hf";
|
||||
if (const char* h = std::getenv("HOME"); h && *h)
|
||||
return std::string(h) + "/.cache/radiance/hf";
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string hf_served_path(const std::string& dir, std::string* why) {
|
||||
std::vector<std::string> rad;
|
||||
std::error_code ec;
|
||||
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
|
||||
std::error_code fe;
|
||||
if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad"))
|
||||
rad.push_back(e.path().filename().string());
|
||||
}
|
||||
if (ec) {
|
||||
*why = dir + ": " + ec.message();
|
||||
return std::string();
|
||||
}
|
||||
if (rad.empty()) return dir;
|
||||
if (rad.size() == 1) return dir + "/" + rad[0];
|
||||
std::string names;
|
||||
for (size_t i = 0; i < rad.size(); ++i) names += (i ? ", " : "") + rad[i];
|
||||
*why = dir + " holds " + std::to_string(rad.size()) + " containers (" + names +
|
||||
"); pass the one to serve as --model " + dir + "/<file>";
|
||||
return std::string();
|
||||
}
|
||||
|
||||
bool resolve_hf_model(Config& c) {
|
||||
if (!hf_repo_id(c.model)) return true;
|
||||
const std::string repo = c.model;
|
||||
const std::string root = c.download_dir.empty() ? hf_default_download_dir() : c.download_dir;
|
||||
if (root.empty()) {
|
||||
RAD_ERR("--model %s: no download directory -- neither XDG_CACHE_HOME nor HOME is set; "
|
||||
"name one with --download-dir", repo.c_str());
|
||||
return false;
|
||||
}
|
||||
const std::string dest = root + "/" + repo;
|
||||
std::error_code ec;
|
||||
const bool cached = fs::is_regular_file(dest + "/.hfget-manifest", ec);
|
||||
|
||||
const std::string script = hfget_path();
|
||||
if (script.empty()) {
|
||||
RAD_ERR("--model %s: not a path here, and hfget.sh, which fetches a Hugging Face repo, is "
|
||||
"not installed beside this binary (libexec/radiance/)", repo.c_str());
|
||||
return false;
|
||||
}
|
||||
RAD_INFO("model: %s is not a path here; fetching it as a Hugging Face repo into %s",
|
||||
repo.c_str(), dest.c_str());
|
||||
const int rc = run_hfget(script, repo, dest);
|
||||
if (rc != 0) {
|
||||
if (rc == 3 && cached) {
|
||||
RAD_WARN("model: %s could not be checked for changes (hfget.sh, above); serving the "
|
||||
"copy fetched before", repo.c_str());
|
||||
} else {
|
||||
RAD_ERR("--model %s: not a path here, and fetching it as a Hugging Face repo failed "
|
||||
"(hfget.sh exit %d, above)", repo.c_str(), rc);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::string why;
|
||||
const std::string path = hf_served_path(dest, &why);
|
||||
if (path.empty()) {
|
||||
RAD_ERR("--model %s: %s", repo.c_str(), why.c_str());
|
||||
return false;
|
||||
}
|
||||
c.model = path;
|
||||
RAD_INFO("model: serving %s", c.model.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,33 @@
|
||||
/* hf_model.h -- a --model that names a Hugging Face repo instead of a local path.
|
||||
*
|
||||
* `radiance --model StillDeadcode/minicpm5-2b-fp8` fetches the repo with scripts/hfget.sh into
|
||||
* the download directory and serves what it fetched: the one container at the repo's top level,
|
||||
* or the directory as a checkpoint when it holds none. Every start re-checks the hub, so a
|
||||
* changed file is fetched again before bring-up; a start that cannot reach the hub serves the
|
||||
* copy a complete earlier fetch left. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Is `s` a repo id ("owner/name") rather than a path? A path that exists always wins. A repo id is
|
||||
* exactly two non-empty parts of [A-Za-z0-9._-], neither starting with '.' or '-', and a name that
|
||||
* does not end like a model file (.rad, .safetensors, .gguf, .json): a missing local file should
|
||||
* be reported as missing, not looked up on the hub. */
|
||||
bool hf_repo_id(const std::string& s);
|
||||
|
||||
/* $XDG_CACHE_HOME/radiance/hf, else $HOME/.cache/radiance/hf; empty if neither is set. */
|
||||
std::string hf_default_download_dir();
|
||||
|
||||
/* What to serve from a fetched repo directory: its one top-level .rad, or the directory itself (a
|
||||
* checkpoint) when it holds none. Several containers are ambiguous: empty, and *why names them. */
|
||||
std::string hf_served_path(const std::string& dir, std::string* why);
|
||||
|
||||
/* If c.model is a repo id, fetch it and point c.model at what to serve. False after an error has
|
||||
* been logged. */
|
||||
bool resolve_hf_model(Config& c);
|
||||
|
||||
} /* namespace rad */
|
||||
+17
-2
@@ -2,6 +2,7 @@
|
||||
* a command line into that sequence and a status into an exit code.
|
||||
*/
|
||||
#include "engine.h"
|
||||
#include "hf_model.h"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
rad::Config cfg;
|
||||
@@ -9,11 +10,25 @@ int main(int argc, char** argv) {
|
||||
if (s == 1) { rad::config_usage(argv[0]); return 0; }
|
||||
if (s < 0) { rad::config_usage(argv[0]); return 2; }
|
||||
|
||||
if (!rad::resolve_hf_model(cfg)) return 1; /* a repo id: fetched, and --model points at it */
|
||||
|
||||
rad::Engine engine(std::move(cfg));
|
||||
|
||||
s = engine.start();
|
||||
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
-7
@@ -424,8 +424,7 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
}
|
||||
|
||||
int KVManager::carve_into(Pool& kv_pool) {
|
||||
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
|
||||
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
/* The pool is what the resolver derived; nothing here re-decides it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
const int64_t budget_bytes = kv_pool.avail();
|
||||
const int64_t fixed = fixed_;
|
||||
pool_base_ = kv_pool.base();
|
||||
@@ -434,10 +433,11 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
if (fixed >= budget_bytes) {
|
||||
RAD_ERR("vram_kv does not fit its fixed costs:\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" --vram-kv-mib %10s\n"
|
||||
" vram_kv %10s\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
|
||||
"for you (spec §6).",
|
||||
"Lower --max-num-seqs, or give the cache more of the card: a smaller "
|
||||
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
|
||||
"them for you (spec §6).",
|
||||
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -459,8 +459,8 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
}
|
||||
if (p.n_blocks <= 0) {
|
||||
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
|
||||
"--max-seqs.",
|
||||
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or "
|
||||
"lower --max-num-seqs.",
|
||||
p.name.c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
|
||||
+3
-3
@@ -156,8 +156,8 @@ public:
|
||||
* exhaust at the same total token count, and any other split strands memory in whichever
|
||||
* group outlasts the others.
|
||||
*
|
||||
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
|
||||
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
|
||||
* The byte budget is the budget resolver's and is not re-derived here: it is whatever
|
||||
* `kv_pool` still has (vram_kv). The linear-state snapshots take none of it -- they live
|
||||
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
|
||||
* else (spec §6, §7.3). */
|
||||
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
|
||||
@@ -165,7 +165,7 @@ public:
|
||||
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
|
||||
* from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
|
||||
* says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
|
||||
* allocated before carve() runs, so a derived --vram-kv-mib has to be decided from these two
|
||||
* allocated before carve() runs, so the KV pool has to be decided from these two
|
||||
* and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
|
||||
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
|
||||
int64_t ceiling(int64_t ctx) const;
|
||||
|
||||
+12
-2
@@ -988,7 +988,7 @@ static bool chain_extends(const std::vector<BlockHash>& shorter,
|
||||
}
|
||||
|
||||
void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns) {
|
||||
uint64_t now_ns, const std::string& label) {
|
||||
if (chain.empty()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
|
||||
@@ -1008,6 +1008,9 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
* to say which of them republished. So the most recent of them is touched and no row is
|
||||
* added, which is the one answer that is wrong about nothing. */
|
||||
uint64_t first_seen = 0;
|
||||
/* A conversation's label outlives the turn that sent it: a later turn without one keeps the
|
||||
* name an earlier one gave. */
|
||||
std::string kept_label = label;
|
||||
bool absorbed = false;
|
||||
std::vector<uint64_t>& at_root = roots_[chain[0]];
|
||||
for (size_t i = 0; i < at_root.size();) {
|
||||
@@ -1016,6 +1019,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
if (!chain_extends(it->second.chain, chain)) { ++i; continue; }
|
||||
if (first_seen == 0 || it->second.first_seen_ns < first_seen)
|
||||
first_seen = it->second.first_seen_ns;
|
||||
if (kept_label.empty()) kept_label = it->second.label;
|
||||
sessions_.erase(it);
|
||||
at_root.erase(at_root.begin() + (long)i);
|
||||
absorbed = true;
|
||||
@@ -1028,7 +1032,11 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
if (it == sessions_.end() || !chain_extends(chain, it->second.chain)) continue;
|
||||
if (!newest || it->second.last_used_ns > newest->last_used_ns) newest = &it->second;
|
||||
}
|
||||
if (newest) { newest->last_used_ns = now_ns; return; }
|
||||
if (newest) {
|
||||
newest->last_used_ns = now_ns;
|
||||
if (!label.empty()) newest->label = label;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Session& s = sessions_[id];
|
||||
@@ -1036,6 +1044,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
s.n_tokens = n_tokens;
|
||||
s.first_seen_ns = first_seen ? first_seen : now_ns;
|
||||
s.chain = chain;
|
||||
s.label = std::move(kept_label);
|
||||
at_root.push_back(id);
|
||||
}
|
||||
|
||||
@@ -1079,6 +1088,7 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
si.model = model_;
|
||||
si.n_tokens = kv.second.n_tokens;
|
||||
si.first_seen_ns = kv.second.first_seen_ns;
|
||||
si.label = kv.second.label;
|
||||
si.last_used_ns = kv.second.last_used_ns;
|
||||
si.bytes = (int64_t)kv.second.chain.size() * cfg_.entry_bytes;
|
||||
out.push_back(std::move(si));
|
||||
|
||||
+3
-1
@@ -383,6 +383,7 @@ public:
|
||||
struct SessionInfo {
|
||||
uint64_t id = 0;
|
||||
std::string model;
|
||||
std::string label; /* the client's own name for the conversation, or "" */
|
||||
int64_t n_tokens = 0;
|
||||
int64_t bytes = 0;
|
||||
uint64_t first_seen_ns = 0;
|
||||
@@ -426,7 +427,7 @@ public:
|
||||
* is a row per turn -- a table nobody can read, holding a copy of every prefix of the
|
||||
* transcript for as long as the newest. */
|
||||
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns);
|
||||
uint64_t now_ns, const std::string& label = std::string());
|
||||
void set_model(const std::string& m) { model_ = m; }
|
||||
/* Newest activity first. Recomputes each session's tier histogram from the records, so it is
|
||||
* a view and never a second copy of the truth. The walk takes the lock in slices and lets
|
||||
@@ -545,6 +546,7 @@ private:
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
std::vector<BlockHash> chain;
|
||||
std::string label;
|
||||
};
|
||||
|
||||
/* Erase one row and its root index entry together. */
|
||||
|
||||
+11
-37
@@ -199,22 +199,20 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t w = cfg.vram_weights_mib * MiB;
|
||||
const int64_t kv = cfg.vram_kv_mib * MiB;
|
||||
const int64_t hp = cfg.host_pool_mib * MiB;
|
||||
const int64_t hp = (cfg.host_pool_mib + cfg.embedding_host_mib) * MiB;
|
||||
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the
|
||||
* operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured
|
||||
* driver residency and the computed arena -- and either way they arrive here as two numbers
|
||||
* with a report behind them. Either way this component refuses rather than shrinking
|
||||
* anything: an engine that quietly re-optimises a split is an engine whose
|
||||
* benchmarks do not reproduce (spec §6). A zero here means the resolver was never called,
|
||||
* which is a wiring bug and gets named as one. */
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
|
||||
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
|
||||
* computed arena, and they arrive here as two numbers with a report behind them. This
|
||||
* component refuses rather than shrinking anything: an engine that quietly re-optimises a
|
||||
* split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
|
||||
* resolver was never called, which is a wiring bug and gets named as one. */
|
||||
std::string missing;
|
||||
if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n";
|
||||
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
|
||||
if (!missing.empty()) {
|
||||
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
|
||||
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
|
||||
+ missing;
|
||||
fit_report_ = "VRAM pool budgets are empty: the budget resolver (core/mem/vram_budget.cpp) "
|
||||
"did not run before the pools were configured:\n" + missing;
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -230,8 +228,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
|
||||
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
|
||||
"The resolved split is larger than the card, which the resolver does not produce: a "
|
||||
"wiring bug (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(),
|
||||
humanb(want - vram_capacity).c_str());
|
||||
@@ -239,30 +237,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there
|
||||
* should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is
|
||||
* not the sum of the budgets. What is left over here is the driver's residency, the activation
|
||||
* arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's
|
||||
* report breaks that down term by term. A budget a couple of GiB under the card is that much
|
||||
* of the expert plane streaming from host memory instead, which costs real prefill throughput
|
||||
* on a model whose experts do not fit.
|
||||
*
|
||||
* THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a
|
||||
* small dense model whose cache is already at the largest context it can address leaves many
|
||||
* GiB that NOTHING can spend, and warning there would tell the operator to leave unset the
|
||||
* very flags they already left unset. Where the resolver made the split it has already printed
|
||||
* every term including the unusable one, and there is nothing to add. */
|
||||
if (vram_capacity > 0 && !cfg.vram_budget_derived) {
|
||||
const int64_t slack = vram_capacity - want;
|
||||
if (slack >= 1024 * MiB)
|
||||
RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor "
|
||||
"accounted. The driver's context, the activation arena and "
|
||||
"--gpu-headroom-mib come out of it; anything past those is throughput on the "
|
||||
"floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split "
|
||||
"automatically.",
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str());
|
||||
}
|
||||
|
||||
int st = RAD_OK;
|
||||
int s;
|
||||
/* Order matters only for the diagnostic: allocate the two big ones first so a failure names
|
||||
|
||||
+2
-2
@@ -342,7 +342,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) {
|
||||
int64_t n_tokens, const std::string& label) {
|
||||
if (!enabled_) return RAD_OK;
|
||||
if (blocks.size() != groups_.size()) return RAD_E_INVAL;
|
||||
if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL;
|
||||
@@ -427,7 +427,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
if (it == map_.end()) continue;
|
||||
tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
|
||||
}
|
||||
tiers_->note_session(session, hs, n_tokens, now);
|
||||
tiers_->note_session(session, hs, n_tokens, now, label);
|
||||
}
|
||||
|
||||
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
|
||||
|
||||
+2
-1
@@ -206,7 +206,8 @@ public:
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens);
|
||||
int64_t n_tokens,
|
||||
const std::string& label = std::string());
|
||||
|
||||
/* Drop the least recently used entries, releasing their KV references. Returns how many were
|
||||
* dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
|
||||
|
||||
+51
-71
@@ -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;
|
||||
@@ -82,11 +83,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
const bool shared = host_reserve > b.headroom;
|
||||
if (shared) b.headroom = host_reserve;
|
||||
|
||||
/* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve
|
||||
* and inventing a capacity would be exactly the inference §6 forbids. */
|
||||
/* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
|
||||
* exactly the inference §6 forbids. What each pool needs is still known: the weights pool
|
||||
* holds what the planner would copy out of the container -- the statics and experts
|
||||
* weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
|
||||
* (The host backend reports half the machine's memory and is split like a card.) */
|
||||
if (b.capacity <= 0) {
|
||||
b.weights = cfg.vram_weights_mib * kMiB;
|
||||
b.kv = cfg.vram_kv_mib * kMiB;
|
||||
b.weights = std::max<int64_t>(b.statics + b.expert_ceiling, kMiB);
|
||||
b.kv = std::max<int64_t>(b.kv_ceiling, kMiB);
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
cfg.vram_kv_mib = to_mib_up(b.kv);
|
||||
if (log)
|
||||
b.report = fmt("the device reports no capacity: weights pool %s (what the planner "
|
||||
"copies out of the container), cache %s (every sequence at the full "
|
||||
"context)", humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -98,17 +109,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* plugin's init has run and its code object is resident. */
|
||||
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
|
||||
|
||||
const bool want_w = cfg.vram_weights_mib <= 0;
|
||||
const bool want_kv = cfg.vram_kv_mib <= 0;
|
||||
b.derived_weights = want_w;
|
||||
b.derived_kv = want_kv;
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
|
||||
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
|
||||
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
|
||||
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
|
||||
b.claimable = b.capacity - fixed;
|
||||
b.drift = kDriverDrift;
|
||||
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
|
||||
b.queues + b.prefetch);
|
||||
|
||||
if (b.claimable < 0) {
|
||||
b.report = fmt(
|
||||
@@ -120,7 +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"
|
||||
"%s%s"
|
||||
" 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), "
|
||||
@@ -128,42 +132,31 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
|
||||
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
|
||||
humanb(-b.claimable).c_str());
|
||||
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;
|
||||
}
|
||||
|
||||
b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB;
|
||||
b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB;
|
||||
|
||||
/* ---- the static weights come off the top ------------------------------------------------
|
||||
*
|
||||
* They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator
|
||||
* who stated --vram-weights-mib has already decided what the weights get, and second-guessing
|
||||
* that is the re-optimisation §6 forbids. */
|
||||
if (want_w) {
|
||||
b.statics = std::min(b.statics, b.claimable);
|
||||
if (b.statics >= b.claimable && b.claimable > 0) {
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
}
|
||||
* They are a floor and not a share. */
|
||||
b.statics = std::min(b.statics, b.claimable);
|
||||
if (b.statics >= b.claimable && b.claimable > 0) {
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
}
|
||||
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
|
||||
b.elastic = b.claimable - b.statics;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is divided --------------------------------------------------- */
|
||||
if (want_w && want_kv) {
|
||||
{
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
|
||||
* zero, which weight_footprint always measures. */
|
||||
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
|
||||
@@ -198,20 +191,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.kv = kv;
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
|
||||
} else if (want_kv) {
|
||||
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
|
||||
b.unusable = b.claimable - b.kv;
|
||||
} else if (want_w) {
|
||||
/* The KV pool was stated, so `claimable` is already net of it; the weights take the rest,
|
||||
* still capped at what the model has to put there. */
|
||||
int64_t exp = b.elastic;
|
||||
if (exp > b.expert_ceiling) {
|
||||
b.unusable = exp - b.expert_ceiling;
|
||||
exp = b.expert_ceiling;
|
||||
}
|
||||
b.experts = exp;
|
||||
b.weights = b.statics + exp;
|
||||
}
|
||||
/* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
|
||||
* container's mapping has it -- every op on the host, on the host backend -- the statics and
|
||||
* experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
|
||||
* out of the headroom as the rounding's is. */
|
||||
b.weights = std::max<int64_t>(b.weights, kMiB);
|
||||
|
||||
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
|
||||
*
|
||||
@@ -227,12 +212,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* The share is the budget's -- what the slab alone leaves off -- which is the most a step can
|
||||
* see: the loans the KV cache and the smaller arena levels make only ever add residency. A
|
||||
* layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
|
||||
if (want_w && layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
cfg.placement != "layer_offload") {
|
||||
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
|
||||
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
|
||||
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
if (b.lends && want_kv) {
|
||||
if (b.lends) {
|
||||
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
|
||||
* leave one with no tier, while the region is lent to the slab whenever the steps are
|
||||
* small -- the same memory the cache would have lent. */
|
||||
@@ -263,7 +248,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
|
||||
* context no single request can complete is a configuration error however much slack the pool
|
||||
* has (core/engine_bringup.cpp, configure_kv). */
|
||||
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
|
||||
"%.1f full-length sessions. That is concurrency at length before the scheduler "
|
||||
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
|
||||
@@ -276,13 +261,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
|
||||
* cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful
|
||||
* fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was
|
||||
* STATED it is not ours to shave and the MiB comes out of the headroom instead. */
|
||||
cfg.vram_budget_derived = want_w || want_kv;
|
||||
* cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
|
||||
* the headroom stays whole. */
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
|
||||
cfg.vram_kv_mib = want_kv ? to_mib(std::max<int64_t>(b.kv - w_over, 0)) : to_mib(b.kv);
|
||||
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
|
||||
|
||||
/* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
|
||||
* can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
|
||||
@@ -290,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"
|
||||
@@ -301,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"
|
||||
@@ -318,15 +302,13 @@ 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; --vram-kv-mib states a pool "
|
||||
"outright"
|
||||
shared ? "integrated graphics: this memory is the host's"
|
||||
: "left unclaimed on purpose",
|
||||
humanb(b.claimable).c_str(),
|
||||
humanb(b.statics).c_str(),
|
||||
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
|
||||
: "(not charged here -- --vram-weights-mib was stated)",
|
||||
"off the top: every rank's own shard, and not a share of anything",
|
||||
humanb(b.elastic).c_str(),
|
||||
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
|
||||
" and lends what no live request holds to the "
|
||||
@@ -375,10 +357,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"slab while steps are small\n", humanb(b.stage).c_str(),
|
||||
b.lends ? "cache" : "experts").c_str()
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(),
|
||||
b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
|
||||
humanb(unclaimed).c_str());
|
||||
|
||||
if (out) *out = b;
|
||||
|
||||
+18
-7
@@ -3,7 +3,7 @@
|
||||
* ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
|
||||
*
|
||||
* Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
|
||||
* re-optimise a split the operator stated. The reason given there is exact and worth repeating:
|
||||
* re-optimise the split it is handed. The reason given there is exact and worth repeating:
|
||||
* a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
|
||||
* window on the machine's desktop.
|
||||
*
|
||||
@@ -46,10 +46,17 @@
|
||||
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
|
||||
* both fit, both are whole.
|
||||
*
|
||||
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
|
||||
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
|
||||
* THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
|
||||
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
|
||||
* GiB costs measurable decode time.
|
||||
* GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
|
||||
* takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
|
||||
* decides which experts must stay on the card -- and the arithmetic follows from them.
|
||||
*
|
||||
* A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
|
||||
* split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
|
||||
* where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
|
||||
* capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
|
||||
* at its ceiling.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -74,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
|
||||
@@ -97,12 +107,14 @@ struct VramFacts {
|
||||
int64_t host_reserve = 0;
|
||||
};
|
||||
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including when the
|
||||
* operator stated the budgets -- the placement report and the pool report both want the totals. */
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
|
||||
* device that reports no capacity -- the placement report and the pool report both want the
|
||||
* totals. */
|
||||
struct VramBudget {
|
||||
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
|
||||
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
|
||||
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 */
|
||||
@@ -120,7 +132,6 @@ struct VramBudget {
|
||||
* any. */
|
||||
int64_t stage = 0;
|
||||
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
|
||||
bool derived_weights = false, derived_kv = false;
|
||||
std::string report; /* the block the engine prints at startup */
|
||||
};
|
||||
|
||||
|
||||
+19
-5
@@ -7,13 +7,27 @@ namespace rad {
|
||||
namespace mm {
|
||||
|
||||
void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
/* AN AUDIO CLIP IS 1-D (RadBatch::enc): the frame's index, whether it is real, the clip's real
|
||||
* frames and its staged ones. */
|
||||
if (kind == Kind::Audio) {
|
||||
for (int64_t k = 0; k < count; ++k) {
|
||||
const int64_t f = first + k;
|
||||
planes[k] = (int32_t)f;
|
||||
planes[count + k] = f < valid ? 1 : 0;
|
||||
planes[2 * count + k] = valid;
|
||||
planes[3 * count + k] = grid_h;
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* Merge-block order inverted: a patch's index within its segment is
|
||||
* ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */
|
||||
const int64_t seg = (int64_t)grid_h * grid_w;
|
||||
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);
|
||||
@@ -21,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+184
-8
@@ -10,8 +10,10 @@
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/imgutils.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
#include <libswscale/swscale.h>
|
||||
}
|
||||
#endif
|
||||
@@ -36,6 +38,10 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
|
||||
std::string* why) {
|
||||
return no_decoder(why);
|
||||
}
|
||||
int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
|
||||
std::string* why) {
|
||||
return no_decoder(why);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
@@ -150,13 +156,19 @@ struct Input {
|
||||
|
||||
/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the
|
||||
* frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were
|
||||
* encoded with; ACCURATE_RND and FULL_CHR_H_INT keep the conversion from truncating and from
|
||||
* sampling chroma at half resolution. */
|
||||
* encoded with.
|
||||
*
|
||||
* THE SCALER FLAGS ARE THE REFERENCE PIPELINE'S: transformers decodes video through PyAV
|
||||
* (`to_ndarray(format="rgb24")`, its default backend), which converts with plain SWS_BILINEAR.
|
||||
* The flags decide how chroma is upsampled, and at a sharp colour edge two choices differ by up to
|
||||
* 70 levels: measured on an EmbeddingGemma 2 clip, SWS_BICUBIC | ACCURATE_RND | FULL_CHR_H_INT
|
||||
* left the embedding at cosine 0.9995 against the reference, these at 0.99998 with every patch
|
||||
* within one level. */
|
||||
int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
const AVPixelFormat src = (AVPixelFormat)f->format;
|
||||
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
|
||||
AV_PIX_FMT_RGB24,
|
||||
SWS_BICUBIC | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, nullptr,
|
||||
SWS_BILINEAR, nullptr,
|
||||
nullptr, nullptr);
|
||||
if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
|
||||
int cs = f->colorspace;
|
||||
@@ -167,13 +179,35 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
|
||||
sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
|
||||
1 << 16, 1 << 16);
|
||||
/* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
|
||||
* store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
|
||||
* 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
|
||||
* exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
|
||||
* at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
|
||||
* and the end as the scaler expects. */
|
||||
AVFrame* rgb = av_frame_alloc();
|
||||
if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
rgb->format = AV_PIX_FMT_RGB24;
|
||||
rgb->width = f->width;
|
||||
rgb->height = f->height;
|
||||
if (av_frame_get_buffer(rgb, 0) < 0) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "out of memory";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
|
||||
if (e != f->height) {
|
||||
av_frame_free(&rgb);
|
||||
*why = "colour conversion failed";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
out->rgb.resize((size_t)f->width * (size_t)f->height * 3);
|
||||
uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr };
|
||||
int dst_ls[4] = { f->width * 3, 0, 0, 0 };
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls);
|
||||
if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; }
|
||||
const size_t row = (size_t)f->width * 3;
|
||||
out->rgb.resize(row * (size_t)f->height);
|
||||
for (int y = 0; y < f->height; ++y)
|
||||
std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
|
||||
av_frame_free(&rgb);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -360,6 +394,148 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== audio */
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE AUDIO DEMUXERS A REQUEST MAY REACH, chosen as the video list is: formats that hold one
|
||||
* stream of samples and cannot name another file. */
|
||||
constexpr const char* kAudioFormats = "wav,w64,mp3,flac,ogg,mov,mp4,m4a,matroska,webm,aac,aiff";
|
||||
|
||||
struct AudioIn {
|
||||
MemIO io;
|
||||
AVIOContext* avio = nullptr;
|
||||
AVFormatContext* fmt = nullptr;
|
||||
AVCodecContext* dec = nullptr;
|
||||
SwrContext* swr = nullptr;
|
||||
int stream = -1;
|
||||
|
||||
~AudioIn() {
|
||||
if (swr) swr_free(&swr);
|
||||
if (dec) avcodec_free_context(&dec);
|
||||
if (fmt) avformat_close_input(&fmt);
|
||||
if (avio) {
|
||||
av_freep(&avio->buffer);
|
||||
avio_context_free(&avio);
|
||||
}
|
||||
}
|
||||
|
||||
int open(const uint8_t* data, size_t n, std::string* why) {
|
||||
io.p = data; io.n = n; io.at = 0;
|
||||
constexpr int kBuf = 64 * 1024;
|
||||
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kBuf));
|
||||
if (!buf) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
avio = avio_alloc_context(buf, kBuf, 0, &io, mem_read, nullptr, mem_seek);
|
||||
if (!avio) { av_free(buf); *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
fmt = avformat_alloc_context();
|
||||
if (!fmt) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
fmt->pb = avio;
|
||||
fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
|
||||
AVDictionary* opts = nullptr;
|
||||
av_dict_set(&opts, "format_whitelist", kAudioFormats, 0);
|
||||
av_dict_set(&opts, "protocol_whitelist", "", 0);
|
||||
int e = avformat_open_input(&fmt, nullptr, nullptr, &opts);
|
||||
av_dict_free(&opts);
|
||||
if (e < 0) {
|
||||
fmt = nullptr;
|
||||
*why = "not a recognised audio format (" + averr(e) + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
e = avformat_find_stream_info(fmt, nullptr);
|
||||
if (e < 0) { *why = "could not read the stream headers (" + averr(e) + ")"; return RAD_E_INVAL; }
|
||||
const AVCodec* codec = nullptr;
|
||||
stream = av_find_best_stream(fmt, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
|
||||
if (stream < 0 || !codec) { *why = "no sound in it: the media holds no audio stream"; return RAD_E_INVAL; }
|
||||
dec = avcodec_alloc_context3(codec);
|
||||
if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar);
|
||||
if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; }
|
||||
dec->thread_count = 1;
|
||||
e = avcodec_open2(dec, codec, nullptr);
|
||||
if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; }
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
|
||||
std::vector<float>* out, std::string* why) {
|
||||
std::string w;
|
||||
if (!why) why = &w;
|
||||
out->clear();
|
||||
if (rate <= 0 || max_samples <= 0) { *why = "no sample rate or length to decode to"; return RAD_E_INVAL; }
|
||||
AudioIn in;
|
||||
RAD_TRY(in.open(data, n, why));
|
||||
AVCodecContext* dec = in.dec;
|
||||
const int channels = dec->ch_layout.nb_channels > 0 ? dec->ch_layout.nb_channels : 1;
|
||||
if (dec->sample_rate <= 0) { *why = "the audio stream states no sample rate"; return RAD_E_INVAL; }
|
||||
|
||||
/* Resampled at the source's own layout, float interleaved; the mono mean is taken after. A
|
||||
* layout the stream does not state is taken as `channels` unordered channels. */
|
||||
AVChannelLayout layout{};
|
||||
if (av_channel_layout_check(&dec->ch_layout)) av_channel_layout_copy(&layout, &dec->ch_layout);
|
||||
else av_channel_layout_default(&layout, channels);
|
||||
int e = swr_alloc_set_opts2(&in.swr, &layout, AV_SAMPLE_FMT_FLT, rate, &layout,
|
||||
(AVSampleFormat)dec->sample_fmt, dec->sample_rate, 0, nullptr);
|
||||
av_channel_layout_uninit(&layout);
|
||||
if (e < 0 || !in.swr || swr_init(in.swr) < 0) {
|
||||
*why = "no resampler for this audio (" + averr(e) + ")";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
std::vector<float> buf;
|
||||
auto take = [&](const uint8_t** src, int n_in) -> int {
|
||||
const int cap = swr_get_out_samples(in.swr, n_in);
|
||||
if (cap <= 0) return 0;
|
||||
buf.resize((size_t)cap * (size_t)channels);
|
||||
uint8_t* dst = reinterpret_cast<uint8_t*>(buf.data());
|
||||
const int got = swr_convert(in.swr, &dst, cap, src, n_in);
|
||||
if (got < 0) { *why = "resampling failed (" + averr(got) + ")"; return RAD_E_INVAL; }
|
||||
for (int i = 0; i < got && (int64_t)out->size() < max_samples; ++i) {
|
||||
float s = 0.0f;
|
||||
for (int c = 0; c < channels; ++c) s += buf[(size_t)i * channels + c];
|
||||
out->push_back(channels == 1 ? s : s / (float)channels);
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
AVPacket* pkt = av_packet_alloc();
|
||||
AVFrame* f = av_frame_alloc();
|
||||
if (!pkt || !f) {
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&f);
|
||||
*why = "out of memory";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
int st = RAD_OK;
|
||||
bool done = false;
|
||||
while (!done && (int64_t)out->size() < max_samples) {
|
||||
e = av_read_frame(in.fmt, pkt);
|
||||
if (e < 0) {
|
||||
avcodec_send_packet(dec, nullptr); /* drain */
|
||||
done = true;
|
||||
} else {
|
||||
if (pkt->stream_index == in.stream) e = avcodec_send_packet(dec, pkt);
|
||||
av_packet_unref(pkt);
|
||||
if (e < 0 && e != AVERROR(EAGAIN)) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
|
||||
}
|
||||
while ((e = avcodec_receive_frame(dec, f)) >= 0) {
|
||||
if ((st = take(const_cast<const uint8_t**>(f->extended_data), f->nb_samples)) < 0) break;
|
||||
av_frame_unref(f);
|
||||
}
|
||||
if (st < 0) break;
|
||||
if (e != AVERROR(EAGAIN) && e != AVERROR_EOF) { *why = "the audio would not decode (" + averr(e) + ")"; st = RAD_E_INVAL; break; }
|
||||
}
|
||||
/* What the resampler still holds. */
|
||||
if (st == RAD_OK && (int64_t)out->size() < max_samples) st = take(nullptr, 0);
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&f);
|
||||
if (st < 0) return st;
|
||||
if (out->empty()) { *why = "the audio decoded to no samples"; return RAD_E_INVAL; }
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#endif /* RAD_HAVE_FFMPEG */
|
||||
|
||||
} /* namespace mm */
|
||||
|
||||
@@ -56,5 +56,13 @@ struct Video {
|
||||
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
|
||||
int64_t max_pixels, Video* out, std::string* why);
|
||||
|
||||
/* AN AUDIO CLIP as mono float samples at `rate` Hz: the first audio stream, resampled with
|
||||
* libswresample at the source's channel layout and then averaged across channels -- the plain
|
||||
* mean every reference loader (librosa, torchaudio's to-mono) takes, where swresample's own
|
||||
* downmix would weight a stereo pair by 0.707. At most `max_samples` are kept: a longer clip is
|
||||
* cut there, as the reference feature extractor truncates. */
|
||||
int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples,
|
||||
std::vector<float>* out, std::string* why);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
+799
-33
@@ -26,7 +26,113 @@ static bool read_triple(const RadModelMeta& m, const char* key, float out[3]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool soft_budget_ok(int32_t n) {
|
||||
return n == 70 || n == 140 || n == 280 || n == 560 || n == 1120;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.pooling_kernel_size", 0);
|
||||
temporal = 1;
|
||||
if (patch <= 0 || merge <= 0) {
|
||||
if (why) *why = "the container states no vision tower geometry (vision_config."
|
||||
"patch_size, pooling_kernel_size)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
|
||||
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
|
||||
tok_start = (int32_t)rad_meta_geti(&m, "boi_token_id", -1);
|
||||
tok_end = (int32_t)rad_meta_geti(&m, "eoi_token_id", -1);
|
||||
if (tok_image < 0 || tok_video < 0 || tok_start < 0 || tok_end < 0) {
|
||||
if (why) *why = "the container states no media token ids (image_token_id, "
|
||||
"video_token_id, boi_token_id, eoi_token_id)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* The budgets from the processor config, the model's stated default when it is absent. */
|
||||
image_soft_tokens = (int32_t)rad_meta_geti(
|
||||
&m, "processor.image_processor.max_soft_tokens",
|
||||
rad_meta_geti(&m, "vision_soft_tokens_per_image",
|
||||
rad_meta_geti(&m, "vision_config.default_output_length", 280)));
|
||||
video_soft_tokens = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_soft_tokens",
|
||||
70);
|
||||
fps = rad_meta_getf(&m, "processor.video_processor.fps", 1.0);
|
||||
min_frames = 1;
|
||||
max_frames = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_frames", 32);
|
||||
max_frame_rows = 0;
|
||||
/* The pixel bands are QwenVL's; here they only have to be consistent for check(). */
|
||||
const int64_t f2 = (int64_t)factor() * factor();
|
||||
image_min_pixels = video_min_pixels = f2;
|
||||
image_max_pixels = (int64_t)image_soft_tokens * f2;
|
||||
video_max_pixels = (int64_t)video_soft_tokens * f2 * max_frames;
|
||||
std::string bad;
|
||||
if (check(&bad) < 0) {
|
||||
if (why) *why = "the container's processor configuration is inconsistent: " + bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
temporal = (int32_t)rad_meta_geti(&m, "vision_config.temporal_patch_size", 0);
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.spatial_merge_size", 0);
|
||||
@@ -90,6 +196,24 @@ 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) +
|
||||
" is not one of 70, 140, 280, 560, 1120");
|
||||
if (!soft_budget_ok(video_soft_tokens))
|
||||
return no("the video frame soft-token budget " + std::to_string(video_soft_tokens) +
|
||||
" is not one of 70, 140, 280, 560, 1120");
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -173,6 +297,65 @@ std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t mi
|
||||
return idx;
|
||||
}
|
||||
|
||||
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
|
||||
int64_t* oh, int64_t* ow, std::string* why) {
|
||||
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
|
||||
/* get_aspect_ratio_preserving_size, in Python's doubles. */
|
||||
const double total = (double)h * (double)w;
|
||||
const double target = (double)max_patches * (double)patch * (double)patch;
|
||||
const double factor = std::sqrt(target / total);
|
||||
const int64_t side = (int64_t)patch * pool;
|
||||
int64_t th = (int64_t)std::floor(factor * (double)h / (double)side) * side;
|
||||
int64_t tw = (int64_t)std::floor(factor * (double)w / (double)side) * side;
|
||||
if (th == 0 && tw == 0) {
|
||||
if (why) *why = "the picture is too small to make one pooled patch";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t max_side = (max_patches / ((int64_t)pool * pool)) * side;
|
||||
if (th == 0) {
|
||||
th = side;
|
||||
tw = std::min<int64_t>((int64_t)std::floor((double)w / (double)h) * side, max_side);
|
||||
} else if (tw == 0) {
|
||||
tw = side;
|
||||
th = std::min<int64_t>((int64_t)std::floor((double)h / (double)w) * side, max_side);
|
||||
}
|
||||
if ((double)th * (double)tw > target) {
|
||||
if (why) *why = "the picture's aspect ratio does not fit the patch budget";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
*oh = th;
|
||||
*ow = tw;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`,
|
||||
* one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by
|
||||
* numpy's linspace truncated to integers. */
|
||||
std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames) {
|
||||
const int64_t total = info.n_frames;
|
||||
if (total <= 0) return {};
|
||||
std::vector<int64_t> idx;
|
||||
if (info.fps > 0.0) {
|
||||
const double step = info.fps / fps;
|
||||
const double duration = (double)total / info.fps;
|
||||
const int64_t n = std::max<int64_t>(1, (int64_t)(duration * fps));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
idx.push_back(std::min<int64_t>(total - 1, (int64_t)((double)i * step)));
|
||||
} else {
|
||||
for (int64_t i = 0; i < total; ++i) idx.push_back(i);
|
||||
}
|
||||
if (max_frames > 0 && (int64_t)idx.size() > max_frames) {
|
||||
std::vector<int64_t> keep((size_t)max_frames);
|
||||
const double span = (double)(idx.size() - 1);
|
||||
for (int32_t i = 0; i < max_frames; ++i) {
|
||||
const double t = max_frames == 1 ? 0.0 : span * (double)i / (double)(max_frames - 1);
|
||||
keep[(size_t)i] = idx[(size_t)(int64_t)t];
|
||||
}
|
||||
idx.swap(keep);
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* ================================================================== the resample
|
||||
*
|
||||
* Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double,
|
||||
@@ -192,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) {
|
||||
@@ -226,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];
|
||||
@@ -265,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;
|
||||
@@ -289,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 {
|
||||
@@ -320,7 +526,12 @@ inline uint64_t mix64(uint64_t x) {
|
||||
void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
|
||||
uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^
|
||||
(uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
|
||||
uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : 2u);
|
||||
uint64_t b = 0xbb67ae8584caa73bull ^
|
||||
mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u);
|
||||
/* 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;
|
||||
@@ -375,6 +586,37 @@ void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, It
|
||||
}
|
||||
}
|
||||
|
||||
/* Gemma 4's patch rows: merge-block order like patchify's (each pooling window's patches are
|
||||
* consecutive, which is what lets the pooler be a mean of k^2 consecutive rows; attention and the
|
||||
* position terms read each patch's own coordinates, so the order is free), each row (y, x,
|
||||
* channel), each value 2 * (u * (1/255)) - 1 in f32 -- the processor's rescale and then the
|
||||
* model's own input scaling -- rounded to bf16. One frame a segment. */
|
||||
void patchify_gemma4(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
|
||||
const int P = c.patch, M = c.merge;
|
||||
const int gh = it->grid_h, gw = it->grid_w;
|
||||
uint16_t lut[256];
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = (float)v * (float)(1.0 / 255.0);
|
||||
lut[v] = rad_f32_to_bf16(2.0f * (p - 0.5f));
|
||||
}
|
||||
const int64_t dim = it->patch_dim;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
uint16_t* dst = it->pixels.data();
|
||||
for (int g = 0; g < it->grid_t; ++g) {
|
||||
const Frame& f = *frames[(size_t)g];
|
||||
for (int bh = 0; bh < gh / M; ++bh)
|
||||
for (int bw = 0; bw < gw / M; ++bw)
|
||||
for (int mh = 0; mh < M; ++mh)
|
||||
for (int mw = 0; mw < M; ++mw) {
|
||||
const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P;
|
||||
for (int y = 0; y < P; ++y) {
|
||||
const uint8_t* row = f.rgb.data() + ((size_t)(py0 + y) * f.w + px0) * 3;
|
||||
for (int x = 0; x < 3 * P; ++x) *dst++ = lut[row[x]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void finish_item(const VisionConfig& c, Item* it) {
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w;
|
||||
@@ -389,10 +631,42 @@ 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 ||
|
||||
(int64_t)cfg.video_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches)
|
||||
return RAD_E_INVAL;
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to
|
||||
* it, so smart_resize itself keeps every image inside a pass. */
|
||||
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
|
||||
@@ -404,8 +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));
|
||||
@@ -435,8 +834,80 @@ int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(gemma4_size(f.h, f.w, c.patch, c.merge, (int64_t)soft * c.merge * c.merge, &h, &w,
|
||||
why));
|
||||
Frame r;
|
||||
const Frame* src = &f;
|
||||
if (h != f.h || w != f.w) {
|
||||
resize_bicubic(f, (int32_t)w, (int32_t)h, &r);
|
||||
src = &r;
|
||||
}
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if (it->n_patch > c.max_patches) {
|
||||
if (why) *why = "the image's soft-token budget is more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
patchify_gemma4(c, { src }, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.reserve((size_t)it->seg_rows + 2);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
|
||||
it->expand.push_back(c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(gemma4_size(v.frames[0].h, v.frames[0].w, c.patch, c.merge,
|
||||
(int64_t)c.video_soft_tokens * c.merge * c.merge, &h, &w, why));
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Video;
|
||||
it->grid_t = (int32_t)v.frames.size();
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if ((int64_t)it->grid_h * it->grid_w > c.max_patches) {
|
||||
if (why) *why = "a video frame's soft-token budget is more patches than one encoder pass "
|
||||
"holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<Frame> resized(v.frames.size());
|
||||
std::vector<const Frame*> rf;
|
||||
for (size_t i = 0; i < v.frames.size(); ++i) {
|
||||
if (v.frames[i].h == h && v.frames[i].w == w) { rf.push_back(&v.frames[i]); continue; }
|
||||
resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
|
||||
rf.push_back(&resized[i]);
|
||||
}
|
||||
patchify_gemma4(c, rf, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
/* One <boi> placeholders <eoi> run a frame, back to back: the reference's visual-only form
|
||||
* (add_timestamps off). */
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back((int32_t)it->expand.size());
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video);
|
||||
it->expand.push_back(c.tok_end);
|
||||
}
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (c.family == Family::Gemma4) return video_gemma4(v, out, why);
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
/* The frames and their indices, padded to whole temporal groups by repeating the last. A clip
|
||||
* shorter than one group is padded the same way, so a single-frame video is one group. */
|
||||
@@ -516,29 +987,319 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
std::shared_ptr<Item>* out, std::string* why, 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 "
|
||||
"budget";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!soft_budget_ok(image_tokens) ||
|
||||
(int64_t)image_tokens * cfg_.merge * cfg_.merge > cfg_.max_patches) {
|
||||
if (why) *why = "the image token budget must be one of 70, 140, 280, 560, 1120 and "
|
||||
"fit one encoder pass (" + std::to_string(cfg_.max_patches) +
|
||||
" patches)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
Frame f;
|
||||
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
|
||||
if (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);
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct SampleArgs { double fps; int32_t lo, hi; };
|
||||
struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; };
|
||||
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
|
||||
const SampleArgs* a = static_cast<const SampleArgs*>(user);
|
||||
return sample_frames(info, a->fps, a->lo, a->hi);
|
||||
return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi)
|
||||
: sample_frames(info, a->fps, a->lo, a->hi);
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
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 };
|
||||
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames,
|
||||
cfg_.family == Family::Gemma4 };
|
||||
RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why));
|
||||
return video_from(v, out, why);
|
||||
}
|
||||
|
||||
/* ================================================================== audio */
|
||||
|
||||
/* A list a container flattened from a JSON array ("1 2 3"), or nothing when it is absent or null. */
|
||||
static std::vector<double> read_list(const RadModelMeta& m, const char* key) {
|
||||
std::vector<double> v;
|
||||
const char* s = rad_meta_gets(&m, key, nullptr);
|
||||
if (!s || !*s) return v;
|
||||
std::istringstream is(s);
|
||||
double x;
|
||||
while (is >> x) v.push_back(x);
|
||||
return v;
|
||||
}
|
||||
|
||||
int AudioConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
const char* mt = rad_meta_gets(&m, "audio_config.model_type", "");
|
||||
if (!mt || std::strcmp(mt, "gemma4_audio")) {
|
||||
if (why) *why = "the container states no audio tower this processor knows (audio_config."
|
||||
"model_type gemma4_audio)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
rate = (int32_t)rad_meta_geti(&m, "preprocessor.sampling_rate", 16000);
|
||||
frame_length = (int32_t)rad_meta_geti(&m, "preprocessor.frame_length", 320);
|
||||
hop = (int32_t)rad_meta_geti(&m, "preprocessor.hop_length", 160);
|
||||
n_mels = (int32_t)rad_meta_geti(&m, "preprocessor.feature_size", 128);
|
||||
fft = (int32_t)rad_meta_geti(&m, "preprocessor.fft_length", 0);
|
||||
if (fft <= 0) {
|
||||
fft = 1;
|
||||
while (fft < frame_length) fft *= 2;
|
||||
}
|
||||
if (rad_meta_geti(&m, "preprocessor.fft_overdrive", 0)) fft *= 2;
|
||||
min_freq = rad_meta_getf(&m, "preprocessor.min_frequency", 0.0);
|
||||
max_freq = rad_meta_getf(&m, "preprocessor.max_frequency", 8000.0);
|
||||
mel_floor = rad_meta_getf(&m, "preprocessor.mel_floor", 1e-3);
|
||||
preemphasis = rad_meta_getf(&m, "preprocessor.preemphasis", 0.0);
|
||||
preemphasis_htk = rad_meta_geti(&m, "preprocessor.preemphasis_htk_flavor", 1) != 0;
|
||||
input_scale = rad_meta_getf(&m, "preprocessor.input_scale_factor", 1.0);
|
||||
bin_mean = read_list(m, "preprocessor.per_bin_mean");
|
||||
bin_std = read_list(m, "preprocessor.per_bin_stddev");
|
||||
max_samples = 480000;
|
||||
tok_audio = (int32_t)rad_meta_geti(&m, "audio_token_id", -1);
|
||||
tok_start = (int32_t)rad_meta_geti(&m, "boa_token_id", -1);
|
||||
tok_end = (int32_t)rad_meta_geti(&m, "eoa_token_id", rad_meta_geti(&m, "eoa_token_index", -1));
|
||||
/* DITHER IS NOISE: the reference adds Gaussian noise of this deviation to every sample, a
|
||||
* different draw each call, and no fixed input reproduces it. */
|
||||
if (rad_meta_getf(&m, "preprocessor.dither", 0.0) != 0.0) {
|
||||
if (why) *why = "the feature extractor dithers its input (preprocessor.dither), which no "
|
||||
"deterministic front end reproduces";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rate <= 0 || frame_length <= 1 || hop <= 0 || n_mels <= 0 || fft < frame_length ||
|
||||
!(max_freq > min_freq) || !(mel_floor > 0.0) || tok_audio < 0 || tok_start < 0 ||
|
||||
tok_end < 0 || (!bin_mean.empty() && (int64_t)bin_mean.size() != n_mels) ||
|
||||
(!bin_std.empty() && (int64_t)bin_std.size() != n_mels)) {
|
||||
if (why) *why = "the container's audio feature configuration is incomplete or "
|
||||
"inconsistent (rate, frame and hop lengths, mel bins, frequencies, "
|
||||
"audio_token_id, boa_token_id, eoa_token_id)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t AudioConfig::real_frames(int64_t n) const {
|
||||
/* Frame i's last sample is (frame_length / 2 zeros) + i * hop + frame_length, and it is real
|
||||
* when that is inside the clip: i * hop + frame_length < frame_length / 2 + n. */
|
||||
const int64_t room = n + frame_length / 2 - frame_length - 1;
|
||||
return room < 0 ? 0 : room / hop + 1;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* An in-place radix-2 complex FFT, n a power of two: the frame's real spectrum in double, as the
|
||||
* reference's numpy rfft computes it. */
|
||||
void fft_inplace(std::vector<double>& re, std::vector<double>& im,
|
||||
const std::vector<double>& tw_re, const std::vector<double>& tw_im,
|
||||
const std::vector<int32_t>& brev) {
|
||||
const size_t n = re.size();
|
||||
for (size_t i = 1; i < n; ++i) {
|
||||
const size_t j = (size_t)brev[i];
|
||||
if (i < j) { std::swap(re[i], re[j]); std::swap(im[i], im[j]); }
|
||||
}
|
||||
for (size_t len = 2; len <= n; len <<= 1) {
|
||||
const size_t step = n / len; /* stage len's k-th twiddle is the table's k * step */
|
||||
for (size_t i = 0; i < n; i += len)
|
||||
for (size_t k = 0; k < len / 2; ++k) {
|
||||
const double wr = tw_re[k * step], wi = tw_im[k * step];
|
||||
const size_t a = i + k, b = i + k + len / 2;
|
||||
const double xr = re[b] * wr - im[b] * wi, xi = re[b] * wi + im[b] * wr;
|
||||
re[b] = re[a] - xr; im[b] = im[a] - xi;
|
||||
re[a] += xr; im[a] += xi;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* numpy.linspace's values: start + i * step, the last exactly `stop`. */
|
||||
std::vector<double> linspace(double a, double b, int64_t n) {
|
||||
std::vector<double> v((size_t)n);
|
||||
const double step = n > 1 ? (b - a) / (double)(n - 1) : 0.0;
|
||||
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = a + (double)i * step;
|
||||
if (n > 1) v[(size_t)n - 1] = b;
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int Processor::init_audio(const AudioConfig& cfg) {
|
||||
if (cfg.merge <= 0 || cfg.max_frames <= 0 || cfg.max_frames % cfg.merge) return RAD_E_INVAL;
|
||||
acfg_ = cfg;
|
||||
/* np.hanning(frame_length + 1)[:-1], the periodic window, stored as float32. */
|
||||
hann_.resize((size_t)cfg.frame_length);
|
||||
for (int32_t i = 0; i < cfg.frame_length; ++i)
|
||||
hann_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * M_PI * (double)i /
|
||||
(double)cfg.frame_length));
|
||||
/* transformers' mel_filter_bank(norm=None, mel_scale="htk"): triangles between consecutive
|
||||
* mel points, in Hz, over the FFT bins' frequencies. */
|
||||
const int64_t nb = cfg.fft / 2 + 1, nm = cfg.n_mels;
|
||||
auto hz2mel = [](double f) { return 2595.0 * std::log10(1.0 + f / 700.0); };
|
||||
auto mel2hz = [](double m) { return 700.0 * (std::pow(10.0, m / 2595.0) - 1.0); };
|
||||
const std::vector<double> fft_f = linspace(0.0, (double)(cfg.rate / 2), nb);
|
||||
std::vector<double> filt = linspace(hz2mel(cfg.min_freq), hz2mel(cfg.max_freq), nm + 2);
|
||||
for (double& f : filt) f = mel2hz(f);
|
||||
mel_.assign((size_t)(nb * nm), 0.0);
|
||||
mel_lo_.assign((size_t)nm, 0);
|
||||
mel_hi_.assign((size_t)nm, 0);
|
||||
for (int64_t i = 0; i < nm; ++i) {
|
||||
int32_t lo = -1, hi = 0;
|
||||
for (int64_t k = 0; k < nb; ++k) {
|
||||
const double down = -(filt[(size_t)i] - fft_f[(size_t)k]) /
|
||||
(filt[(size_t)i + 1] - filt[(size_t)i]);
|
||||
const double up = (filt[(size_t)i + 2] - fft_f[(size_t)k]) /
|
||||
(filt[(size_t)i + 2] - filt[(size_t)i + 1]);
|
||||
const double w = std::max(0.0, std::min(down, up));
|
||||
mel_[(size_t)(i * nb + k)] = w;
|
||||
if (w != 0.0) { if (lo < 0) lo = (int32_t)k; hi = (int32_t)k + 1; }
|
||||
}
|
||||
/* A triangle covers a few bins; the sum skips the zeros, which add nothing to it. */
|
||||
mel_lo_[(size_t)i] = lo < 0 ? 0 : lo;
|
||||
mel_hi_[(size_t)i] = hi;
|
||||
}
|
||||
/* The FFT's twiddles, once: a butterfly that evaluates its own sin and cos makes the
|
||||
* transform cost a 30 s clip over 100 ms. */
|
||||
brev_.assign((size_t)cfg.fft, 0);
|
||||
for (int32_t i = 1, j = 0; i < cfg.fft; ++i) {
|
||||
int32_t bit = cfg.fft >> 1;
|
||||
for (; j & bit; bit >>= 1) j ^= bit;
|
||||
j ^= bit;
|
||||
brev_[(size_t)i] = j;
|
||||
}
|
||||
tw_re_.resize((size_t)cfg.fft / 2);
|
||||
tw_im_.resize((size_t)cfg.fft / 2);
|
||||
for (int32_t k = 0; k < cfg.fft / 2; ++k) {
|
||||
const double ang = -2.0 * M_PI * (double)k / (double)cfg.fft;
|
||||
tw_re_[(size_t)k] = std::cos(ang);
|
||||
tw_im_[(size_t)k] = std::sin(ang);
|
||||
}
|
||||
audio_on_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
const AudioConfig& c = acfg_;
|
||||
const int64_t n = std::min<int64_t>((int64_t)samples.size(), c.max_samples);
|
||||
const int64_t real = c.real_frames(n);
|
||||
const int64_t rows = (real + c.merge - 1) / c.merge;
|
||||
const int64_t frames = rows * c.merge;
|
||||
if (frames > c.max_frames) {
|
||||
if (why) *why = "the clip is more frames than one audio encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Audio;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)frames;
|
||||
it->grid_w = 1;
|
||||
it->patch_dim = c.n_mels;
|
||||
it->n_patch = frames;
|
||||
it->valid = (int32_t)real;
|
||||
it->rows_h = (int32_t)rows;
|
||||
it->rows_w = 1;
|
||||
it->seg_rows = (int32_t)rows;
|
||||
it->n_seg = rows > 0 ? 1 : 0;
|
||||
it->pixels.assign((size_t)(frames * c.n_mels), 0);
|
||||
|
||||
const int64_t pad = c.frame_length / 2;
|
||||
const int64_t nb = c.fft / 2 + 1;
|
||||
std::vector<double> re((size_t)c.fft), im((size_t)c.fft), mag((size_t)nb);
|
||||
std::vector<float> fr((size_t)c.frame_length + 1);
|
||||
auto sample = [&](int64_t p) -> float { /* the zero-led clip, zero past its end */
|
||||
const int64_t q = p - pad;
|
||||
return q >= 0 && q < n ? samples[(size_t)q] * (float)c.input_scale : 0.0f;
|
||||
};
|
||||
/* Frame i's windowed samples into dst, zero past the frame. */
|
||||
auto window = [&](int64_t i, double* dst) {
|
||||
for (int32_t j = 0; j <= c.frame_length; ++j) fr[(size_t)j] = sample(i * c.hop + j);
|
||||
for (int32_t j = 0; j < c.frame_length; ++j) {
|
||||
float v;
|
||||
if (c.preemphasis > 0.0) {
|
||||
const float pe = (float)c.preemphasis;
|
||||
v = c.preemphasis_htk ? (j == 0 ? fr[0] * (1.0f - pe) : fr[(size_t)j] - pe * fr[(size_t)j - 1])
|
||||
: fr[(size_t)j + 1] - pe * fr[(size_t)j];
|
||||
} else {
|
||||
v = fr[(size_t)j];
|
||||
}
|
||||
dst[j] = (double)(v * hann_[(size_t)j]); /* the product in float32 */
|
||||
}
|
||||
for (int32_t j = c.frame_length; j < c.fft; ++j) dst[j] = 0.0;
|
||||
};
|
||||
/* Frame i's mel bins from its magnitudes. */
|
||||
auto emit = [&](int64_t i, const double* m) {
|
||||
uint16_t* dst = it->pixels.data() + i * c.n_mels;
|
||||
for (int32_t b = 0; b < c.n_mels; ++b) {
|
||||
double s = 0.0;
|
||||
const double* w = mel_.data() + (size_t)b * nb;
|
||||
for (int32_t k = mel_lo_[(size_t)b]; k < mel_hi_[(size_t)b]; ++k) s += m[k] * w[k];
|
||||
double v = std::log(s + c.mel_floor);
|
||||
if (!c.bin_mean.empty()) v -= c.bin_mean[(size_t)b];
|
||||
if (!c.bin_std.empty()) v /= c.bin_std[(size_t)b];
|
||||
dst[b] = rad_f32_to_bf16((float)v);
|
||||
}
|
||||
};
|
||||
/* TWO REAL FRAMES A COMPLEX TRANSFORM: frame a in the real part, frame b in the imaginary,
|
||||
* and the two spectra separate by symmetry -- A[k] = (Z[k] + conj Z[n-k]) / 2 and
|
||||
* B[k] = (Z[k] - conj Z[n-k]) / 2i. Half the transforms; the magnitudes agree with one
|
||||
* transform a frame to a few ulps of double. |X| is sqrt(re^2 + im^2), within an ulp of
|
||||
* numpy's hypot and far below the float32 the features are rounded to. */
|
||||
std::vector<double> mag2((size_t)nb);
|
||||
const int64_t N = c.fft;
|
||||
for (int64_t i = 0; i < real; i += 2) {
|
||||
const bool pair = i + 1 < real;
|
||||
window(i, re.data());
|
||||
if (pair) window(i + 1, im.data());
|
||||
else std::fill(im.begin(), im.end(), 0.0);
|
||||
fft_inplace(re, im, tw_re_, tw_im_, brev_);
|
||||
for (int64_t k = 0; k < nb; ++k) {
|
||||
const size_t a = (size_t)k, b = k ? (size_t)(N - k) : 0;
|
||||
const double ar = 0.5 * (re[a] + re[b]), ai = 0.5 * (im[a] - im[b]);
|
||||
const double br = 0.5 * (im[a] + im[b]), bi = -0.5 * (re[a] - re[b]);
|
||||
mag[a] = std::sqrt(ar * ar + ai * ai);
|
||||
mag2[a] = std::sqrt(br * br + bi * bi);
|
||||
}
|
||||
emit(i, mag.data());
|
||||
if (pair) emit(i + 1, mag2.data());
|
||||
}
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)rows, c.tok_audio);
|
||||
it->expand.push_back(c.tok_end);
|
||||
/* A clip too short for one real frame is <boa><eoa> and nothing to encode. */
|
||||
if (rows == 0) it->encoded = true;
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
if (!audio_on_) { if (why) *why = "this program declares no audio encoder"; return RAD_E_UNSUPPORTED; }
|
||||
std::vector<float> s;
|
||||
RAD_TRY(decode_audio(bytes, n, acfg_.rate, acfg_.max_samples, &s, why));
|
||||
return audio_from(s, out, why);
|
||||
}
|
||||
|
||||
/* ================================================================== rotary layout */
|
||||
|
||||
void PromptMedia::layout() {
|
||||
@@ -547,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);
|
||||
}
|
||||
}
|
||||
|
||||
+147
-6
@@ -37,10 +37,33 @@ struct RadModelMeta;
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
enum class Kind { Image, Video };
|
||||
enum class Kind { Image, Video, Audio };
|
||||
|
||||
/* THE PROCESSOR FAMILY, from the container's vision_config.model_type. The two differ in how a
|
||||
* picture is sized, what a patch value is, and how a video is sampled and spelled in the prompt;
|
||||
* the Item they produce and everything after it is shared.
|
||||
*
|
||||
* QwenVL smart_resize into a pixel band; patches (channel, frame, y, x) normalised by the
|
||||
* configured mean and deviation; videos in temporal groups, each after a "<T seconds>".
|
||||
* Gemma4 the largest size whose sides are multiples of patch * pooling and whose patch count
|
||||
* fits the soft-token budget (budget * pooling^2), aspect ratio kept; patches (y, x,
|
||||
* channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is
|
||||
* frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment
|
||||
* at the per-frame budget, each spelled <boi> placeholders <eoi> with no timestamp.
|
||||
* 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;
|
||||
int32_t patch = 0, temporal = 0, merge = 0;
|
||||
/* Gemma4: soft tokens (output rows) an image, and a video frame, may take. One of 70, 140,
|
||||
* 280, 560, 1120 -- the budgets the model was trained at. */
|
||||
int32_t image_soft_tokens = 0, video_soft_tokens = 0;
|
||||
int64_t image_min_pixels = 0, image_max_pixels = 0;
|
||||
int64_t video_min_pixels = 0, video_max_pixels = 0;
|
||||
double fps = 2.0;
|
||||
@@ -52,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
|
||||
@@ -75,6 +103,37 @@ struct VisionConfig {
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
};
|
||||
|
||||
/* WHAT AN AUDIO CLIP BECOMES: Gemma 4's feature extractor (Gemma4AudioFeatureExtractor), read
|
||||
* from the container's `preprocessor.*` (the checkpoint's preprocessor_config.json) and its
|
||||
* audio_config. The samples are mono at `rate`, cut at `max_samples`; `frame_length / 2` zeros go
|
||||
* in front; frame i is samples [i * hop, i * hop + frame_length) of that, pre-emphasised when the
|
||||
* config says so, times a periodic Hann window, through a `fft`-point real FFT; its magnitudes go
|
||||
* through an HTK mel bank (no area normalisation) and log(x + mel_floor), optionally standardised
|
||||
* per bin. A frame is real when its last sample is a real one -- the reference's mask -- so a clip
|
||||
* of n samples has floor((n - frame_length / 2 - 1) / hop) + 1 real frames and the reference's
|
||||
* output keeps ceil(real / merge) rows of it: that many placeholders, between <boa> and <eoa>.
|
||||
* The staged patches are the real frames then zero frames to a whole number of rows -- equal, for
|
||||
* every row the reference keeps, to the frames past the end the reference zeroes. */
|
||||
struct AudioConfig {
|
||||
int32_t rate = 0, frame_length = 0, hop = 0, fft = 0, n_mels = 0;
|
||||
double min_freq = 0.0, max_freq = 0.0, mel_floor = 0.0;
|
||||
double preemphasis = 0.0, input_scale = 1.0;
|
||||
bool preemphasis_htk = true;
|
||||
std::vector<double> bin_mean, bin_std; /* empty: no per-bin standardisation */
|
||||
/* The longest clip in samples: Gemma 4's extractor truncates at 480000 (30 s at 16 kHz). */
|
||||
int64_t max_samples = 0;
|
||||
int32_t tok_audio = -1, tok_start = -1, tok_end = -1;
|
||||
|
||||
/* THE ENCODER'S: frames an output row, and the most frames a pass carries. */
|
||||
int32_t merge = 0;
|
||||
int64_t max_frames = 0;
|
||||
|
||||
/* Read from the container; refuses one that states no Gemma 4 audio tower. */
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
/* The real frames of an n-sample clip. */
|
||||
int64_t real_frames(int64_t n_samples) const;
|
||||
};
|
||||
|
||||
/* One media part after processing: its patches, its place in the prompt's token stream, and --
|
||||
* once the encoder has run -- its rows. Shared between the request that owns it and the engine
|
||||
* thread that encodes it; the engine writes `embd` once and nothing reads it before then. */
|
||||
@@ -88,7 +147,33 @@ struct Item {
|
||||
/* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group.
|
||||
* `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */
|
||||
int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0;
|
||||
int64_t n_rows() const { return (int64_t)n_seg * seg_rows; }
|
||||
/* 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;
|
||||
|
||||
/* 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:
|
||||
@@ -124,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 */
|
||||
|
||||
@@ -144,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);
|
||||
@@ -180,19 +266,50 @@ 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_; }
|
||||
|
||||
int image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
|
||||
* processor that sizes images by pixels refuses a non-zero one. `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, 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. */
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* AUDIO, when the program declared an audio encoder: `merge` and `max_frames` are its. */
|
||||
int init_audio(const AudioConfig& cfg);
|
||||
bool has_audio() const { return audio_on_; }
|
||||
const AudioConfig& audio_config() const { return acfg_; }
|
||||
int audio(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* ...and from samples already decoded (mono at the configured rate), for the test suite. */
|
||||
int audio_from(const std::vector<float>& samples, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
|
||||
private:
|
||||
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int 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_{};
|
||||
AudioConfig acfg_{};
|
||||
bool audio_on_ = false;
|
||||
std::vector<float> hann_; /* the window, float32 as the reference stores it */
|
||||
std::vector<double> mel_; /* [n_mels, fft/2 + 1]: filter b's weight on bin k */
|
||||
std::vector<int32_t> mel_lo_, mel_hi_; /* filter b's nonzero bins, [lo, hi) */
|
||||
std::vector<double> tw_re_, tw_im_; /* exp(-2 pi i k / fft), k < fft/2 */
|
||||
std::vector<int32_t> brev_; /* the FFT's bit-reversal permutation */
|
||||
std::function<std::vector<int32_t>(const std::string&)> encode_text_;
|
||||
};
|
||||
|
||||
@@ -205,9 +322,33 @@ int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t
|
||||
/* Which frames a video keeps. */
|
||||
std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
|
||||
int32_t max_frames);
|
||||
/* ...the Gemma 4 rule: one frame each 1 / fps seconds, thinned evenly to `max_frames`. */
|
||||
std::vector<int64_t> sample_frames_gemma4(const VideoInfo& info, double fps, int32_t max_frames);
|
||||
/* Gemma 4's target size: the largest (h, w), both multiples of `side`, whose patch count stays
|
||||
* within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */
|
||||
int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches,
|
||||
int64_t* oh, int64_t* ow, std::string* why);
|
||||
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
|
||||
* horizontal pass into an 8-bit intermediate and then a vertical one. */
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
|
||||
/* ...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
@@ -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
@@ -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. */
|
||||
|
||||
+373
-73
@@ -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_);
|
||||
}
|
||||
@@ -114,8 +115,8 @@ Mover::~Mover() {
|
||||
}
|
||||
|
||||
/* One place the mover asks for memory. Everything device-side and everything pinned comes out of
|
||||
* the budgets the operator stated (spec §6); the fallback exists so the placement test can run
|
||||
* without standing a whole Pools up, and it announces itself. */
|
||||
* the resolved budgets (spec §6); the fallback exists so the placement test can run without
|
||||
* standing a whole Pools up, and it announces itself. */
|
||||
void* Mover::reserve(const char* what, int64_t bytes, int kind) {
|
||||
if (bytes <= 0) return nullptr;
|
||||
if (budget_) {
|
||||
@@ -134,10 +135,15 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
stats_ = MoverStats{};
|
||||
if (!budget_)
|
||||
RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That "
|
||||
"double-spends --vram-weights-mib against whatever else already reserved it, so "
|
||||
"double-spends the weights pool against whatever else already reserved it, so "
|
||||
"it is a test path and not a deployment.");
|
||||
|
||||
unit_.assign(plan.units.size(), UnitState{});
|
||||
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];
|
||||
@@ -180,7 +187,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
* resident count is untouched by turning the engine on. Under a static plan the plan
|
||||
* asked for none and the slab is exactly the resident set. */
|
||||
/* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of
|
||||
* --vram-weights-mib and the report told the operator how many; allocating a different
|
||||
* the weights pool and the report told the operator how many; allocating a different
|
||||
* count here would mean the mover works against one number while the operator was charged
|
||||
* for another, and the direction that is wrong in is an overrun. */
|
||||
const int64_t shadow = plan.dynamic ? sc.n_shadow : 0;
|
||||
@@ -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",
|
||||
|
||||
+129
-12
@@ -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 {
|
||||
@@ -336,7 +356,7 @@ private:
|
||||
/* ------------------------------------------------------------------ configuration */
|
||||
struct MoverConfig {
|
||||
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
|
||||
* --vram-weights-mib and reported in the plan (SlabClass::n_shadow, n_stage), and a second
|
||||
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
|
||||
* knob for the same quantity is a second number for the mover and the operator to disagree
|
||||
* about -- with an overrun as the direction that disagreement goes wrong in.
|
||||
*
|
||||
@@ -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
|
||||
@@ -419,7 +452,7 @@ public:
|
||||
* diagnosis.
|
||||
*
|
||||
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
|
||||
* --vram-weights-mib as one block; a mover that called rad_dev_alloc beside it would spend
|
||||
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
|
||||
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
|
||||
* launch much later. Reserving from Pools::weights() is also what makes it structurally
|
||||
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
|
||||
@@ -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) --------
|
||||
*
|
||||
@@ -598,7 +672,7 @@ public:
|
||||
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
|
||||
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
|
||||
* and after the layer it is published as null again (unstage_units does that half). The
|
||||
* buffers are the two the plan charged out of --vram-weights-mib (Plan::file_stage_vram).
|
||||
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
|
||||
*
|
||||
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
|
||||
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -655,7 +733,7 @@ private:
|
||||
};
|
||||
|
||||
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
|
||||
* come out of --vram-weights-mib like every other weight allocation and sit at a fixed stride
|
||||
* come out of the weights pool like every other weight allocation and sit at a fixed stride
|
||||
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
|
||||
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
|
||||
* They cannot be one range because the flex slots are scattered over every layer's stripe of
|
||||
@@ -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. */
|
||||
|
||||
+35
-15
@@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) {
|
||||
Budgets Budgets::from(const Config& c) {
|
||||
Budgets b;
|
||||
b.vram_weights = c.vram_weights_mib * 1024 * 1024;
|
||||
b.host_pool = c.host_pool_mib * 1024 * 1024;
|
||||
b.host_pool = (c.host_pool_mib + c.embedding_host_mib) * 1024 * 1024;
|
||||
b.ssd = c.weights_disk_tier;
|
||||
return b;
|
||||
}
|
||||
@@ -123,7 +123,7 @@ int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
TablePlacement ngram, bool host_backend, bool container) {
|
||||
if (!out) return;
|
||||
*out = WeightFootprint{};
|
||||
|
||||
@@ -146,7 +146,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
/* build_units: a model-level weight is its own unit, everything else groups by the declared
|
||||
* (layer, expert). Ordered, for the same reason build_units is. */
|
||||
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
|
||||
bool emb = false, ngram = false, host = true; };
|
||||
bool emb = false, ngram = false, host = true, direct = true; };
|
||||
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
|
||||
std::vector<U> units;
|
||||
|
||||
@@ -175,6 +175,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
|
||||
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
|
||||
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
|
||||
if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
|
||||
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
|
||||
/* The placement flags' tables: model-level, so the unit is this one weight. */
|
||||
if (layer < 0) {
|
||||
@@ -186,6 +187,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
|
||||
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
|
||||
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
|
||||
for (U& mu : units) mu.mapped = mapped_unit(mu.mapped, container && mu.direct, host_backend);
|
||||
std::map<int32_t, int64_t> layer_experts;
|
||||
std::set<int64_t> expert_strides;
|
||||
bool ngram_host = true;
|
||||
@@ -284,8 +286,8 @@ void Planner::resolve_sites(const Program& prog) {
|
||||
* consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
|
||||
* in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
|
||||
* what the planner falls back to when VRAM runs out; this one is where the weight has to be
|
||||
* whatever the budgets say, and charging a pool for bytes that are never copied would make the
|
||||
* operator size a pool against a number that does not exist.
|
||||
* whatever the budgets say, and charging a pool for bytes that are never copied would size that
|
||||
* pool against a number that does not exist.
|
||||
*
|
||||
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
|
||||
* has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
|
||||
@@ -295,9 +297,15 @@ void Planner::resolve_sites(const Program& prog) {
|
||||
void Planner::pin_mapped(const Program& prog, Plan* p) {
|
||||
const TablePlacement ng = in_.config->ngram_resolved;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
bool host_only = false;
|
||||
for (rad_weight w : mu.weights)
|
||||
bool host_only = false, direct = in_.container;
|
||||
for (rad_weight w : mu.weights) {
|
||||
if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
|
||||
if (w < prog.weights.size() &&
|
||||
!weight_file_direct(prog.weights[w], prog.ctx.world_size)) direct = false;
|
||||
}
|
||||
/* On the host backend a unit stored in another form than its host kernel reads is placed
|
||||
* like any other weight, in the pool its kernel can read too (mapped_unit). */
|
||||
host_only = mapped_unit(host_only, direct, in_.host_backend);
|
||||
/* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
|
||||
* a device kernel could read it there: ram and disk are where the operator put it, and the
|
||||
* strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
|
||||
@@ -619,8 +627,8 @@ int Planner::assign_all_vram(Plan* p) {
|
||||
used += mu.slot_bytes;
|
||||
}
|
||||
if (p->vram_budget > 0 && used > p->vram_budget) {
|
||||
p->notes.push_back(fmt("all_vram needs %s of weights against a --vram-weights-mib "
|
||||
"budget of %s: %s short",
|
||||
p->notes.push_back(fmt("all_vram needs %s of weights against a weights pool "
|
||||
"of %s: %s short",
|
||||
humanb(used).c_str(), humanb(p->vram_budget).c_str(),
|
||||
humanb(used - p->vram_budget).c_str()));
|
||||
return RAD_E_NOMEM;
|
||||
@@ -768,9 +776,9 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
rank_units(p, &order);
|
||||
|
||||
/* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the
|
||||
* shadow slots a promotion writes into, and they all come out of --vram-weights-mib -- so a
|
||||
* shadow slots a promotion writes into, and they all come out of the weights pool -- so a
|
||||
* fill that spends the whole budget on residents leaves the mover with nowhere to move into
|
||||
* and, worse, makes the mover's allocation overrun the pool the operator sized.
|
||||
* and, worse, makes the mover's allocation overrun the weights pool.
|
||||
*
|
||||
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
|
||||
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
|
||||
@@ -900,7 +908,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
k = fill(uncapped, --cap);
|
||||
if (fixed + k.used + k.spare + k.file > p->vram_budget) {
|
||||
p->notes.push_back(fmt("the file tier's two layer buffers need %s, beside %s of "
|
||||
"fixed weights, against a --vram-weights-mib budget of %s",
|
||||
"fixed weights, against a weights pool of %s",
|
||||
humanb(k.file).c_str(), humanb(fixed).c_str(),
|
||||
humanb(p->vram_budget).c_str()));
|
||||
return RAD_E_NOMEM;
|
||||
@@ -1119,8 +1127,8 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
|
||||
mu.host_forced = true;
|
||||
mu.reason = "--embedding-placement ram; read over the link in place";
|
||||
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
|
||||
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
|
||||
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
|
||||
"(--embedding-placement ram%s)", name.c_str(), humanb(mu.bytes).c_str(),
|
||||
cfg.embedding_placement_given ? "" : ", the default");
|
||||
}
|
||||
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
|
||||
* so an empty pass is a plan built from a different program than the budget was: a wiring
|
||||
@@ -1235,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());
|
||||
}
|
||||
@@ -1243,7 +1262,8 @@ int Planner::assign(Plan* p) {
|
||||
/* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to
|
||||
* spill against would have to infer one from free VRAM, and an engine that quietly
|
||||
* re-optimises its own split is an engine whose benchmarks do not reproduce. */
|
||||
RAD_ERR("placement: %s needs --vram-weights-mib; there is nothing to spill against",
|
||||
RAD_ERR("placement: %s needs a weights budget and none was resolved; there is nothing to "
|
||||
"spill against",
|
||||
strategy_name(s));
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
+57
-10
@@ -111,7 +111,7 @@ struct MoveUnit {
|
||||
|
||||
/* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The
|
||||
* planner budgets against this and the mover allocates this, so the two cannot drift -- and
|
||||
* the direction they would drift in is an overrun of the pool the operator sized. `bytes` is
|
||||
* the direction they would drift in is an overrun of the weights pool. `bytes` is
|
||||
* still what the report attributes to the weights, because padding is not a weight. */
|
||||
int64_t slot_bytes = 0;
|
||||
|
||||
@@ -176,20 +176,48 @@ 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).
|
||||
*
|
||||
* THEY COME OUT OF --vram-weights-mib, like everything else in the slab. Taking them from
|
||||
* THEY COME OUT OF THE WEIGHTS POOL, like everything else in the slab. Taking them from
|
||||
* whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool
|
||||
* explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic
|
||||
* placement costs a few resident units, and the plan report prints exactly how many.
|
||||
*
|
||||
* 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
|
||||
@@ -260,7 +290,7 @@ public:
|
||||
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
|
||||
* file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is
|
||||
* how the stager packs them; `file_stage_vram` is the two buffers, taken out of
|
||||
* --vram-weights-mib before any expert is made resident. Both 0 when nothing routed is on the
|
||||
* the weights pool before any expert is made resident. Both 0 when nothing routed is on the
|
||||
* file tier. */
|
||||
int64_t file_layer_max = 0;
|
||||
int64_t file_stage_vram = 0;
|
||||
@@ -310,8 +340,23 @@ struct PlannerInput {
|
||||
* served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this
|
||||
* false no unit is file-direct and both tiers are closed (spec §4.3). */
|
||||
bool container = true;
|
||||
/* No card is visible and the device backend is the host's own memory (device_is_host()), so a
|
||||
* host kernel can read the weights pool as well as the container's mapping. See
|
||||
* mapped_unit(). */
|
||||
bool host_backend = false;
|
||||
};
|
||||
|
||||
/* DOES A UNIT STAY IN THE CONTAINER'S MAPPING because only a host kernel can read it? On a card,
|
||||
* always: a host kernel cannot read VRAM, and the mapping is the one host address its bytes
|
||||
* already have. On the host backend the weights pool is host memory too, and a unit whose stored
|
||||
* form is not the container's (a widening or a relayout its host kernel asked for at load, or a
|
||||
* checkpoint served directly) has no place in the mapping that looks the way its kernel reads it,
|
||||
* so there it takes a converted copy in the weights pool like any other weight. One rule, for the
|
||||
* planner and the budget alike. */
|
||||
inline bool mapped_unit(bool host_only, bool direct, bool host_backend) {
|
||||
return host_only && (direct || !host_backend);
|
||||
}
|
||||
|
||||
class Planner {
|
||||
public:
|
||||
explicit Planner(const PlannerInput& in) : in_(in) {}
|
||||
@@ -399,10 +444,12 @@ struct WeightFootprint {
|
||||
};
|
||||
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
|
||||
* statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
|
||||
* kernel reads it. Stated by every caller, so the budget and the planner cannot count it
|
||||
* differently. */
|
||||
* kernel reads it. `host_backend` and `container` are PlannerInput's: whether a host kernel can
|
||||
* read the weights pool, and whether the weights lie in a container at all (a checkpoint served
|
||||
* directly has no mapping a unit could stay in). Stated by every caller, so the budget and the
|
||||
* planner cannot count it differently. */
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram);
|
||||
TablePlacement ngram, bool host_backend, bool container);
|
||||
|
||||
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
|
||||
|
||||
+217
-77
@@ -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 */
|
||||
|
||||
+132
-50
@@ -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,18 +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;
|
||||
@@ -88,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 -------------------------------------
|
||||
|
||||
+65
-16
@@ -360,12 +360,16 @@ int Registry::commit_(Staged& s, int order) {
|
||||
* libraries for several cards would serve none of them but the first in the hierarchy.
|
||||
* What the library carries is read out of the fat binaries its dlopen registered, which is
|
||||
* what the launch itself will consult (core/device/aql_code.cpp), not out of
|
||||
* build_target, which is prose. Its host rows run anywhere and stay. */
|
||||
* build_target, which is prose. Its host rows run anywhere and stay. On the host backend
|
||||
* an engine that serves says no GPU code runs at all (set_no_device_code). */
|
||||
int n_device = 0;
|
||||
for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
|
||||
std::string why;
|
||||
if (no_device_code_)
|
||||
why = "no card is visible, so this process runs on the host backend and no GPU code "
|
||||
"object runs here";
|
||||
if (n_device > 0 && s.code_to > s.code_from &&
|
||||
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0) {
|
||||
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) {
|
||||
std::vector<std::pair<const RadKernelInfo*, int>> keep;
|
||||
for (const auto& r : staged_rows)
|
||||
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
|
||||
@@ -451,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;
|
||||
@@ -458,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);
|
||||
}
|
||||
@@ -480,8 +488,8 @@ int Registry::commit_(Staged& s, int order) {
|
||||
if (rad_dev_count() > code_device_ && rad_dev_props(code_device_, &dp) == RAD_OK &&
|
||||
dp.arch[0] && !target_covers(p.build_target, dp.arch))
|
||||
RAD_WARN("kernel plugin '%s' declares it was built for %s and this machine reports %s. "
|
||||
"Its kernels will fail to launch; build it for %s, or put a library that "
|
||||
"serves this device ahead of it with --kernels.",
|
||||
"Its kernels will fail to launch; build it for %s, or leave it out with "
|
||||
"--kernels.",
|
||||
p.name.c_str(), p.build_target.c_str(), dp.arch, dp.arch);
|
||||
}
|
||||
|
||||
@@ -576,33 +584,74 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
|
||||
staged.push_back(s);
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered. A plugin the operator named takes that
|
||||
* position; a plugin present on disk but absent from the list loads after everything named,
|
||||
* so dropping an .so into the directory adds it with no configuration and naming it ahead of
|
||||
* another is what substitutes it.
|
||||
/* An entry names a library by its declared name or by its file, written as the operator sees
|
||||
* it on disk: `libr4d`, `r4d`, `libr4d.so` and a path to it are one library. */
|
||||
auto names = [](const std::string& h, const Staged& s) {
|
||||
return h == s.name || h == s.file || stem_of(h) == s.file;
|
||||
};
|
||||
std::string found; /* every kernel library on the search path, for a list that names none */
|
||||
for (const Staged& s : staged)
|
||||
if (s.info && s.info->kind == RAD_PLUGIN_KERNEL)
|
||||
found += (found.empty() ? "" : ", ") + s.name;
|
||||
|
||||
/* A HIERARCHY NAMES THE KERNEL LIBRARIES THAT SERVE, AND ONLY THOSE LOAD. Ordering alone
|
||||
* cannot keep a library out: selection runs per domain, so a library named first that has no
|
||||
* device row for an op leaves that op to whichever unnamed library does -- a GPU library on a
|
||||
* machine whose card it was not built for, say -- and an operator who listed what to use gets
|
||||
* something else. A kernel library on the search path that the list leaves out is closed again
|
||||
* before it registers anything, and said once. Architecture and quantiser plugins are not
|
||||
* kernel libraries and no list ranks them. */
|
||||
if (!hierarchy.empty()) {
|
||||
std::vector<Staged> kept;
|
||||
std::string left_out;
|
||||
for (Staged& s : staged) {
|
||||
const bool kernel = s.info && s.info->kind == RAD_PLUGIN_KERNEL;
|
||||
const bool named = std::find_if(hierarchy.begin(), hierarchy.end(),
|
||||
[&](const std::string& h) {
|
||||
return names(h, s);
|
||||
}) != hierarchy.end();
|
||||
if (!kernel || named) {
|
||||
kept.push_back(s);
|
||||
continue;
|
||||
}
|
||||
left_out += (left_out.empty() ? "" : ", ") + s.name;
|
||||
unstage_(s);
|
||||
}
|
||||
staged.swap(kept);
|
||||
if (!left_out.empty())
|
||||
RAD_INFO("kernel libraries on the search path that --kernels (or RADIANCE_KERNELS) "
|
||||
"does not name, and so not loaded: %s", left_out.c_str());
|
||||
}
|
||||
|
||||
/* The hierarchy is configured, not discovered: a library the operator named takes that
|
||||
* position. With no list every kernel library on the search path loads, so dropping an .so
|
||||
* into the directory adds it with no configuration.
|
||||
*
|
||||
* A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for
|
||||
* every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library
|
||||
* for this machine's card would load, never be selected for anything, and leave the whole
|
||||
* model resolving to the naive implementation. Pinning it is what makes an unconfigured
|
||||
* drop-in work. Naming it in the hierarchy overrides this, which is how it is put in front of
|
||||
* a library to compare against. Which library is one is its own declaration
|
||||
* drop-in work. Naming it in the hierarchy places it where it is named, which is how it is put
|
||||
* in front of a library to compare against. Which library is one is its own declaration
|
||||
* (RadPluginReferenceFn), not its name. */
|
||||
const size_t kUnnamed = (size_t)INT_MAX - 1;
|
||||
std::vector<size_t> rank(staged.size());
|
||||
for (size_t i = 0; i < staged.size(); ++i)
|
||||
rank[i] = staged[i].reference ? (size_t)INT_MAX : kUnnamed;
|
||||
for (size_t h = 0; h < hierarchy.size(); ++h) {
|
||||
bool found = false;
|
||||
bool hit = false;
|
||||
for (size_t i = 0; i < staged.size(); ++i) {
|
||||
if (staged[i].name == hierarchy[h] || staged[i].file == hierarchy[h]) {
|
||||
if (names(hierarchy[h], staged[i])) {
|
||||
rank[i] = h;
|
||||
found = true;
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
RAD_WARN("kernel hierarchy names '%s', which is not in %s -- ignored",
|
||||
hierarchy[h].c_str(), dir.c_str());
|
||||
/* The list is what loads, so an entry that matches nothing is a library that is not
|
||||
* there to select -- and a list none of whose entries match loads no kernel library. */
|
||||
if (!hit)
|
||||
RAD_WARN("--kernels (or RADIANCE_KERNELS) names '%s', which is no kernel library in "
|
||||
"%s, so nothing loads in its place; the kernel libraries there are: %s",
|
||||
hierarchy[h].c_str(), dir.c_str(), found.empty() ? "none" : found.c_str());
|
||||
}
|
||||
std::vector<size_t> idx(staged.size());
|
||||
for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
|
||||
|
||||
+14
-4
@@ -150,10 +150,12 @@ public:
|
||||
/* ---------------------------------------------------------- loading (§2, §18) */
|
||||
/* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured,
|
||||
* not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the
|
||||
* file's stem, whichever the operator wrote), so substituting a kernel is dropping an .so in a
|
||||
* directory and naming it ahead of the default. A plugin present on disk but absent from the
|
||||
* list loads at the END, after everything named, in filename order so the result is
|
||||
* reproducible.
|
||||
* file as the operator wrote it -- `libr4d`, `r4d`, `libr4d.so`), so substituting a kernel is
|
||||
* dropping an .so in a directory and naming it ahead of the default. A non-empty list is
|
||||
* EXCLUSIVE: a kernel library it does not name is closed before it registers anything, and an
|
||||
* entry that matches nothing is warned about by name. An empty list loads every kernel library
|
||||
* found, in filename order so the result is reproducible, with a reference library last.
|
||||
* Architecture and quantiser plugins are not ranked and always load.
|
||||
*
|
||||
* Always completes: every plugin that can be loaded is, every refusal is recorded in
|
||||
* load_errors(), and the FIRST negative status is returned. Reporting the whole list beats
|
||||
@@ -181,6 +183,13 @@ public:
|
||||
* loads anything, once it has chosen its cards. */
|
||||
void set_code_device(int device) { code_device_ = device; }
|
||||
|
||||
/* THE ENGINE ABOUT TO SERVE ON THE HOST BACKEND SAYS SO: no card is visible, and no GPU code
|
||||
* object runs in this process at all. A kernel library that brought device code then has its
|
||||
* device rows left out of selection at load, its host rows staying, so every op takes its host
|
||||
* kernel. Only the engine says this. A tool that selects without serving -- rad-convert's
|
||||
* recipe check, rad-kbench's tables, a test of a library's constraints -- sees every row, as
|
||||
* it would on the machine the model is served on. */
|
||||
void set_no_device_code(bool v) { no_device_code_ = v; }
|
||||
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
|
||||
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
|
||||
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
|
||||
@@ -333,6 +342,7 @@ private:
|
||||
};
|
||||
|
||||
int code_device_ = 0;
|
||||
bool no_device_code_ = false;
|
||||
Geometry device_facts_;
|
||||
TuneCache tune_;
|
||||
|
||||
|
||||
+121
-17
@@ -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;
|
||||
};
|
||||
@@ -122,11 +127,12 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* it, and why the operator gets to choose.
|
||||
*
|
||||
* Vram resident on the card, a weight like any other.
|
||||
* Ram in host memory the card or a host kernel reads in place: the embedding in the pinned
|
||||
* host pool, read over the link; an n-gram table as a locked copy made at load.
|
||||
* Disk read from the container on demand.
|
||||
* Auto the fastest of the three that has room once every other weight is placed; Engine::plan
|
||||
* decides it and writes the answer into Config, so every rank plans from one choice. */
|
||||
* Ram in host memory the card or a host kernel reads in place: the embedding pinned beside
|
||||
* the host pool, read over the link; an n-gram table as a copy made at load.
|
||||
* Disk read from the container on demand; the n-gram table's only.
|
||||
* Auto the fastest of the three that has room once every other weight is placed; the n-gram
|
||||
* table's only. Engine::plan decides it and writes the answer into Config, so every rank
|
||||
* plans from one choice. The embedding takes Ram or Vram. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
|
||||
@@ -346,6 +352,9 @@ public:
|
||||
* purpose -- the engine refuses to SERVE such a program and says so at startup, rather
|
||||
* than discovering at the first step that there is nothing to sample. */
|
||||
rad_buf logits_buf = 0;
|
||||
/* The buffer the plugin named as this step's pooled vectors (rad_declare_pooled): set only by
|
||||
* an EMBEDDING program, which then has no logits buffer. */
|
||||
rad_buf pooled_buf = 0;
|
||||
|
||||
/* THE DRAFT HEAD THIS PLUGIN DECLARED (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when
|
||||
* it declared none, which is the normal case -- the engine then speculates with the
|
||||
@@ -359,6 +368,9 @@ public:
|
||||
* media (RadBuildCtx::max_enc_patches 0). `encoder_name` for the reason `drafter_name` is. */
|
||||
RadEncoderDecl encoder{};
|
||||
std::string encoder_name;
|
||||
/* ...and the audio encoder, the second a program may declare (RAD_MM_AUDIO). */
|
||||
RadEncoderDecl audio_encoder{};
|
||||
std::string audio_encoder_name;
|
||||
|
||||
/* Two arenas, because a host-site activation cannot index device memory. The buffer plan
|
||||
* colours the domains SEPARATELY -- a transient may share storage only with a transient in the
|
||||
@@ -399,9 +411,18 @@ public:
|
||||
std::string span; /* the band, as Band::span */
|
||||
std::string why;
|
||||
int domain = 0; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
|
||||
int32_t index = 0; /* the instance that missed (OpInfo::index): bands are its own */
|
||||
std::string line() const; /* "op geometry [domain] -> why", the full-detail rendering */
|
||||
};
|
||||
std::vector<Miss> misses;
|
||||
/* THE DEVICE MISSES A REQUEST CAN FALL INTO, in `misses` order: the device bands no kernel
|
||||
* serves and no host kernel stands in for. A host kernel for the same band stands in on the
|
||||
* host backend, where every op without a device row runs on the host (Ctx::bind_ops); on a
|
||||
* card it stands in only for an op that has weights, because the planner moves an op to the
|
||||
* host by placing its weights there and has nothing to place for an op without them --
|
||||
* attention over a cache that lives in VRAM is the case that matters. One rule for the engine
|
||||
* that refuses to start on a hole and for the tools that count them. */
|
||||
std::vector<const Miss*> device_holes(bool host_backend) const;
|
||||
|
||||
/* Every (kernel, shape) pair rad-tune would need to benchmark (spec §15). */
|
||||
/* `info` is the kernel's own row, so rad-tune can read its RadTunable axes and expand the
|
||||
@@ -476,6 +497,24 @@ struct ReasoningCount {
|
||||
bool inside() const { return st == Think; }
|
||||
};
|
||||
|
||||
/* THE MOST ALTERNATIVES ONE TOKEN'S LOGPROBS MAY CARRY: OpenAI's bound on top_logprobs. A request
|
||||
* above it is refused. The sampler declares `sample_logprobs` one wider (Sampler::kLpK), for the
|
||||
* width of the row the split-vocabulary gather moves; the extra pair is never reported. */
|
||||
static constexpr int RAD_MAX_LOGPROBS = 20;
|
||||
|
||||
/* One emitted token's log-probability under the model's RAW distribution -- the logits before any
|
||||
* penalty, temperature, mask or cut -- and its `n_top` most likely alternatives in descending
|
||||
* order, ties to the lower id. What OpenAI's `logprobs` and llama-server's `n_probs` report.
|
||||
* `token` -1 is a token whose logprobs could not be computed (a row with no finite logit): the
|
||||
* scheduler fails its request rather than report a number for it. */
|
||||
struct TokenLogprobs {
|
||||
int32_t token = -1;
|
||||
float logprob = 0.0f;
|
||||
int32_t n_top = 0;
|
||||
int32_t top_id[RAD_MAX_LOGPROBS] = {};
|
||||
float top_lp[RAD_MAX_LOGPROBS] = {};
|
||||
};
|
||||
|
||||
struct SamplingParams {
|
||||
float temp = 1.0f;
|
||||
int top_k = 0; /* 0 = off */
|
||||
@@ -492,6 +531,14 @@ struct SamplingParams {
|
||||
int dry_penalty_last_n = -1;
|
||||
float xtc_probability = 0.0f;
|
||||
float xtc_threshold = 0.1f;
|
||||
/* TEMPERATURE AFTER THE CUTS rather than before them: top-p, min-p, typical and XTC read the
|
||||
* distribution at temperature 1 and the pick draws at `temp`. llama.cpp's default order; the
|
||||
* default here is vLLM's, temperature first. A request names the order with `samplers`. */
|
||||
bool temp_last = false;
|
||||
/* LOGPROBS: -1 is none; 0..RAD_MAX_LOGPROBS returns every emitted token's logprob and that
|
||||
* many alternatives. Speculation is unaffected: every verified position is a row of its own,
|
||||
* and an accepted draft is the token the target drew there. */
|
||||
int n_probs = -1;
|
||||
uint64_t seed = 0;
|
||||
bool greedy() const { return top_k == 1 || temp <= 0.0f; }
|
||||
std::string grammar; /* GBNF, or "" */
|
||||
@@ -531,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;
|
||||
@@ -598,6 +656,30 @@ 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
|
||||
* embedding program (rad_declare_pooled) serves these, and it serves nothing else. */
|
||||
bool embed = false;
|
||||
|
||||
/* THE CONVERSATION AS THE CLIENT NAMES IT (OpenRouter's `session_id`), "" when it names
|
||||
* none: carried to the session the prefix cache records for it, as a label on /sessions and
|
||||
* the dashboard. It changes nothing about how the request is served. */
|
||||
std::string session_label;
|
||||
|
||||
std::string finish_reason;
|
||||
void* sink = nullptr; /* the server's per-request stream sink */
|
||||
};
|
||||
@@ -608,7 +690,8 @@ struct Request {
|
||||
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
|
||||
|
||||
struct Config {
|
||||
std::string model; /* path to the .rad */
|
||||
std::string model; /* path to the .rad, or a Hugging Face repo id (hf_model.h) */
|
||||
std::string download_dir; /* where a repo id is fetched to; empty = the XDG cache */
|
||||
std::string radiance_home;
|
||||
std::vector<std::string> kernel_hierarchy; /* ordered; first wins */
|
||||
|
||||
@@ -642,6 +725,13 @@ struct Config {
|
||||
* P2P should not quietly serve on something else. */
|
||||
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
/* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is
|
||||
* pending in it (decode rows behind it, another prefill, a request waiting to be admitted).
|
||||
* -1 = auto: the chunk leaves those their rows and a share for admission, and keeps at least
|
||||
* the smallest pass the prefill stager arms for. 0 = off: the chunk takes every token the
|
||||
* step has left, as 1.3.0 did. N > 0: the chunk is held to N tokens on such a step.
|
||||
* Scheduler::step, docs/GUIDE.md. */
|
||||
int64_t busy_prefill_chunk = -1;
|
||||
int64_t max_seqs = 256;
|
||||
int64_t max_ctx = 0; /* 0 = the model's training context */
|
||||
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
|
||||
@@ -649,8 +739,8 @@ struct Config {
|
||||
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
|
||||
std::string rope_scaling;
|
||||
|
||||
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
|
||||
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
|
||||
/* THE ENGINE DERIVES THE BUDGET FROM THE CARD, AND IT IS STATED IN FULL BEFORE ANYTHING IS
|
||||
* ALLOCATED.
|
||||
*
|
||||
* Spec §6 forbids a derived budget because a budget derived from the FREE VRAM at startup is
|
||||
* a benchmark that moves when a desktop opens a window. What it does not forbid is arithmetic
|
||||
@@ -664,7 +754,7 @@ struct Config {
|
||||
* still one number per card, and the same number on every card whose cache costs as much per
|
||||
* token as the dearest rank's.
|
||||
*
|
||||
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
|
||||
* NO FLAG SETS THEM: zero until the resolver has run. */
|
||||
int64_t vram_weights_mib = 0;
|
||||
int64_t vram_kv_mib = 0;
|
||||
int64_t gpu_headroom_mib = 96; /* --gpu-headroom, left unclaimed on every card */
|
||||
@@ -677,11 +767,6 @@ struct Config {
|
||||
* a third name for the second one, and a flag whose values are not all distinct is a flag
|
||||
* whose log line cannot be read back. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
/* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into
|
||||
* this config, which erases the only evidence of whether they were stated or derived -- and
|
||||
* Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or
|
||||
* a split it made itself and already printed a receipt for. */
|
||||
bool vram_budget_derived = false;
|
||||
int64_t host_pool_mib = 0;
|
||||
/* THE FILE TIER FOR WEIGHTS: what fits neither the VRAM slab nor the pinned host pool is read
|
||||
* from the container itself, with O_DIRECT, ahead of the ops that read it -- a scheduled unit by
|
||||
@@ -693,11 +778,19 @@ struct Config {
|
||||
|
||||
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
|
||||
/* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
|
||||
* is), and what Engine::plan resolved them to before any rank planned: never Auto. */
|
||||
TablePlacement embedding_placement = TablePlacement::Auto;
|
||||
* is), and what Engine::plan resolved them to before any rank planned: never Auto. The
|
||||
* embedding's default is Ram; `embedding_placement_given` says whether the operator named it,
|
||||
* because a named tier that cannot be honoured stops the server where the default gives way
|
||||
* to the card with the reason. */
|
||||
TablePlacement embedding_placement = TablePlacement::Ram;
|
||||
bool embedding_placement_given = false;
|
||||
TablePlacement ngram_placement = TablePlacement::Auto;
|
||||
TablePlacement embedding_resolved = TablePlacement::Vram;
|
||||
TablePlacement ngram_resolved = TablePlacement::Disk;
|
||||
/* SET BY THE RESOLVER: the pinned host room the token embedding takes when it resolves to Ram,
|
||||
* a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool,
|
||||
* and a dense model that has no pool still has a place for it. */
|
||||
int64_t embedding_host_mib = 0;
|
||||
bool deterministic = false;
|
||||
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
|
||||
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
|
||||
@@ -780,6 +873,9 @@ struct Config {
|
||||
* when the container carries a vision tower and 0 when it does not. 0 serves text only and
|
||||
* keeps a tower the container carries off the card. */
|
||||
int64_t mm_max_patches = -1;
|
||||
/* The audio encoder's pass in frames, resolved at bring-up from the plugin's probe when the
|
||||
* container carries an audio encoder; --mm-max-patches 0 (text only) turns it off too. */
|
||||
int64_t mm_audio_frames = -1;
|
||||
|
||||
std::string host = "0.0.0.0";
|
||||
/* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
|
||||
@@ -869,10 +965,12 @@ struct Config {
|
||||
std::optional<double> video_fps;
|
||||
std::optional<int32_t> video_min_frames, video_max_frames, video_max_frame_tokens;
|
||||
std::optional<int64_t> max_source_pixels;
|
||||
/* A token-budget processor's (Gemma 4's) soft tokens an image. */
|
||||
std::optional<int32_t> image_tokens;
|
||||
bool media_flags_set() const {
|
||||
return image_min_pixels || image_max_pixels || video_min_pixels || video_max_pixels ||
|
||||
video_fps || video_min_frames || video_max_frames || video_max_frame_tokens ||
|
||||
max_source_pixels;
|
||||
max_source_pixels || image_tokens;
|
||||
}
|
||||
|
||||
/* An operator-supplied generation_config.json, overriding the search described above. */
|
||||
@@ -895,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 */
|
||||
|
||||
+94
-13
@@ -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 "
|
||||
@@ -401,9 +420,21 @@ int Ctx::bind_ops() {
|
||||
/* Execution site. Site is a property of the weights (spec §5.1), so an op whose every
|
||||
* weight operand was placed on the host runs its host kernel and everything else runs on
|
||||
* the device. An op with no weights stays on the device; the planner overrides through
|
||||
* set_op_domain, which is where the "contiguous host runs" objective actually lands. */
|
||||
* set_op_domain, which is where the "contiguous host runs" objective actually lands.
|
||||
*
|
||||
* ON THE HOST BACKEND (no card visible: CPU-only serving) the device domain is the host's
|
||||
* own memory and an op with no device kernel in any band runs its host kernel -- the
|
||||
* whole model on libavx (or libref) with no switch to set. An op that does carry device
|
||||
* rows there is a test registering fakes, and keeps them. */
|
||||
int dom = RAD_DOMAIN_DEVICE;
|
||||
if (!oi.weights.empty()) {
|
||||
if (device_is_host()) {
|
||||
bool any_device = false;
|
||||
for (int b = 0; b < p.n_bands && !any_device; ++b)
|
||||
any_device = issue_table_[(size_t)p.plan_off + (size_t)b * RAD_N_DOMAINS +
|
||||
RAD_DOMAIN_DEVICE].launch != nullptr;
|
||||
if (!any_device) dom = RAD_DOMAIN_HOST;
|
||||
}
|
||||
if (dom == RAD_DOMAIN_DEVICE && !oi.weights.empty()) {
|
||||
bool all_host = true;
|
||||
for (rad_weight w : oi.weights) {
|
||||
const WeightInfo* wi = P.weight(w);
|
||||
@@ -835,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
|
||||
@@ -876,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",
|
||||
@@ -900,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;
|
||||
@@ -910,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];
|
||||
@@ -924,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 */
|
||||
@@ -1188,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) {
|
||||
@@ -1236,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;
|
||||
@@ -1338,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))
|
||||
@@ -1349,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
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -883,7 +883,7 @@ const IssuePlan* Ctx::oracle_before(rad_op h, int band, int n_opd) {
|
||||
static const IssuePlan kRepeatArmed{};
|
||||
return &kRepeatArmed;
|
||||
}
|
||||
/* NOT GATED ON THE DEVICE DOMAIN. Under RADIANCE_HOST_DOMAIN the launch IS the host kernel,
|
||||
/* NOT GATED ON THE DEVICE DOMAIN. On the host backend the launch IS the host kernel,
|
||||
* so the comparison is host against host and agrees by construction -- but the per-operand
|
||||
* lines are still the only ordered trace of what the graph computed, and diffing those
|
||||
* against another engine's is what the whole-model reference exists for. */
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
|
||||
@@ -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 */
|
||||
@@ -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 */
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -577,13 +577,16 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
|
||||
}
|
||||
|
||||
if (order == ChainOrder::Radiance) {
|
||||
host_temp(s, sp.temp);
|
||||
/* `temp_last` moves temperature behind the cuts, as the device chain moves it onto the
|
||||
* candidate plane (Sampler::issue); the cuts keep this order either way. */
|
||||
if (!sp.temp_last) host_temp(s, sp.temp);
|
||||
host_mask(s, in.bitmask, in.n_words);
|
||||
host_top_k(s, sp.top_k);
|
||||
host_top_p(s, sp.top_p, 1);
|
||||
host_min_p(s, sp.min_p, 1);
|
||||
host_typical(s, sp.typical_p, 1);
|
||||
host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
|
||||
if (sp.temp_last) host_temp(s, sp.temp);
|
||||
} else {
|
||||
/* llama.cpp's default order, for checking this port against llama.cpp itself. Note the
|
||||
* absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a
|
||||
|
||||
+302
-9
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
@@ -177,6 +178,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
buf_params_ = decl("sampler.params", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
|
||||
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
|
||||
buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* One byte beside every history token: nonzero where that token is a whole DRY sequence
|
||||
* breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
|
||||
@@ -194,7 +197,16 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
|
||||
}
|
||||
|
||||
if (!buf_params_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_) {
|
||||
/* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
|
||||
* declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
|
||||
* over the op list would hand its bytes to the candidate planes the stages after it write. */
|
||||
buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
|
||||
if (vocab_parallel())
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -252,6 +264,15 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
|
||||
* which is all the kernel reads it as -- a row length. */
|
||||
{
|
||||
RadParam p[2] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
RadParam{ "n_vocab", RAD_P_INT, (long long)ncand, 0, nullptr },
|
||||
};
|
||||
op_temp_late_ = rad_decl_op(b, "sample_temp", p, 2, nullptr, 0);
|
||||
}
|
||||
|
||||
if (vocab_parallel()) {
|
||||
/* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
|
||||
@@ -269,6 +290,31 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_merge_ = op_cand("sample_merge_topk");
|
||||
}
|
||||
|
||||
/* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
|
||||
* deployment whose kernels lack it serves every request that does not ask for logprobs;
|
||||
* check_request refuses the ones that do, by name. */
|
||||
{
|
||||
RadParam p[4] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr },
|
||||
RadParam{ "k", RAD_P_INT, (long long)kLpK, 0, nullptr },
|
||||
RadParam{ "vocab_off", RAD_P_INT, (long long)cfg_.vocab_off, 0, nullptr },
|
||||
};
|
||||
op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
|
||||
}
|
||||
if (vocab_parallel()) {
|
||||
/* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
|
||||
* row lands beside the others' as the candidate pairs do. */
|
||||
RadParam ag[4] = {
|
||||
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
|
||||
RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
|
||||
RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
|
||||
RadParam{ "row", RAD_P_INT, (long long)lp_width(), 0, nullptr },
|
||||
};
|
||||
op_lp_gather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
|
||||
if (!op_lp_gather_) op_logprobs_ = RAD_NULL_HANDLE;
|
||||
}
|
||||
|
||||
RAD_TRY(stage_alloc());
|
||||
declared_ = true;
|
||||
|
||||
@@ -288,14 +334,32 @@ int Sampler::stage_alloc() {
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
late_stage_ = (DeviceSampleParams*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
|
||||
greedy_ready_ = false;
|
||||
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !hist_stage_ || !brk_stage_ || !mask_stage_) {
|
||||
/* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
|
||||
* reads them. */
|
||||
if (cfg_.rank == 0) {
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
lp_host_ = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
|
||||
lp_ci_host_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
|
||||
lp_cv_host_ = (float*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
|
||||
if (!lp_host_ || !lp_ci_host_ || !lp_cv_host_) {
|
||||
RAD_ERR("sampler: could not pin %s for the logprobs readback",
|
||||
humanb(rows * (w + 2 * cfg_.max_candidates) * 4).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
|
||||
!mask_stage_) {
|
||||
RAD_ERR("sampler: could not pin %s of staging",
|
||||
humanb(rows * ((int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
mask_words_ * 4)).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
@@ -306,11 +370,19 @@ int Sampler::stage_alloc() {
|
||||
void Sampler::stage_free() {
|
||||
if (params_stage_) rad_dev_free(params_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (greedy_stage_) rad_dev_free(greedy_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED);
|
||||
lp_host_ = nullptr;
|
||||
lp_ci_host_ = nullptr;
|
||||
lp_cv_host_ = nullptr;
|
||||
params_stage_ = nullptr;
|
||||
greedy_stage_ = nullptr;
|
||||
late_stage_ = nullptr;
|
||||
cur_stage_ = nullptr;
|
||||
hist_stage_ = nullptr;
|
||||
brk_stage_ = nullptr;
|
||||
@@ -349,6 +421,11 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (sp.top_k > cfg_.max_candidates)
|
||||
return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
|
||||
RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
|
||||
* sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
|
||||
* work is queued, rather than truncated -- a request whose breakers quietly went missing is a
|
||||
@@ -366,12 +443,18 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
return (wanted && !h) ? n : nullptr;
|
||||
};
|
||||
/* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
|
||||
* it: not the argmax, but the top-k, the merge and the pick that build_step's top_k = 1 sends
|
||||
* it through. Admission has to check what will actually be issued. */
|
||||
const bool greedy_chain = sp.greedy() && vocab_parallel();
|
||||
* it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
|
||||
* build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
|
||||
* batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
|
||||
* is. Admission has to check what will actually be issued. */
|
||||
/* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
|
||||
* token comes off a candidate plane (sampler.h). */
|
||||
const bool lp = sp.n_probs >= 0;
|
||||
const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
|
||||
const char* missing = nullptr;
|
||||
if (!missing) missing = need(lp, op_logprobs_, "sample_logprobs");
|
||||
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
|
||||
if (!missing) missing = need(!sp.greedy(), op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
|
||||
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
|
||||
/* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
|
||||
* the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
|
||||
@@ -381,6 +464,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
|
||||
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
|
||||
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
|
||||
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
|
||||
"sample_temp (over the candidates, for temperature last)");
|
||||
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
|
||||
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
|
||||
"sample_mask");
|
||||
@@ -514,7 +599,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int64_t cap = rows_for(cfg_);
|
||||
n_seq_ = 0;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
|
||||
/* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
|
||||
* strings resolved against the vocabulary, so what they mean for this window is worked out
|
||||
@@ -651,11 +738,28 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
* Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
|
||||
* skips a row that does, because in an unsplit batch that flag is what keeps the pick
|
||||
* from overwriting the argmax's answer with a draw. */
|
||||
/* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
|
||||
* its token has to come off a candidate plane, which is where logprobs_for reads the
|
||||
* value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
|
||||
* same. */
|
||||
const bool want_lp = sp.n_probs >= 0;
|
||||
if (sp.greedy()) {
|
||||
if (vocab_parallel()) p.top_k = 1;
|
||||
else p.flags |= RAD_SP_GREEDY;
|
||||
if (vocab_parallel() || want_lp) p.top_k = 1;
|
||||
else p.flags |= RAD_SP_GREEDY;
|
||||
}
|
||||
if (want_lp) p.flags |= RAD_SP_LOGPROBS;
|
||||
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
|
||||
/* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
|
||||
* the temperature stage skips -- in whichever of the two it does not run in. Every row
|
||||
* gets a late row, because the late stage is issued over the whole batch. */
|
||||
const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
|
||||
DeviceSampleParams& lp = late_stage_[row];
|
||||
lp = p;
|
||||
lp.temp = late ? sp.temp : 1.0f;
|
||||
if (late) {
|
||||
p.temp = 1.0f;
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
|
||||
* -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
|
||||
@@ -766,6 +870,23 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
|
||||
if (budget && think.inside() && think.body >= sp.thinking_budget)
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
|
||||
if (want_lp) {
|
||||
/* The temperature the candidate value carries: the early stage's and the late
|
||||
* one's, each only where its kernel runs (temp > 0 and not 1). */
|
||||
auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
|
||||
LpRow L;
|
||||
L.row = row;
|
||||
L.n_top = sp.n_probs;
|
||||
L.temp = t_of(p.temp) * t_of(late_stage_[row].temp);
|
||||
L.p = p;
|
||||
if (p.hist_len > 0) {
|
||||
const int32_t* h = hist_stage_ + row * cfg_.max_hist;
|
||||
L.hist.assign(h, h + p.hist_len);
|
||||
}
|
||||
L.dry = brk;
|
||||
lp_rows_.push_back(std::move(L));
|
||||
}
|
||||
}
|
||||
|
||||
/* Back to where the sequence actually is. The tokens it really accepted are applied by
|
||||
@@ -881,6 +1002,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
* number that makes a host-side grammar affordable at all (spec §13). */
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
/* The late temperature's rows only when this build staged one: a greedy build's rows come
|
||||
* from greedy_stage_, and late_stage_ then holds an older build's. */
|
||||
const bool late = any_late_ && cur_stage_ == params_stage_;
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
if (any_penalty || any_dry)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
|
||||
n_seq_ * cfg_.max_hist * 4, s));
|
||||
@@ -906,6 +1033,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
|
||||
};
|
||||
|
||||
/* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
|
||||
* place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
|
||||
* stages none, and must not overwrite the summary rank 0 is about to copy back. */
|
||||
const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
|
||||
const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
|
||||
if (lp) {
|
||||
RAD_TRY(issue(op_logprobs_, { o_logits, o_params, o_lp }));
|
||||
if (vocab_parallel())
|
||||
RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
|
||||
}
|
||||
|
||||
/* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
|
||||
* breaker marks only when some row in the batch has breakers; its fourth operand is optional
|
||||
* and absent means no token is exempt. */
|
||||
@@ -962,8 +1100,163 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_minp) RAD_TRY(issue(op_minp_, { o_ci, o_cv, o_params }));
|
||||
if (any_typ) RAD_TRY(issue(op_typical_, { o_ci, o_cv, o_params }));
|
||||
if (any_xtc) RAD_TRY(issue(op_xtc_, { o_ci, o_cv, o_params }));
|
||||
if (late)
|
||||
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
|
||||
/* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
|
||||
* summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
|
||||
* there when the summary does not hold it). Only the rows between the first and the last
|
||||
* that asked, and only on rank 0, which is the rank collect_step asks. */
|
||||
if (lp && cfg_.rank == 0) {
|
||||
lp_lo_ = lp_rows_.front().row;
|
||||
lp_hi_ = lp_rows_.back().row + 1;
|
||||
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
|
||||
const int64_t nc = cfg_.max_candidates, n = lp_hi_ - lp_lo_;
|
||||
const char* sp = (const char*)rad_buf_ptr(c, vocab_parallel() ? buf_lp_g_ : buf_lp_);
|
||||
const char* ci = (const char*)rad_buf_ptr(c, buf_cand_i_);
|
||||
const char* cv = (const char*)rad_buf_ptr(c, buf_cand_v_);
|
||||
if (!sp || !ci || !cv) return RAD_E_STATE;
|
||||
RAD_TRY(rad_memcpy_async(lp_host_ + lp_lo_ * w, sp + lp_lo_ * w * 4, n * w * 4, s));
|
||||
RAD_TRY(rad_memcpy_async(lp_ci_host_ + lp_lo_ * nc, ci + lp_lo_ * nc * 4, n * nc * 4, s));
|
||||
RAD_TRY(rad_memcpy_async(lp_cv_host_ + lp_lo_ * nc, cv + lp_lo_ * nc * 4, n * nc * 4, s));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== logprobs */
|
||||
|
||||
float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
|
||||
const DeviceSampleParams& p = L.p;
|
||||
double y = (double)v * (double)L.temp;
|
||||
/* DRY subtracted a penalty that depends on the token and the window alone, so the host
|
||||
* reference computes it for this one token: a single candidate at 0 comes back at minus the
|
||||
* penalty. */
|
||||
if (p.flags & RAD_SP_DRY) {
|
||||
static const DryBreakers kNone;
|
||||
CandidateSet s;
|
||||
s.c.push_back(Candidate{ token, 0.0f, 0.0f });
|
||||
DryParams dp;
|
||||
dp.multiplier = p.dry_multiplier;
|
||||
dp.base = p.dry_base;
|
||||
dp.allowed_length = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2;
|
||||
dp.penalty_last_n = p.dry_penalty_last_n < 0 ? -1 : p.dry_penalty_last_n;
|
||||
host_dry(s, L.hist.data(), (int64_t)L.hist.size(), (int64_t)L.hist.size(), dp,
|
||||
L.dry ? *L.dry : kNone);
|
||||
y -= (double)s.c[0].logit;
|
||||
}
|
||||
/* The penalties, inverted: presence and frequency added back, then the repetition penalty
|
||||
* undone on the side of zero the logit is on -- it never changes sign. The window is the
|
||||
* stage's: the tail of the staged history, penalty_last_n long when that is positive. */
|
||||
if (p.flags & RAD_SP_PENALTY) {
|
||||
int64_t n = (int64_t)L.hist.size(), o = 0;
|
||||
if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
|
||||
int64_t count = 0;
|
||||
for (int64_t i = 0; i < n; ++i) count += L.hist[(size_t)(o + i)] == token;
|
||||
if (count > 0) {
|
||||
y += (double)count * p.freq_penalty + p.pres_penalty;
|
||||
y = y > 0.0 ? y * p.rep_penalty : y / p.rep_penalty;
|
||||
}
|
||||
}
|
||||
return (float)y;
|
||||
}
|
||||
|
||||
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
||||
int cap) {
|
||||
const int64_t w = 2 + 2 * (int64_t)k;
|
||||
auto live = [&](int r) {
|
||||
const float m = st[r * w], z = st[r * w + 1];
|
||||
return std::isfinite(m) && std::isfinite(z) && z > 0.0f;
|
||||
};
|
||||
double mx = -INFINITY;
|
||||
for (int r = 0; r < W; ++r)
|
||||
if (live(r)) mx = std::max(mx, (double)st[r * w]);
|
||||
double sum = 0.0;
|
||||
for (int r = 0; r < W; ++r)
|
||||
if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
|
||||
*log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
|
||||
|
||||
/* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
|
||||
* more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
|
||||
struct Pair { float v; int32_t id; };
|
||||
Pair buf[256];
|
||||
std::vector<Pair> heap;
|
||||
Pair* top = buf;
|
||||
if ((int64_t)W * k > (int64_t)(sizeof buf / sizeof buf[0])) {
|
||||
heap.resize((size_t)W * (size_t)k);
|
||||
top = heap.data();
|
||||
}
|
||||
int m = 0;
|
||||
for (int r = 0; r < W; ++r) {
|
||||
if (!live(r)) continue;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
const int32_t id = (int32_t)st[r * w + 2 + 2 * j];
|
||||
const float v = st[r * w + 3 + 2 * j];
|
||||
if (id >= 0 && std::isfinite(v)) top[m++] = Pair{ v, id };
|
||||
}
|
||||
}
|
||||
std::sort(top, top + m, [](const Pair& a, const Pair& b) {
|
||||
return a.v > b.v || (a.v == b.v && a.id < b.id);
|
||||
});
|
||||
const int n = std::min(cap, m);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
ids[j] = top[j].id;
|
||||
vals[j] = top[j].v;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const {
|
||||
if (!out || !lp_host_ || row < lp_lo_ || row >= lp_hi_) return RAD_E_STATE;
|
||||
const LpRow* L = nullptr;
|
||||
for (const LpRow& x : lp_rows_)
|
||||
if (x.row == row) { L = &x; break; }
|
||||
if (!L) return RAD_E_STATE;
|
||||
|
||||
/* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
|
||||
* rescale, the largest by value with the lower id first. */
|
||||
const int W = vocab_parallel() ? cfg_.world_size : 1;
|
||||
double log_z = 0.0;
|
||||
int32_t ids[kLpK * 8];
|
||||
float vals[kLpK * 8];
|
||||
const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
|
||||
(int)(sizeof ids / sizeof ids[0]));
|
||||
/* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
|
||||
* model, or every one at -inf -- and any number sent for it would be invented. */
|
||||
if (!std::isfinite(log_z)) {
|
||||
RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
|
||||
(long long)row);
|
||||
out->token = -1;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
out->token = token;
|
||||
out->n_top = std::min(L->n_top, n);
|
||||
for (int j = 0; j < out->n_top; ++j) {
|
||||
out->top_id[j] = ids[j];
|
||||
out->top_lp[j] = (float)((double)vals[j] - log_z);
|
||||
}
|
||||
|
||||
/* The token's own raw logit: exact when it is among the largest, and otherwise recovered
|
||||
* from the value the pick drew it at. */
|
||||
double own = NAN;
|
||||
for (int j = 0; j < n && std::isnan(own); ++j)
|
||||
if (ids[j] == token) own = (double)vals[j];
|
||||
if (std::isnan(own)) {
|
||||
const int64_t nc = cfg_.max_candidates;
|
||||
const int32_t* ci = lp_ci_host_ + row * nc;
|
||||
const float* cv = lp_cv_host_ + row * nc;
|
||||
for (int64_t c = 0; c < nc && std::isnan(own); ++c)
|
||||
if (ci[c] == token) own = (double)raw_logit(*L, token, cv[c]);
|
||||
}
|
||||
if (!std::isfinite(own)) {
|
||||
RAD_WARN("sampler: row %lld sampled token %d, which has no finite logit on the candidate "
|
||||
"plane it was drawn from; its logprobs cannot be computed", (long long)row, token);
|
||||
out->token = -1;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->logprob = (float)(own - log_z);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,21 @@
|
||||
* XTC
|
||||
* the pick
|
||||
*
|
||||
* TEMPERATURE MAY RUN AFTER THE CUTS INSTEAD, per sequence: llama.cpp's order, which a request
|
||||
* names with `samplers` (SamplingParams::temp_last). Such a row's temperature is staged at 1 for
|
||||
* the stage above, which skips it, and at its own value for a second `sample_temp` over the
|
||||
* candidate plane after XTC -- the same kernel at the candidate width, so no plugin needs a
|
||||
* second implementation of it. Every other row is 1 there.
|
||||
*
|
||||
* LOGPROBS ARE READ OFF THE RAW LOGITS, before the first stage: `sample_logprobs` summarises each
|
||||
* row that asks (RAD_SP_LOGPROBS) as its maximum, its normaliser and its kLpK largest (one more
|
||||
* than RAD_MAX_LOGPROBS, for the row's width below), and rank 0 copies that back behind the pick.
|
||||
* The emitted token's own logprob is its raw logit less the log normaliser. When it is not among the largest its raw logit is no longer on the card
|
||||
* -- every stage wrote the logits in place -- so it is recovered from the value the pick drew it
|
||||
* at, the candidate plane's, by undoing temperature, DRY and the penalties on the host
|
||||
* (logprobs_for). Such a row is never a greedy-flagged one: a greedy row asking for logprobs is
|
||||
* staged as a top-1 chain row, so that its token is drawn from a candidate plane too.
|
||||
*
|
||||
* A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask,
|
||||
* because temperature 0 collapses every other logit to -inf and a mask applied afterwards would
|
||||
* leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must
|
||||
@@ -50,6 +65,7 @@
|
||||
* sample_xtc M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
|
||||
* sample_pick M(range) n_cand cand_idx, cand_val, params -> token
|
||||
* sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val
|
||||
* sample_logprobs M(range) n_vocab k vocab_off? logits, params -> stats
|
||||
*
|
||||
* `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per
|
||||
* sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is
|
||||
@@ -196,6 +212,17 @@ public:
|
||||
* top-k) happens between the top-k and the cuts; full logits are never gathered. */
|
||||
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
|
||||
|
||||
/* THE EMITTED TOKEN'S LOGPROBS, after the step the last build_step staged has completed on the
|
||||
* card: row `row` must have been staged for a request with SamplingParams::n_probs >= 0, and
|
||||
* `token` is what the step sampled there. Rank 0's sampler only -- it is the one that copies
|
||||
* the summary back. RAD_E_STATE for a row that was not staged for logprobs; RAD_E_INVAL, with
|
||||
* `out->token` -1, for one whose numbers are not finite -- a row with no finite logit, or a
|
||||
* token drawn where none was -- which is a number no client should be sent. */
|
||||
int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
|
||||
/* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */
|
||||
bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
|
||||
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. */
|
||||
const DeviceSampleParams* staged_params(int64_t* n) const {
|
||||
@@ -240,6 +267,7 @@ private:
|
||||
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
||||
rad_op op_dry_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
|
||||
rad_op op_mask_ = RAD_NULL_HANDLE;
|
||||
rad_op op_topk_ = RAD_NULL_HANDLE;
|
||||
rad_op op_topp_ = RAD_NULL_HANDLE;
|
||||
@@ -250,9 +278,12 @@ private:
|
||||
rad_op op_argmax_ = RAD_NULL_HANDLE;
|
||||
rad_op op_allgather_ = RAD_NULL_HANDLE;
|
||||
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
|
||||
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* the raw distribution's summary */
|
||||
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
|
||||
|
||||
/* Device-side buffers, from the ordinary buffer plan. */
|
||||
rad_buf buf_params_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
|
||||
rad_buf buf_hist_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
|
||||
rad_buf buf_mask_ = RAD_NULL_HANDLE;
|
||||
@@ -260,9 +291,15 @@ private:
|
||||
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_gather_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
|
||||
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
||||
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
||||
|
||||
/* Pinned staging. One allocation each, at declare, never on the step path. */
|
||||
DeviceSampleParams* params_stage_ = nullptr;
|
||||
/* The late temperature's rows: params_stage_'s, with each row's temperature at 1 unless it
|
||||
* runs last. Uploaded only by a step where some row does (any_late_). */
|
||||
DeviceSampleParams* late_stage_ = nullptr;
|
||||
bool any_late_ = false;
|
||||
/* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the
|
||||
* step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not
|
||||
* have run yet; rows written into the same staging would reach that step's sampler instead.
|
||||
@@ -305,6 +342,35 @@ private:
|
||||
* request must not stop the step loop for everyone else. */
|
||||
std::vector<uint64_t> failed_;
|
||||
|
||||
/* ---------------------------------------------------------- logprobs */
|
||||
/* THE SUMMARY'S WIDTH: RAD_MAX_LOGPROBS + 1 pairs, not RAD_MAX_LOGPROBS, so that a row is 44
|
||||
* floats -- whole 16-byte words, which is what the all-gather of a split vocabulary moves (and
|
||||
* libr4d's refuses anything else). The extra pair is never reported. */
|
||||
static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
|
||||
static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
|
||||
/* WHAT UNDOING A ROW'S CHAIN NEEDS, kept from build_step for each row staged with
|
||||
* RAD_SP_LOGPROBS: the staged row itself, the temperature the candidate value carries, the
|
||||
* history window both history stages read, and the request's DRY breakers. Copied rather
|
||||
* than pointed at, because the staging is rebuilt by the next step. */
|
||||
struct LpRow {
|
||||
int64_t row = -1;
|
||||
int32_t n_top = 0;
|
||||
float temp = 1.0f; /* the candidate value is l / temp */
|
||||
DeviceSampleParams p{};
|
||||
std::vector<int32_t> hist; /* the staged history row, [0, hist_len) */
|
||||
const DryBreakers* dry = nullptr; /* lives in seqs_ for the request's lifetime */
|
||||
};
|
||||
std::vector<LpRow> lp_rows_;
|
||||
/* Rank 0's copies, written behind the pick: the summaries ([rows, W * lp_width()], W ranks
|
||||
* side by side) and the candidate planes the pick drew from. */
|
||||
float* lp_host_ = nullptr;
|
||||
int32_t* lp_ci_host_ = nullptr;
|
||||
float* lp_cv_host_ = nullptr;
|
||||
int64_t lp_lo_ = 0, lp_hi_ = 0; /* the rows copied, [lo, hi) */
|
||||
/* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
|
||||
* undone, in the reverse of the order the chain applied them. */
|
||||
float raw_logit(const LpRow& L, int32_t token, float v) const;
|
||||
|
||||
/* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request
|
||||
* because Request is a frozen struct shared across components and a unique_ptr in it would
|
||||
* make the scheduler's copies a compile error. */
|
||||
@@ -314,4 +380,13 @@ private:
|
||||
void stage_free();
|
||||
};
|
||||
|
||||
/* SPLIT-VOCABULARY SUMMARIES, MERGED: `W` ranks' `sample_logprobs` rows of `k` pairs each, side by
|
||||
* side in `st` (W * (2 + 2k) floats). Sets the shared log normaliser and fills up to `cap` of the
|
||||
* largest (id, logit) pairs over every rank, descending, ties to the lower id; returns how many. A
|
||||
* rank whose maximum or normaliser is not finite contributes nothing, nor does a pair whose logit
|
||||
* is not finite, and `*log_z` comes back NaN when no rank contributes. One rank is the same
|
||||
* arithmetic. What Sampler::logprobs_for reads a step's summaries with. */
|
||||
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
|
||||
int cap);
|
||||
|
||||
} /* namespace rad */
|
||||
+41
-28
@@ -495,21 +495,27 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
: a.conv_grp < b.conv_grp;
|
||||
});
|
||||
|
||||
mm_on_ = prog.encoder.modalities != 0;
|
||||
mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ media staging */
|
||||
BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
const RadEncoderDecl& e = prog_->encoder;
|
||||
n_embd_ = e.n_embd;
|
||||
enc_patches_ = e.max_patches;
|
||||
enc_dim_ = e.patch_dim;
|
||||
/* The most segments one pass can hold: a segment is at least one output row, `merge` patches. */
|
||||
enc_segs_ = e.max_patches / (e.merge > 0 ? e.merge : 1) + 1;
|
||||
/* The larger of the two encoders' passes, field by field: they run one at a time. Both write
|
||||
* rows of the model's embedding width. */
|
||||
enc_patches_ = enc_pix_elems_ = enc_segs_ = 0;
|
||||
n_embd_ = 0;
|
||||
for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) {
|
||||
if (e->modalities == 0) continue;
|
||||
n_embd_ = std::max<int64_t>(n_embd_, e->n_embd);
|
||||
enc_patches_ = std::max<int64_t>(enc_patches_, e->max_patches);
|
||||
enc_pix_elems_ = std::max<int64_t>(enc_pix_elems_, e->max_patches * e->patch_dim);
|
||||
/* The most segments one pass can hold: a segment is at least one output row. */
|
||||
enc_segs_ = std::max<int64_t>(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1);
|
||||
}
|
||||
MediaBytes m;
|
||||
m.mm = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t);
|
||||
m.pix = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t);
|
||||
m.pix = enc_pix_elems_ * (int64_t)sizeof(uint16_t);
|
||||
m.crd = 4 * enc_patches_ * (int64_t)sizeof(int32_t);
|
||||
m.cu = (enc_segs_ + 1) * (int64_t)sizeof(int32_t);
|
||||
return m;
|
||||
@@ -546,7 +552,7 @@ int BatchBuilder::alloc_media() {
|
||||
}
|
||||
if (rad_event_create_as(&mm_ev_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT) < 0) return RAD_E_DEVICE;
|
||||
RAD_INFO("media staging: %s a rank for a step's encoder rows and %s for an encoder pass of "
|
||||
"%lld patches", humanb(mm_bytes).c_str(),
|
||||
"up to %lld patches", humanb(mm_bytes).c_str(),
|
||||
humanb(pix_bytes + crd_bytes + cu_bytes).c_str(), (long long)enc_patches_);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1272,30 +1278,38 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the encoder pass */
|
||||
const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& parts, int step) {
|
||||
if (!mm_on_ || parts.empty()) return nullptr;
|
||||
const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc) {
|
||||
if (!mm_on_ || parts.empty() || enc.modalities == 0) return nullptr;
|
||||
const int64_t enc_dim = enc.patch_dim;
|
||||
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
|
||||
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
|
||||
enc_cu_host_[0] = 0;
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
const int64_t seg_p = (int64_t)it.grid_h * it.grid_w;
|
||||
const int64_t np = seg_p * p.n_seg;
|
||||
if (it.patch_dim != enc_dim_ || n_patch + np > enc_patches_ ||
|
||||
n_seg + p.n_seg > enc_segs_ || p.seg0 + p.n_seg > it.n_seg) {
|
||||
RAD_ERR("encoder pass: %lld patches in %lld segments do not fit the declared pass of "
|
||||
"%lld patches of %lld elements", (long long)(n_patch + np),
|
||||
(long long)(n_seg + p.n_seg), (long long)enc_patches_, (long long)enc_dim_);
|
||||
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;
|
||||
}
|
||||
std::memcpy(enc_pix_host_ + n_patch * enc_dim_,
|
||||
it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim_,
|
||||
(size_t)(np * enc_dim_) * sizeof(uint16_t));
|
||||
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) {
|
||||
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() + 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]. */
|
||||
{
|
||||
@@ -1303,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));
|
||||
@@ -1316,7 +1329,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RadStream st = ranks_[r].stream;
|
||||
if (rad_memcpy_async(enc_pix_dev_[r], enc_pix_host_,
|
||||
n_patch * enc_dim_ * (int64_t)sizeof(uint16_t), st) < 0 ||
|
||||
n_patch * enc_dim * (int64_t)sizeof(uint16_t), st) < 0 ||
|
||||
rad_memcpy_async(enc_coord_dev_[r], enc_coord_host_,
|
||||
4 * n_patch * (int64_t)sizeof(int32_t), st) < 0 ||
|
||||
rad_memcpy_async(enc_cu_dev_[r], enc_cu_host_,
|
||||
@@ -1333,7 +1346,7 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
B.step = step;
|
||||
B.n_kv_groups = (int)o.kv[r].size();
|
||||
B.kv = o.kv[r].data();
|
||||
B.enc = 1;
|
||||
B.enc = (int32_t)enc.modalities;
|
||||
B.enc_n_patch = n_patch;
|
||||
B.enc_pixels = enc_pix_dev_[r];
|
||||
B.enc_coord = static_cast<const int32_t*>(enc_coord_dev_[r]);
|
||||
|
||||
+8
-5
@@ -168,9 +168,11 @@ public:
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step);
|
||||
/* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts,
|
||||
* and its modalities are RadBatch::enc. */
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc);
|
||||
bool has_encoder() const { return mm_on_; }
|
||||
int64_t encoder_patches() const { return enc_patches_; }
|
||||
|
||||
|
||||
private:
|
||||
@@ -366,9 +368,10 @@ private:
|
||||
uint16_t* mm_host_ = nullptr;
|
||||
RadEvent mm_ev_ = nullptr;
|
||||
bool mm_ev_live_ = false;
|
||||
/* ...and the encoder's inputs: patches, their coordinates and the segment boundaries, the
|
||||
* largest pass the plugin declared. One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_dim_ = 0, enc_segs_ = 0;
|
||||
/* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized
|
||||
* for the larger of the passes the plugin declared (a vision tower's and an audio encoder's
|
||||
* run one at a time and share it). One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0;
|
||||
std::vector<void*> enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
|
||||
uint16_t* enc_pix_host_ = nullptr;
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
|
||||
@@ -374,7 +374,7 @@ struct PCBinding final : IPrefixCache {
|
||||
/* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by --
|
||||
* so the tiers' session view and the checkpoint index are talking about one thing. */
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label);
|
||||
}
|
||||
/* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
|
||||
* now, and says whether any landed. Called on the step thread under the scheduler's lock. */
|
||||
|
||||
@@ -46,6 +46,11 @@ struct SchedMetrics {
|
||||
* commit and staging with the card idle, so steps_ahead against steps is how much of the run
|
||||
* kept the card fed through the host's part of it. */
|
||||
int64_t steps_ahead = 0;
|
||||
/* PREFILL CHUNKS HELD BACK for other work in the same step (--busy-prefill-chunk): each is a
|
||||
* chunk that would have taken more of the step and left decode rows behind it, or a request
|
||||
* waiting to be admitted, with nothing. Zero under `off`, and on a load that never overlaps a
|
||||
* prefill with anything else. */
|
||||
int64_t prefill_chunks_capped = 0;
|
||||
|
||||
/* HOW LONG THE ENGINE SPENT INSIDE A STEP, cumulative nanoseconds, and the decode half of it
|
||||
* separately. Neither is a derived rate -- they are counters, and that is the point.
|
||||
|
||||
+259
-11
@@ -177,6 +177,17 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
if (!r) return RAD_E_INVAL;
|
||||
if (r->prompt.empty()) return RAD_E_INVAL;
|
||||
if (by_id_.count(r->id)) return RAD_E_DUPLICATE;
|
||||
/* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a
|
||||
* step could never be admitted and would wait for good. */
|
||||
if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
|
||||
/* 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. */
|
||||
@@ -705,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;
|
||||
@@ -732,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) {
|
||||
@@ -774,6 +792,97 @@ int64_t Scheduler::tail_checkpoint(int64_t target) const {
|
||||
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ a prefill sharing a step */
|
||||
void Scheduler::set_stage_rows(int64_t rows) {
|
||||
stage_rows_ = rows > 0 ? rows : 0;
|
||||
const int64_t n = cfg_.busy_prefill_chunk;
|
||||
if (n == 0) {
|
||||
RAD_INFO("scheduler: --busy-prefill-chunk off: a prefill chunk takes every token the step "
|
||||
"has left, so decode rows behind it and requests waiting to start get none until "
|
||||
"it ends");
|
||||
return;
|
||||
}
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
if (n > 0) {
|
||||
RAD_INFO("scheduler: --busy-prefill-chunk %lld: a prefill chunk sharing a step with other "
|
||||
"work takes at most %lld tokens of it", (long long)n, (long long)(n / Q * Q));
|
||||
if (stage_rows_ > 0 && n < stage_rows_)
|
||||
RAD_WARN("scheduler: --busy-prefill-chunk %lld is under the %lld-token step the prefill "
|
||||
"stager overlaps at: a held-back chunk alone reads every routed layer's "
|
||||
"pooled experts synchronously, which slows a long prefill far more than the "
|
||||
"smaller step saves", (long long)n, (long long)stage_rows_);
|
||||
return;
|
||||
}
|
||||
RAD_INFO("scheduler: --busy-prefill-chunk auto: a prefill chunk sharing a step leaves decode "
|
||||
"rows and waiting requests their room and keeps at least %lld tokens%s",
|
||||
(long long)std::max(Q, stage_rows_ / Q * Q),
|
||||
stage_rows_ > 0 ? " (the prefill stager's smallest pass)" : "");
|
||||
}
|
||||
|
||||
/* HOW MUCH OF THE STEP A PREFILL CHUNK MAY TAKE WHEN OTHER WORK WANTS IN.
|
||||
*
|
||||
* Without a cap the running loop hands a prefill row every token the step has left
|
||||
* (plan_chunk(..., budget)). On a step budget of a few thousand tokens and a prompt of a few
|
||||
* hundred thousand, that is every step for a minute or more, and in that time a decode row behind
|
||||
* the prefill in running_ gets nothing (`want > budget` -> break) and admission never runs
|
||||
* (`budget > 0`): a mostly-cached turn that needs a few hundred tokens waits for the whole of
|
||||
* somebody else's prefill. The cap leaves `reserve` -- the rows behind it and a share for
|
||||
* admission, worked out by step() -- and never goes under the floor.
|
||||
*
|
||||
* THE FLOOR is the smallest step the prefill stager overlaps (rounded down to the quantum: the
|
||||
* rows the chunk shares the step with make up the difference). A step under it reads every
|
||||
* routed layer's pooled experts synchronously, and on an expert-tiered placement that costs a
|
||||
* long prefill far more than the shared step saves -- a budget set one token under the threshold
|
||||
* measured -65 % prefill (#61). With no stager the floor is one quantum.
|
||||
*
|
||||
* AND THE REST OF THE INTERVAL STAYS ABOVE IT. A chunk ends on the checkpoint interval
|
||||
* (plan_chunk), so a chunk held short of the boundary leaves a remainder that is the next step's
|
||||
* whole chunk. Held to `budget - reserve`, that remainder is the size of the reserve -- a few
|
||||
* hundred tokens, under the floor, and the slowest step of all. When the cap would leave such a
|
||||
* remainder the interval is split into two chunks each at or above the floor instead: two staged
|
||||
* steps, each with room for the rest of the step's work. */
|
||||
int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t reserve, bool shared, bool rows_only) const {
|
||||
const int64_t mode = cfg_.busy_prefill_chunk;
|
||||
if (mode == 0 || budget <= 0) return budget;
|
||||
/* auto holds a chunk back only for work that would otherwise get NOTHING this step -- rows
|
||||
* behind it, a request waiting to start. Rows already planned ahead of it are in the step
|
||||
* whatever the chunk takes, so auto leaves the chunk alone for them (it was never what
|
||||
* starved them). An explicit N is the operator trading prefill speed for the latency of every
|
||||
* other row, so it applies whenever the chunk shares the step at all. */
|
||||
if (reserve <= 0 && !(mode > 0 && shared)) return budget;
|
||||
reserve = std::max<int64_t>(reserve, 0);
|
||||
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
|
||||
|
||||
int64_t cap = budget - reserve;
|
||||
if (mode > 0) {
|
||||
/* The operator's number. No floor: --busy-prefill-chunk N under the stager's step is a
|
||||
* choice set_stage_rows warns about, not one this overrides. */
|
||||
cap = std::min(cap, mode);
|
||||
} else {
|
||||
const int64_t floor = std::max(Q, stage_rows_ / Q * Q);
|
||||
cap = std::max(cap, floor);
|
||||
const int64_t remaining = n_target - n_computed;
|
||||
int64_t span = remaining; /* where this run of chunks must end */
|
||||
if (geo_.checkpoints()) {
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
span = std::min(span, ((n_computed / I) + 1) * I - n_computed);
|
||||
}
|
||||
/* ...but not for decode rows alone. Their reserve is a few tokens, the chunk ends a
|
||||
* quantum short of the boundary and the next step finishes the interval: the same pair of
|
||||
* steps a prefill already runs whenever decode rows are planned AHEAD of it, so it adds
|
||||
* no step shape the engine does not already pay for. Halving instead would hold a long
|
||||
* prompt to half-interval chunks for as long as any request decodes behind it -- measured
|
||||
* as the larger cost (NOTES: prefill-share run 2). The split is for a share (a request
|
||||
* waiting to start, another prefill), which lasts a step or two. */
|
||||
if (!rows_only && cap < span && span - cap < floor && span - floor >= floor)
|
||||
cap = span - floor;
|
||||
}
|
||||
cap = std::min(cap, budget);
|
||||
cap = std::max(cap, Q);
|
||||
return std::min(cap, budget);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ preemption */
|
||||
void Scheduler::preempt_back() {
|
||||
int32_t slot = running_.back();
|
||||
@@ -807,7 +916,7 @@ void Scheduler::preempt_back() {
|
||||
/* Admission checks the KV budget BEFORE a request enters running. A request admitted without the
|
||||
* blocks to run it is a request that will be preempted on its first step, which costs a full
|
||||
* recompute for nothing. */
|
||||
int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
Request& r = *s.req;
|
||||
|
||||
if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
|
||||
@@ -899,7 +1008,17 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
|
||||
int64_t target = s.seq_len();
|
||||
int64_t ckpt = -1;
|
||||
int64_t want = plan_chunk(r.n_computed, target, budget, &ckpt);
|
||||
/* AN ADMISSION SHARES THE STEP THE SAME WAY. A cold prompt admitted with requests queued
|
||||
* behind it would otherwise take every token left, and the queue behind it would wait a step
|
||||
* 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, 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;
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL;
|
||||
@@ -942,6 +1061,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
r.state = ReqState::Running;
|
||||
s.running = true;
|
||||
server::sink_admitted(r.sink);
|
||||
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(), r.n_cached);
|
||||
s.sched_tokens = (int32_t)want;
|
||||
s.pending_ckpt = ckpt;
|
||||
++m_.admitted;
|
||||
@@ -995,6 +1115,31 @@ const RadBatch* Scheduler::step() {
|
||||
* alone rather than as anything failing. */
|
||||
const int depth = draft_.next_depth();
|
||||
|
||||
/* WHAT ELSE WANTS INTO THIS STEP, for --busy-prefill-chunk (busy_cap). The rows still to be
|
||||
* walked -- each decode row's 1 + the deepest window it can take, each prefill row a share --
|
||||
* and one share when a request is waiting and a sequence slot is free for it. Counted down as
|
||||
* the loop walks, so a row's reserve is what is BEHIND it. No allocation: two counters. */
|
||||
const bool share_step = cfg_.busy_prefill_chunk != 0;
|
||||
const int64_t share_tok = std::max<int64_t>(std::max<int64_t>(geo_.quantum, 1),
|
||||
cfg_.max_tok / 8 / std::max<int64_t>(geo_.quantum, 1)
|
||||
* std::max<int64_t>(geo_.quantum, 1));
|
||||
const int64_t dec_row_tok = 1 + std::max<int64_t>(depth, draft_.step_window());
|
||||
int64_t behind_dec = 0, behind_pf = 0;
|
||||
if (share_step) {
|
||||
for (int32_t slot : running_) {
|
||||
const Request& rr = *reqs_[(size_t)slot]->req;
|
||||
const int64_t tg = reqs_[(size_t)slot]->seq_len();
|
||||
const bool pf = (rr.n_computed < (int64_t)rr.prompt.size()) || (rr.n_computed + 1 < tg);
|
||||
if (pf) ++behind_pf; else behind_dec += dec_row_tok;
|
||||
}
|
||||
}
|
||||
const bool admit_waits = share_step && !waiting_.empty() && !free_cards_.empty() &&
|
||||
(int64_t)running_.size() < cfg_.max_seqs;
|
||||
/* The first prefill chunk held back this step (its index in plan_.e before the sort) and what
|
||||
* it would have taken: whatever the work it made room for did not use goes back to it. */
|
||||
int32_t capped_at = -1;
|
||||
int64_t capped_full = 0;
|
||||
|
||||
/* ---------------------------------------------------------- running requests first */
|
||||
/* Continuous batching: a request already holding blocks is served before a new one is let in,
|
||||
* because the alternative is admitting work that then preempts work already half done. */
|
||||
@@ -1008,11 +1153,28 @@ const RadBatch* Scheduler::step() {
|
||||
const int64_t target = s.seq_len();
|
||||
const bool prefill = (r.n_computed < (int64_t)r.prompt.size()) ||
|
||||
(r.n_computed + 1 < target);
|
||||
if (share_step) {
|
||||
if (prefill) behind_pf = std::max<int64_t>(0, behind_pf - 1);
|
||||
else behind_dec = std::max<int64_t>(0, behind_dec - dec_row_tok);
|
||||
}
|
||||
|
||||
int64_t ckpt = -1;
|
||||
int64_t want;
|
||||
if (prefill) {
|
||||
want = plan_chunk(r.n_computed, target, budget, &ckpt);
|
||||
const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0;
|
||||
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, r.checkpoint_at);
|
||||
if (cap < budget && want > 0 && capped_at < 0) {
|
||||
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
|
||||
* take nothing this step, but a decode row behind it needs only 1 + its window -- so
|
||||
* it is passed over rather than ending the loop (off keeps the old `break`). */
|
||||
if (want <= 0 && share_step) { ++i; continue; }
|
||||
} else {
|
||||
/* A verify step is 1 + n_draft query rows, which is why attention kernels take a
|
||||
* query length rather than assuming one (spec §10). */
|
||||
@@ -1180,9 +1342,21 @@ const RadBatch* Scheduler::step() {
|
||||
* behind it is asked, exactly as for a context still being read off disk; the engine
|
||||
* runs the encoder before the next step (encodes_pending). */
|
||||
if (s.req->media && !media_ready(s)) { ++at; continue; }
|
||||
const int as = admit_one(s, budget);
|
||||
/* One share left for the next request in the queue, when there is one and a slot
|
||||
* for it (busy_cap). The embed path takes a whole input or nothing, so it is not
|
||||
* held back: a share could only turn its admission into a refusal. */
|
||||
const int64_t areserve =
|
||||
share_step && !s.req->embed && at + 1 < waiting_.size() &&
|
||||
(int64_t)plan_.e.size() + 1 < cfg_.max_seqs && free_cards_.size() > 1
|
||||
? share_tok : 0;
|
||||
admit_full_ = 0;
|
||||
const int as = admit_one(s, budget, areserve);
|
||||
if (as == kAdmitWait) { ++at; continue; }
|
||||
if (as < 0) break; /* head of line: do not admit behind it */
|
||||
if (admit_full_ > s.sched_tokens && capped_at < 0) {
|
||||
capped_at = (int32_t)plan_.e.size();
|
||||
capped_full = admit_full_;
|
||||
}
|
||||
|
||||
Request& r = *s.req;
|
||||
StepEntry e;
|
||||
@@ -1236,6 +1410,43 @@ const RadBatch* Scheduler::step() {
|
||||
}
|
||||
}
|
||||
|
||||
/* WHAT THE HELD-BACK CHUNK LEFT FOR OTHERS AND THEY DID NOT TAKE GOES BACK TO IT. The reserve
|
||||
* is a forecast: a decode row drafts less than its window, an admission is refused (the pool
|
||||
* is short, the head of the queue waits on a read), a step preempts and skips admission. A
|
||||
* chunk held to the stager's floor in a step that then carries nothing else is a pass under
|
||||
* the threshold -- exactly the slow step the floor exists to avoid -- so the unused budget is
|
||||
* handed back, as far as the chunk's own geometry allows (plan_chunk) and only if the pool
|
||||
* grants the blocks without a preemption; otherwise the chunk stays as planned. */
|
||||
if (capped_at >= 0) {
|
||||
StepEntry& e = plan_.e[(size_t)capped_at];
|
||||
const Request& r = *e.req;
|
||||
SchedReq& s = *reqs_[(size_t)e.slot];
|
||||
const int64_t had = e.n_tokens;
|
||||
/* An explicit --busy-prefill-chunk N is a ceiling the operator chose, not a forecast:
|
||||
* the chunk grows back to it at most. */
|
||||
int64_t limit = std::min(capped_full, had + budget);
|
||||
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, 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());
|
||||
if (ckpt > 0) {
|
||||
int32_t cs = -1;
|
||||
if (pc_->reserve_checkpoint(r, ckpt, &cs) >= 0 && cs >= 0) {
|
||||
e.ckpt_tok = (int32_t)(grown - 1);
|
||||
e.ckpt_slot = cs;
|
||||
++m_.checkpoints_written;
|
||||
}
|
||||
}
|
||||
s.sched_tokens = (int32_t)grown;
|
||||
plan_.n_tok += grown - had;
|
||||
budget -= grown - had;
|
||||
}
|
||||
if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped;
|
||||
}
|
||||
|
||||
if (plan_.e.empty()) return nullptr;
|
||||
|
||||
/* THE DECODE ROWS FIRST, and both halves therefore contiguous.
|
||||
@@ -1363,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) {
|
||||
@@ -1581,6 +1804,10 @@ int Scheduler::commit(const StepResult& res) {
|
||||
bool eos = res.eos && res.eos[i] && !r.ignore_eos;
|
||||
|
||||
bool overflowed = false;
|
||||
/* A token whose logprobs the engine could not compute (TokenLogprobs::token -1) for a
|
||||
* request that asked for them: the request fails with the reason rather than send that
|
||||
* token without the numbers it was asked for, and nothing after it is sent. */
|
||||
bool lp_failed = false;
|
||||
|
||||
/* THE SNAPSHOT THE ENGINE JUST TOOK IS NOW READABLE. Marking it here rather than at
|
||||
* reservation is the difference between a checkpoint and a promise: reserve_checkpoint
|
||||
@@ -1596,14 +1823,24 @@ int Scheduler::commit(const StepResult& res) {
|
||||
if (e.is_prefill) {
|
||||
r.n_computed += e.n_tokens;
|
||||
step_prefill_tok_ += e.n_tokens;
|
||||
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
|
||||
r.n_cached);
|
||||
/* Once, when the prompt is fully placed: the admission accounting the usage block
|
||||
* reports. `n_cached` is what the prefix cache supplied and is not recomputed here. */
|
||||
if (r.n_computed >= (int64_t)r.prompt.size())
|
||||
server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached);
|
||||
if (e.produces_token && res.token) {
|
||||
if (e.produces_token && res.token && r.embed) {
|
||||
/* The answer is the pooled vector the engine already put in the sink; there is
|
||||
* no token to emit, and `eos` ends the request below. */
|
||||
if (!s.first_tok_us) s.first_tok_us = mono_us();
|
||||
} else if (e.produces_token && res.token) {
|
||||
if (!s.first_tok_us) s.first_tok_us = mono_us();
|
||||
r.output.push_back(res.token[i]);
|
||||
overflowed = !server::sink_push(r.sink, res.token[i]);
|
||||
const TokenLogprobs* lp =
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i]] : nullptr;
|
||||
if (lp && lp->token < 0) lp_failed = true;
|
||||
else overflowed = !server::sink_push(r.sink, res.token[i], lp);
|
||||
/* The conv window absorbed this chunk; the cursor advances by one committed
|
||||
* position, exactly as it does in decode. */
|
||||
s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
|
||||
@@ -1651,15 +1888,21 @@ int Scheduler::commit(const StepResult& res) {
|
||||
/* AND THE CONTEXT BOUNDS IT WHATEVER max_tokens SAYS, including "no limit": a
|
||||
* sequence may not grow past the positions this deployment can address. */
|
||||
if (ctx_limit_ > 0 && ctx_limit_ - s.seq_len() < room) room = ctx_limit_ - s.seq_len();
|
||||
auto emit = [&](int32_t t) {
|
||||
/* `j` is the token's place in the step's emission: its logprobs row is the entry's
|
||||
* j-th, when the request asked for them. */
|
||||
auto emit = [&](int32_t t, int32_t j) {
|
||||
if (room <= 0) return;
|
||||
--room;
|
||||
if (!s.first_tok_us) s.first_tok_us = mono_us();
|
||||
r.output.push_back(t);
|
||||
if (!server::sink_push(r.sink, t)) overflowed = true;
|
||||
const TokenLogprobs* lp =
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i] + j] : nullptr;
|
||||
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
|
||||
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
|
||||
};
|
||||
for (int32_t j = 0; j < a; ++j) emit(s.draft[j]);
|
||||
if (res.token) emit(res.token[i]);
|
||||
for (int32_t j = 0; j < a; ++j) emit(s.draft[j], j);
|
||||
if (res.token) emit(res.token[i], a);
|
||||
r.n_computed = valid;
|
||||
step_decode_tok_ += 1 + a;
|
||||
|
||||
@@ -1709,6 +1952,11 @@ int Scheduler::commit(const StepResult& res) {
|
||||
close_request(s, ReqState::Failed, "sink_overflow", carried);
|
||||
++m_.failed;
|
||||
completed_.push_back(r.id);
|
||||
} else if (lp_failed) {
|
||||
close_request(s, ReqState::Failed, "logprobs", carried, true, RAD_E_STATE,
|
||||
"the logprobs of a token it generated could not be computed");
|
||||
++m_.failed;
|
||||
completed_.push_back(r.id);
|
||||
} else if (server::sink_cancelled(r.sink)) {
|
||||
/* The client hung up. Spec §14: the blocks go back now rather than at the end of a
|
||||
* generation nobody will read. */
|
||||
|
||||
+32
-7
@@ -176,6 +176,10 @@ public:
|
||||
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
|
||||
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
|
||||
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
|
||||
/* LOGPROBS, null on a step where no request asked: entry i's j-th emitted token (its
|
||||
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
|
||||
const TokenLogprobs* lp = nullptr;
|
||||
const int32_t* first_row = nullptr; /* [n_seq] */
|
||||
};
|
||||
|
||||
/* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it,
|
||||
@@ -301,11 +305,11 @@ public:
|
||||
bool encodes_pending() const;
|
||||
void take_encodes(std::vector<std::shared_ptr<mm::Item>>* out);
|
||||
/* An encoder pass over whole segments; see BatchBuilder::build_encoder. */
|
||||
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step) {
|
||||
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return builder_.build_encoder(parts, step);
|
||||
return builder_.build_encoder(parts, step, enc);
|
||||
}
|
||||
int64_t encoder_patches() const { return builder_.encoder_patches(); }
|
||||
|
||||
/* Drop every prefix-cache entry, returning how many were dropped, or RAD_E_UNSUPPORTED when
|
||||
* this engine has no prefix cache. Under the step lock: releasing the cache's references is
|
||||
@@ -453,13 +457,28 @@ 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
|
||||
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
|
||||
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
|
||||
bool shared = false, bool rows_only = false) const;
|
||||
|
||||
private:
|
||||
Program* prog_ = nullptr;
|
||||
@@ -468,6 +487,10 @@ private:
|
||||
KVGeom kvgeom_{};
|
||||
/* Does this model carry recurrent state a prefix hit would have to restore? See admit_one. */
|
||||
bool has_linear_state_ = false;
|
||||
/* set_stage_rows: the prefill stager's smallest pass, 0 when it is not armed. */
|
||||
int64_t stage_rows_ = 0;
|
||||
/* Set by admit_one when it held the admitted chunk back: what it would have taken. */
|
||||
int64_t admit_full_ = 0;
|
||||
IKVManager* kv_ = nullptr;
|
||||
IPrefixCache* pc_ = nullptr;
|
||||
|
||||
@@ -715,7 +738,9 @@ private:
|
||||
/* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is
|
||||
* either -- or kAdmitWait when its context is still being read off disk and the next request
|
||||
* may go ahead of it. */
|
||||
int admit_one(SchedReq& s, int64_t budget);
|
||||
/* `reserve`: tokens of the step to leave for the requests queued behind this one
|
||||
* (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */
|
||||
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
|
||||
static constexpr int kAdmitWait = 1;
|
||||
/* The queue positions one step's admission took, kept to reuse the allocation. */
|
||||
std::vector<size_t> took_;
|
||||
|
||||
@@ -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
|
||||
+35
-5
@@ -142,6 +142,7 @@ public:
|
||||
SessionStat o;
|
||||
o.id = s.id;
|
||||
o.model = s.model;
|
||||
o.label = s.label;
|
||||
o.n_tokens = s.n_tokens;
|
||||
o.bytes = s.bytes;
|
||||
o.idle_s = now > s.last_used_ns ? (double)(now - s.last_used_ns) / 1e9 : 0.0;
|
||||
@@ -293,6 +294,7 @@ public:
|
||||
o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed;
|
||||
o.steps_decode = m.steps_decode;
|
||||
o.steps_ahead = m.steps_ahead;
|
||||
o.prefill_chunks_capped = m.prefill_chunks_capped;
|
||||
o.decode_rows_unspeculated = m.decode_rows_unspeculated;
|
||||
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
|
||||
return o;
|
||||
@@ -319,6 +321,7 @@ public:
|
||||
std::string push(int32_t t) override { return d_.push(t); }
|
||||
std::string flush() override { return d_.flush(); }
|
||||
bool stopped() const override { return d_.stopped(); }
|
||||
std::string stop_hit() const override { return d_.stop_hit(); }
|
||||
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
|
||||
private:
|
||||
Detokenizer d_;
|
||||
@@ -376,6 +379,14 @@ public:
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return utf8_sanitize(vocab_->text(id));
|
||||
}
|
||||
std::string token_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/true);
|
||||
}
|
||||
std::string reply_bytes(int32_t id) const override {
|
||||
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
|
||||
return tok_.decode({ id }, /*render_special=*/false);
|
||||
}
|
||||
|
||||
std::unique_ptr<IDetokenizer> detokenizer(
|
||||
const std::vector<std::string>& stops,
|
||||
@@ -549,7 +560,21 @@ public:
|
||||
bool supports_tools() const override { return t_.caps().tools; }
|
||||
bool supports_reasoning() const override { return t_.caps().preserve_reasoning; }
|
||||
std::string tool_refusal() const override { return tool_refusal_; }
|
||||
const std::string& source() const { return t_.source(); }
|
||||
std::string source() const override { return t_.source(); }
|
||||
/* Under llama-server's names (its chat_template_caps), from the same probe. */
|
||||
std::string caps() const override {
|
||||
const ChatCaps& c = t_.caps();
|
||||
json o;
|
||||
o["supports_tools"] = c.tools;
|
||||
o["supports_tool_calls"] = c.tool_calls;
|
||||
o["supports_system_role"] = c.system_role;
|
||||
o["supports_parallel_tool_calls"] = c.parallel_tool_calls;
|
||||
o["supports_preserve_reasoning"] = c.preserve_reasoning;
|
||||
o["supports_string_content"] = c.string_content;
|
||||
o["supports_typed_content"] = c.typed_content;
|
||||
o["supports_object_arguments"] = c.object_arguments;
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
|
||||
ChatRender* out, std::string* why) const override {
|
||||
@@ -559,6 +584,7 @@ public:
|
||||
o.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
o.tool_choice = opt.tool_choice;
|
||||
o.reasoning_format = opt.reasoning_format;
|
||||
o.continue_final = opt.continue_final;
|
||||
o.grammar = opt.grammar;
|
||||
o.json_schema = opt.json_schema;
|
||||
o.template_kwargs = opt.template_kwargs;
|
||||
@@ -698,14 +724,18 @@ public:
|
||||
if (!p_ || !mm::decoder_available()) return false;
|
||||
if (k == MediaKind::Image) return (mod_ & RAD_MM_IMAGE) != 0;
|
||||
if (k == MediaKind::Video) return (mod_ & RAD_MM_VIDEO) != 0;
|
||||
if (k == MediaKind::Audio) return (mod_ & RAD_MM_AUDIO) != 0 && p_->has_audio();
|
||||
return false;
|
||||
}
|
||||
|
||||
int prepare(MediaKind k, const std::vector<uint8_t>& bytes, std::shared_ptr<mm::Item>* out,
|
||||
std::string* why) override {
|
||||
int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
|
||||
std::shared_ptr<mm::Item>* out, std::string* why) override {
|
||||
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
|
||||
return k == MediaKind::Image ? p_->image(bytes.data(), bytes.size(), out, why)
|
||||
: p_->video(bytes.data(), bytes.size(), out, why);
|
||||
if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why);
|
||||
return k == MediaKind::Image
|
||||
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
|
||||
opts.max_pixels)
|
||||
: p_->video(bytes.data(), bytes.size(), out, why);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
+220
-27
@@ -1,6 +1,7 @@
|
||||
/* core/server/admin.cpp -- vLLM's non-generation endpoints.
|
||||
/* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
|
||||
*
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache.
|
||||
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
|
||||
* /props.
|
||||
*
|
||||
* Separate from server.cpp because none of it touches the step path: no admission, no Sink, no
|
||||
* cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered
|
||||
@@ -8,15 +9,17 @@
|
||||
* streaming lifetime would make that file harder to read for no shared code at all.
|
||||
*
|
||||
* WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
|
||||
* /rerank (an embedding or cross-encoder model, which this engine does not load), /sleep, /wake_up
|
||||
* /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
|
||||
* and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and
|
||||
* /v1/responses (a stateful conversation store, which is a component and not an endpoint). Each
|
||||
* would be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
|
||||
* Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
|
||||
* component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
|
||||
* be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
|
||||
*/
|
||||
#include "server.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -143,8 +146,61 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
auto msgs = b.find("messages");
|
||||
auto prom = b.find("prompt");
|
||||
if (msgs != b.end() && prom != b.end())
|
||||
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"), req.peer);
|
||||
auto cont = b.find("content");
|
||||
if ((msgs != b.end()) + (prom != b.end()) + (cont != b.end()) > 1)
|
||||
return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
|
||||
req.peer);
|
||||
|
||||
/* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
|
||||
* as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
|
||||
* control tokens recognised), answered under its own key, `tokens`, as ids or with
|
||||
* `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
|
||||
* llama-server sends it. */
|
||||
if (cont != b.end()) {
|
||||
const bool add_special = get_bool_or(b, "add_special", false);
|
||||
const bool parse_special = get_bool_or(b, "parse_special", true);
|
||||
const bool with_pieces = get_bool_or(b, "with_pieces", false);
|
||||
auto take = [&](const json& v, bool first) -> bool {
|
||||
if (v.is_string()) {
|
||||
const std::vector<int32_t> t =
|
||||
deps_.tok->encode(v.get<std::string>(), first && add_special, parse_special);
|
||||
toks.insert(toks.end(), t.begin(), t.end());
|
||||
return true;
|
||||
}
|
||||
int32_t id = 0;
|
||||
if (!v.is_number_integer() || !token_id(v, &id)) return false;
|
||||
toks.push_back(id);
|
||||
return true;
|
||||
};
|
||||
bool ok = true;
|
||||
if (cont->is_array()) {
|
||||
bool first = true;
|
||||
for (const json& v : *cont) { ok = ok && take(v, first); first = false; }
|
||||
} else {
|
||||
ok = cont->is_string() && take(*cont, true);
|
||||
}
|
||||
if (!ok)
|
||||
return error_response(err_bad("content", "must be a string, or an array of strings "
|
||||
"and token ids"), req.peer);
|
||||
json arr = json::array();
|
||||
for (int32_t t : toks) {
|
||||
if (!with_pieces) { arr.push_back(t); continue; }
|
||||
const std::string piece = deps_.tok->token_bytes(t);
|
||||
json e;
|
||||
e["id"] = t;
|
||||
/* A piece that is not whole UTF-8 goes as its bytes, 0-255, as llama-server sends it. */
|
||||
if (utf8_valid_prefix(piece) == piece.size()) e["piece"] = piece;
|
||||
else e["piece"] = std::vector<int>((const unsigned char*)piece.data(),
|
||||
(const unsigned char*)piece.data() + piece.size());
|
||||
arr.push_back(std::move(e));
|
||||
}
|
||||
json o;
|
||||
o["tokens"] = std::move(arr);
|
||||
o["count"] = (int64_t)toks.size();
|
||||
o["max_model_len"] = opt_.max_ctx;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
if (msgs != b.end()) {
|
||||
if (!deps_.chat)
|
||||
@@ -227,8 +283,113 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
toks.push_back(id);
|
||||
}
|
||||
|
||||
/* `prompt` is vLLM's key and `content` llama-server's, for the same text. */
|
||||
json o;
|
||||
o["prompt"] = deps_.tok->decode(toks);
|
||||
o["content"] = o["prompt"];
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
/* ================================================================== /props */
|
||||
/* llama-server's /props, for the clients built against it: a front-end that sizes its context
|
||||
* from default_generation_settings.n_ctx, shows an image button when modalities.vision is set,
|
||||
* and reads what a request that sends no sampler fields inherits. /server_info says all of it and
|
||||
* more, but nothing written for llama-server knows to ask there.
|
||||
*
|
||||
* Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
|
||||
* per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
|
||||
* n_ctx means to the clients reading it; left out when the server does not know its length. */
|
||||
HttpResponse Server::handle_props(const HttpRequest&) {
|
||||
const SamplingParams& sp = opt_.default_sampling;
|
||||
/* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
|
||||
* missing. The samplers this server does not run are reported at their off values -- which
|
||||
* is what it serves -- and `samplers` is its own order, temperature first. */
|
||||
const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
|
||||
json params;
|
||||
params["n_predict"] = n_predict;
|
||||
params["max_tokens"] = n_predict;
|
||||
params["seed"] = -1;
|
||||
params["temperature"] = sp.temp;
|
||||
params["dynatemp_range"] = 0.0;
|
||||
params["dynatemp_exponent"] = 1.0;
|
||||
params["top_k"] = sp.top_k;
|
||||
params["top_p"] = sp.top_p;
|
||||
params["min_p"] = sp.min_p;
|
||||
params["top_n_sigma"] = -1.0;
|
||||
params["typical_p"] = sp.typical_p;
|
||||
params["typ_p"] = sp.typical_p;
|
||||
params["xtc_probability"] = sp.xtc_probability;
|
||||
params["xtc_threshold"] = sp.xtc_threshold;
|
||||
params["repeat_last_n"] = sp.penalty_last_n;
|
||||
params["repeat_penalty"] = sp.rep_penalty;
|
||||
params["presence_penalty"] = sp.pres_penalty;
|
||||
params["frequency_penalty"] = sp.freq_penalty;
|
||||
params["dry_multiplier"] = sp.dry_multiplier;
|
||||
params["dry_base"] = sp.dry_base;
|
||||
params["dry_allowed_length"] = sp.dry_allowed_length;
|
||||
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
|
||||
params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
|
||||
? std::vector<std::string>{ "\n", ":", "\"", "*" }
|
||||
: sp.dry_seq_breakers;
|
||||
params["mirostat"] = 0;
|
||||
params["mirostat_tau"] = 5.0;
|
||||
params["mirostat_eta"] = 0.1;
|
||||
params["stop"] = json::array();
|
||||
params["n_keep"] = 0;
|
||||
params["n_discard"] = 0;
|
||||
params["ignore_eos"] = false;
|
||||
params["stream"] = true;
|
||||
params["logit_bias"] = json::array();
|
||||
params["n_probs"] = 0;
|
||||
params["min_keep"] = 0;
|
||||
params["grammar"] = "";
|
||||
params["grammar_lazy"] = false;
|
||||
params["grammar_triggers"] = json::array();
|
||||
params["preserved_tokens"] = json::array();
|
||||
params["chat_format"] = "";
|
||||
params["reasoning_format"] = "auto";
|
||||
params["reasoning_in_content"] = false;
|
||||
params["generation_prompt"] = "";
|
||||
params["samplers"] = { "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p",
|
||||
"xtc" };
|
||||
params["backend_sampling"] = false;
|
||||
params["timings_per_token"] = false;
|
||||
params["post_sampling_probs"] = false;
|
||||
params["lora"] = json::array();
|
||||
|
||||
json gen;
|
||||
if (opt_.max_ctx > 0) gen["n_ctx"] = opt_.max_ctx;
|
||||
gen["params"] = std::move(params);
|
||||
|
||||
json modal;
|
||||
modal["vision"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
modal["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
modal["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
|
||||
json o;
|
||||
o["default_generation_settings"] = std::move(gen);
|
||||
o["total_slots"] = opt_.max_seqs;
|
||||
o["model_alias"] = opt_.model_id;
|
||||
o["model_path"] = opt_.model_path;
|
||||
o["modalities"] = std::move(modal);
|
||||
o["endpoint_slots"] = false;
|
||||
o["endpoint_props"] = false;
|
||||
o["endpoint_metrics"] = true;
|
||||
o["chat_template"] = deps_.chat ? deps_.chat->source() : std::string();
|
||||
o["chat_template_caps"] = json::parse(deps_.chat ? deps_.chat->caps() : std::string("{}"),
|
||||
nullptr, false);
|
||||
std::string bos, eos;
|
||||
if (deps_.tok) {
|
||||
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
|
||||
if (v.bos >= 0) bos = deps_.tok->piece(v.bos);
|
||||
if (v.eos >= 0) eos = deps_.tok->piece(v.eos);
|
||||
}
|
||||
o["bos_token"] = bos;
|
||||
o["eos_token"] = eos;
|
||||
o["build_info"] = "radiance " + opt_.version;
|
||||
o["role"] = "model";
|
||||
o["is_sleeping"] = false;
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
@@ -262,6 +423,30 @@ HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) {
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
/* ================================================================== capabilities */
|
||||
json Server::capabilities() const {
|
||||
json caps;
|
||||
caps["chat"] = deps_.chat != nullptr;
|
||||
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
|
||||
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
|
||||
caps["grammar"] = deps_.grammar != nullptr;
|
||||
caps["embedding"] = deps_.embed != nullptr;
|
||||
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
return caps;
|
||||
}
|
||||
|
||||
/* ================================================================== /server_info */
|
||||
/* vLLM returns the repr() of its config object, which is a Python string a client can only print.
|
||||
* This returns the same information as JSON, in two halves: what the SERVER decided, which is
|
||||
@@ -288,25 +473,7 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
srv["uptime_s"] = unix_now() - started_at_;
|
||||
srv["in_flight"] = in_flight_.load(std::memory_order_relaxed);
|
||||
|
||||
json caps;
|
||||
caps["chat"] = deps_.chat != nullptr;
|
||||
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
|
||||
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
|
||||
caps["grammar"] = deps_.grammar != nullptr;
|
||||
caps["embedding"] = deps_.embed != nullptr;
|
||||
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
json caps = capabilities();
|
||||
|
||||
/* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each
|
||||
* field, so a client can read off exactly what leaving one out means on this deployment. */
|
||||
@@ -367,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
|
||||
|
||||
@@ -59,6 +59,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
json e;
|
||||
e["id"] = s.id;
|
||||
e["model"] = s.model;
|
||||
if (!s.label.empty()) e["label"] = s.label;
|
||||
e["tokens"] = s.n_tokens;
|
||||
e["bytes"] = s.bytes;
|
||||
e["idle_s"] = s.idle_s;
|
||||
@@ -191,6 +192,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["steps"] = m.steps;
|
||||
o["steps_prefill"] = m.steps_prefill;
|
||||
o["steps_mixed"] = m.steps_mixed;
|
||||
o["prefill_chunks_capped"] = m.prefill_chunks_capped;
|
||||
o["steps_decode"] = m.steps_decode;
|
||||
/* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count.
|
||||
* That is the derivation this handler's header calls the page's job, and it is the one
|
||||
@@ -311,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);
|
||||
}
|
||||
|
||||
@@ -681,6 +684,7 @@ th + th, td + td { padding-left:14px; }
|
||||
/* Fixed, so the tier column starts at one x in both tables. */
|
||||
.stbl .ret { width:340px; }
|
||||
.sid { font-weight:500; }
|
||||
.slabel { margin-left:8px; color:var(--faint); }
|
||||
.mv { font:500 10px/1 var(--ui); color:var(--faint); border:1px solid var(--rule);
|
||||
border-radius:4px; padding:2px 5px; margin-left:6px; }
|
||||
/* WHERE IT IS, by share of the conversation's context, one colour a tier. A conversation is
|
||||
@@ -2850,6 +2854,8 @@ function sessRow(r, hybrid, manyModels) {
|
||||
const tr = el("tr");
|
||||
const id = tr.appendChild(el("td"));
|
||||
id.appendChild(el("span", "sid", "#" + r.id));
|
||||
/* The client's own name for the conversation (`session_id`), when it sent one. */
|
||||
if (r.label) id.appendChild(el("span", "slabel", r.label));
|
||||
if (r.moving) id.appendChild(el("span", "mv", "moving"));
|
||||
if (manyModels) tr.appendChild(el("td", "l", r.model || DASH));
|
||||
tr.appendChild(el("td", null, cnt3(r.tokens) + " tok"));
|
||||
|
||||
+56
-8
@@ -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); };
|
||||
@@ -363,10 +385,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
* leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the
|
||||
* chat template. This does not. */
|
||||
const std::string& p = hreq.path;
|
||||
if (!api_key.empty() && p != "/health" && p != "/ping" && p != "/" && p != "/dashboard") {
|
||||
std::string got = hreq.get_header_value("Authorization");
|
||||
const std::string want = "Bearer " + api_key;
|
||||
if (got != want) {
|
||||
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
|
||||
p != "/dashboard") {
|
||||
/* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
|
||||
* llama-server takes as well; either one carrying the key is enough. */
|
||||
const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
|
||||
hreq.get_header_value("X-Api-Key") == api_key;
|
||||
if (!ok) {
|
||||
/* Said like every other refusal (Server::error_response), which this one never
|
||||
* reaches: the gate answers before the router does. */
|
||||
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
|
||||
@@ -453,15 +478,38 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
bridge(q, std::move(body), s);
|
||||
});
|
||||
}
|
||||
svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) {
|
||||
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
|
||||
* the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
|
||||
* that does not list one fails the request before it is sent. A wildcard would not do: CORS
|
||||
* never lets `*` stand for Authorization, so the requested list is echoed back. */
|
||||
svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (cors) {
|
||||
const std::string asked = req.get_header_value("Access-Control-Request-Headers");
|
||||
res.set_header("Access-Control-Allow-Origin", "*");
|
||||
res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
res.set_header("Access-Control-Allow-Headers",
|
||||
asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
|
||||
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
res.set_header("Access-Control-Max-Age", "86400");
|
||||
}
|
||||
res.status = 204;
|
||||
});
|
||||
|
||||
/* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
|
||||
* other refusal this server makes is an error object, and a client reading one finds an
|
||||
* empty 404 unparseable; so an error with no body gets one here. A response that already
|
||||
* carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
|
||||
svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
|
||||
if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
|
||||
if (cors) res.set_header("Access-Control-Allow-Origin", "*");
|
||||
const std::string type = res.status == 404 ? "not_found_error"
|
||||
: res.status >= 500 ? "internal_server_error"
|
||||
: "invalid_request_error";
|
||||
const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
|
||||
: httplib::status_message(res.status);
|
||||
res.set_content(error_body(type.c_str(), what), "application/json");
|
||||
return httplib::Server::HandlerResponse::Handled;
|
||||
});
|
||||
|
||||
/* Bound once: asking for a named port and then for any port would leave the first socket
|
||||
* bound and unused. */
|
||||
const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
|
||||
|
||||
@@ -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();
|
||||
|
||||
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user