From dc339b4cd239f7124700dd1f52213f73e8939a14 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Mon, 12 Oct 2026 11:46:14 +0200 Subject: [PATCH] radiance 1.4.0 - Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against 1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20% - deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM (4096-token prefill steps, 4 sequences, a 301K-token cache) - #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the requests decoding beside it and to new arrivals, instead of taking all of it (baKon) - LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50) - a startup report: every option with its value and where it came from, the hardware, and what on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only to the same machine) - #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at once (exit status 70), instead of hanging or writing a core of tens of gigabytes - #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of crashing at the first launch - the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's libLLVM rebuilt so the same source compiles to the same kernels every time; a source build takes ROCm 10.1 or 7.2 - #71: the image ships curl, jq and a CA bundle, so --model works in the container, and hfget.sh runs under its busybox (baKon) - --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an integrated GPU instead of stopping --- CMakeLists.txt | 8 +- Dockerfile | 123 ++- NOTICE | 12 +- README.md | 12 +- abi/rad_abi.h | 23 +- abi/rad_format.h | 7 +- abi/rad_runtime.h | 36 + arch/common/rad_block_attn_gated_fp8.h | 19 + arch/common/rad_block_mlp_fp8.h | 2 + arch/common/rad_block_moe_fp8.h | 50 +- arch/common/rad_block_mtp_fp8.h | 71 +- arch/common/rad_block_mtp_hc.h | 80 +- arch/common/rad_qsa.h | 79 +- arch/lfm2_bf16/CMakeLists.txt | 10 + arch/lfm2_bf16/lfm2_bf16.cpp | 489 +++++++++ arch/lfm2_bf16/siglip2.h | 329 ++++++ arch/qwen35_fp8/qwen35_fp8.cpp | 4 + arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 3 + cmake/RadAddPlugin.cmake | 22 + core/CMakeLists.txt | 15 +- core/build/startup.cpp | 16 +- core/config.cpp | 197 +++- core/device/aql.cpp | 976 +++++++++++++++++- core/device/device.h | 108 ++ core/device/dispatch.cpp | 88 +- core/device/hip.cpp | 28 +- core/device/host.cpp | 14 + core/diag/checks.cpp | 446 ++++++++ core/diag/diag.h | 216 ++++ core/diag/report.cpp | 296 ++++++ core/diag/sysinfo.cpp | 473 +++++++++ core/engine.cpp | 199 +++- core/engine.h | 66 ++ core/engine_bringup.cpp | 159 ++- core/engine_diag.cpp | 160 +++ core/engine_mm.cpp | 28 +- core/engine_priv.h | 6 + core/format/checkpoint.cpp | 6 +- core/gen_config.cpp | 23 + core/gen_config.h | 11 + core/main.cpp | 16 +- core/mem/vram_budget.cpp | 11 +- core/mem/vram_budget.h | 4 + core/mm/item.cpp | 12 +- core/mm/processor.cpp | 313 +++++- core/mm/processor.h | 77 +- core/place/heat.cpp | 32 +- core/place/heat.h | 81 +- core/place/mover.cpp | 438 ++++++-- core/place/mover.h | 133 ++- core/place/planner.cpp | 11 + core/place/planner.h | 38 +- core/place/stager.cpp | 294 ++++-- core/place/stager.h | 178 +++- core/plugin/loader.cpp | 4 + core/rad_core.h | 35 + core/runtime/ctx.cpp | 91 +- core/runtime/ctx.h | 63 +- core/runtime/issue.cpp | 48 +- core/runtime/stager.h | 8 +- core/runtime/xp_state.h | 82 ++ core/runtime/xprefetch.cpp | 439 ++++++++ core/runtime/xprefetch.h | 93 ++ core/runtime/xprefetch.hip | 314 ++++++ core/sample/sampler.h | 1 + core/sched/batch.cpp | 22 +- core/sched/scheduler.cpp | 41 +- core/sched/scheduler.h | 10 +- core/server/LICENSE.lfm | 71 ++ core/server/adapters.h | 3 +- core/server/admin.cpp | 26 + core/server/dashboard.cpp | 1 + core/server/http.cpp | 26 +- core/server/http.h | 8 + core/server/iface.h | 3 + core/server/liveview.h | 4 +- core/server/oai.cpp | 10 +- core/server/oai.h | 8 + core/server/server.cpp | 155 +++ core/server/server.h | 14 + core/server/systemone.cpp | 404 ++++++++ core/server/systemone.h | 59 ++ core/text/tokenizer.cpp | 19 +- core/text/tokenizer.h | 1 + core/text/tokenizer_json.cpp | 14 +- deploy/compose/common.yaml | 2 +- deploy/compose/flashnext-tp1.yaml | 24 + docker/licenses.sh | 4 +- docker/llvm-check.sh | 61 ++ docker/llvm-vopd-pairing.patch | 23 + docs/DOCKER.md | 22 +- docs/GUIDE.md | 159 ++- docs/OPS.md | 18 + docs/PLUGIN.md | 3 +- docs/TOOLS.md | 15 +- libavx/avx_cases.cpp | 5 + libavx/avx_check.cpp | 25 + libavx/avx_isa.h | 2 +- libavx/avx_misc.cpp | 39 +- libavx/avx_norm.cpp | 64 ++ libavx/avx_registry.cpp | 14 + libr4d/r4d.h | 16 +- libr4d/r4d_ar_entry.hip | 45 +- libr4d/r4d_ar_oneshot_2rank_exact.hip | 20 +- libr4d/r4d_ar_oneshot_2rank_wht6.hip | 11 +- libr4d/r4d_ar_seq.h | 34 +- libr4d/r4d_attn_decode_h256_gqa6.hip | 43 +- libr4d/r4d_attn_paged_gqa8.hip | 42 +- libr4d/r4d_attn_paged_h128_gqa4.hip | 6 +- libr4d/r4d_attn_paged_h256_gqa4.hip | 3 + libr4d/r4d_attn_paged_h256_gqa6.hip | 9 +- libr4d/r4d_common.h | 66 ++ libr4d/r4d_dflash_select_bf16.hip | 51 +- libr4d/r4d_fp8_wmma.h | 5 + ...urrent_update_k128_v128_bf16_fp32state.hip | 25 +- libr4d/r4d_gemm_bf16_nt_tiled.hip | 21 +- libr4d/r4d_gemm_fp8a16_nt_m1.hip | 169 ++- libr4d/r4d_gemm_fp8a8.hip | 140 ++- libr4d/r4d_gemm_mxfp4a8_decode.hip | 32 +- libr4d/r4d_gemm_mxfp4a8_tiled.hip | 12 +- libr4d/r4d_hc_bf16.hip | 229 ++-- libr4d/r4d_model_bf16.hip | 28 +- libr4d/r4d_moe.hip | 227 ++-- libr4d/r4d_ple_conv_bf16.hip | 83 +- libr4d/r4d_plugin.h | 6 + libr4d/r4d_qk_norm_rope_gate.hip | 44 +- libr4d/r4d_qsa_score_bf16.hip | 6 +- libr4d/r4d_rows.cpp | 94 ++ libr4d/r4d_selftest.cpp | 129 ++- libr4d/r4d_vit_bf16.hip | 99 +- libref/ref_elementwise.cpp | 65 ++ libref/ref_ops.h | 4 + libref/ref_ple.cpp | 42 +- libref/ref_registry.cpp | 27 + libref/ref_shapes.cpp | 30 + scripts/cardclock.py | 18 +- tests/CMakeLists.txt | 18 +- tests/arch_test.cpp | 353 +++++++ tests/device_test.cpp | 209 ++++ tests/diag_test.cpp | 710 +++++++++++++ tests/lfm2_golden.h | 97 ++ tests/mklfm2golden.py | 107 ++ tests/mm_test.cpp | 111 +- tests/place_test.cpp | 621 ++++++++++- tests/ref_test.cpp | 106 ++ tests/runtime_test.cpp | 7 + tests/sched_test.cpp | 67 ++ tests/server_test.cpp | 35 + tests/systemone_test.cpp | 310 ++++++ tests/text_test.cpp | 2 + tests/tokenizer_test.cpp | 53 + tools/rad_kbench.cpp | 217 +++- tools/tokref.cpp | 14 +- 153 files changed, 12956 insertions(+), 1067 deletions(-) create mode 100644 arch/lfm2_bf16/CMakeLists.txt create mode 100644 arch/lfm2_bf16/lfm2_bf16.cpp create mode 100644 arch/lfm2_bf16/siglip2.h create mode 100644 core/diag/checks.cpp create mode 100644 core/diag/diag.h create mode 100644 core/diag/report.cpp create mode 100644 core/diag/sysinfo.cpp create mode 100644 core/engine_diag.cpp create mode 100644 core/runtime/xp_state.h create mode 100644 core/runtime/xprefetch.cpp create mode 100644 core/runtime/xprefetch.h create mode 100644 core/runtime/xprefetch.hip create mode 100644 core/server/LICENSE.lfm create mode 100644 core/server/systemone.cpp create mode 100644 core/server/systemone.h create mode 100644 deploy/compose/flashnext-tp1.yaml create mode 100755 docker/llvm-check.sh create mode 100644 docker/llvm-vopd-pairing.patch create mode 100644 tests/diag_test.cpp create mode 100644 tests/lfm2_golden.h create mode 100644 tests/mklfm2golden.py create mode 100644 tests/systemone_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d4b60dd..5906cc04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.3.0 LANGUAGES C CXX) +project(radiance VERSION 1.4.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -22,6 +22,10 @@ set(RAD_WITH_FFMPEG "AUTO" CACHE STRING "ON | OFF | AUTO -- decode image, video set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO) option(RAD_BUILD_TESTS "Build the test suite" ON) option(RAD_ASAN "Build with AddressSanitizer" OFF) +# Whether the HIP compiler's VOPD pairing is repeatable. LLVM 24's is not unless it carries the +# fix the image builds (docker/llvm-vopd-pairing.patch); without this the build turns pairing off +# on LLVM 24, see rad_hip_repeatable in cmake/RadAddPlugin.cmake. +option(RAD_HIP_VOPD_REPEATABLE "The HIP compiler's VOPD pairing is repeatable (the image's LLVM 24 is)" OFF) # ---------------------------------------------------------------- HIP detection @@ -455,3 +459,5 @@ install(FILES vendor/nlohmann/LICENSE.MIT DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME nlohmann-json.LICENSE) install(FILES vendor/cpp-httplib/LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME cpp-httplib.LICENSE) +install(FILES core/server/LICENSE.lfm + DESTINATION ${CMAKE_INSTALL_DOCDIR}/third_party RENAME liquidai-d1.LICENSE) diff --git a/Dockerfile b/Dockerfile index 99759451..33ab2b78 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,8 +13,14 @@ # ffmpeg FFmpeg built with only the demuxers core/mm/media.cpp admits and the decoders their # streams need (pictures, video, and audio with swresample); the distribution's build # brings ~200 packages of encoders, filters and display libraries the engine never calls -# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage -# test `ctest -LE gpu` on that build -- everything that does not need a card +# llvm ROCm's libLLVM rebuilt from ROCm's own llvm-project at the commit the image's clang +# reports, with docker/llvm-vopd-pairing.patch -- the fix that makes LLVM 24's device +# code repeatable from build to build (cmake/RadAddPlugin.cmake, rad_hip_repeatable) +# build ROCm dev image + cmake/ninja/g++-14; configures, builds, installs to /stage, every +# device source compiled by ROCm's clang from a shadow of the ROCm tree whose libLLVM +# is the llvm stage's +# test docker/llvm-check.sh, then `ctest -LE gpu` on that build -- everything that does not +# need a card # rootfs the install tree stripped, and every library its binaries and plugins load, resolved # by ldd, copied into one directory and checked from inside a chroot # runtime FROM scratch + rootfs. This is the image that ships @@ -31,9 +37,10 @@ # docker run ... -v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance # # The ROCm userspace in the image must be one the host's amdgpu kernel driver supports. It is -# pinned to the version the serving host runs; move both together. +# pinned to the version the serving host runs; move both together. From ROCm 10 on, the dev image +# is published only as the -full tag. -ARG ROCM_VERSION=7.2.4 +ARG ROCM_VERSION=10.1.0-full ARG UBUNTU_VERSION=24.04 ARG FFMPEG_VERSION=8.1.3 ARG FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3 @@ -73,6 +80,52 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ && echo "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}" \ > /opt/ffmpeg/share/doc/ffmpeg/SOURCE +# ------------------------------------------------------------------------------------------- llvm +FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS llvm +ARG JOBS= +# THE ONE LIBRARY OF THE HIP COMPILER THAT CHANGES. clang, lld and the offload tools all load +# lib/llvm/lib/libLLVM.so, so this stage rebuilds that file and nothing else: the source is ROCm's +# llvm-project at exactly the commit `clang --version` names (a different commit refuses, as does +# a patch that no longer applies), configured as ROCm's lib/cmake/llvm/LLVMConfig.cmake says it +# was -- Release without assertions, AMDGPU;SPIRV;X86, every component in the dylib, no RTTI or +# exceptions, zlib and zstd from rocm_sysdeps -- and compiled by ROCm's own clang and lld. With +# VOPD pairing off it produces ROCm's code byte for byte; docker/llvm-check.sh holds the build +# stage to that. A sparse, depth-one fetch: llvm/, the cmake/, libc/ and third-party/ directories +# its configure reads, and none of its tests or documentation. +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + git cmake ninja-build ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY docker/llvm-vopd-pairing.patch /tmp/ +RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ + set -e; L=/opt/rocm/lib/llvm; S=/opt/rocm/lib/rocm_sysdeps; \ + rev=$($L/bin/clang --version | sed -n 's|.*ROCm/llvm-project.git \([0-9a-f]\{40\}\).*|\1|p'); \ + [ -n "$rev" ] || { echo "llvm: no ROCm/llvm-project commit in: $($L/bin/clang --version | head -1)" >&2; exit 1; }; \ + git init -q /llvm-project; cd /llvm-project; \ + git remote add origin https://github.com/ROCm/llvm-project.git; \ + git sparse-checkout set --no-cone '/*' '!/*/' /cmake/ /libc/ /llvm/ /third-party/ \ + '!/llvm/test/' '!/llvm/unittests/' '!/llvm/docs/' '!/llvm/benchmarks/'; \ + git fetch -q --depth 1 --filter=blob:none origin "$rev"; \ + git checkout -q FETCH_HEAD; \ + git apply /tmp/llvm-vopd-pairing.patch; \ + cmake -G Ninja -S llvm -B /build-llvm -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=OFF \ + -DLLVM_TARGETS_TO_BUILD="AMDGPU;SPIRV;X86" -DLLVM_BUILD_LLVM_DYLIB=ON -DLLVM_LINK_LLVM_DYLIB=ON \ + -DLLVM_DYLIB_COMPONENTS=all -DLLVM_ENABLE_RTTI=OFF -DLLVM_ENABLE_EH=OFF -DLLVM_ENABLE_FFI=OFF \ + -DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_CURL=OFF \ + -DLLVM_ENABLE_HTTPLIB=OFF -DLLVM_ENABLE_TELEMETRY=ON -DLLVM_ENABLE_PLUGINS=ON \ + -DLLVM_ENABLE_LIBPFM=OFF \ + -DLLVM_ENABLE_ZLIB=FORCE_ON -DZLIB_INCLUDE_DIR=$S/include -DZLIB_LIBRARY=$S/lib/librocm_sysdeps_z.so.1 \ + -DLLVM_ENABLE_ZSTD=FORCE_ON -Dzstd_INCLUDE_DIR=$S/include -Dzstd_LIBRARY=$S/lib/librocm_sysdeps_zstd.so.1 \ + -DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF \ + -DLLVM_INCLUDE_DOCS=OFF -DLLVM_BUILD_TOOLS=OFF -DLLVM_USE_LINKER=lld -DLLVM_PARALLEL_LINK_JOBS=2 \ + -DCMAKE_C_COMPILER=$L/bin/clang -DCMAKE_CXX_COMPILER=$L/bin/clang++ > /tmp/llvm-configure.log 2>&1 \ + || { tail -40 /tmp/llvm-configure.log >&2; exit 1; }; \ + ninja -C /build-llvm ${JOBS:+-j${JOBS}} LLVM > /tmp/llvm-build.log 2>&1 \ + || { grep -m20 -B2 -A8 'error' /tmp/llvm-build.log >&2; exit 1; }; \ + so=$(basename $(readlink -f $L/lib/libLLVM.so)); \ + mkdir -p /out; cp /build-llvm/lib/$so /out/; \ + rm -rf /build-llvm /llvm-project + # ------------------------------------------------------------------------------------------ build FROM rocm/dev-ubuntu-${UBUNTU_VERSION}:${ROCM_VERSION} AS build ARG GPU_TARGETS=gfx1201 @@ -91,11 +144,41 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg -RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf && ldconfig +# ROCm's library directory is registered with the loader beside FFmpeg's because the ROCm 10 images +# register none, and the rootfs stage resolves every library the installed binaries load with ldd. +RUN echo /opt/ffmpeg/lib > /etc/ld.so.conf.d/ffmpeg.conf \ + && echo /opt/rocm/lib > /etc/ld.so.conf.d/rocm.conf && ldconfig ENV ROCM_PATH=/opt/rocm HIP_PATH=/opt/rocm CC=gcc-14 CXX=g++-14 \ PKG_CONFIG_PATH=/opt/ffmpeg/lib/pkgconfig +# THE HIP COMPILER: ROCm's clang, loading the llvm stage's libLLVM. ROCm's tools find their +# libraries through RPATHs relative to themselves -- $ORIGIN/../lib for libLLVM, which +# LD_LIBRARY_PATH cannot override, and $ORIGIN/../../rocm_sysdeps/lib and $ORIGIN/../../../lib, +# which leave lib/llvm -- so the compiler lives in a shadow of the whole ROCm tree at the same +# depth: /opt/rocm-repeatable, every entry a link back into /opt/rocm except lib/llvm/bin, which +# holds real copies of the executables, and lib/llvm/lib's libLLVM, which is the rebuilt one. +# Only compiling uses it. The build names /opt/rocm with --rocm-path, so the headers and device +# libraries are ROCm's and the runtime path clang records in a linked plugin is /opt/rocm/lib; +# without it clang takes the tree it sits in as ROCm, and a loader that follows that path from +# the HIP runtime to comgr reaches the rebuilt libLLVM, which lacks the libstdc++ symbols ROCm's +# GCC-built one re-exports for comgr. The rootfs stage refuses any library resolved through it. +COPY --from=llvm /out/ /tmp/llvm-out/ +RUN set -e; R=/opt/rocm; D=/opt/rocm-repeatable; L=lib/llvm; \ + so=$(basename $(readlink -f $R/$L/lib/libLLVM.so)); \ + [ -f /tmp/llvm-out/$so ] || { echo "the llvm stage built no $so" >&2; exit 1; }; \ + mkdir -p $D/$L/lib; \ + for e in $R/*; do n=${e##*/}; [ $n = lib ] || ln -s $e $D/$n; done; \ + for e in $R/lib/*; do n=${e##*/}; [ $n = llvm ] || ln -s $e $D/lib/$n; done; \ + for e in $R/$L/*; do n=${e##*/}; [ $n = bin ] || [ $n = lib ] || ln -s $e $D/$L/$n; done; \ + cp -a $R/$L/bin $D/$L/; \ + for e in $R/$L/lib/*; do n=${e##*/}; \ + if [ $n = $so ]; then mv /tmp/llvm-out/$so $D/$L/lib/; \ + elif [ -L $e ] && [ "$(readlink $e)" = $so ]; then ln -s $so $D/$L/lib/$n; \ + else ln -s $e $D/$L/lib/$n; fi; \ + done; \ + rm -rf /tmp/llvm-out + WORKDIR /src COPY . . @@ -108,6 +191,9 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ -DCMAKE_INSTALL_PREFIX=/opt/radiance \ -DRAD_WITH_HIP=ON -DRAD_WITH_FFMPEG=ON \ "-DRAD_GPU_TARGETS=${GPU_TARGETS}" \ + -DCMAKE_HIP_COMPILER=/opt/rocm-repeatable/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=/opt/rocm \ + -DCMAKE_HIP_FLAGS=--rocm-path=/opt/rocm \ + -DRAD_HIP_VOPD_REPEATABLE=ON \ && cmake --build /build ${JOBS:+-j${JOBS}} \ && DESTDIR=/stage cmake --install /build \ && mkdir -p /stage/opt/radiance/share/radiance/recipes \ @@ -126,7 +212,8 @@ FROM build AS test # rebuilt against the installed package, libr4d included -- is the development tree's to run # (tests/oot_plugins.sh): it re-does this stage's whole compile. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ - ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \ + bash /src/docker/llvm-check.sh /build \ + && ctest --test-dir /build -LE 'gpu|oot' --output-on-failure \ && touch /build/host-tests-passed # ----------------------------------------------------------------------------------------- rootfs @@ -142,32 +229,32 @@ RUN apt-get update \ COPY --from=test /build/host-tests-passed /rootfs/opt/radiance/share/radiance/.host-tests-passed # Every library the binaries and plugins load, plus comgr, which the HIP runtime opens at run time # and cannot initialise a device without, goes into one directory the dynamic loader searches by -# default: no ld.so.cache, no LD_LIBRARY_PATH. libdrm_amdgpu names the card from amdgpu.ids. A -# static busybox provides the health check's wget and a shell for `docker exec`; curl, jq and the -# CA bundle are hfget.sh's, and the bundle is ca-certificates' Mozilla set, which is the directory -# named for it in the license list. docker/licenses.sh -# traces each of those files to its package and records its license and source in -# /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing can -# depend on a library the image lacks. +# default: no ld.so.cache, no LD_LIBRARY_PATH. ROCm's own libdrm_amdgpu carries the card name table +# compiled in, so no amdgpu.ids is copied. A static busybox provides the health check's wget and a +# shell for `docker exec`; curl, jq and the CA bundle are hfget.sh's, and the bundle is +# ca-certificates' Mozilla set, which is the directory named for it in the license list. +# docker/licenses.sh traces each of those files to its package and records its license and source +# in /usr/share/doc/THIRD-PARTY. Then every ELF file is resolved from inside the tree, so nothing +# can depend on a library the image lacks. RUN set -e; R=/rootfs; L=$R/usr/lib/x86_64-linux-gnu; \ - mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/usr/share/libdrm $R/etc/ssl/certs $R/data $R/tmp; \ + mkdir -p $L $R/lib64 $R/usr/bin $R/bin $R/etc/ssl/certs $R/data $R/tmp; \ chmod 1777 $R/tmp; \ cp -a /stage/opt/radiance $R/opt/; \ elves=$(find $R/opt/radiance -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print); \ strip --strip-unneeded $elves; \ libs=$(for f in $elves /usr/bin/curl /usr/bin/jq /opt/rocm/lib/libamd_comgr.so.3; do ldd "$f"; done \ | awk '/=> \//{print $3} /^\t\/lib64\//{print $1}' | sort -u); \ + if echo "$libs" | grep /opt/rocm-repeatable/; then \ + echo "these resolve through the compiler's shadow ROCm tree, not /opt/rocm" >&2; exit 1; fi; \ for lib in $libs; do \ case "$lib" in */ld-linux-x86-64.so.2) cp -L "$lib" $R/lib64/ ;; *) cp -L "$lib" $L/ ;; esac; \ done; \ cp -L /opt/rocm/lib/libamd_comgr.so.3 $L/; \ - cp /usr/share/libdrm/amdgpu.ids $R/usr/share/libdrm/; \ cp /bin/busybox $R/usr/bin/busybox; ln -s /usr/bin/busybox $R/bin/sh; \ cp /usr/bin/curl /usr/bin/jq $R/usr/bin/; \ cp /etc/ssl/certs/ca-certificates.crt $R/etc/ssl/certs/; \ - sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 \ - /usr/share/libdrm/amdgpu.ids /bin/busybox /usr/bin/curl /usr/bin/jq \ - /usr/share/ca-certificates/mozilla; \ + sh /src/docker/licenses.sh $R $libs /opt/rocm/lib/libamd_comgr.so.3 /bin/busybox \ + /usr/bin/curl /usr/bin/jq /usr/share/ca-certificates/mozilla; \ for f in $(cd $R && find opt/radiance usr/lib -type f -exec sh -c 'head -c4 "$1" | grep -q ELF' _ {} \; -print) \ usr/bin/curl usr/bin/jq; do \ out=$(chroot $R /lib64/ld-linux-x86-64.so.2 --list "/$f" 2>&1) || { echo "$f: $out" >&2; exit 1; }; \ diff --git a/NOTICE b/NOTICE index 50a4c8b1..d81cbbbe 100644 --- a/NOTICE +++ b/NOTICE @@ -14,8 +14,10 @@ sorted operand's decode kernel), mechkbfan (the token embedding in the pinned ho parallelism, serving any world size from the shipped container, the request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of -the three-rank lossy-wire crash, and cardclock.py), hazyumps (static YaRN for the Qwen rotary -paths) and redxherring (--model taking a Hugging Face repo id). +the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle +in the image with hfget.sh under its busybox), hazyumps (static YaRN for the Qwen rotary paths), +redxherring (--model taking a Hugging Face repo id) and zivius (LiquidAI's LFM2 and LFM2-VL and +d1's /v1/systemone, after the design of their Codeberg PR 50). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. @@ -26,3 +28,9 @@ license text is in the file named beside each. libquant/lq_ggml_* nlohmann/json Copyright (c) 2013-2025 Niels Lohmann vendor/nlohmann/LICENSE.MIT cpp-httplib Copyright (c) 2017 yhirose vendor/cpp-httplib/LICENSE + +core/server/systemone.cpp carries text from Liquid AI's d1 (prompt.py and api.py in the +LiquidAI/d1-3B repository): the prompt it renders, its question blocks, the option codes and their +fallback codebook and the answer spellings, unchanged, in code rewritten in C++. That text is Liquid +AI, Inc.'s, under the LFM Open License v1.0, whose terms -- including its limit on commercial use -- +apply to it; the license is in core/server/LICENSE.lfm. diff --git a/README.md b/README.md index 99d3a69f..8ef6b27a 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,8 @@ curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/ ## Run with Docker -The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The +The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The +card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from one of them: @@ -62,7 +63,8 @@ in the clone (it needs `docker buildx` and tests the build as it goes). Then set ## Build from source You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need -ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it: +ROCm 10.1 or 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and +build in it: ```sh git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance @@ -72,6 +74,12 @@ cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards thi cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/radiance/ ``` +With ROCm 10.1 the build turns the compiler's VOPD pairing (dual-issue instruction pairs) off: its +LLVM 24 pairs in an order that follows heap addresses, so two builds of the same source can differ. +The Docker image builds its compiler with the fix and keeps the pairing, which is 1-3% faster on +the fp8 prefill GEMMs; a compiler that has the same fix is declared with +`-DRAD_HIP_VOPD_REPEATABLE=ON`. ROCm 7.2 is unaffected. + ## Run without Docker ```sh diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 44f87947..fd37c252 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -95,7 +95,8 @@ typedef int (*RadInitFn) (const RadParam* p, int n_p, int rank, int world_ typedef void (*RadFiniFn) (void* instance); /* The launch. Must not allocate and must not synchronise. Returns RAD_OK or negative; a negative - * return aborts the step and fails the requests in it, naming the kernel and the geometry. */ + * return aborts the step and fails the requests in it, naming the kernel and the geometry. A launch + * handed `link_gate` may return RAD_LINK_ENDED instead of RAD_OK (rad_kernel_collective). */ typedef int (*RadLaunchFn) (const RadArgs* a, RadStream stream); /* ================================================================== the described launch */ @@ -597,6 +598,26 @@ typedef void (*RadPluginCloseFn)(void); * before it, which is always correct. The symbol name is `rad_kernel_concurrent`. */ typedef int (*RadKernelConcurrentFn)(int i); +/* Optional, and a promise about kernel `i` of rad_kernel_at: nonzero means it is a COLLECTIVE -- + * its launches exchange data with the other ranks' cards, so the interconnect carries their bytes + * for as long as they run and the step waits on it. The engine then keeps its own bulk traffic on + * the same links (weights it streams onto the card while the card computes) out of their way for + * that time. A plugin that does not export the symbol, or answers 0, has only the conventional + * `all_reduce` op treated as one. The symbol name is `rad_kernel_collective`. + * + * 2 promises more: every launch of the kernel ends that time itself, as soon as the last byte the + * other ranks send this card for it has landed -- a kernel that reduces after the exchange has the + * link to spare for the rest of its run. The engine then hands each launch it holds the link for + * the parameter `link_gate`, the address of a 64-bit word in memory the kernel reaches at system + * scope; a launch without it holds nothing and has nothing to end. The kernel reads the word on + * the device as it starts -- not the host in the launch call, where the hold has not taken effect + * yet -- and, once those bytes have landed, takes one off it with a system-scope atomic if it was + * odd; an even word it leaves alone. A launch that did so returns RAD_LINK_ENDED; any other + * success is RAD_OK, and the engine then ends the hold behind the launch, so a path that does not + * know the word is always safe. */ +typedef int (*RadKernelCollectiveFn)(int i); +#define RAD_LINK_ENDED 1 + /* Optional: nonzero declares this kernel library a REFERENCE implementation -- written to be * plainly correct rather than fast. Three things follow, for any library that says so and for no * other, whatever it is called: diff --git a/abi/rad_format.h b/abi/rad_format.h index 73a200f2..0d7ab0be 100644 --- a/abi/rad_format.h +++ b/abi/rad_format.h @@ -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 }; diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 5892f88e..b168cb98 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -376,6 +376,42 @@ int rad_route_report(RadCtx* c, int layer, const RadRouting* r); * `n_expert` -- the router then writes its own buffer and reports that. */ int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert); +/* THE NEXT-LAYER EXPERT PREFETCH, at decode. A routed layer names the next routed layer at its router + * input; the core applies that layer's router to this layer's input rows, takes the experts the next + * layer is likeliest to route that sit in the pinned host pool, and copies them onto the card while + * the rest of this layer runs. Just before the next layer's routed GEMMs it points their weight-table + * entries at the copies, where the copies have landed and the entries still name the pool slots they + * were made from. It changes no result: a copy holds the bytes of its slot. It is on where the + * placement keeps experts in a pinned pool and the device backend can spare a DMA engine for it, and + * a pass of more than 16 rows makes no prediction; the three calls are no-ops otherwise. + * + * `parts` names, for each of the next layer's experts, the weights its unit is made of (at most four, + * e.g. the gate-up matrix and its scales and the down matrix and its scales), as the routed GEMMs + * read them through weight tables; 0 where an expert has fewer or none. An expert is prefetched only + * where each of its weights is in exactly one table and all of them sit in one pool slot. The arrays + * must outlive the context; the core reads the routing counts only to rank and count, never to choose + * an expert's bytes. `layer` is the next layer's index as rad_route_report and + * rad_expert_prefetch_step name it; `router` is its router, [n_expert, n_embd] bf16. */ +typedef struct RadPrefetchNext { + int layer; + rad_weight router; + int64_t n_expert, top_k; + int64_t n_parts; + const rad_weight* parts; /* [n_expert * n_parts] */ + const int32_t* count_at; /* [n_expert]: where the expert's count is in the layer's routing + counts (rad_route_counts), -1 for nowhere; null when at its index */ +} RadPrefetchNext; + +/* At this layer's router input: `h` rows [r0, r0 + rows) of n_embd bf16, read in place on another + * stream -- the block must not overwrite them before this layer's routed GEMMs. */ +int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, int64_t rows, + int64_t n_embd); +/* After this layer's routed down GEMM: the copies cross the link from here, under the next layer's + * attention rather than under this layer's own streamed experts. */ +int rad_expert_prefetch_mark(RadCtx* c); +/* Ahead of `layer`'s routed GEMMs, on every routed layer of every pass. */ +int rad_expert_prefetch_step(RadCtx* c, int layer); + /* A weight's pointer, for the rare op that genuinely needs one (a plugin-private kernel invoked * outside the op vocabulary). Waits on the mover. Using this forfeits nothing except the ability * to move that weight while the pointer is live, so it is legal only within one issue. */ diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h index 411e85d8..6de75cf8 100644 --- a/arch/common/rad_block_attn_gated_fp8.h +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -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; diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index d0831af8..af2a2b35 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -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; }; diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 51b7c285..1d1efa1e 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -387,6 +387,16 @@ struct MoeFP8 { * `pff`, and down into the same `edn` rows the quantised down left zero. */ std::vector 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 xp_parts; + std::vector 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); diff --git a/arch/common/rad_block_mtp_fp8.h b/arch/common/rad_block_mtp_fp8.h index dac7f122..9a9f739b 100644 --- a/arch/common/rad_block_mtp_fp8.h +++ b/arch/common/rad_block_mtp_fp8.h @@ -288,6 +288,24 @@ inline int MtpBlockFP8::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::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::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. */ diff --git a/arch/common/rad_block_mtp_hc.h b/arch/common/rad_block_mtp_hc.h index ef87de7c..11ea0019 100644 --- a/arch/common/rad_block_mtp_hc.h +++ b/arch/common/rad_block_mtp_hc.h @@ -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 diff --git a/arch/common/rad_qsa.h b/arch/common/rad_qsa.h index 62b406c5..cb95ded6 100644 --- a/arch/common/rad_qsa.h +++ b/arch/common/rad_qsa.h @@ -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 diff --git a/arch/lfm2_bf16/CMakeLists.txt b/arch/lfm2_bf16/CMakeLists.txt new file mode 100644 index 00000000..119b72a4 --- /dev/null +++ b/arch/lfm2_bf16/CMakeLists.txt @@ -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=`). +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) diff --git a/arch/lfm2_bf16/lfm2_bf16.cpp b/arch/lfm2_bf16/lfm2_bf16.cpp new file mode 100644 index 00000000..51717ba8 --- /dev/null +++ b/arch/lfm2_bf16/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 +#include +#include + +#include "siglip2.h" + +#include +#include +#include + +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 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* 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 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 diff --git a/arch/lfm2_bf16/siglip2.h b/arch/lfm2_bf16/siglip2.h new file mode 100644 index 00000000..323b1363 --- /dev/null +++ b/arch/lfm2_bf16/siglip2.h @@ -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 + +#include +#include +#include +#include + +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 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(P, seg); + if (ctx->shape_probe) { + const int64_t r = std::min(P, ctx->max_tok); + P = std::max(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 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 */ diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 4af86d8b..77d68017 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -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), diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 64a8bf44..16de4373 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -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. */ diff --git a/cmake/RadAddPlugin.cmake b/cmake/RadAddPlugin.cmake index 31d2b745..9ff68ae7 100644 --- a/cmake/RadAddPlugin.cmake +++ b/cmake/RadAddPlugin.cmake @@ -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 $<$:-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 $<$:--no-offload-compress>) target_link_options(${tgt} PRIVATE $<$:--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 diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 3bba2e3b..8afcf8d7 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -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 diff --git a/core/build/startup.cpp b/core/build/startup.cpp index c0e97a9e..116c5842 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -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 */ diff --git a/core/config.cpp b/core/config.cpp index a619b23f..b7051fa4 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -9,6 +9,7 @@ #include "format/rope_override.h" #include "sample/host_ref.h" #include "server/oai.h" +#include "diag/diag.h" #include @@ -755,11 +756,16 @@ int config_parse(int argc, char** argv, Config* c) { RAD_ERR("unknown option '%s'", a.c_str()); return RAD_E_INVAL; } + /* WHERE EACH OPTION CAME FROM, for the startup report (core/diag/diag.h): every branch + * above that returned refused the option, so reaching here is the option taken. Under the + * table's spelling, so an alias reports as the option it is. */ + c->given[S("--gpu-headroom") ? "--gpu-headroom-mib" : a] = "command line"; } if (c->radiance_home.empty()) { const char* h = getenv("RADIANCE_HOME"); c->radiance_home = h ? h : RAD_DEFAULT_HOME; + if (h) c->given["--radiance-home"] = "environment (RADIANCE_HOME)"; } if (c->kernel_hierarchy.empty()) { /* RADIANCE_KERNELS, ahead of the built-in default. @@ -769,7 +775,10 @@ int config_parse(int argc, char** argv, Config* c) { * plugin with rad-kbench or rad-tune has no way to serve with it short of editing every * launcher's command line. Same spelling, same separator. */ const char* e = getenv("RADIANCE_KERNELS"); - if (e && *e) c->kernel_hierarchy = split_commas(e); + if (e && *e) { + c->kernel_hierarchy = split_commas(e); + c->given["--kernels"] = "environment (RADIANCE_KERNELS)"; + } } /* AND THERE IS NO BUILT-IN DEFAULT, deliberately. Naming a library here -- the RDNA4 one, say * -- would make the core carry the name of one card's kernels, and on any other machine that @@ -850,4 +859,190 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_OK; } +/* ------------------------------------------------------------------ the startup report's rows */ +namespace { + +std::string onoff(bool b) { return b ? "on" : "off"; } +std::string num(int64_t v) { return std::to_string(v); } +std::string or_none(const std::string& s, const char* none) { return s.empty() ? std::string(none) : s; } +std::string fnum(double v) { + char b[48]; + snprintf(b, sizeof b, "%g", v); + return b; +} +template +std::string opt(const std::optional& v, const char* unset) { + if (!v) return unset; + if constexpr (std::is_floating_point_v) return fnum((double)*v); + else return std::to_string(*v); +} +std::string joined(const std::map& 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 config_rows(const Config& c) { + std::vector 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 config_option_names() { + std::vector out; + for (const Flag& f : g_flags) + if (std::strcmp(f.name, "--help")) out.push_back(f.name); + return out; +} + +} /* namespace diag */ + } /* namespace rad */ diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 7a54c4fd..d4859f40 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -270,6 +270,47 @@ std::vector agent_isas(hsa_agent_t a) { return v; } +/* The driver's topology node of card `gpu_id`, -1 when no node names it. */ +int topo_node(uint32_t gpu_id) { + for (int n = 0; n < 256; ++n) { + char path[96]; + std::snprintf(path, sizeof path, "/sys/class/kfd/kfd/topology/nodes/%d/gpu_id", n); + FILE* f = std::fopen(path, "r"); + if (!f) { if (n > 0) break; continue; } + unsigned id = 0; + const bool got = std::fscanf(f, "%u", &id) == 1; + std::fclose(f); + if (got && id == gpu_id) return n; + } + return -1; +} + +/* WHETHER THE CPU CAN WRITE THE CARD'S VRAM: 1 yes, 0 no, -1 the topology does not say. The driver + * maps VRAM for the CPU only where the PCI BAR spans all of it. With a smaller BAR -- Resizable BAR + * off in the firmware, or a board without it -- the topology calls the card's memory a private + * frame buffer and the runtime maps every VRAM allocation PROT_NONE, which the kernel argument + * rings are; the heap type is what the runtime itself decides from. */ +int vram_host_writable(uint32_t gpu_id) { + constexpr unsigned long long kHeapFbPrivate = 2; /* HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE */ + const int n = gpu_id ? topo_node(gpu_id) : -1; + if (n < 0) return -1; + int banks = 0; + bool priv = false; + for (int b = 0; b < 64; ++b, ++banks) { + char path[128]; + std::snprintf(path, sizeof path, "/sys/class/kfd/kfd/topology/nodes/%d/mem_banks/%d/properties", + n, b); + FILE* f = std::fopen(path, "r"); + if (!f) break; + char key[128]; + unsigned long long v = 0; + while (std::fscanf(f, "%127s %llu", key, &v) == 2) + if (!std::strcmp(key, "heap_type") && v == kHeapFbPrivate) priv = true; + std::fclose(f); + } + return banks == 0 ? -1 : priv ? 0 : 1; +} + hsa_status_t collect_gpu(hsa_agent_t a, void* data) { hsa_device_type_t t; if (hsa_agent_get_info(a, HSA_AGENT_INFO_DEVICE, &t) != HSA_STATUS_SUCCESS) return HSA_STATUS_SUCCESS; @@ -316,6 +357,8 @@ bool interrupts(hsa_signal_t s) { return s.handle && reinterpret_cast(s.handle)->event_mailbox_ptr != 0; } +hsa_status_t on_system_event(const hsa_amd_event_t* e, void*); /* the memory-fault report */ + /* HIP's ordinals and HSA's agents are matched by PCI address rather than by position: the CPU's * integrated graphics is an HSA agent too, and HIP's visible-device mask can hide any of them. */ bool init_devices() { @@ -368,7 +411,21 @@ bool init_devices() { g.why = fmt("HIP device %d (%s) has no matching HSA agent with a VRAM pool", i, bus); return false; } + /* Every dispatch's arguments are written by the host into VRAM (a_stream_create), so a + * card the CPU cannot write is refused here rather than at the first launch's SIGSEGV. */ + if (vram_host_writable(g.dev[(size_t)i].kfd_id) == 0) { + g.why = fmt("card %d (%s) does not let the CPU write its VRAM: its PCI BAR is smaller " + "than its memory. The AQL backend needs Resizable BAR -- turn on Above 4G " + "Decoding and Resizable BAR in the firmware setup; `lspci -vv` then shows " + "the card's first region as large as its VRAM", i, bus); + return false; + } } + /* Refused, a fault is left to the runtime's own handling, which is what the memory-fault + * report below exists to replace: so the start says it. */ + if (hsa_amd_register_system_event_handler(on_system_event, nullptr) != HSA_STATUS_SUCCESS) + RAD_WARN("device: the runtime refused the memory-fault report's handler; a GPU memory " + "fault will not be reported, and may hang the server instead of ending it"); return true; } @@ -526,6 +583,8 @@ struct Stream { uint64_t rd = 0; /* last read index seen */ int64_t last_sys_acq = -(int64_t)kQueuePackets; uint64_t epoch = 0; /* host epoch at the last system acquire */ + hsa_signal_t ride{}; /* rad_ride: the next dispatch's completion signal */ + bool agent_only = false; /* rad_xp_stream_create: never a system-scope acquire */ std::atomic fault{0}; char* bounce = nullptr; /* pinned, for pageable copies */ std::mutex bounce_mu; @@ -572,6 +631,9 @@ uint64_t read_progress() { return n; } +/* The DMA lanes' part of the dump, set once a lane opens (the lanes are kept further down). */ +void (*g_dump_lanes)() = nullptr; + void dump_queues(const char* where) { std::lock_guard lk(G().streams_mu); RAD_ERR("device: %s has waited 5 s; the queues:", where); @@ -602,6 +664,180 @@ void dump_queues(const char* where) { RAD_ERR(" device %d queue %p: written %" PRIu64 ", read %" PRIu64 " -> %s", s->ord, (void*)s->q, wr, rd, what.c_str()); } + if (g_dump_lanes) g_dump_lanes(); +} + +/* ------------------------------------------------------------------ the memory-fault report + * + * WHAT A GPU MEMORY FAULT READ, in this process's terms. The runtime's own line gives the card and + * the address and nothing else, and an address alone cannot say whether a kernel was handed a + * buffer that was freed under it, read past the end of a live one, or followed a pointer that was + * never one. So every range this backend hands out is kept with its kind, size and order, and the + * latest frees with it, and on a fault the address and the running kernel's pointer arguments are + * each placed against both. + * + * AND THEN THE PROCESS ENDS, at once and without a core. A fault stops the queue it happened on for + * good, and what the runtime does next turns on the core-size limit, neither way usefully. With no + * core file to write, the HIP runtime's own handler claims the event (HIP_SKIP_ABORT_ON_GPU_ERROR + * defaults on) and keeps the error for a HIP call this backend never makes: nothing prints, nothing + * aborts, and every wait spins on the stopped queue -- a server that hangs with only the stall + * report to say so. With a limit set, the runtime prints its line and writes a GPU core of every + * device mapping before it aborts, tens of gigabytes for a served model: minutes of a server that + * neither answers nor exits. So the report is followed by fatal() -- exit status 70, no destructors + * (they would wait on that queue), no core -- and a supervisor's restart is what brings the server + * back. */ +struct AllocRec { + uintptr_t base = 0; + int64_t bytes = 0; + int kind = 0; + uint64_t seq = 0; /* the order it was handed out in, from 1 */ + uint64_t freed_ns = 0; /* when it was freed (CLOCK_MONOTONIC); 0 while it is live */ +}; +std::mutex g_alloc_mu; +std::map g_live; /* by base */ +std::deque g_freed; /* the latest frees, oldest first */ +uint64_t g_alloc_seq = 0; +constexpr size_t kFreedKept = 1024; + +uint64_t mono_ns() { + timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; +} + +const char* mem_kind(int kind) { + switch (kind) { + case RAD_MEM_DEVICE: return "device"; + case RAD_MEM_HOST: return "host"; + case RAD_MEM_HOST_PINNED: return "host-pinned"; + case RAD_MEM_HOST_MAPPED: return "host-mapped"; + default: return "backend"; + } +} + +void note_alloc(const void* p, int64_t bytes, int kind) { + if (!p) return; + std::lock_guard lk(g_alloc_mu); + g_live[(uintptr_t)p] = AllocRec{(uintptr_t)p, bytes, kind, ++g_alloc_seq, 0}; +} + +void note_free(const void* p) { + if (!p) return; + std::lock_guard lk(g_alloc_mu); + auto it = g_live.find((uintptr_t)p); + if (it == g_live.end()) return; + AllocRec r = it->second; + g_live.erase(it); + r.freed_ns = mono_ns(); + g_freed.push_back(r); + if (g_freed.size() > kFreedKept) g_freed.pop_front(); +} + +std::string rec_str(const AllocRec& r, uintptr_t a) { + return fmt("#%" PRIu64 " %s %s at %#" PRIxPTR " +%s", r.seq, mem_kind(r.kind), + humanb(r.bytes).c_str(), r.base, humanb((int64_t)(a - r.base)).c_str()); +} + +/* Where address `a` lies among this process's ranges: inside a live one, inside one freed since + * (the newest such first -- a range handed out again holds the address live as well), or in + * neither, with the live ranges either side of it. Called with g_alloc_mu held. */ +std::string where_is(uintptr_t a) { + auto it = g_live.upper_bound(a); + if (it != g_live.begin()) { + const AllocRec& r = std::prev(it)->second; + if (a < r.base + (uintptr_t)r.bytes) return "inside live " + rec_str(r, a); + } + const uint64_t now = mono_ns(); + for (auto f = g_freed.rbegin(); f != g_freed.rend(); ++f) + if (a >= f->base && a < f->base + (uintptr_t)f->bytes) + return fmt("inside FREED %s, freed %.1f s ago", rec_str(*f, a).c_str(), + (double)(now - f->freed_ns) * 1e-9); + std::string s = "in no range this process holds or recently freed"; + if (it != g_live.begin()) { + const AllocRec& r = std::prev(it)->second; + s += fmt("; %s past the end of #%" PRIu64 " %s %s at %#" PRIxPTR, + humanb((int64_t)(a - (r.base + (uintptr_t)r.bytes))).c_str(), r.seq, + mem_kind(r.kind), humanb(r.bytes).c_str(), r.base); + } + if (it != g_live.end()) + s += fmt("; %s before #%" PRIu64 " %s %s at %#" PRIxPTR, + humanb((int64_t)(it->second.base - a)).c_str(), it->second.seq, + mem_kind(it->second.kind), humanb(it->second.bytes).c_str(), it->second.base); + return s; +} + +/* The runtime's view of the address, which covers what this backend did not allocate itself (a + * kernel library's own hipMalloc, the runtime's internals): the allocation it falls in, if any. */ +std::string runtime_view(uintptr_t a) { + hsa_amd_pointer_info_t info{}; + info.size = sizeof info; + if (hsa_amd_pointer_info((void*)a, &info, nullptr, nullptr, nullptr) != HSA_STATUS_SUCCESS) + return "the runtime could not be asked"; + if (info.type == HSA_EXT_POINTER_TYPE_UNKNOWN) return "the runtime holds no allocation there"; + const char* t = info.type == HSA_EXT_POINTER_TYPE_HSA ? "runtime memory" + : info.type == HSA_EXT_POINTER_TYPE_LOCKED ? "a locked host range" + : info.type == HSA_EXT_POINTER_TYPE_IPC ? "an IPC import" + : info.type == HSA_EXT_POINTER_TYPE_GRAPHICS ? "a graphics interop range" + : "a runtime range"; + return fmt("the runtime has %s of %s at %p", t, humanb((int64_t)info.sizeInBytes).c_str(), + info.agentBaseAddress); +} + +/* A word that could be an address in this process: canonical user space, past the null page. */ +bool looks_like_pointer(uint64_t w) { return w >= 0x10000 && w < 0x0000800000000000ull; } + +hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) { + if (!e || e->event_type != HSA_AMD_GPU_MEMORY_FAULT_EVENT) return HSA_STATUS_ERROR; + const hsa_amd_gpu_memory_fault_info_t& f = e->memory_fault; + const uintptr_t va = (uintptr_t)f.virtual_address; + int card = -1; + for (size_t i = 0; i < G().dev.size(); ++i) + if (G().dev[i].agent.handle == f.agent.handle) card = (int)i; + std::string why; + const uint32_t m = f.fault_reason_mask; + if (m & HSA_AMD_MEMORY_FAULT_PAGE_NOT_PRESENT) why += " page-not-present"; + if (m & HSA_AMD_MEMORY_FAULT_READ_ONLY) why += " write-to-read-only"; + if (m & HSA_AMD_MEMORY_FAULT_NX) why += " execute"; + if (m & HSA_AMD_MEMORY_FAULT_HOST_ONLY) why += " host-only"; + if (m & HSA_AMD_MEMORY_FAULT_IMPRECISE) why += " imprecise-address"; + { + std::lock_guard lk(g_alloc_mu); + RAD_ERR("device %d: GPU memory fault at %#" PRIxPTR " (%s ): %s; %s", card, va, + why.empty() ? " ?" : why.c_str(), where_is(va).c_str(), runtime_view(va).c_str()); + } + /* THE KERNEL THAT RAN, AND WHAT IT WAS GIVEN. A queue's read index stays on a packet until it + * completes, so the packet there is the one in flight; every pointer-shaped word of its + * arguments is placed like the address, which names the operand a stale or short buffer was + * passed as. Card `card`'s queues only, and the arguments read through the BAR as they were + * written. */ + std::lock_guard sl(G().streams_mu); + for (Stream* s : G().streams) { + if (s->ord != card) continue; + const uint64_t rd = hsa_queue_load_read_index_scacquire(s->q); + const uint64_t wr = hsa_queue_load_write_index_scacquire(s->q); + if (rd >= wr) continue; + auto* p = static_cast(s->q->base_address) + (rd & s->mask); + const uint16_t h = __atomic_load_n(&p->header, __ATOMIC_ACQUIRE); + if (((h >> HSA_PACKET_HEADER_TYPE) & 0xff) != HSA_PACKET_TYPE_KERNEL_DISPATCH) continue; + std::string name; + { + std::lock_guard nl(g_names_mu); + auto it = g_names.find(p->kernel_object); + name = it != g_names.end() ? it->second : fmt("%#" PRIx64, p->kernel_object); + } + RAD_ERR("device %d: queue %p packet %" PRIu64 " (of %" PRIu64 " written) ran kernel %s", card, + (void*)s->q, rd, wr, name.c_str()); + const uint64_t* ka = static_cast(p->kernarg_address); + if (!ka) continue; + std::lock_guard lk(g_alloc_mu); + for (uint32_t i = 0; i < kKargMax / 8; ++i) { + const uint64_t w = ka[i]; + if (!looks_like_pointer(w)) continue; + RAD_ERR(" argument +%u = %#" PRIx64 ": %s", i * 8, w, where_is((uintptr_t)w).c_str()); + } + } + fatal("a GPU memory fault on device %d stopped its queue for good (the report is above); " + "exiting so a restart can bring the server back", card); } /* How long a host wait goes before it reports the queues; see dump_queues. */ @@ -761,6 +997,9 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) { if (forced || lap || s->epoch != ep) { s->last_sys_acq = (int64_t)idx; s->epoch = ep; + /* The prefetch's stream reads nothing the host writes: a system acquire there would only + * invalidate the L2 under the compute stream's feet. */ + if (s->agent_only && !forced) return HSA_FENCE_SCOPE_AGENT; return HSA_FENCE_SCOPE_SYSTEM; } return HSA_FENCE_SCOPE_AGENT; @@ -832,6 +1071,12 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t p->completion_signal.handle = 0; constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS; if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence); + /* A ride goes on after the tape has its copy: a recorded packet carries no signal of this + * issue's, and a play puts on whichever ride is waiting then (PlayRun::put). */ + if (s->ride.handle) { + p->completion_signal = s->ride; + s->ride.handle = 0; + } const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0); const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel), setup); @@ -908,6 +1153,13 @@ struct PlayRun { auto* p = static_cast(s->q->base_address) + (idx & s->mask); std::memcpy(reinterpret_cast(p) + 4, reinterpret_cast(&r.pkt) + 4, sizeof(hsa_kernel_dispatch_packet_t) - 4); + /* A ride left waiting by host work between two played stretches (rad_ride) is the first + * played dispatch's to complete, as an issued one's would be. A record riding on this + * dispatch already has the signal; the ride then waits for the next one. */ + if (!done.handle && s->ride.handle) { + done = s->ride; + s->ride.handle = 0; + } if (done.handle) p->completion_signal = done; const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0); int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; @@ -1180,8 +1432,12 @@ int a_stream_create(RadStream* out, int high_priority) { return RAD_E_NOMEM; } s->bounce = static_cast(bb); + note_alloc(ka, (int64_t)(s->mask + 1) * kKargSlot, -1); + note_alloc(bb, kBounceBytes, -1); s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed); if (s->id >= kMaxQueues) { + note_free(bb); + note_free(ka); hsa_amd_memory_pool_free(bb); hsa_amd_memory_pool_free(ka); hsa_queue_destroy(s->q); @@ -1208,6 +1464,8 @@ void a_stream_destroy(RadStream rs) { } g_queue_by_id[s->id].store(nullptr, std::memory_order_release); hsa_queue_destroy(s->q); + note_free(s->karg); + note_free(s->bounce); hsa_amd_memory_pool_free(s->karg); hsa_amd_memory_pool_free(s->bounce); s->magic = 0; @@ -1476,6 +1734,7 @@ bool tape_idle(const Tape* t) { } void tape_free(Tape* t) { + note_free(t->karg); if (t->karg) hsa_amd_memory_pool_free(t->karg); t->magic = 0; delete t; @@ -1546,6 +1805,7 @@ RadTape a_tape_end(int keep) { std::memcpy(ka, t->karg_host.data(), t->karg_host.size()); _mm_sfence(); t->karg = static_cast(ka); + note_alloc(ka, (int64_t)t->karg_host.size(), -1); for (TapeRec& r : t->rec) if (r.kind == kTapeDispatch) r.pkt.kernarg_address = t->karg + r.karg_off; } @@ -1822,6 +2082,698 @@ int a_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadC return rc < 0 ? RAD_E_DEVICE : RAD_OK; } +/* ---- the DMA lane: a card's own SDMA queue ------------------------------------------------------ + * + * A LIST OF COPIES GOES TO THE CARD'S DMA ENGINE THROUGH A QUEUE OF THIS BACKEND'S OWN, not through + * the runtime's copy call. Measured on gfx1201 with 1.3 MB host->card copies beside a kernel stream + * that saturates VRAM: this queue moves 28.7 GB/s -- the link -- and costs the kernels nothing; the + * runtime's copy call moves 22.0 GB/s and costs them 8%; copy kernels get 2.3 GB/s. The runtime's + * difference is in its packets: from gfx10 on it brackets every copy with a write-back and an + * invalidation of the WHOLE L2, so a prefill layer's ninety copies were 180 cache flushes under the + * running GEMMs, and the engine sat out each flush. Here a list is one wait, its copies and one + * write, and the caches are kept by the two barriers that order the list on its AQL stream. + * + * The queue is the driver's user-mode SDMA queue (AMDKFD_IOC_CREATE_QUEUE), and the driver holds its + * buffers to rules the runtime's allocations do not meet: the write pointer must open a one-page GTT + * buffer of THIS card, which the scheduler firmware pins into the GART, and the ring must be a buffer + * of exactly its own size. So both are allocated here with the driver calls the runtime's thunk makes + * for its queues, at an address reserved in this process so the CPU and the card share it, and + * CPU-mapped through the render node the thunk bound to the process's GPU address space -- the one + * file the driver lets map a buffer of that space. + * + * Engine 0 only. A second engine on the same direction moved nothing more (the link is the bound) + * and cost a VRAM-bound kernel stream 40%. */ +constexpr uint32_t kSdmaCopy = 1; /* COPY, sub-op LINEAR */ +constexpr uint32_t kSdmaFence = 5; +constexpr uint32_t kSdmaPoll = 8; /* POLL_REGMEM */ +constexpr uint64_t kSdmaMaxCopy = 0x3fffe0; /* the largest count a linear copy carries */ +constexpr uint64_t kDmaRingBytes = (uint64_t)1 << 20; +constexpr size_t kDoorbellPage = 8192; /* 1024 64-bit doorbells a process */ +/* THE LINK GATE is a signal that only ever counts down: each hold and each release is a barrier + * packet on the holding stream whose completion takes one off, so the value is odd exactly while a + * hold is in force, and the engine waits on its low bit. Even to start, and far from zero. */ +constexpr int64_t kGateStart = (int64_t)1 << 62; +/* A YIELDING LIST CHECKS THE GATE EVERY MEGABYTE. A check costs the engine ~2 us whatever the word's + * place, so this is 5% of its rate, and a hold that starts mid-list shares the link for 36 us at + * most; at 2 MB the prefill was slower, at 256 KB the checks cost 17%. */ +constexpr uint64_t kYieldBytes = (uint64_t)1 << 20; + +/* THE QUEUE REQUEST AT THE DRIVER'S CURRENT LAYOUT, NOT THE BUILD MACHINE'S. Naming the SDMA engine + * -- queue type 4 and the sdma_engine_id field -- is KFD ioctl 1.17, and the kernel headers a build + * sees can be older than the driver the engine runs on: Ubuntu 24.04's is 1.14, + * whose struct ends before both fields. The driver copies as many bytes as the ioctl number says and + * zero-fills or drops the rest, so this longer form is what every driver is sent; one older than + * 1.17 refuses the queue type, and the lane reports that as its reason. */ +struct KfdCreateQueue { + uint64_t ring_base_address, write_pointer_address, read_pointer_address, doorbell_offset; + uint32_t ring_size, gpu_id, queue_type, queue_percentage, queue_priority, queue_id; + uint64_t eop_buffer_address, eop_buffer_size, ctx_save_restore_address; + uint32_t ctx_save_restore_size, ctl_stack_size, sdma_engine_id, metadata_ring_size; +}; +static_assert(sizeof(KfdCreateQueue) == 96, "the KFD 1.22 create-queue layout"); +constexpr uint32_t kKfdQueueSdmaByEngine = 0x4; +constexpr unsigned long kKfdCreateQueue = _IOWR(AMDKFD_IOCTL_BASE, 0x02, KfdCreateQueue); + +struct DmaBo { + char* va = nullptr; + size_t size = 0; + uint64_t handle = 0; + char* res = nullptr; /* the address reservation it sits in */ + size_t res_size = 0; +}; + +struct DmaQueue { + std::once_flag once; + std::mutex mu; + bool ok = false; + DmaBo ring, ptrs; + uint32_t* rb = nullptr; + volatile uint64_t* rptr = nullptr; /* bytes the engine has read, written by the engine */ + volatile uint64_t* wptr = nullptr; /* bytes written, for the firmware */ + volatile uint64_t* db = nullptr; + uint64_t w = 0; /* bytes written, monotonic */ + uint32_t qid = 0; + std::once_flag gate_once; + hsa_signal_t gate{}; /* the link gate: odd while a stream holds the link */ + bool held = false; /* the last hold issued, for the alternation check */ + bool ever_held = false; /* a stream has held this card's link at least once */ + std::atomic tried{false}; /* dma_open has run, for the startup report */ + std::string why; /* why it failed */ + /* A QUEUE WHOSE EVERY LIST ENDS BY WRITING ITS NUMBER to `fin` (the expert prefetch's): the room + * check takes the end of the last list finished as the least the engine has read. The read + * pointer the engine writes back has been seen to stop moving on such a queue while the engine + * ran on, and a ring the host thinks full would wait for ever. */ + volatile uint32_t* fin = nullptr; + uint32_t lists = 0; /* lists handed over; list k ends at ends[k % kDmaEnds] */ + std::unique_ptr ends; +}; +constexpr uint32_t kDmaEnds = 4096; +DmaQueue g_dma[kMaxDevices]; +DmaQueue g_dma_xp[kMaxDevices]; /* the expert prefetch's, on the card's second engine */ + +/* The render node a card's buffers are CPU-mapped through: /dev/dri/renderD, the minor from + * the driver's topology entry for its gpu_id. */ +int render_minor(uint32_t gpu_id) { + const int n = topo_node(gpu_id); + if (n < 0) return -1; + char path[96]; + std::snprintf(path, sizeof path, "/sys/class/kfd/kfd/topology/nodes/%d/properties", n); + FILE* f = std::fopen(path, "r"); + if (!f) return -1; + char key[128]; + unsigned long long v = 0; + int minor = -1; + while (std::fscanf(f, "%127s %llu", key, &v) == 2) + if (!std::strcmp(key, "drm_render_minor")) minor = (int)v; + std::fclose(f); + return minor; +} + +void dma_bo_free(uint32_t gpu_id, DmaBo* b) { + if (b->handle) { + uint32_t ids[1] = { gpu_id }; + kfd_ioctl_unmap_memory_from_gpu_args u{}; + u.handle = b->handle; + u.device_ids_array_ptr = (uint64_t)(uintptr_t)ids; + u.n_devices = 1; + ioctl(G().kfd, AMDKFD_IOC_UNMAP_MEMORY_FROM_GPU, &u); + kfd_ioctl_free_memory_of_gpu_args f{}; + f.handle = b->handle; + ioctl(G().kfd, AMDKFD_IOC_FREE_MEMORY_OF_GPU, &f); + } + if (b->res) munmap(b->res, b->res_size); + *b = DmaBo{}; +} + +/* A GTT buffer of card `gpu_id`, at one address for the CPU and the card. */ +bool dma_bo(uint32_t gpu_id, int minor, size_t size, DmaBo* b, std::string* why) { + const size_t al = (size_t)2 << 20; + b->res_size = size + al; + void* r = mmap(nullptr, b->res_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if (r == MAP_FAILED) { + b->res = nullptr; + *why = fmt("no address range for a %zu-byte buffer: %s", size, std::strerror(errno)); + return false; + } + b->res = (char*)r; + b->va = (char*)(((uintptr_t)r + al - 1) & ~(uintptr_t)(al - 1)); + b->size = size; + kfd_ioctl_alloc_memory_of_gpu_args a{}; + a.va_addr = (uint64_t)(uintptr_t)b->va; + a.size = size; + a.gpu_id = gpu_id; + a.flags = KFD_IOC_ALLOC_MEM_FLAGS_GTT | KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE | + KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE | KFD_IOC_ALLOC_MEM_FLAGS_COHERENT | + KFD_IOC_ALLOC_MEM_FLAGS_NO_SUBSTITUTE; + if (ioctl(G().kfd, AMDKFD_IOC_ALLOC_MEMORY_OF_GPU, &a) < 0) { + *why = fmt("the driver refused a %zu-byte GTT buffer: %s", size, std::strerror(errno)); + dma_bo_free(gpu_id, b); + return false; + } + b->handle = a.handle; + uint32_t ids[1] = { gpu_id }; + kfd_ioctl_map_memory_to_gpu_args m{}; + m.handle = a.handle; + m.device_ids_array_ptr = (uint64_t)(uintptr_t)ids; + m.n_devices = 1; + if (ioctl(G().kfd, AMDKFD_IOC_MAP_MEMORY_TO_GPU, &m) < 0) { + *why = fmt("the driver would not map a GTT buffer to the card: %s", std::strerror(errno)); + dma_bo_free(gpu_id, b); + return false; + } + char want[64]; + std::snprintf(want, sizeof want, "/dev/dri/renderD%d", minor); + if (DIR* d = opendir("/proc/self/fd")) { + while (dirent* e = readdir(d)) { + char link[300], tgt[128]; + std::snprintf(link, sizeof link, "/proc/self/fd/%s", e->d_name); + const ssize_t n = readlink(link, tgt, sizeof tgt - 1); + if (n <= 0) continue; + tgt[n] = 0; + if (std::strcmp(tgt, want)) continue; + const int fd = std::atoi(e->d_name); + if (mmap(b->va, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, a.mmap_offset) != + MAP_FAILED) { + closedir(d); + return true; + } + } + closedir(d); + } + *why = fmt("no file of this process maps a buffer of the card's address space (%s, the runtime's " + "render node, is not open or refused)", want); + dma_bo_free(gpu_id, b); + return false; +} + +/* THE GATE IS MADE APART FROM THE QUEUE, on first use by either: a launch is handed its address when + * its op is bound, and that must not open a DMA queue on a card nothing streams weights onto. */ +hsa_signal_t* gate_signal(int ord) { + if (ord < 0 || ord >= kMaxDevices) return nullptr; + DmaQueue& q = g_dma[ord]; + std::call_once(q.gate_once, [&] { + if (hsa_amd_signal_create(kGateStart, 0, nullptr, HSA_AMD_SIGNAL_AMD_GPU_ONLY, &q.gate) != + HSA_STATUS_SUCCESS) + q.gate.handle = 0; + }); + return q.gate.handle ? &q.gate : nullptr; +} + +/* The card's queue if it has been opened and is usable; never opens it. */ +DmaQueue* dma_queue_open(int ord) { + if (ord < 0 || ord >= kMaxDevices) return nullptr; + DmaQueue& q = g_dma[ord]; + return q.tried.load(std::memory_order_acquire) && q.ok ? &q : nullptr; +} + +bool dma_open(int ord, DmaQueue* q, std::string* why, uint32_t engine = 0, bool gated = true) { + const uint32_t gpu_id = G().dev[(size_t)ord].kfd_id; + const int minor = gpu_id ? render_minor(gpu_id) : -1; + if (G().kfd < 0 || !gpu_id || minor < 0) { + *why = "the driver's topology does not name the card's render node"; + return false; + } + if (!dma_bo(gpu_id, minor, kDmaRingBytes, &q->ring, why)) return false; + if (!dma_bo(gpu_id, minor, 4096, &q->ptrs, why)) { dma_bo_free(gpu_id, &q->ring); return false; } + std::memset(q->ring.va, 0, kDmaRingBytes); + std::memset(q->ptrs.va, 0, 4096); + q->rb = (uint32_t*)q->ring.va; + q->rptr = (volatile uint64_t*)q->ptrs.va; + q->wptr = (volatile uint64_t*)(q->ptrs.va + 64); + KfdCreateQueue a{}; + a.ring_base_address = (uint64_t)(uintptr_t)q->ring.va; + a.ring_size = (uint32_t)kDmaRingBytes; + a.read_pointer_address = (uint64_t)(uintptr_t)q->rptr; + a.write_pointer_address = (uint64_t)(uintptr_t)q->wptr; + a.gpu_id = gpu_id; + a.queue_type = kKfdQueueSdmaByEngine; + a.sdma_engine_id = engine; + a.queue_percentage = KFD_MAX_QUEUE_PERCENTAGE; + a.queue_priority = KFD_MAX_QUEUE_PRIORITY; + if (ioctl(G().kfd, kKfdCreateQueue, &a) < 0) { + *why = fmt("the driver refused an SDMA queue: %s", std::strerror(errno)); + dma_bo_free(gpu_id, &q->ptrs); + dma_bo_free(gpu_id, &q->ring); + return false; + } + q->qid = a.queue_id; + /* The offset names the process's doorbell page and, in its low bits, this queue's doorbell in it. */ + void* m = mmap(nullptr, kDoorbellPage, PROT_READ | PROT_WRITE, MAP_SHARED, G().kfd, + (off_t)(a.doorbell_offset & ~(uint64_t)(kDoorbellPage - 1))); + if (m == MAP_FAILED) { + *why = fmt("the SDMA queue's doorbell could not be mapped: %s", std::strerror(errno)); + kfd_ioctl_destroy_queue_args d{}; + d.queue_id = q->qid; + ioctl(G().kfd, AMDKFD_IOC_DESTROY_QUEUE, &d); + dma_bo_free(gpu_id, &q->ptrs); + dma_bo_free(gpu_id, &q->ring); + return false; + } + q->db = (volatile uint64_t*)((char*)m + (a.doorbell_offset & (kDoorbellPage - 1))); + q->w = 0; + if (!gated) return true; + if (!gate_signal(ord)) { + /* The queue stays open and unused: a list without a gate would not know when to yield. */ + *why = "no signal could be made for the link gate"; + return false; + } + return true; +} + +inline uint64_t dma_read(const DmaQueue* q); + +/* The DMA lanes beside dump_queues' AQL queues: a list stops at the gate while a hold is in force, + * so a gate left odd shows as a lane whose ring is written past what it has read. Read without the + * lane's lock, which a stuck writer may hold. */ +void dump_dma_lanes() { + for (int c = 0; c < kMaxDevices; ++c) { + DmaQueue& q = g_dma[c]; + if (!q.tried.load(std::memory_order_acquire) || !q.ok) continue; + RAD_ERR(" device %d DMA lane: ring written %" PRIu64 " B, read %" PRIu64 " B; link gate %" + PRId64 " (%s), last hold issued %s", c, (uint64_t)q.w, (uint64_t)*q.rptr, + (int64_t)hsa_signal_load_relaxed(q.gate), + (hsa_signal_load_relaxed(q.gate) & 1) ? "held" : "free", q.held ? "on" : "off"); + } + for (int c = 0; c < kMaxDevices; ++c) { + DmaQueue& q = g_dma_xp[c]; + if (!q.tried.load(std::memory_order_acquire) || !q.ok) continue; + RAD_ERR(" device %d prefetch DMA queue: ring written %" PRIu64 " B, read %" PRIu64 " B; %u lists " + "handed over, %u finished", c, (uint64_t)q.w, dma_read(&q), q.lists, q.fin ? *q.fin : 0u); + } +} + +/* The card's queue, made on first use; null, after one warning, where the driver will not give one. */ +DmaQueue* dma_queue(int ord) { + if (ord < 0 || ord >= kMaxDevices || ord >= (int)G().dev.size()) return nullptr; + DmaQueue& q = g_dma[ord]; + std::call_once(q.once, [&] { + std::string why; + const auto t0 = std::chrono::steady_clock::now(); + q.ok = dma_open(ord, &q, &why); + q.why = why; + q.tried.store(true, std::memory_order_release); + if (q.ok) aql::g_dump_lanes = dump_dma_lanes; + if (q.ok) + RAD_INFO("device: card %d copy lists go to DMA engine 0 on a queue of this process's own " + "(%.1f ms to open)", ord, + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + if (!q.ok) + RAD_WARN("device: card %d has no DMA queue of this process's own (%s); copy lists go as " + "copy kernels, which share the compute units with the running kernels and slow " + "the prefill stager down", ord, why.c_str()); + }); + return q.ok ? &q : nullptr; +} + +/* What the engine has read: the read pointer it writes back, or past it the end of the last list a + * numbered queue has finished (DmaQueue::fin). */ +inline uint64_t dma_read(const DmaQueue* q) { + uint64_t r = *q->rptr; + if (q->fin) { + const uint32_t k = *q->fin; + if (k) r = std::max(r, q->ends[k % kDmaEnds]); + } + return r; +} + +/* `n` dwords onto the ring, the queue's lock held. A packet never straddles the ring's end: the + * tail is padded with single-dword NOPs. The room is what the engine has read: the ring holds a few + * hundred layers' lists, so a wait here is the host that far ahead of a stalled engine. */ +int dma_put(DmaQueue* q, const uint32_t* dw, uint64_t n) { + const uint64_t cap = kDmaRingBytes / 4; + uint64_t at = (q->w / 4) & (cap - 1); + const uint64_t pad = at + n > cap ? cap - at : 0; + const uint64_t need = (pad + n) * 4; + if (q->w + need - dma_read(q) > kDmaRingBytes) { + Stall st("a full DMA ring"); + while (q->w + need - dma_read(q) > kDmaRingBytes) { + if (G().faulted.load(std::memory_order_relaxed)) { + device_set_error("rad_memcpy_list_async: a queue faulted while the DMA ring was full"); + return RAD_E_DEVICE; + } + st.tick(); + _mm_pause(); + } + } + for (uint64_t i = 0; i < pad; ++i) q->rb[at + i] = 0; + q->w += pad * 4; + at = (q->w / 4) & (cap - 1); + for (uint64_t i = 0; i < n; ++i) q->rb[at + i] = dw[i]; + q->w += n * 4; + return RAD_OK; +} + +void dma_kick(DmaQueue* q) { + _mm_sfence(); + *q->wptr = q->w; + _mm_sfence(); + *q->db = q->w; +} + +/* Where the engine reads and writes a signal's value: the 64-bit word the CP decrements and polls. */ +inline uint64_t sig_value_addr(const Sig* g) { + return (uint64_t)g->h.handle + offsetof(amd_signal_t, value); +} + +/* ------------------------------------------------- the expert prefetch's device half (rad_xp_*) */ + +/* The card's prefetch queue, on its second DMA engine (the first is the lane's): made on first use; + * null where the driver gives none. Its lists end with a write of their number to a signal's value, + * which the room check and rad_xp_behind read. */ +DmaQueue* xp_queue(int ord) { + if (ord < 0 || ord >= kMaxDevices || ord >= (int)G().dev.size()) return nullptr; + DmaQueue& q = g_dma_xp[ord]; + std::call_once(q.once, [&] { + std::string why; + Sig* g = sig_get(false); + if (g) { + hsa_signal_silent_store_relaxed(g->h, 0); + q.ends.reset(new uint64_t[kDmaEnds]()); + q.ok = dma_open(ord, &q, &why, 1, false); + if (q.ok) q.fin = (volatile uint32_t*)(uintptr_t)sig_value_addr(g); + } else { + why = "no signal could be made for its lists' numbers"; + } + q.why = why; + q.tried.store(true, std::memory_order_release); + if (!q.ok) RAD_INFO("card %d: no DMA queue on the second engine for the expert prefetch (%s)", ord, + why.c_str()); + }); + return q.ok ? &q : nullptr; +} + +int a_xp_supported(int device) { return xp_queue(device) != nullptr; } + +int a_xp_stream_create(RadStream* out) { + const int rc = a_stream_create(out, 0); + if (rc < 0) return rc; + ours(*out)->agent_only = true; + return RAD_OK; +} + +/* Refused while another ride is waiting for its dispatch on the stream. */ +int a_ride(RadStream rs, void** token) { + Stream* s = ours(rs); + if (!s || !token) return RAD_E_INVAL; + *token = nullptr; + Sig* g = sig_get(false); + if (!g) return RAD_E_DEVICE; + hsa_signal_silent_store_relaxed(g->h, 1); + s->lock(); + const bool busy = s->ride.handle != 0; + if (!busy) s->ride = g->h; + s->unlock(); + if (busy) { + hsa_signal_silent_store_relaxed(g->h, 0); + sig_retire(g); + return RAD_E_STATE; + } + *token = g; + return RAD_OK; +} + +int a_ride_wait(RadStream rs, void* token) { + Stream* s = ours(rs); + Sig* g = (Sig*)token; + if (!s || !g) return RAD_E_INVAL; + uint64_t idx = 0; + const int rc = barrier(s, g->h, hsa_signal_t{0}, HSA_FENCE_SCOPE_AGENT, HSA_FENCE_SCOPE_NONE, &idx); + if (rc == RAD_OK) g->waiters.emplace_back(s->id, idx); + sig_retire(g); + return rc; +} + +void a_ride_release(void* token, RadStream after, int64_t packets) { + Sig* g = (Sig*)token; + if (!g) return; + if (Stream* s = ours(after)) { + s->lock(); + g->waiters.emplace_back(s->id, s->wr + (uint64_t)std::max(packets, 0)); + s->unlock(); + } + sig_retire(g); +} + +/* Wait for the mark, wait for the card's link gate if a collective has ever held it (TP: the + * all-reduce crosses the same link, and the step waits on it, not on these copies), copy, write + * `done`, then the list's number. */ +int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, + uint32_t* done, uint32_t done_val) { + DmaQueue* dq = xp_queue(ord); + if (!dq) return RAD_E_UNSUPPORTED; + Sig* in = (Sig*)mark; + DmaQueue* lane = dma_queue_open(ord); + std::lock_guard lk(dq->mu); + int rc = RAD_OK; + if (in) { + const uint64_t ia = sig_value_addr(in); + const uint32_t poll[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, + (uint32_t)ia, (uint32_t)(ia >> 32), 0u, 0xffffffffu, + 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; + rc = dma_put(dq, poll, 6); + } + if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle) { + const uint64_t ga = (uint64_t)lane->gate.handle + offsetof(amd_signal_t, value); + const uint32_t gate[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, + (uint32_t)ga, (uint32_t)(ga >> 32), 0u, 1u /* the low bit */, + 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; + rc = dma_put(dq, gate, 6); + } + for (int i = 0; rc == RAD_OK && i < n; ++i) + for (uint64_t o = 0; rc == RAD_OK && o < bytes[i]; o += kSdmaMaxCopy) { + const uint64_t len = std::min(kSdmaMaxCopy, bytes[i] - o); + const uint64_t sa = src[i] + o, da = dst[i] + o; + const uint32_t cp[7] = { kSdmaCopy, (uint32_t)(len - 1), 0u, (uint32_t)sa, (uint32_t)(sa >> 32), + (uint32_t)da, (uint32_t)(da >> 32) }; + rc = dma_put(dq, cp, 7); + } + if (rc == RAD_OK && done) { + const uint64_t a = (uint64_t)(uintptr_t)done; + const uint32_t fence[4] = { kSdmaFence | (3u << 16) /* uncached */, (uint32_t)a, (uint32_t)(a >> 32), + done_val }; + rc = dma_put(dq, fence, 4); + } + if (rc == RAD_OK) { + const uint32_t k = dq->lists + 1; + const uint64_t a = (uint64_t)(uintptr_t)dq->fin; + const uint32_t fence[4] = { kSdmaFence | (3u << 16) /* uncached */, (uint32_t)a, (uint32_t)(a >> 32), k }; + rc = dma_put(dq, fence, 4); + if (rc == RAD_OK) { + dq->ends[k % kDmaEnds] = dq->w; + dq->lists = k; + } + } + dma_kick(dq); + return rc; +} + +int64_t a_xp_behind(int ord) { + DmaQueue* dq = (ord >= 0 && ord < kMaxDevices) ? &g_dma_xp[ord] : nullptr; + if (!dq || !dq->tried.load(std::memory_order_acquire) || !dq->ok) return 0; + std::lock_guard lk(dq->mu); + return (int64_t)(uint32_t)(dq->lists - *dq->fin); +} + +bool card_has_room(int ord, int64_t bytes, const char* what); +void* a_alloc_uncached(int64_t bytes) { + if (bytes <= 0) return nullptr; + int dev = -1; + if (hipGetDevice(&dev) != hipSuccess || !card_has_room(dev, bytes, "rad_dev_alloc_uncached")) return nullptr; + void* p = nullptr; + if (hipExtMallocWithFlags(&p, (size_t)bytes, hipDeviceMallocUncached) != hipSuccess) return nullptr; + return p; +} + +void a_free_uncached(void* p) { + if (p) (void)hipFree(p); +} + +/* A LIST: the engine waits for the stream, copies, and the stream waits for the engine (the two + * barriers in `flush`). A copy the engine cannot take goes the kernel way, in its place in the + * list: pageable memory (staged through a bounce buffer), a peer card's memory, and any copy while a + * pass is being recorded -- a tape replays queue packets, and a DMA submission is not one. The two + * signals go back to the pool behind the second barrier: by then the engine has written `out`, so + * it has stopped reading `in` as well. */ +int a_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream rs) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_memcpy_list_async: not a stream of this backend"); return RAD_E_INVAL; } + 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; + } + if (n == 0) { /* readies the card's queue; see device.h */ + (void)dma_queue(s->ord); + return RAD_OK; + } + struct Dma { const RadCopySeg* seg; uint64_t dst, src; }; + std::vector dma; + dma.reserve((size_t)n); + bool card = false; /* a copy reads or writes this card's memory */ + /* THE ORDER ON THE STREAM IS KEPT BY TWO BARRIERS AND A SIGNAL EACH WAY. The first completes `in` + * once everything before the list has; the engine polls `in` before the copies and writes `out` + * after them, and the second barrier holds the stream on `out`. The release before is the + * system's when a copy touches this card's memory, so the engine reads what kernels wrote and no + * dirty L2 line of a destination is written back over its copy later; the acquire after is the + * system's always, because the engine writes memory past the L2 and the L2 may still hold the + * destination's old bytes. */ + auto flush = [&]() -> int { + if (dma.empty()) return RAD_OK; + DmaQueue* dq = dma_queue(s->ord); + if (!dq) { + for (const Dma& c : dma) RAD_TRY(a_memcpy_async(c.seg->dst, c.seg->src, c.seg->bytes, rs)); + dma.clear(); + card = false; + return RAD_OK; + } + Sig* in = sig_get(false); + Sig* out = sig_get(false); + if (!in || !out) { + if (in) sig_retire(in); + if (out) sig_retire(out); + device_set_error("rad_memcpy_list_async: no signal could be made"); + return RAD_E_DEVICE; + } + hsa_signal_silent_store_relaxed(in->h, 1); + hsa_signal_silent_store_relaxed(out->h, 1); + int rc = barrier(s, hsa_signal_t{0}, in->h, HSA_FENCE_SCOPE_NONE, + card ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_NONE); + if (rc != RAD_OK) { + /* The queue has faulted and nothing was submitted: `in` will never complete. */ + sig_retire(in); + sig_retire(out); + dma.clear(); + return rc; + } + { + std::lock_guard lk(dq->mu); + const uint64_t ia = sig_value_addr(in), oa = sig_value_addr(out); + const uint32_t poll[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, + (uint32_t)ia, (uint32_t)(ia >> 32), 0u, 0xffffffffu, + 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; + rc = dma_put(dq, poll, 6); + /* A yielding list checks the gate before its first copy and again once a piece's worth + * has gone since the last check, its copies cut to that size, so a hold that starts + * mid-list shares the link for one piece at most. Not on a card whose link nothing has + * held: no collective crosses it (one card serving alone), and the checks would cost + * the engine 5% of a link-bound prefill for nothing. */ + const bool yield = (flags & RAD_COPY_YIELD) != 0 && dq->ever_held; + const uint64_t piece = yield ? std::min(kYieldBytes, kSdmaMaxCopy) : kSdmaMaxCopy; + const uint64_t ga = (uint64_t)dq->gate.handle + offsetof(amd_signal_t, value); + const uint32_t gate[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, + (uint32_t)ga, (uint32_t)(ga >> 32), 0u, 1u /* the low bit */, + 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; + uint64_t since = piece; + for (size_t i = 0; rc == RAD_OK && i < dma.size(); ++i) { + const uint64_t bytes = (uint64_t)dma[i].seg->bytes; + for (uint64_t o = 0; rc == RAD_OK && o < bytes; o += piece) { + const uint64_t len = std::min(piece, bytes - o); + const uint64_t sa = dma[i].src + o, da = dma[i].dst + o; + if (yield && since >= piece) { + rc = dma_put(dq, gate, 6); + since = 0; + if (rc != RAD_OK) break; + } + const uint32_t cp[7] = { kSdmaCopy, (uint32_t)(len - 1), 0u, + (uint32_t)sa, (uint32_t)(sa >> 32), + (uint32_t)da, (uint32_t)(da >> 32) }; + rc = dma_put(dq, cp, 7); + since += len; + } + } + if (rc == RAD_OK) { + /* The low half of `out`'s value; the high half is already zero. */ + const uint32_t fence[4] = { kSdmaFence | (3u << 16) /* uncached */, + (uint32_t)oa, (uint32_t)(oa >> 32), 0u }; + rc = dma_put(dq, fence, 4); + } + dma_kick(dq); + } + /* A list the ring could not take is not waited for: the stream would stop on `out` for good. */ + if (rc != RAD_OK) hsa_signal_store_screlease(out->h, 0); + uint64_t idx = 0; + const int br = barrier(s, out->h, hsa_signal_t{0}, HSA_FENCE_SCOPE_SYSTEM, + HSA_FENCE_SCOPE_NONE, &idx); + if (br == RAD_OK) { + /* `in` is read by the engine, which is done with it once `out` is written. */ + in->waiters.emplace_back(s->id, idx); + out->waiters.emplace_back(s->id, idx); + } + sig_retire(in); + sig_retire(out); + dma.clear(); + card = false; + if (br != RAD_OK) return br; + return rc; + }; + for (int i = 0; i < n; ++i) { + const RadCopySeg& g = segs[i]; + if (g.bytes == 0) continue; + if (g.bytes < 0 || !g.src || !g.dst) { + device_set_error("rad_memcpy_list_async: segment %d (%p <- %p, %lld)", i, g.dst, g.src, + (long long)g.bytes); + return RAD_E_INVAL; + } + const void* gd = nullptr; + const void* gs = nullptr; + const Loc ld = locate(g.dst, s, &gd); + const Loc ls = locate(g.src, s, &gs); + /* A peer card's memory is the peer's engine's to copy, and the list keeps to this card. */ + if (capturing() || ld == kPageable || ls == kPageable || ld == kDevPeer || ls == kDevPeer) { + RAD_TRY(flush()); + RAD_TRY(a_memcpy_async(g.dst, g.src, g.bytes, rs)); + continue; + } + card = card || ld == kDevLocal || ls == kDevLocal; + dma.push_back(Dma{&g, (uint64_t)(uintptr_t)gd, (uint64_t)(uintptr_t)gs}); + } + return flush(); +} + +/* A hold or a release is one barrier on the holding stream, completing the gate: it takes effect + * once everything before it on the stream is done, which is when the collective issued after it + * starts, or when the one before it has finished. A recorded pass holds nothing -- a hold only paces + * the lists, and a play issues none. */ +int a_link_hold(RadStream rs, int on) { + Stream* s = ours(rs); + if (!s) { device_set_error("rad_link_hold: not a stream of this backend"); return RAD_E_INVAL; } + if (capturing()) return RAD_OK; + /* Only where lists go to the engine: nothing else polls the gate. */ + DmaQueue* dq = dma_queue_open(s->ord); + if (!dq) return RAD_OK; + std::lock_guard lk(dq->mu); + if (dq->held == (on == 1)) { + device_set_error("rad_link_hold: card %d's link is %s held", s->ord, + on == 1 ? "already" : "not"); + return RAD_E_STATE; + } + /* The book follows the queue: a barrier the queue refused changed nothing. */ + if (on != 2) + RAD_TRY(barrier(s, hsa_signal_t{0}, dq->gate, HSA_FENCE_SCOPE_NONE, HSA_FENCE_SCOPE_NONE)); + dq->held = on == 1; + dq->ever_held = dq->ever_held || on == 1; + return RAD_OK; +} + +int a_dma_lane(int device, char* out, int cap) { + if (device < 0 || device >= kMaxDevices || device >= (int)G().dev.size() || !out || cap <= 0) + return RAD_E_INVAL; + const DmaQueue& q = g_dma[device]; + if (!q.tried.load(std::memory_order_acquire)) + std::snprintf(out, (size_t)cap, "copy lists not used: nothing streams weights onto this card"); + else if (q.ok) + std::snprintf(out, (size_t)cap, "copy lists on DMA engine 0, a queue of this process's own; " + "they give way to the collectives"); + else + std::snprintf(out, (size_t)cap, "copy lists as copy kernels: %s", q.why.c_str()); + return RAD_OK; +} + +void* a_link_gate(RadStream rs) { + Stream* s = ours(rs); + hsa_signal_t* g = s ? gate_signal(s->ord) : nullptr; + return g ? (void*)(uintptr_t)(g->handle + offsetof(amd_signal_t, value)) : nullptr; +} + int a_memset_async(void* dst, int value, int64_t bytes, RadStream rs) { Stream* s = ours(rs); if (!s) { device_set_error("rad_memset_async: not a stream of this backend"); return RAD_E_INVAL; } @@ -2310,12 +3262,18 @@ void* a_alloc(int64_t bytes, int kind) { if (hipGetDevice(&dev) == hipSuccess && !card_has_room(dev, bytes, "rad_dev_alloc")) return nullptr; } - if (!pinned_kind(kind)) return g_hip_alloc(bytes, kind); + if (!pinned_kind(kind)) { + void* p = g_hip_alloc(bytes, kind); + note_alloc(p, bytes, kind); + return p; + } if (bytes <= 0) { device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes); return nullptr; } - return pin_pieces(bytes); + void* p = pin_pieces(bytes); + note_alloc(p, bytes, kind); + return p; } /* Behind the forgetting every free needs (locate's cache). */ @@ -2323,6 +3281,7 @@ void (*g_hip_free)(void*, int) = nullptr; void a_free(void* p, int kind) { loc_forget(); if (!p) return; + note_free(p); if (pinned_kind(kind)) unpin_pieces(p); else if (g_hip_free) g_hip_free(p, kind); } @@ -2417,6 +3376,19 @@ const DeviceBackend* aql_backend_if_present(void) { g_aql.memcpy_2d_async = a_memcpy_2d_async; g_aql.memset_async = a_memset_async; g_aql.memcpy_ranges_async = a_memcpy_ranges_async; + g_aql.memcpy_list_async = a_memcpy_list_async; + g_aql.link_hold = a_link_hold; + g_aql.link_gate = a_link_gate; + g_aql.xp_supported = a_xp_supported; + g_aql.xp_stream_create = a_xp_stream_create; + g_aql.ride = a_ride; + g_aql.ride_wait = a_ride_wait; + g_aql.ride_release = a_ride_release; + g_aql.xp_list = a_xp_list; + g_aql.xp_behind = a_xp_behind; + g_aql.alloc_uncached = a_alloc_uncached; + g_aql.free_uncached = a_free_uncached; + g_aql.dma_lane = a_dma_lane; g_aql.vmem_granularity = a_vmem_granularity; g_aql.vmem_reserve = a_vmem_reserve; g_aql.vmem_release = a_vmem_release; diff --git a/core/device/device.h b/core/device/device.h index 136d3130..409debe2 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -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 diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 01be8ff3..ce184f9b 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -67,13 +67,16 @@ static std::string device_inventory(const DeviceBackend* b) { return s; } +#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP /* COMPUTE WAVE SAVE/RESTORE OFF IS A GPU HANG WAITING FOR AN EVICTION. The driver evicts a * process's queues whenever host memory the card maps is moved or reclaimed under memory pressure, * and a serve with a host pool or a host KV tier maps gigabytes of it. With * amdgpu.cwsr_enable=0 it cannot preempt a running queue and waits for it to drain, which a queue * a serve keeps fed never does: the queue stops inside whatever kernel it was running, MES fails * REMOVE_QUEUE, and the driver resets the card. Said at startup because nothing later can tell - * that hang from a kernel bug. */ + * that hang from a kernel bug -- and said here, as the backend comes up, and not only in the + * startup report: a hang during the load ends the process before the report prints, and the + * tools that bring a backend up (rad-kbench, rad-tune) print no report at all. */ static void warn_cwsr_off() { FILE* f = std::fopen("/sys/module/amdgpu/parameters/cwsr_enable", "r"); if (!f) return; @@ -87,7 +90,6 @@ static void warn_cwsr_off() { "amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)"); } -#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP /* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The * registration hooks are this build's own exported symbols and see every dlopen'ed kernel * library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know @@ -535,6 +537,39 @@ int tape_set_overlap(RadTape t, int i, bool on) { return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED; } bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; } +/* A FAILURE ANSWERED HERE, as "", is not one for the next reader of rad_dev_last_error: that + * reader is reporting a failure of its own and would name this one instead. The slot is put back + * as the call found it. */ +std::string dev_pci_address(int device) { + char buf[64] = { 0 }; + if (!dev()->pci_address) return std::string(); + const std::string before = t_last_error; + if (dev()->pci_address(device, buf, (int)sizeof buf) < 0) { + t_last_error = before; + return std::string(); + } + return buf; +} +std::string dev_dma_lane(int device) { + char buf[256] = { 0 }; + if (!dev()->dma_lane) return std::string(); + const std::string before = t_last_error; + if (dev()->dma_lane(device, buf, (int)sizeof buf) < 0) { + t_last_error = before; + return std::string(); + } + return buf; +} +std::string dev_runtime_version() { + char buf[128] = { 0 }; + if (!dev()->runtime_version) return std::string(); + const std::string before = t_last_error; + if (dev()->runtime_version(buf, (int)sizeof buf) < 0) { + t_last_error = before; + return std::string(); + } + return buf; +} int dev_peer_access(int self, int peer) { if (self == peer) return 1; return dev()->peer_access ? dev()->peer_access(self, peer) : 1; @@ -589,6 +624,55 @@ int rad_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges, int n, RadStream s) { return dev()->memcpy_ranges_async(dst, src, prefix, ranges, n, s); } +int rad_memcpy_list_async(const RadCopySeg* segs, int n, unsigned flags, RadStream s) { + if (const auto f = dev()->memcpy_list_async) return f(segs, n, flags, s); + for (int i = 0; i < n; ++i) RAD_TRY(dev()->memcpy_async(segs[i].dst, segs[i].src, segs[i].bytes, s)); + return RAD_OK; +} +int rad_link_hold(RadStream s, int on) { + if (const auto f = dev()->link_hold) return f(s, on); + return RAD_OK; +} +void* rad_link_gate(RadStream s) { + if (const auto f = dev()->link_gate) return f(s); + return nullptr; +} +int rad_xp_supported(int device) { + const auto* d = dev(); + return d->xp_supported && d->xp_stream_create && d->ride && d->ride_wait && d->ride_release && d->xp_list && + d->xp_behind && d->alloc_uncached && d->free_uncached && d->xp_supported(device); +} +int rad_xp_stream_create(RadStream* out) { + if (const auto f = dev()->xp_stream_create) return f(out); + return RAD_E_UNSUPPORTED; +} +int rad_ride(RadStream s, void** token) { + if (const auto f = dev()->ride) return f(s, token); + return RAD_E_UNSUPPORTED; +} +int rad_ride_wait(RadStream s, void* token) { + if (const auto f = dev()->ride_wait) return f(s, token); + return RAD_E_UNSUPPORTED; +} +void rad_ride_release(void* token, RadStream after, int64_t packets) { + if (const auto f = dev()->ride_release) f(token, after, packets); +} +int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, + uint32_t* done, uint32_t done_val) { + if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val); + return RAD_E_UNSUPPORTED; +} +int64_t rad_xp_behind(int device) { + if (const auto f = dev()->xp_behind) return f(device); + return 0; +} +void* rad_dev_alloc_uncached(int64_t bytes) { + if (const auto f = dev()->alloc_uncached) return f(bytes); + return nullptr; +} +void rad_dev_free_uncached(void* p) { + if (const auto f = dev()->free_uncached) f(p); +} /* Cleared by reading it, per the header. Never null: a caller printing "%s" on a path where * nothing failed should get an empty line, not a segfault. */ diff --git a/core/device/hip.cpp b/core/device/hip.cpp index 0ba4d4e6..2f440bfa 100644 --- a/core/device/hip.cpp +++ b/core/device/hip.cpp @@ -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 */ diff --git a/core/device/host.cpp b/core/device/host.cpp index 87284227..702b7a92 100644 --- a/core/device/host.cpp +++ b/core/device/host.cpp @@ -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, diff --git a/core/diag/checks.cpp b/core/diag/checks.cpp new file mode 100644 index 00000000..0d7c25cb --- /dev/null +++ b/core/diag/checks.cpp @@ -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 +#include +#include +#include + +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* 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 served(const Facts& f) { + std::vector 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* 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* 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* out) { + const auto cs = served(f); + if (cs.size() < 2) return; + std::vector diffs; + auto field = [&](const char* what, auto get, auto show) { + std::map> 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* 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* 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* 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* 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* 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* 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* 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* 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* 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* 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 check(const Facts& f, const RunFacts& r) { + std::vector 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 */ diff --git a/core/diag/diag.h b/core/diag/diag.h new file mode 100644 index 00000000..3cd3c780 --- /dev/null +++ b/core/diag/diag.h @@ -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 +#include +#include + +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* 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 config_rows(const Config& c); + +/* The options the table holds, for a test that every one reaches the report. */ +std::vector 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 chain; /* root port first, the card's own link last */ + std::vector 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 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* 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 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 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 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 check(const Facts& f, const RunFacts& r); + +/* ------------------------------------------------------------------ the report */ +std::string render(const std::vector& config, const std::vector& derived, + const Facts& f, const RunFacts& r, const std::vector& findings); + +/* The same, as a JSON object in text: {"configuration", "derived", "hardware", "findings"}. */ +std::string to_json(const std::vector& config, const std::vector& derived, + const Facts& f, const RunFacts& r, const std::vector& 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* rows, const std::vector& decisions, + std::vector* 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 */ diff --git a/core/diag/report.cpp b/core/diag/report.cpp new file mode 100644 index 00000000..707d489d --- /dev/null +++ b/core/diag/report.cpp @@ -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 + +#include + +namespace rad { +namespace diag { + +void decide(std::vector* 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* rows, const std::vector& decisions, + std::vector* 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(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& config, const std::vector& derived, + const Facts& f, const RunFacts& r, const std::vector& 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(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& config, const std::vector& derived, + const Facts& f, const RunFacts& r, const std::vector& 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 */ diff --git a/core/diag/sysinfo.cpp b/core/diag/sysinfo.cpp new file mode 100644 index 00000000..b7253c77 --- /dev/null +++ b/core/diag/sysinfo.cpp @@ -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 +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 list(const std::string& dir) { + std::vector 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* 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> 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* 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 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 env_names(char* const* env, const char* prefix) { + std::vector 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 */ diff --git a/core/engine.cpp b/core/engine.cpp index 8d13055d..45a91d0a 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -34,12 +34,16 @@ #include #include #include +#include namespace rad { -Engine::Engine(Config cfg) : cfg_(std::move(cfg)) {} +/* The RADIANCE_* names are taken here, before start(): bring-up sets one of its own + * (RADIANCE_GDN_ANCHOR, Engine::configure_kv), and the report lists what the operator set. */ +Engine::Engine(Config cfg) + : cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {} int32_t* Engine::Readback::reserve(int64_t count) { if (count <= n) return p; @@ -61,6 +65,7 @@ Engine::~Engine() { if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED); if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED); + for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED); /* The disk thread first: it reads the host arena and writes the store, both of which go with * the ranks and kv_disk_ below. */ if (pump_) pump_->io.stop(); @@ -79,6 +84,13 @@ Engine::~Engine() { (unsigned long long)r->ctx.route_dropped()); RAD_INFO("%s", r->mover.report().c_str()); } + /* THE TRANSFER STREAM BEFORE THE CONTEXTS. Ctx::shutdown drains the compute streams and then + * frees the arena, but the mover's stream copies into the arena too -- the prefill stager's + * ring is its top, and an idle arena lends its slots to the expert slab -- and is drained only + * when the mover goes, after it. A fill still landing in a lent arena slot at that moment is + * a GPU memory fault on the way out. */ + for (auto& r : ranks_) + if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s); for (auto& r : ranks_) r->ctx.shutdown(); step_state_fini(); ranks_.clear(); @@ -259,8 +271,13 @@ void Engine::tiering_dispatch(Rank& r, int step) { ++r.heat_credited; } + /* NO SWAPS BEHIND A PASS THE STAGER ARMED. Such a step is bound by its own copies -- every + * pooled expert of every routed layer crosses the link on the transfer stream a swap would + * share -- and the turnover slots a swap would land in are filled for it (below). The + * histograms are credited all the same, and the next step that stages nothing swaps on what + * they said. */ std::vector swaps; - if (r.heat.step(&swaps) < 0) return; + if (!r.stager.staged() && r.heat.step(&swaps) < 0) return; for (const Swap& s : swaps) { /* CONTRACT: every unit the engine named is BUSY on the way out, and a proposal that is * silently dropped leaves the pair busy forever. `issue` clears it; `abandon` is what @@ -270,8 +287,25 @@ void Engine::tiering_dispatch(Rank& r, int step) { /* AFTER the swaps, because a swap is what the policy asked for and a fill is what the memory * allows: spending a move record on a fill that the next swap then needs would let a - * boundary the arbiter happens to be moving reorder the engine's own decisions. */ - (void)r.mover.balance(&r.heat); + * boundary the arbiter happens to be moving reorder the engine's own decisions. + * + * Behind a staged pass the turnover slots are filled too: that step swaps nothing, and kept + * free they are residents its stager copies instead -- at TP2 a 160K-token prompt staged + * 9.6% more and ran 3-5% slower. + * + * AND THEY STAY FILLED UNTIL kTurnoverAfter STEPS IN A ROW HAVE STAGED NOTHING, idle ticks + * included. A prompt answered in a token or two -- or a pause before the next one -- would + * otherwise drop them and copy them straight back at the next prompt's first chunk, across the + * link the chunk stages over, and each round trip scatters the lent residents through the + * pool runs the stager coalesces its copies on: at TP2, 26K-token prompts back to back ran + * 33 copies a staged layer that way against 16 held, and the first prompt after a pause up to + * 0.4% slower. A decode run reaches the count in a few steps, and its swaps land in the working + * slots until it does. */ + constexpr int kTurnoverAfter = 4; + r.unstaged_steps = r.stager.staged() ? 0 : r.unstaged_steps + 1; + const bool hold = r.unstaged_steps < kTurnoverAfter; + r.mover.hold_turnover(hold); + (void)r.mover.balance(&r.heat, !hold); } /* ------------------------------------------------------------------ the rank thread */ void Engine::rank_loop(int index) { @@ -318,7 +352,9 @@ void Engine::rank_loop(int index) { * host synchronisation between them: it is more ops on the compute stream and not * a second phase (spec ยง13). */ if (bst >= 0) { - s = r.sampler.run(&r.ctx, r.program.logits_buf, r.tok_buf); + /* The scored rows first: the sampler may rewrite a row in place. */ + if (b->draft_pass == 0 && !score_rows_.empty()) s = issue_scored_rows(r); + if (s >= 0) s = r.sampler.run(&r.ctx, r.program.logits_buf, r.tok_buf); if (s < 0) { RAD_ERR("rank %d step %d: sampler: %s", index, b->step, rad_strerror(s)); step_status_.store(s, std::memory_order_release); @@ -574,6 +610,7 @@ int Engine::step_loop() { so.reqs.push_back(const_cast(e.req)); } so.n_rows = logit_row; + if (const int ss = stage_scored_rows(plan, so); ss < 0) return fail_loop(ss); /* THE SAMPLER'S HOST WORK, staged by this lambda either in front of the ranks or -- by * default, see build_mu_ in engine.h -- underneath them. It touches request state and the @@ -1004,6 +1041,76 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) { return RAD_OK; } +/* THE SCORED ROWS (Request::token_scores): the logits row at a scored prompt's last position, on + * its way to the host before the sampler can rewrite it in place. Three parts, on three threads' + * turns: which rows, decided with the rows themselves and while every rank is parked + * (stage_scored_rows); one copy a row on each rank's own stream, right ahead of its sampler + * (issue_scored_rows); and each request's ids read out of the staging after the step's one wait + * (collect_scored_rows), which is ahead of the commit that finishes the request. A whole row + * crosses, not the ids: one copy of 512 KB at a 128K vocabulary is cheaper than a copy an id. */ +int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { + score_rows_.clear(); + if (embedding_) return RAD_OK; + for (size_t i = 0; i < plan.e.size(); ++i) { + const Request* r = plan.e[i].req; + if (so.first_row[i] < 0 || !r || !r->token_scores || !r->output.empty()) continue; + score_rows_.push_back({ so.first_row[i], r->token_scores.get() }); + } + if (score_rows_.empty()) return RAD_OK; + const int64_t n = (int64_t)score_rows_.size(); + for (auto& rk : ranks_) { + if (n <= rk->score_rows_cap) continue; + if (ranks_.size() > 1) RAD_TRY(rad_dev_set(rk->device)); + if (rk->score_host) rad_dev_free(rk->score_host, RAD_MEM_HOST_PINNED); + const int64_t width = rk->sampler.config().n_vocab_local; + rk->score_host = static_cast( + 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(r.ctx.buf_ptr(r.program.logits_buf)); + if (!logits || !r.score_host) return RAD_E_STATE; + for (size_t k = 0; k < score_rows_.size(); ++k) + RAD_TRY(rad_memcpy_async(r.score_host + (int64_t)k * width, + logits + (int64_t)score_rows_[k].first * width * 4, + width * 4, r.ctx.stream())); + return RAD_OK; +} + +int Engine::collect_scored_rows() { + if (score_rows_.empty()) return RAD_OK; + /* step_end_ fences rank 0's stream; every other rank's copies are fenced here. */ + for (size_t i = 1; i < ranks_.size(); ++i) { + RAD_TRY(rad_dev_set(ranks_[i]->device)); + RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream())); + } + if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device)); + for (size_t k = 0; k < score_rows_.size(); ++k) { + TokenScores& ts = *score_rows_[k].second; + ts.logits.assign(ts.tokens.size(), 0.0f); + for (size_t j = 0; j < ts.tokens.size(); ++j) { + const int64_t t = ts.tokens[j]; + for (auto& rk : ranks_) { + const SamplerConfig& sc = rk->sampler.config(); + if (t < sc.vocab_off || t >= sc.vocab_off + sc.n_vocab_local) continue; + ts.logits[j] = rk->score_host[(int64_t)k * sc.n_vocab_local + (t - sc.vocab_off)]; + break; + } + } + } + score_rows_.clear(); + return RAD_OK; +} + /* One sampled row's logprobs into the step's table, which is sized on the first row that asks. * A ROW WHOSE LOGPROBS CANNOT BE COMPUTED FAILS ITS REQUEST, NOT THE STEP: its numbers are not * finite (RAD_E_INVAL), so its entry is left at token -1 (TokenLogprobs), which the scheduler @@ -1035,6 +1142,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) { RAD_TRY(rad_event_sync(step_end_)); std::memcpy(so.rows.data(), so.rb, (size_t)so.n_rows * sizeof(int32_t)); so.rb = nullptr; + RAD_TRY(collect_scored_rows()); const std::vector& lg = so.lg; const int64_t nv = meta_.n_vocab; if (!lg.empty()) { @@ -1281,6 +1389,10 @@ int Engine::arena_step(const RadBatch* b) { const uint64_t now = rad_mono_ns(); arena_last_ = arena_rows_[(size_t)level]; if (arena_last_ >= arena_floor_) { arena_floor_ = arena_last_; arena_floor_ns_ = now; } + /* Whether the step after this one goes on with a prompt, for the stager to stage that step's + * first layers at this one's end. A step issued ahead is a decode step and the plan the + * scheduler holds is not its own, so it never says so. */ + const bool more = b->phase != RAD_PHASE_DECODE && sched_.prefill_continues(); for (auto& r : ranks_) { const int64_t allow = r->arena_lent[(size_t)level]; if (r->mover.loan(Mover::kLendArena) > allow || @@ -1296,6 +1408,7 @@ int Engine::arena_step(const RadBatch* b) { RAD_TRY(r->ctx.set_level(level)); /* The full plan lends nothing, so its top -- the staging region -- is the step's. */ r->stager.set_full_arena(level == 0); + r->stager.set_next_prefill(more && level == 0); } if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); return RAD_OK; @@ -1602,6 +1715,9 @@ int Engine::serve() { /* NO PREFIX CACHE: an encoder keeps no KV to reuse, and attending both ways means a * shared prefix does not even compute to the same rows. */ cfg_.prefix_cache = false; + prefix_off_why_ = "an embedding model: an encoder keeps no KV to reuse, and attending both " + "ways means a shared prefix does not compute to the same rows"; + decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); RAD_INFO("embedding model: %lld-wide pooled vectors, one step an input, up to %lld " "tokens an input", (long long)pooled_dim_, (long long)cfg_.max_tok); } @@ -1771,6 +1887,7 @@ int Engine::serve() { for (int i = 0; i < cfg_.tp; ++i) rank_threads_.emplace_back([this, i] { rank_loop(i); }); std::thread stepper([this] { step_loop(); }); + if (cfg_.kld()) print_startup_report(RAD_OK); int s = cfg_.kld() ? run_kld() : run_server(); /* Stop the step loop before anything the server owns is destroyed: Request::sink is a raw @@ -1952,9 +2069,13 @@ void on_signal(int) { g_signalled.store(true, std::memory_order_relaxed); } * SamplingParams' own defaults the untruncated floor * * Each source is consulted only if the one above it said nothing at all, so a deployment that - * names a file gets that file's sampler and not a blend of it with the container's. */ + * names a file gets that file's sampler and not a blend of it with the container's. + * + * `stated` and `source`, when given, receive what the source in force read and its name ("" for + * none): gen_sampling_sources turns the two into the reason for each field. */ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool container, - const Config& cfg) { + const Config& cfg, GenSampling* stated = nullptr, + std::string* source = nullptr) { GenSampling g; std::string src; @@ -1999,6 +2120,8 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe const std::string from = src.empty() ? (over.empty() ? "nothing stated it" : "the command line") : src; + if (stated) *stated = g; + if (source) *source = src; RAD_INFO("sampling defaults for requests that send none: %s (from %s%s%s)", GenSampling::describe(sp).c_str(), from.c_str(), over.empty() || src.empty() ? "" : ", overridden by", over.c_str()); @@ -2166,6 +2289,7 @@ int Engine::run_server() { s.experts.staged_units = (int64_t)ms.staged_units; s.experts.staged_bytes = (int64_t)ms.staged_bytes; s.experts.stage_overflow = (int64_t)ms.stage_overflow; + s.experts.stage_copies = (int64_t)ms.stage_copies; s.experts.flex_bytes = ranks_[0]->mover.flex_used_bytes(); s.experts.flex_capacity = ranks_[0]->mover.flex_offered_bytes(); /* THE HEAT ENGINE'S OWN TALLY, which answers a different question from the @@ -2290,6 +2414,7 @@ int Engine::run_server() { server::ServerOptions o{}; o.embedding_model = embedding_; + o.decision_type = rad_meta_gets(&meta_, "decision.type", ""); o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name : meta_.name && *meta_.name ? meta_.name : "radiance"; o.host = cfg_.host; @@ -2299,12 +2424,27 @@ int Engine::run_server() { /* `n` fans one request out over the batch, so a server that runs more sequences a step takes * more choices a request; the floor keeps a small batch from refusing what it would queue. */ o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max(o.max_n, cfg_.max_seqs); + if (cfg_.max_n <= 0) + decide("--max-n", std::to_string(o.max_n), "the larger of 8 and --max-num-seqs"); o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; o.model_path = cfg_.model; o.default_reasoning_effort = cfg_.reasoning_effort; o.reasoning_effort_map = cfg_.reasoning_effort_map; o.default_thinking_budget = cfg_.thinking_token_budget; - o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); + { + /* THE FOUR SAMPLER DEFAULTS A FILE CAN STATE, where no flag set them: the value served and, + * field by field, the file or metadata it came from. */ + GenSampling stated; + std::string src; + o.default_sampling = + resolve_sampling_defaults(meta_, file_ != nullptr, cfg_, &stated, &src); + for (const GenFieldSource& f : gen_sampling_sources(stated, src, o.default_sampling, cfg_)) + decide(f.flag, f.value, f.why); + } + if (cfg_.served_model_name.empty()) + decide("--served-model-name", o.model_id, + meta_.name && *meta_.name ? "the name the container states" + : "the container states no name"); o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value(); /* An embedding model samples nothing, so it has no logprobs to give. */ o.supports_logprobs = !embedding_ && ranks_[0]->sampler.has_logprobs(); @@ -2323,7 +2463,10 @@ int Engine::run_server() { o.max_stop_bytes = cfg_.max_stop_bytes; o.default_template_kwargs = cfg_.chat_template_kwargs; o.reasoning_format = cfg_.reasoning_format; - o.n_threads = cfg_.http_threads; + o.n_threads = server::idle_workers(cfg_.http_threads); + if (cfg_.http_threads <= 0) + decide("--http-threads", std::to_string(o.n_threads), + "one a hardware thread, at least 4"); o.read_timeout_s = cfg_.http_read_timeout_s; o.write_timeout_s = cfg_.http_write_timeout_s; o.keep_alive_timeout_s = cfg_.http_keep_alive_timeout_s; @@ -2339,6 +2482,9 @@ int Engine::run_server() { /* Per request, not once: the dump carries OpInfo::issued, which only becomes true once the * run phase has run. See ServerOptions::graph_json. */ o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); }; + /* Read again for a request, from a reading at most a second old (Engine::diagnostics_json): + * the links and clocks it reports are only telling under load. */ + o.diagnostics_json = [this] { return diagnostics_json(); }; /* MEDIA, WHEN THE PROGRAM DECLARED AN ENCODER. The processor reads its geometry from the * container and the encoder states the one it was built for; the two meet at the patch width @@ -2361,6 +2507,14 @@ int Engine::run_server() { * A TOKEN-BUDGET PROCESSOR (Gemma 4's) sizes images and frames by soft tokens, not pixel * bands: the band flags would do nothing on it, so they are refused by name, and the * budgets come from --image-tokens and --video-max-frame-tokens. */ + /* LFM2-VL's processor takes pictures only, so the video flags would do nothing on it. */ + if (vc.family == mm::Family::Lfm2 && + (cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames || + cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) { + RAD_ERR("media: this model's processor takes pictures, not video, so the --video-* " + "flags do nothing on it"); + return RAD_E_INVAL; + } if (vc.family == mm::Family::Gemma4) { if (cfg_.image_min_pixels || cfg_.image_max_pixels || cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames) { @@ -2417,15 +2571,33 @@ int Engine::run_server() { return RAD_E_INVAL; } mm_proc = std::make_unique(); - RAD_TRY(mm_proc->init(vc, [&tok_bridge](const std::string& t) { - return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false); - })); + const int pi = mm_proc->init( + vc, + [&tok_bridge](const std::string& t) { + return tok_bridge.encode(t, /*add_special=*/false, /*parse_special=*/false); + }, + [this](const std::string& t) { return vocab_->find(t); }); + if (pi < 0) { + RAD_ERR("media: the container's processor configuration does not fit this deployment " + "or this vocabulary (a marker it names is missing, or a segment is larger " + "than one encoder pass): %s", rad_strerror(pi)); + return pi; + } o.allow_image = (encd.modalities & RAD_MM_IMAGE) != 0; o.allow_video = (encd.modalities & RAD_MM_VIDEO) != 0; if (!mm::decoder_available()) RAD_WARN("media: the '%s' encoder is loaded but this build has no media decoder " "(RAD_WITH_FFMPEG), so every media part will be refused", ranks_[0]->program.encoder_name.c_str()); + else if (mm_proc->config().family == mm::Family::Lfm2) + RAD_INFO("media: images through '%s'; a picture resizes to %lld..%lld pixels, or one " + "past %g times that is cut into %d..%d tiles of %d pixels a side plus a " + "thumbnail; %lld patches a pass", ranks_[0]->program.encoder_name.c_str(), + (long long)mm_proc->config().image_min_pixels, + (long long)mm_proc->config().image_max_pixels, + mm_proc->config().max_pixels_tolerance, mm_proc->config().min_tiles, + mm_proc->config().max_tiles, mm_proc->config().tile, + (long long)encd.max_patches); else if (mm_proc->config().family == mm::Family::Gemma4) RAD_INFO("media: %s%s through '%s'; an image becomes at most %d soft tokens (a " "request's image_tokens may ask for 70..1120), a video %d a frame at %.3g " @@ -2483,6 +2655,8 @@ int Engine::run_server() { : "takes no images or video"); server::Server srv(d, o); + if (cfg_.max_queued_requests <= 0) + decide("--max-queued-requests", std::to_string(srv.queue_cap()), "8 x --max-num-seqs"); /* A TEMPLATE DEFAULT THE TEMPLATE REFUSES is a 400 on every chat request that leaves it to * the default, found by the first caller rather than the operator. --chat-template-kwargs @@ -2530,6 +2704,7 @@ int Engine::run_server() { why.c_str()); return RAD_E_INVAL; } + print_startup_report(RAD_OK); if (embedding_) RAD_INFO("serving on http://%s:%d (/v1/embeddings; completions and chat are 501)%s", o.host.c_str(), o.port, o.api_key.empty() ? "" : " -- a bearer key is required"); diff --git a/core/engine.h b/core/engine.h index ea820186..37cd6455 100644 --- a/core/engine.h +++ b/core/engine.h @@ -22,6 +22,7 @@ #pragma once #include "rad_core.h" #include "build/startup.h" +#include "diag/diag.h" #include "mem/hostarena.h" #include "sched/mem_iface.h" #include "sched/scheduler.h" @@ -70,6 +71,20 @@ public: const Program& program() const; const Config& config() const { return cfg_; } + /* THE STARTUP REPORT (core/diag/diag.h): every option with the value in force and its source, + * the machine, and what on it costs speed or correctness. serve() prints it before it starts + * listening with `status` RAD_OK; main prints it with the error start() or serve() stopped + * with, so a log of a server that never came up still says what it was running on and what + * it had decided -- and ends with that error again on an E line, because the report's lines + * now follow the one that said it and a reader of the log's tail would see only them. */ + void print_startup_report(int status); + /* The same, as JSON, with the hardware read again -- a card's link and clock are only + * meaningful under load, and /diagnostics is how they are read while a request runs. The + * reading is reused for a second, and covers the power-management files of the serving + * cards only (hardware_facts). */ + std::string diagnostics_json() const; + bool startup_report_printed() const { return report_printed_; } + private: /* One thread per tensor-parallel rank, each owning one device. No IPC, no shared-memory * handshake, no serialisation between ranks -- which is most of what a Python engine spends @@ -218,6 +233,14 @@ private: * the device cannot reach until the whole forward pass has run, and that pass is the time the * walk hides inside. This is a one-shot gate per step, reset while the ranks are parked at the * release, so there is no window in which a rank can read a stale ready flag. */ + /* THIS STEP'S SCORED ROWS (Request::token_scores): a logits row and the result it fills. + * Written by the scheduler thread while the ranks are parked, read by them during the step, + * consumed by collect_step. */ + std::vector> score_rows_; + int stage_scored_rows(const StepPlan& plan, const StepOut& so); + int issue_scored_rows(Rank& r); + int collect_scored_rows(); + std::mutex build_mu_; std::condition_variable build_cv_; bool build_ready_ = false; @@ -384,6 +407,49 @@ private: /* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */ std::string engine_info() const; + /* ---- what the startup report says about the run (engine_diag.cpp). `decisions_` holds each + * value startup resolved and why, recorded where it was resolved; the rest are the facts a + * check needs that only startup saw. */ + std::vector 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 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 dev_ids_; + std::string runtime_version_; + void identify_devices(const std::vector& 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. */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index d1bd2222..717b63cc 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -20,6 +20,7 @@ #include "rad_plugin.h" #include "mem/vram_budget.h" #include "runtime/arena.h" +#include "runtime/xprefetch.h" #include "sample/gbnf.h" #include "sched/scheduler.h" #include "text/tokenizer.h" @@ -166,9 +167,14 @@ static MissReport miss_report(const Program& p, bool host_backend) { * an APU machine -- and of those the ones sharing the first one's arch, and prints only what that * choice DID, rather than reprinting the backend's inventory. Which devices the backend shows at * all is the runtime's to say: ROCR_VISIBLE_DEVICES and HIP_VISIBLE_DEVICES pick them. */ -static int usable_devices(std::vector* 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* out, std::string* inventory, std::string* note, + std::vector* 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 all; @@ -177,6 +183,7 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st for (int i = 0; i < n; ++i) { RadDeviceProps p{}; if (rad_dev_props(i, &p) < 0) continue; + (*names)[(size_t)i] = p.name; const bool igpu = dev_integrated(i); inv += fmt("%s%d:%s%s", i ? " " : "", i, p.arch, igpu ? "(integrated)" : ""); all.push_back({ i, p.arch, igpu }); @@ -635,6 +642,13 @@ int Engine::resolve_table_placement(const std::vector& facts, RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(), table_placement_name(ng), cfg_.ngram_placement == TablePlacement::Auto ? " (auto)" : "", ng_why.c_str()); + decide("--embedding-placement", table_placement_name(emb), + emb_max > 0 ? fmt("the table is %s a rank: %s", humanb(emb_max).c_str(), emb_why.c_str()) + : emb_why); + has_ngram_ = ngram_bytes > 0; + decide("--ngram-placement", ngram_bytes > 0 ? table_placement_name(ng) : "n/a", + ngram_bytes > 0 ? fmt("the table is %s: %s", humanb(ngram_bytes).c_str(), ng_why.c_str()) + : std::string("this model has no n-gram table")); return RAD_OK; } @@ -906,6 +920,10 @@ int Engine::declare() { cfg_.n_spec = 0; cfg_.prefix_cache = false; if (cfg_.mm_max_patches < 0) cfg_.mm_max_patches = 0; + decide("--num-speculative-tokens", "0", "the KL mode scores the trunk's own rows"); + prefix_off_why_ = + "the KL mode: a prefix hit would start a document past positions the reference holds"; + decide("--no-prefix-cache", "prefix caching off", prefix_off_why_); } if (cfg_.n_spec < 0) { RadArchProbe pb{}; @@ -916,6 +934,9 @@ int Engine::declare() { "(--num-speculative-tokens N overrides it)", cfg_.n_spec); else RAD_INFO("speculation: off -- this container carries no draft head"); + decide("--num-speculative-tokens", std::to_string(cfg_.n_spec), + cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point" + : "this container carries no draft head"); } /* THE ENCODER'S PASS SIZE, resolved the same way and for the same reason: whether there is a * tower to size is a property of the model file. A container says so (`radiance.encoder`, @@ -946,6 +967,13 @@ int Engine::declare() { if (cfg_.mm_max_patches == 0 && tower) RAD_INFO("media: off -- the checkpoint has a vision tower but this container was " "converted without its weights; convert again to serve images and video"); + decide("--mm-max-patches", std::to_string(cfg_.mm_max_patches), + cfg_.mm_max_patches > 0 + ? "the model carries a vision tower: 16384 patches is a 2048 x 2048 image, the " + "largest one encoder pass takes" + : tower ? "the checkpoint has a vision tower but this container was converted " + "without its weights" + : "the model carries no vision tower"); } std::vector st(ranks_.size(), RAD_OK); @@ -1217,6 +1245,21 @@ int Engine::plan() { for (RadStream s : q) if (s) rad_stream_destroy(s); } f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0); + /* THE EXPERT PREFETCH'S STREAM, RING AND BUFFERS, where it can be on: a placement that + * keeps experts in a pinned pool, not --deterministic, on a backend with a DMA engine to + * spare for it (asked before the free figure below, so its queue there is already held). */ + WeightFootprint xwf; + weight_footprint(r->program, &xwf, TablePlacement::Vram, TablePlacement::Disk, device_is_host(), + file_ != nullptr); + if (xwf.routed && xwf.expert_unit_max > 0 && !cfg_.deterministic && + (cfg_.placement == "auto" || cfg_.placement == "expert_tiered") && rad_xp_supported(r->device)) { + /* Counted as Ctx::bind_routing counts the routed layers: past the trunk where a head is. */ + int64_t nl = r->program.meta.n_layers; + for (const WeightInfo& w : r->program.weights) + if (w.decl.group.expert >= 0) nl = std::max(nl, (int64_t)w.decl.group.layer + 1); + f.n_queues += 1; + f.prefetch = xp_device_bytes(xwf.expert_unit_max, nl); + } RadDeviceProps props{}; rad_dev_props(r->device, &props); f.capacity = props.vram_bytes; @@ -1326,6 +1369,10 @@ int Engine::plan() { VramBudget vb; RAD_TRY(vram_budget_resolve(cfg_, facts, &vb)); if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str()); + decide("vram split", + fmt("weights %s (experts %s of it), KV cache %s, a card", humanb(vb.weights).c_str(), + humanb(vb.experts).c_str(), humanb(vb.kv).c_str()), + vb.report); /* The staging region the budget took out of the experts, above everything the buffer plan * placed -- so it is at the top of the arena, the part the smaller levels lend. */ if (vb.stage > 0) @@ -1478,6 +1525,21 @@ int Engine::plan() { if (s < 0) return s; /* The slab the planner filled is the pool the mover will fill: one split, read twice. */ RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes())); + if (r->index == 0) { + decide("--placement", strategy_name(r->plan.strategy), + r->plan.strategy_why.empty() ? std::string("as asked") : r->plan.strategy_why); + const int64_t host = r->plan.totals.bytes[(int)Tier::HostPinned] + + r->plan.totals.bytes[(int)Tier::HostPageable]; + decide("weights by tier", + fmt("VRAM %s, host pool %s, container on disk %s, mapped %s (rank 0)", + humanb(r->plan.totals.bytes[(int)Tier::VRAM]).c_str(), humanb(host).c_str(), + humanb(r->plan.totals.bytes[(int)Tier::SSD]).c_str(), + humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()), + r->plan.embedding_host_used > 0 + ? fmt("the host pool holds the token embedding's %s beside the weights " + "placed there", humanb(r->plan.embedding_host_used).c_str()) + : std::string()); + } /* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a * re-split rank whose grown weights pool took every weight still holds it. Said, because * the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */ @@ -2511,6 +2573,10 @@ int Engine::load_weights() { "(%s); it is read from the container%s", w.name.c_str(), into, why.c_str(), card ? " by the host gather" : ""); cfg_.ngram_resolved = TablePlacement::Disk; + decide("--ngram-placement", "disk", + fmt("auto chose a %s copy in RAM, which could not be made (%s); the " + "rows are read from the container%s", into, why.c_str(), + card ? " by the host gather" : "")); } /* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows * out of it, and the only reason a weight is on this tier at all is that it is far @@ -2765,6 +2831,14 @@ int Engine::configure_kv() { /* Resolved once, for the cache below and for Scheduler::init later. Resolving it separately in * each is how the two come to disagree, and the interval is the field where that shows. */ RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_)); + if (geo_.checkpoint_interval != cfg_.checkpoint_interval) + decide("--checkpoint-interval", + geo_.checkpoint_interval ? std::to_string(geo_.checkpoint_interval) : "0 (none)", + geo_.checkpoint_interval + ? fmt("rounded up to a multiple of %lld tokens, the step quantum (the attention " + "block and the linear-state chunk), so a checkpoint is a legal chunk split", + (long long)geo_.quantum) + : std::string("the model keeps no linear state to checkpoint")); /* ONE BLOCK TABLE SERVES EVERY RANK (serve() checks it), so every rank carves the SAME number * of paged blocks. The ranks' pools are not the same size under an uneven tensor-parallel * split -- a rank with more delta-net heads holds more recurrent state, a rank with zero @@ -3231,8 +3305,13 @@ int Engine::start() { * are each attributed to the card they are about. At tp 1 there is nothing to disambiguate. */ log_rank_tags(cfg_.tp > 1); - int s = usable_devices(&devs, &inventory, &devnote); + std::vector dev_names; + int s = usable_devices(&devs, &inventory, &devnote, &dev_names); + /* Before any refusal below, so a report printed for a startup that stopped here still joins + * the runtime's devices to the machine's cards. */ + identify_devices(dev_names); if (!devnote.empty()) RAD_WARN("device: %s", devnote.c_str()); + devnote_ = devnote; if (s < 0) { RAD_ERR("no usable device"); return s; } if ((int)devs.size() < cfg_.tp) { @@ -3242,12 +3321,29 @@ int Engine::start() { } RAD_TRY(read_metadata()); + if (cfg_.max_ctx == 0) + decide("--max-model-len", std::to_string(meta_.n_ctx_train), + "the model's training context (--max-model-len 0)"); RAD_TRY(load_vocab()); /* The cards are chosen, so a kernel library's device code is checked against the ones the * ranks will run on and not against whichever device the backend happens to list first. */ rad_tools_registry().set_code_device(devs[0]); rad_tools_registry().set_no_device_code(device_is_host()); RAD_TRY(load_plugins()); + { + /* THE LIBRARIES THAT LOADED, in the order that decides selection: what --kernels named, or + * every library the home holds when it named none. */ + std::string libs; + for (const PluginId& p : plugins_.kernels) + libs += (libs.empty() ? "" : ",") + p.name + (p.version.empty() ? "" : "@" + p.version); + decide("--kernels", libs.empty() ? "none" : libs, + cfg_.kernel_hierarchy.empty() + ? "every kernel library under --radiance-home, in the loader's order (a reference " + "implementation last); architecture plugin " + plugins_.arch_plugin + + (plugins_.arch_version.empty() ? "" : "@" + plugins_.arch_version) + : "the libraries named, in that order; architecture plugin " + plugins_.arch_plugin + + (plugins_.arch_version.empty() ? "" : "@" + plugins_.arch_version)); + } ranks_.clear(); for (int i = 0; i < cfg_.tp; ++i) { @@ -3291,6 +3387,15 @@ int Engine::start() { const bool forced_off = cfg_.p2p == RAD_P2P_OFF; if (forced_off) p2p = 0; rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p); + p2p_measured_ = (int)p2p; + p2p_blocked_ = blocked; + if (cfg_.tp > 1) + decide("--p2p", p2p ? "peer to peer" : "through pinned host memory", + p2p ? "the driver reports every pair of the ranks' cards can reach the other's memory" + : forced_off ? "--p2p off" + : "the driver reports no peer access between cards " + blocked); + else + decide("--p2p", "n/a", "one rank: no collective crosses a card"); if (cfg_.tp > 1) { if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to " "peer)", cfg_.tp); @@ -3317,6 +3422,27 @@ int Engine::start() { * implementation is a container that will serve at reference speed, and that is a decision the * operator makes rather than one the engine discovers three minutes into a load. */ RAD_TRY(rad_gate_reference_kernels(ranks_[0]->program, cfg_.accept_reference_kernels, "serve")); + { + /* WHAT SELECTION CHOSE, in two lines a reader can compare across machines: how many of the + * declared op bands each library serves, and the attention rows by name -- the family whose + * choice moves with the card, the head width and the context. */ + std::map by_lib; + std::set attn; + for (const OpInfo& op : ranks_[0]->program.ops) + for (const Band& b : op.bands) + for (int dm = 0; dm < RAD_N_DOMAINS; ++dm) { + const KernelRow* row = b.dom[dm].row; + if (!row || !row->info) continue; + ++by_lib[row->plugin + (dm == RAD_DOMAIN_HOST ? " (host)" : "")]; + if (row->info->family && !std::strcmp(row->info->family, "attn")) + attn.insert(op.op + " -> " + row->info->name); + } + std::string libs, rows; + for (const auto& [lib, n] : by_lib) libs += fmt("%s%s %d", libs.empty() ? "" : ", ", lib.c_str(), n); + for (const std::string& a : attn) rows += (rows.empty() ? "" : "\n") + a; + decide("kernel selection", libs.empty() ? "none" : libs + " op bands", + rows.empty() ? std::string() : "attention:\n" + rows); + } RAD_TRY(plan()); RAD_TRY(load_weights()); @@ -3360,11 +3486,11 @@ int Engine::start() { (char*)r->ctx.arena_base() + r->program.arena_stage_off, r->program.arena_stage_bytes, top_level + 1)); if (r->stager.enabled() && r->index == 0) - RAD_INFO("prefill staging: two %s buffers at the top of the arena; a step of " - "more than %lld tokens copies the next of %zu routed layers' pooled " - "experts onto the card while the one before it runs", - humanb(r->stager.buffer_bytes()).c_str(), (long long)top_level, - r->stager.n_layers()); + RAD_INFO("prefill staging: a %s ring at the top of the arena; a step of more " + "than %lld tokens copies the pooled experts of %zu routed layers onto " + "the card up to %d layers ahead of the layers that read them", + humanb(r->stager.ring_bytes()).c_str(), (long long)top_level, + r->stager.n_layers(), (int)PrefillStager::lead()); } /* THE FILE STAGER, wherever the plan put a routed expert on the file tier -- static plan * or dynamic, since a file-tier unit has no other address. */ @@ -3411,6 +3537,16 @@ int Engine::start() { RAD_TRY(r->mover.lend_from(Mover::kLendKV, strips)); if (r->mover.flex_capacity() > 0) lending_ = true; } + /* THE NEXT-LAYER EXPERT PREFETCH, wherever the placement left experts in a pinned pool for a + * routed layer's GEMMs to read across the link (core/runtime/xprefetch.h). Its stream and ring are + * in the VRAM budget (xp_device_bytes, Engine::plan). Not under --deterministic, where nothing moves. */ + if (!cfg_.deterministic) + for (auto& r : ranks_) { + RAD_TRY(rad_dev_set(r->device)); + uint64_t lo[kXpMaxPools], hi[kXpMaxPools], st[kXpMaxPools]; + const int n = r->mover.pool_ranges(lo, hi, st, kXpMaxPools); + if (n > 0) r->ctx.xp_open(lo, hi, st, n); + } (void)rad_dev_set(ranks_[0]->device); /* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends @@ -3430,6 +3566,15 @@ int Engine::start() { } const int64_t mlen = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train; const int64_t lent = lending_ ? ranks_[0]->mover.flex_capacity() : 0; + if (bytes > 0) + decide("kv cache", + fmt("%s a card: %lld tokens, %.1f sessions at %lld", humanb(bytes).c_str(), + (long long)tokens, mlen > 0 ? (double)tokens / (double)mlen : 0.0, + (long long)mlen), + fmt("%s of it is per-sequence state; %s", humanb(state).c_str(), + lent > 0 ? fmt("up to %s is lent to the experts while no request holds it", + humanb(lent).c_str()).c_str() + : "nothing is lent: it is all the cache's")); if (bytes > 0) RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at " "%lld -- with every block it lends the experts taken back; %s of that is " diff --git a/core/engine_diag.cpp b/core/engine_diag.cpp new file mode 100644 index 00000000..0493489d --- /dev/null +++ b/core/engine_diag.cpp @@ -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 + +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& 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 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(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 rows = diag::config_rows(cfg_); + std::vector derived; + diag::merge(&rows, decisions_, &derived); + const diag::Facts f = hardware_facts(false); + const diag::RunFacts r = run_facts(status < 0); + const std::vector 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 rows = diag::config_rows(cfg_); + std::vector derived; + diag::merge(&rows, decisions_, &derived); + diag::Facts f; + { + std::lock_guard 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 */ diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp index 8fd00e33..fe683731 100644 --- a/core/engine_mm.cpp +++ b/core/engine_mm.cpp @@ -83,18 +83,19 @@ int Engine::run_encodes() { int64_t np = 0; while (i < mine.size()) { mm::Item& it = *mine[i]; - const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; - if (seg_p > max_p) { - RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld", - (long long)seg_p, (long long)max_p); - return RAD_E_STATE; + const int32_t first = seg; + for (; seg < it.n_seg; ++seg) { + const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg); + if (seg_p > max_p) { + RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld", + (long long)seg_p, (long long)max_p); + return RAD_E_STATE; + } + if (np + seg_p > max_p) break; + np += seg_p; } - const int64_t room = (max_p - np) / seg_p; - const int32_t can = (int32_t)std::min(it.n_seg - seg, room); - if (can <= 0) break; - parts.push_back({ &it, seg, can }); - np += (int64_t)can * seg_p; - seg += can; + if (seg == first) break; + parts.push_back({ &it, first, seg - first }); if (seg == it.n_seg) { ++i; seg = 0; } } if (parts.empty()) break; @@ -127,9 +128,10 @@ int Engine::run_encodes() { int64_t row = 0; for (const BatchBuilder::EncoderPart& p : parts) { mm::Item& it = *const_cast(p.item); - const int64_t rows = (int64_t)p.n_seg * it.seg_rows; + const int64_t first = it.row_at(p.seg0); + const int64_t rows = it.row_at(p.seg0 + p.n_seg) - first; const int64_t bytes = rows * n_embd * (int64_t)sizeof(uint16_t); - RAD_TRY(rad_memcpy_async(it.embd.data() + (int64_t)p.seg0 * it.seg_rows * n_embd, + RAD_TRY(rad_memcpy_async(it.embd.data() + first * n_embd, static_cast(out) + row * n_embd * (int64_t)sizeof(uint16_t), bytes, r0.ctx.stream())); diff --git a/core/engine_priv.h b/core/engine_priv.h index 6c18c8b9..eaaf85ad 100644 --- a/core/engine_priv.h +++ b/core/engine_priv.h @@ -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 diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index f53d5fae..ff3f7880 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -234,6 +234,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { if (const char* mt = gs("model_type")) { out->arch.clear(); for (const char* p = mt; *p; ++p) if (*p != '_') out->arch += *p; + /* LFM2-VL is LFM2 with a vision tower, and unlike Qwen's VL releases it names the wrapper + * rather than the text model. One plugin serves both, the way one serves a Qwen3.5 with + * or without its tower; `model_type` itself stays in the free-form keys. */ + if (out->arch == "lfm2vl") out->arch = "lfm2"; } if (const char* nm = gs("_name_or_path")) out->name = nm; @@ -257,7 +261,7 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { m.n_expert = gi("num_experts", gi("num_local_experts", 0)); m.n_expert_used = gi("num_experts_per_tok", 0); m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0; - m.rms_eps = (float)gf("rms_norm_eps", 1e-6); + m.rms_eps = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6)); /* LFM2: norm_eps */ m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0)); /* The rotary's scaling stays in the free-form keys with its type beside it; the architecture * reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would diff --git a/core/gen_config.cpp b/core/gen_config.cpp index 7764b126..5510df2f 100644 --- a/core/gen_config.cpp +++ b/core/gen_config.cpp @@ -41,6 +41,29 @@ std::string GenSampling::describe(const SamplingParams& sp) { return buf; } +std::vector gen_sampling_sources(const GenSampling& stated, const std::string& src, + const SamplingParams& served, const Config& cfg) { + std::vector 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); } diff --git a/core/gen_config.h b/core/gen_config.h index 1977d72f..67b8d0e7 100644 --- a/core/gen_config.h +++ b/core/gen_config.h @@ -25,6 +25,7 @@ #include #include +#include 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 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); diff --git a/core/main.cpp b/core/main.cpp index 240d512e..8e27f065 100644 --- a/core/main.cpp +++ b/core/main.cpp @@ -15,8 +15,20 @@ int main(int argc, char** argv) { rad::Engine engine(std::move(cfg)); s = engine.start(); - if (s < 0) return 1; /* start() already said what and why */ + if (s < 0) { + /* start() already said what and why; the report adds what it was running on and what it + * had decided by then, which is what a log of a server that never came up is read for. */ + engine.print_startup_report(s); + return 1; + } if (engine.config().debug_graph) return engine.dump(); - return engine.serve() < 0 ? 1 : 0; + s = engine.serve(); + if (s < 0) { + /* A refusal between start() and listening (a chat template the defaults cannot render, a + * thinking budget the model cannot hold) also ends a server that never came up. */ + if (!engine.startup_report_printed()) engine.print_startup_report(s); + return 1; + } + return 0; } diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 7a405221..85852af8 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -60,6 +60,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg freeb = std::min(freeb, f.free); b.arena = std::max(b.arena, f.arena); b.staging = std::max(b.staging, f.staging); + b.prefetch = std::max(b.prefetch, f.prefetch); if ((int64_t)f.n_queues * f.queue_bytes > b.queues) { b.queues = (int64_t)f.n_queues * f.queue_bytes; b.n_queues = f.n_queues; @@ -111,7 +112,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg /* What is left after the terms nobody gets to spend. */ b.drift = kDriverDrift; b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging + - b.queues); + b.queues + b.prefetch); if (b.claimable < 0) { b.report = fmt( @@ -123,6 +124,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " activation arena %10s (buffer plan + kernel scratch)\n" " step staging %10s (block tables, media and KV tier staging)\n" " hardware queues %10s (%d at %s each, measured)\n" + " expert prefetch %10s (its ring of expert units and buffers)\n" " ------------------------------\n" " SHORT BY %10s\n" "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " @@ -130,7 +132,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(), humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), - humanb(-b.claimable).c_str()); + humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str()); if (log) RAD_ERR("%s", b.report.c_str()); if (out) *out = b; return RAD_E_NOMEM; @@ -271,7 +273,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg * the headroom. */ const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB; const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues - - b.stage - granted; + b.prefetch - b.stage - granted; const double ela = b.elastic > 0 ? (double)b.elastic : 1.0; b.report = fmt( "VRAM budget, per card:\n" @@ -282,6 +284,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " step staging %10s the step batch's block tables and media staging, and the\n" " KV tiers' copy staging\n" " hardware queues %10s %d a card at %s each, measured: the engine's streams\n" + " expert prefetch %10s the next-layer prefetch's ring of expert units and buffers\n" " %-18s %10s %s\n" " ------------------------------\n" " claimable %10s\n" @@ -299,7 +302,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " could not place\n", humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), - humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), + humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), humanb(b.prefetch).c_str(), shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(), shared ? "integrated graphics: this memory is the host's" : "left unclaimed on purpose", diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 3673c53c..4e327f60 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -81,6 +81,9 @@ struct VramFacts { * times the ring). */ int n_queues = 0; int64_t queue_bytes = 0; + /* THE NEXT-LAYER EXPERT PREFETCH's ring of expert units and its buffers (xprefetch.h), where it + * will be on; its stream is one of `n_queues`. */ + int64_t prefetch = 0; int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */ int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */ /* weight_footprint() for this rank, which under tensor parallel is already this card's even @@ -111,6 +114,7 @@ struct VramBudget { int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0; int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */ int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */ + int64_t prefetch = 0; /* the expert prefetch's ring and buffers */ int n_queues = 0; int64_t queue_bytes = 0; int64_t claimable = 0; /* after the fixed terms above */ diff --git a/core/mm/item.cpp b/core/mm/item.cpp index 18794c6f..ced6ad86 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -21,11 +21,13 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { } /* Merge-block order inverted: a patch's index within its segment is * ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */ - const int64_t seg = (int64_t)grid_h * grid_w; const int32_t merge = grid_h / rows_h; - const int64_t bw = grid_w / merge; + int32_t s = 0; + while (s + 1 < n_seg && patch_at(s + 1) <= first) ++s; for (int64_t k = 0; k < count; ++k) { - const int64_t within = (first + k) % seg; + while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s; + const int64_t within = first + k - patch_at(s); + const int64_t bw = seg_w(s) / merge; const int64_t in_col = within % merge; const int64_t in_row = (within / merge) % merge; const int64_t blk = within / (merge * merge); @@ -33,8 +35,8 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { const int64_t col = (blk % bw) * merge + in_col; planes[k] = (int32_t)row; planes[count + k] = (int32_t)col; - planes[2 * count + k] = grid_h; - planes[3 * count + k] = grid_w; + planes[2 * count + k] = seg_h(s); + planes[3 * count + k] = seg_w(s); } } diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index b1890d40..e4701ba0 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -30,7 +30,65 @@ static bool soft_budget_ok(int32_t n) { return n == 70 || n == 140 || n == 280 || n == 560 || n == 1120; } +/* A flag a container flattened from JSON: `true`/`false`, or a number. */ +static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) { + const char* v = rad_meta_gets(&m, key, nullptr); + if (!v || !*v) return dflt; + if (!std::strcmp(v, "true")) return true; + if (!std::strcmp(v, "false")) return false; + return std::strtol(v, nullptr, 10) != 0; +} + int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { + /* LFM2-VL states its processor twice, in config.json and in processor_config.json's + * image_processor; the latter is what the reference processor reads, so it goes first. */ + if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) { + family = Family::Lfm2; + auto key = [](const char* k) { return std::string("processor.image_processor.") + k; }; + auto geti = [&](const char* k, int64_t dflt) { + return rad_meta_geti(&m, key(k).c_str(), rad_meta_geti(&m, k, dflt)); + }; + auto getb = [&](const char* k, bool dflt) { + return meta_bool(m, key(k).c_str(), meta_bool(m, k, dflt)); + }; + patch = (int32_t)geti("encoder_patch_size", rad_meta_geti(&m, "vision_config.patch_size", 0)); + merge = (int32_t)geti("downsample_factor", 0); + temporal = 1; + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + if (patch <= 0 || merge <= 0 || tok_image < 0) { + if (why) *why = "the container states no LFM2-VL processor geometry (encoder_patch_size, " + "downsample_factor, image_token_id)"; + return RAD_E_NOTFOUND; + } + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = geti("min_image_tokens", 64) * f2; + image_max_pixels = geti("max_image_tokens", 256) * f2; + video_min_pixels = image_min_pixels; /* no video; consistent for check() */ + video_max_pixels = image_max_pixels; + /* The markers around a picture and before each tile are what the model was trained on; + * a checkpoint that turns them off spells its pictures differently, which is not served. */ + if (!meta_bool(m, "use_image_special_tokens", true)) { + if (why) *why = "use_image_special_tokens is off; this processor writes LFM2-VL's " + "picture markers and serves only the checkpoints that read them"; + return RAD_E_UNSUPPORTED; + } + const bool split = getb("do_image_splitting", true); + min_tiles = split ? (int32_t)geti("min_tiles", 2) : 1; + max_tiles = split ? (int32_t)geti("max_tiles", 10) : 1; + tile = (int32_t)geti("tile_size", 512); + use_thumbnail = getb("use_thumbnail", true); + max_pixels_tolerance = rad_meta_getf(&m, key("max_pixels_tolerance").c_str(), + rad_meta_getf(&m, "max_pixels_tolerance", 2.0)); + max_segment_patches = geti("max_num_patches", 1024); + if (!read_triple(m, key("image_mean").c_str(), mean)) read_triple(m, "preprocessor.image_mean", mean); + if (!read_triple(m, key("image_std").c_str(), stdv)) read_triple(m, "preprocessor.image_std", stdv); + std::string bad; + if (check(&bad) < 0) { + if (why) *why = "the container's LFM2-VL processor configuration is inconsistent: " + bad; + return RAD_E_INVAL; + } + return RAD_OK; + } const char* mt = rad_meta_gets(&m, "vision_config.model_type", ""); if (mt && !std::strcmp(mt, "gemma4_vision")) { family = Family::Gemma4; @@ -138,6 +196,16 @@ int VisionConfig::check(std::string* why) const { if (max_frames < min_frames) return no("max_frames " + std::to_string(max_frames) + " is below min_frames " + std::to_string(min_frames)); + if (family == Family::Lfm2) { + if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor()) + return no("the tiling (min_tiles " + std::to_string(min_tiles) + ", max_tiles " + + std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) + + ") is not a range of whole merged patches"); + if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0) + return no("max_pixels_tolerance and max_num_patches must be positive"); + for (int c = 0; c < 3; ++c) + if (!(stdv[c] > 0.0f)) return no("image_std must be positive"); + } if (family == Family::Gemma4) { if (!soft_budget_ok(image_soft_tokens)) return no("the image soft-token budget " + std::to_string(image_soft_tokens) + @@ -307,20 +375,21 @@ inline double bicubic(double x) { return 0.0; } -inline uint8_t clip8(int32_t v) { - const int32_t s = v >> kPrec; +inline uint8_t clip8(int32_t v, int prec) { + const int32_t s = v >> prec; return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s)); } /* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize` - * a row. */ + * a row, `*prec` their fraction bits: PIL's fixed 22, or -- `torch` -- ATen's per-axis choice, the + * most bits at which the largest weight still fits an int16. */ int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, - std::vector* kk) { + std::vector* 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 k((size_t)ksize); + std::vector k((size_t)ksize), w((size_t)out_size * (size_t)ksize, 0.0); bounds->assign((size_t)out_size * 2, 0); kk->assign((size_t)out_size * (size_t)ksize, 0); for (int xx = 0; xx < out_size; ++xx) { @@ -341,24 +410,32 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector* 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 bh, kh, bv, kv; - const int ksh = coeffs(in.w, w, &bh, &kh); - const int ksv = coeffs(in.h, h, &bv, &kv); + int ph = kPrec, pv = kPrec; + const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph); + const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv); /* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */ const int y_first = bv[0]; @@ -380,16 +457,16 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { for (int xx = 0; xx < w; ++xx) { const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; const int32_t* k = kh.data() + (size_t)xx * ksh; - int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0; + int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0; for (int x = 0; x < xmax; ++x) { const uint8_t* p = row + (size_t)(x + xmin) * 3; s0 += p[0] * k[x]; s1 += p[1] * k[x]; s2 += p[2] * k[x]; } - o[xx * 3 + 0] = clip8(s0); - o[xx * 3 + 1] = clip8(s1); - o[xx * 3 + 2] = clip8(s2); + o[xx * 3 + 0] = clip8(s0, ph); + o[xx * 3 + 1] = clip8(s1, ph); + o[xx * 3 + 2] = clip8(s2, ph); } } src = &tmp; @@ -404,20 +481,34 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { const int32_t* k = kv.data() + (size_t)yy * ksv; uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3; for (int xx = 0; xx < src->w; ++xx) { - int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0; + int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0; for (int y = 0; y < ymax; ++y) { const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3; s0 += p[0] * k[y]; s1 += p[1] * k[y]; s2 += p[2] * k[y]; } - o[xx * 3 + 0] = clip8(s0); - o[xx * 3 + 1] = clip8(s1); - o[xx * 3 + 2] = clip8(s2); + o[xx * 3 + 0] = clip8(s0, pv); + o[xx * 3 + 1] = clip8(s1, pv); + o[xx * 3 + 2] = clip8(s2, pv); } } } +void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { + resize_bicubic_impl(in, w, h, out, false); +} + +void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) { + resize_bicubic_impl(in, w, h, out, true); +} + +void cap_area(const Frame& in, int64_t max_pixels, Frame* out) { + if (max_pixels <= 0 || (int64_t)in.w * in.h <= max_pixels) { *out = in; return; } + const double scale = std::sqrt((double)max_pixels / ((double)in.w * in.h)); + resize_bicubic(in, std::max(1, (int)(in.w * scale)), std::max(1, (int)(in.h * scale)), out); +} + /* ================================================================== patches */ namespace { @@ -437,6 +528,10 @@ void content_key(const Item& it, uint64_t* hi, uint64_t* lo) { (uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w); uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : it.kind == Kind::Video ? 2u : 3u); + /* The tiling, when the segments have sizes of their own: the same patches cut differently + * are different encoder inputs. */ + for (const Item::Segment& sg : it.segments) + a = mix64(a ^ ((uint64_t)(uint32_t)sg.h << 32 | (uint32_t)sg.w)) + (uint64_t)sg.patch0; const uint8_t* p = reinterpret_cast(it.pixels.data()); const size_t n = it.pixels.size() * sizeof(uint16_t); size_t i = 0; @@ -536,10 +631,34 @@ void finish_item(const VisionConfig& c, Item* it) { /* ================================================================== the processor */ int Processor::init(const VisionConfig& cfg, - std::function(const std::string&)> encode_text) { + std::function(const std::string&)> encode_text, + std::function 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)(cfg.tile / cfg.patch) * (cfg.tile / cfg.patch), + cfg.image_max_pixels / ((int64_t)cfg.patch * cfg.patch)); + if (seg > cfg.max_patches || seg > cfg.max_segment_patches) return RAD_E_INVAL; + encode_text_ = std::move(encode_text); + return RAD_OK; + } if (cfg.family == Family::Gemma4) { /* A budget is a patch count, and an image is one segment of one pass. */ if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches || @@ -559,9 +678,133 @@ int Processor::init(const VisionConfig& cfg, return RAD_OK; } +void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px, + int64_t* oh, int64_t* ow) { + const double f = factor; + int64_t hb = std::max(factor, pyround((double)h / f) * factor); + int64_t wb = std::max(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(factor, (int64_t)std::floor((double)h / beta / f) * factor); + wb = std::max(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(patch, pyround((double)h / factor) * factor); + const int64_t wb = std::max(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* 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(); + 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* out, std::string* why) const { const VisionConfig& c = cfg_; if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why); + if (c.family == Family::Lfm2) return image_lfm2(f, out, why); int64_t h = 0, w = 0; RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, &h, &w, why)); @@ -745,7 +988,7 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin } int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, - std::shared_ptr* out, std::string* why) const { + std::shared_ptr* out, std::string* why, int64_t max_pixels) const { if (image_tokens != 0) { if (cfg_.family != Family::Gemma4) { if (why) *why = "this model's processor sizes an image by its pixels, not by a token " @@ -762,6 +1005,11 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, } Frame f; RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why)); + if (max_pixels > 0 && (int64_t)f.w * f.h > max_pixels) { + Frame capped; + cap_area(f, max_pixels, &capped); + f = std::move(capped); + } if (cfg_.family == Family::Gemma4) return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why); return image_from(f, out, why); @@ -778,6 +1026,10 @@ std::vector sample_cb(const VideoInfo& info, const void* user) { int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const { + if (cfg_.family == Family::Lfm2) { + if (why) *why = "this model's processor takes pictures, not video"; + return RAD_E_UNSUPPORTED; + } Video v; const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames, cfg_.family == Family::Gemma4 }; @@ -1056,19 +1308,24 @@ void PromptMedia::layout() { for (size_t pi = 0; pi < items.size(); ++pi) { const Placed& p = items[pi]; const Item& it = *p.item; + const int32_t m = it.rows_h > 0 ? it.grid_h / it.rows_h : 1; for (int32_t s = 0; s < it.n_seg; ++s) { const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s]; pos += run_tok - tok; /* the text in front of the run counts up */ + const int32_t rh = it.segments.empty() ? it.rows_h : it.seg_h(s) / m; + const int32_t rw = it.segments.empty() ? it.rows_w : it.seg_w(s) / m; RopeLayout::Run r; r.tok = (int32_t)run_tok; - r.n = it.seg_rows; - r.w = it.rows_w; + r.n = (int32_t)(it.row_at(s + 1) - it.row_at(s)); + r.w = rw; r.base = (int32_t)pos; - pos += std::max(it.rows_h, it.rows_w); - tok = run_tok + it.seg_rows; + r.flat = it.rope_1d; + /* A grid advances the rotary by its longer side; a 1-D run by its length. */ + pos += it.rope_1d ? r.n : std::max(rh, rw); + tok = run_tok + r.n; r.shift = (int32_t)(pos - tok); r.item = (int32_t)pi; - r.row0 = s * it.seg_rows; + r.row0 = (int32_t)it.row_at(s); rope.runs.push_back(r); } } diff --git a/core/mm/processor.h b/core/mm/processor.h index 92cfec31..ab50b2eb 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -49,8 +49,14 @@ enum class Kind { Image, Video, Audio }; * fits the soft-token budget (budget * pooling^2), aspect ratio kept; patches (y, x, * channel) as 2 * (u / 255) - 1, the reference model's own input scaling; a video is * frames sampled at `fps` (at most `max_frames`, thinned evenly), each its own segment - * at the per-frame budget, each spelled placeholders with no timestamp. */ -enum class Family { QwenVL, Gemma4 }; + * at the per-frame budget, each spelled placeholders with no timestamp. + * Lfm2 LFM2-VL's: a picture within its token budget (times a tolerance) is resized whole -- + * sides multiples of patch * merge, pixels within the budget's band -- and one past it + * is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its + * own, followed by the whole picture at the budgeted size as a thumbnail. Patches + * (y, x, channel) normalised by the mean and deviation, resized with torchvision's + * fixed-point bicubic; images only, and the tokens rotate at their positions. */ +enum class Family { QwenVL, Gemma4, Lfm2 }; struct VisionConfig { Family family = Family::QwenVL; @@ -69,6 +75,11 @@ struct VisionConfig { float mean[3] = { 0.5f, 0.5f, 0.5f }; float stdv[3] = { 0.5f, 0.5f, 0.5f }; int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1; + /* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */ + int32_t min_tiles = 0, max_tiles = 0, tile = 0; + bool use_thumbnail = false; + double max_pixels_tolerance = 0.0; + int64_t max_segment_patches = 0; /* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an * image is one segment and a segment is never split, so no image may resize past it, and the @@ -139,7 +150,30 @@ struct Item { /* An audio clip's REAL feature frames; the rest of its `grid_h` are the zero frames that make * it whole output rows. 0 for a picture or a video. */ int32_t valid = 0; - int64_t n_rows() const { return (int64_t)n_seg * seg_rows; } + + /* SEGMENTS OF THEIR OWN SIZE, when an item's segments differ -- an LFM2-VL picture is its + * tiles and a thumbnail -- each `h` x `w` patches from patch `patch0` on. Empty, every segment + * is grid_h x grid_w (a picture, a video's temporal groups, an audio clip). The accessors + * below are the only way the rest of the engine reads a segment, so both forms look alike. */ + struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; }; + std::vector segments; + /* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not + * on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */ + bool rope_1d = false; + + int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; } + int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; } + /* Segment s's first patch and first output row; s == n_seg is the end of the item. */ + int64_t patch_at(int32_t s) const { + if (segments.empty()) return (int64_t)s * grid_h * grid_w; + return s >= n_seg ? n_patch : segments[(size_t)s].patch0; + } + int64_t row_at(int32_t s) const { + if (segments.empty()) return (int64_t)s * seg_rows; + const int64_t m = rows_h > 0 ? grid_h / rows_h : 1; + return patch_at(s) / (m * m); + } + int64_t n_rows() const { return row_at(n_seg); } /* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of * placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one: @@ -175,6 +209,7 @@ struct RopeLayout { int32_t shift = 0; /* rotary minus token index for the text AFTER the run */ int32_t item = 0; /* which of PromptMedia::items the run belongs to */ int32_t row0 = 0; /* the item's encoder row that its first token takes */ + bool flat = false; /* Item::rope_1d: the run's tokens rotate at their positions */ }; std::vector runs; /* ascending */ @@ -195,7 +230,7 @@ struct RopeLayout { const Run* r = last_at(i); if (!r) { out[0] = out[1] = out[2] = (int32_t)i; return; } const int64_t k = i - r->tok; - if (k < r->n) { + if (k < r->n && !r->flat) { out[0] = r->base; out[1] = r->base + (int32_t)(k / r->w); out[2] = r->base + (int32_t)(k % r->w); @@ -231,14 +266,18 @@ struct PromptMedia { class Processor { public: /* `encode_text` tokenises the timestamp text between a video's groups: plain text, no - * special tokens added and none parsed. */ - int init(const VisionConfig& cfg, std::function(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(const std::string&)> encode_text, + std::function token_id = {}); const VisionConfig& config() const { return cfg_; } /* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a - * processor that sizes images by pixels refuses a non-zero one. */ + * processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first + * scales a larger picture down to that area (PIL's bicubic), as a caller's own pipeline may. */ int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out, - std::string* why) const; + std::string* why, int64_t max_pixels = 0) const; int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; /* The pieces, exposed for the test suite: an already-decoded picture or frame list. */ @@ -257,6 +296,10 @@ public: private: int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, std::string* why) const; + int image_lfm2(const Frame& f, std::shared_ptr* 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 tok_tiles_; int video_gemma4(const Video& v, std::shared_ptr* out, std::string* why) const; VisionConfig cfg_{}; @@ -288,6 +331,24 @@ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_p /* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a * horizontal pass into an 8-bit intermediate and then a vertical one. */ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); +/* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the + * coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */ +void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out); +/* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels + * within [min_px, max_px] where the rounding left them outside. */ +void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px, + int64_t* oh, int64_t* ow); +/* LFM2-VL's test for a picture to tile: its sides rounded to whole merged patches cover more than + * `max_px` times `tolerance` pixels. */ +bool lfm2_too_large(int64_t h, int64_t w, int32_t patch, int32_t factor, int64_t max_px, + double tolerance); +/* A picture over `max_pixels` scaled down to that area with PIL's bicubic, sides truncated; any + * other picture as it is. */ +void cap_area(const Frame& in, int64_t max_pixels, Frame* out); +/* LFM2-VL's tile grid for a w x h picture: (columns, rows) of the min..max-tile ratio nearest its + * aspect, the larger grid of two equally near when the picture fills over half of it. */ +void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, + int32_t* cols, int32_t* rows); } /* namespace mm */ } /* namespace rad */ diff --git a/core/place/heat.cpp b/core/place/heat.cpp index 9ee56410..dcb296a5 100644 --- a/core/place/heat.cpp +++ b/core/place/heat.cpp @@ -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* 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 diff --git a/core/place/heat.h b/core/place/heat.h index 72d773d4..04d742e9 100644 --- a/core/place/heat.h +++ b/core/place/heat.h @@ -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 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 rank_hot_, rank_cold_; std::vector n_hot_, n_cold_, m_of_; /* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */ diff --git a/core/place/mover.cpp b/core/place/mover.cpp index 2de52953..fffe8773 100644 --- a/core/place/mover.cpp +++ b/core/place/mover.cpp @@ -90,6 +90,7 @@ Mover::~Mover() { * that name the events below and the copies into and out of the memory below, so each of * those goes only once nothing queued refers to it. */ if (mover_) { + (void)flush_moves(); rad_stream_sync(mover_); rad_stream_destroy(mover_); } @@ -138,6 +139,11 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P "it is a test path and not a deployment."); unit_.assign(plan.units.size(), UnitState{}); + copying_.assign(plan.units.size(), 0); + pool_layer_.assign(plan.classes.size(), {}); + donors_.assign(plan.classes.size(), DonorRank{}); + n_layers_ = 0; + for (const MoveUnit& mu : plan.units) n_layers_ = std::max(n_layers_, mu.layer + 1); pools_.clear(); pools_.resize(plan.classes.size()); @@ -162,6 +168,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P static_need = us.static_off + mu.bytes; } else if (mu.tier == Tier::HostPinned) { us.pool_slot = n_pool[(size_t)mu.slab_class]++; + pool_layer_[(size_t)mu.slab_class].push_back(mu.layer); } else if (mu.tier == Tier::HostPageable) { us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT); pageable_need = us.static_off + mu.bytes; @@ -170,7 +177,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P } /* ---- allocate ------------------------------------------------------------------------- */ - int64_t total_shadow = 0; + int64_t total_shadow = 0, total_turn = 0; for (size_t c = 0; c < plan.classes.size(); ++c) { const SlabClass& sc = plan.classes[c]; ClassPools& cp = pools_[c]; @@ -193,6 +200,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P * lend_from() adds them once it is. */ cp.n_fixed = slab_slots; cp.n_work = shadow + sc.n_stage; + cp.n_turn = std::min(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(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(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& units, char* dst, int64_t cap, RadEvent after, RadEvent done, std::vector* 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& units, const StageSpan* spans, int n_spans, + RadEvent after, RadEvent done, std::vector* 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 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& 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& 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>* 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& 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& a, const std::pair& 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> freed; + std::vector 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", diff --git a/core/place/mover.h b/core/place/mover.h index 0c28ba3b..37d889a3 100644 --- a/core/place/mover.h +++ b/core/place/mover.h @@ -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 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()); + held_[(size_t)s] = 1; + ++n_held_; + --n_usable_; + return s; + } /* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in * quarantine -- or -1. A scan down from the segment's mark. */ int64_t top_held(int k = 0) const { @@ -356,6 +376,13 @@ struct MoverConfig { * layer. */ int max_lead_dispatches = 2; + /* Lent slots kept free for swaps to land in, a slab class (planner.h's + * RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges + * nothing for them: they are the KV cache's memory, free only while it lends. A class whose + * shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a + * small loan is not left emptier than it is filled. */ + int turnover_slots = RAD_PLACE_TURNOVER_SLOTS; + /* The container, for the file tier. Empty means there is no file tier and a unit the planner * put there is an error rather than a slow path. */ std::string container_path; @@ -393,10 +420,16 @@ struct MoverStats { /* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going * back to the host tier was a change of address. Counted inside `demotions` as well. */ uint64_t dropped = 0; + /* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to + * (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled + * or shrank. */ + uint64_t donated = 0, relocated = 0; uint64_t ssd_reads = 0, ssd_bytes = 0; /* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and - * pooled units a buffer had no room left for -- those were read across the link in place. */ + * pooled units a buffer had no room left for -- those were read across the link in place. + * `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */ uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0; + uint64_t stage_copies = 0; /* The file stager's reads (stage_file_units): routed layers read from the container, the * units and bytes they carried, the preads that carried them, and the host time spent inside * those reads and waiting for a window's copies to drain -- the two halves of what a step @@ -547,6 +580,13 @@ public: int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); } int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); } int64_t flex_capacity() const; + /* The lent slots the fill leaves free for the engine to swap into + * (MoverConfig::turnover_slots), summed over the slab classes. */ + int64_t turnover_slots() const { + int64_t n = 0; + for (const ClassPools& cp : pools_) n += cp.n_turn; + return n; + } /* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that * covers every slot carved from it. The slots were carved no deeper than the units the host * pool holds, so a loan this size already has room for every unit that could move -- more VRAM @@ -556,14 +596,38 @@ public: /* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the * half-swaps the heat engine never proposes, because its decision is a COMPARISON and a * comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams - * across the link is VRAM bought and wasted on every step, so every free slot is filled in - * one call, hottest units first, and the copies run at the rate the link carries them. */ - int balance(HeatEngine* heat); + * across the link is VRAM bought and wasted on every step, so every free slot past the + * turnover slots is filled in one call, hottest units first, and the copies run at the rate + * the link carries them. The turnover slots are left free because the engine's swaps land in + * them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer + * than the working and turnover slots are free, the coldest lent units are dropped until + * enough are -- a change of address, never a copy. + * + * `turnover` false treats the turnover slots as room, filled like any other: a step bound by + * its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is + * one its stager does not copy. The next call with it true drops them back out. */ + int balance(HeatEngine* heat, bool turnover = true); /* balance() for a rank with no step to ride on. Retires what has landed and fills what is * free, so a loan made while the server is idle is filled before the next request rather - * than by it. Only while the rank thread is parked. */ + * than by it -- the turnover slots too while they are held. Only while the rank thread is + * parked. */ int idle_tick(HeatEngine* heat); + /* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt + * and the few steps after it (Engine::tiering_dispatch). */ + void hold_turnover(bool held) { hold_turnover_ = held; } + /* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */ + int pool_ranges(uint64_t* lo, uint64_t* hi, uint64_t* stride, int max) const { + int n = 0; + for (const ClassPools& cp : pools_) + if (cp.pool_dev && cp.stride > 0 && n < max) { + lo[n] = (uint64_t)(uintptr_t)cp.pool_dev; + hi[n] = lo[n] + (uint64_t)cp.pool.size() * (uint64_t)cp.stride; + stride[n] = (uint64_t)cp.stride; + ++n; + } + return n; + } /* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier * unit that has not been staged. */ @@ -587,10 +651,20 @@ public: * unstage_units publish those units at their pool slots again. The caller must already have * ordered the next writer of `dst` behind every op that read the copies; this * only moves the address the NEXT issue resolves. + * stage_need the room stage_units would fill with `units` given room for all of them, so + * a caller packing several layers into one region can size each one's share; + * `largest`, when not null, gets the room the largest of those units takes. + * + * The span form packs into up to two stretches, the second taking what the first has no + * room left for: a ring's place that wraps past the region's end is two. */ + struct StageSpan { char* dst; int64_t cap; }; int stage_units(const std::vector& units, char* dst, int64_t cap, RadEvent after, RadEvent done, std::vector* staged); + int stage_units(const std::vector& units, const StageSpan* spans, int n_spans, + RadEvent after, RadEvent done, std::vector* staged); void unstage_units(const std::vector& staged); + int64_t stage_need(const std::vector& units, int64_t* largest = nullptr) const; /* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) -------- * @@ -629,18 +703,22 @@ private: * mid-layer, because placement would then depend on host timing and stop being reproducible. */ struct Move { enum class State { Free, Copying, Published, Quarantine }; - /* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is + /* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is * the exact prefetch bringing an offloaded unit into a slot. Release is the same slot * going back once the declared order says nothing will read it again this step -- it * copies nothing and still needs the quarantine, because the barrier is about kernels * already issued and not about bytes in flight. Drop is a unit in a lent slot going back - * to the host copy it kept: no copy either, and the same quarantine for the same reason. */ - enum class Kind { Promote, Demote, Stage, Release, Drop }; + * to the host copy it kept: no copy either, and the same quarantine for the same reason. + * Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers + * for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and + * `to_slot` the one it lands in. */ + enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate }; State state = State::Free; Kind kind = Kind::Promote; int32_t unit = -1; int64_t slab_slot = -1; int64_t pool_slot = -1; + int64_t to_slot = -1; RadEvent ev = nullptr; }; @@ -672,6 +750,11 @@ private: int64_t stride = 0; int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */ int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */ + int64_t n_turn = 0; /* lent slots kept free past those: the fill stops short + * of them and balance() drops lent units to rebuild them + * (MoverConfig::turnover_slots) */ + int64_t n_donated = 0; /* units in lent slots that gave their host copy away + * (Mover::donor_slot); at most n_turn of them */ std::vector 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 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 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 move_segs_; + std::vector move_recs_; + int queue_move_copy(void* dst, const void* src, int64_t bytes, int rec); + int flush_moves(); std::vector pools_; std::vector unit_; std::vector 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 copying_; + /* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */ + std::vector> 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>> by_layer; }; + std::vector 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> 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. */ diff --git a/core/place/planner.cpp b/core/place/planner.cpp index e7a413db..b37ec0c3 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -1243,6 +1243,17 @@ int Planner::assign(Plan* p) { else if (has_conditional) s = Strategy::ExpertTiered; else s = Strategy::LayerOffload; p->strategy = s; + p->strategy_why = + s == Strategy::AllVram + ? fmt("%s of weights fit the %s weights pool", humanb(total).c_str(), + humanb(p->vram_budget).c_str()) + : s == Strategy::ExpertTiered + ? fmt("%s of weights against a %s weights pool: routed experts, read only when " + "selected, are what spills to host memory", humanb(total).c_str(), + humanb(p->vram_budget).c_str()) + : fmt("%s of weights against a %s weights pool and no routed experts to spill: " + "whole layers are offloaded", humanb(total).c_str(), + humanb(p->vram_budget).c_str()); RAD_DEBUG("placement: auto chose %s (%s of weights against a %s budget)", strategy_name(s), humanb(total).c_str(), humanb(p->vram_budget).c_str()); } diff --git a/core/place/planner.h b/core/place/planner.h index 899f9cf3..3e21bb30 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -176,6 +176,18 @@ struct SlabClass { #define RAD_PLACE_FILE_WINDOWS 4 #define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20) +/* THE HEAT ENGINE'S MOVE BUDGET: swaps a STEP, a slab class. HeatParams::moves_per_step defaults + * to it, and the free slots below are sized from it, because the two are one quantity: a swap + * that finds no free slot does not happen. + * + * The engine proposes once a step (Engine::tiering_dispatch), and a step routes every layer, so + * the budget has to cover the whole model's turnover. Replaying the routing of a mixed workload + * through the engine's policy at Qwen3.8-Flash-Next TP1 (40% of the experts resident), the hit + * rate on decode rows is 63.8% at 8 a step, 74.1% at 32, 77.1% at 64 and 77.8% at 128 -- and an + * oracle that knows every future routing, held to the same 64 swaps a step, reaches 78.0%. Past + * this the move rate, not the ranking, is what bounds the hit rate. */ +#define RAD_PLACE_MOVES_PER_STEP 64 + /* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one * and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h). * @@ -184,12 +196,28 @@ struct SlabClass { * explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic * placement costs a few resident units, and the plan report prints exactly how many. * - * 32 is far past where the knob stops mattering, and MORE is the wrong end of the problem: extra - * shadows raise the move rate and run SLOWER, because more copies in flight contend with the - * zero-copy tier for the same link. The quarter-of-the-slab cap only ever binds on a slab too - * small for the number to be meaningful. */ + * THESE ARE THE SLOTS THE ENGINE CAN ALWAYS COUNT ON, and the expert floor charges for them + * (expert_vram_floor), so every slot here is one the KV cache can never have. The rest of what the + * move budget needs is RAD_PLACE_TURNOVER_SLOTS, taken out of the cache's loan instead. The + * quarter-of-the-slab cap only ever binds on a slab too small for the number to be meaningful. */ #define RAD_PLACE_SHADOW_SLOTS 32 +/* THE TURNOVER SLOTS: free slab slots the mover keeps out of a loan (Mover::lend_from), past the + * shadow slots, by filling the loan's slots only up to them. A swap holds a slot for about three + * steps -- the copies go out behind the step that proposed them, the next step's retire publishes + * them, and the slot the demotion left comes back only once the compute stream has passed the + * quarantine recorded after that publish -- so a budget of RAD_PLACE_MOVES_PER_STEP needs three + * times as many free slots, and with fewer the budget is smaller than it says. At 64 a step, + * replaying the routing with 32 slots in all reaches 65.9% against 77.9% with 192. + * + * Out of the loan because that costs the cache nothing: a lent slot left free is one the experts + * were borrowing anyway, and charged to the expert floor instead the same slots would come out of + * the cache's largest size. When the cache takes memory back, the free slots at the loan's top go + * first and the mover rebuilds them by dropping its coldest lent units, which still have their + * host copies (Mover::balance); only once nothing is lent does the move rate fall back to what + * the shadow slots alone allow. */ +#define RAD_PLACE_TURNOVER_SLOTS (3 * RAD_PLACE_MOVES_PER_STEP - RAD_PLACE_SHADOW_SLOTS) + /* ------------------------------------------------------------------ per-weight result */ struct Placement { Tier tier = Tier::VRAM; @@ -206,6 +234,8 @@ class Plan { public: int rank = 0, world_size = 1; Strategy strategy = Strategy::Auto; + /* Why `strategy` is the one it is, when `auto` chose it; empty when it was asked for. */ + std::string strategy_why; /* False under Config::deterministic. Dynamic placement sets which experts are resident and * residency sets the summation order, so identical inputs do not give identical outputs diff --git a/core/place/stager.cpp b/core/place/stager.cpp index 2d44e40e..e9aa6af4 100644 --- a/core/place/stager.cpp +++ b/core/place/stager.cpp @@ -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 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 */ diff --git a/core/place/stager.h b/core/place/stager.h index 00e1f52e..e4433ec3 100644 --- a/core/place/stager.h +++ b/core/place/stager.h @@ -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 #include #include @@ -60,22 +102,29 @@ public: ~PrefillStager() override; /* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at - * `region` as two buffers. `min_rows` is the smallest pass it arms for. Leaves it disabled -- + * `region` as the ring. `min_rows` is the smallest pass it arms for. Leaves it disabled -- * enabled() false -- when the plan has no routed layer with a pooled unit to stage. */ int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes, int64_t min_rows); /* Per pass, before it is released: whether the step runs at the arena's full plan, which is - * when the buffers are not lent. */ + * when the region is not lent. */ void set_full_arena(bool full) { full_ = full; } + /* Per step, before it is released: whether the step after it goes on with a prompt in a pass + * this stager arms for, so this step's trunk pass stages that pass's first layers. */ + void set_next_prefill(bool more) { next_prefill_ = more; } bool enabled() const { return !layers_.empty(); } - int64_t buffer_bytes() const { return cap_; } + int64_t ring_bytes() const { return ring_; } /* The smallest pass (in tokens) the stager arms for: a step under it reads every pooled * expert of a routed layer synchronously. The scheduler keeps a held-back prefill chunk at * or above it (Scheduler::set_stage_rows). */ int64_t min_rows() const { return min_rows_; } size_t n_layers() const { return layers_.size(); } + /* Whether the last trunk pass armed: its routed layers' pooled experts were copied onto the + * card through the ring. A draft pass leaves it as the trunk pass set it. */ + bool staged() const { return staged_; } + static constexpr int32_t lead() { return kLead; } bool begin_pass(const RadBatch* b) override; int before_op(rad_op h, RadStream s, bool* resync) override; @@ -92,33 +141,62 @@ private: std::vector first_of_; /* by op: the layer whose first op it is, or -1 */ std::vector 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 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 ring_order_; /* places in the ring, oldest first; retired ones stay until lapped */ + std::vector 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 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 started_; /* by layer: staged (or tried) this pass */ - int32_t pass_kind_ = 0; - int32_t last_issued_ = -1; - std::map 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 ------------------------------------- diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 27c58866..8b6e0ef1 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -455,6 +455,7 @@ int Registry::commit_(Staged& s, int order) { if (q->decode) enc_add_decoder(q->decode); } const auto concurrent = dl_fn(s.handle, "rad_kernel_concurrent"); + const auto collective = dl_fn(s.handle, "rad_kernel_collective"); for (const auto& sr : staged_rows) { KernelRow row; row.info = sr.first; @@ -462,6 +463,9 @@ int Registry::commit_(Staged& s, int order) { row.plugin_order = order; row.index = sr.second; row.concurrent = concurrent && concurrent(sr.second) != 0; + const int coll = collective ? collective(sr.second) : 0; + row.collective = coll != 0; + row.releases_link = coll == 2; row.reference = p.reference; rows_.push_back(row); } diff --git a/core/rad_core.h b/core/rad_core.h index c485409f..f121ea92 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -53,6 +53,11 @@ struct KernelRow { * their operands and their scratch, so one may run beside another that shares none of those * bytes. False when the plugin does not say. */ bool concurrent = false; + /* The plugin's rad_kernel_collective answer for this row: its launches exchange data with + * the other ranks' cards, and -- `releases_link` -- end the engine's hold on the link + * themselves, through `link_gate`. False when the plugin does not say. */ + bool collective = false; + bool releases_link = false; /* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */ bool reference = false; }; @@ -573,6 +578,17 @@ struct SamplingParams { std::shared_ptr 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 tokens; + std::vector logits; +}; + struct Request { uint64_t id = 0; std::vector prompt; @@ -640,6 +656,19 @@ struct Request { * it; the logits buffer is sized for it there and nowhere else. */ bool score = false; + /* THE END OF A PREFIX OTHER REQUESTS WILL START FROM, in prompt tokens; 0 for none. On a + * model with linear state (convolutions, a recurrence) a prefix hit resumes from a state + * checkpoint, and those are written only on the checkpoint interval and at a long prompt's + * tail -- neither is where a shared head of a few hundred tokens ends. The scheduler ends a + * prefill chunk here, rounded down to its quantum, and writes a checkpoint as it does on the + * interval (Scheduler::plan_chunk), so the requests that follow reuse the whole head. + * /v1/systemone sets it on the first question of several over one state. */ + int64_t checkpoint_at = 0; + + /* NON-NULL: read the raw logits at these ids at the prompt's last position (TokenScores). + * The request still samples the one token max_tokens allows; the caller discards it. */ + std::shared_ptr token_scores; + /* AN EMBEDDING REQUEST: the whole prompt in ONE step, never split -- an encoder that attends * both ways cannot be fed half its input -- and finished at that step with its pooled vector * in the sink (Sink::embedding). Nothing is generated and nothing is emitted. Only an @@ -964,6 +993,12 @@ struct Config { * output to say so, so it is refused unless this says otherwise -- deliberately, and by a * flag with `debug` in its name (startup.h, rad_gate_reference_kernels). */ bool accept_reference_kernels = false; + + /* WHERE EACH OPTION THE OPERATOR SET CAME FROM, keyed by the option table's spelling: + * "command line", or the environment variable that supplied it. An option absent here took + * its default or was resolved at startup -- the distinction the startup report + * (core/diag/diag.h) prints beside every value. */ + std::map given; }; } /* namespace rad */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 41e3465e..3ec3afb8 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -4,6 +4,7 @@ */ #include #include "ctx.h" +#include "xp_state.h" #include "../device/device.h" #include @@ -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>(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& v = + gate_params_.emplace_back(ip.args.p, ip.args.p + ip.args.n_p); + RadParam q{}; + q.key = "link_gate"; + q.kind = RAD_P_INT; + q.ival = (long long)(uintptr_t)g; + v.push_back(q); + ip.gate_p = v.data(); + ip.gate_n_p = (int)v.size(); + } if (r.scratch_bytes > arena_.scratch_bytes()) { RAD_ERR("op '%s' band %lld kernel %s wants %s of scratch but the plan " @@ -847,6 +866,7 @@ int Ctx::bind_profiling() { prof_calls_.assign(program_->ops.size(), 0); prof_host_.assign(program_->ops.size(), 0); prof_join_ms_.assign(program_->ops.size(), 0.0); + prof_wait_ms_.assign(program_->ops.size(), 0.0); if (!profiling_) return RAD_OK; /* Printed, not buried in a doc. Anyone reading a profiled run's numbers has to see this on the @@ -888,12 +908,21 @@ void Ctx::profile_collect() { ++n_host_syncs_; /* counted, so the caveat is a number and not a claim */ if (rad_stream_sync(stream_) < 0) prof_n_ = 0; } + /* The idle time before each op, per lane: the first op a lane runs in the step has nothing + * before it on that lane, and the gap from the last step is mostly this collection's own + * synchronisation, so it is not charged. */ + const ProfSlot* prev[2] = { nullptr, nullptr }; for (size_t i = 0; i < prof_n_; ++i) { ProfSlot& s = prof_ring_[i]; float ms = 0.0f; if (rad_event_elapsed_ms(s.a, s.b, &ms) < 0) continue; prof_ms_[(size_t)s.op] += (double)ms; prof_calls_[(size_t)s.op] += 1; + const ProfSlot*& p = prev[s.lane & 1]; + float gap = 0.0f; + if (p && rad_event_elapsed_ms(p->b, s.a, &gap) >= 0 && gap > 0.0f) + prof_wait_ms_[(size_t)s.op] += (double)gap; + p = &s; } if (prof_overflowed_) { RAD_WARN("per-op timing: the step issued more than %zu ops; the tail was not timed", @@ -912,9 +941,10 @@ void Ctx::dump_profile() const { "enabling this restores synchronisations that change the mover's slot supply.\n" "A row marked `host` was timed on the HOST CLOCK around a host-site launch and\n" "includes everything that call waited on -- page faults, link reads. The rest are\n" - "device event pairs around a kernel.\n\n" - " %10s %12s %10s %5s %10s %s\n", rank_, "calls", "total ms", "us/call", "site", - "join us", "op / geometry"); + "device event pairs around a kernel. `wait us` is how long, a call, the op's lane\n" + "sat idle before it started -- stream waits and issue delays, in no op's time.\n\n" + " %10s %12s %10s %5s %10s %10s %s\n", rank_, "calls", "total ms", "us/call", "site", + "join us", "wait us", "op / geometry"); /* Slowest first: the only ordering anybody reads this table in. */ std::vector order; @@ -922,7 +952,7 @@ void Ctx::dump_profile() const { std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return prof_ms_[a] > prof_ms_[b]; }); - double total = 0.0; + double total = 0.0, waited = 0.0; for (size_t i : order) { const OpInfo& o = program_->ops[i]; const bool ho = i < prof_host_.size() && prof_host_[i]; @@ -936,13 +966,16 @@ void Ctx::dump_profile() const { * tied to anything. */ const char* wname = !o.weights.empty() && o.weights[0] < program_->weights.size() ? program_->weights[o.weights[0]].name.c_str() : "-"; - fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %s %s #%d %s\n", + const double wait = i < prof_wait_ms_.size() ? prof_wait_ms_[i] : 0.0; + fprintf(stderr, " %10lld %12.3f %10.2f %5s %s %10.2f %s %s #%d %s\n", (long long)prof_calls_[i], prof_ms_[i], prof_ms_[i] * 1000.0 / (double)prof_calls_[i], ho ? "host" : "dev", jbuf, + wait * 1000.0 / (double)prof_calls_[i], o.op.c_str(), o.base.str().c_str(), (int)o.index, wname); total += prof_ms_[i]; + waited += wait; } - fprintf(stderr, " %10s %12.3f\n\n", "total", total); + fprintf(stderr, " %10s %12.3f (waited %.3f ms besides)\n\n", "total", total, waited); } /* ================================================================== the step driver */ @@ -1200,6 +1233,22 @@ bool Ctx::tapes_agree(const PassTape& a, const PassTape& b, std::string* why) { same = std::memcmp(&x.t[k], &y.t[k], sizeof(RadTensor)) == 0; if (!same) { *why = fmt("host op %zu (op %u) differs", i, (unsigned)x.h); return false; } } + if (a.xp.size() != b.xp.size()) { + *why = fmt("%zu prefetch calls against %zu", a.xp.size(), b.xp.size()); + return false; + } + for (size_t i = 0; i < a.xp.size(); ++i) { + const TapeXp& x = a.xp[i]; + const TapeXp& y = b.xp[i]; + const RadPrefetchNext& u = x.next; + const RadPrefetchNext& v = y.next; + if (u.layer != v.layer || u.router != v.router || u.n_expert != v.n_expert || u.top_k != v.top_k || + u.n_parts != v.n_parts || u.parts != v.parts || u.count_at != v.count_at || x.h != y.h || + x.r0 != y.r0 || x.rows != y.rows || x.n_embd != y.n_embd) { + *why = fmt("prefetch call %zu (for layer %d) differs", i, x.next.layer); + return false; + } + } for (size_t i = 0; i < a.route.size(); ++i) if (a.route[i].first != b.route[i].first || std::memcmp(&a.route[i].second, &b.route[i].second, sizeof(RadRouting)) != 0) { @@ -1248,6 +1297,23 @@ int Ctx::play_pass(PassTape& t) { rc = route_report_impl(t.route[(size_t)st.a].first, &t.route[(size_t)st.a].second, false); break; + case kTapeXp: { + const TapeXp& p = t.xp[(size_t)st.a]; + lane_ = st.lane; + rc = xp_ ? xp_predict_run(p.next, p.h, p.r0, p.rows, p.n_embd) : RAD_OK; + lane_ = l0; + break; + } + case kTapeXpMark: + lane_ = st.lane; + rc = xp_ ? xp_mark_run() : RAD_OK; + lane_ = l0; + break; + case kTapeXpStep: + lane_ = st.lane; + rc = xp_ ? xp_step_run(st.a) : RAD_OK; + lane_ = l0; + break; } if (rc < 0) { if (step_status_ >= 0) step_status_ = rc; @@ -1350,6 +1416,11 @@ int Ctx::run_step(const RadBatch* b) { return RAD_E_STATE; } + /* BEFORE THE RESIDENCY SYNC: a stager may give back weights it published for this pass when + * it turns the pass down (runtime/stager.h), and the sync is what carries that into the + * tables the pass resolves. */ + staging_ = stager_ != nullptr && stager_->begin_pass(b); + /* The mover relocates between steps, never during one. Honouring WeightInfo::generation here * costs one relaxed atomic load per step instead of one per weight per issue. */ if (weights_dirty_.exchange(false, std::memory_order_acq_rel)) @@ -1361,8 +1432,6 @@ int Ctx::run_step(const RadBatch* b) { step_fail_.clear(); prof_n_ = 0; in_step_ = true; - - staging_ = stager_ != nullptr && stager_->begin_pass(b); { const int rc = run_pass(b); if (rc < 0 && step_status_ >= 0) step_status_ = rc; diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 8a231df4..cef8e481 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -33,7 +33,9 @@ #include "device/device.h" #include +#include #include +#include #include #include @@ -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 steps; std::vector host; std::vector> route; + std::vector 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 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 unflushed_; std::vector band_table_; std::vector 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> gate_params_; std::vector> op_domain_; /* sized once, never resized */ std::vector 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 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 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 prof_wait_ms_; std::atomic weights_dirty_{false}; /* Bumped whenever bind_weights rewrites the templates: any weight pointer resolved from one diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 3bdd18e0..35a8f0d4 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -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(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; 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(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(c)->xp_predict(next, h, r0, rows, n_embd) : RAD_E_INVAL; +} +int rad_expert_prefetch_mark(RadCtx* c) { + return c ? static_cast(c)->xp_mark() : RAD_E_INVAL; +} +int rad_expert_prefetch_step(RadCtx* c, int layer) { + return c ? static_cast(c)->xp_step(layer) : RAD_E_INVAL; +} + void* rad_weight_ptr(RadCtx* c, rad_weight w) { return c ? static_cast(c)->weight_ptr(w) : nullptr; } diff --git a/core/runtime/stager.h b/core/runtime/stager.h index 0722281d..34a216be 100644 --- a/core/runtime/stager.h +++ b/core/runtime/stager.h @@ -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; }; diff --git a/core/runtime/xp_state.h b/core/runtime/xp_state.h new file mode 100644 index 00000000..4c2875b3 --- /dev/null +++ b/core/runtime/xp_state.h @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 q; + std::atomic stop{false}; + std::deque> marks; /* thread only: a mark and the list that polls it */ + int64_t lists = 0; /* thread only: lists handed over */ + std::atomic dropped{0}; /* requests the queue was too far behind for */ +}; + +} /* namespace rad */ diff --git a/core/runtime/xprefetch.cpp b/core/runtime/xprefetch.cpp new file mode 100644 index 00000000..0960965e --- /dev/null +++ b/core/runtime/xprefetch.cpp @@ -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 +#include +#include +#include + +#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(); + 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 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 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)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 hm((size_t)kXpMaxNe * kXpParts, nullptr); + std::vector 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 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 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 */ diff --git a/core/runtime/xprefetch.h b/core/runtime/xprefetch.h new file mode 100644 index 00000000..3221a33d --- /dev/null +++ b/core/runtime/xprefetch.h @@ -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 + +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); diff --git a/core/runtime/xprefetch.hip b/core/runtime/xprefetch.hip new file mode 100644 index 00000000..1d7c74b2 --- /dev/null +++ b/core/runtime/xprefetch.hip @@ -0,0 +1,314 @@ +/* xprefetch.hip -- the expert prefetch's kernels. See xprefetch.h. */ +#include +#include + +#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; +} diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 07d02924..9a55de11 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -221,6 +221,7 @@ public: int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const; /* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */ bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; } + const SamplerConfig& config() const { return cfg_; } /* The parameter rows the last build_step or build_greedy staged, and how many. What `run` * uploads, readable so the staging can be checked without a device behind it. */ diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 2480d991..97a6aed0 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -1287,24 +1287,29 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part enc_cu_host_[0] = 0; for (const EncoderPart& p : parts) { const mm::Item& it = *p.item; - const int64_t seg_p = (int64_t)it.grid_h * it.grid_w; - const int64_t np = seg_p * p.n_seg; + if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) { + RAD_ERR("encoder pass: segments [%d, %d) of an item of %d", p.seg0, p.seg0 + p.n_seg, + it.n_seg); + return nullptr; + } + const int64_t np = it.patch_at(p.seg0 + p.n_seg) - it.patch_at(p.seg0); if (it.patch_dim != enc_dim || n_patch + np > enc.max_patches || - n_seg + p.n_seg > max_segs || p.seg0 + p.n_seg > it.n_seg) { + n_seg + p.n_seg > max_segs) { RAD_ERR("encoder pass: %lld patches in %lld segments do not fit the declared pass of " "%lld patches of %lld elements", (long long)(n_patch + np), (long long)(n_seg + p.n_seg), (long long)enc.max_patches, (long long)enc_dim); return nullptr; } std::memcpy(enc_pix_host_ + n_patch * enc_dim, - it.pixels.data() + (int64_t)p.seg0 * seg_p * enc_dim, + it.pixels.data() + it.patch_at(p.seg0) * enc_dim, (size_t)(np * enc_dim) * sizeof(uint16_t)); n_patch += np; - for (int32_t q = 0; q < p.n_seg; ++q) { + for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) { + const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q); enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p; ++n_seg; + if (seg_p > max_seg) max_seg = seg_p; } - if (seg_p > max_seg) max_seg = seg_p; } /* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */ { @@ -1312,10 +1317,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& 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)); diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index c28fdabd..a2b5bf78 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -180,6 +180,14 @@ int Scheduler::add_locked(std::unique_ptr r) { /* AN EMBEDDING INPUT RUNS IN ONE STEP OR NOT AT ALL (Request::embed), so one longer than a * step could never be admitted and would wait for good. */ if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL; + /* A SCORED PROMPT names real vocabulary rows, and one step's decision is all it needs: + * drafts would be proposed for a continuation nobody reads. */ + if (r->token_scores) { + if (r->embed || r->token_scores->tokens.empty()) return RAD_E_INVAL; + for (int32_t t : r->token_scores->tokens) + if (t < 0 || t >= prog_->meta.n_vocab) return RAD_E_INVAL; + r->may_speculate = false; + } /* NO ENGINE BEHIND THE QUEUE ANY MORE. Accepting would leave the caller waiting on a step * that is never coming, so the sink is failed here -- it is the one thing the caller is * listening to -- and the refusal says why. */ @@ -708,7 +716,7 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const { * second clamp is a no-op on it. Reversing them would round a chunk PAST the checkpoint down and * then miss the boundary, which is the exact failure this is written to avoid. */ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, - int64_t* checkpoint_pos) const { + int64_t* checkpoint_pos, int64_t keep_at) const { if (checkpoint_pos) *checkpoint_pos = -1; int64_t remaining = n_target - n_computed; if (remaining <= 0 || budget <= 0) return 0; @@ -735,6 +743,13 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg if (checkpoint_pos) *checkpoint_pos = tail; } } + /* AND ONE WHERE THE REQUEST ASKED (Request::checkpoint_at), on its quantum: the end of a + * prefix other requests are about to start from. Same split as the interval's. */ + const int64_t keep = keep_at / geo_.quantum * geo_.quantum; + if (keep > n_computed && keep <= n_computed + want && keep <= n_target) { + want = keep - n_computed; + if (checkpoint_pos) *checkpoint_pos = keep; + } } if (want < remaining) { @@ -998,8 +1013,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { * for nothing; the hit above is known by now, so the cap is on what really has to run. */ const int64_t cap = r.embed ? budget /* whole input or nothing: never held back (below) */ : busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty()); - int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt); - if (cap < budget && want > 0) admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr); + int64_t want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at); + if (cap < budget && want > 0) + admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at); /* The whole input or nothing this step (Request::embed): the next step starts with a whole * budget, and add_locked refused an input no budget holds. */ if (r.embed && want < target - (int64_t)r.n_computed) want = 0; @@ -1149,9 +1165,10 @@ const RadBatch* Scheduler::step() { const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0; const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(), /*rows_only=*/shares == 0); - want = plan_chunk(r.n_computed, target, cap, &ckpt); + want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at); if (cap < budget && want > 0 && capped_at < 0) { - const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr); + const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr, + r.checkpoint_at); if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; } } /* A PREFILL WITH NO ROOM LEFT DOES NOT STOP THE WALK. Under a quantum of budget it can @@ -1411,7 +1428,7 @@ const RadBatch* Scheduler::step() { if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk)); int64_t ckpt = -1; const int64_t grown = e.ckpt_slot < 0 && limit > had - ? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt) : had; + ? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had; if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) { e.n_tokens = (int32_t)grown; e.produces_token = (r.n_computed + grown >= s.seq_len()); @@ -1557,6 +1574,18 @@ const RadBatch* Scheduler::step() { } /* ------------------------------------------------------------------ media */ +bool Scheduler::prefill_continues() const { + std::lock_guard 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) { diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 5976639b..9c4e7b1a 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -457,18 +457,22 @@ public: SchedMetrics observed_metrics() const; int observed_requests(ReqStat* out, int max) const; - /* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a - * token budget, and the checkpoint position it will land on (-1 for none). */ /* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */ bool last_checkpoint(int64_t pos, int64_t target) const; int64_t tail_checkpoint(int64_t target) const; + /* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a + * token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the + * request's own checkpoint (Request::checkpoint_at), 0 for none. */ int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, - int64_t* checkpoint_pos) const; + int64_t* checkpoint_pos, int64_t keep_at = 0) const; /* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS, in tokens (0 = no stager), set once by the * engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it; see * busy_cap. Also where the resolved policy is stated at startup. */ void set_stage_rows(int64_t rows); + /* Whether the step just planned leaves a prompt with at least the stager's smallest pass still + * to prefill, so the next step most likely carries a chunk the stager arms for. */ + bool prefill_continues() const; /* Visible for tests: the most a prefill chunk at `n_computed` of a `n_target`-token sequence * may take of `budget` when `reserve` tokens of other work are still to be planned in the step * and `shared` says rows are already planned ahead of it. Returns `budget` when diff --git a/core/server/LICENSE.lfm b/core/server/LICENSE.lfm new file mode 100644 index 00000000..25e731c6 --- /dev/null +++ b/core/server/LICENSE.lfm @@ -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 \ No newline at end of file diff --git a/core/server/adapters.h b/core/server/adapters.h index 04e06b82..a84a4d07 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -733,7 +733,8 @@ public: if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; } if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why); return k == MediaKind::Image - ? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why) + ? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why, + opts.max_pixels) : p_->video(bytes.data(), bytes.size(), out, why); } diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 4c54f00f..0eeec990 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -534,6 +534,32 @@ HttpResponse Server::handle_server_info(const HttpRequest&) { return HttpResponse::json_body(200, json_dump(o)); } +/* ================================================================== /diagnostics */ +/* The startup report, read again for this request (ServerOptions::diagnostics_json). Behind the + * bearer key like /server_info: it names the machine's devices and boot parameters. + * + * AND WITHOUT A KEY, ONLY TO THIS MACHINE. /server_info without a key describes the model a + * client is already talking to; this describes the host -- its kernel, its boot parameters, its + * PCI layout, its memory limits -- which a server bound to 0.0.0.0 with no key would otherwise + * hand to anyone who can reach the port. A key is the operator's statement of who may ask. */ +HttpResponse Server::handle_diagnostics(const HttpRequest& req) { + if (!opt_.diagnostics_json) + return error_response(err_not_implemented( + "the server was not given a diagnostics provider; this build has no engine attached"), + req.peer); + if (opt_.api_key.empty() && !req.peer_is_loopback()) { + ApiError e; + e.status = 403; + e.type = "permission_error"; + e.message = "/diagnostics describes this machine, and a server started without --api-key " + "answers it only to a client on the same machine (a loopback address); start " + "it with --api-key to read it from elsewhere"; + return error_response(e, req.peer); + } + metrics_.observe_http(200); + return HttpResponse::json_body(200, opt_.diagnostics_json()); +} + /* ================================================================== /reset_prefix_cache */ /* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an * empty body whether or not anything happened, so a benchmark that thinks it started cold has no diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index b1a578fc..1e6fa8c7 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -313,6 +313,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) { e["staged_units"] = s.experts.staged_units; e["staged_bytes"] = (double)s.experts.staged_bytes; e["stage_overflow"] = s.experts.stage_overflow; + e["stage_copies"] = s.experts.stage_copies; o["experts"] = std::move(e); } diff --git a/core/server/http.cpp b/core/server/http.cpp index 8641965c..e1d739a1 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -5,6 +5,9 @@ * translation unit so that nothing above the transport seam pays for it. */ #include "cpp-httplib/httplib.h" +#include +#include + #include #include #include @@ -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(o.max_threads, nt); const size_t queued = (size_t)std::max(o.max_queued, 0); svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); }; diff --git a/core/server/http.h b/core/server/http.h index 1a7a6f63..f1992a41 100644 --- a/core/server/http.h +++ b/core/server/http.h @@ -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(); diff --git a/core/server/iface.h b/core/server/iface.h index 36e8af27..6e28fa2d 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -583,6 +583,9 @@ struct MediaOpts { /* Soft tokens (encoder output rows) an image may become, for a processor that sizes images * by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */ int32_t image_tokens = 0; + /* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides + * truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */ + int64_t max_pixels = 0; }; class IMultimodal { diff --git a/core/server/liveview.h b/core/server/liveview.h index 3f260243..496364de 100644 --- a/core/server/liveview.h +++ b/core/server/liveview.h @@ -89,8 +89,10 @@ struct ExpertPlane { int64_t routed = 0, routed_resident = 0; int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0; /* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes - * copied onto the card, and pooled units a buffer had no room for. */ + * copied onto the card, pooled units a buffer had no room for, and the copies that carried + * the units. */ int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0; + int64_t stage_copies = 0; /* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache * lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says * whether the boundary between the two pools is moving, and whether what was lent is being diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 9277042e..d5a8f022 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -1190,8 +1190,8 @@ static const char* const MEDIA_MARKER = RAD_MEDIA_MARKER; * arbitrary http(s) URL on a caller's behalf turns the inference server into an SSRF proxy with * network access to everything the deployment can reach, and no amount of allowlisting makes * that a good default. */ -static int decode_media_url(const std::string& url, const std::string& field, - std::vector* out, ApiError* err) { +int decode_media_url(const std::string& url, const std::string& field, + std::vector* out, ApiError* err) { if (url.rfind("data:", 0) != 0) { *err = err_bad(field, "only data: URLs are accepted; the server does not fetch remote URLs " "on a request's behalf"); @@ -1462,9 +1462,9 @@ static int lower_content_parts(json& messages, const OaiDeps& d, const OaiLimits * Each media part is processed HERE, on the request's own worker, because decoding a video and * resizing its frames is the most expensive host work a request can bring: it must not reach the * scheduler's thread, where every other request's step would wait on it. */ -static int tokenize_with_media(const std::string& rendered, const OaiDeps& d, - std::vector>>& media, - const MediaOpts& opts, PromptInput* out, ApiError* err) { +int tokenize_with_media(const std::string& rendered, const OaiDeps& d, + std::vector>>& media, + const MediaOpts& opts, PromptInput* out, ApiError* err) { out->text = rendered; auto pm = std::make_shared(); const std::string marker = MEDIA_MARKER; diff --git a/core/server/oai.h b/core/server/oai.h index 642a65e8..87a77a22 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -291,6 +291,14 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit * token ids mixed as ONE prompt, as llama-server reads it. */ int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err, bool native = false); +/* A media part's bytes out of a data: URL; any other URL is refused, never fetched. */ +int decode_media_url(const std::string& url, const std::string& field, + std::vector* out, ApiError* err); +/* A prompt holding RAD_MEDIA_MARKER once a media part, tokenised with each marker replaced by its + * part's processed token run; `media` is consumed in order. */ +int tokenize_with_media(const std::string& rendered, const OaiDeps& d, + std::vector>>& media, + const MediaOpts& opts, PromptInput* out, ApiError* err); /* Embeddings: fills `out->prompts` with one entry per input. */ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err); diff --git a/core/server/server.cpp b/core/server/server.cpp index 4b5852f0..ffbb83ec 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -2,6 +2,7 @@ #include #include "json_partial.h" +#include "systemone.h" #include "rad_internal.h" #include "text/tokenizer.h" @@ -136,6 +137,7 @@ void Server::register_routes() { router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); }); router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); }); router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); }); + router_.post("/v1/systemone", [this](const HttpRequest& q) { return handle_systemone(q); }); router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); }); /* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the @@ -175,6 +177,7 @@ void Server::register_routes() { router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); }); router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); }); router_.get ("/props", [this](const HttpRequest& q) { return handle_props(q); }); + router_.get ("/diagnostics", [this](const HttpRequest& q) { return handle_diagnostics(q); }); router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); }); router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); }); @@ -1723,6 +1726,158 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) { return HttpResponse::json_body(200, embeddings_body(r, vecs, u)); } +/* /v1/systemone (systemone.h): one request a question, each reading its answer's candidates at + * the prompt's last position (Request::token_scores) and sampling one token nobody reads. + * + * SEVERAL QUESTIONS SHARE THE STATE THEY ARE ASKED OVER, and it is read once. The first question + * runs alone and leaves the state at the end of that shared head in the prefix cache -- its + * attention blocks, and a checkpoint of the convolutions there (Request::checkpoint_at) -- and the + * rest are submitted together once it has finished, each starting from that head and computing + * only its own tail. d1's own runner shares the head the same way, as one batched tree. */ +HttpResponse Server::handle_systemone(const HttpRequest& req) { + if (!deps_.sched || !deps_.tok) + return error_response(err_not_implemented("the server has no engine attached"), req.peer); + if (opt_.decision_type != "d1") + return error_response(err_not_implemented( + "/v1/systemone serves a decision model; this container does not declare one " + "(convert d1 with --set decision.type=d1)"), req.peer); + + DecisionRequest r; + ApiError err; + if (parse_decision_request(req.body, odeps_, lim_, opt_.model_id, &r, &err) < 0) + return error_response(err, req.peer); + + sweep_abandoned(); + const int n = (int)r.questions.size(); + if (!admit(n)) { + metrics_.observe_rejected(); + return error_response(err_overloaded( + "the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) + + "s. The server refuses rather than queueing without bound"), req.peer); + } + RAD_INFO("systemone admitted%s questions=%d prompt=%lld tok", from_peer(req.peer).c_str(), n, + (long long)r.input_tokens); + + std::vector gens; + std::vector rqs; + std::vector> scores; + for (int i = 0; i < n; ++i) { + Generation g; + g.index = i; + g.sink = std::make_shared(16); + auto ts = std::make_shared(); + ts->tokens = r.questions[(size_t)i].candidates; + Request rq; + rq.prompt = r.questions[(size_t)i].tokens; + rq.media = r.media; + rq.token_scores = ts; + rq.max_tokens = 1; + rq.sp.temp = 0.0f; + rq.sink = g.sink.get(); + if (i == 0 && n > 1) rq.checkpoint_at = r.trunk; + rqs.push_back(std::move(rq)); + gens.push_back(std::move(g)); + scores.push_back(std::move(ts)); + } + /* The questions handed to the scheduler so far: an early exit retires those and drops the + * rest, whose sinks nothing will ever finish. */ + size_t submitted = 0; + auto fail = [&](const std::string& why) { + gens.resize(submitted); + retire(gens); + release(n); + ApiError e; + e.status = 500; + e.type = "internal_server_error"; + e.message = why; + return error_response(e, req.peer); + }; + + /* Questions [first, last) submitted together and waited for. A non-null response is the + * call's answer already: the scheduler refused one, the client left, or the server stops. */ + std::unique_ptr early; + auto run = [&](int first, int last) { + std::vector part(std::make_move_iterator(rqs.begin() + first), + std::make_move_iterator(rqs.begin() + last)); + std::vector ids; + deps_.sched->submit_all(part, &ids); + submitted = (size_t)last; + for (size_t k = 0; k < ids.size(); ++k) { + Generation& g = gens[(size_t)first + k]; + g.id = ids[k]; + g.sink->id = ids[k]; + if (!ids[k]) { + early = std::make_unique( + fail("the scheduler refused question " + r.questions[(size_t)first + k].name)); + return; + } + } + for (;;) { + bool all = true; + for (int i = first; i < last; ++i) { + Generation& g = gens[(size_t)i]; + if (!g.closed && g.sink->done()) { g.closed = true; g.finish = g.sink->finish_reason(); } + all = all && g.closed; + } + if (all) return; + if (req.peer_gone()) { + gens.resize(submitted); + cancel_all(gens, true); + retire(gens); + release(n); + metrics_.observe_http(499); + early = std::make_unique( + HttpResponse::text(499, "client closed request\n")); + return; + } + if (stopping_.load()) { + gens.resize(submitted); + cancel_all(gens, false); + retire(gens); + release(n); + early = std::make_unique( + error_response(err_overloaded("the server is shutting down"), req.peer)); + return; + } + for (int i = first; i < last; ++i) + if (!gens[(size_t)i].closed) { gens[(size_t)i].sink->wait(); break; } + } + }; + run(0, 1); + if (early) return std::move(*early); + /* A first question that failed fails the call; the rest would only repeat it. */ + if (gens[0].finish == Finish::Error || gens[0].finish == Finish::Cancelled) + return fail(gens[0].finish == Finish::Error ? engine_failure(*gens[0].sink) + : "the engine cancelled question " + + r.questions[0].name); + if (n > 1) { + run(1, n); + if (early) return std::move(*early); + } + + json answers = json::object(); + for (size_t i = 0; i < gens.size(); ++i) { + const Generation& g = gens[i]; + if (g.finish == Finish::Error || g.finish == Finish::Cancelled) + return fail(g.finish == Finish::Error ? engine_failure(*g.sink) + : "the engine cancelled question " + + r.questions[i].name); + json a; + if (decision_answer(r.questions[i], scores[i]->logits, &a, &err) < 0) { + retire(gens); + release(n); + return error_response(err, req.peer); + } + answers[r.questions[i].name] = std::move(a); + } + retire(gens); + release(n); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(json{ + { "answers", std::move(answers) }, + { "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } })); +} + HttpResponse Server::handle_models(const HttpRequest& req) { const std::string id = req.param("id"); if (!id.empty() && id != opt_.model_id) { diff --git a/core/server/server.h b/core/server/server.h index 3f04865d..e33672d3 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -57,6 +57,9 @@ struct ServerOptions { * /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine * would finish after one step with no text. */ bool embedding_model = false; + /* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`: + * "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */ + std::string decision_type; /* What --model named, reported as the model entry's `root` the way vLLM reports the path it * loaded: a served name chosen for clients says nothing about which file is behind it. Empty * leaves the field out. */ @@ -121,6 +124,13 @@ struct ServerOptions { * showing an op as unissued one step before it flips. Registry::select is asked with * record = false and mutates nothing else. */ std::function graph_json; + /* THE STARTUP REPORT READ AGAIN, as JSON (core/diag/diag.h): the options in force, the machine + * as it is now (the provider may reuse a reading for a second), and what on it costs speed. + * Without a key it is answered to loopback clients only (Server::handle_diagnostics). A + * provider like the graph's, because a card's link speed and clock only say anything under + * load -- a request made during a long prefill is how a link parked below its maximum is told + * from one at rest. */ + std::function diagnostics_json; std::string api_key; bool cors = true; @@ -171,6 +181,8 @@ public: int port() const { return transport_.port(); } /* 0 until run() is accepting */ int64_t in_flight() const { return in_flight_.load(std::memory_order_relaxed); } + /* The admission ceiling as resolved: ServerOptions::queue_depth, or 8 x max_seqs for 0. */ + int64_t queue_cap() const { return queue_depth_; } private: struct Generation; @@ -185,6 +197,7 @@ private: HttpResponse handle_chat(const HttpRequest& req); HttpResponse handle_completion(const HttpRequest& req); HttpResponse handle_embeddings(const HttpRequest& req); + HttpResponse handle_systemone(const HttpRequest& req); HttpResponse handle_models(const HttpRequest& req); HttpResponse handle_metrics(const HttpRequest& req); @@ -213,6 +226,7 @@ private: HttpResponse handle_detokenize(const HttpRequest& req); HttpResponse handle_tokenizer_info(const HttpRequest& req); HttpResponse handle_server_info(const HttpRequest& req); + HttpResponse handle_diagnostics(const HttpRequest& req); /* What this deployment can do -- chat, tools, reasoning, grammar, media, logprobs, the * reasoning efforts it takes -- as /server_info's `capabilities` and the model entry both * report it, built in one place so the two cannot disagree. */ diff --git a/core/server/systemone.cpp b/core/server/systemone.cpp new file mode 100644 index 00000000..ee0f73ea --- /dev/null +++ b/core/server/systemone.cpp @@ -0,0 +1,404 @@ +/* systemone.cpp -- d1's prompt and readout (systemone.h). + * + * EVERY STRING BELOW IS d1's OWN, from prompt.py in the model's repository: the user turn, the + * state block, the three question blocks, the option codes and their fallback codebook, the + * yes/no spellings. The model was trained on exactly these, so a reworded instruction or a + * different code for an option is a different (and worse-calibrated) question. + * + * THAT TEXT IS LIQUID AI'S, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE): + * this file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their + * strings kept as they are. + * + * AND SO IS THE TOKENISATION SPLIT. d1 tokenises a single question's prompt as one text, and a + * request with several as the shared head (the state and the pictures) followed by each question's + * tail, tokenised separately -- its runner reads the head once and branches. The two are not the + * same ids where BPE would merge across the join, so each case is tokenised the way the model's + * own runner does. + */ +#include "systemone.h" + +#include "llama/src/unicode.h" +#include "mm/processor.h" + +#include + +#include +#include +#include + +namespace rad { +namespace server { + +namespace { + +const char* const kImStart = "<|im_start|>"; +const char* const kImEnd = "<|im_end|>"; + +bool only_keys(const json& o, std::initializer_list allowed, const std::string& path, + ApiError* err) { + for (const auto& kv : o.items()) { + bool ok = false; + for (const char* k : allowed) ok = ok || kv.key() == k; + if (!ok) { + *err = err_unsupported(path + kv.key(), "not a field of a System One request"); + return false; + } + } + return true; +} + +/* The one id `text` encodes to, or -1 when it is not a single token. */ +int32_t one_token(const ITokenizer& tok, const std::string& text) { + const std::vector ids = tok.encode(text, false, true); + return ids.size() == 1 ? ids[0] : -1; +} + +/* An answer's spellings: the distinct single-token ones among `texts` (prompt.py, _ids). */ +void add_answer(DecisionQuestion* q, const ITokenizer& tok, const std::vector& texts) { + std::vector group; + for (const std::string& t : texts) { + const int32_t id = one_token(tok, t); + if (id < 0) continue; + size_t at = 0; + while (at < q->candidates.size() && q->candidates[at] != id) ++at; + if (at == q->candidates.size()) q->candidates.push_back(id); + bool have = false; + for (size_t g : group) have = have || g == at; + if (!have) group.push_back(at); + } + q->groups.push_back(std::move(group)); +} + +/* Python's str.strip() and str.isalpha() over one stripped label. */ +std::string strip(const std::string& s) { + const std::vector c = unicode_cpts_from_utf8(s); + size_t a = 0, b = c.size(); + while (a < b && unicode_cpt_flags_from_cpt(c[a]).is_whitespace) ++a; + while (b > a && unicode_cpt_flags_from_cpt(c[b - 1]).is_whitespace) --b; + std::string out; + for (size_t i = a; i < b; ++i) out += unicode_cpt_to_utf8(c[i]); + return out; +} +bool one_letter(const std::string& s) { + const std::vector c = unicode_cpts_from_utf8(s); + return c.size() == 1 && unicode_cpt_flags_from_cpt(c[0]).is_letter; +} + +std::string two_digits(size_t i) { return (i < 10 ? "0" : "") + std::to_string(i); } + +/* prompt.py, option_codes: the labels themselves when every one is a single letter, else A..Z, + * else 00, 01, ... */ +std::vector option_codes(const std::vector& labels) { + std::vector codes; + bool letters = !labels.empty(); + for (const std::string& l : labels) letters = letters && one_letter(strip(l)); + for (size_t i = 0; i < labels.size(); ++i) + codes.push_back(letters ? strip(labels[i]) + : labels.size() <= 26 ? std::string(1, (char)('A' + i)) : two_digits(i)); + return codes; +} + +/* prompt.py, _FALLBACK_POOL: where a code is not one token of its own, or is already taken. */ +const std::vector& fallback_pool() { + static const std::vector pool = [] { + std::vector v; + for (char c = 'A'; c <= 'Z'; ++c) v.emplace_back(1, c); + for (size_t i = 0; i < 100; ++i) v.push_back(two_digits(i)); + for (char c = 'a'; c <= 'z'; ++c) v.emplace_back(1, c); + for (size_t i = 0; i < 200; ++i) v.push_back("#" + std::to_string(i)); + for (char a = 'A'; a <= 'Z'; ++a) + for (char b = 'A'; b <= 'Z'; ++b) v.push_back(std::string{ a, b }); + return v; + }(); + return pool; +} + +/* A string criterion, or null (Python's None, which a question block writes as "None"). */ +bool text_or_null(const json& v, const std::string& path, ApiError* err) { + if (v.is_string() || v.is_null()) return true; + *err = err_bad(path, "must be a string or null"); + return false; +} +std::string py_str(const json& v) { return v.is_null() ? "None" : v.get(); } + +/* One question: its block (prompt.py, question_block), the assistant header behind it, and the + * ids its answers are read at (readout_ids). */ +int parse_question(const std::string& name, const json& src, const ITokenizer& tok, + DecisionQuestion* q, std::string* suffix, ApiError* err) { + const std::string path = "questions." + name; + auto bad = [&](const std::string& field, const std::string& why) { + *err = err_bad(path + field, why); + return RAD_E_INVAL; + }; + if (!src.is_object()) return bad("", "must be an object"); + if (!only_keys(src, { "type", "instructions", "criteria" }, path + ".", err)) return RAD_E_INVAL; + auto it = src.find("instructions"); + if (it == src.end() || !it->is_string()) return bad(".instructions", "must be a string"); + const std::string instructions = it->get(); + auto ty = src.find("type"); + if (ty != src.end() && !ty->is_string()) return bad(".type", "must be noul, choice or score"); + q->name = name; + q->type = ty == src.end() ? "choice" : ty->get(); /* prompt.py's default */ + const json criteria = src.contains("criteria") ? src.at("criteria") : json(); + + std::string block; + if (q->type == "noul") { + if (!criteria.is_null() && !criteria.is_object()) + return bad(".criteria", "must be an object with `true` and `false`, or absent"); + if (criteria.is_object()) { + if (!only_keys(criteria, { "true", "false" }, path + ".criteria.", err)) return RAD_E_INVAL; + for (const auto& kv : criteria.items()) + if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL; + } + block = instructions; + if (criteria.is_object() && !criteria.empty()) + block += "\nYes: " + py_str(criteria.value("true", json())) + + "\nNo: " + py_str(criteria.value("false", json())); + block += "\n\nReply with yes or no only."; + q->labels = { "true", "false" }; + add_answer(q, tok, { "yes", "Yes", "YES" }); + add_answer(q, tok, { "no", "No", "NO" }); + if (q->groups[0].empty() || q->groups[1].empty()) { + *err = err_not_implemented("this vocabulary has no single-token yes or no"); + return RAD_E_UNSUPPORTED; + } + } else if (q->type == "choice") { + if (!criteria.is_object() || criteria.empty()) + return bad(".criteria", "must be a non-empty object of option names to descriptions"); + std::vector descs; + for (const auto& kv : criteria.items()) { + if (!text_or_null(kv.value(), path + ".criteria." + kv.key(), err)) return RAD_E_INVAL; + q->labels.push_back(kv.key()); + std::string d = kv.value().is_null() ? std::string() : kv.value().get(); + if (d.empty()) { /* `desc or label.replace("_", " ")` */ + d = kv.key(); + for (char& c : d) if (c == '_') c = ' '; + } + descs.push_back(std::move(d)); + } + /* prompt.py, aliases: each option's code if it is one token nobody has, else the first + * fallback that is. Then readout_ids: the code, and " code" where that is one token. */ + std::unordered_set used; + block = instructions + "\n\nOptions:\n"; + const std::vector codes = option_codes(q->labels); + for (size_t i = 0; i < codes.size(); ++i) { + std::string code; + int32_t id = one_token(tok, codes[i]); + if (id >= 0 && !used.count(id)) code = codes[i]; + else { + id = -1; + for (const std::string& f : fallback_pool()) { + const int32_t t = one_token(tok, f); + if (t >= 0 && !used.count(t)) { id = t; code = f; break; } + } + } + if (id < 0) return bad(".criteria", "more options than this vocabulary has distinct " + "single-token codes for"); + used.insert(id); + if (i) block += "\n"; + block += code + " " + descs[i]; + add_answer(q, tok, { code, " " + code }); + } + block += "\n\nReply with the option code only."; + } else if (q->type == "score") { + if (!criteria.is_array() || criteria.size() < 2 || criteria.size() > 10) + return bad(".criteria", "must be an array of 2 to 10 level descriptions, lowest first"); + block = instructions + "\n\n"; + for (size_t i = 0; i < criteria.size(); ++i) { + if (!criteria[i].is_string()) return bad(".criteria", "each level must be a string"); + q->labels.push_back(std::to_string(i)); + q->legend.push_back(criteria[i].get()); + if (i) block += "\n"; + block += q->labels.back() + " " + q->legend.back(); + add_answer(q, tok, { q->labels.back() }); + if (q->groups.back().empty()) { + *err = err_not_implemented("this vocabulary has no single-token digit " + + q->labels.back()); + return RAD_E_UNSUPPORTED; + } + } + block += "\n\nReply with a single digit 0-" + std::to_string(criteria.size() - 1) + " only."; + } else { + return bad(".type", "must be noul, choice or score"); + } + *suffix = block + kImEnd + "\n" + kImStart + "assistant\n"; + return RAD_OK; +} + +/* prompt.py, state_block at its default style: a string as it is, anything else as indented JSON + * in the order the request gave its keys. */ +std::string state_block(const json& state) { + return (state.is_string() ? state.get() : state.dump(2)) + "\n\n"; +} + +} /* namespace */ + +int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + const std::string& model_id, DecisionRequest* out, ApiError* err) { + *out = DecisionRequest{}; + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + if (!only_keys(b, { "model", "state", "questions", "images" }, "", err)) return RAD_E_INVAL; + if (b.contains("model") && (!b["model"].is_string() || b["model"] != model_id)) { + *err = err_bad("model", "must name the loaded model, " + model_id); + return RAD_E_INVAL; + } + if (!b.contains("state")) { + *err = err_bad("state", "required: a string, any JSON value, or null with images"); + return RAD_E_INVAL; + } + const json& qs = b.contains("questions") ? b["questions"] : json(); + if (!qs.is_object() || qs.empty()) { + *err = err_bad("questions", "must be a non-empty object of named questions"); + return RAD_E_INVAL; + } + + /* THE PICTURES, decoded here and processed when the head is tokenised. */ + std::vector>> media; + if (b.contains("images")) { + const json& im = b["images"]; + if (!im.is_array()) { *err = err_bad("images", "must be an array of data: URLs"); return RAD_E_INVAL; } + if (!im.empty() && (!d.mm || !d.mm->accepts(MediaKind::Image))) { + *err = err_not_implemented("images need the model's image encoder, and this deployment " + "has none loaded"); + return RAD_E_UNSUPPORTED; + } + for (size_t i = 0; i < im.size(); ++i) { + const std::string field = "images[" + std::to_string(i) + "]"; + if (!im[i].is_string()) { *err = err_bad(field, "must be a data: URL"); return RAD_E_INVAL; } + std::vector bytes; + RAD_TRY(decode_media_url(im[i].get(), field, &bytes, err)); + media.push_back({ MediaKind::Image, std::move(bytes) }); + } + } + + /* prompt.py, prefix_text: BOS, the user turn, the pictures as the chat template writes them + * (one marker each, which the processor expands), then the state. A null state leaves the + * question right behind the pictures. */ + const std::string marker = RAD_MEDIA_MARKER; + std::string head; + if (d.tok->bos() >= 0) head += d.tok->token_bytes(d.tok->bos()); + head += std::string(kImStart) + "user\n"; + for (size_t i = 0; i < media.size(); ++i) head += marker; + std::string body_text; + if (!b["state"].is_null()) body_text = state_block(b["state"]) + "\nQUESTION:\n"; + if (body_text.find(marker) != std::string::npos) { + *err = err_bad("state", "contains \"" + marker + "\", which this server reserves"); + return RAD_E_INVAL; + } + head += body_text; + + std::vector suffixes; + for (const auto& kv : qs.items()) { + DecisionQuestion q; + std::string suffix; + RAD_TRY(parse_question(kv.key(), kv.value(), *d.tok, &q, &suffix, err)); + if (!media.empty() && suffix.find(marker) != std::string::npos) { + *err = err_bad("questions." + kv.key(), "contains \"" + marker + "\", which this " + "server reserves"); + return RAD_E_INVAL; + } + out->questions.push_back(std::move(q)); + suffixes.push_back(std::move(suffix)); + } + + /* runner.py, VISION_MAX_PIXELS: d1 bounds every picture at 1024 x 1024 pixels' area before + * its processor, so a larger one is a different input unless it is bounded here too. */ + MediaOpts opts; + opts.max_pixels = 1024 * 1024; + auto tokenize = [&](const std::string& text, std::vector* ids) -> int { + if (media.empty()) { *ids = d.tok->encode(text, false, true); return RAD_OK; } + PromptInput in; + RAD_TRY(tokenize_with_media(text, d, media, opts, &in, err)); + *ids = std::move(in.tokens); + out->media = std::move(in.media); + return RAD_OK; + }; + if (out->questions.size() == 1) { + RAD_TRY(tokenize(head + suffixes[0], &out->questions[0].tokens)); + out->input_tokens = (int64_t)out->questions[0].tokens.size(); + } else { + std::vector trunk; + RAD_TRY(tokenize(head, &trunk)); + out->trunk = (int32_t)trunk.size(); + out->input_tokens = (int64_t)trunk.size(); + for (size_t i = 0; i < out->questions.size(); ++i) { + std::vector& t = out->questions[i].tokens; + const std::vector tail = d.tok->encode(suffixes[i], false, true); + t = trunk; + t.insert(t.end(), tail.begin(), tail.end()); + out->input_tokens += (int64_t)tail.size(); + } + } + /* One position stays free: the request samples a token, which nobody reads. */ + for (const DecisionQuestion& q : out->questions) + if (lim.max_ctx > 0 && (int64_t)q.tokens.size() >= lim.max_ctx) { + ApiError e = err_bad("questions." + q.name, + "the prompt is " + std::to_string(q.tokens.size()) + + " tokens; this deployment's context holds " + + std::to_string(lim.max_ctx - 1) + " for a decision"); + e.code = "context_length_exceeded"; + *err = e; + return RAD_E_INVAL; + } + return RAD_OK; +} + +int decision_answer(const DecisionQuestion& q, const std::vector& logits, json* out, + ApiError* err) { + if (logits.size() != q.candidates.size() || q.groups.size() != q.labels.size()) { + *err = ApiError{}; + err->status = 500; + err->type = "internal_server_error"; + err->message = "the engine returned no scores for question " + q.name; + return RAD_E_STATE; + } + std::vector p; + for (const std::vector& g : q.groups) { + double best = -std::numeric_limits::infinity(); + for (size_t i : g) best = std::max(best, (double)logits[i]); + if (!std::isfinite(best)) { + *err = ApiError{}; + err->status = 500; + err->type = "internal_server_error"; + err->message = "question " + q.name + " scored a non-finite logit"; + return RAD_E_STATE; + } + p.push_back(best); + } + const double peak = *std::max_element(p.begin(), p.end()); + double total = 0.0; + for (double& v : p) total += (v = std::exp(v - peak)); + for (double& v : p) v /= total; + + /* api.py, answer. */ + json a = json::object(); + a["type"] = q.type; + if (q.type == "noul") { + a["noul"] = p[0]; + *out = std::move(a); + return RAD_OK; + } + const size_t best = (size_t)(std::max_element(p.begin(), p.end()) - p.begin()); + json probs = json::object(); + for (size_t i = 0; i < p.size(); ++i) probs[q.labels[i]] = p[i]; + if (q.type == "choice") { + a["choice"] = q.labels[best]; + } else { + double expected = 0.0; + for (size_t i = 0; i < p.size(); ++i) expected += (double)i * p[i]; + a["score"] = expected; + } + a["confidence"] = p[best]; + a["probabilities"] = std::move(probs); + if (q.type == "score") { + json legend = json::object(); + for (size_t i = 0; i < q.legend.size(); ++i) legend[q.labels[i]] = q.legend[i]; + a["legend"] = std::move(legend); + } + *out = std::move(a); + return RAD_OK; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/systemone.h b/core/server/systemone.h new file mode 100644 index 00000000..ce54f146 --- /dev/null +++ b/core/server/systemone.h @@ -0,0 +1,59 @@ +/* systemone.h -- POST /v1/systemone: LiquidAI d1's decisions, a distribution read off one position. + * + * d1 is a decision model. It is given a state (text, any JSON value, pictures, or a mix) and named + * questions, and each answer is a softmax over a handful of tokens at the position right after the + * assistant header: `yes` / `no` for a noul, one code a option for a choice, a digit a level for a + * score. Nothing is generated. The API and the prompt are the model's own (its prompt.py and api.py + * on the Hub); this file is that adapter, and the engine knows nothing of it beyond + * Request::token_scores -- "read these ids' raw logits at the prompt's last position". + * + * A container serves it only when it says it is d1 (`decision.type` = `d1`, set at convert with + * `--set decision.type=d1`); the HF config does not declare it. + */ +#pragma once + +#include "oai.h" + +#include +#include +#include + +namespace rad { +namespace server { + +struct DecisionQuestion { + std::string name, type; /* type: noul | choice | score */ + /* One entry an answer, in the response's order: "true"/"false", the option names, the + * levels "0".."n-1". */ + std::vector labels; + std::vector legend; /* score: each level's description */ + /* The ids read at the answer slot, and for each answer the indices into them of the + * spellings it scores as: an answer's score is its best spelling's. */ + std::vector candidates; + std::vector> groups; + std::vector tokens; /* the whole prompt */ +}; + +struct DecisionRequest { + std::vector questions; + /* The pictures, placed in the shared head of every question's prompt. */ + std::shared_ptr media; + /* How many leading tokens every question's prompt shares: the state, tokenised once. 0 for + * a single question, which d1 tokenises as one text. */ + int32_t trunk = 0; + /* What the model reads, as d1 counts it: the shared head once and each question's own tail. */ + int64_t input_tokens = 0; +}; + +/* Parse and render. `max_ctx` bounds every question's prompt (one position stays free for the + * token the request samples and discards). */ +int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, + const std::string& model_id, DecisionRequest* out, ApiError* err); + +/* One answer from its candidates' raw logits: each answer scores its best spelling, a softmax over + * the answers is the distribution. Non-finite logits are an error, not a distribution. */ +int decision_answer(const DecisionQuestion& q, const std::vector& logits, json* out, + ApiError* err); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 562f22cb..bd747a9a 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -379,6 +379,7 @@ struct TokEncoder { uint32_t kind = RAD_TOK_BPE; bool bytelevel = false; /* the chain has a ByteLevel pre-tokeniser */ bool byte_fallback = false; + bool ignore_merges = false; /* VocabBuild::ignore_merges */ /* The ByteLevel step at this index is the last step that rewrites text, so the mapping is * never materialised: the BPE merges raw bytes against `raw` instead. -1 when that does not * hold (no ByteLevel, or a step after it that reads the mapped text). */ @@ -407,6 +408,7 @@ struct TokEncoder { int TokEncoder::build(const VocabBuild& b, const std::vector& special) { kind = b.kind; + ignore_merges = b.ignore_merges; types = b.types; unk = b.unk; @@ -1029,15 +1031,16 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out * the vocabulary promises to round-trip; decomposing one into codepoints and merging back * can land on a different sequence, because the merge table was never fitted over them. * - * ORDINARY VOCABULARY ENTRIES STILL GO THROUGH THE MERGE LOOP, which is HuggingFace's - * behaviour at `ignore_merges: false` and is what every checkpoint in scope declares. A - * vocabulary setting it TRUE wants the same short-circuit for any word that is already a - * token, and this engine does not honour the flag: core/text/tokenizer_json.cpp only warns - * when it is set, and the vocabulary has nowhere to carry it. Such a model would tokenise - * differently here than it does in transformers, mostly on rare words. Supporting it is a - * vocabulary field, not a change to this loop. */ + * ORDINARY VOCABULARY ENTRIES GO THROUGH THE MERGE LOOP unless the vocabulary sets + * `ignore_merges`, which is HuggingFace's short-circuit for a word that is already a token: + * the merge table can reach a different split of a rare word than the entry it ships. The + * word is the pre-token after the declared chain, and the raw-byte table looks the same entry + * up under its byte spelling. A CONTROL entry is not taken whole even then: one that reaches + * this loop is text the caller asked to have read as text, and the flag must not turn it back + * into the marker. */ const int32_t whole = table.find(w); - if (whole >= 0 && e.types[whole] == RAD_TT_USER_DEFINED) { + if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED || + (e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) { out.push_back(whole); return; } diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index f73eff40..c678131d 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -70,6 +70,7 @@ inline bool step_is_dec (uint32_t k) { return k >= 64 && k < 96; } * milliseconds at load, against a model measured in gigabytes -- which is not a cost. */ struct VocabBuild { uint32_t kind = RAD_TOK_BPE; + bool ignore_merges = false; /* BPE: a whole pre-token in the vocab is not merged */ std::vector tokens; /* id -> text, in the vocab's own encoding */ std::vector scores; /* unigram only; empty otherwise */ diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index f308288e..b46b4dc0 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -335,17 +335,7 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l if (type == "BPE") { out.kind = RAD_TOK_BPE; - /* `ignore_merges` SHORT-CIRCUITS THE MERGE LOOP for any word that is already a token, and - * this reader does not carry it: the vocabulary has no field for it and tokenizer.cpp - * applies the short-circuit only to added tokens. A vocabulary that sets it would tokenise - * differently here than in transformers, on rare words, with nothing in the output to say - * so -- so it is said here instead of being discovered from a quality regression. */ - if (const json* im = get(m, "ignore_merges")) - if (im->is_boolean() && im->get()) - RAD_WARN("%s: the vocabulary sets ignore_merges, which this tokeniser does not " - "implement. Words that are already tokens will be re-split through the " - "merge table and may tokenise differently than they do in transformers.", - origin); + out.ignore_merges = bool_or(m, "ignore_merges", false); RAD_TRY(read_text_to_id("BPE")); } else if (type == "Unigram") { out.kind = RAD_TOK_UNIGRAM; @@ -942,6 +932,7 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t off, h.add_bos = in.add_bos ? 1u : 0u; h.add_eos = in.add_eos ? 1u : 0u; h.chat_template = tmpl; + h.flags = in.ignore_merges ? RAD_VOCAB_IGNORE_MERGES : 0; out.resize(sizeof(RadVocabHeader), 0); /* Each array is aligned to its own element so a mapped reader can point a typed pointer at @@ -1004,6 +995,7 @@ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocab out.pad = h->pad_id; out.unk = h->unk; out.sep = h->sep; out.add_bos = h->add_bos != 0; out.add_eos = h->add_eos != 0; + out.ignore_merges = (h->flags & RAD_VOCAB_IGNORE_MERGES) != 0; out.chat_template = S(h->chat_template); if (!in_file(h->tok_text_off, (uint64_t)h->n_tokens * sizeof(rad_stroff))) diff --git a/deploy/compose/common.yaml b/deploy/compose/common.yaml index 1fa27eab..afc29967 100644 --- a/deploy/compose/common.yaml +++ b/deploy/compose/common.yaml @@ -1,7 +1,7 @@ # The service every model file in this directory extends. It holds what any radiance container # needs on an AMD host; a model file adds only its container and its flags. # -# Each model takes both cards (--tp 2) and the same port, so run one at a time: +# Each model takes both cards (--tp 2; a -tp1 file one) and the same port, so run one at a time: # docker compose -f flashnext.yaml up -d start (it comes back after a reboot) # docker compose -f flashnext.yaml logs -f follow the log # docker compose -f flashnext.yaml down stop diff --git a/deploy/compose/flashnext-tp1.yaml b/deploy/compose/flashnext-tp1.yaml new file mode 100644 index 00000000..0c4350c3 --- /dev/null +++ b/deploy/compose/flashnext-tp1.yaml @@ -0,0 +1,24 @@ +# Qwen3.8-Flash-Next on one card: the production container of flashnext.yaml at --tp 1. The routed +# experts that do not fit the card sit in a 42 GiB pinned host pool, so the process pins about +# 49 GiB of host memory and wants a host with 64 GB of RAM; the n-gram table is read from the +# model file on the drive. +# +# A prefill step copies every pooled expert across the link once, so on one card prefill is bound +# by the link, and a 4096-token step pays that once for twice the tokens of a 2048-token one: 26K +# prompts prefill at 2545 tok/s against 1413. The checkpoint interval matches the step, since a +# prefill chunk never crosses a checkpoint. At 4 sequences the cache holds 301K tokens, one and a +# half 200K-token sessions. +name: radiance-flashnext-tp1 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-flashnext-tp1 + command: > + --model /models/qwen3.8-next-flash-fp8-iq4r-moe.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 4 --max-model-len 200000 + --placement expert_tiered --host-pool-mib 43000 --gpu-headroom-mib 96 + --kv-cache-dtype fp8 + --prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext-tp1 + --prefix-cache-disk-mib 131072 + --num-speculative-tokens 3 --max-num-batched-tokens 4096 --checkpoint-interval 4096 diff --git a/docker/licenses.sh b/docker/licenses.sh index b6e66b4e..0e91775c 100755 --- a/docker/licenses.sh +++ b/docker/licenses.sh @@ -3,8 +3,8 @@ # did not write. # # FILE... are the paths, in the build image, of every file copied into ROOT from outside the -# radiance install: the shared libraries, comgr, busybox, the GPU name table. Each is traced to the -# package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files +# radiance install: the shared libraries, comgr, busybox, curl, jq and the CA bundle's directory. +# Each is traced to the package that installed it, or to the FFmpeg stage's /opt/ffmpeg. Every package's license files # are copied to ROOT/usr/share/doc//, the license texts Debian's copyright files refer to # go to ROOT/usr/share/common-licenses/, and ROOT/usr/share/doc/THIRD-PARTY lists each component # with its version, its license files and where its source is. A file that no package owns, or a diff --git a/docker/llvm-check.sh b/docker/llvm-check.sh new file mode 100755 index 00000000..9876d7c6 --- /dev/null +++ b/docker/llvm-check.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# docker/llvm-check.sh BUILD -- the image's HIP compiler held to the two things it is for, on one of +# the build's own compile commands: r4d_hc_bf16.hip, the file whose code varied from build to build +# under ROCm's own clang. The command is run again four ways, outputs in a scratch directory: +# 1. pairing off, by ROCm's clang and by the image's: the device code must match byte for byte, +# so the llvm stage's libLLVM is ROCm's but for the patch; +# 2. pairing on, exactly as the build ran it, twice more by the image's clang: both must match +# the build's own object, so the pairing is repeatable. +# A mismatch fails the image build. +set -euo pipefail +B=$1 +STOCK=/opt/rocm/lib/llvm/bin/clang++ +IMAGE=/opt/rocm-repeatable/lib/llvm/bin/clang++ +OBJCOPY=/opt/rocm/lib/llvm/bin/llvm-objcopy +O=libr4d/CMakeFiles/libr4d.dir/r4d_hc_bf16.hip.o +fail() { echo "llvm-check: $*" >&2; exit 1; } + +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +cd "$B" +cmds=$(ninja -t commands libr4d) +line=$(grep -m1 -F -- "-o $O " <<< "$cmds") || fail "no compile command for $O" +eval "set -- $line" +args=("$@") +[ "${args[0]}" = "$IMAGE" ] || fail "the build compiled with ${args[0]}, not $IMAGE" +for a in "${args[@]}"; do + case "$a" in *amdgpu-enable-vopd*) fail "the build turned VOPD pairing off ($a)" ;; esac +done + +# variant NAME COMPILER [FLAG]: the build's command with this compiler, its object and depfile in +# the scratch directory, and FLAG appended; then the object's device code as NAME.fb. +variant() { + local name=$1 cc=$2 extra=${3:-} i=1 + local v=("$cc") + while [ $i -lt ${#args[@]} ]; do + case "${args[$i]}" in + -o) v+=(-o "$T/$name.o"); i=$((i + 2)); continue ;; + -MF) v+=(-MF "$T/$name.d"); i=$((i + 2)); continue ;; + *) v+=("${args[$i]}") ;; + esac + i=$((i + 1)) + done + [ -z "$extra" ] || v+=("$extra") + "${v[@]}" > "$T/$name.log" 2>&1 || { cat "$T/$name.log" >&2; return 1; } + "$OBJCOPY" --dump-section=.hip_fatbin="$T/$name.fb" "$T/$name.o" /dev/null +} + +OFF=-mllvm=-amdgpu-enable-vopd=false +pids=() +variant stock_off "$STOCK" "$OFF" & pids+=($!) +variant image_off "$IMAGE" "$OFF" & pids+=($!) +variant image_on1 "$IMAGE" & pids+=($!) +variant image_on2 "$IMAGE" & pids+=($!) +for p in "${pids[@]}"; do wait "$p" || fail "a compile of $O failed"; done +"$OBJCOPY" --dump-section=.hip_fatbin="$T/build.fb" "$O" /dev/null + +cmp -s "$T/stock_off.fb" "$T/image_off.fb" \ + || fail "with pairing off the image's clang and ROCm's emit different device code: the llvm stage did not rebuild ROCm's libLLVM" +cmp -s "$T/build.fb" "$T/image_on1.fb" && cmp -s "$T/build.fb" "$T/image_on2.fb" \ + || fail "with pairing on, three compiles of $O emitted different device code" +echo "llvm-check: r4d_hc_bf16.hip -- pairing off, ROCm's clang and the image's agree; pairing on, three compiles agree" diff --git a/docker/llvm-vopd-pairing.patch b/docker/llvm-vopd-pairing.patch new file mode 100644 index 00000000..21231bab --- /dev/null +++ b/docker/llvm-vopd-pairing.patch @@ -0,0 +1,23 @@ +The VOPD pairing fix the image's HIP compiler is built with (Dockerfile, stage `llvm`). + +VOPDPairingMutation caches each load's transitive load dependencies (LoadPredsCache), and +fuseInstructionPair adds edges after entries were filled, so they go stale. loadsMayOverlap stops +at the first witness while iterating a SmallPtrSet, whose order past eight entries is +the order of the pointers, so WHICH loads were cached before a fusion depends on heap addresses and +the pair decisions with it: the same source compiles to different code from run to run. A stale +entry can only miss dependencies and so only refuses pairs; dropping the cache after every fusion +makes every answer come from the current DAG. + +diff --git a/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp b/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp +index 29dec3b8b..b241a2f24 100644 +--- a/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp ++++ b/llvm/lib/Target/AMDGPU/GCNVOPDUtils.cpp +@@ -486,6 +486,8 @@ struct VOPDPairingMutation : ScheduleDAGMutation { + continue; + + if (fuseInstructionPair(*DAG, *ISUI, *JSUI)) { ++ // Fusion adds edges, so cached transitive load dependencies are stale. ++ LoadPredsComputed.reset(); + // Clear to prevent future checks/fusing + VOPDCapable[JIdx] = false; + break; diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 740ee56a..70ab80c5 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -3,7 +3,7 @@ The repository builds into one Docker image that holds the engine, its plugins, its tools and the recipes, and nothing else: it is assembled from scratch out of the install tree and exactly the shared libraries that tree loads. The host needs Docker, an AMD GPU and an `amdgpu` kernel driver -that supports ROCm 7.2. It does not need ROCm itself, a compiler, or ffmpeg. +that supports ROCm 10.1. It does not need ROCm itself, a compiler, or ffmpeg. The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for @@ -32,26 +32,29 @@ committed: no build directory, no uncommitted edit, no model file. It builds wit (`docker buildx`), which runs independent stages side by side and caches each one; with `-s` only the remote machine needs buildx. -The `Dockerfile` has three stages: +The `Dockerfile` has these stages: | stage | what it does | |---|---| | `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits and the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263). The distribution's build brings about 200 packages of encoders, filters and display libraries the engine never calls | -| `build` | `rocm/dev-ubuntu-24.04:7.2.4` plus cmake, ninja and g++-14. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle | -| `test` | `ctest -LE gpu`: every suite that runs without a card. The image is only produced if they pass | -| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, `amdgpu.ids`, and a static busybox. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks | +| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's own llvm-project, at the exact commit the image's `clang --version` names, with `docker/llvm-vopd-pairing.patch` applied and configured as ROCm ships it. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. The library is the only file of the compiler that changes | +| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Every device source is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image stay ROCm's own. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle | +| `test` | `docker/llvm-check.sh`, then `ctest -LE gpu`: every suite that runs without a card. The check recompiles one kernel file four ways -- with pairing off the image's compiler must emit ROCm's device code byte for byte, with pairing on three compiles must agree. The image is only produced if both pass | +| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, and a static busybox. ROCm's `libdrm_amdgpu` carries the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks | | `runtime` | `FROM scratch` and the rootfs. This is the image that ships | -The largest single file is comgr (about 150 MB), which the HIP runtime cannot initialise a device -without. There is no distribution in the shipped image: no package manager and no shell beyond busybox -(`docker exec -it sh`). JPEG XL input is refused by name, since its decoder needs libjxl. +The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), which the +HIP runtime cannot initialise a device without. There is no distribution in the shipped image: no +package manager and no shell beyond busybox (`docker exec -it sh`). JPEG XL input is refused +by name, since its decoder needs libjxl. A build container has no card to enumerate, so the GPU architecture must be named. A bare-metal `./build.sh` detects it instead. `libr4d` builds for gfx12 targets only; any other target in the list just gets no RDNA4 kernels. The ROCm version in the image has to be one the host's kernel driver supports. It is a build -argument (`ROCM_VERSION`, default 7.2.4). +argument (`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published +only with the `-full` suffix). The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from the `build` stage: @@ -120,6 +123,7 @@ the cards the engine runs on. | file | container | what it is | |---|---|---| | `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; idle sessions kept in host memory and on disk | +| `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences | | `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server | | `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 | | `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower | diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 2e5e6d6c..32970ecc 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -57,6 +57,7 @@ driver on the host. [`DOCKER.md`](DOCKER.md) covers it, along with ready compose |---|---| | **Required** | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads | | **Optional** | ROCm with `hipcc`, for AMD device kernels. Without it you get the host backend. Set `ROCM_PATH` if it is not at `/opt/rocm` | +| **With a card** | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup): the host writes every dispatch's arguments into VRAM, and startup refuses a card whose memory the CPU cannot reach | | **Optional** | OpenMP, used by the host kernel libraries if present | | **For the shell harnesses** | `curl` and `jq` | @@ -487,6 +488,27 @@ The cache never gets less than one `--max-model-len` sequence, and when both sid whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts off the card and gives the cache more. +**The next layer's experts are fetched ahead at decode.** The experts kept only in the pinned host +pool are read across the link by the routed GEMMs that need them, while those GEMMs run. At each +routed layer of a decode pass of up to 16 rows, the engine applies the *next* routed layer's router +to this layer's router input -- it predicts that layer's choice well -- and the card's second DMA +engine copies the two likeliest experts that are only in the pool onto the card while the rest of +this layer runs. Just before the next layer's GEMMs, their weight tables point at the copies that +have landed, so those GEMMs read them from VRAM. A copy holds the bytes of the pool slot it was made +from, so this changes no output; a copy that lands late is not used. It is on wherever the pool +holds experts (`--placement expert_tiered` or `auto`), off under `--deterministic` and where the +device backend has no second DMA engine, and the startup log says which (`expert prefetch on` / +`off`). It costs one hardware queue and a ring of six expert units on the card, both in the VRAM +receipt (`hardware queues`, `expert prefetch`). + +It pays only where the steps use enough of what it copies, so it measures that: every 2048 +predictions it looks at the share of its copies the steps routed, and under 30% it rests -- no +prediction, no copy -- for 8192 passes before measuring again (`expert prefetch resting`, once, in +the log). On Qwen3.8-Flash-Next at `--tp 1` with the `flashnext-tp1` flags the steps use about half +of the copies, and the decode step goes from 29.0 to 28.0 ms at one sequence and from 101.3 to 95.3 +ms at four. At `--tp 2` each card keeps most of its experts and the pool holds the ones the steps +rarely route; under a quarter of the copies were used, it was a loss, and the prefetch rests there. + **An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under @@ -1185,6 +1207,7 @@ for a model that takes no images or video. | `POST /v1/chat/completions` | chat, with tools, reasoning and streaming | | `POST /v1/completions` | raw text completion | | `POST /v1/embeddings` | needs a model with an embedding head, else 501 | +| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 โ€” ยง5.12 | | `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs โ€” ยง5.9 | | `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client โ€” ยง5.9 | | `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and the clients built on llama-server's own API โ€” ยง5.9 | @@ -1196,6 +1219,7 @@ for a model that takes no images or video. | `POST /apply-template` | the prompt a chat request renders to, as llama-server answers it | | `POST /v1/chat/completions/input_tokens` | how many tokens that prompt is | | `GET /server_info` | the whole configuration of the running engine | +| `GET /diagnostics` | the startup report as JSON โ€” every option and its source, the hardware read again now, the findings โ€” ยง7.1. Without `--api-key` it answers only a client on the same machine (ยง6.6) | | `GET /metrics` | Prometheus | | `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) | | `GET /get_tokenizer_info` | | @@ -1648,6 +1672,69 @@ agrees to float rounding. there and none here, which is OpenAI's default. The values themselves agree with llama-server's to bf16 rounding (within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included). +### 5.12 Decisions: `/v1/systemone` + +LiquidAI's d1-3B is a decision model on LFM2-VL. It is given a state โ€” text, any JSON value, +pictures, or a mix โ€” and named questions, and each answer is read off the model's distribution at +the position after the assistant header: `yes`/`no` for a `noul`, one code an option for a +`choice`, a digit a level for a `score`. Nothing is generated, so an answer is always in its +schema. The request and response are d1's own (`api.py` in the model's repository), and the +prompt it renders is d1's `prompt.py` string for string, since the model was trained on exactly +those. + +The endpoint answers only a container that says it is d1, which the checkpoint does not: convert +it with `--set decision.type=d1`. d1's prompt text, which radiance carries, is Liquid AI's under the +LFM Open License v1.0, as the model is (NOTICE). + +```sh +rad-convert ~/models/LiquidAI/d1-3B -o d1-3b-bf16.rad --set decision.type=d1 +radiance --model d1-3b-bf16.rad --port 8000 + +curl -s localhost:8000/v1/systemone -H 'Content-Type: application/json' -d '{ + "state": "I was charged twice this month, please refund one of them.", + "questions": { + "refund": {"type": "noul", "instructions": "Is the customer asking for a refund?"}, + "team": {"type": "choice", "instructions": "Which team should handle this?", + "criteria": {"billing": "Charges, refunds, invoices", "technical": "App or site faults"}}, + "urgency": {"type": "score", "instructions": "How urgent is this?", + "criteria": ["Can wait", "Today", "Blocking the customer now"]}}}' +``` + +The answer is an object of the same names, in the same order: + +``` +{"answers": { + "refund": {"type": "noul", "noul": P(yes)}, + "team": {"type": "choice", "choice": "billing", "confidence": P(billing), + "probabilities": {"billing": ..., "technical": ...}}, + "urgency": {"type": "score", "score": the expected level, "confidence": P(likeliest level), + "probabilities": {"0": ..., "1": ..., "2": ...}, + "legend": {"0": "Can wait", "1": "Today", "2": "Blocking the customer now"}}}, + "usage": {"input_tokens": N, "output_tokens": 0}} +``` + +- **`state`** is required: a string, any JSON value (rendered as indented JSON, keys in the order + sent), or `null` with pictures alone. +- **`questions`** is an object of named questions, answered in the order sent. A question is + `type` (`noul`, `choice` โ€” the default โ€” or `score`), `instructions`, and `criteria`: for a + `noul` optionally `{"true": ..., "false": ...}`; for a `choice` the options, name to description; + for a `score` 2 to 10 level descriptions, lowest first. +- **`images`** is an array of `data:` URLs, placed ahead of the state. Each picture is first + scaled down to at most 1024 x 1024 pixels' area, as d1's runner does, then cut as LFM2-VL's + processor cuts it: whole when it is small, else into 512-pixel tiles plus a thumbnail. +- **`noul`** is P(yes); a `choice` names its most probable option; a `score` is the expected level. + Each answer is a softmax over its options' raw logits, an option scoring its best spelling. +- **`usage.input_tokens`** counts what the model read as d1 counts it: the shared state once and + each question's own tail. + +**Several questions read the state once.** The first runs alone and leaves the state's end in the +prefix cache โ€” its attention blocks and a checkpoint of LFM2's convolutions there โ€” and the rest +start from it together, each computing only its own question. A single question is one pass of +the whole prompt, tokenised as one text, as d1 does. + +Against d1's own runner in float32, on eight text cases (one and several questions, JSON and long +log states): every choice and every `input_tokens` equal, worst probability difference 0.0044. + ## 6. Operate it ### 6.1 The dashboard @@ -1688,6 +1775,7 @@ curl -s localhost:8000/stats | jq # counters, memory, throughput curl -s localhost:8000/sessions | jq # what is stored and where curl -s localhost:8000/graph | jq # the resolved kernel graph curl -s localhost:8000/server_info | jq # model, cards, KV, draft depth, wire +curl -s localhost:8000/diagnostics | jq # the startup report, hardware read again now (ยง7.1) ``` `/server_info` is the operator's first question asked of a process that is already running: which @@ -1782,6 +1870,11 @@ authenticated probe is a server that reports itself down, and the dashboard page `/dashboard`), which holds no data โ€” on a 401 it shows a key field, keeps the key in the browser's storage and sends it on every fetch of data it makes. +Without a key, `/diagnostics` answers only a client on the same machine (a loopback address) and +every other one 403: it describes the host โ€” kernel, boot parameters, PCI layout, memory limits โ€” +and not just the model. Read it with `curl localhost:8000/diagnostics` on the machine, or start +the server with `--api-key` to read it from elsewhere. + The key is checked, not encrypted: on any network you do not control, bind to localhost and put a TLS-terminating reverse proxy in front: @@ -1801,6 +1894,70 @@ released until it does. ## 7. When something goes wrong +### 7.1 Start with the startup report + +The last thing startup prints before `serving on` is one block, `STARTUP REPORT`, in three parts. +A startup that stops prints it too, after the error, with what it had resolved by then, and ends +it with an `E` line that repeats the error, so the tail of the log still shows it. It is the part +of a log to paste into an issue. + +- **CONFIGURATION** lists every option the command line takes, from the same table `--help` + prints. Each line shows the value in force and where it came from: `default`, `command line`, + an environment variable, or `auto`. An `auto` line carries the reason under it: the drafter's + depth, where the embedding and the n-gram table went and why, the VRAM split, the placement + strategy, and each sampler default with the file it came from, or the built-in default the + file left it at. `--api-key` shows only `set` or `not set`. +- **ENVIRONMENT** names the `RADIANCE_*` variables that are set (ยง8). It shows only the names, + never the values. +- **DERIVED** shows what startup worked out that no single option states: the VRAM split with the + budget report under it, the weights by tier, the KV cache, and the kernel libraries selection + used, with the attention rows by name. +- **HARDWARE** reads the machine from `/proc` and `/sys`, the same files inside the image. It + covers the CPU, RAM, swap, kernel, container, cgroup and memlock limits, transparent huge + pages, the IOMMU mode from the cards' own groups, TTM's page limit (`ttm.pages_limit`) and + `cwsr_enable`. Each display device gets its gfx target, VRAM and BAR, and its PCIe link **at + every hop up to the root port**. A card with a switch on it reports its own link at full speed + whatever the slot does, so a root port parked at half speed only shows here. The block also + shows the card's PCIe power levels, its power cap against its default and its maximum, any + voltage offset, and its runtime power management. The cgroup limit is the tightest one from + the process's own cgroup up to the root. +- **FINDINGS** lists warnings first, then notes. Each says what was seen, what it costs, and the + fix. Every warning is also printed as a `W` line of its own. + +``` +I STARTUP REPORT -- radiance 1.4.0 +I CONFIGURATION -- every option, the value in force, and where it came from +I --model /models/flashnext.rad [command line] +I --tp 2 [command line] +I --num-speculative-tokens 3 [auto] +I the depth the drafter in this container states as its operating point +I --embedding-placement ram [auto] +I the table is 606.25 MiB a rank: pinned in host memory and read over the link in place, ... +I ... +I HARDWARE +I card 0000:07:00.0 rank 1 (device 1) gfx1201 "AMD Radeon AI PRO R9700" 31.86 GiB VRAM NUMA -1 driver amdgpu card1 +I link 00:01.3 16.0 GT/s x8 (max 32.0 GT/s x8) -> 05:00.0 32.0 GT/s x16 (max 32.0 GT/s x16) -> ... -> 07:00.0 32.0 GT/s x16 (max 32.0 GT/s x16) [read at 90% busy] +I pcie 0: 2.5GT/s, x8 250Mhz | *1: 16.0GT/s, x8 616Mhz | 2: 32.0GT/s, x8 1143Mhz +I power cap 280 W (default 300 W, max 330 W) | voltage offset -75 mV | sclk 500-2350 MHz | ... +I FINDINGS -- 3 warnings, 4 notes +I WARN link-below-max: card 0000:07:00.0 (rank 1): the PCIe link at 0000:00:01.3 runs 16.0 GT/s x8 of its 32.0 GT/s x8 while the card is 90% busy +I why: every copy between host memory and the card ... cross this link, so ... a tensor-parallel step waits for it +I fix: a link stuck one level down after long uptime has been cleared by a reboot; ... +``` + +A PCIe link at rest parks at its lowest speed, so a link below its maximum is only a finding when +the card was busy as it was read. At startup the cards are mostly idle. `GET /diagnostics` reads +the hardware again and runs the same checks, so call it during a long prefill to see the links and +power levels under load. A reading is reused for a second, and the power-management files (DPM +levels, power caps, busy percentage) are read only for the cards the server runs on: the driver +answers them from the card's firmware under a lock, and wakes a sleeping card to do it. + +```sh +curl -s -H "Authorization: Bearer $KEY" localhost:8000/diagnostics | jq '.findings' +``` + +### 7.2 Messages and what they mean + | What you see | What it means | What to do | |---|---|---| | `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement | @@ -1813,7 +1970,7 @@ released until it does. | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | | `pool allocation refused` with `backing allocation of โ€ฆ refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` ร— `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` | | `host_pool: backing allocation of โ€ฆ refused: rad_dev_alloc(โ€ฆ): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line | -| `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception โ€ฆ GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the engine warns at startup when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended | +| `a synchronisation has waited 5 s` naming a kernel, then `no queue has advanced`, then `HW Exception โ€ฆ GPU Hang` and a reset in `journalctl -k` (`MES failed to respond to msg=REMOVE_QUEUE`, `MODE1 reset`) | The card stopped running the queue. The kernel named is where it stopped, not necessarily why. The driver resets the whole card, VRAM included, and the engine is aborted. The usual cause is compute wave save/restore being off: the driver evicts a process's queues whenever host memory the card maps is moved under memory pressure, and with `cwsr_enable=0` it cannot preempt a running queue, so the eviction waits for a queue a serve never lets drain. A voltage offset or other clock instability is the other cause seen on R9700s. If the stall line says the queues **advanced**, the wait was long rather than stuck, and nothing is wrong | `cat /sys/module/amdgpu/parameters/cwsr_enable` must print `1` (the startup report warns when it is `0`); set `amdgpu.cwsr_enable=1`, rebuild the initramfs and reboot. Remove any `OD_VDDGFX_OFFSET` (`pp_od_clk_voltage`). A reset puts the power cap, fan curve and voltage offset back to firmware defaults, so re-apply them before every start rather than once at boot. Keep the devcoredump under `/sys/class/drm/card*/device/devcoredump/data`; a reboot loses it. `docker inspect` shows exit code 0 for a container Docker has already restarted, which says nothing about how the old process ended | | `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | | `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it | | `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` | diff --git a/docs/OPS.md b/docs/OPS.md index 28d74441..d190d409 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -165,6 +165,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th | `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout | | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? โ†’ `y` | | `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | +| `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | | `add` | `M`(range) `n` `dtype` | `a`, `b` โ†’ `y` | | `mul` | `M`(range) `n` `dtype` | `a`, `b` โ†’ `y` | | `silu_mul` | `M`(range) `n` `dtype` | `gate_up` โ†’ `y` (splits `[M,2n]` into gateยทup) | @@ -493,6 +494,12 @@ is `[4, M]` (row, column, grid height, grid width), sampled bilinearly with the table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s dtype before the add. +**`grid_embed_aa`** is the same addition with SigLIP2's resample: torch's +`F.interpolate(mode="bilinear", align_corners=False, antialias=True)`. Per axis a triangle filter on +half-pixel centres, widened by the scale when the grid is smaller than the table, its taps inside the +table normalised to sum to one; separable, f32, rounded once. A different function from +`grid_embed`'s, and so a different op rather than a mode a library could ignore. + | op | params | operands | |---|---|---| | `attn_paged_gate_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? โ†’ `out`; `gate` โ†’ `q8`, `q8_scale` | @@ -910,6 +917,7 @@ form exists, as for `ar_hc_write`. | `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? โ†’ `ids`, `ahead_ids`? | | `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w โ†’ `gv`, `gvn` | | `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? โ†’ `y` | +| `causal_conv1d` | `M`(range) `n` `width` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `cache_idx`?, `has_init`?, `num_accepted`? โ†’ `y` | Separate from `gemm_nt` because `lm_head` is its own access class (`RAD_ACCESS_VOCAB`) and because the sampler wants to fuse against it: at a 151K vocab and batch 256 the logits are ~77 MiB a step, @@ -1172,6 +1180,16 @@ it takes the union of the two contracts instead: `has_init` is prefill's questio The residual add is folded in because the reference is `gv + silu(conv(gvn))` and the two tensors are both `[M, hc*n]` โ€” 10240 wide here. `resid` absent leaves the plain convolution. +### `causal_conv1d`: `ple_conv` without the PLE + + y[t] = sum_j w[c][j] * x[t - (width-1-j)] + +LFM2's short convolution: depthwise, causal, undilated, with no activation and no residual โ€” the +gates around it are separate `mul`s in the architecture. The window and its three optional operands +are `ple_conv`'s at dilation one, so an architecture issues it the same way, once over its decode +rows with `num_accepted` and once over its prefill rows without. libr4d, libref and libavx each +serve both ops from one implementation. + ## Sampling Every sampler is a kernel, not a host lift. `llama.cpp`'s chain is kept as a **host reference** diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index 28c923a9..1dd0edbe 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -52,13 +52,14 @@ any shape change in a header a plugin compiles against (`rad_abi.h` says which). both in-tree host libraries say โ€” or `""` for a plugin that really is portable. It is printed, not trusted: what the engine checks is the code objects your library actually carries (ยง10). -Four more exports are optional, each looked up by exactly this name: +Five more exports are optional, each looked up by exactly this name: | symbol | says | |---|---| | `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` **declines this machine** โ€” the library is unloaded and the rest of the installation carries on; any other negative status refuses it as an error | | `void rad_plugin_close(void)` | called once at shutdown | | `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap | +| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic out of the way while it runs. 2: each launch ends that itself once the other ranks' bytes have landed, through the `link_gate` parameter (rad_abi.h). Without it only the `all_reduce` op counts as one | | `int rad_plugin_reference(void)` | nonzero: this library is a **reference implementation** โ€” ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref says so through this, as any library would | --- diff --git a/docs/TOOLS.md b/docs/TOOLS.md index d0bbcec5..67394691 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -348,6 +348,8 @@ rad-kbench -m moe.rad --max-cases 1 --record data/kernels_moe.rkb | `--bench` | time each case that passes, on the same bytes | | `--bench-iters N`, `--bench-reps N` | launches per rep (20), timed reps (3) | | `--bench-warm-ms N` | untimed launches before each timed window (default 500) | +| `--bench-flush MIB` | time cold: read MIB through the caches before every timed launch (256 empties an R9700's 8 MiB L2 and 64 MiB last level) and time each launch alone between two device events. Implies `--bench` | +| `--timing-only` | time every device kernel and check nothing: no reference run, read-back, margins or fusion chain, host rows skipped. For comparing builds a checked run has already passed; refuses `--record`. Implies `--bench` | | `--report FILE` | write the markdown report | | `--analysis FILE` | splice in a fragment from `tools/kbench-analysis.sh` | | `--num-speculative-tokens N` | draft depth to declare at | @@ -365,8 +367,17 @@ running on the same box, pass something small explicitly: rad-kbench --home $RADIANCE_HOME --max-cases 1 --max-bytes 1024 ``` -**`--bench` is cache-warm.** It cannot rank a bandwidth-bound kernel the way production runs it. -Read the caveat the report prints about the GB/s column. +**`--bench` is cache-warm.** Every launch of a timed window reuses one set of operands, so a weight +that fits in the last-level cache is read from it after the first launch: a 52 MB bf16 decode weight +times at 1.45 TB/s warm and at 565 GB/s, the card's DRAM rate, cold. The engine streams its weights +cold every step. `--bench-flush 256` measures that; use it whenever the comparison is about how a +kernel waits on memory. Its numbers are device time per launch and are not comparable with a warm +run's, which divide a window's wall time by its launches. + +**`--timing-only` runs the card hotter.** With no host-side check between cases the card is busy +almost all of the run, and on the same binary its times come out 0.3-0.8% above a checked run's in +total, compute-bound kernels 1-2%. Compare builds within one mode, interleaved; the ratio between +two builds matched the checked mode's to within half a percent. **`--max-cases`.** A 62-layer model presents the same kernel at the same shape sixty times and only the weights differ. The default of 4 is not a sample of anything interesting; `--max-cases 1` is diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e0b9589f..d9034c5d 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -117,6 +117,7 @@ std::vector build_cases() { HF("wadd", 1), HF("gate_eps", 1e-6) }); add("ple_conv", { HI("M", 9), HI("n", 128), HI("width", 4), HI("dilation", 2), HS("dtype", dt) }); + add("causal_conv1d", { HI("M", 9), HI("n", 128), HI("width", 3), HS("dtype", dt) }); } add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) }); @@ -309,6 +310,10 @@ std::vector build_cases() { HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"), HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) }); add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) }); + /* Two table sides. A drawn grid is never larger than the table, so enlarging is + * avx_check's hand-built case. */ + add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) }); + add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) }); } /* MoE. `a_order` exists because the two grouped GEMMs of one routed block disagree about it, diff --git a/libavx/avx_check.cpp b/libavx/avx_check.cpp index 5a2f6b80..52174e0e 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -624,6 +624,31 @@ static bool hand_cases(const Lib& ref, const Lib& avx, bool verbose, int* n_chec .pi("M", BAND).pi("n", N).pi("width", WIDTH).pi("dilation", DIL).ps("dtype", "f32"); hs.push_back(std::move(c)); + /* LFM2's form of the same window: width 3, undilated, no residual and no activation. */ + const int64_t CW = 3, CHIST = CW - 1, CSL = CHIST + 2; + Hand k("M = 64 over 5 rows, verifies of 3 and 2", "causal_conv1d", 1e-5); + k.dense(RAD_F32, { T, N }, hfill(55)) + .dense(RAD_F32, { N, CW }, hfill(56, 0.5f)) + .dense(RAD_F32, { 2, N, CSL }, hfill(57), true) + .idx({ 0, 3, 5 }) + .idx({ 1, 0 }) + .idx({ 7, 9 }) + .idx({ 2, 3 }) + .dense(RAD_F32, { T, N }, hfill(58), true) + .pi("M", BAND).pi("n", N).pi("width", CW).ps("dtype", "f32"); + hs.push_back(std::move(k)); + + /* The antialiased resample ENLARGING a 4 x 4 table (a drawn case's grid is never larger + * than the table), one row shrinking it, and a 1 x 1 grid. */ + static const int32_t kAaCrd[4][6] = { { 0, 6, 3, 1, 0, 5 }, { 0, 8, 4, 2, 0, 1 }, + { 7, 7, 7, 2, 1, 7 }, { 9, 9, 9, 3, 1, 9 } }; + Hand ga("a 4 x 4 table onto 7 x 9, 2 x 3 and 1 x 1 grids", "grid_embed_aa", 1e-6); + ga.dense(RAD_F32, { 6, N }, hfill(59), true) + .dense(RAD_F32, { 16, N }, hfill(60)) + .dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kAaCrd[i / 6][i % 6]; }) + .pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32"); + hs.push_back(std::move(ga)); + Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0); n.idx({ 11, 12, 13, 21, 22 }) .dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true) diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 96b4784e..090ec8ea 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -86,7 +86,7 @@ int avx_isa_force(int level); /* ---- elementwise and norms */ \ X(rmsnorm) X(rmsnorm_add) X(hc_enter) X(hc_read) \ X(hc_write) X(mtp_enter) X(layernorm) X(add) \ - X(grid_embed) \ + X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ X(mul) X(silu_mul) X(gelu) X(silu) \ X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ diff --git a/libavx/avx_misc.cpp b/libavx/avx_misc.cpp index cc491a83..061722df 100644 --- a/libavx/avx_misc.cpp +++ b/libavx/avx_misc.cpp @@ -176,17 +176,16 @@ AVX_KERNEL(ple_gate) { * Absent, every token commits and the last (width-1)*dilation inputs land at offset zero. The * write happens in a SECOND pass after every read is done, because a sequence longer than the * window would otherwise overwrite history it is still reading. */ -AVX_KERNEL(ple_conv) { - if (a->n_t < 9) return RAD_E_INVAL; - const RadTensor* x = rad_arg_in(a, 0); - const RadTensor* w = rad_arg_in(a, 1); - const RadTensor* cs = rad_arg_in(a, 2); - const RadTensor* cu = rad_arg_in(a, 3); - const RadTensor* resid = rad_arg_in(a, 4); - const RadTensor* sidx = rad_arg_in(a, 5); - const RadTensor* hini = rad_arg_in(a, 6); - const RadTensor* nacc = rad_arg_in(a, 7); - const RadTensor* y = rad_arg_in(a, 8); +/* ONE BODY FOR ple_conv AND causal_conv1d (LFM2's short convolution: undilated, no activation, no + * residual), as in libref, so the two cannot disagree about the window's layout. */ +struct ConvOps { + const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; + bool silu; +}; + +static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { + const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid; + const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y; if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL; const int64_t n = p_int(a, "n", 0); @@ -260,7 +259,7 @@ AVX_KERNEL(ple_conv) { acc += vv * tap[j]; } const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f; - stt(y, (bos + t) * yrow + c * ycol, r + acc / (1.0f + std::exp(-acc))); + stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + std::exp(-acc)) : acc)); } } @@ -298,6 +297,22 @@ AVX_KERNEL(ple_conv) { return RAD_OK; } +AVX_KERNEL(ple_conv) { + if (a->n_t < 9) return RAD_E_INVAL; + return depthwise_causal_conv(a, { rad_arg_in(a, 0), rad_arg_in(a, 1), rad_arg_in(a, 2), + rad_arg_in(a, 3), rad_arg_in(a, 4), rad_arg_in(a, 5), + rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true }); +} + +/* ple_conv's operands without `resid`, at dilation one and with no activation. */ +AVX_KERNEL(causal_conv1d) { + if (a->n_t < 8) return RAD_E_INVAL; + if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL; + return depthwise_causal_conv(a, { rad_arg_in(a, 0), rad_arg_in(a, 1), rad_arg_in(a, 2), + rad_arg_in(a, 3), nullptr, rad_arg_in(a, 4), + rad_arg_in(a, 5), rad_arg_in(a, 6), rad_arg_in(a, 7), false }); +} + /* ------------------------------------------------------------------ ngram_ids * * ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h]. diff --git a/libavx/avx_norm.cpp b/libavx/avx_norm.cpp index 3f288d7e..4323bee5 100644 --- a/libavx/avx_norm.cpp +++ b/libavx/avx_norm.cpp @@ -284,3 +284,67 @@ AVX_KERNEL(grid_embed) { } return RAD_OK; } + +/* ------------------------------------------------------------------ grid_embed_aa */ +/* The table resampled as torch's F.interpolate(bilinear, align_corners=False, antialias=True) does + * it -- SigLIP2's position embedding -- and added in: libref's grid_embed_aa, operation for + * operation. Per axis a triangle filter on half-pixel centres, widened by the scale when + * shrinking, its taps inside the table normalised; the rows summed first, f32, rounded once + * before the add. A coordinate outside its grid is clamped into it. */ +static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) { + if (size < 1) size = 1; + at = at < 0 ? 0 : (at >= size ? size - 1 : at); + const float scale = (float)side / (float)size; + const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support; + const float center = scale * ((float)at + 0.5f); + int64_t a = (int64_t)(center - support + 0.5f), b = (int64_t)(center + support + 0.5f); + if (a < 0) a = 0; + if (b > side) b = side; + float total = 0.0f; + for (int64_t j = a; j < b; ++j) { + const float d = std::fabs(((float)j - center + 0.5f) * inv); + w[j - a] = d < 1.0f ? 1.0f - d : 0.0f; + total += w[j - a]; + } + for (int64_t j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f; + *lo = a; + *cnt = b > a ? b - a : 0; +} + +AVX_KERNEL(grid_embed_aa) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; + const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0); + const int64_t side = p_int(a, "side", 0); + if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows) + return RAD_E_SHAPE; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + const int64_t ts = laststride(tab); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + int64_t g[4]; + for (int c = 0; c < 4; ++c) g[c] = ldi(crd, c * cs + r * ms); + float* wh = scratch_f32((size_t)(2 * side)); + float* ww = wh + side; + int64_t h0 = 0, nh = 0, w0 = 0, nw = 0; + aa_taps(g[0], g[2], side, wh, &h0, &nh); + aa_taps(g[1], g[3], side, ww, &w0, &nw); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int64_t y = 0; y < nh; ++y) { + float row = 0.0f; + for (int64_t c = 0; c < nw; ++c) + row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) * ww[c]; + acc += row * wh[y]; + } + float pe = acc; + if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe)); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); + } + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 96137405..98ddc3d2 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -109,6 +109,11 @@ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width" static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"), OPD_O("num_accepted"), OUT("y") }; +static const RadParamSpec pCausalConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), + P_STR("dtype") }; +static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), + OPD_O("cache_idx"), OPD_O("has_init"), + OPD_O("num_accepted"), OUT("y") }; static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; @@ -495,6 +500,8 @@ static const RadOpSchema kSchemas[] = { { "layernorm", ARR(pLayernorm), ARR(oLayernorm), "layer norm with gain and optional bias." }, { "grid_embed", ARR(pGridEmbed), ARR(oGridEmbed), "x += a side x side position table resampled bilinearly to the row's grid." }, +{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), + "x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." }, { "add", ARR(pMnD), ARR(oBinary), "elementwise sum." }, { "mul", ARR(pMnD), ARR(oBinary), "elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." }, @@ -525,6 +532,8 @@ static const RadOpSchema kSchemas[] = { "PLE gate: three grouped norms, a dot, a signed sqrt." }, { "ple_conv", ARR(pPleConv), ARR(oPleConv), "PLE's dilated depthwise conv, silu and residual add." }, +{ "causal_conv1d", ARR(pCausalConv), ARR(oCausalConv), + "depthwise causal conv with ple_conv's window, no activation and no residual (LFM2)." }, { "ngram_ids", ARR(pNgramIds), ARR(oNgramIds), "hashed n-gram row ids for PLE." }, { "gather_rows", ARR(pMnD), ARR(oGather), "y[i,:] = x[idx[i],:]." }, { "scatter_rows", ARR(pMnD), ARR(oScatterRows), @@ -697,6 +706,9 @@ SIMPLE("avx_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT L(layernorm)), SIMPLE("avx_grid_embed", "grid_embed", "elem", "bilinear resample of a learned position grid, added in", DT_FLOAT, L(grid_embed)), +SIMPLE("avx_grid_embed_aa", "grid_embed_aa", "elem", + "antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT, + L(grid_embed_aa)), SIMPLE("avx_add", "add", "elem", "elementwise sum", DT_FLOAT, L(add)), SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT, L(mul)), SIMPLE("avx_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, L(act_mul)), @@ -732,6 +744,8 @@ SIMPLE("avx_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot DT_FLOAT, L(ple_gate)), SIMPLE("avx_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add", DT_FLOAT, L(ple_conv)), +SIMPLE("avx_causal_conv1d", "causal_conv1d", "conv", "depthwise causal conv, no activation", + DT_FLOAT, L(causal_conv1d)), SIMPLE("avx_cast", "cast", "elem", "dtype conversion", DT_ANY, L(cast)), SIMPLE("avx_softmax", "softmax", "elem", "row-wise softmax", DT_FLOAT, L(softmax)), SIMPLE("avx_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row", diff --git a/libr4d/r4d.h b/libr4d/r4d.h index b497ab09..b3038fbc 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -281,11 +281,13 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla long stream, long nblocks, long nthreads, long drain, long acq); // The exact all-reduce of `y` [M][n] bf16 with hc_write as its epilogue: h[r][c*n + i] += // inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and -// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. +// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate` +// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed); `gate_ctr` +// is the instance's block counter for it. The gather form below takes the same pair. void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream, long nblocks, long nthreads, - long drain, long acq); + long drain, long acq, long gate, long gate_ctr); // The same with the MoE gather as its prologue: y is not read but produced -- the routed experts' // rows `ye` [M*top_k][ye_ld] summed back to token order by the weights `ew` [M][ew_ld] and the // sorted list `sorted` [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded @@ -298,19 +300,21 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream, long nblocks, long nthreads, - long drain, long acq, long inv); + long drain, long acq, long inv, long gate, long gate_ctr); // r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's // format and arithmetic, its loc_pack and scratch split): byte-identical to all_reduce on that wire // then hc_write, and with `ye` non-zero to moe_gather, then those two. The gather's operands are // r4d_ar_gather_hc_write's; its slot table is built in LDS, and the grid is widened until a -// block's table fits. M*n must be a multiple of 64. Returns 0, or a negative code for a shape it -// does not serve. +// block's table fits. M*n must be a multiple of 64. A non-zero `gate` is the engine's link word, +// ended by the launch once the peer's bytes have landed (r4d_ar_link_landed); `gate_ctr` is the +// instance's block counter for it. Returns 0, or a negative code for a shape it does not serve. int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, long scale_off_bytes, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, - long stream, long nblocks, long nthreads, long drain, long acq); + long stream, long nblocks, long nthreads, long drain, long acq, + long gate, long gate_ctr); int r4d_ar_max_blocks(void); // the two 2-rank kernels void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit payload only diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 2e52c93c..65bd7d87 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -123,6 +123,7 @@ struct ArInst { /* Where the exchange buffers live: 0 in each rank's own VRAM, written by its peers over P2P; * 1 in pinned host memory that every card reaches over its own link (build, below). */ int host = 0; + long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */ }; /* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one @@ -139,6 +140,10 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } +/* The sequence counters' allocation in words: 2 * nbw (r4d_ar_seq.h) and, after them, the block + * counter r4d_ar_link_landed keeps, padded to a cache line. */ +long kSeqWords(long nbw) { return 2L * nbw + 32; } + /* Build the world. `max_numel` is the largest message any launch on this instance will carry. * * ONE SIZING RULE FOR THE WHOLE FAMILY, which is also what libr4d's own driver did ("one set @@ -220,8 +225,8 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); } } - sq = r4d_ar_ipc_alloc(2L * maxb * 4, 1, handle, &hlen); - if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(2L * maxb * 4, 0, handle, &hlen); }); + sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen); + if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen); }); if (!sc || !fl || !sq) return RAD_E_NOMEM; /* SAY IT, because the fallback above changes what the KERNEL's fence settings mean. The @@ -254,6 +259,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->my_flags = fl; in->my_seq = sq; in->locpack = lp; + in->gate_ctr = sq + 2L * maxb * 4; /* the word after the sequence counters (r4d_ar_seq.h) */ { std::lock_guard lk(g_rv.m); @@ -482,6 +488,15 @@ extern "C" void r4d_rad_ar_fini(void* instance) { /* ------------------------------------------------------------------ launch helpers */ +/* THE ENGINE'S LINK WORD, where it handed one (rad_abi.h, `link_gate`). Over P2P the fused kernels + * end the hold as the peer's push lands, on either wire, and say so (RAD_LINK_ENDED); through the + * host mailbox it is the reduce that reads those bytes across the link, so those launches return + * RAD_OK and leave the hold to the engine. */ +static long link_gate(const RadArgs* a) { + long long g = 0; + return rad_args_geti(a, "link_gate", &g) ? (long)g : 0L; +} + enum { AR_X = 0, AR_Y }; struct ArCall { @@ -1350,26 +1365,32 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { if (!in->locpack) return RAD_E_STATE; int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, R4D_AR_WHT6_NB_CAP); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; const int rc = r4d_ar_hc_write_wht6( in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, r4d_addr(ye), r4d_addr(ew), r4d_addr(so), sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig, - (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq); - return rc == 0 ? RAD_OK : RAD_E_SHAPE; + (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq, + early, early ? in->gate_ctr : 0L); + if (rc != 0) return RAD_E_SHAPE; + return early ? RAD_LINK_ENDED : RAD_OK; } int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; const int rc = r4d_ar_gather_hc_write( in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, r4d_addr(ye), r4d_addr(ew), r4d_addr(so), sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads, - cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L); - return rc == 0 ? RAD_OK : RAD_E_SHAPE; + cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early, + early ? in->gate_ctr : 0L); + if (rc != 0) return RAD_E_SHAPE; + return early ? RAD_LINK_ENDED : RAD_OK; } /* AT FOUR RANKS, EXACT WIRE ONLY: r4d_rad_ar_hc_write_4rank with the gather in front, on an @@ -1477,23 +1498,27 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { if (!in->locpack) return RAD_E_STATE; int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, R4D_AR_WHT6_NB_CAP); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; const int rc = r4d_ar_hc_write_wht6( in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, - cfgv.drain, cfgv.acq); - return rc == 0 ? RAD_OK : RAD_E_SHAPE; + cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L); + if (rc != 0) return RAD_E_SHAPE; + return early ? RAD_LINK_ENDED : RAD_OK; } int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap); if (nblocks > in->max_blocks) nblocks = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; R4D_TRY("ar_hc_write", r4d_ar_hc_write(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s, - nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq)); - return RAD_OK; + nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early, + early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; } /* AT FOUR RANKS, EXACT WIRE ONLY: the wide one-shot with the write as its epilogue. The four-rank diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 384d76a6..1af343d8 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -142,9 +142,11 @@ __global__ void r4d_ar_hc_write_kernel( int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, - int slot_stride16, int drain, int acq, unsigned int nbw) { + int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate, + unsigned int* gate_ctr) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int slot = (int)s_slot; @@ -175,6 +177,7 @@ __global__ void r4d_ar_hc_write_kernel( } } __syncthreads(); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); const int wpr = n >> 3; // 16B words a row @@ -225,12 +228,13 @@ __global__ void r4d_ar_gather_hc_write_kernel( unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G, - const int* __restrict__ inv) { + const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; __shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS]; __shared__ float s_w[R4D_ARG_ROWS * R4D_ARG_SLOTS]; __shared__ float s_g[R4D_ARG_ROWS]; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; const int slot = (int)s_slot; @@ -286,6 +290,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( } } __syncthreads(); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); if (acq) __threadfence_system(); for (int k = start + tid; k < end; k += nt) { @@ -398,7 +403,7 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads, - long drain, long acq) { + long drain, long acq, long gate, long gate_ctr) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8"); if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words"); @@ -415,7 +420,8 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m r4d_ar_hc_write_kernel<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, - n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw); + n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, + (long long*)gate, (unsigned int*)gate_ctr); } int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, @@ -423,7 +429,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream_i, long nblocks, long nthreads, - long drain, long acq, long inv) { + long drain, long acq, long inv, long gate, long gate_ctr) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2; @@ -466,13 +472,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, - (const int*)inv); + (const int*)inv, (long long*)gate, (unsigned int*)gate_ctr); } else { r4d_ar_gather_hc_write_kernel<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, - nullptr); + nullptr, (long long*)gate, (unsigned int*)gate_ctr); } return (int)hipGetLastError(); } diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.hip b/libr4d/r4d_ar_oneshot_2rank_wht6.hip index dc353b1f..afe25030 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.hip +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.hip @@ -77,12 +77,14 @@ __global__ void r4d_ar_hc_write_wht6_kernel( unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n, int hc, long irow, long hrow, int n_groups, int n_chunks, long slot_stride_bytes, - long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max) { + long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max, + long long* gate, unsigned int* gate_ctr) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE; const int lig = lane & (LPG - 1), gw = lane / LPG; __shared__ unsigned int s_seq, s_slot; extern __shared__ int s_tab[]; // slots, weights: [rows_max * top_k]; gates: [rows_max] + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph) const unsigned int s = s_seq; const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, @@ -145,6 +147,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel( wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc); wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int c = c0 + wid; c < c1; c += nwarp) wht6_reduce_chunk(st, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, w.l_pay, w.l_sc); @@ -155,7 +158,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo long scale_off_bytes, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, - long stream_i, long nblocks, long nthreads, long drain, long acq) { + long stream_i, long nblocks, long nthreads, long drain, long acq, + long gate, long gate_ctr) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if ((M * n) % GROUP) return -1; @@ -197,7 +201,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo (unsigned short*)y, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, \ (unsigned short*)h, (int)n, (int)hc, irow, hrow, n_groups, n_chunks, slot_stride_bytes, \ - scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max) + scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max, \ + (long long*)gate, (unsigned int*)gate_ctr) if (gather) LF(true, kWht6FusedCG); else LF(false, kWht6FusedCG); #undef LF diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index 7ee43d52..27622d0f 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -5,7 +5,7 @@ // instance's buffers has to take the step identically or the two ranks stop agreeing. // // THE COUNTER ALLOCATION IS 2 * nbw WORDS, zeroed once, where nbw is the block capacity the flag -// array was sized for: +// array was sized for, and the landed counter after them (r4d_ar_link_landed): // // [0, nbw) HANDSHAKE counters, one a block. Block b advances word b once per launch it // runs in, publishes the new value to the peer and waits for the peer's. Kept per @@ -19,6 +19,9 @@ // of them always equal the number of launches, and each block reads the slot // parity off its own word without talking to any other block. // +// [2*nbw] the LANDED counter: the blocks of the running launch that have seen their +// peer's push land, back at zero when the launch ends. +// // WHY THE SLOT CANNOT COME OFF THE HANDSHAKE COUNTER. The double-buffered scratch is safe only if // consecutive launches on one instance use opposite slots: launch k+1 may push while the peer is // still reducing launch k, and it must not land in the bytes being read. Block counts differ from @@ -56,6 +59,35 @@ __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs, __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); } +// THE ENGINE'S HOLD ON THE LINK, ENDED BY THE LAUNCH (rad_abi.h, rad_kernel_collective answering +// 2). The word is odd exactly while the engine holds the link for this launch, and nothing else +// writes it while the launch runs, so its value is read once, at the start, by each block's first +// thread (r4d_ar_link_word): the read crosses to host memory, and at the start it overlaps the push +// where at the end it would hold up the reduce. +// +// r4d_ar_link_landed is called by every block once its handshake has seen the peer's push to it +// land. The last block to get there knows every byte the peer sends this card has arrived, so the +// link is free for the rest of the kernel's run -- the reduce and whatever it writes -- and takes +// one off the word if it was odd, with an atomic so it commutes with any barrier counting the same +// word down. `ctr` counts the blocks and is back at zero when the launch ends, ready for the next +// one on the stream. The word is in memory the DMA engine polls past every cache, so it is read and +// written at system scope. +__device__ __forceinline__ long long r4d_ar_link_word(const long long* gate, unsigned int tid) { + return gate && tid == 0 ? __hip_atomic_load(gate, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM) + : 0; +} + +__device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long word, + unsigned int* ctr, unsigned int nb, + unsigned int tid) { + if (!gate || tid != 0) return; + const unsigned int prev = __hip_atomic_fetch_add(ctr, 1u, __ATOMIC_RELAXED, + __HIP_MEMORY_SCOPE_AGENT); + if (prev + 1u != nb) return; + __hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + if (word & 1) __hip_atomic_fetch_add(gate, -1LL, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); +} + // True while `flag` has not yet reached `want`. The counters are u32 and wrap, so the comparison is // on the signed difference: a peer at or past `want` -- it may already be a launch ahead -- reads // as arrived on either side of the wrap, where a plain `flag < want` stops waiting altogether once diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 1d20b3a7..a7e6cc0f 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -17,6 +17,7 @@ #include "r4d_common.h" #include "r4d_dt16.h" #include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2) +#include #define O_F16 1 #define O_MSKIP 2 @@ -58,6 +59,19 @@ // conversion is exact, so the fragments, and every byte after them, match the f16 tile's. With more // waves a workgroup each would convert the whole tile, so the launcher sets it at one. #define O_V8 8388608 +// O_KRAW: with K read straight from the paged cache (KLDS0, CONTIG), an m-tile's K is loaded in ONE +// round -- all HEAD_DIM/16 fragment loads, issued as soon as the row address is known -- and each +// fragment is converted from its registers just before its WMMA. +// +// The prefetch depth (PF) and the scheduling barrier between a group's loads and its WMMAs say +// what may overlap, and a compiler is free to honour them literally: LLVM 24 does, and with PF 2 a +// tile's K then arrives in HEAD_DIM/32 round trips, one after another, which cost the head_dim-128 +// drafter leg 16-19% on a bf16 cache. LLVM 22 lifted the loads over the barriers and issued them in +// one round. This bit asks for that round explicitly. What is held is the cache's own bytes -- 8 a +// fragment from fp8, 16 from bf16 -- not the converted fragment, so a full round costs 2 or 4 x +// HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold every converted fragment at once and cost the +// waves a SIMD. The fragments, and every byte after them, are unchanged. +#define O_KRAW 16777216 // `__builtin_nontemporal_load` will not take `uint4`/`uint2` -- they are HIP_vector_type class // templates, not native vectors -- so the hinted loads go through these and bit-cast the WHOLE // value back (never a subscript of it, which miscompiles). @@ -107,6 +121,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) constexpr int KNT = (OPT & O_KNT) ? 1 : 0; constexpr int V8 = ((OPT & O_V8) && !KVP) ? 1 : 0; static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout"); + constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0; + static_assert(!KRAW || (OPT & O_CONTIG), "the raw K round reads the contiguous layout"); typedef DT16 D; typedef typename D::frag frag16; @@ -339,6 +355,14 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM)) * (KVP ? 2 : 1); } + // A fragment's K bytes: 8 elements at 1 byte (fp8) or 2 (bf16), as the branches below read. + typedef typename std::conditional::type kraw_t; + kraw_t kraw[KRAW ? NKS : 1]; + if constexpr (KRAW) { + #pragma unroll + for (int t = 0; t < NKS; ++t) + kraw[t] = *(const kraw_t*)(grow + (16 * t + 8 * h) * (KVP ? 2 : 1)); + } v8f s = (v8f){0,0,0,0,0,0,0,0}; #pragma unroll for (int g = 0; g < NKS; g += PF) { @@ -357,17 +381,26 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } } else if (KVP) { const uint16_t* kp = (const uint16_t*)grow + 16 * t; - const uint2 l0 = *(const uint2*)(kp + (CTG ? 8 * h : 4 * h)); - const uint2 h0 = *(const uint2*)(kp + (CTG ? 8 * h + 4 : 8 + 4 * h)); + uint2 l0, h0; + if constexpr (KRAW && KVP != 0) { + const uint4 u = kraw[t]; + l0 = make_uint2(u.x, u.y); + h0 = make_uint2(u.z, u.w); + } else { + l0 = *(const uint2*)(kp + (CTG ? 8 * h : 4 * h)); + h0 = *(const uint2*)(kp + (CTG ? 8 * h + 4 : 8 + 4 * h)); + } kb[j] = D::mk(make_uint2(D::from_bf16w(l0.x), D::from_bf16w(l0.y)), make_uint2(D::from_bf16w(h0.x), D::from_bf16w(h0.y))); } else { const uint8_t* kp = grow + 16 * t; uint32_t w4[4]; // CONTIG makes this ONE 8-byte load where the split map needs two 4-byte. - const uint2 raw = CTG ? *(const uint2*)(kp + 8 * h) - : make_uint2(*(const uint32_t*)(kp + 4 * h), - *(const uint32_t*)(kp + 8 + 4 * h)); + uint2 raw; + if constexpr (KRAW && KVP == 0) raw = kraw[t]; + else raw = CTG ? *(const uint2*)(kp + 8 * h) + : make_uint2(*(const uint32_t*)(kp + 4 * h), + *(const uint32_t*)(kp + 8 + 4 * h)); fp8x8_to_16x4w(raw, w4); kb[j] = D::mk(make_uint2(w4[0], w4[1]), make_uint2(w4[2], w4[3])); } diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index dca3af3d..c7cc284f 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -13,13 +13,14 @@ // bound is the constraint value the selector bands on, so it is stated in the row and nowhere // else. A prefill block carries `NWARPS * 16 / gqa` query positions, 48 here against 64 there. // -// WHAT CHANGES WITH HEAD_DIM IS ONE OPTION BIT. `O_KWIDE` fetches 16 K elements a thread and its +// WHAT CHANGES WITH HEAD_DIM IS HOW K IS FETCHED. `O_KWIDE` fetches 16 K elements a thread and its // thread-to-(key, channel) map is written for 16 channels of 16 -- which is head_dim 256 exactly. -// At 128 it would stage past the tile, so the h128 prefill runs the same option set without it -// (3430923 against 3955211) and pays one more pass over a tile that is half the size. Everything -// else -- the lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k -// fragments, the SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and -// each bit is defined and justified in r4d_attn_prefill_h256_gqa6.hip. +// At 128 it would stage past the tile, so the h128 prefill runs without it and pays one more pass +// over a tile that is half the size; and its fragments are half as many registers, so it keeps a +// K prefetch of 4 where head_dim 256 takes 2 (3430923 against 3954187). Everything else -- the +// lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k fragments, the +// SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and each bit is +// defined and justified in r4d_attn_prefill_h256_gqa6.hip. // // NO `r4d_attn_dims` HERE. That entry point and the `check_dims_once` assertion built on it are // the h256/gqa6 unit's statement about ITSELF, and a second definition would not link. A geometry @@ -55,6 +56,14 @@ using std::max; #define R4D_ATTN_GQA 8 #define R4D_ATTN_H128 1 /* this ratio also serves head_dim 128 -- MiniCPM5-2B is 16 over 2 */ #endif +/* A head_dim 64 PREFILL leg, off unless the including unit asks for it: LFM2 is 32 query heads + * over 8 at head_dim 64 (r4d_attn_paged_h256_gqa4.hip). It runs the h128 prefill option set -- + * O_KWIDE's 16-channel staging is written for 256. There is no decode leg: the split-KV kernel + * holds a lane's columns as one or two dwords of codes, which is head_dim 128 or 256, so the + * query-tiled kernel serves every query length at this width. */ +#ifndef R4D_ATTN_H64 +#define R4D_ATTN_H64 0 +#endif #define GQ_JOIN_(a, b, c) a##b##c #define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c) #define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf) @@ -73,8 +82,11 @@ using std::max; #define G8_P_NWARPS 24 #define G8_P_TILE 48 -#define G8_P_OPT_256 3955211 -#define G8_P_OPT_128 3430923 // the same set without O_KWIDE; see the header +// K prefetch 2, as the h256/gqa6 prefill and for the same reason (see P_OPT there): 4 spills the +// m-tile loop. The head_dim-128 set keeps its prefetch of 4, which fits. +#define G8_P_OPT_256 3954187 +#define G8_P_OPT_128 3430923 // without O_KWIDE, at prefetch 4; see the header +#define G8_P_OPT_64 G8_P_OPT_128 #define G8_D_TILE 16 #define G8_D_OPT 3429947 #define G8_D_JPB 2 @@ -230,6 +242,20 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _bf16)(const RadArgs* a, Ra return g8_prefill_launch<128, G8_P_OPT_128, 1>(&r, (hipStream_t)s); } #endif +#if R4D_ATTN_H64 +extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _fp8)(const RadArgs* a, RadStream s) { + R4DArgs r; + const int rc = fill_paged(a, &r, 64); + if (rc != RAD_OK) return rc; + return g8_prefill_launch<64, G8_P_OPT_64, 0>(&r, (hipStream_t)s); +} +extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, RadStream s) { + R4DArgs r; + const int rc = fill_paged(a, &r, 64); + if (rc != RAD_OK) return rc; + return g8_prefill_launch<64, G8_P_OPT_64, 1>(&r, (hipStream_t)s); +} +#endif /* The split-KV partial buffer, sized at declare from the band's upper bound. IT IS CALLED WITH * PARAMETERS AND NO TENSORS -- that is what declare is -- so the parameters are the primary source diff --git a/libr4d/r4d_attn_paged_h128_gqa4.hip b/libr4d/r4d_attn_paged_h128_gqa4.hip index fe46016b..f6017ee3 100644 --- a/libr4d/r4d_attn_paged_h128_gqa4.hip +++ b/libr4d/r4d_attn_paged_h128_gqa4.hip @@ -37,8 +37,10 @@ using std::max; // The same option set the h256 decode kernel ships, K prefetch of 2 included. This geometry does // not need it -- head_dim 128 halves both the accumulator and the query, so it sits at 162-179 // VGPRs and does not spill at 4 -- but 2 is still 0.3-1.3% faster at every concurrency and window, -// for bit-identical output, so the two legs stay on one number. -#define B_OPT 3429947 +// for bit-identical output, so the two legs stay on one number -- plus O_KRAW, which loads an +// m-tile's K codes in one round (see r4d_attn_decode_h256_gqa6.hip): at head_dim 128 that round is +// 16 VGPRs and leaves the residency where it was. +#define B_OPT 20207163 #ifndef B_JPB #define B_JPB 2 #endif diff --git a/libr4d/r4d_attn_paged_h256_gqa4.hip b/libr4d/r4d_attn_paged_h256_gqa4.hip index 7a19f4bb..133654a3 100644 --- a/libr4d/r4d_attn_paged_h256_gqa4.hip +++ b/libr4d/r4d_attn_paged_h256_gqa4.hip @@ -11,8 +11,11 @@ // // NO head_dim 128 LEG. gqa 4 at 128 is the DFlash2 drafter's windowed geometry, which // r4d_attn_paged_h128_gqa4.hip serves; R4D_ATTN_H128 leaves those entry points out of this unit. +// A head_dim 64 PREFILL leg, for LFM2 (32 query heads over 8, d1-3B among them), which serves +// every query length: the split-KV decode kernel has no 64-wide form. // The page is the body's default 16. #define R4D_ATTN_GQA 4 #define R4D_ATTN_H128 0 +#define R4D_ATTN_H64 1 #include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 12ba77ee..781fc281 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -10,8 +10,8 @@ // the production configuration). // // `opt` is a bitmask of the optimisation steps, all of them on: -// prefill 3955211 = f16 operands | mask skip | folded query scale | contiguous-k fragments -// | prefetch 4 + scheduling barrier | dot2 row sum | block table in SGPRs +// prefill 3954187 = f16 operands | mask skip | folded query scale | contiguous-k fragments +// | prefetch 2 + scheduling barrier | dot2 row sum | block table in SGPRs // | wide K fetch | V prefetch across the m-tile loop | LDS-scoped barrier // decode 3429947 = the same, minus the wide K fetch (its K never reaches LDS), with the K // prefetch at 2 rather than 4, plus reading K straight from the paged cache @@ -50,7 +50,10 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max // would need 68096 B > 65536, so the geometry stops at 48. #define P_NWARPS 24 #define P_TILE 48 -#define P_OPT 3955211 +// K PREFETCH 2, NOT 4. Four fragments in flight hold more than the m-tile loop has to give at six +// waves a SIMD, and the loop then spills: LLVM 22 to 36 bytes a lane and LLVM 24 to 48, which cost +// LLVM 24 4% of the prefill. At 2 both compilers spill the same 20 bytes, outside the WMMA groups. +#define P_OPT 3954187 // KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below. template diff --git a/libr4d/r4d_common.h b/libr4d/r4d_common.h index 11ed254f..a3d7b6f8 100644 --- a/libr4d/r4d_common.h +++ b/libr4d/r4d_common.h @@ -39,10 +39,27 @@ __device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_le return lo; } +// ---- the occupancy a kernel is built for --------------------------------------------------------- +// R4D_WAVES(n) fixes the waves a SIMD the compiler schedules a kernel for. Left to itself the +// scheduler picks that target, trading registers for occupancy or the reverse, and the choice +// moves between compiler releases: LLVM 24 serialises a GEMM's loads to win one more wave a SIMD, +// paying a load round trip per WMMA, and elsewhere hoists more loads and gives a wave up. A kernel +// whose speed rests on a register budget states the budget with this, so the source and not the +// compiler version decides it. `n` may depend on template arguments. +#define R4D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n)))) + typedef short v8s __attribute__((ext_vector_type(8))); typedef float v8f __attribute__((ext_vector_type(8))); typedef float v2f __attribute__((ext_vector_type(2))); // what cvt_pk_f32_fp8 actually returns +/* A 16-BYTE STAGING REGISTER AS A NATIVE VECTOR. HIP's uint4 is a class template wrapping a union, + * and an array of them that a K loop carries -- the next tile's chunks, loaded while this tile is + * computed -- is not promoted to registers: LLVM 22 and LLVM 24 both keep it in scratch, so every + * staged chunk goes global load, scratch store, scratch load, LDS store. The same array of an + * ext_vector_type is promoted. Loaded and stored whole only; r4d_dflash_conv_body.h declares the + * same type for a source that is also compiled without this header. */ +typedef unsigned int r4d_u32x4 __attribute__((ext_vector_type(4))); + // exp2 with the hardware transcendental. __device__ __forceinline__ float ex2(float x) { @@ -65,6 +82,55 @@ __device__ __forceinline__ float bf16_to_f32(uint16_t h) { return __builtin_bit_cast(float, (uint32_t)h << 16); } +// ---- 16-bit values held in whole registers ------------------------------------------------------- +// LLVM 24 gives gfx12 real 16-bit registers: a value of a 16-bit type lives in one HALF of a VGPR. +// Two bf16 assembled into a word then cost a shift and a half move each pair where LLVM 22 used one +// v_perm_b32, a bf16 widened to a float costs a half move and a shift, and a 16-bit load goes into a +// half (global_load_d16_b16), so it depends on the register's earlier contents and the waitcnt pass +// waits for them. The helpers below keep bf16 data in whole 32-bit registers from load to store, +// which compiles to the same code under both compilers. The bits are the same as the 16-bit forms. + +// f32 -> bf16 rounded to nearest even, as the HIGH half of a word whose low half is not zero: +// f32_to_bf16 before its final shift. A NaN can round to infinity here, as there. +__device__ __forceinline__ uint32_t bf16_hi_rne(float f) { + const uint32_t u = __float_as_uint(f); + return u + 0x7fffu + ((u >> 16) & 1u); +} +// The same as (__hip_bfloat16)f computes it (LLVM's own expansion of the conversion): a NaN stays +// a NaN, made quiet, and everything else rounds to nearest even. Both results are formed before +// the choice so it compiles to one v_cndmask: written as `nan ? u | 0x400000 : u + ...`, the +// rounding is too long to speculate and each element becomes an exec-masked branch. +__device__ __forceinline__ uint32_t bf16_hi_rne_nan(float f) { + const uint32_t u = __float_as_uint(f); + const uint32_t r = u + 0x7fffu + ((u >> 16) & 1u), q = u | 0x400000u; + return f != f ? q : r; +} +// Two such words as one bf16 pair, `lo`'s high half in the low half: one byte permute. +__device__ __forceinline__ uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) { + return __builtin_amdgcn_perm(hi, lo, 0x07060302u); +} +// Two floats as a bf16 pair (`lo` in the low half), rounded as f32_to_bf16 rounds. +__device__ __forceinline__ uint32_t bf16x2_rne(float lo, float hi) { + return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi)); +} +// Two floats as a bf16 pair, rounded as (__hip_bfloat16) rounds. +__device__ __forceinline__ uint32_t bf16x2_rne_nan(float lo, float hi) { + return bf16_pack_hi(bf16_hi_rne_nan(lo), bf16_hi_rne_nan(hi)); +} +// A bf16 pair word's two values as floats: a shift and a mask, no conversion. +__device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w << 16); } +__device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); } + +// One 16-bit element of global memory, zero-extended into a whole register (global_load_u16). +// Read as a uint16_t and widened afterwards, it is loaded into a register half instead +// (global_load_d16_b16, or d16_hi_b16 straight into the bf16's float position), which waits for +// the register's other half; through a generic pointer it is a flat load as well. The pointer +// must address global memory. +typedef __attribute__((address_space(1))) const uint16_t* r4d_gu16; +__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r4d_gu16)p; } +// The same element as a bf16 widened to float. +__device__ __forceinline__ float ldg_bf16(const uint16_t* p) { return bf16w_lo(ldg_u16(p)); } + // `lane ^ N` WITHOUT THE LDS PIPE. `__shfl_xor` lowers to `ds_bpermute_b32` plus an // `s_wait_dscnt` -- an LDS round trip, and when the exchange sits on a dependency chain (a dot // product closed inside a token loop, say) that latency is the loop. gfx10 and up carry ROW_XMASK diff --git a/libr4d/r4d_dflash_select_bf16.hip b/libr4d/r4d_dflash_select_bf16.hip index 158104ca..781c7fc6 100644 --- a/libr4d/r4d_dflash_select_bf16.hip +++ b/libr4d/r4d_dflash_select_bf16.hip @@ -72,14 +72,29 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( // candidate, so it is computed once per step and read K times out of LDS. __shared__ float sa[DSL_MAX_R]; __shared__ float ssc[DSL_MAX_K]; - __shared__ int schosen; // the previous step's INDEX into its candidate list + __shared__ int spid; // the token the previous step chose: this step's predecessor + + // THE CANDIDATES A WAVE SCORES, at most this many: c = wave, wave + DSL_WAVES, ... + constexpr int CPW = (DSL_MAX_K + DSL_WAVES - 1) / DSL_WAVES; for (int l = 0; l < steps; ++l) { const long row = (long)s * steps + l; + // THE STEP'S OWN READS GO FIRST. The candidates' ids and unary scores do not depend on the + // predecessor, so they are in flight with its codebook row instead of behind the barrier, each + // a round trip of its own in a walk that is nothing but round trips. A wave past K re-reads + // the last candidate and scores nothing. + int cid[CPW]; + float un[CPW]; +#pragma unroll + for (int i = 0; i < CPW; ++i) { + const int c = wave + i * DSL_WAVES; + const long at = row * cand_ld + (c < K ? c : K - 1); + cid[i] = cand[at]; + un[i] = unary[at]; + } // Step 0's predecessor is the committed anchor; every later step's is the token this walk - // picked last time round, which is why the read has to happen after the barrier below. - const int pid = (l == 0) ? anchor[(long)s * anchor_stride] - : cand[(row - 1) * cand_ld + schosen]; + // picked last time round, which thread 0 left in LDS before the barrier that ended that step. + const int pid = (l == 0) ? anchor[(long)s * anchor_stride] : spid; const bool pid_ok = pid >= 0 && pid < V; const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R; @@ -99,16 +114,21 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( __syncthreads(); // One wave a candidate. R is a multiple of the wave, so the strided loop is balanced and the - // reduction is five xor-butterfly steps with no barrier inside it. - for (int c = wave; c < K; c += DSL_WAVES) { - const int cid = cand[row * cand_ld + c]; - float acc = 0.0f; - if (cid >= 0 && cid < V) { - const r4d_u16* __restrict__ srow = succ + (long)cid * R; + // reduction is five xor-butterfly steps with no barrier inside it. A candidate out of range + // reads codebook row 0 and drops the sum, so the row's loads are never in a branch of their + // own; its score is its unary term alone either way. +#pragma unroll + for (int i = 0; i < CPW; ++i) { + const int c = wave + i * DSL_WAVES; + if (c < K) { + const bool ok = cid[i] >= 0 && cid[i] < V; + const r4d_u16* __restrict__ srow = succ + (long)(ok ? cid[i] : 0) * R; + float acc = 0.0f; +#pragma unroll 8 for (int r = lane; r < R; r += DSL_WAVE) acc += sa[r] * r4d_bf2f(srow[r]); + acc = r4d_wave_sum(ok ? acc : 0.0f); + if (lane == 0) ssc[c] = acc + un[i]; } - acc = r4d_wave_sum(acc); - if (lane == 0) ssc[c] = acc + unary[row * cand_ld + c]; } __syncthreads(); @@ -120,10 +140,11 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( float bv = -INFINITY; for (int c = 0; c < K; ++c) if (ssc[c] > bv) { bv = ssc[c]; best = c; } - schosen = best; - out[(long)s * out_ld + l] = cand[row * cand_ld + best]; + const int tok = cand[row * cand_ld + best]; + spid = tok; + out[(long)s * out_ld + l] = tok; } - // Both directions: the next step reads `schosen` and overwrites `sa`, and every other thread + // Both directions: the next step reads `spid` and overwrites `sa`, and every other thread // is still reading this step's. __syncthreads(); } diff --git a/libr4d/r4d_fp8_wmma.h b/libr4d/r4d_fp8_wmma.h index b4057b01..fbb720c0 100644 --- a/libr4d/r4d_fp8_wmma.h +++ b/libr4d/r4d_fp8_wmma.h @@ -161,6 +161,11 @@ __device__ __forceinline__ v2f e4m3_pk(uint32_t q) { __device__ __forceinline__ float bscale(uint16_t s) { return __uint_as_float((uint32_t)s << 16); } +/* The same scale held zero-extended in a whole register: the form a 16-bit value should stay in + * from its load on (see u16_load_w in r4d_moe.hip). The upper sixteen bits must be zero. */ +__device__ __forceinline__ float bscale(uint32_t s) { + return __uint_as_float(s << 16); +} // ---- LDS staging, shared by both fp8a8 instantiations ------------------------------------------- // diff --git a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip index bd865f4c..a8107675 100644 --- a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip +++ b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip @@ -332,6 +332,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, __shared__ unsigned short cvq[CV ? RU_CVT * RU_K : 1], cvk[CV ? RU_CVT * RU_K : 1]; __shared__ unsigned short cvv[CV ? RU_CVT * RU_V : 1]; __shared__ int cvlast; + /* THE KEY HEAD'S HISTORY FOR THE REWRITE AT THE END, parked here once its taps are computed: the + * two newest history entries and this step's inputs, one channel a thread. Held in registers they + * stay live across the whole token loop, ten values a thread that the loop's h, q and k leave no + * room for -- they went to scratch, and other values with them. */ + __shared__ unsigned short cvh[CV ? (CS - 1 + RU_CVT) * THR : 1]; /* THE TOKEN LOOP'S OWN GLOBAL READS, STAGED THE SAME WAY. Per token the loop reads `a` and `b` * (the decay and beta inputs, one scalar each) and the output gate's row, and at decode there * is well under a wave a SIMD to hide a load behind -- read in the loop, each is a full global @@ -494,7 +499,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, // A NEGATIVE slot is the pad and ZERO IS A REAL SLOT -- see the same rule in // r4d_gdn_conv_w4_h128_bf16.hip. A `<= 0` test here loses the first sequence's state entirely. if (si < 0) return; - const int grp = row >> 5; // fixed 32-row group, see RU_FSTR + /* Fixed 32-row group, see RU_FSTR. One per WAVE: a wave's 32 threads are 16 consecutive rows from + * a multiple of 16, inside one group whatever VS is (a workgroup's first row is a multiple of + * NR >= 32). Said so to the compiler, the factor addresses it scales are scalar; as a lane value + * they were 64-bit VGPR offsets live across the token loop and reloaded from scratch there. */ + const int grp = __builtin_amdgcn_readfirstlane(row >> 5); float h[RU_HK]; { @@ -571,6 +580,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, } }; conv(cwa, cba, cha, cxa, (tid < RU_K ? cvq : cvk) + (tid & (RU_K - 1))); +#pragma unroll + for (int i = 1; i < CS; ++i) cvh[(i - 1) * THR + tid] = cha[i]; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + if (t < T) cvh[(CS - 1 + t) * THR + tid] = cxa[t]; if (tid < RU_V) { conv(cwb, cbb, chb, cxb, cvv + tid); ru_conv_rewrite(spb, chb, cxb, T, cv.cs_tok); @@ -808,7 +822,14 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, __syncthreads(); if (!cvlast) return; } - ru_conv_rewrite(spa, cha, cxa, T, cv.cs_tok); + unsigned short rh[CS], rx[RU_CVT]; + rh[0] = 0; /* never read: the oldest entry is shifted out */ +#pragma unroll + for (int i = 1; i < CS; ++i) rh[i] = cvh[(i - 1) * THR + tid]; +#pragma unroll + for (int t = 0; t < RU_CVT; ++t) + rx[t] = t < T ? cvh[(CS - 1 + t) * THR + tid] : (unsigned short)0; + ru_conv_rewrite(spa, rh, rx, T, cv.cs_tok); } } diff --git a/libr4d/r4d_gemm_bf16_nt_tiled.hip b/libr4d/r4d_gemm_bf16_nt_tiled.hip index 3d7fc03f..7b53e41e 100644 --- a/libr4d/r4d_gemm_bf16_nt_tiled.hip +++ b/libr4d/r4d_gemm_bf16_nt_tiled.hip @@ -29,6 +29,7 @@ // last valid row, computes a result nobody stores, and never touches memory it does not own. #include "r4d.h" #include "r4d_gemm_args.h" +#include "r4d_common.h" #include "r4d_gdn_wmma.h" #include #include @@ -95,27 +96,27 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( for (int j = 0; j < TN; ++j) tot[i][j] = (v8f)(0.f); } - uint4 ra[AL], rw[WL]; + r4d_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch #pragma unroll - for (int i = 0; i < AL; ++i) ra[i] = *(const uint4*)(A + aoff[i]); + for (int i = 0; i < AL; ++i) ra[i] = *(const r4d_u32x4*)(A + aoff[i]); #pragma unroll - for (int i = 0; i < WL; ++i) rw[i] = *(const uint4*)(W + woff[i]); + for (int i = 0; i < WL; ++i) rw[i] = *(const r4d_u32x4*)(W + woff[i]); const int nk = K / BT_BK; int left = spk; // k steps to the end of this split slice for (int kt = 0; kt < nk; ++kt) { __syncthreads(); // the previous tile's fragments are all read #pragma unroll - for (int i = 0; i < AL; ++i) *(uint4*)adst[i] = ra[i]; + for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i]; #pragma unroll - for (int i = 0; i < WL; ++i) *(uint4*)wdst[i] = rw[i]; + for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i]; __syncthreads(); if (kt + 1 < nk) { const unsigned k1 = (unsigned)(kt + 1) * BT_BK; #pragma unroll - for (int i = 0; i < AL; ++i) ra[i] = *(const uint4*)(A + aoff[i] + k1); + for (int i = 0; i < AL; ++i) ra[i] = *(const r4d_u32x4*)(A + aoff[i] + k1); #pragma unroll - for (int i = 0; i < WL; ++i) rw[i] = *(const uint4*)(W + woff[i] + k1); + for (int i = 0; i < WL; ++i) rw[i] = *(const r4d_u32x4*)(W + woff[i] + k1); } #pragma unroll for (int s = 0; s < BT_BK / 16; ++s) { @@ -128,6 +129,12 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel( for (int i = 0; i < TM; ++i) #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = mma(af[i], bf[j], acc[i][j]); + /* A K STEP'S FRAGMENT READS, THEN ITS PRODUCTS, as the scheduler's groups. Left to itself, + * gfx12's compiler spreads each step's LDS reads among the previous step's WMMAs and waits on + * them early; grouped, the 128 x 128 tile measured 6 to 9% faster than LLVM 22's schedule at + * Flash-Next's shapes (M 384 to 2048, K 2560, N 2560 and 10240). */ + __builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */ + __builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */ if constexpr (SPLIT) { if (--left == 0) { left = spk; diff --git a/libr4d/r4d_gemm_fp8a16_nt_m1.hip b/libr4d/r4d_gemm_fp8a16_nt_m1.hip index 6cdc26cb..af3d4cd5 100644 --- a/libr4d/r4d_gemm_fp8a16_nt_m1.hip +++ b/libr4d/r4d_gemm_fp8a16_nt_m1.hip @@ -319,12 +319,52 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, #pragma unroll for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = 0.0f; + /* AT MT <= 2 EACH PASS'S WEIGHT CHUNK, SCALE AND ACTIVATION ARE LOADED ONE PASS AHEAD (kPre), + * so a pass's loads run under the previous pass's arithmetic. Loaded in the pass that uses + * them, LLVM 24 issues them and then waits for the first three before it converts anything, + * and at M = 2 the head ran 0.65% behind LLVM 22's build; loaded ahead it is level, and M = 1 + * is unchanged. Held a pass, the activation is eight registers a row, which the wider tiles do + * not have: at MT = 32 it spills a thousand slots, so they load in the pass. The last pass + * reloads its own chunk rather than reading past the row. */ + constexpr bool kPre = MT <= 2u; + [[maybe_unused]] uint4 wn[RB]; + [[maybe_unused]] uint32_t sn[RB]; + [[maybe_unused]] uint4 xn[kPre ? MT : 1][2]; + auto load = [&](uint32_t c) { +#pragma unroll + for (uint32_t r = 0; r < RB; ++r) { + wn[r] = *(const uint4*)(w[r] + c); + sn[r] = srow[r][c / kBlock]; + } + if constexpr (kPre) { +#pragma unroll + for (uint32_t m = 0; m < MT; ++m) { + const uint4* xm = (const uint4*)(X + (size_t)xrow(m) * a_ld + c); + xn[m][0] = xm[0]; + xn[m][1] = xm[1]; + } + } + }; + if constexpr (kPre) + if ((uint32_t)lane * 16u < full) load((uint32_t)lane * 16u); for (uint32_t c = (uint32_t)lane * 16u; c < full; c += stride) { float wf[RB][16]; float sc[RB]; + [[maybe_unused]] uint4 wc[kPre ? RB : 1]; + [[maybe_unused]] uint32_t scr[kPre ? RB : 1]; + [[maybe_unused]] uint4 xc[kPre ? MT : 1][2]; + if constexpr (kPre) { +#pragma unroll + for (uint32_t r = 0; r < RB; ++r) { wc[r] = wn[r]; scr[r] = sn[r]; } +#pragma unroll + for (uint32_t m = 0; m < MT; ++m) { xc[m][0] = xn[m][0]; xc[m][1] = xn[m][1]; } + load(c + stride < full ? c + stride : c); + } #pragma unroll for (uint32_t r = 0; r < RB; ++r) { - const uint4 packed = *(const uint4*)(w[r] + c); + uint4 packed; + if constexpr (kPre) packed = wc[r]; + else packed = *(const uint4*)(w[r] + c); const uint32_t* pw = (const uint32_t*)&packed; #pragma unroll for (int k = 0; k < 4; ++k) { @@ -335,14 +375,31 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W, wf[r][k * 4 + 2] = e23.x; wf[r][k * 4 + 3] = e23.y; } - sc[r] = bscale(srow[r][c / kBlock]); + if constexpr (kPre) sc[r] = bscale(scr[r]); + else sc[r] = bscale(srow[r][c / kBlock]); } #pragma unroll for (uint32_t m = 0; m < MT; ++m) { - const uint16_t* xm = X + (size_t)xrow(m) * a_ld + c; + /* THE SIXTEEN bf16 AS EIGHT DWORDS, each widened by a shift (the even element) and a + * mask (the odd one): the same floats. Read a uint16_t at a time, LLVM 24 moves each + * into a 16-bit register half before shifting it -- two instructions an element where + * LLVM 22 took one. */ + uint4 x0, x1; + if constexpr (kPre) { + x0 = xc[m][0]; + x1 = xc[m][1]; + } else { + const uint4* xm = (const uint4*)(X + (size_t)xrow(m) * a_ld + c); + x0 = xm[0]; + x1 = xm[1]; + } + const uint32_t xw[8] = { x0.x, x0.y, x0.z, x0.w, x1.x, x1.y, x1.z, x1.w }; float xv[16]; #pragma unroll - for (int k = 0; k < 16; ++k) xv[k] = __uint_as_float((uint32_t)xm[k] << 16); + for (int k = 0; k < 8; ++k) { + xv[2 * k] = __uint_as_float(xw[k] << 16); + xv[2 * k + 1] = __uint_as_float(xw[k] & 0xffff0000u); + } #pragma unroll for (uint32_t r = 0; r < RB; ++r) { float a0 = 0.0f, a1 = 0.0f; @@ -488,17 +545,34 @@ uint32_t rb_default(uint32_t rows, uint32_t cols) { // rather than sixteen. That is what makes the scale a scalar multiply in the epilogue of each // block instead of a per-element gather. typedef short lm_s8v __attribute__((ext_vector_type(8))); +typedef unsigned lm_u4v __attribute__((ext_vector_type(4))); + +/* TWO DECODED CODES AS ONE bf16 PAIR: the high halves of both floats, by one byte permute. A code + * decodes to a float whose low sixteen bits are zero (E4M3's three mantissa bits, an int8's seven), + * so its bf16 is exactly those high bits -- f32_to_bf16's rounding adds less than one to the low + * half and carries nothing out of it -- and packed here it is one v_perm_b32 a pair, the rounding + * adds gone too. Built from f32_to_bf16 and the vector's lanes instead, LLVM 24's 16-bit register + * halves turn each pair into two half moves and a shift where LLVM 22 had the permute: 24 more + * instructions a K step of the M = 32 tile. The same bits either way. The floats are read with + * __float_as_uint, by value: __builtin_bit_cast of a vector's element miscompiles (see the + * nontemporal load in r4d_fp8_wmma.h), and here it fed the WMMA garbage. + * + * Every tile takes it: against the f32_to_bf16 form it is 0.3 to 0.7% faster at M = 4 to 16 + * (MT 1, K 2048 to 5120), 0.8% at M = 32 (MT 2) and 7.7% at M = 64 (MT 4). */ +__device__ __forceinline__ uint32_t lm_bf16_pair(v2f p) { + return __builtin_amdgcn_perm(__float_as_uint(p.y), __float_as_uint(p.x), 0x07060302u); +} template __device__ __forceinline__ lm_s8v e4m3x8_to_bf16(uint32_t lo, uint32_t hi) { const v2f a01 = code_pk(lo), a23 = code_pk(lo); const v2f b01 = code_pk(hi), b23 = code_pk(hi); - lm_s8v r; - r[0] = (short)f32_to_bf16(a01.x); r[1] = (short)f32_to_bf16(a01.y); - r[2] = (short)f32_to_bf16(a23.x); r[3] = (short)f32_to_bf16(a23.y); - r[4] = (short)f32_to_bf16(b01.x); r[5] = (short)f32_to_bf16(b01.y); - r[6] = (short)f32_to_bf16(b23.x); r[7] = (short)f32_to_bf16(b23.y); - return r; + lm_u4v r; + r.x = lm_bf16_pair(a01); + r.y = lm_bf16_pair(a23); + r.z = lm_bf16_pair(b01); + r.w = lm_bf16_pair(b23); + return __builtin_bit_cast(lm_s8v, r); } // MT is ceil(M / 16): how many 16-row activation tiles ride the one weight read. @@ -620,8 +694,21 @@ __device__ __forceinline__ lm_s8v e4m3x8_to_bf16(uint32_t lo, uint32_t hi) { // The band is five things it is not: not the register file, not staging latency, not the straddle, // not the activation loads, not the activation re-read. It needs a new hypothesis, not another // pass over these. +// +// ---- THE WAVES A SIMD EACH TILE RUNS AT (R4D_WAVES) -------------------------------------------- +// +// Two staged blocks a round (FKB = 2) hold 33 KB of LDS, which caps a SIMD at six waves whatever +// the registers, so six is the target there. One block a round at MT >= 3 is a register budget: +// seven waves at MT = 3 and six at MT = 4, where two K steps in flight are worth more than a +// seventh wave (above). MT <= 2 at one block is reachable only through R4D_LM_FKB and keeps the +// budget it was measured at. Without the target the scheduler is free to trade the activation +// loads' overlap for occupancy, and at MT = 4 that trade cost 40%. +constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) { + return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u; +} + template -__global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel( +__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel( const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) { @@ -629,6 +716,7 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel( constexpr uint32_t kRows = kDenseWaves * 16u; /* weight rows a workgroup covers */ constexpr uint32_t kPitch = lds_pitch(); /* BYTES a staged weight row */ constexpr uint32_t kWUnits = kRows * (kFK / 16u); /* 16-byte staging units, weight */ + constexpr bool kPre = MT <= 3u; /* activation a K step ahead, below */ __shared__ uint8_t s_w[kRows * kPitch]; @@ -650,8 +738,37 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel( for (uint32_t t = 0; t < MT; ++t) acc[t] = (f8v)(0.0f); for (uint32_t kt = 0; kt < cols; kt += kFK) { - /* Before the store, because the previous tile's fragment reads are still in flight. */ - __syncthreads(); + /* THE ACTIVATION FRAGMENTS ARE LOADED ONE K STEP AHEAD at MT <= 3 (kPre): each step + * takes the fragments the step before it loaded and issues the next step's, so their + * round trip runs under a step's WMMAs; the tile's first step is issued here, while the + * tile stages. Loaded in the step that uses them, LLVM 24 waits for them right after + * issuing them, every step -- LLVM 22's schedule had moved the loads a step early + * itself. Against LLVM 22's build: M = 4 from +0.44% to level, M = 32 to -1.4%. At + * MT = 4 the held fragments take the tile to 238 VGPRs and it runs 3.4% slower, so it + * loads in place there. The last step reloads its own fragments rather than reading + * past the tile. */ + [[maybe_unused]] lm_s8v an[kPre ? MT : 1]; + auto aload = [&](uint32_t kf) { +#pragma unroll + for (uint32_t t = 0; t < MT; ++t) { + const uint32_t m = t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u); + an[t] = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u); + } + }; + if constexpr (kPre) aload(0u); + /* THE TILE'S BLOCK SCALES ARE READ HERE, ahead of the staging barrier, so they land + * while the tile stages and computes. Read where they are used, after a block's + * WMMAs, each is a global round trip the wave waits out with nothing else in flight, + * and a compiler is free to put the load there: LLVM 24 does for the second block of + * an FKB = 2 tile. Read here, M = 4 to 64 run 0.2 to 0.6% faster. */ + uint16_t sraw[FKB]; +#pragma unroll + for (uint32_t sb = 0; sb < FKB; ++sb) sraw[sb] = scl[(kt + sb * kBlock) / kBlock]; + /* Before the store, because the previous tile's fragment reads are still in flight. + * Both barriers order LDS only: no thread reads global memory another one writes, and + * __syncthreads() is a fence over every address space, which on gfx12 waits for every + * load in flight -- the scale read above and the prefetched fragments with it. */ + lds_barrier(); /* HOW MANY STAGING LOADS ARE IN FLIGHT, and it is a REGISTER decision, not a memory one. A round * is kFK/32 units a thread -- eight at FKB = 2 -- and unrolling it whole holds eight uint4 results * live across the stores, 32 VGPRs on top of MT accumulators and MT partials. At MT >= 3 unrolling @@ -664,7 +781,7 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel( const uint8_t* src = W + (size_t)((g < rows) ? g : (rows - 1u)) * w_ld + kt + off; *(uint4*)(s_w + (size_t)r * kPitch + off) = *(const uint4*)src; } - __syncthreads(); + lds_barrier(); /* One scale block at a time INSIDE the staged tile, so the partial that the block * scale multiplies is exactly the one a one-block round forms. FK is a staging width and @@ -680,19 +797,33 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel( #pragma unroll MT >= 4 ? 2 : 4 for (uint32_t ks = 0; ks < kBlock; ks += 16u) { const uint32_t kf = sb * kBlock + ks; /* K inside the staged tile */ + [[maybe_unused]] lm_s8v ac[kPre ? MT : 1]; + if constexpr (kPre) { +#pragma unroll + for (uint32_t t = 0; t < MT; ++t) ac[t] = an[t]; + aload(kf + 16u < kFK ? kf + 16u : kf); + } const i2v raw = frag(s_w, wv * 16u, kf, lane); - const lm_s8v bf = e4m3x8_to_bf16((uint32_t)raw[0], (uint32_t)raw[1]); + const lm_s8v bf = + e4m3x8_to_bf16((uint32_t)raw[0], (uint32_t)raw[1]); +/* THE ACTIVATION LOAD IS UNCONDITIONAL: a padding row reads the last real row again and a select + * zeroes it. Guarding the load with `m < m_real` puts each one in its own branch with its WMMA + * right behind it, and the compiler is then free to wait for every load before issuing the next + * -- MT round trips a K step where one would do. LLVM 24 does exactly that, and it cost M = 64 + * 40%. The clamped row is always in bounds and already in cache, so the extra loads are free. */ #pragma unroll for (uint32_t t = 0; t < MT; ++t) { const uint32_t m = t * 16u + c; - const lm_s8v af = - (m < m_real) ? *(const lm_s8v*)(A + (size_t)m * a_ld + kt + kf + h * 8u) - : (lm_s8v)(short)0; + [[maybe_unused]] const uint32_t mr = (m < m_real) ? m : (m_real - 1u); + lm_s8v af; + if constexpr (kPre) af = ac[t]; + else af = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u); + if (m >= m_real) af = (lm_s8v)(short)0; part[t] = __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(af, bf, part[t]); } } - const float sc = bscale(scl[(kt + sb * kBlock) / kBlock]); + const float sc = bscale(sraw[sb]); #pragma unroll for (uint32_t t = 0; t < MT; ++t) #pragma unroll diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 75fab30d..98fa1489 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -53,6 +53,7 @@ #include #include #include +#include namespace { @@ -334,9 +335,34 @@ constexpr bool kNarrowWeightNT = false; * per 128x128 tile. Only the fold reads the difference: one weight scale per accumulator row on * the narrow path, one per lane's column on the prefill tile. The fp8 instantiations are * unaffected. */ +/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget every shape here was + * tuned at. The narrow tile's NT accumulators and its K-step unroll are sized against it, and a + * compiler left to choose moves it either way -- LLVM 24 spends 25 to 55 more VGPRs on NT 3 and 4 + * at FK 256 and drops a wave or two, which cost the 64-row verify step 15%. One and two waves a + * block are held by LDS, not registers, and carry the LDS-bound count. */ +constexpr uint32_t f8_waves(bool full, bool aw, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) { + if (!aw) return 6u; + if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u; + if (mw == 2u) return nt == 1u ? 12u : nt == 2u ? 8u : nt == 3u ? 5u : 4u; + if (!i8) { + if (fk == 128u) + return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u + : (full && mw >= 8u) ? 10u : 9u; + return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? 9u : mw == 4u ? 7u : 8u; + } + if (fk == 128u) + return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u) + : full ? 7u : 9u; + if (nt == 1u) return 12u; + if (nt == 2u) return full ? 9u : mw == 4u ? 9u : 10u; + if (nt == 3u) return full ? (mw == 16u ? 8u : 7u) : (mw == 4u ? 8u : 9u); + return full ? (mw == 4u ? 5u : 6u) : (mw == 4u ? 7u : 8u); +} + template -__global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel( +__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, AW, NT, MW, FK, I8)) +void gemm_fp8a8_kernel( const uint8_t* __restrict__ Ap, const void* __restrict__ Sa, const uint8_t* __restrict__ Bp, const void* __restrict__ Sb, void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr, @@ -579,6 +605,25 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel( } } + /* THE FOLD'S ACTIVATION SCALES, A TILE AHEAD (fp8 prefill tile): eight a lane, read at the + * top of the staged tile that ends in a fold so its WMMA cover them. Loaded where the fold + * runs, LLVM 24 issues them there and waits for each one in turn. At FK <= kBlock the fold + * fires only at a tile's last step, so the tile is known here. */ + constexpr bool kAsAhead = !AW && !I8 && FK <= kBlock; + [[maybe_unused]] float asn[kAsAhead ? MT : 1][8]; + if constexpr (kAsAhead) { + if ((c0 + FK) % kBlock == 0 || c0 + FK >= kend) { + const uint32_t kb = (c0 + FK - 1) / kBlock; +#pragma unroll + for (uint32_t i = 0; i < MT; ++i) +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t); + asn[i][t] = (Full || r < rows) ? ((const float*)Sa)[(size_t)r * sa_ld + kb] + : 0.0f; + } + } + } #pragma unroll for (uint32_t ks = 0; ks < FK; ks += kK) { i2v af[MT], bf[NT]; @@ -724,9 +769,12 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel( #pragma unroll for (uint32_t t = 0; t < 8; ++t) { const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t); - as[i][t] = (Full || r < rows) - ? ws * ((const float*)Sa)[(size_t)r * sa_ld + kb] - : 0.0f; + if constexpr (kAsAhead) + as[i][t] = (Full || r < rows) ? ws * asn[i][t] : 0.0f; + else + as[i][t] = (Full || r < rows) + ? ws * ((const float*)Sa)[(size_t)r * sa_ld + kb] + : 0.0f; } #pragma unroll for (uint32_t i = 0; i < MT; ++i) @@ -833,11 +881,11 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel( *(uint2*)(Q + (size_t)tok * q_ld + col0) = make_uint2((uint32_t)pk[0], (uint32_t)pk[1]); if (Yb) { - __attribute__((aligned(16))) uint16_t hy[8]; -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) hy[t] = f32_to_bf16(v[j][t]); + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written through + * a uint16_t[8], LLVM 24 assembles the pairs from register halves. */ uint16_t* const yr = Yb + (size_t)tok * y_ld + col0; - *(uint4*)yr = *(const uint4*)hy; + *(uint4*)yr = make_uint4(bf16x2_rne(v[j][0], v[j][1]), bf16x2_rne(v[j][2], v[j][3]), + bf16x2_rne(v[j][4], v[j][5]), bf16x2_rne(v[j][6], v[j][7])); } } @@ -873,40 +921,60 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel( * are exactly when `rows` is a multiple of 8: `r` is already one (m0, wm, i*16 and * `(lane>>4)*8` all are), so `col * rows + r` is too. */ const bool vec8 = AW && (rows & 7u) == 0u; + /* THE SPLIT-K AND VEC8 TESTS ARE TAKEN ONCE, outside the store loop. Inside it, gfx12's + * compiler keeps a scalar compare and branch on each at every one of the tile's stores -- 64 + * of each at NT 8 -- where LLVM 22 unswitched the loop; and with the per-element fallback in + * the same body it rounds both paths' values to 16-bit halves once, so the vec8 words are + * assembled from register halves instead of one byte permute a pair. The same stores either + * way. */ + auto store = [&](auto split, auto v8) { + constexpr bool CK = decltype(split)::value; + constexpr bool V8 = decltype(v8)::value; #pragma unroll - for (uint32_t i = 0; i < MT; ++i) + for (uint32_t i = 0; i < MT; ++i) #pragma unroll - for (uint32_t j = 0; j < NT; ++j) { - const uint32_t col = n0 + wn + j * 16 + c; - if (!Full && col >= nb) continue; - const uint32_t rb = m0 + wm + i * 16; - const uint32_t r0 = rb + acc_row(lane, 0); - if (vec8 && (Full || r0 + 8u <= rows)) { - const size_t o = (size_t)col * rows + r0; - if (ck) { - __attribute__((aligned(16))) float pv[8]; + for (uint32_t j = 0; j < NT; ++j) { + const uint32_t col = n0 + wn + j * 16 + c; + if (!Full && col >= nb) continue; + const uint32_t rb = m0 + wm + i * 16; + const uint32_t r0 = rb + acc_row(lane, 0); + if (V8 && (Full || r0 + 8u <= rows)) { + const size_t o = (size_t)col * rows + r0; + if constexpr (CK) { + __attribute__((aligned(16))) float pv[8]; #pragma unroll - for (uint32_t t = 0; t < 8; ++t) pv[t] = out[i][j][t]; - *(uint4*)(part + o) = *(const uint4*)pv; - *(uint4*)(part + o + 4) = *(const uint4*)(pv + 4); - } else { - __attribute__((aligned(16))) uint16_t hy[8]; -#pragma unroll - for (uint32_t t = 0; t < 8; ++t) hy[t] = f32_to_bf16(out[i][j][t]); - *(uint4*)(c16 + o) = *(const uint4*)hy; + for (uint32_t t = 0; t < 8; ++t) pv[t] = out[i][j][t]; + *(uint4*)(part + o) = *(const uint4*)pv; + *(uint4*)(part + o + 4) = *(const uint4*)(pv + 4); + } else { + /* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written + * through a uint16_t[8], LLVM 24 assembles the pairs from register halves + * where LLVM 22 used one byte permute a pair. */ + const f8v& ov = out[i][j]; + *(uint4*)(c16 + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]), + bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7])); + } + continue; } - continue; - } #pragma unroll - for (uint32_t t = 0; t < 8; ++t) { - const uint32_t r = rb + acc_row(lane, t); - if (!Full && r >= rows) continue; - // AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. See the AW comment. - const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col; - if (ck) part[o] = out[i][j][t]; - else c16[o] = f32_to_bf16(out[i][j][t]); + for (uint32_t t = 0; t < 8; ++t) { + const uint32_t r = rb + acc_row(lane, t); + if (!Full && r >= rows) continue; + // AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. See the AW + // comment. + const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col; + if constexpr (CK) part[o] = out[i][j][t]; + else c16[o] = f32_to_bf16(out[i][j][t]); + } } - } + }; + if (vec8) { + if (ck) store(std::true_type{}, std::true_type{}); + else store(std::false_type{}, std::true_type{}); + } else { + if (ck) store(std::true_type{}, std::false_type{}); + else store(std::false_type{}, std::false_type{}); + } // ---- THE SPLIT'S FINISHER, WHICH IS WHY THERE IS USUALLY NO SECOND LAUNCH ------------------ // diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index e45b6ed8..52e56f0a 100644 --- a/libr4d/r4d_gemm_mxfp4a8_decode.hip +++ b/libr4d/r4d_gemm_mxfp4a8_decode.hip @@ -145,11 +145,17 @@ static __device__ __forceinline__ void mxd_epilogue( for (int i = 0; i < DTM; ++i) { const int m = i * 16 + col; if (m < M) { - union { __hip_bfloat16 h[8]; mxd_u4 v; } o; + // rounded as (__hip_bfloat16) rounds, packed in whole registers (see bf16x2_rne_nan) + float v[8]; #pragma unroll for (int e = 0; e < 8; ++e) - o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]); - *(mxd_u4*)(C + (size_t)m * N + nb) = o.v; + v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]; + mxd_u4 o; + o.x = bf16x2_rne_nan(v[0], v[1]); + o.y = bf16x2_rne_nan(v[2], v[3]); + o.z = bf16x2_rne_nan(v[4], v[5]); + o.w = bf16x2_rne_nan(v[6], v[7]); + *(mxd_u4*)(C + (size_t)m * N + nb) = o; } } } @@ -194,8 +200,23 @@ static __device__ __forceinline__ void mxd_epilogue( } } +/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget the decode tile was + * tuned at, by K block, M fragments and activation-scale form, so a compiler release cannot move + * it -- LLVM 24 adds two VGPRs to the DBK 64, three-fragment form and drops it from sixteen waves to + * twelve. Where LLVM 22 itself ran out of registers (DBK 128 at seven and eight fragments without + * block activation scales, 256 VGPRs and a spill) the budget is the one the tile reaches without + * spilling. */ +constexpr int mxd_waves(int dbk, int dtm, bool ablk) { + if (dbk == 64) + return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10) + : dtm == 7 ? 9 : (ablk ? 8 : 9); + return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6) + : 6; +} + template -__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kernel( +__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(mxd_waves(DBK, DTM, ABLK)) +void r4d_gemm_mxfp4a8_decode_kernel( const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, @@ -314,7 +335,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern // row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at // every split: the K order, the fold and the reduction are unchanged. template -__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_kernel( +__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12) +void r4d_gemm_mxfp4a8_decode1_kernel( const unsigned char* __restrict__ A, const float* __restrict__ As, const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws, const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt, diff --git a/libr4d/r4d_gemm_mxfp4a8_tiled.hip b/libr4d/r4d_gemm_mxfp4a8_tiled.hip index 4ebf5b74..01c0fab1 100644 --- a/libr4d/r4d_gemm_mxfp4a8_tiled.hip +++ b/libr4d/r4d_gemm_mxfp4a8_tiled.hip @@ -300,13 +300,19 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel( for (int i = 0; i < TM; ++i) { const int m = m0 + wm * TM * 16 + i * 16 + col; if (m >= M) continue; - union { __hip_bfloat16 h[8]; mxt_u4 v; } o; + // rounded as (__hip_bfloat16) rounds, packed in whole registers (see bf16x2_rne_nan) + float v[8]; #pragma unroll for (int e = 0; e < 8; ++e) { const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23); - o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]); + v[e] = acc[i][j][e] * rf * sc[i]; } - *(mxt_u4*)(C + (size_t)m * N + nb) = o.v; + mxt_u4 o; + o.x = bf16x2_rne_nan(v[0], v[1]); + o.y = bf16x2_rne_nan(v[2], v[3]); + o.z = bf16x2_rne_nan(v[4], v[5]); + o.w = bf16x2_rne_nan(v[6], v[7]); + *(mxt_u4*)(C + (size_t)m * N + nb) = o; } } } diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index aa9a093d..1a10f238 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -119,6 +119,28 @@ __device__ __forceinline__ float sigmoidf_(float v) { return 1.0f / (1.0f + __ex __device__ __forceinline__ float siluf_(float v) { return v * sigmoidf_(v); } __device__ __forceinline__ float nbf(float v) { return bf2f(f2bf(v)); } +/* BF16 IN WHOLE REGISTERS. gfx12's compiler holds a 16-bit value in a register HALF: eight f2bf + * results written through a union of shorts are eight half moves before the pack, and a short + * loaded on its own is a d16 load that leaves the register's other half live, so it waits on that + * register's last write. These keep every value 32 bits wide -- pairs packed with f2bf2, whose + * rounding is f2bf's, a pair word's halves read with a shift and a mask, a lone bf16 loaded + * zero-extended -- and give the same bits. */ +__device__ __forceinline__ uint4 f2bf8(const float (&f)[8]) { + return make_uint4(f2bf2(f[0], f[1]), f2bf2(f[2], f[3]), f2bf2(f[4], f[5]), f2bf2(f[6], f[7])); +} +__device__ __forceinline__ void bf8_f(uint4 v, float (&f)[8]) { + f[0] = bf16w_lo(v.x); f[1] = bf16w_hi(v.x); f[2] = bf16w_lo(v.y); f[3] = bf16w_hi(v.y); + f[4] = bf16w_lo(v.z); f[5] = bf16w_hi(v.z); f[6] = bf16w_lo(v.w); f[7] = bf16w_hi(v.w); +} +__device__ __forceinline__ void bf8_f(r4d_u32x4 v, float (&f)[8]) { + f[0] = bf16w_lo(v.x); f[1] = bf16w_hi(v.x); f[2] = bf16w_lo(v.y); f[3] = bf16w_hi(v.y); + f[4] = bf16w_lo(v.z); f[5] = bf16w_hi(v.z); f[6] = bf16w_lo(v.w); f[7] = bf16w_hi(v.w); +} +/* Read through a GLOBAL pointer: through a generic one the load is still flat_load_d16_b16. */ +typedef __attribute__((address_space(1))) const unsigned short* hc_gu16; +__device__ __forceinline__ uint32_t bfw(const unsigned short* p) { return *(hc_gu16)p; } +__device__ __forceinline__ float bfw_f(uint32_t w) { return __uint_as_float(w << 16); } + /* ---- THE E4M3 MIXING MATRICES (r4d_hc_fp8.h) ------------------------------------------------ * * Every kernel below that reads mix_down or mix_up has an F8 form, selected by the stored dtype: @@ -152,10 +174,9 @@ __device__ __forceinline__ uint4 e4m3x8_bf16(const unsigned char* __restrict__ c const uint2 c = *(const uint2*)codes; float f[8]; e4m3x8(c.x, c.y, f); - union { uint4 v; unsigned short s[8]; } o; #pragma unroll - for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * sc); - return o.v; + for (int e = 0; e < 8; ++e) f[e] *= sc; + return f2bf8(f); } /* A WAVE'S DOT OF THE NATURAL-ORDER LDS VECTOR WITH ONE E4M3 ROW OF mix_down. A lane takes @@ -644,22 +665,22 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short constexpr int kSsIter = 5; long i = tid; for (; i + (long)(kSsIter - 1) * kThreads < n; i += (long)kSsIter * kThreads) { - unsigned short ev[kSsIter], hv[kSsIter][kHcMax]; + uint32_t ev[kSsIter], hv[kSsIter][kHcMax]; #pragma unroll for (int q = 0; q < kSsIter; ++q) { const long iq = i + (long)q * kThreads; - ev[q] = ep[iq]; + ev[q] = bfw(ep + iq); #pragma unroll for (int c = 0; c < kHcMax; ++c) - if (c < hc) hv[q][c] = hp[(long)c * n + iq]; + if (c < hc) hv[q][c] = bfw(hp + (long)c * n + iq); } #pragma unroll for (int q = 0; q < kSsIter; ++q) { - const float evf = bf2f(ev[q]); + const float evf = bfw_f(ev[q]); pe += evf * evf; #pragma unroll for (int c = 0; c < kHcMax; ++c) - if (c < hc) { const float v = bf2f(hv[q][c]); part[c] += v * v; } + if (c < hc) { const float v = bfw_f(hv[q][c]); part[c] += v * v; } } } for (; i < n; i += kThreads) { @@ -723,13 +744,13 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short const long q = base + (long)tid * 8; if (q >= n) break; const long ch = q & ~(kPer - 1); - unsigned short out[8]; + float out[8]; #pragma unroll for (int t = 0; t < 8; ++t) { const long li = ch + lane8 + (long)t * kWave; - out[t] = f2bf(bf2f(src[li]) * sc * (wv[li] + wadd)); + out[t] = bfw_f(bfw(src + li)) * sc * (wv[li] + wadd); } - *(uint4*)(dst + q) = *(const uint4*)out; + *(uint4*)(dst + q) = f2bf8(out); } } } else { @@ -785,8 +806,14 @@ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)size * columns share one pass over `h` and one grouped reduction. It is held TRANSPOSED inside each * 256-element chunk; wave_dot_swz above is the whole argument for that, and it is the difference * between eight conflicted 16-bit LDS reads a chunk and one ds_load_b128. */ +/* THE WAVES A SIMD: nine for the E4M3 dot, the budget it was tuned at. Left to choose, LLVM 24 + * builds it at 120 VGPRs for twelve waves, which costs 11% at four rows and 20% at seven with the + * weight read cold -- the shapes a speculative decode step runs. The bf16 form keeps the full + * range, which is what it is built at without the attribute; pinning it to sixteen changes its + * code. */ template __global__ __launch_bounds__(kThreads) +__attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16))) void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, const void* __restrict__ downv, long dld, const unsigned short* __restrict__ injw, @@ -882,11 +909,11 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr float acc = 0.0f; long i = tid; for (; i + (long)(kPreSs - 1) * kThreads < n; i += (long)kPreSs * kThreads) { - unsigned short hv[kPreSs]; + uint32_t hv[kPreSs]; #pragma unroll - for (int p = 0; p < kPreSs; ++p) hv[p] = hp[cb + i + (long)p * kThreads]; + for (int p = 0; p < kPreSs; ++p) hv[p] = bfw(hp + cb + i + (long)p * kThreads); #pragma unroll - for (int p = 0; p < kPreSs; ++p) { const float v = bf2f(hv[p]); acc += v * v; } + for (int p = 0; p < kPreSs; ++p) { const float v = bfw_f(hv[p]); acc += v * v; } } for (; i < n; i += kThreads) { const float v = bf2f(hp[cb + i]); acc += v * v; } acc = wave_sum(acc); @@ -921,28 +948,28 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr const long q = base + (long)tid * 8; if (q >= n) break; const long ch = cb + (q & ~(kPer - 1)); - unsigned short out[8]; + float out[8]; #pragma unroll for (int t = 0; t < 8; ++t) { const long li = ch + lane + (long)t * kWave; - out[t] = f2bf(bf2f(hp[li]) * sc * (w[li] + wadd)); + out[t] = bfw_f(bfw(hp + li)) * sc * (w[li] + wadd); } - *(uint4*)(sN + cb + q) = *(const uint4*)out; + *(uint4*)(sN + cb + q) = f2bf8(out); } } else { constexpr int kPreScale = 8; long i = tid; for (; i + (long)(kPreScale - 1) * kThreads < n; i += (long)kPreScale * kThreads) { float wv[kPreScale]; - unsigned short hv[kPreScale]; + uint32_t hv[kPreScale]; #pragma unroll for (int p = 0; p < kPreScale; ++p) { wv[p] = w[cb + i + (long)p * kThreads]; - hv[p] = hp[cb + i + (long)p * kThreads]; + hv[p] = bfw(hp + cb + i + (long)p * kThreads); } #pragma unroll for (int p = 0; p < kPreScale; ++p) - sN[cb + i + (long)p * kThreads] = f2bf(bf2f(hv[p]) * sc * (wv[p] + wadd)); + sN[cb + i + (long)p * kThreads] = f2bf(bfw_f(hv[p]) * sc * (wv[p] + wadd)); } for (; i < n; i += kThreads) sN[cb + i] = f2bf(bf2f(hp[cb + i]) * sc * (w[cb + i] + wadd)); @@ -1618,11 +1645,11 @@ void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __r long r = r0 + rr; if (r >= rows) r = rows - 1; const float sc = scalein[r * kHcMax + c]; const float* wp = w + k0 + k8; - union { uint4 v; unsigned short s[8]; } in, out; - in.v = *(const uint4*)(h + r * hrow + k0 + k8); + float f8v[8]; + bf8_f(*(const uint4*)(h + r * hrow + k0 + k8), f8v); #pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * sc * (wp[e] + wadd)); - *(uint4*)(sA + rr * kTAP + k8) = out.v; + for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * sc * (wp[e] + wadd); + *(uint4*)(sA + rr * kTAP + k8) = f2bf8(f8v); } for (int idx = tid; idx < NT * (kTKT / 8); idx += kThreads) { const int tt = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; @@ -1786,15 +1813,18 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re arow[i] = r < rows ? r : rows - 1; } - uint4 pa[kAV]; + /* The bf16-weight form stages through a native vector: in uint4 LLVM 24 keeps these arrays in + * scratch. The fp8 form is promoted either way and keeps uint4, at its tuned register count. */ + using Stg = std::conditional_t; + Stg pa[kAV]; float psc[kAV], pw[8]; - uint4 pb[kBV]; + Stg pb[kBV]; float pbs[kBV]; auto fetch = [&](long k0) { const int c = (int)(k0 / n); #pragma unroll for (int i = 0; i < kAV; ++i) { - pa[i] = *(const uint4*)(h + arow[i] * hrow + k0 + k8a); + pa[i] = *(const Stg*)(h + arow[i] * hrow + k0 + k8a); psc[i] = scalein[arow[i] * kHcMax + c]; } #pragma unroll @@ -1808,39 +1838,40 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re if (F8 && col < lr) { const unsigned char* row = (const unsigned char*)downv + col * dld; const uint2 cc = *(const uint2*)(row + k); - pb[b] = make_uint4(cc.x, cc.y, 0u, 0u); + pb[b] = Stg{cc.x, cc.y, 0u, 0u}; pbs[b] = ((const float*)(row + HN))[k / r4d_hc8::kDownGroup]; } else { const unsigned short* src = (col < lr) ? (const unsigned short*)downv + col * HN : injw + (col - lr) * HN; - pb[b] = *(const uint4*)(src + k); + pb[b] = *(const Stg*)(src + k); } } }; auto stage = [&]() { #pragma unroll for (int i = 0; i < kAV; ++i) { - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pa[i]; + float f8v[8]; + bf8_f(pa[i], f8v); #pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * psc[i] * (pw[e] + wadd)); - *(uint4*)(sA + (ar + i * kRS) * kTAP + k8a) = out.v; + for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * psc[i] * (pw[e] + wadd); + *(uint4*)(sA + (ar + i * kRS) * kTAP + k8a) = f2bf8(f8v); } #pragma unroll for (int b = 0; b < kBV; ++b) { const int idx = tid + b * kThreads, tt = idx / kKV, k8 = (idx % kKV) * 8; if (idx >= NT * kKV || tt >= nlive * 16) continue; long col = c0 + tt; if (col >= ncol) col = ncol - 1; - uint4 v = pb[b]; - if (F8 && col < lr) { - float f[8]; - e4m3x8(v.x, v.y, f); - union { uint4 v; unsigned short s[8]; } o; + Stg v = pb[b]; + if constexpr (F8) { + if (col < lr) { + float f[8]; + e4m3x8(v.x, v.y, f); #pragma unroll - for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * pbs[b]); - v = o.v; + for (int e = 0; e < 8; ++e) f[e] = f[e] * pbs[b]; + v = f2bf8(f); + } } - *(uint4*)(sB + tt * kTAP + k8) = v; + *(Stg*)(sB + tt * kTAP + k8) = v; } }; @@ -2303,10 +2334,9 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, if constexpr (F8) { float f[8]; e4m3x8(v.x, v.y, f); - union { uint4 v; unsigned short s[8]; } o; #pragma unroll - for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * pbs[i]); - v = k0 + k8a + 8 <= lr ? o.v : make_uint4(0u, 0u, 0u, 0u); + for (int e = 0; e < 8; ++e) f[e] = f[e] * pbs[i]; + v = k0 + k8a + 8 <= lr ? f2bf8(f) : make_uint4(0u, 0u, 0u, 0u); } *(uint4*)(sB + (tr + i * kRS) * kTAP + k8a) = v; } @@ -2341,11 +2371,11 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8; if (r0 + rl >= rows) continue; const long j = (long)c * n + i0 + i8; - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pn[i]; + float f8v[8]; + bf8_f(pn[i], f8v); #pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * pns[i] * (w[j + e] + wadd)); - *(uint4*)(sN + (rl * HC + c) * CH + i8) = out.v; + for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * pns[i] * (w[j + e] + wadd); + *(uint4*)(sN + (rl * HC + c) * CH + i8) = f2bf8(f8v); } __syncthreads(); @@ -2629,10 +2659,9 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ const float sc = ((const float*)(row + HN))[k / r4d_hc8::kDownGroup]; float fv[8]; e4m3x8(*(const uint32_t*)(row + k), *(const uint32_t*)(row + k + 8), fv); - union { uint4 v; unsigned short s[8]; } u; #pragma unroll - for (int e = 0; e < 8; ++e) u.s[e] = f2bf(fv[e] * sc); - o = u.v; + for (int e = 0; e < 8; ++e) fv[e] = fv[e] * sc; + o = f2bf8(fv); } else { const unsigned short* src = (col < lr) ? (const unsigned short*)downv + col * HN : injw + (col - lr) * HN; @@ -2711,11 +2740,11 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res auto stageA = [&](unsigned short* dst) { #pragma unroll for (int i = 0; i < kAV; ++i) { - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pa[i]; + float f8v[8]; + bf8_f(pa[i], f8v); #pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * psc[i] * (pw[e] + wadd)); - *(uint4*)(dst + (ar + i * kRS) * kTAP + k8a) = out.v; + for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * psc[i] * (pw[e] + wadd); + *(uint4*)(dst + (ar + i * kRS) * kTAP + k8a) = f2bf8(f8v); } }; @@ -2883,18 +2912,18 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned for (int k = 0; k < kSsRows; ++k) acc[k] = 0.0f; long j = lane; for (; j + (long)(kSsPre - 1) * kWave < len; j += (long)kSsPre * kWave) { - unsigned short v[kSsRows][kSsPre]; + uint32_t v[kSsRows][kSsPre]; #pragma unroll for (int k = 0; k < kSsRows; ++k) if (k < nr) { #pragma unroll - for (int q = 0; q < kSsPre; ++q) v[k][q] = p[k][j + (long)q * kWave]; + for (int q = 0; q < kSsPre; ++q) v[k][q] = bfw(p[k] + j + (long)q * kWave); } #pragma unroll for (int k = 0; k < kSsRows; ++k) if (k < nr) { #pragma unroll - for (int q = 0; q < kSsPre; ++q) { const float f = bf2f(v[k][q]); acc[k] += f * f; } + for (int q = 0; q < kSsPre; ++q) { const float f = bfw_f(v[k][q]); acc[k] += f * f; } } } for (; j < len; j += kWave) @@ -2976,28 +3005,40 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned if constexpr (F8) { float f[8]; e4m3x8(o.c.x, o.c.y, f); - union { uint4 v; unsigned short s[8]; } u; #pragma unroll - for (int q = 0; q < 8; ++q) u.s[q] = f2bf(f[q] * o.s); - return u.v; + for (int q = 0; q < 8; ++q) f[q] = f[q] * o.s; + return f2bf8(f); } else { return o.v; } }; + /* AN A ITEM'S ROWS ARE THE SAME EVERY K STEP: its token and sub-stream are a 64-bit division + * by `hc` and its remainder, worked out once here as element offsets. Left in the step, gfx12's + * compiler expands the division again every slice -- twenty times over at the 64-row tile and + * fifty at the 128-row one -- where LLVM 22 moved it out of the loop. The same addresses. */ + uint32_t aoh[kAI], aoe[kAI], aow[kAI], ak8[kAI]; +#pragma unroll + for (int a = 0; a < kAI; ++a) { + const int idx = tid + a * kThreads; + const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; + const long Ri = r0 + rr; + const long rt = (Ri < R) ? Ri / hc : rows - 1, kt = (Ri < R) ? Ri % hc : 0; + aoh[a] = (uint32_t)(rt * hrow + kt * n + k8); + aoe[a] = (uint32_t)(rt * erow + k8); + aow[a] = (uint32_t)(kt * n + k8); + ak8[a] = (uint32_t)k8; + } auto issue = [&](long k0) { #pragma unroll for (int a = 0; a < kAI; ++a) { const int idx = tid + a * kThreads; if (idx >= RT * (kTKT / 8)) break; - const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; - const long Ri = r0 + rr; - const long rt = (Ri < R) ? Ri / hc : rows - 1, kt = (Ri < R) ? Ri % hc : 0; - ap[a].h = *(const uint4*)(h + rt * hrow + kt * n + k0 + k8); - ap[a].e = *(const uint4*)(e + rt * erow + k0 + k8); - ap[a].wh0 = *(const float4*)(wh + kt * n + k0 + k8); - ap[a].wh1 = *(const float4*)(wh + kt * n + k0 + k8 + 4); - ap[a].we0 = *(const float4*)(we + k0 + k8); - ap[a].we1 = *(const float4*)(we + k0 + k8 + 4); + ap[a].h = *(const uint4*)(h + aoh[a] + k0); + ap[a].e = *(const uint4*)(e + aoe[a] + k0); + ap[a].wh0 = *(const float4*)(wh + aow[a] + k0); + ap[a].wh1 = *(const float4*)(wh + aow[a] + k0 + 4); + ap[a].we0 = *(const float4*)(we + ak8[a] + k0); + ap[a].we1 = *(const float4*)(we + ak8[a] + k0 + 4); } #pragma unroll for (int b = 0; b < kBI; ++b) { @@ -3019,19 +3060,19 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned if (idx >= RT * (kTKT / 8)) break; const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; const float sc = s_rs[rr], se = s_re[rr]; - union { uint4 v; unsigned short s[8]; } in, out; const float wp[8] = { ap[a].wh0.x, ap[a].wh0.y, ap[a].wh0.z, ap[a].wh0.w, ap[a].wh1.x, ap[a].wh1.y, ap[a].wh1.z, ap[a].wh1.w }; const float wq[8] = { ap[a].we0.x, ap[a].we0.y, ap[a].we0.z, ap[a].we0.w, ap[a].we1.x, ap[a].we1.y, ap[a].we1.z, ap[a].we1.w }; - in.v = ap[a].h; + float f8v[8]; + bf8_f(ap[a].h, f8v); #pragma unroll - for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * sc * (wp[q] + wadd)); - *(uint4*)(sAh + rr * kTAP + k8) = out.v; - in.v = ap[a].e; + for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * sc * (wp[q] + wadd); + *(uint4*)(sAh + rr * kTAP + k8) = f2bf8(f8v); + bf8_f(ap[a].e, f8v); #pragma unroll - for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * se * (wq[q] + wadd)); - *(uint4*)(sAe + rr * kTAP + k8) = out.v; + for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * se * (wq[q] + wadd); + *(uint4*)(sAe + rr * kTAP + k8) = f2bf8(f8v); } #pragma unroll for (int b = 0; b < kBI; ++b) { @@ -3068,11 +3109,14 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned if (nt >= NT16) continue; const long j = j0 + nt * 16 + nn; if (j >= n) continue; + /* The eight rows are consecutive output rows: one division for the first, and the + * (token, sub-stream) pair stepped from there rather than divided out again a row. */ + const long Rq = r0 + mt * 16 + e0; + long tq = Rq / hc, kq = Rq % hc; #pragma unroll for (int q = 0; q < 8; ++q) { - const long Ri = r0 + mt * 16 + e0 + q; - if (Ri >= R) continue; - x[(Ri / hc) * xrow + (Ri % hc) * n + j] = f2bf(acc[im][in][q]); + if (Rq + q < R) x[tq * xrow + kq * n + j] = f2bf(acc[im][in][q]); + if (++kq == hc) { kq = 0; ++tq; } } } } @@ -3126,11 +3170,11 @@ void mtp_prefill_scale_kernel(const unsigned short* __restrict__ h, float acc = 0.0f; long j = lane; for (; j + (long)(kPre - 1) * kWave < len; j += (long)kPre * kWave) { - unsigned short v[kPre]; + uint32_t v[kPre]; #pragma unroll - for (int q = 0; q < kPre; ++q) v[q] = p[j + (long)q * kWave]; + for (int q = 0; q < kPre; ++q) v[q] = bfw(p + j + (long)q * kWave); #pragma unroll - for (int q = 0; q < kPre; ++q) { const float f = bf2f(v[q]); acc += f * f; } + for (int q = 0; q < kPre; ++q) { const float f = bfw_f(v[q]); acc += f * f; } } for (; j < len; j += kWave) { const float f = bf2f(p[j]); acc += f * f; } acc = wave_sum(acc); @@ -3212,7 +3256,7 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow, float4 rg0[AL], rg1[AL]; uint2 rc[WL]; float rsc[WL]; - uint4 rw[WL]; + r4d_u32x4 rw[WL]; /* registers; uint4 would sit in scratch */ auto fetch = [&](long k0) { #pragma unroll for (int i = 0; i < AL; ++i) { @@ -3227,7 +3271,7 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow, rc[i] = *(const uint2*)(wrow[i] + k); rsc[i] = ((const float*)(wrow[i] + n))[k / r4d_hc8::kDownGroup]; } else { - rw[i] = *(const uint4*)(wsrc[i] + k0); + rw[i] = *(const r4d_u32x4*)(wsrc[i] + k0); } } }; @@ -3238,25 +3282,24 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow, __syncthreads(); /* the previous tile's fragments are read */ #pragma unroll for (int i = 0; i < AL; ++i) { - union { uint4 v; unsigned short s[8]; } in, out; - in.v = ra[i]; + float f8v[8]; + bf8_f(ra[i], f8v); const float g[8] = { rg0[i].x, rg0[i].y, rg0[i].z, rg0[i].w, rg1[i].x, rg1[i].y, rg1[i].z, rg1[i].w }; #pragma unroll - for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * asc[i] * (g[q] + wadd)); - *(uint4*)adst[i] = out.v; + for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * asc[i] * (g[q] + wadd); + *(uint4*)adst[i] = f2bf8(f8v); } #pragma unroll for (int i = 0; i < WL; ++i) { if constexpr (F8) { float f[8]; e4m3x8(rc[i].x, rc[i].y, f); - union { uint4 v; unsigned short s[8]; } o; #pragma unroll - for (int q = 0; q < 8; ++q) o.s[q] = f2bf(f[q] * rsc[i]); - *(uint4*)wdst[i] = o.v; + for (int q = 0; q < 8; ++q) f[q] = f[q] * rsc[i]; + *(uint4*)wdst[i] = f2bf8(f); } else { - *(uint4*)wdst[i] = rw[i]; + *(r4d_u32x4*)wdst[i] = rw[i]; } } __syncthreads(); diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 1539c9d8..5d9d848d 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -314,15 +314,32 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel( // ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is // the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot // drift because both are stated and neither is inferred. +// +// A ROW IS SPLIT OVER grid.y, kSiluPer elements a thread. One workgroup a row put a decode step's few +// rows on as many workgroups, each walking its row a strided element at a time behind an exp and a +// divide: latency-bound, and the shape of that walk was up to the compiler. Here a thread's +// elements are independent and their loads unconditional (a column past the row reads its last +// element and the store drops it), so they are all in flight at once. Same arithmetic an element. +constexpr uint32_t kSiluPer = 4; __global__ __launch_bounds__(kThreads) void silu_mul_kernel( const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { const uint32_t m = blockIdx.x; const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; - for (uint32_t i = threadIdx.x; i < n; i += kThreads) { - const float g = bf2f(gr[i]); - yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(gr[n + i])); + const uint32_t i0 = blockIdx.y * (kSiluPer * kThreads) + threadIdx.x; + uint16_t gv[kSiluPer], uv[kSiluPer]; +#pragma unroll + for (uint32_t u = 0; u < kSiluPer; ++u) { + const uint32_t i = i0 + u * kThreads, ic = i < n ? i : n - 1u; + gv[u] = gr[ic]; + uv[u] = gr[n + ic]; + } +#pragma unroll + for (uint32_t u = 0; u < kSiluPer; ++u) { + const uint32_t i = i0 + u * kThreads; + const float g = bf2f(gv[u]); + if (i < n) yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(uv[u])); } } @@ -776,8 +793,9 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y if (M <= 0 || n <= 0) return -2; if (!gu_ld) gu_ld = 2 * n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(silu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, - (const uint16_t*)gu, (uint16_t*)y, (uint32_t)n, + const uint32_t chunks = ((uint32_t)n + kSiluPer * kThreads - 1u) / (kSiluPer * kThreads); + hipLaunchKernelGGL(silu_mul_kernel, dim3((uint32_t)M, chunks), dim3(kThreads), 0, + (hipStream_t)stream, (const uint16_t*)gu, (uint16_t*)y, (uint32_t)n, (uint32_t)gu_ld, (uint32_t)y_ld); return hipGetLastError() == hipSuccess ? 0 : -4; } diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 6a55388f..384c9d1f 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -773,13 +773,26 @@ __device__ __forceinline__ Stage8 stage8_load_w(const uint8_t* __restrict__ src, } return r; } +/* A staged tile row as loaded, or the zero a dead row stages. */ +__device__ __forceinline__ Stage8 stage8_keep(const Stage8& s, bool live) { + Stage8 r; + r.v = live ? s.v : make_uint4(0, 0, 0, 0); + r.w = live ? s.w : make_uint4(0, 0, 0, 0); + return r; +} template __device__ __forceinline__ uint32_t u32_load_w(const uint32_t* p) { if constexpr (!UW) return *p; return *(r4d_moe_gu32)p; } +/* A 16-BIT SCALE LOADED ZERO-EXTENDED INTO A WHOLE REGISTER. Kept 16-bit, LLVM 24 loads it into a + * register HALF (global_load_d16_b16), which leaves the other half live in the same register: the + * load then depends on that register's last write, and the waitcnt pass answers with a full wait + * at the branch joins around the scale loads. The first pass's three loads -- this scale, the + * activation scale, the activation -- went out one round trip each, which cost the down + * projection's four-pass blocks 25-30%. Widened here, it is LLVM 22's global_load_u16. */ template -__device__ __forceinline__ uint16_t u16_load_w(const uint16_t* p) { +__device__ __forceinline__ uint32_t u16_load_w(const uint16_t* p) { if constexpr (!UW) return *p; return *(r4d_moe_gu16)p; } @@ -961,11 +974,23 @@ static_assert(sizeof(MoeTab) == 16, "the code table is four words"); * * RS finds an ES block's run in one round trip -- see the RS note at the run search. It covers * up to kMaxExpert experts; a wider expert count takes the chunked search, which numbers the runs - * the same way. */ + * the same way. + * + * THE WAVES A SIMD EACH FORM RUNS AT (R4D_WAVES), as every form was measured: the ES prefill grid + * at 9-11 (5 at FK 256, where the staged pass is the register budget), the aligned form at 9-12, + * the uniform grid at 8-9. Left to itself LLVM 24 spends about 30 more VGPRs on the aligned + * split-K form for one to three fewer waves, which cost its prefill tiles 16-52%. */ +constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk, bool rs) { + return es ? (fk == 256u ? 5u : w4 == 0 ? (rs ? 10u : 11u) : w4 == 1 ? 11u : w4 == 3 ? 9u : 10u) + : al ? (ntl == 16u ? (w4 == 1 ? 12u : 9u) : ntl == 8u ? (w4 <= 1 ? 10u : 9u) : 9u) + : (w4 <= 1 ? 9u : 8u); +} + template -__global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( +__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS)) +void moe_gemm_q_kernel( const uint8_t* __restrict__ Aq, const float* __restrict__ As, const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, @@ -1325,7 +1350,14 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( if (re <= rs) break; /* Not this block's run: walk past it. Block-uniform, so no barrier is skipped by some * threads and not others. */ - if (ES && run != jrun) { rs = re; ++run; continue; } + /* Not this block's run: never true, since under ES the loop starts at the block's run. + * It stays for the fp8 weight (W4 0) alone, as the back edge it makes: the CFG + * structurizer keeps it, and LLVM 24's waitcnt pass then places the decode form's first-pass + * waits differently. With it the four-bit forms' first pass went out one load a round trip + * (FK 256 gate_up at one and two tokens 4-7% slower than 7.2); without it the fp8 form's + * K loop did (11-13% slower at one and two tokens). Each form is built the way it measured + * faster: r4d_selftest --perfmoe --cold and the MoE fixture's cold kbench. */ + if (ES && W4 == 0 && run != jrun) { rs = re; ++run; continue; } /* The expert's class, and where this block's columns sit in its weight. Block-uniform: a * pad tile zeroes the run's rows and moves on without touching LDS or a barrier. `cshift` @@ -1341,7 +1373,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( } rs = re; ++run; - if (ES) break; + if (ES || AL) break; continue; } const uint32_t wn0 = part * fc + j0; /* the weight row of the block's column 0 */ @@ -1419,11 +1451,28 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( uint4 bpre4[kBP]; /* W4: packed nibbles, expanded at store time as before */ uint32_t spre[W4 == 4 ? kBP : 1]; /* W4 4: the same 32 elements' sign bits */ Stage8 bpre8[kBP]; /* otherwise: the fp8 bytes themselves */ + /* kUL: WHETHER EACH STAGED ROW IS LIVE. Under kUL a row's tile is loaded whether it is + * live or not -- a dead row reads a row that exists -- and the zero it stages is selected + * at the LDS store, from these. Loaded only when live, the zero is written into the + * load's destination first, and that write lands on registers the previous pass's load + * filled: on the path where a wave's lanes all skipped that load's store branch, the + * waitcnt pass cannot see the load collected, so it waits for every load in flight before + * the write. Each pass's loads then went out one pair a round trip -- three a K step at + * the aligned down projection's tile, 15% of its time -- where an unconditional load into + * the same registers needs no wait at all (loads of one kind retire in order). The + * one-run-a-block form (ES) keeps the guarded loads: unconditional, it measured 1.5% + * slower, and it does not have the waits. */ + constexpr bool kUL = UW && AL; + [[maybe_unused]] bool aok[kUL ? kAP : 1]; + [[maybe_unused]] bool bok[kUL ? kBP : 1]; /* thread tid < FM: its row's activation scale, one a 128-wide block of the pass */ float pas[kBpS] = {}; /* thread FM + c: column c's weight scale (w4), or the block's (fp8); at W4 3 its four -- * again one a 128-wide block of the pass */ - using PwsT = std::conditional_t; + /* At W4 3 the scale IS 32 bits, its four E4M3 groups packed: a 16-bit register would keep + * two of them. Otherwise a 16-bit scale: under AL held zero-extended in a whole register + * (see u16_load_w), the other forms measured 1% slower that way and keep it 16-bit. */ + using PwsT = std::conditional_t; PwsT pws[kBpS] = {}; /* UW: the thread's scale as loaded, and whether it is live -- the zero is selected where * it is staged. Two registers, one a role, and NOT initialised: the two branches run in @@ -1433,7 +1482,12 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( float pau[UW ? kBpS : 1]; PwsT pwu[UW ? kBpS : 1]; bool pok = false; - auto issue = [&](uint32_t cc) { + /* `first` is the pass at cc 0 as a TYPE, not a test of cc: the early weight is read there + * and nowhere else, and a runtime `cc == 0` in the loop's issue(c0 + FK) is one the compiler + * cannot rule out (the sum is unsigned and may wrap), so it kept the ew_ registers live + * across every pass -- under LLVM 24, sixteen VGPRs the WMMA block then went without: at + * the pinned occupancy it read each fragment pair behind a full LDS wait. */ + auto issue = [&](uint32_t cc, auto first) { const uint32_t kbk = cc / kBlock; if constexpr (UW) { /* UNDER UW THE SCALE LOADS ARE UNCONDITIONAL -- from a row that exists when this @@ -1479,7 +1533,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( else if constexpr (W4) pws[h] = j0 + nn < fc ? u16_load_w(Wsp + (size_t)(wn0 + nn) * ws_ld + kbk + h) - : (uint16_t)0; + : 0u; else if (nn == 0) pws[h] = u16_load_w(Wsp + (size_t)kb_n * ws_ld + kbk + h); } @@ -1490,26 +1544,40 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( if (r >= FM) continue; const int32_t tok = s_tok[r]; const bool ok = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re; - apre[p] = stage8_load(Aq + (size_t)(ok ? tok : 0) * a_ld + cc + sk, ok); + const uint8_t* src = Aq + (size_t)(ok ? tok : 0) * a_ld + cc + sk; + if constexpr (kUL) { + aok[p] = ok; + apre[p] = stage8_load_w(src, true); + } else + apre[p] = stage8_load(src, ok); } - if constexpr (AL) { + if constexpr (AL && decltype(first)::value) { + /* the first pass's weight is already in flight */ static_assert(kEwBP == kBP && kEwRPP == kRPP, "the early weight stages the pass issue() would"); - if (cc == 0) { /* the first pass's weight is already in flight */ #pragma unroll - for (uint32_t p = 0; p < kBP; ++p) { - if (sn + p * kRPP >= FN) continue; - /* The dead rows' zeros, as w4_load / stage8_load give them. */ + for (uint32_t p = 0; p < kBP; ++p) { + if (sn + p * kRPP >= FN) continue; + if constexpr (kUL) { + /* loaded from a row that exists; the store selects the dead rows' zero */ + bok[p] = ew_ok[p]; if constexpr (W4) { - bpre4[p] = ew_ok[p] ? ew_b4[p] : make_uint4(0, 0, 0, 0); - if constexpr (W4 == 4) spre[p] = ew_ok[p] ? ew_sp[p] : 0u; - } else { - bpre8[p].v = ew_ok[p] ? ew_b8[p].v : make_uint4(0, 0, 0, 0); - bpre8[p].w = ew_ok[p] ? ew_b8[p].w : make_uint4(0, 0, 0, 0); - } + bpre4[p] = ew_b4[p]; + if constexpr (W4 == 4) spre[p] = ew_sp[p]; + } else + bpre8[p] = ew_b8[p]; + continue; + } + /* The dead rows' zeros, as w4_load / stage8_load give them. */ + if constexpr (W4) { + bpre4[p] = ew_ok[p] ? ew_b4[p] : make_uint4(0, 0, 0, 0); + if constexpr (W4 == 4) spre[p] = ew_ok[p] ? ew_sp[p] : 0u; + } else { + bpre8[p].v = ew_ok[p] ? ew_b8[p].v : make_uint4(0, 0, 0, 0); + bpre8[p].w = ew_ok[p] ? ew_b8[p].w : make_uint4(0, 0, 0, 0); } - return; } + return; } #pragma unroll for (uint32_t p = 0; p < kBP; ++p) { @@ -1518,21 +1586,23 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( const bool ok = (j0 + r) < fc; /* W4: half the bytes off the same row, expanded on the way in. `w_ld` is the * PACKED byte pitch there, which is why it is not divided here. At W4 4 the row's - * sign plane follows its K/2 bytes of nibbles, a bit an element. */ + * sign plane follows its K/2 bytes of nibbles, a bit an element. Under kUL a dead + * row reads the tile's first row, and the store selects its zero (see bok). */ + const uint8_t* wr = Wp + (size_t)(kUL && !ok ? wn0 : wn0 + r) * w_ld; + if constexpr (kUL) bok[p] = ok; if constexpr (W4) { - const uint8_t* wr = Wp + (size_t)(wn0 + r) * w_ld; - bpre4[p] = w4_load_w(wr + ((cc + sk) >> 1), ok); + bpre4[p] = w4_load_w(wr + ((cc + sk) >> 1), kUL || ok); if constexpr (W4 == 4) - spre[p] = ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + - ((cc + sk) >> 3))) - : 0u; + spre[p] = kUL || ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + + ((cc + sk) >> 3))) + : 0u; } else - bpre8[p] = stage8_load_w(Wp + (size_t)(wn0 + r) * w_ld + cc + sk, ok); + bpre8[p] = stage8_load_w(wr + cc + sk, kUL || ok); } }; /* `s_tok` is settled by the barrier above the run loop and no run rewrites it, so priming * ahead of the loop's own barrier reads nothing another thread is still writing. */ - issue(0); + issue(0u, std::true_type{}); /* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE -- no thread reads what another wrote * to global memory inside it. __syncthreads() is a workgroup fence over every address @@ -1561,18 +1631,21 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( for (uint32_t p = 0; p < kAP; ++p) { const uint32_t r = sn + p * kRPP; if (r >= FM) continue; - stage8_store(s_a, r, sk, apre[p]); + stage8_store(s_a, r, sk, kUL ? stage8_keep(apre[p], aok[p]) : apre[p]); } #pragma unroll for (uint32_t p = 0; p < kBP; ++p) { const uint32_t r = sn + p * kRPP; if (r >= FN) continue; + /* a dead row's zero, where the packed form held it before (see bok) */ + const bool live = !kUL || bok[p]; + const uint4 b4 = live ? bpre4[p] : make_uint4(0, 0, 0, 0); if constexpr (W4 == 4) - stage8_store(s_b, r, sk, w5_expand(bpre4[p], spre[p], tab.v)); + stage8_store(s_b, r, sk, w5_expand(b4, live ? spre[p] : 0u, tab.v)); else if constexpr (W4) - stage8_store(s_b, r, sk, w4_expand(bpre4[p], tab.v)); + stage8_store(s_b, r, sk, w4_expand(b4, tab.v)); else - stage8_store(s_b, r, sk, bpre8[p]); + stage8_store(s_b, r, sk, kUL ? stage8_keep(bpre8[p], live) : bpre8[p]); } /* The scales as issued; under UW the dead ones are zeroed here (see issue). */ auto pas_v = [&](uint32_t h) { @@ -1601,7 +1674,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( s_ws[tid - FM] = (W4 || tid == FM) ? bscale(pws_v(0)) : 0.0f; } } - if (c0 + FK < K) issue(c0 + FK); + if (c0 + FK < K) issue(c0 + FK, std::false_type{}); kbar(); if (!wlive) continue; @@ -1748,7 +1821,11 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( rs = re; ++run; - if (ES) break; /* one run a block, and it is done */ + /* One run a block under ES and AL, and it is done. Under AL a second pass of this loop would + * leave at once (the map's run ends at al_end), but as a loop it lets the compiler hoist + * the first pass's selects of the early weight out of it, to the top: LLVM 24 does, and + * then waits for that weight before the pass's other loads are issued. */ + if (ES || AL) break; } } /* The whole argument list against the descriptor (see MoeTab): every instantiation takes the same @@ -1850,11 +1927,15 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( * the (tile, run) form's runs do: an operand may name fewer rows than its buffer, never more. * A run that would start past T is then empty and has no tile, so the tile count also stays * inside the grid's bound. */ + /* The loads are unconditional -- a thread past the experts reads off[n_expert] again and a + * select drops it -- so the NPT + 1 of them issue in one round. Guarded, each sits in a branch + * of its own with its wait behind it: NPT + 1 round trips in front of the first barrier. */ uint32_t ov[NPT + 1]; #pragma unroll for (uint32_t k = 0; k <= NPT; ++k) { const uint32_t x = tid * NPT + k; - const uint32_t o = x <= n_expert ? (uint32_t)off[x] : 0u; + const uint32_t raw = (uint32_t)off[x <= n_expert ? x : n_expert]; + const uint32_t o = x <= n_expert ? raw : 0u; ov[k] = o < T ? o : T; } uint32_t nt[NPT], cnt = 0; @@ -1947,7 +2028,7 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( uint4 bpre4[kBP]; uint32_t spre[W4 == 4 ? kBP : 1]; Stage8 bpre8[kBP]; - using PwsT = std::conditional_t; + using PwsT = uint32_t; /* a 16-bit scale zero-extended: see u16_load_w */ float pau[1]; PwsT pwu[1]; bool pok = false; @@ -2297,9 +2378,14 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( #pragma unroll for (uint32_t j = 0; j < WN; ++j) acc[i][j] = (mb_v8f)(0.0f); - /* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8 of it; a row outside the run - * or a dropped slot stages zeros and issues no load, so the bytes read are the live rows. */ + /* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8 of it. A row outside the run, + * a dropped slot or a column past N stages zeros. EVERY LOAD IS ISSUED, a dead row's from a + * row that exists -- the activation's row 0, the tile's last weight row -- and the store + * selects its zero: a load under its own condition is an exec-masked branch, and the + * waitcnt pass then waits inside it, which serialises the pass's loads (moe_gemm_q_kernel's + * K-loop note). */ uint4 apre[kAC], bpre[kBC]; + bool aok[kAC], bok[kBC]; auto issue = [&](uint32_t k0) { #pragma unroll for (uint32_t p = 0; p < kAC; ++p) { @@ -2307,37 +2393,45 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel( if (c >= FM * kCPR) continue; const uint32_t r = c / kCPR, kk = (c % kCPR) * 8; const int32_t tok = s_tok[r]; - const bool ok = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re; - apre[p] = ok ? *(const uint4*)(A + (size_t)tok * a_ld + k0 + kk) - : make_uint4(0, 0, 0, 0); + aok[p] = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re; + apre[p] = *(const uint4*)(A + (size_t)(aok[p] ? tok : 0) * a_ld + k0 + kk); } #pragma unroll for (uint32_t p = 0; p < kBC; ++p) { const uint32_t c = tid + p * NTHR; if (c >= FN * kCPR) continue; const uint32_t r = c / kCPR, kk = (c % kCPR) * 8; - bpre[p] = (n0 + r) < N ? *(const uint4*)(Wp + (size_t)(n0 + r) * w_ld + k0 + kk) - : make_uint4(0, 0, 0, 0); + bok[p] = (n0 + r) < N; + bpre[p] = *(const uint4*)(Wp + (size_t)(bok[p] ? n0 + r : N - 1) * w_ld + k0 + kk); } }; issue(0); + /* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE, so they are lds_barrier(): + * __syncthreads() is a fence over global memory too, `s_wait_loadcnt 0` in front of the + * barrier, and the next pass's prefetch would be waited for right after it is issued + * instead of behind this pass's WMMA. The prefetch is collected by one explicit wait where + * the stores begin -- a release fence on the global address space, the spelling the + * waitcnt pass reads as `s_wait_loadcnt 0` (moe_gemm_q_kernel's K-loop note). */ for (uint32_t k0 = 0; k0 < K; k0 += kBK16) { - __syncthreads(); /* the previous pass's fragments are read */ + lds_barrier(); /* the previous pass's fragments are read */ + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "global"); #pragma unroll for (uint32_t p = 0; p < kAC; ++p) { const uint32_t c = tid + p * NTHR; if (c >= FM * kCPR) continue; - *(uint4*)(s_a + (c / kCPR) * kP16 + (c % kCPR) * 8) = apre[p]; + *(uint4*)(s_a + (c / kCPR) * kP16 + (c % kCPR) * 8) = + aok[p] ? apre[p] : make_uint4(0, 0, 0, 0); } #pragma unroll for (uint32_t p = 0; p < kBC; ++p) { const uint32_t c = tid + p * NTHR; if (c >= FN * kCPR) continue; - *(uint4*)(s_b + (c / kCPR) * kP16 + (c % kCPR) * 8) = bpre[p]; + *(uint4*)(s_b + (c / kCPR) * kP16 + (c % kCPR) * 8) = + bok[p] ? bpre[p] : make_uint4(0, 0, 0, 0); } if (k0 + kBK16 < K) issue(k0 + kBK16); - __syncthreads(); + lds_barrier(); if (!wlive) continue; #pragma unroll @@ -3043,7 +3137,8 @@ static inline long long r4d_blockmap_bytes(long long cap) { /* ONE WORKGROUP, because the whole of it is a scan over at most kMaxExpert counters and a second * launch to split that across the device would cost more than the scan does. The offsets are read - * into LDS once so the scan is not 512 dependent global loads. + * once, in parallel, so the scan is not 512 dependent global loads. The launch is NT threads, a + * thread owning experts tid, tid + NT, ... * * THE PREFIX IS PARALLEL: a DPP scan in each wave and one exchange of the wave totals, 256 counts * a tile -- three tiles at 512 experts, whose n_expert + 1 counts end one past the second. On one @@ -3055,20 +3150,31 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( uint32_t* __restrict__ map) { constexpr uint32_t NT = 256, NW = NT / kWave, kTiles = (kMaxExpert + NT) / NT; __shared__ uint32_t s_cnt[kMaxExpert + 1]; - __shared__ int32_t s_off[kMaxExpert + 1]; __shared__ int32_t s_wt[kTiles][NW]; const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; - for (uint32_t e = tid; e <= n_expert; e += blockDim.x) s_off[e] = off[e]; - __syncthreads(); + /* EVERY OFFSET THIS THREAD NEEDS IN ONE ROUND OF LOADS: both ends of each expert it owns + * (e = tid + i * NT), the index clamped so every load is unconditional, all issued before the + * first is waited on. A loop over e that stores each offset to LDS before the next load makes + * one dependent trip to memory per expert a thread owns -- three at 512 experts -- and the + * offsets are read cold, straight after the router wrote them. The counts and the map's rows + * then come from these registers, so the offsets never pass through LDS. */ + int32_t lo[kTiles], hi[kTiles]; +#pragma unroll + for (uint32_t i = 0; i < kTiles; ++i) { + const uint32_t e = tid + i * NT; + lo[i] = off[e < n_expert ? e : n_expert]; + hi[i] = off[e + 1 < n_expert ? e + 1 : n_expert]; + } + const uint32_t live = (uint32_t)off[n_expert]; /* Blocks this expert needs. A zero-row run needs none, and asking for one would put an empty * block in the map that the GEMM would then have to recognise. */ - for (uint32_t e = tid; e < n_expert; e += blockDim.x) { - const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]); - s_cnt[e] = (run + FM - 1) / FM; +#pragma unroll + for (uint32_t i = 0; i < kTiles; ++i) { + const uint32_t e = tid + i * NT; + if (e < n_expert) s_cnt[e] = ((uint32_t)(hi[i] - lo[i]) + FM - 1) / FM; } /* The tail of dropped slots, carried as one more "expert" so the scan places it too. */ - const uint32_t live = (uint32_t)s_off[n_expert]; if (tid == 0) s_cnt[n_expert] = T > live ? (T - live + FM - 1) / FM : 0u; __syncthreads(); @@ -3094,13 +3200,16 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel( if (tid == 0) map[0] = carry < cap ? carry : cap; /* the count, clamped to the grid */ __syncthreads(); - for (uint32_t e = tid; e < n_expert; e += blockDim.x) { - const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]); +#pragma unroll + for (uint32_t i = 0; i < kTiles; ++i) { + const uint32_t e = tid + i * NT; + if (e >= n_expert) continue; + const uint32_t run = (uint32_t)(hi[i] - lo[i]); uint32_t o = s_cnt[e]; for (uint32_t r = 0; r < run; r += FM, ++o) { if (o >= cap) break; map[1 + 2 * o + 0] = e; - map[1 + 2 * o + 1] = (uint32_t)s_off[e] + r; + map[1 + 2 * o + 1] = (uint32_t)lo[i] + r; } } if (tid == 0) { diff --git a/libr4d/r4d_ple_conv_bf16.hip b/libr4d/r4d_ple_conv_bf16.hip index d6f0238f..a2e3774f 100644 --- a/libr4d/r4d_ple_conv_bf16.hip +++ b/libr4d/r4d_ple_conv_bf16.hip @@ -1,5 +1,6 @@ // r4d_ple_conv_bf16.hip -- Per-Layer Embedding's dilated depthwise convolution, its silu, and the -// residual add that finishes the layer. +// residual add that finishes the layer; and, as `causal_conv1d`, the same convolution with no +// activation, no residual and no dilation, which is LFM2's short convolution. // // ============================== WHAT IT COMPUTES ============================== // @@ -83,6 +84,9 @@ static_assert(kPcMaxHist < kPcBT, "the conv history must fit inside tile 0 for t * against uses std::exp. The GDN conv, which is instruction-bound, makes the opposite trade. */ __device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z)); } +/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window + * with none, no residual and dilation one. */ +template __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, uint16_t* __restrict__ cs, const int32_t* __restrict__ cu, @@ -125,14 +129,15 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( float acc = 0.0f; #pragma unroll for (uint32_t j = 0; j < kPcMaxW; ++j) { - if (j >= wid) break; - const int32_t src = t - (int32_t)hist + (int32_t)(j * dil); - const float v = src >= 0 ? bf16_to_f32(xc[(size_t)src * xld]) - : (hc ? bf16_to_f32(hc[(src + (int32_t)hist) * cs_tok]) : 0.0f); - acc += v * wt[j]; + if (j < wid) { + const int32_t src = t - (int32_t)hist + (int32_t)(j * dil); + const float v = src >= 0 ? bf16_to_f32(xc[(size_t)src * xld]) + : (hc ? bf16_to_f32(hc[(src + (int32_t)hist) * cs_tok]) : 0.0f); + acc += v * wt[j]; + } } const float r = rc ? bf16_to_f32(rc[(size_t)t * rld]) : 0.0f; - yc[(size_t)t * yld] = f32_to_bf16(r + pc_silu(acc)); + yc[(size_t)t * yld] = f32_to_bf16(r + (SILU ? pc_silu(acc) : acc)); } /* THE WINDOW THIS STEP LEAVES BEHIND, in the same launch and with no barrier at all. @@ -162,47 +167,36 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( uint16_t keep[kPcMaxHist]; if (nacc) { #pragma unroll - for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) { - if (i + 1 >= hist) break; - keep[i] = hc ? hc[(size_t)(i + 1) * cs_tok] : (uint16_t)0; - } + for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) + if (i + 1 < hist) keep[i] = hc ? hc[(size_t)(i + 1) * cs_tok] : (uint16_t)0; #pragma unroll - for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) { - if (i + 1 >= hist) break; - dst[(size_t)i * cs_tok] = keep[i]; - } + for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) + if (i + 1 < hist) dst[(size_t)i * cs_tok] = keep[i]; for (int32_t t = 0; t < slen && (long long)hist - 1 + t < state_len; ++t) dst[(size_t)(hist - 1 + (uint32_t)t) * cs_tok] = xc[(size_t)t * xld]; return; } #pragma unroll for (uint32_t i = 0; i < kPcMaxHist; ++i) { - if (i >= hist) break; - const int32_t src = slen - (int32_t)hist + (int32_t)i; - keep[i] = src >= 0 ? xc[(size_t)src * xld] - : (hc ? hc[(src + (int32_t)hist) * cs_tok] : (uint16_t)0); + if (i < hist) { + const int32_t src = slen - (int32_t)hist + (int32_t)i; + keep[i] = src >= 0 ? xc[(size_t)src * xld] + : (hc ? hc[(src + (int32_t)hist) * cs_tok] : (uint16_t)0); + } } #pragma unroll - for (uint32_t i = 0; i < kPcMaxHist; ++i) { - if (i >= hist) break; - dst[(size_t)i * cs_tok] = keep[i]; - } + for (uint32_t i = 0; i < kPcMaxHist; ++i) + if (i < hist) dst[(size_t)i * cs_tok] = keep[i]; } enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y }; +/* causal_conv1d's operands: ple_conv's without `resid`. */ +enum { CC_X = 0, CC_W, CC_CS, CC_CU, CC_CIDX, CC_HINIT, CC_NACC, CC_Y }; -} // namespace - -extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) { - const RadTensor* x = r4d_opt(a, PC_X); - const RadTensor* w = r4d_opt(a, PC_W); - const RadTensor* cs = r4d_opt(a, PC_CS); - const RadTensor* cu = r4d_opt(a, PC_CU); - const RadTensor* resid = r4d_opt(a, PC_RESID); - const RadTensor* cidx = r4d_opt(a, PC_CIDX); - const RadTensor* hini = r4d_opt(a, PC_HINIT); - const RadTensor* nacc = r4d_opt(a, PC_NACC); - const RadTensor* y = r4d_opt(a, PC_Y); +int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, const RadTensor* w, + const RadTensor* cs, const RadTensor* cu, const RadTensor* resid, + const RadTensor* cidx, const RadTensor* hini, const RadTensor* nacc, + const RadTensor* y) { if (!x || !w || !cu || !y) return R4D_NO(RAD_E_INVAL); if (x->dtype != RAD_BF16 || w->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); @@ -255,8 +249,8 @@ extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) { const uint32_t cb = (uint32_t)((n + kPcThreads - 1) / kPcThreads); const uint32_t tb = (uint32_t)((T + kPcBT - 1) / kPcBT); - hipLaunchKernelGGL(ple_conv_kernel, dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), 0, - (hipStream_t)s, + const auto kernel = silu ? ple_conv_kernel : ple_conv_kernel; + hipLaunchKernelGGL(kernel, dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), 0, (hipStream_t)s, (const uint16_t*)r4d_addr(x), (const uint16_t*)r4d_addr(w), have_cs ? (uint16_t*)r4d_addr(cs) : nullptr, (const int32_t*)r4d_addr(cu), @@ -269,3 +263,18 @@ extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) { cs_slot, cs_ch, cs_tok, state_len); return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } + +} // namespace + +extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) { + return conv_launch(a, s, true, r4d_opt(a, PC_X), r4d_opt(a, PC_W), r4d_opt(a, PC_CS), + r4d_opt(a, PC_CU), r4d_opt(a, PC_RESID), r4d_opt(a, PC_CIDX), + r4d_opt(a, PC_HINIT), r4d_opt(a, PC_NACC), r4d_opt(a, PC_Y)); +} + +extern "C" int r4d_rad_causal_conv1d(const RadArgs* a, RadStream s) { + if (r4d_geti_or(a, "dilation", 1) != 1) return R4D_NO(RAD_E_INVAL); + return conv_launch(a, s, false, r4d_opt(a, CC_X), r4d_opt(a, CC_W), r4d_opt(a, CC_CS), + r4d_opt(a, CC_CU), nullptr, r4d_opt(a, CC_CIDX), r4d_opt(a, CC_HINIT), + r4d_opt(a, CC_NACC), r4d_opt(a, CC_Y)); +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 2d227f5a..7e660ccc 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -111,6 +111,9 @@ int r4d_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa4_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*); +/* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */ +int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream); /* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body, * different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */ int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream); @@ -407,6 +410,7 @@ int r4d_rad_ngram_ids (const RadArgs*, RadStream); int r4d_rad_ngram_ids_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_ple_gate (const RadArgs*, RadStream); int r4d_rad_ple_conv (const RadArgs*, RadStream); +int r4d_rad_causal_conv1d (const RadArgs*, RadStream); int r4d_rad_cast (const RadArgs*, RadStream); int r4d_rad_gather_rows (const RadArgs*, RadStream); int r4d_rad_gather_rows_u8 (const RadArgs*, RadStream); @@ -440,6 +444,8 @@ int r4d_rad_rope (const RadArgs*, RadStream); int r4d_rad_layernorm (const RadArgs*, RadStream); int r4d_rad_layernorm_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_grid_embed (const RadArgs*, RadStream); +int r4d_rad_grid_embed_aa (const RadArgs*, RadStream); +int r4d_rad_grid_embed_aa_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_grid_embed_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream); int r4d_rad_gemm_nt_bias_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index c7cd6ce7..2366b5e1 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -102,21 +102,37 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( auto gain = [&](int i) -> float { return w_f32 ? ((const float*)w)[i] : __bfloat162float(((const __hip_bfloat16*)w)[i]); }; - auto normed = [&](int i, float inv) -> float { - const float v = __bfloat162float(in[i]); - // ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of - // this file: the reference stores the norm and RoPEs what it reads back. - return __bfloat162float(__float2bfloat16(v * inv * (gain(i) + wadd))); + // ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of + // this file: the reference stores the norm and RoPEs what it reads back. + auto normed = [&](float v, float g, float inv) -> float { + return __bfloat162float(__float2bfloat16(v * inv * (g + wadd))); }; + // EVERYTHING THE ROTATION READS IS LOADED HERE, ahead of the reduction, so it is in flight while + // the sum of squares goes round: this lane's element and gain, its partner's, and its cos and + // sin. None of it depends on the norm. The indices are clamped rather than the loads guarded -- + // a lane past the head reads its last element, a lane past the rotary range its own element and + // column 0 of the table (rot >= 2, so the table has one) -- and the values are used only where + // the guards below say. + const int tc = t < HD ? t : HD - 1; + const bool rl = t < rot, first = t < half; + const int pt = rl ? (first ? t + half : t - half) : tc; + const int ci = rl ? (first ? t : t - half) : 0; + const size_t co = (size_t)p * rot; + const float vt = __bfloat162float(in[tc]), gt = gain(tc); + const float vp = __bfloat162float(in[pt]), gp = gain(pt); + const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]); + const float s = cs_f32 ? csf[co + half + ci] : __bfloat162float(csb[co + half + ci]); + float ss = 0.0f; - if (t < HD) { const float v = __bfloat162float(in[t]); ss = v * v; } + if (t < HD) ss = vt * vt; // rmsnorm_bf16's block_sum, transcribed: the wave butterfly, then the wave partials summed in // ASCENDING index order. Both halves matter -- an accumulation over the same values in a - // different order breaks the bit-equality argument above. + // different order breaks the bit-equality argument above. The barrier orders the partials in LDS + // and nothing else, so the loads above stay in flight across it. ss = r4d_wave_sum(ss); if ((t & 31) == 0) lds[t >> 5] = ss; - __syncthreads(); + lds_barrier(); float sum = 0.0f; #pragma unroll for (int wv = 0; wv < THR / 32; ++wv) sum += lds[wv]; @@ -124,15 +140,9 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( float res = 0.0f; if (t < HD) { - res = normed(t, inv); - if (t < rot) { - const bool first = t < half; - const int pt = first ? t + half : t - half; - const int ci = first ? t : t - half; - const size_t co = (size_t)p * rot; - const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]); - const float s = cs_f32 ? csf[co + half + ci] : __bfloat162float(csb[co + half + ci]); - const float xp = normed(pt, inv); + res = normed(vt, gt, inv); + if (rl) { + const float xp = normed(vp, gp, inv); res = first ? (res * c - xp * s) : (xp * s + res * c); } } diff --git a/libr4d/r4d_qsa_score_bf16.hip b/libr4d/r4d_qsa_score_bf16.hip index 6815a53f..96b47c84 100644 --- a/libr4d/r4d_qsa_score_bf16.hip +++ b/libr4d/r4d_qsa_score_bf16.hip @@ -357,16 +357,20 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel( const int bend = wb0 + tpw * 16 < nbs ? wb0 + tpw * 16 : nbs; const int32_t* tab = bt + (size_t)seq * bt_ld; + /* THE NEXT TILE'S PAGE ID IS READ WHILE THIS TILE'S KEY IS OUT: the key's address + * depends on it, so read in its own iteration it is a second load latency every tile. */ + int pg_next = wb0 + col < bend ? tab[wb0 + col] : -1; for (int b0 = wb0; b0 < bend; b0 += 16) { /* The A operand: block `b0 + col`'s key, one page-id read and eight fragment loads. A * block past the end or without a page reads page 0's key, which always exists, and * is overwritten or skipped at the store. */ const int b = b0 + col; - const int pg = b < bend ? tab[b] : -1; + const int pg = pg_next; const unsigned short* kp = bk + (size_t)(pg >= 0 ? pg : 0) * bk_ld + 4 * half; v8bf kf[kMxKS]; #pragma unroll for (int ks = 0; ks < kMxKS; ++ks) kf[ks] = fragP(kp + ks * 16); + pg_next = b + 16 < bend ? tab[b + 16] : -1; /* Which of the tile's sixteen blocks have no page: lanes 0-15 each read one. */ const unsigned absent = (unsigned)__ballot(pg < 0) & 0xFFFFu; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4d13d05a..cc1791c1 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1810,6 +1810,23 @@ static const RadOperandSpec oPleConv[] = { { "num_accepted", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; +/* ple_conv's operands without `resid`, its parameters without `dilation`. */ +static const RadParamSpec pCausalConv[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + { "width", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oCausalConv[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "conv_state", RAD_OPD_INOUT, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "cache_idx", RAD_OPD_IN, 1 }, + { "has_init", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pNgramIds[] = { { "M", RAD_P_INT, RAD_REQUIRED }, @@ -2015,6 +2032,12 @@ static const RadOpSchema kSchemas[] = { "x += a side x side table resampled bilinearly (corners aligned, taps clamped) to each " "row's grid; coord is [4, M] row, column, height, width. The taps are summed in f32 " "and rounded before the add."), + SCHEMA("grid_embed_aa", pGridEmbed, oGridEmbed, + "x += the side x side table resampled as torch's F.interpolate(bilinear, " + "align_corners=False, antialias=True) resamples it to the row's grid -- SigLIP2's " + "position embedding: per axis a triangle filter on half-pixel centres, widened by the " + "scale when shrinking, its in-table taps normalised. Separable, f32, rounded once " + "before the add; coordinates clamp into their grid."), SCHEMA("gemm_nt_bias", pGemmBias, oGemmBias, "y = res + act(a @ b^T + bias), rounded to bf16 after the biased product, after the " "activation and after the residual -- the unfused chain's three tensors."), @@ -2051,6 +2074,10 @@ static const RadOpSchema kSchemas[] = { "Absent, every token commits: the read is at offset zero and the last " "(width-1)*dilation inputs land at offset zero, which is the prefill chunk. " "`resid` absent drops the add and leaves the plain convolution."), + SCHEMA("causal_conv1d", pCausalConv, oCausalConv, + "y[t] = sum_j w[c][j] * x[t - (width-1-j)], ple_conv at dilation one with no " + "activation and no residual: LFM2's short convolution, whose gates the caller applies. " + "The window, `has_init`, `cache_idx` and `num_accepted` are ple_conv's."), SCHEMA("ngram_ids", pNgramIds, oNgramIds, "ids[m][h] = remainder(hash of the n-gram ending at m, vocab_sizes[h]) + offsets[h]. " "Heads are `ngram - 1` equal blocks, block b using the (b+2)-gram. A shift that would " @@ -2469,6 +2496,17 @@ static const RadConstraint cAttnDecodeH256G4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* The prefill pair at head_dim 64 (LFM2: 32 query heads over 8). There is no decode row at this + * width -- the split-KV kernel's lanes hold 128 or 256 columns -- so the query-tiled kernel serves + * every q_len. */ +static const RadConstraint cAttnPrefillH64G4Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH64G4Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two * ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is @@ -3402,6 +3440,9 @@ static const RadConstraint cPleGate[] = { C_IN("dtype", "bf16"), C_GE("n", 1), static const RadConstraint cPleConv[] = { C_IN("dtype", "bf16"), C_GE("width", 1), C_LE("width", 5), C_GE("dilation", 1), C_LE("dilation", 4) }; +/* The same kernel undilated: the window is width-1 deep, and the taps are held in registers. */ +static const RadConstraint cCausalConv[] = { C_IN("dtype", "bf16"), C_GE("width", 2), + C_LE("width", 8) }; static const RadConstraint cKvStore[] = { C_GE("block_size", 1), C_IN("kv_dtype", "bf16") }; static const RadConstraint cKvStoreFp8[] = { C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3") }; static const RadConstraint cRopeRow[] = { C_GE("head_dim", 1), @@ -3491,6 +3532,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_ple_conv, nullptr, nullptr, nullptr, nullptr, nullptr }, +{ "causal_conv1d_bf16", "causal_conv1d", "conv", + "depthwise causal conv with no activation (ple_conv's kernel); one thread a channel", + "width 2 to 8, undilated", + "bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cCausalConv), NOTUNE, + nullptr, nullptr, r4d_rad_causal_conv1d, nullptr, nullptr, nullptr, + nullptr, nullptr }, + { "ngram_ids_i32", "ngram_ids", "vocab", "PLE's hashed n-gram row ids, one thread a token", "any heads and n-gram size up to 8; heads must divide into ngram-1 equal blocks", @@ -3684,6 +3734,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_grid_embed, nullptr, nullptr, nullptr, r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_describe }, +{ "grid_embed_aa_bf16", "grid_embed_aa", "elem", + "a learned position grid resampled as torch's antialiased bilinear and added in (SigLIP2)", + "side up to 1024, any n; coord [4, M] dense; one workgroup a row, its taps in LDS", + "bf16 x, bf16 or f32 table, i32 coord, f32 taps", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGridEmbed), NOTUNE, + nullptr, nullptr, r4d_rad_grid_embed_aa, nullptr, nullptr, nullptr, + r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_aa_describe }, + { "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm", "biased GEMM C = res + act(A @ W^T + bias): eight waves over an LDS-staged 64-deep K tile, " "the K tail staged as zeros, the activation and residual in the store", @@ -4097,6 +4156,24 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h64_gqa4_fp8kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 64, 4 queries per kv head, paged block 16, varlen", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH64G4Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h64_gqa4_bf16kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 64, 4 queries per kv head, paged block 16, varlen", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH64G4Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 12 queries per kv head, paged block 4, varlen", @@ -5697,6 +5774,23 @@ extern "C" int rad_kernel_concurrent(int i) { return 1; } +/* WHICH ROWS ARE COLLECTIVES (rad_abi.h): every row whose instance its init builds with the + * exchange buffers, peer flags and handshake of the all-reduce family -- the standalone all-reduces + * and gathers, and the norms and hc writes with one folded in -- and each one's `_host` twin, which + * exchanges through the pinned mailbox instead. Keyed on the init because that is what makes a row + * one: a kernel that reduces across ranks cannot run without the instance only these build. */ +extern "C" int rad_kernel_collective(int i) { + const RadKernelInfo* k = rad_kernel_at(i); + if (!k || !k->init) return 0; + const bool coll = host_init_for(k->init) != nullptr || k->init == r4d_rad_ar_host_init || + k->init == r4d_rad_ar_ln_host_init || k->init == r4d_rad_ar_hc_wide_host_init; + if (!coll) return 0; + /* The two-rank hc writes end the engine's link hold themselves, through `link_gate`, as soon as + * the peer's push has landed over P2P (RAD_LINK_ENDED); through the host mailbox they leave it + * to the engine. */ + return (k->launch == r4d_rad_ar_hc_write || k->launch == r4d_rad_ar_gather_hc_write) ? 2 : 1; +} + /* ------------------------------------------------------------------------ tuned config access * * THE CHOSEN POINT ARRIVES AS ORDINARY PARAMETERS. The core resolved one instantiation of this diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2cf5af7c..8bfe30d7 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -412,6 +412,9 @@ static void cross_check(const Plugin& pl) { } /* ================================================================== the device phase */ +/* --cold MIB: bytes read through the caches before every timed launch; see st_time_us. */ +static int64_t g_cold = 0; + #ifdef RAD_HAVE_HIP /* EVERY hipError_t IN THIS FILE IS CHECKED, and that is not pedantry about a `nodiscard`. A @@ -465,6 +468,63 @@ static void* dalloc(size_t bytes) { return p; } +/* ---- THE TIMED WINDOW, WARM OR COLD (--cold MIB). + * + * Warm, a perf mode launches `iters` times back to back on one set of operands, so a weight that + * fits in L2 (8 MiB here) or the last-level cache (64 MiB) is read from cache after the first + * launch: --perfmoe's whole expert set times at ten thousand GB/s "of weight", sixteen times what + * the part's DRAM delivers. The engine streams its weights cold every step, and a change in how a + * kernel waits on memory can look free warm and cost microseconds there. + * + * Cold, every launch is preceded by a read of g_cold bytes through the hierarchy and timed alone + * between two events, and the median launch is the figure. The read is device copies into one + * kColdChunk destination: copied in full, the span would leave that many dirty lines for the + * timed launch to write back, which inflates exactly the bandwidth-bound kernels this mode is for. + * The flush buffers are allocated outside dalloc because dfree_all runs between shapes. */ +constexpr int64_t kColdChunk = 4ll << 20; + +template +static double st_time_us(F&& launch, int iters, hipStream_t s) { + if (iters <= 0) return 0.0; + if (g_cold <= 0) { + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + st_ev_record(e0, s); + for (int i = 0; i < iters; ++i) launch(i); + st_ev_record(e1, s); + st_ev_sync(e1); + float ms = 0.0f; + st_ev_elapsed(&ms, e0, e1); + st_ev_destroy(e0); st_ev_destroy(e1); + return (double)ms * 1000.0 / iters; + } + static void* src = nullptr; + static void* dst = nullptr; + if (!src && (hipMalloc(&src, (size_t)g_cold) != hipSuccess || + hipMalloc(&dst, (size_t)std::min(g_cold, kColdChunk)) != hipSuccess)) { + std::printf("--cold: no %lld MiB of device memory for the flush\n", + (long long)(g_cold >> 20)); + std::exit(1); + } + std::vector ev(2 * (size_t)iters); + for (hipEvent_t& e : ev) st_ev_create(&e); + for (int i = 0; i < iters; ++i) { + for (int64_t off = 0; off < g_cold; off += kColdChunk) + hip_ck(hipMemcpyAsync(dst, (const char*)src + off, + (size_t)std::min(kColdChunk, g_cold - off), + hipMemcpyDeviceToDevice, s), "hipMemcpyAsync", __LINE__); + st_ev_record(ev[2 * (size_t)i], s); + launch(i); + st_ev_record(ev[2 * (size_t)i + 1], s); + } + st_ev_sync(ev.back()); + std::vector t((size_t)iters); + for (int i = 0; i < iters; ++i) st_ev_elapsed(&t[(size_t)i], ev[2 * (size_t)i], ev[2 * (size_t)i + 1]); + for (hipEvent_t e : ev) st_ev_destroy(e); + std::sort(t.begin(), t.end()); + return (double)t[t.size() / 2] * 1000.0; +} + static void dfree_all() { for (void* p : g_allocs) st_free(p); g_allocs.clear(); @@ -5328,21 +5388,10 @@ static void perf_row(const Plugin& pl, const char* name, std::vector return; } - hipEvent_t e0, e1; - st_ev_create(&e0); - st_ev_create(&e1); - st_ev_record(e0, nullptr); - for (int i = 0; i < iters; ++i) { + const double us = st_time_us([&](int i) { ts[widx].data = (uint8_t*)wbase + (size_t)(i % copies) * wbytes; r->launch(&a, nullptr); - } - st_ev_record(e1, nullptr); - st_ev_sync(e1); - float ms = 0; - st_ev_elapsed(&ms, e0, e1); - st_ev_destroy(e0); - st_ev_destroy(e1); - const double us = (double)ms * 1000.0 / iters; + }, iters, nullptr); std::printf(" %-22s %8.1f us %6.1f GB/s\n", name, us, bytes / (us * 1e3)); } @@ -5557,16 +5606,7 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { } st_ev_destroy(w0); st_ev_destroy(w1); } - hipEvent_t e0, e1; - st_ev_create(&e0); st_ev_create(&e1); - st_ev_record(e0, nullptr); - for (int i = 0; i < iters; ++i) r->launch(&a, nullptr); - st_ev_record(e1, nullptr); - st_ev_sync(e1); - float ms = 0; - st_ev_elapsed(&ms, e0, e1); - st_ev_destroy(e0); st_ev_destroy(e1); - const double us = (double)ms * 1000.0 / iters; + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); std::printf(" %-30s %9.2f us %6.1f GB/s\n", name, us, bytes / (us * 1e3)); }; @@ -5869,16 +5909,7 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, } st_ev_destroy(w0); st_ev_destroy(w1); } - hipEvent_t e0, e1; - st_ev_create(&e0); st_ev_create(&e1); - st_ev_record(e0, nullptr); - for (int i = 0; i < iters; ++i) r->launch(&a, nullptr); - st_ev_record(e1, nullptr); - st_ev_sync(e1); - float ms = 0.0f; - st_ev_elapsed(&ms, e0, e1); - st_ev_destroy(e0); st_ev_destroy(e1); - const double us = (double)ms * 1000.0 / iters; + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); std::string same = ""; if (f == 0) { @@ -6193,16 +6224,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool st_ev_elapsed(&wms, w0, w1); } st_ev_destroy(w0); st_ev_destroy(w1); - hipEvent_t e0, e1; - st_ev_create(&e0); st_ev_create(&e1); - st_ev_record(e0, hs); - for (int i = 0; i < iters; ++i) r->launch(&a, rst); - st_ev_record(e1, hs); - st_ev_sync(e1); - float ms = 0.0f; - st_ev_elapsed(&ms, e0, e1); - st_ev_destroy(e0); st_ev_destroy(e1); - const double us = (double)ms * 1000.0 / iters; + const double us = st_time_us([&](int) { r->launch(&a, rst); }, iters, hs); const double flop = 2.0 * (double)M * (double)HN * (double)(2 * lr + hc); std::printf("%s at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + " "rotated), %s: %.1f us a call, %.1f TFLOP/s\n", rn, (long long)M, @@ -10280,18 +10302,9 @@ static void moe16_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int if (pl.pin_moe) pl.pin_moe(0); continue; } - hipEvent_t e0, e1; - st_ev_create(&e0); st_ev_create(&e1); for (int i = 0; i < 3; ++i) r->launch(&a, nullptr); - st_ev_record(e0, nullptr); - for (int i = 0; i < iters; ++i) r->launch(&a, nullptr); - st_ev_record(e1, nullptr); - st_ev_sync(e1); - float ms = 0.0f; - st_ev_elapsed(&ms, e0, e1); - st_ev_destroy(e0); st_ev_destroy(e1); + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); if (pl.pin_moe) pl.pin_moe(0); - const double us = (double)ms * 1000.0 / iters; st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); std::string same; if (f == 0) first = got; @@ -11246,6 +11259,8 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0); attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); + attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); + attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); attn_gq_fold_case(pl, 3, false); attn_gq_fold_case(pl, 24, false); attn_gq_fold_case(pl, 3, true); @@ -12934,6 +12949,11 @@ static void usage(void) { " prefill-tile form (PF2 from M=512) compared byte for byte and timed\n" " as one op each;\n" " run it under libr4d/isa/trace.sh for its launches.\n" + " --cold MIB: with a --perf mode, time cold: read MIB through the caches before\n" + " every timed launch (256 empties this card's L2 and last level) and\n" + " time each launch alone, the median reported. Warm, a weight under\n" + " 64 MiB is read from cache after the first launch; the engine reads\n" + " its weights cold.\n" " --perfmoe M [iters] [experts] [top_k] [pooled%%]: the routed-expert w4 GEMM,\n" " both projections at rank 0's tp2 width split, over a skewed routing of\n" " an M-token chunk (512 experts, top 10 by default); every form, each\n" @@ -13016,6 +13036,9 @@ int main(int argc, char** argv) { qsa_ctx = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--cold")) { + if (i + 1 >= argc) { usage(); return 2; } + g_cold = std::strtoll(argv[++i], nullptr, 0) << 20; } else if (!std::strcmp(argv[i], "--perfmoe")) { /* The routed-expert GEMM at a prefill chunk of M tokens, every prefill form. */ if (i + 1 >= argc) { usage(); return 2; } diff --git a/libr4d/r4d_vit_bf16.hip b/libr4d/r4d_vit_bf16.hip index a2573bc4..3b96d900 100644 --- a/libr4d/r4d_vit_bf16.hip +++ b/libr4d/r4d_vit_bf16.hip @@ -120,6 +120,58 @@ __global__ __launch_bounds__(kThr) void grid_embed_kernel( } } +// ---------------------------------------------------------------------------- grid_embed_aa +// ref_grid_embed_aa: torch's antialiased half-pixel bilinear resample (SigLIP2's position table). +// Thread 0 lays out the row's two tap lists -- at most `side` each -- in LDS; every thread then +// takes channels, summing the taps in libref's order (a row of columns, then the rows), and the sum +// is rounded once before the add. +__device__ __forceinline__ int aa_taps(int at, int size, int side, float* w, int* lo) { + size = size < 1 ? 1 : size; + at = at < 0 ? 0 : (at >= size ? size - 1 : at); + const float scale = (float)side / (float)size; + const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support; + const float center = scale * ((float)at + 0.5f); + int a = (int)(center - support + 0.5f), b = (int)(center + support + 0.5f); + a = a < 0 ? 0 : a; + b = b > side ? side : b; + float total = 0.0f; + for (int j = a; j < b; ++j) { + const float d = fabsf(((float)j - center + 0.5f) * inv); + w[j - a] = d < 1.0f ? 1.0f - d : 0.0f; + total += w[j - a]; + } + for (int j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f; + *lo = a; + return b > a ? b - a : 0; +} + +template +__global__ __launch_bounds__(kThr) void grid_embed_aa_kernel( + unsigned short* __restrict__ x, const void* __restrict__ tab, const int32_t* __restrict__ crd, + uint32_t n, int side, uint32_t x_ld, uint32_t plane) { + extern __shared__ float aa_w[]; // [2 * side]: the row taps, then the column taps + __shared__ int aa_span[4]; // h0, nh, w0, nw + const uint32_t m = blockIdx.x; + if (threadIdx.x == 0) { + aa_span[1] = aa_taps(crd[m], crd[2 * plane + m], side, aa_w, &aa_span[0]); + aa_span[3] = aa_taps(crd[plane + m], crd[3 * plane + m], side, aa_w + side, &aa_span[2]); + } + __syncthreads(); + const int h0 = aa_span[0], nh = aa_span[1], w0 = aa_span[2], nw = aa_span[3]; + unsigned short* __restrict__ xr = x + (size_t)m * x_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThr) { + float acc = 0.0f; + for (int y = 0; y < nh; ++y) { + float row = 0.0f; + for (int c = 0; c < nw; ++c) + row += ldw(tab, (uint32_t)((h0 + y) * side + w0 + c) * n + i) * aa_w[side + c]; + acc += row * aa_w[y]; + } + const float pe = bf2f(f32_to_bf16(acc)); + xr[i] = f32_to_bf16(bf2f(xr[i]) + pe); + } +} + // ---------------------------------------------------------------------------- gemm_nt_bias #define VB_BK 64 #define VB_PITCH (VB_BK + 8) // 144-byte LDS rows: gemm_bf16_nt_tiled's bank argument @@ -176,29 +228,29 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel( // THE K TAIL IS STAGED AS ZEROS: K is a multiple of 8, so a 16-byte chunk is wholly inside K // or wholly past it, and a zero chunk contributes exactly nothing to the dot products. - const uint4 zero = make_uint4(0, 0, 0, 0); - uint4 ra[AL], rw[WL]; + const r4d_u32x4 zero = (r4d_u32x4)(0u); + r4d_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch #pragma unroll - for (int i = 0; i < AL; ++i) ra[i] = ae[i] < K ? *(const uint4*)(A + aoff[i]) : zero; + for (int i = 0; i < AL; ++i) ra[i] = ae[i] < K ? *(const r4d_u32x4*)(A + aoff[i]) : zero; #pragma unroll - for (int i = 0; i < WL; ++i) rw[i] = we[i] < K ? *(const uint4*)(W + woff[i]) : zero; + for (int i = 0; i < WL; ++i) rw[i] = we[i] < K ? *(const r4d_u32x4*)(W + woff[i]) : zero; const int nk = (K + VB_BK - 1) / VB_BK; for (int kt = 0; kt < nk; ++kt) { __syncthreads(); #pragma unroll - for (int i = 0; i < AL; ++i) *(uint4*)adst[i] = ra[i]; + for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i]; #pragma unroll - for (int i = 0; i < WL; ++i) *(uint4*)wdst[i] = rw[i]; + for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i]; __syncthreads(); if (kt + 1 < nk) { const int k1 = (kt + 1) * VB_BK; #pragma unroll for (int i = 0; i < AL; ++i) - ra[i] = k1 + ae[i] < K ? *(const uint4*)(A + aoff[i] + k1) : zero; + ra[i] = k1 + ae[i] < K ? *(const r4d_u32x4*)(A + aoff[i] + k1) : zero; #pragma unroll for (int i = 0; i < WL; ++i) - rw[i] = k1 + we[i] < K ? *(const uint4*)(W + woff[i] + k1) : zero; + rw[i] = k1 + we[i] < K ? *(const r4d_u32x4*)(W + woff[i] + k1) : zero; } #pragma unroll for (int s = 0; s < VB_BK / 16; ++s) { @@ -307,6 +359,37 @@ static int rad_grid_embed_body(const RadArgs* a, const R4dSink& sk) { } R4D_ENTRY(r4d_rad_grid_embed, rad_grid_embed_body) +/* grid_embed_aa: grid_embed's operands and checks, the antialiased resample. */ +static int rad_grid_embed_aa_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GE_X); + const RadTensor* tab = r4d_opt(a, GE_TAB); + const RadTensor* crd = r4d_opt(a, GE_CRD); + if (!x || !tab || !crd) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || crd->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (tab->dtype != RAD_BF16 && tab->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(tab)) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_geti_or(a, "n", r4d_dim(tab, (int)tab->rank - 1)); + const long long side = r4d_geti_or(a, "side", 0); + if (n <= 0 || side <= 0 || side > 1024 || r4d_numel(tab) < side * side * n) + return R4D_NO(RAD_E_SHAPE); + long long M = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + if (x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M || !r4d_contig(crd)) + return R4D_NO(RAD_E_SHAPE); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + const uint32_t plane = (uint32_t)crd->shape[1]; + const size_t lds = (size_t)(2 * side) * sizeof(float); + if (tab->dtype == RAD_F32) + return R4D_EMIT(sk, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, + (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), + (uint32_t)n, (int)side, (uint32_t)x_ld, plane); + return R4D_EMIT(sk, grid_embed_aa_kernel, dim3((uint32_t)M), dim3(kThr), lds, + (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), + (uint32_t)n, (int)side, (uint32_t)x_ld, plane); +} +R4D_ENTRY(r4d_rad_grid_embed_aa, rad_grid_embed_aa_body) + /* ------------------------------------------------------------------ gemm_nt_bias */ enum { GB_A = 0, GB_W, GB_BIAS, GB_RES, GB_Y }; diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 28bcc217..4b5d2c3c 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -8,6 +8,9 @@ #include "ref_common.h" #include "ref_ops.h" +#include +#include + using namespace ref; /* Rows of a tensor read as [rows, n]. `n` is a declared parameter and the row count is whatever @@ -188,6 +191,68 @@ int ref_grid_embed(const RadArgs* a, RadStream) { return RAD_OK; } +/* grid_embed_aa: the table resampled as torch's F.interpolate(mode="bilinear", align_corners=False, + * antialias=True) does it -- SigLIP2's position embedding. Per axis a triangle filter on half-pixel + * centres, widened by the scale when shrinking, its taps inside the table normalised to sum to one. + * Separable, f32 throughout, rounded once before the add. A coordinate outside its grid is clamped + * into it, so every input is defined. */ +static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) { + if (size < 1) size = 1; + at = at < 0 ? 0 : (at >= size ? size - 1 : at); + const float scale = (float)side / (float)size; + const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support; + const float center = scale * ((float)at + 0.5f); + int64_t a = (int64_t)(center - support + 0.5f), b = (int64_t)(center + support + 0.5f); + if (a < 0) a = 0; + if (b > side) b = side; + float total = 0.0f; + for (int64_t j = a; j < b; ++j) { + const float d = std::fabs(((float)j - center + 0.5f) * inv); + w[j - a] = d < 1.0f ? 1.0f - d : 0.0f; + total += w[j - a]; + } + for (int64_t j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f; + *lo = a; + *cnt = b > a ? b - a : 0; +} + +int ref_grid_embed_aa(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; + const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0); + const int64_t side = p_int(a, "side", 0); + if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows) + return RAD_E_SHAPE; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + const int64_t ts = laststride(tab); + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + int64_t g[4]; + for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms); + std::vector wh((size_t)side), ww((size_t)side); + int64_t h0 = 0, nh = 0, w0 = 0, nw = 0; + aa_taps(g[0], g[2], side, wh.data(), &h0, &nh); + aa_taps(g[1], g[3], side, ww.data(), &w0, &nw); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int64_t y = 0; y < nh; ++y) { + float row = 0.0f; + for (int64_t c = 0; c < nw; ++c) + row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) * + ww[(size_t)c]; + acc += row * wh[(size_t)y]; + } + const float pe = round_to(x->dtype, acc); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ add / mul */ /* Elementwise over the output's extent. `b` may carry one row instead of all of them, so a bias * add is this op rather than a second one: an operand with exactly `n` elements against an output diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 276f0209..8e5398d3 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -70,6 +70,7 @@ int ref_hc_write (const RadArgs*, RadStream); int ref_mtp_enter (const RadArgs*, RadStream); int ref_layernorm (const RadArgs*, RadStream); int ref_grid_embed (const RadArgs*, RadStream); +int ref_grid_embed_aa (const RadArgs*, RadStream); int ref_add (const RadArgs*, RadStream); int ref_mul (const RadArgs*, RadStream); int ref_silu_mul (const RadArgs*, RadStream); @@ -92,6 +93,7 @@ int ref_scatter_rows (const RadArgs*, RadStream); int ref_ngram_ids (const RadArgs*, RadStream); int ref_ple_gate (const RadArgs*, RadStream); int ref_ple_conv (const RadArgs*, RadStream); +int ref_causal_conv1d (const RadArgs*, RadStream); int ref_cast (const RadArgs*, RadStream); int ref_softmax (const RadArgs*, RadStream); @@ -199,6 +201,7 @@ REF_SHAPE_FN(ref_hc_write); REF_SHAPE_FN(ref_mtp_enter); REF_SHAPE_FN(ref_layernorm); REF_SHAPE_FN(ref_grid_embed); +REF_SHAPE_FN(ref_grid_embed_aa); REF_SHAPE_FN(ref_add); REF_SHAPE_FN(ref_mul); REF_SHAPE_FN(ref_silu_mul); @@ -221,6 +224,7 @@ REF_SHAPE_FN(ref_scatter_rows); REF_SHAPE_FN(ref_ngram_ids); REF_SHAPE_FN(ref_ple_gate); REF_SHAPE_FN(ref_ple_conv); +REF_SHAPE_FN(ref_causal_conv1d); REF_SHAPE_FN(ref_cast); REF_SHAPE_FN(ref_softmax); diff --git a/libref/ref_ple.cpp b/libref/ref_ple.cpp index 879a4f0c..f564adaf 100644 --- a/libref/ref_ple.cpp +++ b/libref/ref_ple.cpp @@ -219,19 +219,17 @@ int ref_ple_gate(const RadArgs* a, RadStream) { * several would hand a step that accepted only the first of them a history ending at a rejected * draft, and one that accepted two a slot nothing wrote. */ -int ref_ple_conv(const RadArgs* a, RadStream) { - /* NINE positions, four of them optional, so the count is checked and the optionals are tested - * one by one -- `have()` would refuse the op for an absent operand that is allowed to be. */ - if (a->n_t < 9) return RAD_E_INVAL; - const RadTensor* x = t_in(a, 0); - const RadTensor* w = t_in(a, 1); - const RadTensor* cs = t_in(a, 2); - const RadTensor* cu = t_in(a, 3); - const RadTensor* resid = t_in(a, 4); /* optional */ - const RadTensor* sidx = t_in(a, 5); /* optional */ - const RadTensor* hini = t_in(a, 6); /* optional */ - const RadTensor* nacc = t_in(a, 7); /* optional */ - const RadTensor* y = t_in(a, 8); +/* THE DEPTHWISE CAUSAL CONVOLUTION AND ITS ROLLING WINDOW, shared by `ple_conv` (dilated, silu, + * an optional residual) and `causal_conv1d` (LFM2's short convolution: undilated, no activation, + * no residual). One body, so the two ops cannot disagree about the window's layout. */ +struct ConvArgs { + const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; + bool silu; +}; + +static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { + const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid; + const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y; if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL; const int64_t n = p_int(a, "n", 0); @@ -303,7 +301,7 @@ int ref_ple_conv(const RadArgs* a, RadStream) { acc += v * ldt(w, c * wrow + j * wcol); } const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f; - stt(y, (bos + t) * yrow + c * ycol, r + act_silu(acc)); + stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? act_silu(acc) : acc)); } } @@ -345,3 +343,19 @@ int ref_ple_conv(const RadArgs* a, RadStream) { } return RAD_OK; } + +int ref_ple_conv(const RadArgs* a, RadStream) { + /* NINE positions, four of them optional, so the count is checked and the optionals are tested + * one by one -- `have()` would refuse the op for an absent operand that is allowed to be. */ + if (a->n_t < 9) return RAD_E_INVAL; + return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), t_in(a, 4), + t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 8), true }); +} + +/* ple_conv's operands without `resid`, at dilation one and with no activation. */ +int ref_causal_conv1d(const RadArgs* a, RadStream) { + if (a->n_t < 8) return RAD_E_INVAL; + if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL; + return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), nullptr, + t_in(a, 4), t_in(a, 5), t_in(a, 6), t_in(a, 7), false }); +} diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index abc3ba3c..cafc9524 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -124,6 +124,11 @@ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"), OPD_O("num_accepted"), OUT("y") }; +static const RadParamSpec pCausalConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), + P_STR("dtype") }; +static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), + OPD_O("cache_idx"), OPD_O("has_init"), + OPD_O("num_accepted"), OUT("y") }; static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; @@ -655,6 +660,11 @@ static const RadOpSchema kSchemas[] = { "`coord` is [4, M] -- row, column, grid height, grid width -- and the position is sampled " "bilinearly with the grid's corners on the table's corners (align_corners), edge taps clamped. " "The taps are summed in f32 and rounded to x's dtype, then added to x and rounded again." }, +{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), + "x += the side x side table resampled as torch's F.interpolate(bilinear, align_corners=False, " + "antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a " + "triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps " + "normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." }, { "add", ARR(pMnD), ARR(oBinary), "y = a + b. An operand carrying exactly n elements against a taller output broadcasts along " "rows; nothing else broadcasts." }, @@ -723,6 +733,12 @@ static const RadOpSchema kSchemas[] = { "(width-1)*dilation - 1 slots plus one a token. Absent, every token commits: the read is at " "offset zero and the last (width-1)*dilation inputs land at offset zero, which is the prefill " "chunk. `resid` absent drops the add and leaves the plain convolution." }, +{ "causal_conv1d", ARR(pCausalConv), ARR(oCausalConv), + "y[t] = sum_j w[c][j] * x[t - (width-1-j)], a DEPTHWISE CAUSAL convolution with no activation " + "and no residual (LFM2's short convolution, whose gates the caller applies). The state, " + "`has_init`, `cache_idx` and `num_accepted` are ple_conv's at dilation one: a window of width-1 " + "values, read at `num_accepted - 1` and rewritten shifted by one with every input of a decode " + "step behind it, or left as the chunk's last width-1 inputs when `num_accepted` is absent." }, { "ngram_ids", ARR(pNgramIds), ARR(oNgramIds), "ids[m][h] = remainder(hash of the n-gram ending at m, vocab_sizes[h]) + offsets[h], where " "hash = t0*mult[0] ^ t1*mult[1] ^ ... over as many shifted tokens as head h's block needs -- " @@ -1094,6 +1110,9 @@ SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT ref_layernorm), SIMPLE("ref_grid_embed", "grid_embed", "elem", "bilinear resample of a learned position grid, added in", DT_FLOAT, ref_grid_embed), +SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem", + "antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT, + ref_grid_embed_aa), SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add), SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul), SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, @@ -1126,6 +1145,8 @@ SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot DT_FLOAT, ref_ple_gate), SIMPLE("ref_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add", DT_FLOAT, ref_ple_conv), +SIMPLE("ref_causal_conv1d", "causal_conv1d", "conv", "depthwise causal conv, no activation", + DT_FLOAT, ref_causal_conv1d), SIMPLE("ref_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, ref_gather_rows), SIMPLE("ref_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_ANY, ref_scatter_rows), SIMPLE("ref_cast", "cast", "elem", "dtype conversion", DT_ANY, ref_cast), @@ -1305,3 +1326,9 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { if (i < 0 || i >= rad_kernel_count()) return nullptr; return &kKernels[i]; } +/* The rows that join the other ranks (ref_collective.cpp), said through the ABI + * (RadKernelCollectiveFn) so the gather counts as one as well as the all-reduce. */ +extern "C" int rad_kernel_collective(int i) { + const RadKernelInfo* k = rad_kernel_at(i); + return k && k->init == ref_collective_init; +} diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 684aa57a..d84261cc 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -434,6 +434,18 @@ int ref_grid_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("grid_embed", operand, out); } +/* grid_embed's operands; the coordinates are drawn over the table's side, as there. */ +int ref_grid_embed_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), side = gi(p, n_p, "side", 0); + if (M <= 0 || n <= 0 || side <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x, INOUT */ + o.t(D, { side * side, n }); /* table */ + o.t_idx({ 4, M }, side, -1, 0); + return o.finish("grid_embed_aa", operand, out); +} + int ref_layernorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -721,6 +733,24 @@ int ref_ple_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("ple_conv", operand, out); } +/* ple_conv's description without `resid` and at dilation one. */ +int ref_causal_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), wid = gi(p, n_p, "width", 0); + if (M <= 0 || n <= 0 || wid <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = 1, depth = wid - 2 + M; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n, wid }); /* w */ + o.t(D, { S, n, depth }); /* conv_state, INOUT */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ + o.t_idx({ S }, S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx */ + o.t_idx({ S }, 0, 1, 0); /* has_init: warm */ + o.t_idx({ S }, 0, M, 0); /* num_accepted: read at M - 1 */ + o.t(D, { M, n }); /* y */ + return o.finish("causal_conv1d", operand, out); +} + int ref_ngram_ids_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t heads = gi(p, n_p, "heads", 0); diff --git a/scripts/cardclock.py b/scripts/cardclock.py index d6f9b177..cec9c596 100755 --- a/scripts/cardclock.py +++ b/scripts/cardclock.py @@ -39,8 +39,8 @@ # particular must be proven under a SUSTAINED hot load, not a short test: an offset that passes a # minute-long selftest can wedge a card twenty minutes into real traffic once it runs at 90 C. # -# Needs Linux amdgpu with a gpu_metrics v1.3 table (RDNA3 / RDNA4 discrete cards); any other layout -# is refused rather than misread. +# Needs Linux amdgpu with a gpu_metrics v1.3 table (RDNA3 / RDNA4 discrete cards); a card with any +# other layout is skipped rather than misread. import argparse, glob, json, os, random, re, statistics as st, struct, sys, threading, time, urllib.request BITS = {0: "PPT0", 1: "PPT1", 2: "PPT2", 3: "PPT3", 4: "SPL", 5: "FPPT", 6: "SPPT", 7: "SPPT_APU", @@ -107,8 +107,18 @@ def find_cards(): for dev in sorted(glob.glob("/sys/class/drm/card*/device")): if not re.fullmatch(r"card\d+", dev.split("/")[-2]): continue if rd(dev + "/vendor") != "0x1002" or not os.path.exists(dev + "/gpu_metrics"): continue - c = Card(dev); out.setdefault(c.bdf, c) - if not out: raise SystemExit("no AMD card with a gpu_metrics table under /sys/class/drm") + c = Card(dev) + # ANOTHER LAYOUT IS ANOTHER KIND OF PART, not a reason to stop: an APU's integrated graphics + # beside the discrete cards reports a v2.x table, and the engine does not serve on it. + try: + size, fr, cr = struct.unpack_from(" @@ -3086,3 +3096,346 @@ TEST(the_per_expert_tap_keeps_each_experts_gram_whole) { } CHECK_EQ(bad, 0); } + +/* ==================================================================== LFM2 */ +namespace { + +/* d1-3B's graph cut to four layers: conv, conv, attention, conv -- an irregular schedule the + * plugin must read, not derive. A VL checkpoint (it has a text_config), tied head. */ +const char* k_lfm2_keys[] = { "text_config.num_hidden_layers", "layer_types", "conv_L_cache", + "tie_word_embeddings" }; +const char* k_lfm2_vals[] = { "4", "conv conv full_attention conv", "3", "true" }; + +RadModelMeta lfm2_meta(int n_kv = 4) { + RadModelMeta m{}; + m.arch_id = "lfm2"; m.name = "test-lfm2"; m.quant = ""; + m.n_layers = 4; m.n_embd = 64; m.n_head = 4; m.n_head_kv = 1; m.head_dim = 16; + m.n_ff = 128; m.n_vocab = 512; m.n_ctx_train = 32768; + m.rms_eps = 1e-5f; m.rope_theta = 1e6f; m.rope_scale = 1.0f; + m.n_kv = n_kv; m.kv_key = k_lfm2_keys; m.kv_val = k_lfm2_vals; + return m; +} + +std::vector lfm2_layer_ops(bool attention) { + std::vector v = { "rmsnorm" }; + if (attention) { + for (const char* s : { "gemm_nt", "gemm_nt", "gemm_nt", "rmsnorm", "rmsnorm", "rope", + "rope", "attn_paged", "kv_store", "gemm_nt" }) + v.push_back(s); + } else { + for (const char* s : { "gemm_nt", "mul", "causal_conv1d", "mul", "gemm_nt" }) + v.push_back(s); + } + v.push_back("add"); + append(v, mlp_ops(false)); + return v; +} + +} /* namespace */ + +TEST(lfm2_declares_the_checkpoints_own_schedule) { + RadBuilder b; + RadModelMeta meta = lfm2_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + + std::vector want = { "embed_lookup" }; + for (bool att : { false, false, true, false }) append(want, lfm2_layer_ops(att)); + for (const char* s : { "gather_rows", "rmsnorm", "logits_gemm" }) want.push_back(s); + CHECK_EQ(join(op_names(b)), join(want)); + + /* Two state groups: paged KV bound to the one attention layer, and a conv window of + * n_embd channels and the checkpoint's width bound to the other three. */ + REQUIRE(b.kv_groups.size() == 2); + CHECK_EQ(b.kv_groups[0].d.kind, (int)RAD_KV_FULL); + CHECK_EQ(b.kv_groups[1].d.kind, (int)RAD_KV_CONV); + CHECK_EQ(b.kv_groups[1].d.conv_width, (int64_t)3); + CHECK_EQ(b.kv_groups[1].d.n_head_kv * b.kv_groups[1].d.head_dim, (int64_t)64); + REQUIRE(b.binds.size() == 4); + for (const auto& bd : b.binds) + CHECK_EQ(bd.second, bd.first == 2 ? (rad_kvgroup)1 : (rad_kvgroup)2); + + /* A plain RMSNorm at the checkpoint's epsilon, NeoX over the whole head. */ + const RecOp* norm = find_op(b, "rmsnorm"); + CHECK_NEAR(pflt(norm, "eps"), 1e-5, 1e-9); + CHECK_EQ(param(norm, "wadd") ? pflt(norm, "wadd") : 0.0, 0.0); + CHECK_EQ(pstr(find_op(b, "rope"), "mode"), "neox"); + CHECK_EQ(pint(find_op(b, "rope"), "rotary_dim"), 16); + CHECK_EQ(pint(find_op(b, "attn_paged"), "gqa"), 4); + CHECK_EQ(pint(find_op(b, "causal_conv1d"), "width"), 3); + + /* The VL checkpoint's names, and a tied head read from the embedding when there is no + * lm_head of its own. */ + const RecMap* in = find_map(b, "blk.0.conv_in.weight"); + REQUIRE(in != nullptr); + CHECK_EQ(in->src[0], "model.language_model.layers.0.conv.in_proj.weight"); + const RecMap* head = find_map(b, "output.weight"); + REQUIRE(head != nullptr && head->src.size() == 2); + CHECK_EQ(head->src[0], "lm_head.weight"); + CHECK_EQ(head->src[1], "model.language_model.embed_tokens.weight"); +} + +TEST(lfm2_text_checkpoint_keeps_its_names_under_model) { + /* No text_config: a text-only LFM2, whose layers sit under `model.` */ + static const char* keys[] = { "layer_types", "conv_L_cache" }; + static const char* vals[] = { "conv conv full_attention conv", "3" }; + RadBuilder b; + RadModelMeta meta = lfm2_meta(); + meta.n_kv = 2; meta.kv_key = keys; meta.kv_val = vals; + RadBuildCtx ctx = build_ctx(); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + const RecMap* q = find_map(b, "blk.2.attn_q.weight"); + REQUIRE(q != nullptr); + CHECK_EQ(q->src[0], "model.layers.2.self_attn.q_proj.weight"); +} + +TEST(lfm2_refuses_what_it_does_not_serve) { + { + RadBuilder b; + RadModelMeta meta = lfm2_meta(1); /* no layer_types */ + RadBuildCtx ctx = build_ctx(); + CHECK(lfm2_bf16::declare(&b, &meta, &ctx) < 0); + } + { + RadBuilder b; + RadModelMeta meta = lfm2_meta(); + RadBuildCtx ctx = build_ctx(0, 2); + CHECK_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED); + } + { + static const char* keys[] = { "layer_types", "conv_L_cache" }; + static const char* vals[] = { "conv sliding_attention conv conv", "3" }; + RadBuilder b; + RadModelMeta meta = lfm2_meta(); + meta.n_kv = 2; meta.kv_key = keys; meta.kv_val = vals; + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED); + } +} + +TEST(lfm2_issues_the_convolution_once_per_half_of_a_mixed_step) { + RadBuilder b; + RadModelMeta meta = lfm2_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + + /* Two decode rows (a verify of 3 and a plain decode) and one prefill chunk of 5. */ + static const int32_t tok[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + static const int32_t pos[9] = { 40, 41, 42, 30, 0, 1, 2, 3, 4 }; + static const int32_t cu[4] = { 0, 3, 4, 9 }; + static const int32_t ctxl[3] = { 40, 30, 0 }; + static const int32_t nacc[3] = { 2, 1, 1 }; + static const int32_t out[3] = { 2, 3, 8 }; + static int32_t cv_idx[3] = { 4, 5, 6 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = lfm2_bf16::g_model[0].kv_attn; + kv[1].group = lfm2_bf16::g_model[0].kv_conv; kv[1].state_index = cv_idx; + RadBatch mixed{}; + mixed.phase = RAD_PHASE_MIXED; + mixed.n_tok = 9; mixed.n_seq = 3; mixed.max_q_len = 5; + mixed.n_seq_decode = 2; mixed.n_tok_decode = 4; + mixed.token_ids = tok; mixed.positions = pos; mixed.cu_seqlens = cu; mixed.ctx_lens = ctxl; + mixed.num_accepted = nacc; mixed.n_out = 3; mixed.out_ids = out; + mixed.n_kv_groups = 2; mixed.kv = kv; + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; c.batch = &mixed; + lfm2_bf16::step(&c, &mixed); + CHECK(c.step_fail.empty()); + + int convs = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o) continue; + if (o->op == "mul" && i.opd.size() == 3 && i.opd[0].cols > 0) { + /* conv(B * x): the B and x thirds of the [B | C | x] row, as column slices. */ + if (i.opd[1].cols > 0) { + CHECK_EQ(i.opd[0].offset, (int64_t)0); + CHECK_EQ(i.opd[1].offset, (int64_t)128); + } else { + CHECK_EQ(i.opd[0].offset, (int64_t)64); /* C * conv(...) */ + } + CHECK_EQ(i.opd[0].cols, (int64_t)64); + } + if (o->op != "causal_conv1d") continue; + REQUIRE(i.opd.size() == 8); + if (convs++ % 2 == 0) { /* the decode half */ + CHECK_EQ(i.n, (int64_t)4); + CHECK_EQ(i.opd[0].rows, (int64_t)4); + CHECK(i.opd[3].raw == (void*)cu); CHECK_EQ(i.opd[3].rows, (int64_t)3); + CHECK(i.opd[4].raw == (void*)cv_idx); + CHECK(i.opd[6].raw == (void*)nacc); + } else { /* the prefill half: arrays from D, rows from the base */ + CHECK_EQ(i.n, (int64_t)9); + CHECK_EQ(i.opd[0].rows, (int64_t)9); + CHECK(i.opd[3].raw == (void*)(cu + 2)); CHECK_EQ(i.opd[3].rows, (int64_t)2); + CHECK(i.opd[4].raw == (void*)(cv_idx + 2)); + CHECK(i.opd[5].raw == (void*)(ctxl + 2)); + CHECK_EQ(i.opd[6].kind, (uint8_t)RAD_OPK_NONE); + } + } + CHECK_EQ(convs, 6); /* three conv layers, two halves each */ +} + +/* ==================================================================== LFM2-VL's tower */ +namespace { + +/* lfm2_meta's text model under a SigLIP2 tower cut to two layers of 64 (four heads of 16), d1's + * patch, position table and unshuffle, a 96-wide projector. */ +const char* k_lfm2vl_keys[] = { "text_config.num_hidden_layers", "layer_types", "conv_L_cache", + "tie_word_embeddings", "vision_config.model_type", + "vision_config.num_hidden_layers", "vision_config.hidden_size", + "vision_config.num_attention_heads", "vision_config.intermediate_size", + "vision_config.patch_size", "vision_config.num_patches", + "vision_config.hidden_act", "vision_config.vision_use_head", + "downsample_factor", "projector_hidden_size", + "projector_hidden_act", "projector_bias", + "projector_use_layernorm", "max_num_patches" }; +const char* k_lfm2vl_vals[] = { "4", "conv conv full_attention conv", "3", "true", + "siglip2_vision_model", "2", "64", "4", "128", "16", "256", + "gelu_pytorch_tanh", "false", "2", "96", "gelu", "true", "false", + "1024" }; +const char* k_lfm2vl_norm_vals[] = { "4", "conv conv full_attention conv", "3", "true", + "siglip2_vision_model", "2", "64", "4", "128", "16", "256", + "gelu_pytorch_tanh", "false", "2", "96", "gelu", "true", "true", + "1024" }; + +RadModelMeta lfm2vl_meta(bool proj_norm = false) { + RadModelMeta m = lfm2_meta(); + m.n_kv = (int)(sizeof(k_lfm2vl_keys) / sizeof(k_lfm2vl_keys[0])); + m.kv_key = k_lfm2vl_keys; + m.kv_val = proj_norm ? k_lfm2vl_norm_vals : k_lfm2vl_vals; + return m; +} + +} /* namespace */ + +TEST(lfm2_vl_declares_the_siglip2_tower_and_its_projector) { + { /* No encoder budget: text only, whatever the container carries. */ + RadBuilder b; + RadModelMeta meta = lfm2vl_meta(); + RadBuildCtx ctx = vl_ctx(0); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + CHECK(b.encoder_name.empty()); + CHECK_EQ(count_op(b, "scatter_rows"), 0); + } + RadBuilder b; + RadModelMeta meta = lfm2vl_meta(); + RadBuildCtx ctx = vl_ctx(1024); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + CHECK_EQ(b.encoder_name, std::string("vision")); + CHECK_EQ(b.encoder.modalities, (uint32_t)RAD_MM_IMAGE); + CHECK_EQ(b.encoder.patch_dim, 3 * 16 * 16); + CHECK_EQ(b.encoder.merge, 4); + CHECK_EQ(b.encoder.max_patches, 1024); + CHECK_EQ(b.encoder.n_embd, 64); + CHECK_EQ(count_op(b, "scatter_rows"), 1); + + /* 3 stem + 12 a layer + 2 post-norm + 4 projector, each mapped from the checkpoint. */ + int nv = 0; + for (const auto& w : b.weights) + if (w.name.rfind("v.", 0) == 0) { + ++nv; + CHECK(find_map(b, w.name) != nullptr); + } + CHECK_EQ(nv, 3 + 2 * 12 + 2 + 4); + /* q, k and v are concatenated at convert into one QKV weight and one bias. */ + const RecMap* qkv = find_map(b, "v.blk.1.qkv.weight"); + REQUIRE(qkv != nullptr); + REQUIRE_EQ(qkv->src.size(), (size_t)3); + CHECK_EQ(qkv->src[0], + std::string("model.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight")); + CHECK_EQ(qkv->src[2], + std::string("model.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight")); + const RecMap* l1 = find_map(b, "v.proj.fc1.weight"); + REQUIRE(l1 != nullptr); + CHECK_EQ(l1->src[0], std::string("model.multi_modal_projector.linear_1.weight")); + /* The projector reads four patches as one row; its first layer is erf GELU, the tower's tanh. */ + const RecWeight* w1 = find_w(b, "v.proj.fc1.weight"); + REQUIRE(w1 != nullptr); + CHECK_EQ(w1->d.shape[0], 96); + CHECK_EQ(w1->d.shape[1], 4 * 64); + int tanh = 0, erf = 0; + for (const auto& o : b.ops) + if (o.op == "gemm_nt_bias") { + tanh += pstr(&o, "act") == "gelu_tanh"; + erf += pstr(&o, "act") == "gelu"; + } + CHECK_EQ(tanh, 2); + CHECK_EQ(erf, 1); + /* No rotary in the tower, the position table resampled as torch's antialiased bilinear, and + * the attention's block height bounded by the longest segment the processor makes. */ + CHECK_EQ(count_op(b, "grid_embed_aa"), 1); + CHECK_EQ(count_op(b, "grid_embed"), 0); + CHECK_EQ(pint(find_op(b, "attn_dense"), "max_seqlen"), 1024); + CHECK_EQ(pint(find_op(b, "attn_dense"), "head_dim"), 16); + + /* A projector with its layer norm declares one over the merged rows. */ + RadBuilder bn; + RadModelMeta mn = lfm2vl_meta(true); + CHECK_OK(lfm2_bf16::declare(&bn, &mn, &ctx)); + CHECK(find_w(bn, "v.proj.norm.weight") != nullptr); + CHECK_EQ(count_op(bn, "layernorm"), count_op(b, "layernorm") + 1); +} + +TEST(lfm2_vl_encoder_pass_and_the_rows_it_scatters) { + RadBuilder b; + RadModelMeta meta = lfm2vl_meta(); + RadBuildCtx ctx = vl_ctx(1024); + CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx)); + + /* A tile of 8 x 8 patches and a thumbnail of 4 x 8. */ + static uint16_t pix[96 * 768]; + static int32_t coord[4 * 96]; + static const int32_t cu[] = { 0, 64, 96 }; + RadBatch batch{}; + batch.enc = RAD_MM_IMAGE; + batch.enc_n_patch = 96; + batch.enc_pixels = pix; + batch.enc_coord = coord; + batch.enc_n_seg = 2; + batch.enc_cu = cu; + batch.enc_max_seg = 64; + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; c.batch = &batch; + lfm2_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + std::vector want = { "gemm_nt_bias", "grid_embed_aa" }; + for (int l = 0; l < 2; ++l) + for (const char* s : { "layernorm", "gemm_nt_bias", "attn_dense", "gemm_nt_bias", + "layernorm", "gemm_nt_bias", "gemm_nt_bias" }) + want.push_back(s); + for (const char* s : { "layernorm", "gemm_nt_bias", "gemm_nt_bias" }) want.push_back(s); + CHECK_EQ(join(issued_ops(b, c)), join(want)); + /* The position resample reads all four coordinate planes; the projector runs on merged rows. */ + const RecIssue* ge = issue_of(b, c, "grid_embed_aa"); + REQUIRE(ge != nullptr); + CHECK(ge->opd[2].raw == coord); + CHECK_EQ(ge->opd[2].rows, 4); + CHECK_EQ(c.issues.back().n, 24); + const RecIssue* at = issue_of(b, c, "attn_dense"); + REQUIRE(at != nullptr); + CHECK_EQ(at->opd[1].offset, 64); + CHECK_EQ(at->opd[2].offset, 128); + CHECK(at->opd[3].raw == cu); + + /* A text step with media rows puts them over the lookup, before the first layer. */ + static const int32_t tok[4] = { 1, 2, 3, 4 }, pos[4] = { 0, 1, 2, 3 }, cus[2] = { 0, 4 }; + static const int32_t ctxl[1] = { 0 }, out[1] = { 3 }, rows[2] = { 1, 2 }; + static uint16_t embd[2 * 64]; + static int32_t cv_idx[1] = { 0 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = lfm2_bf16::g_model[0].kv_attn; + kv[1].group = lfm2_bf16::g_model[0].kv_conv; kv[1].state_index = cv_idx; + RadBatch tb{}; + tb.phase = RAD_PHASE_PREFILL; + tb.n_tok = 4; tb.n_seq = 1; tb.max_q_len = 4; + tb.token_ids = tok; tb.positions = pos; tb.cu_seqlens = cus; tb.ctx_lens = ctxl; + tb.n_out = 1; tb.out_ids = out; tb.n_kv_groups = 2; tb.kv = kv; + tb.n_mm_rows = 2; tb.mm_rows = rows; tb.mm_embd = embd; + RadCtx ct; ct.b = &b; ct.rank = 0; ct.world = 1; ct.batch = &tb; + lfm2_bf16::step(&ct, &tb); + CHECK(ct.step_fail.empty()); + const std::vector ops = issued_ops(b, ct); + REQUIRE(ops.size() > 2); + CHECK_EQ(ops[0], std::string("embed_lookup")); + CHECK_EQ(ops[1], std::string("scatter_rows")); +} diff --git a/tests/device_test.cpp b/tests/device_test.cpp index d2f24018..2a23b4cd 100644 --- a/tests/device_test.cpp +++ b/tests/device_test.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include using rad::DirectFile; @@ -281,6 +282,214 @@ TEST(memcpy_async_then_stream_sync) { rad_dev_free(dst, RAD_MEM_HOST); } +/* A list copy is many copies handed to the card's DMA engine at once, so what it can get wrong is + * at the BOUNDARIES: a copy landing a few bytes off, short by its last bytes, or running into its + * neighbour. So: dozens of copies, lengths from one word to a few hundred KiB, sources taken out of + * order, destinations with gaps whose sentinel bytes must survive, odd lengths and unaligned + * sources -- and the bytes read back through an ordinary copy on the same stream, which must wait + * for the list. */ +TEST(memcpy_list_async_copies_every_segment_and_nothing_else) { + const int nseg = 77; + const int64_t gap = 48, slab = 16 << 20; + Stream st; + auto* src = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_HOST_PINNED); + auto* dev = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_DEVICE); + auto* back = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_HOST_PINNED); + CHECK(src && dev && back); + if (!src || !dev || !back) return; + fill(src, slab, 0x5EC5u); + + std::vector segs; + std::vector s_off, d_off, len; + int64_t d = 0, s = slab; + for (int i = 0; i < nseg; ++i) { + int64_t n = 16 * (1 + (int64_t)((i * 2654435761u) % 13000)); /* 16 B .. ~200 KiB */ + if (i % 19 == 7) n += 5; /* an odd length */ + s -= n + 64; /* sources backwards */ + if (i % 23 == 11) s -= 4; /* an unaligned source */ + s_off.push_back(s); + d_off.push_back(d); + len.push_back(n); + d = (d + n + gap + 15) & ~(int64_t)15; + } + CHECK(s > 0 && d < slab); + CHECK_OK(rad_memset_async(dev, 0xA7, slab, st.s)); + for (int i = 0; i < nseg; ++i) segs.push_back(RadCopySeg{src + s_off[i], dev + d_off[i], len[i]}); + segs.push_back(RadCopySeg{src, dev, 0}); /* nothing to copy */ + CHECK_OK(rad_memcpy_list_async(segs.data(), (int)segs.size(), 0, st.s)); + CHECK_OK(rad_memcpy_async(back, dev, slab, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + + int bad = 0, smashed = 0; + for (int i = 0; i < nseg; ++i) { + if (std::memcmp(back + d_off[i], src + s_off[i], (size_t)len[i]) != 0) ++bad; + const int64_t end = i + 1 < nseg ? d_off[i + 1] : d; + for (int64_t j = d_off[i] + len[i]; j < end; ++j) + if (back[j] != 0xA7) { ++smashed; break; } + } + CHECK_EQ(bad, 0); + CHECK_EQ(smashed, 0); + + rad_dev_free(src, RAD_MEM_HOST_PINNED); + rad_dev_free(dev, RAD_MEM_DEVICE); + rad_dev_free(back, RAD_MEM_HOST_PINNED); +} + +/* THE DMA QUEUE'S RING IS FINITE AND WRAPS. Thousands of lists of small copies write several times + * the ring's packets, so lists land across the wrap and behind a full ring; every copy must still + * arrive, at its own place. Every other list yields, so the gate's checks wrap as well. */ +TEST(memcpy_list_async_survives_its_ring_wrapping) { + const int lists = 1500, per = 64; + const int64_t each = 256, total = (int64_t)lists * per * each; + Stream st; + auto* src = (uint8_t*)rad_dev_alloc(total, RAD_MEM_HOST_PINNED); + auto* dev = (uint8_t*)rad_dev_alloc(total, RAD_MEM_DEVICE); + auto* back = (uint8_t*)rad_dev_alloc(total, RAD_MEM_HOST_PINNED); + CHECK(src && dev && back); + if (!src || !dev || !back) return; + fill(src, total, 0x3A11u); + CHECK_OK(rad_memset_async(dev, 0, total, st.s)); + std::vector segs((size_t)per); + for (int k = 0; k < lists; ++k) { + for (int i = 0; i < per; ++i) { + const int64_t at = ((int64_t)k * per + i) * each; + segs[(size_t)i] = RadCopySeg{src + (total - each - at), dev + at, each}; /* mirrored */ + } + CHECK_OK(rad_memcpy_list_async(segs.data(), per, k & 1 ? RAD_COPY_YIELD : 0, st.s)); + } + CHECK_OK(rad_memcpy_async(back, dev, total, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + int64_t bad = 0; + for (int64_t at = 0; at < total; at += each) + bad += std::memcmp(back + at, src + (total - each - at), (size_t)each) != 0; + CHECK_EQ(bad, (int64_t)0); + rad_dev_free(src, RAD_MEM_HOST_PINNED); + rad_dev_free(dev, RAD_MEM_DEVICE); + rad_dev_free(back, RAD_MEM_HOST_PINNED); +} + +/* THE ENGINE WRITES PAST THE L2 AND READS PAST IT. A card buffer small enough to stay in the L2 is + * read by a kernel, overwritten by a list and read again by a kernel on the same stream: the second + * read must see the list's bytes, not the lines the first left behind. And the other way: bytes a + * kernel has just written, still dirty in the L2, are what a list copying them to the host must read. + * Twelve rounds, each with new bytes. The inbound list yields, which cuts its one copy into pieces + * that must join up exactly. */ +TEST(memcpy_list_async_is_ordered_against_the_l2_both_ways) { + const int64_t n = 4 << 20; + Stream st; + auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + auto* a = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE); + auto* b = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE); + CHECK(src && back && a && b); + if (!src || !back || !a || !b) return; + int stale = 0, lost = 0; + for (int r = 0; r < 12; ++r) { + fill(src, n, 0x1000u + (uint32_t)r); + CHECK_OK(rad_memset_async(a, 0x40 + r, n, st.s)); + CHECK_OK(rad_memcpy_async(b, a, n, st.s)); /* a's lines into the L2 */ + const RadCopySeg in{src, a, n}; + CHECK_OK(rad_memcpy_list_async(&in, 1, RAD_COPY_YIELD, st.s)); /* in pieces */ + CHECK_OK(rad_memcpy_async(b, a, n, st.s)); /* must read the list's bytes */ + CHECK_OK(rad_memcpy_async(back, b, n, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + stale += std::memcmp(back, src, (size_t)n) != 0; + + CHECK_OK(rad_memset_async(b, 0x80 + r, n, st.s)); /* dirty in the L2 */ + const RadCopySeg out{b, back, n}; + CHECK_OK(rad_memcpy_list_async(&out, 1, 0, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + for (int64_t i = 0; i < n; i += 4093) + if (back[i] != (uint8_t)(0x80 + r)) { ++lost; break; } + } + CHECK_EQ(stale, 0); + CHECK_EQ(lost, 0); + rad_dev_free(src, RAD_MEM_HOST_PINNED); + rad_dev_free(back, RAD_MEM_HOST_PINNED); + rad_dev_free(a, RAD_MEM_DEVICE); + rad_dev_free(b, RAD_MEM_DEVICE); +} + +/* A HELD LINK STOPS A YIELDING LIST UNTIL IT IS RELEASED. Stream `c` holds the link, then waits for + * a long chain of fills on `slow` before it releases; a yielding list on `t`, ordered behind the + * hold, can therefore finish only after the chain has. Without the gate the list -- 64 MiB, a few + * milliseconds -- is done long before the chain's tens of milliseconds of fills. A backend without a + * DMA engine holds nothing, which it shows by taking a second hold without complaint. */ +TEST(link_hold_stops_a_yielding_list_until_released) { + const int64_t n = 64 << 20, big = 256 << 20; + Stream c, t, slow; + Event held, chain; + CHECK_OK(rad_memcpy_list_async(nullptr, 0, 0, t.s)); /* the card's DMA queue, if it has one */ + CHECK_OK(rad_link_hold(c.s, 1)); + if (rad_link_hold(c.s, 1) == RAD_OK) return; /* nothing to hold on this backend */ + (void)rad_dev_last_error(); + auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE); + auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + auto* fat = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE); + CHECK(src && dst && back && fat); + if (!src || !dst || !back || !fat) { (void)rad_link_hold(c.s, 0); return; } + fill(src, n, 0x6A7Eu); + for (int k = 0; k < 40; ++k) CHECK_OK(rad_memset_async(fat, k, big, slow.s)); + CHECK_OK(rad_event_record(chain.e, slow.s)); + CHECK_OK(rad_event_record(held.e, c.s)); + CHECK_OK(rad_event_wait(c.s, chain.e)); + CHECK_OK(rad_link_hold(c.s, 0)); + CHECK_EQ(rad_link_hold(c.s, 0), RAD_E_STATE); /* a release must follow a hold */ + (void)rad_dev_last_error(); + + CHECK_OK(rad_event_wait(t.s, held.e)); + const RadCopySeg seg{src, dst, n}; + CHECK_OK(rad_memcpy_list_async(&seg, 1, RAD_COPY_YIELD, t.s)); + CHECK_OK(rad_stream_sync(t.s)); + CHECK_EQ(rad_event_query(chain.e), 1); + CHECK_OK(rad_memcpy_async(back, dst, n, t.s)); + CHECK_OK(rad_stream_sync(t.s)); + CHECK(std::memcmp(back, src, (size_t)n) == 0); + CHECK_OK(rad_stream_sync(c.s)); + CHECK_OK(rad_stream_sync(slow.s)); + rad_dev_free(src, RAD_MEM_HOST_PINNED); + rad_dev_free(dst, RAD_MEM_DEVICE); + rad_dev_free(back, RAD_MEM_HOST_PINNED); + rad_dev_free(fat, RAD_MEM_DEVICE); +} + +/* A HOLD ENDED BY THE WORK IT COVERED. A collective that knows when its peers' bytes have landed + * takes one off the word itself (rad_link_gate) and the stream records it with mode 2, so no + * barrier follows. Here the host plays the collective: the word is odd once the hold has taken + * effect, even once ended, a yielding list behind it runs, and a second end is refused because + * nothing is held. */ +TEST(link_gate_word_ends_a_hold_from_the_work_it_covers) { + const int64_t n = 4 << 20; + Stream c, t; + CHECK_OK(rad_memcpy_list_async(nullptr, 0, 0, t.s)); /* the card's DMA queue, if it has one */ + volatile long long* g = (volatile long long*)rad_link_gate(c.s); + if (!g) return; /* nothing to hold on this backend */ + CHECK_OK(rad_link_hold(c.s, 1)); + CHECK_OK(rad_stream_sync(c.s)); + CHECK_EQ((int)(*g & 1), 1); + *g = *g - 1; /* what the launch does once its bytes land */ + CHECK_OK(rad_link_hold(c.s, 2)); + CHECK_EQ((int)(*g & 1), 0); + CHECK_EQ(rad_link_hold(c.s, 2), RAD_E_STATE); + (void)rad_dev_last_error(); + + auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE); + auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED); + CHECK(src && dst && back); + if (!src || !dst || !back) return; + fill(src, n, 0x9A7Eu); + const RadCopySeg seg{src, dst, n}; + CHECK_OK(rad_memcpy_list_async(&seg, 1, RAD_COPY_YIELD, t.s)); + CHECK_OK(rad_memcpy_async(back, dst, n, t.s)); + CHECK_OK(rad_stream_sync(t.s)); + CHECK(std::memcmp(back, src, (size_t)n) == 0); + rad_dev_free(src, RAD_MEM_HOST_PINNED); + rad_dev_free(dst, RAD_MEM_DEVICE); + rad_dev_free(back, RAD_MEM_HOST_PINNED); +} + TEST(memset_async) { const int64_t n = 1 << 20; Stream st; diff --git a/tests/diag_test.cpp b/tests/diag_test.cpp new file mode 100644 index 00000000..55d2a806 --- /dev/null +++ b/tests/diag_test.cpp @@ -0,0 +1,710 @@ +/* diag_test.cpp -- the startup report (core/diag/diag.h). + * + * THE MACHINE IS A DIRECTORY. The collector reads /proc and /sys under a root, so every case here + * builds the root it wants: two R9700s behind on-card switches, one of them on a root port running + * at half its speed under load, an integrated GPU beside them, and the host files a real Linux box + * has. The layout copies what a gfx1201 host's sysfs actually holds (KFD topology location ids, + * pp_dpm_pcie's table, pp_od_clk_voltage's offset block), so a parser that only works on a + * simplified fixture fails here. + * + * What is held down: + * COLLECTED each fact reaches its field, every hop of a card's PCIe path included + * CHECKED each finding fires on the machine that has the problem and stays quiet on one + * that does not -- an idle link parked low is not a finding + * REPORTED every option in the command line's table reaches the report, and a secret does not + */ +#include "rad_test.h" + +#include "rad_core.h" +#include "diag/diag.h" +#include "gen_config.h" + +#include + +#include +#include +#include +#include +#include +#include + +using namespace rad; +namespace fs = std::filesystem; + +namespace { + +struct Root { + std::string dir; + Root() { + const char* t = std::getenv("TMPDIR"); + std::string base = (t && *t) ? t : "/tmp"; + char tmpl[512]; + snprintf(tmpl, sizeof tmpl, "%s/diag_test.XXXXXX", base.c_str()); + dir = mkdtemp(tmpl) ? tmpl : ""; + } + ~Root() { + std::error_code ec; + if (!dir.empty()) fs::remove_all(dir, ec); + } + void put(const std::string& rel, const std::string& text) const { + const fs::path p = fs::path(dir) / rel.substr(1); + fs::create_directories(p.parent_path()); + std::ofstream(p) << text; + } + void mkdir(const std::string& rel) const { fs::create_directories(fs::path(dir) / rel.substr(1)); } + /* A relative symlink, as sysfs's are, so it resolves inside the root. */ + void link(const std::string& rel, const std::string& target) const { + const fs::path p = fs::path(dir) / rel.substr(1); + fs::create_directories(p.parent_path()); + fs::create_symlink(target, p); + } +}; + +/* A PCI device directory under /sys/devices and its /sys/bus/pci/devices link. `path` is the + * device's position under the root complex, "pci0000:00/0000:00:01.1/0000:01:00.0". */ +void pci(const Root& r, const std::string& path, const std::string& cls, const std::string& cur, + int curw, const std::string& max, int maxw) { + const std::string bdf = path.substr(path.rfind('/') + 1); + const std::string d = "/sys/devices/" + path; + r.put(d + "/class", cls + "\n"); + r.put(d + "/current_link_speed", cur + "\n"); + r.put(d + "/current_link_width", std::to_string(curw) + "\n"); + r.put(d + "/max_link_speed", max + "\n"); + r.put(d + "/max_link_width", std::to_string(maxw) + "\n"); + r.link("/sys/bus/pci/devices/" + bdf, "../../../devices/" + path); +} + +/* An R9700 behind its on-card switch, under root port `rp`. */ +void r9700(const Root& r, const std::string& rp, const std::string& up, const std::string& down, + const std::string& bdf, const std::string& rp_cur, int busy, int64_t cap_uw, + const char* drm, int dpm_cur, int64_t kfd_loc, int node) { + const std::string base = "pci0000:00/0000:00:" + rp; + pci(r, base, "0x060400", rp_cur, 8, "32.0 GT/s PCIe", 8); + pci(r, base + "/" + up, "0x060400", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16); + pci(r, base + "/" + up + "/" + down, "0x060400", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16); + const std::string path = base + "/" + up + "/" + down + "/" + bdf; + pci(r, path, "0x030000", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16); + const std::string d = "/sys/devices/" + path; + r.put(d + "/vendor", "0x1002\n"); + r.put(d + "/device", "0x7551\n"); + r.mkdir("/sys/bus/pci/drivers/amdgpu"); + r.link(d + "/driver", "../../../../../../../bus/pci/drivers/amdgpu"); + r.put(d + "/numa_node", "-1\n"); + r.put(d + "/power/runtime_status", "active\n"); + r.put(d + "/power/control", "auto\n"); + r.put(d + "/iommu_group/type", "identity\n"); + r.mkdir(d + "/drm/" + drm); + r.put(d + "/mem_info_vram_total", "34208743424\n"); + r.put(d + "/mem_info_vis_vram_total", "34208743424\n"); + r.put(d + "/gpu_busy_percent", std::to_string(busy) + "\n"); + std::string pcie; + const char* lv[] = { "0: 2.5GT/s, x8 250Mhz", "1: 16.0GT/s, x8 616Mhz", "2: 32.0GT/s, x8 1143Mhz" }; + for (int i = 0; i < 3; ++i) pcie += std::string(lv[i]) + (i == dpm_cur ? " *" : "") + "\n"; + r.put(d + "/pp_dpm_pcie", pcie); + r.put(d + "/pp_dpm_sclk", "0: 500Mhz \n1: 1768Mhz *\n2: 2350Mhz \n"); + r.put(d + "/pp_dpm_mclk", "0: 96Mhz \n1: 456Mhz \n2: 772Mhz \n3: 875Mhz *\n4: 1124Mhz \n5: 1258Mhz \n"); + r.put(d + "/hwmon/hwmon2/name", "amdgpu\n"); + r.put(d + "/hwmon/hwmon2/power1_cap", std::to_string(cap_uw) + "\n"); + r.put(d + "/hwmon/hwmon2/power1_cap_default", "300000000\n"); + r.put(d + "/hwmon/hwmon2/power1_cap_max", "330000000\n"); + r.put(d + "/pp_od_clk_voltage", + "OD_SCLK_OFFSET:\n0Mhz\nOD_MCLK:\n0: 97Mhz\n1: 1259MHz\nOD_RANGE:\n" + "SCLK_OFFSET: -500Mhz 1000Mhz\nVDDGFX_OFFSET: -200mv 0mv\n" + "OD_VDDGFX_OFFSET:\n-75mV\n"); + r.put("/sys/class/kfd/kfd/topology/nodes/" + std::to_string(node) + "/properties", + "cpu_cores_count 0\nsimd_count 128\nlocation_id " + std::to_string(kfd_loc) + + "\ndomain 0\ngfx_target_version 120001\n"); +} + +/* The machine the report was written against: a 16-core desktop part, two R9700s (the second on a + * root port parked at Gen4 while busy, and with a lower power cap), an integrated GPU. */ +void machine(const Root& r) { + std::string cpu; + for (int i = 0; i < 4; ++i) + cpu += "processor\t: " + std::to_string(i) + "\nmodel name\t: AMD Ryzen 9 7950X3D 16-Core Processor\n" + "physical id\t: 0\ncore id\t\t: " + std::to_string(i / 2) + "\n\n"; + r.put("/proc/cpuinfo", cpu); + r.put("/proc/meminfo", "MemTotal: 64669548 kB\nMemFree: 14000000 kB\n" + "MemAvailable: 53000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"); + r.put("/proc/sys/kernel/osrelease", "7.2.7-arch1-1\n"); + r.put("/etc/os-release", "NAME=\"Arch Linux\"\nPRETTY_NAME=\"Arch Linux\"\nID=arch\n"); + r.put("/proc/cmdline", "initrd=\\initramfs-linux.img root=PARTUUID=x rw iommu=pt amdgpu.ppfeaturemask=0xfff7ffff\n"); + r.put("/proc/self/cgroup", "0::/user.slice\n"); + r.put("/sys/fs/cgroup/user.slice/memory.max", "max\n"); + r.put("/sys/kernel/mm/transparent_hugepage/enabled", "[always] madvise never\n"); + r.put("/sys/kernel/mm/transparent_hugepage/defrag", "always defer defer+madvise [madvise] never\n"); + r.put("/sys/kernel/mm/transparent_hugepage/shmem_enabled", "always within_size [advise] never deny force\n"); + r.put("/sys/module/ttm/parameters/pages_limit", "8083693\n"); + r.put("/sys/module/amdgpu/parameters/cwsr_enable", "1\n"); + r.put("/proc/sys/kernel/io_uring_disabled", "0\n"); + r.put("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", "powersave\n"); + r.put("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference", "balance_performance\n"); + r.put("/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver", "amd-pstate-epp\n"); + r.mkdir("/sys/class/iommu/ivhd0"); + r.mkdir("/sys/kernel/iommu_groups/0"); + r9700(r, "01.1", "0000:01:00.0", "0000:02:00.0", "0000:03:00.0", "32.0 GT/s PCIe", 3, + 300000000, "card0", 2, 768, 1); + r9700(r, "01.3", "0000:05:00.0", "0000:06:00.0", "0000:07:00.0", "16.0 GT/s PCIe", 90, + 280000000, "card1", 1, 1792, 2); + /* The integrated GPU: on the root bus, a display device with its own KFD node. */ + pci(r, "pci0000:00/0000:00:08.1/0000:1b:00.0", "0x030000", "16.0 GT/s PCIe", 16, "16.0 GT/s PCIe", 16); + r.put("/sys/devices/pci0000:00/0000:00:08.1/0000:1b:00.0/vendor", "0x1002\n"); + r.put("/sys/devices/pci0000:00/0000:00:08.1/0000:1b:00.0/device", "0x13c0\n"); + r.put("/sys/class/kfd/kfd/topology/nodes/3/properties", + "simd_count 4\nlocation_id 6912\ndomain 0\ngfx_target_version 100306\n"); + r.put("/sys/class/kfd/kfd/topology/nodes/0/properties", + "cpu_cores_count 32\nsimd_count 0\nlocation_id 0\ndomain 0\ngfx_target_version 0\n"); +} + +const diag::CardFacts* card(const diag::Facts& f, const char* bdf) { + for (const diag::CardFacts& c : f.cards) if (c.bdf == bdf) return &c; + return nullptr; +} + +/* The engine's half: the two cards are ranks 0 and 1. */ +diag::Facts served_machine(const Root& r) { + diag::Facts f = diag::collect(r.dir); + for (diag::CardFacts& c : f.cards) { + if (c.bdf == "0000:03:00.0") { c.rank = 0; c.device = 0; } + if (c.bdf == "0000:07:00.0") { c.rank = 1; c.device = 1; } + } + return f; +} + +bool has(const std::vector& v, const char* id, diag::Finding::Level lv) { + for (const diag::Finding& x : v) if (x.id == id && x.level == lv) return true; + return false; +} +bool has(const std::vector& v, const char* id) { + for (const diag::Finding& x : v) if (x.id == id) return true; + return false; +} + +} /* namespace */ + +/* ------------------------------------------------------------------ collected */ + +TEST(host_facts_reach_their_fields) { + Root r; + machine(r); + const diag::Facts f = diag::collect(r.dir); + const diag::HostFacts& h = f.host; + CHECK_EQ(h.cpu_model, std::string("AMD Ryzen 9 7950X3D 16-Core Processor")); + CHECK_EQ(h.threads, 4); + CHECK_EQ(h.cores, 2); + CHECK_EQ(h.mem_total, (int64_t)64669548 * 1024); + CHECK_EQ(h.mem_available, (int64_t)53000000 * 1024); + CHECK_EQ(h.swap_total, 0); + CHECK_EQ(h.kernel, std::string("7.2.7-arch1-1")); + CHECK_EQ(h.distro, std::string("Arch Linux")); + CHECK_EQ(h.cgroup_mem_limit, -2); + CHECK_EQ(h.thp_enabled, std::string("always")); + CHECK_EQ(h.thp_defrag, std::string("madvise")); + CHECK_EQ(h.thp_shmem, std::string("advise")); + CHECK_EQ(h.iommu, std::string("passthrough")); + CHECK_EQ(h.cmdline, std::string("iommu=pt amdgpu.ppfeaturemask=0xfff7ffff")); + CHECK_EQ(h.ttm_pages_limit, 8083693); + CHECK_EQ(h.cwsr_enable, 1); + CHECK_EQ(h.io_uring, std::string("available")); + CHECK_EQ(h.cpu_governor, std::string("powersave")); + CHECK_EQ(h.cpu_epp, std::string("balance_performance")); +} + +TEST(every_display_device_is_listed_with_its_kfd_target) { + Root r; + machine(r); + const diag::Facts f = diag::collect(r.dir); + CHECK_EQ((int)f.cards.size(), 3); + const diag::CardFacts* a = card(f, "0000:03:00.0"); + const diag::CardFacts* i = card(f, "0000:1b:00.0"); + CHECK(a && i); + if (!a || !i) return; + CHECK_EQ(a->gfx, std::string("gfx1201")); + CHECK_EQ(a->simd, 128); + CHECK_EQ(i->gfx, std::string("gfx1036")); + CHECK_EQ(a->vendor, std::string("0x1002")); + CHECK_EQ(a->pci_device, std::string("0x7551")); + CHECK_EQ(a->driver, std::string("amdgpu")); + CHECK_EQ(a->drm, std::string("card0")); + CHECK_EQ(a->iommu_type, std::string("identity")); + CHECK_EQ(a->vram_total, (int64_t)34208743424); + CHECK_EQ(a->busy_percent, 3); + CHECK_EQ(a->sclk, std::string("500-2350 MHz")); + CHECK_EQ(a->mclk, std::string("96-1258 MHz")); + CHECK_EQ(a->power_cap_uw, (int64_t)300000000); + CHECK_EQ(a->power_cap_max_uw, (int64_t)330000000); + CHECK_EQ(a->vddgfx_offset, std::string("-75 mV")); + CHECK_EQ((int)a->dpm_pcie.size(), 3); + CHECK_EQ(a->dpm_pcie_cur, 2); + CHECK_EQ(a->dpm_pcie[1], std::string("1: 16.0GT/s, x8 616Mhz")); +} + +/* THE ROOT PORT IS ON THE PATH. The card's own link reads Gen5 x16 on both cards; only the second + * card's root port says it runs at 16 GT/s. */ +TEST(the_whole_pcie_path_is_read_root_port_first) { + Root r; + machine(r); + const diag::Facts f = diag::collect(r.dir); + const diag::CardFacts* b = card(f, "0000:07:00.0"); + CHECK(b); + if (!b) return; + CHECK_EQ((int)b->chain.size(), 4); + if (b->chain.size() != 4) return; + CHECK_EQ(b->chain[0].bdf, std::string("0000:00:01.3")); + CHECK_EQ(b->chain[0].cur_speed, std::string("16.0 GT/s PCIe")); + CHECK_EQ(b->chain[0].max_speed, std::string("32.0 GT/s PCIe")); + CHECK_EQ(b->chain[0].max_width, 8); + CHECK_EQ(b->chain[3].bdf, std::string("0000:07:00.0")); + CHECK_EQ(b->chain[3].cur_speed, std::string("32.0 GT/s PCIe")); + CHECK_EQ(b->chain[3].cur_width, 16); + CHECK(diag::link_gts(b->chain[0].cur_speed) == 16.0); +} + +TEST(an_empty_root_is_all_unknown_and_does_not_fail) { + Root r; + const diag::Facts f = diag::collect(r.dir); + CHECK(f.cards.empty()); + CHECK(f.host.cpu_model.empty()); + CHECK_EQ(f.host.mem_total, -1); + CHECK_EQ(f.host.iommu, std::string("off")); + const std::string text = diag::render({}, {}, f, diag::RunFacts{}, {}); + CHECK(text.find("unknown") != std::string::npos); + CHECK(text.find("no display-class PCI device") != std::string::npos); +} + +/* A LIMIT ABOVE THE PROCESS'S OWN CGROUP BINDS IT. The leaf says max; the slice above it holds + * 8 GiB and the one above that 16 GiB, so the process can have 8. */ +TEST(the_tightest_cgroup_limit_on_the_way_up_is_reported) { + Root r; + machine(r); + r.put("/proc/self/cgroup", "0::/system.slice/radiance.slice/radiance.service\n"); + r.put("/sys/fs/cgroup/system.slice/radiance.slice/radiance.service/memory.max", "max\n"); + r.put("/sys/fs/cgroup/system.slice/radiance.slice/memory.max", "8589934592\n"); + r.put("/sys/fs/cgroup/system.slice/memory.max", "17179869184\n"); + CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, (int64_t)8 << 30); + /* Every level unlimited is unlimited, not unknown. */ + r.put("/sys/fs/cgroup/system.slice/radiance.slice/memory.max", "max\n"); + r.put("/sys/fs/cgroup/system.slice/memory.max", "max\n"); + CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, -2); + /* Inside a cgroup namespace the process is at "/", and the mount's root is its group. */ + r.put("/proc/self/cgroup", "0::/\n"); + r.put("/sys/fs/cgroup/memory.max", "4294967296\n"); + CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, (int64_t)4 << 30); +} + +/* unique_id is a full 64-bit hash, which a signed 64-bit read cannot hold. Ahead of the keys the + * target is read from, it must not stop the read. */ +TEST(a_kfd_value_too_large_for_a_signed_read_does_not_hide_the_rest) { + Root r; + machine(r); + r.put("/sys/class/kfd/kfd/topology/nodes/1/properties", + "cpu_cores_count 0\nunique_id 17293822569102704640\nsimd_count 128\nlocation_id 768\n" + "domain 0\ngfx_target_version 120001\n"); + const diag::Facts f = diag::collect(r.dir); + const diag::CardFacts* a = card(f, "0000:03:00.0"); + CHECK(a); + if (!a) return; + CHECK_EQ(a->gfx, std::string("gfx1201")); + CHECK_EQ(a->simd, 128); +} + +/* A SERVING PROCESS READS THE SMU-BACKED FILES OF ITS OWN CARDS ONLY. The other cards are still + * listed, from their PCI and memory files. */ +TEST(only_the_managed_cards_power_files_are_read) { + Root r; + machine(r); + const std::vector mine = { "0000:03:00.0" }; + const diag::Facts f = diag::collect(r.dir, &mine); + CHECK_EQ((int)f.cards.size(), 3); + const diag::CardFacts* a = card(f, "0000:03:00.0"); + const diag::CardFacts* b = card(f, "0000:07:00.0"); + CHECK(a && b); + if (!a || !b) return; + CHECK_EQ(a->busy_percent, 3); + CHECK_EQ(a->power_cap_uw, (int64_t)300000000); + CHECK_EQ(a->vddgfx_offset, std::string("-75 mV")); + CHECK_EQ(b->busy_percent, -1); + CHECK_EQ(b->power_cap_uw, -1); + CHECK(b->dpm_pcie.empty()); + CHECK(b->sclk.empty()); + CHECK(b->vddgfx_offset.empty()); + CHECK_EQ(b->vram_total, (int64_t)34208743424); + CHECK_EQ(b->gfx, std::string("gfx1201")); + CHECK_EQ((int)b->chain.size(), 4); +} + +TEST(environment_names_and_never_their_values) { + char a[] = "RADIANCE_TUNE=gemm:tile=128"; + char b[] = "PATH=/usr/bin"; + char c[] = "RADIANCE_LOG=debug"; + char d[] = "RADIANCE_SECRETISH=sk-not-for-the-log"; + char* env[] = { a, b, c, d, nullptr }; + const std::vector n = diag::env_names(env, "RADIANCE_"); + CHECK_EQ(n.size(), (size_t)3); + if (n.size() != 3) return; + CHECK_EQ(n[0], std::string("RADIANCE_LOG")); + CHECK_EQ(n[1], std::string("RADIANCE_SECRETISH")); + CHECK_EQ(n[2], std::string("RADIANCE_TUNE")); + diag::RunFacts run; + run.environment = n; + const std::string text = diag::render({}, {}, diag::Facts{}, run, {}); + const std::string json = diag::to_json({}, {}, diag::Facts{}, run, {}); + CHECK(text.find(" RADIANCE_TUNE\n") != std::string::npos); + CHECK(json.find("RADIANCE_SECRETISH") != std::string::npos); + CHECK(text.find("sk-not-for-the-log") == std::string::npos); + CHECK(json.find("sk-not-for-the-log") == std::string::npos); + CHECK(text.find("gemm:tile") == std::string::npos); +} + +/* ------------------------------------------------------------------ checked */ + +TEST(a_link_below_max_under_load_is_a_warning) { + Root r; + machine(r); + const auto found = diag::check(served_machine(r), diag::RunFacts{}); + CHECK(has(found, "link-below-max", diag::Finding::Warn)); + CHECK(has(found, "link-dpm-below-top", diag::Finding::Warn)); + bool names_port = false; + for (const diag::Finding& x : found) + if (x.id == "link-below-max") names_port = x.what.find("0000:00:01.3") != std::string::npos && + x.what.find("0000:07:00.0") != std::string::npos; + CHECK(names_port); +} + +/* AT REST A LINK PARKS LOW, and that is not a finding: the same parked root port on an idle card + * says nothing. */ +TEST(an_idle_card_with_a_parked_link_is_not_a_finding) { + Root r; + machine(r); + diag::Facts f = served_machine(r); + for (diag::CardFacts& c : f.cards) c.busy_percent = 0; + const auto found = diag::check(f, diag::RunFacts{}); + CHECK(!has(found, "link-below-max")); + CHECK(!has(found, "link-dpm-below-top")); +} + +TEST(cards_set_up_differently_are_named) { + Root r; + machine(r); + const auto found = diag::check(served_machine(r), diag::RunFacts{}); + CHECK(has(found, "cards-differ", diag::Finding::Warn)); + for (const diag::Finding& x : found) + if (x.id == "cards-differ") { + CHECK(x.what.find("power cap") != std::string::npos); + CHECK(x.what.find("280 W") != std::string::npos); + } + CHECK(has(found, "power-cap-below-default", diag::Finding::Note)); + CHECK(has(found, "od-runtime-suspend", diag::Finding::Note)); + CHECK(has(found, "cpu-governor", diag::Finding::Note)); +} + +/* THE DEFAULT IS THE YARDSTICK, NOT THE MAXIMUM. Both cards allow 330 W and default to 300 W; the + * first is at its default and says nothing, the second was lowered to 280 W and is named. */ +TEST(a_power_cap_is_judged_against_the_cards_default) { + Root r; + machine(r); + diag::Facts f = served_machine(r); + auto named = [](const std::vector& v, const char* bdf) { + for (const diag::Finding& x : v) + if (x.id == "power-cap-below-default" && x.what.find(bdf) != std::string::npos) + return true; + return false; + }; + auto found = diag::check(f, diag::RunFacts{}); + CHECK(!named(found, "0000:03:00.0")); + CHECK(named(found, "0000:07:00.0")); + /* A card that does not say its default is not judged at all. */ + for (diag::CardFacts& c : f.cards) c.power_cap_default_uw = -1; + CHECK(!has(diag::check(f, diag::RunFacts{}), "power-cap-below-default")); +} + +TEST(cards_alike_say_nothing_about_each_other) { + Root r; + machine(r); + diag::Facts f = served_machine(r); + for (diag::CardFacts& c : f.cards) { + c.power_cap_uw = c.power_cap_max_uw; + c.runtime_control = "on"; + c.busy_percent = 0; + if (!c.chain.empty()) c.chain.front().max_width = 8; + } + const auto found = diag::check(f, diag::RunFacts{}); + CHECK(!has(found, "cards-differ")); + CHECK(!has(found, "power-cap-below-default")); + CHECK(!has(found, "od-runtime-suspend")); +} + +TEST(the_unserved_igpu_is_not_checked_as_a_rank) { + Root r; + machine(r); + const auto found = diag::check(served_machine(r), diag::RunFacts{}); + for (const diag::Finding& x : found) CHECK(x.what.find("1b:00.0") == std::string::npos); +} + +TEST(host_findings) { + Root r; + machine(r); + diag::Facts f = served_machine(r); + diag::RunFacts run; + CHECK(!has(diag::check(f, run), "cwsr-off")); + f.host.cwsr_enable = 0; + f.host.thp_enabled = "never"; + for (diag::CardFacts& c : f.cards) c.iommu_type = "DMA-FQ"; + f.host.mem_available = (int64_t)1 << 30; + f.host.swap_total = (int64_t)8 << 30; + f.host.swap_free = (int64_t)6 << 30; + run.host_pool_mib = 12288; + run.pinned_bytes = f.host.ttm_pages_limit * f.host.page_size - ((int64_t)1 << 20); + const auto found = diag::check(f, run); + CHECK(has(found, "cwsr-off", diag::Finding::Warn)); + CHECK(has(found, "thp-never", diag::Finding::Warn)); + CHECK(has(found, "iommu-translated", diag::Finding::Note)); + CHECK(has(found, "memory-low", diag::Finding::Warn)); + CHECK(has(found, "swap-in-use", diag::Finding::Note)); + /* Warnings come before notes, so the first lines of the section are the ones to act on. */ + bool seen_note = false, order_ok = true; + for (const diag::Finding& x : found) { + if (x.level == diag::Finding::Note) seen_note = true; + else if (seen_note) order_ok = false; + } + CHECK(order_ok); + /* Huge pages off on a passthrough IOMMU is a note: the page size has not measured slower. */ + for (diag::CardFacts& c : f.cards) c.iommu_type = "identity"; + CHECK(has(diag::check(f, run), "thp-never", diag::Finding::Note)); +} + +TEST(engine_findings) { + Root r; + machine(r); + diag::Facts f = served_machine(r); + diag::RunFacts run; + run.tp = 2; + run.tp_wire_lossy = true; + run.tp_wire_min_kb = 128; + run.prefix_cache = false; + run.host_weight_bytes = (int64_t)20 << 30; + run.p2p = 0; + run.p2p_blocked = "0->1"; + run.ignored.push_back("using 2 of 3 [0:gfx1201 1:gfx1201], ignoring [2:gfx1036]"); + run.reference_kernels = true; + run.profile_ops = true; + const auto found = diag::check(f, run); + CHECK(has(found, "tp-wire-lossy", diag::Finding::Note)); + CHECK(has(found, "prefix-cache-off", diag::Finding::Note)); + /* Passthrough is not advice for peer access: on one Intel VT-d host it removed it. */ + for (const diag::Finding& x : found) + if (x.id == "p2p-off") CHECK(x.fix.find("IOMMU in passthrough") == std::string::npos); + CHECK(has(found, "experts-from-host", diag::Finding::Note)); + CHECK(has(found, "p2p-off", diag::Finding::Note)); + CHECK(has(found, "device-ignored", diag::Finding::Note)); + CHECK(has(found, "reference-kernels", diag::Finding::Warn)); + CHECK(has(found, "profile-ops", diag::Finding::Warn)); + CHECK(!has(found, "host-backend")); + run.p2p_forced_off = true; + CHECK(!has(diag::check(f, run), "p2p-off")); + /* The cache the engine turned off itself -- the KL mode, an embedding model -- is not a + * setting to undo, and its reason is on the option's line instead. */ + run.prefix_cache_off_why = "an embedding model: an encoder keeps no KV to reuse"; + CHECK(!has(diag::check(f, run), "prefix-cache-off")); + /* #58's shape: a card is in the machine and the engine came up on the host. */ + for (diag::CardFacts& c : f.cards) { c.rank = -1; } + run.host_backend = true; + CHECK(has(diag::check(f, run), "host-backend", diag::Finding::Warn)); + /* An integrated GPU's few hundred MiB of carve-out is not a card the engine would serve on. */ + for (diag::CardFacts& c : f.cards) c.vram_total = (int64_t)512 << 20; + CHECK(!has(diag::check(f, run), "host-backend")); +} + +/* THE MODE IS THE CARDS'. An integrated GPU identity-mapped beside a translated discrete card is + * a machine whose serving card is translated, whatever the other group says. */ +TEST(the_iommu_mode_is_read_from_the_serving_cards) { + Root r; + machine(r); + r.put("/proc/cmdline", "root=PARTUUID=x rw\n"); + r.put("/sys/devices/pci0000:00/0000:00:01.3/0000:05:00.0/0000:06:00.0/0000:07:00.0/iommu_group/type", + "DMA-FQ\n"); + diag::Facts f = served_machine(r); + CHECK_EQ(f.host.iommu, std::string("mixed")); + CHECK(f.host.iommu_why.find("DMA-FQ for 0000:07:00.0") != std::string::npos); + diag::RunFacts run; + run.host_pool_mib = 12288; + CHECK(has(diag::check(f, run), "iommu-translated", diag::Finding::Note)); + for (diag::CardFacts& c : f.cards) c.iommu_type = "identity"; + CHECK(!has(diag::check(f, run), "iommu-translated")); +} + +/* ------------------------------------------------------------------ reported */ + +namespace { + +struct Argv { + std::vector store; + std::vector argv; + explicit Argv(std::initializer_list v) { + store.emplace_back("radiance"); + for (const char* s : v) store.emplace_back(s); + for (std::string& s : store) argv.push_back(s.data()); + } +}; + +} /* namespace */ + +/* EVERY OPTION IN THE TABLE REACHES THE REPORT, with a value shown and not the placeholder an + * option without a formatter gets. An option added to the table without one fails here by name. */ +TEST(every_option_in_the_table_is_reported) { + Config c; + Argv a({ "--model", "/m/x.rad" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + const std::vector rows = diag::config_rows(c); + const std::vector names = diag::config_option_names(); + CHECK_EQ(rows.size(), names.size()); + CHECK(names.size() > 80); + for (size_t i = 0; i < rows.size() && i < names.size(); ++i) { + CHECK_EQ(rows[i].flag, names[i]); + if (rows[i].value == "(not shown)") { + radtest::fail(__FILE__, __LINE__, "no value shown for " + rows[i].flag); + } + } + const std::string text = diag::render(rows, {}, diag::Facts{}, diag::RunFacts{}, {}); + for (const std::string& n : names) + if (text.find(" " + n + " ") == std::string::npos) + radtest::fail(__FILE__, __LINE__, "the report has no line for " + n); +} + +TEST(sources_and_secrets) { + setenv("RADIANCE_KERNELS", "libr4d,libref", 1); + Config c; + Argv a({ "--model", "/m/x.rad", "--tp", "2", "--api-key", "sk-very-secret-value", + "--gpu-headroom", "128" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + unsetenv("RADIANCE_KERNELS"); + std::vector rows = diag::config_rows(c); + auto row = [&](const char* f) -> const diag::ConfigRow* { + for (const diag::ConfigRow& x : rows) if (x.flag == f) return &x; + return nullptr; + }; + CHECK(row("--tp") && row("--tp")->source == "command line" && row("--tp")->value == "2"); + CHECK(row("--max-num-seqs") && row("--max-num-seqs")->source == "default"); + /* The alias reports as the option it is. */ + CHECK(row("--gpu-headroom-mib") && row("--gpu-headroom-mib")->source == "command line" && + row("--gpu-headroom-mib")->value == "128"); + CHECK(row("--kernels") && row("--kernels")->source == "environment (RADIANCE_KERNELS)" && + row("--kernels")->value == "libr4d,libref"); + CHECK(row("--api-key") && row("--api-key")->value == "set"); + + /* A DECISION SUPPLIES THE VALUE AND THE REASON; a default it resolves becomes `auto`, a given + * option keeps its source; a topic no option states is returned as derived. */ + std::vector d; + diag::decide(&d, "--num-speculative-tokens", "2", "the drafter's own depth"); + diag::decide(&d, "--tp", "2", "as given"); + diag::decide(&d, "vram split", "weights 20 GiB", "the report"); + diag::decide(&d, "--num-speculative-tokens", "3", "revised"); + CHECK_EQ(d.size(), (size_t)3); + std::vector derived; + diag::merge(&rows, d, &derived); + CHECK(row("--num-speculative-tokens")->value == "3"); + CHECK(row("--num-speculative-tokens")->source == "auto"); + CHECK(row("--num-speculative-tokens")->why == "revised"); + CHECK(row("--tp")->source == "command line"); + CHECK_EQ(derived.size(), (size_t)1); + CHECK(!derived.empty() && derived[0].key == "vram split"); + + const std::string text = diag::render(rows, derived, diag::Facts{}, diag::RunFacts{}, {}); + const std::string json = diag::to_json(rows, derived, diag::Facts{}, diag::RunFacts{}, {}); + CHECK(text.find("sk-very-secret-value") == std::string::npos); + CHECK(json.find("sk-very-secret-value") == std::string::npos); + CHECK(text.find("DERIVED") != std::string::npos); +} + +/* BYTES THAT ARE NOT UTF-8 ARE REPLACED, NOT THROWN ON. A --model path is the operator's bytes, + * and a strict serialiser would turn every /diagnostics request into a 500. */ +TEST(a_value_that_is_not_utf8_does_not_break_the_json) { + Config c; + Argv a({ "--model", "/m/caf\xe9.rad" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + c.sample_dry_seq_breakers = std::vector{ "\xff\xfe" }; + std::vector rows; + bool threw = false; + try { rows = diag::config_rows(c); } catch (...) { threw = true; } + CHECK(!threw); + diag::Facts f; + diag::CardFacts card; + card.bdf = "0000:03:00.0"; + card.name = "R9700 \xc3\x28"; + f.cards.push_back(card); + std::string out; + try { out = diag::to_json(rows, {}, f, diag::RunFacts{}, {}); } catch (...) { threw = true; } + CHECK(!threw); + const nlohmann::json j = nlohmann::json::parse(out, nullptr, false); + CHECK(!j.is_discarded()); + if (j.is_discarded()) return; + CHECK(j["configuration"][0]["value"].get() == "/m/caf\xef\xbf\xbd.rad"); +} + +/* EACH SAMPLER FIELD NAMES ITS OWN SOURCE. A generation_config.json that states a temperature and + * a top_p and nothing else supplied those two; top_k and min_p are SamplingParams' own values, + * and a reason that named the file for all four would send a reader to look for them in it. */ +TEST(sampler_defaults_carry_a_source_per_field) { + Config c; + Argv a({ "--model", "/m/x.rad", "--min-p", "0.05" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + GenSampling g; + CHECK(gen_sampling_parse(R"({"temperature": 0.6, "top_p": 0.95})", "test", &g)); + SamplingParams sp = g.onto(SamplingParams{}); + sp.min_p = c.sample_min_p; + const std::vector s = gen_sampling_sources(g, "/m/gen.json", sp, c); + auto find = [&](const char* flag) -> const GenFieldSource* { + for (const GenFieldSource& x : s) if (x.flag == flag) return &x; + return nullptr; + }; + CHECK(find("--temp") && find("--temp")->why == "from /m/gen.json" && + find("--temp")->value == "0.6"); + CHECK(find("--top-p") && find("--top-p")->why == "from /m/gen.json"); + CHECK(find("--top-k") && find("--top-k")->why.find("/m/gen.json states no top_k") == 0); + /* --min-p was given: its own row says "command line", and nothing here overrides that. */ + CHECK(!find("--min-p")); + /* No source at all: every field says the model stated nothing. */ + for (const GenFieldSource& x : gen_sampling_sources(GenSampling{}, "", SamplingParams{}, c)) + CHECK(x.why.find("the model states no sampling of its own") == 0); +} + +/* A VALUE THE SERVER RESOLVES IS RECORDED WHERE IT IS RESOLVED, not worked out again by the + * report: unresolved, the option's line says only how it will be. */ +TEST(auto_server_bounds_are_not_recomputed_by_the_report) { + Config c; + Argv a({ "--model", "/m/x.rad" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + std::vector rows = diag::config_rows(c); + for (const diag::ConfigRow& x : rows) + if (x.flag == "--http-threads" || x.flag == "--max-n" || x.flag == "--max-queued-requests") + CHECK(x.value.rfind("auto (", 0) == 0); + std::vector d, derived; + diag::decide(&d, "--http-threads", "32", "one a hardware thread, at least 4"); + diag::merge(&rows, d, &derived); + for (const diag::ConfigRow& x : rows) + if (x.flag == "--http-threads") CHECK(x.value == "32" && x.source == "auto"); +} + +TEST(the_json_carries_every_section) { + Root r; + machine(r); + const diag::Facts f = served_machine(r); + const auto found = diag::check(f, diag::RunFacts{}); + Config c; + Argv a({ "--model", "/m/x.rad" }); + CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0); + const nlohmann::json j = nlohmann::json::parse( + diag::to_json(diag::config_rows(c), {}, f, diag::RunFacts{}, found), nullptr, false); + CHECK(!j.is_discarded()); + if (j.is_discarded()) return; + CHECK(j["configuration"].is_array() && j["configuration"].size() == diag::config_option_names().size()); + CHECK(j["hardware"]["cards"].size() == 3); + CHECK(j["hardware"]["cards"][1]["link_chain"].size() == 4); + CHECK(j["hardware"]["host"]["iommu"]["mode"] == "passthrough"); + CHECK(j["findings"].size() == found.size()); + const std::string text = diag::render(diag::config_rows(c), {}, f, diag::RunFacts{}, found); + CHECK(text.find("00:01.3 16.0 GT/s x8 (max 32.0 GT/s x8)") != std::string::npos); + CHECK(text.find("WARN link-below-max") != std::string::npos); +} + +RAD_TEST_MAIN() diff --git a/tests/lfm2_golden.h b/tests/lfm2_golden.h new file mode 100644 index 00000000..86aa7768 --- /dev/null +++ b/tests/lfm2_golden.h @@ -0,0 +1,97 @@ +/* lfm2_golden.h -- GENERATED by mklfm2golden.py from transformers 5.19.0; do not edit. */ +#pragma once +#include + +static const int32_t kLfm2Patch = 16, kLfm2Merge = 2, kLfm2MinTok = 64, kLfm2MaxTok = 256; +static const int32_t kLfm2MinTiles = 2, kLfm2MaxTiles = 10, kLfm2Tile = 512, kLfm2MaxPatches = 1024; +static const double kLfm2Tolerance = 2.0; +struct GoldLfm2Size { int64_t h, w, oh, ow; int32_t large, cols, rows; }; +static const GoldLfm2Size kGoldLfm2Size[] = { + { 1, 1, 256, 256, 0, 2, 2 }, + { 40, 30, 320, 224, 0, 2, 3 }, + { 300, 500, 288, 512, 0, 3, 2 }, + { 700, 700, 512, 512, 0, 2, 2 }, + { 900, 1400, 384, 608, 1, 3, 2 }, + { 2000, 600, 928, 256, 1, 1, 3 }, + { 515, 1031, 352, 704, 0, 2, 1 }, + { 512, 1024, 352, 704, 0, 2, 1 }, + { 1080, 1920, 384, 672, 1, 4, 2 }, + { 4000, 300, 1856, 128, 1, 1, 10 }, + { 31, 4000, 32, 4000, 0, 10, 1 }, + { 777, 333, 768, 320, 0, 2, 5 }, + { 1024, 1024, 512, 512, 1, 2, 2 }, + { 1023, 2047, 352, 704, 1, 4, 2 }, + { 64, 64, 256, 256, 0, 2, 2 }, + { 100, 5000, 64, 3616, 0, 10, 1 }, + { 3000, 3000, 512, 512, 1, 3, 3 }, + { 720, 1280, 384, 672, 1, 2, 1 }, +}; +struct GoldLfm2Marker { const char* name; int32_t id; }; +static const GoldLfm2Marker kGoldLfm2Markers[] = { + { "<|image_start|>", 125009 }, + { "<|image_end|>", 125010 }, + { "<|img_thumbnail|>", 125008 }, + { "<|img_row_1_col_1|>", 124908 }, + { "<|img_row_1_col_2|>", 124909 }, + { "<|img_row_1_col_3|>", 124910 }, + { "<|img_row_1_col_4|>", 124911 }, + { "<|img_row_1_col_5|>", 124912 }, + { "<|img_row_1_col_6|>", 124913 }, + { "<|img_row_1_col_7|>", 124914 }, + { "<|img_row_1_col_8|>", 124915 }, + { "<|img_row_1_col_9|>", 124916 }, + { "<|img_row_1_col_10|>", 124917 }, + { "<|img_row_2_col_1|>", 124918 }, + { "<|img_row_2_col_2|>", 124919 }, + { "<|img_row_2_col_3|>", 124920 }, + { "<|img_row_2_col_4|>", 124921 }, + { "<|img_row_2_col_5|>", 124922 }, + { "<|img_row_3_col_1|>", 124928 }, + { "<|img_row_3_col_2|>", 124929 }, + { "<|img_row_3_col_3|>", 124930 }, + { "<|img_row_4_col_1|>", 124938 }, + { "<|img_row_4_col_2|>", 124939 }, + { "<|img_row_5_col_1|>", 124948 }, + { "<|img_row_5_col_2|>", 124949 }, + { "<|img_row_6_col_1|>", 124958 }, + { "<|img_row_7_col_1|>", 124968 }, + { "<|img_row_8_col_1|>", 124978 }, + { "<|img_row_9_col_1|>", 124988 }, + { "<|img_row_10_col_1|>", 124998 }, +}; +static const int32_t kLfm2ImageToken = 124907; +struct GoldLfm2Pic { int32_t f, h, w; int64_t cap; int32_t cols, rows, n_seg, seg0; int32_t n_ids; uint64_t ids_fnv; }; +static const GoldLfm2Pic kGoldLfm2Pics[] = { + { 0, 40, 30, 0, 1, 1, 1, 0, 72, 0xf4a13171f5dba0b2ull }, + { 1, 300, 500, 0, 1, 1, 1, 1, 146, 0x31e5951b9e177f96ull }, + { 2, 700, 700, 0, 1, 1, 1, 2, 258, 0xa3fceabcb4070e76ull }, + { 3, 900, 1400, 0, 3, 2, 7, 3, 1773, 0xe878e4810a1f66cdull }, + { 4, 2000, 600, 0, 1, 3, 4, 10, 1006, 0xed3837ea6bba64b8ull }, + { 5, 1800, 1200, 1048576, 2, 3, 7, 14, 1792, 0x68ef61a1fe0e31ddull }, + { 6, 515, 1031, 0, 1, 1, 1, 21, 244, 0x41e3b3c2daa2fccaull }, +}; +struct GoldLfm2Seg { int32_t h, w; uint64_t fnv; }; +static const GoldLfm2Seg kGoldLfm2Segs[] = { + { 20, 14, 0xde350f8ffaae060dull }, + { 18, 32, 0x1e897c3d485cf756ull }, + { 32, 32, 0x275822a4d8e5c314ull }, + { 32, 32, 0xd5c661c14ae1062full }, + { 32, 32, 0x1deb651bff0aa1fbull }, + { 32, 32, 0x571cdfffc3d7bda4ull }, + { 32, 32, 0xc4a9e6d1acc5e8a7ull }, + { 32, 32, 0x64bc191eced1db77ull }, + { 32, 32, 0x5d9b1cfc1f6748b8ull }, + { 24, 38, 0x803957c943657915ull }, + { 32, 32, 0xb609a02f3c340c8full }, + { 32, 32, 0xed17e14b9740a2c9ull }, + { 32, 32, 0x1a6114e52cc829fdull }, + { 58, 16, 0x595479cd72f7ff69ull }, + { 32, 32, 0xfaaa7e21c05b8325ull }, + { 32, 32, 0x851b719d2331a839ull }, + { 32, 32, 0xf6e8f07ecad1d04bull }, + { 32, 32, 0xb4cc3efd44779290ull }, + { 32, 32, 0xd935c251cfcbccf4ull }, + { 32, 32, 0x7ca1535ecf888407ull }, + { 38, 26, 0xeaf5a49573123b49ull }, + { 22, 44, 0x072680b110281b00ull }, +}; diff --git a/tests/mklfm2golden.py b/tests/mklfm2golden.py new file mode 100644 index 00000000..254ace51 --- /dev/null +++ b/tests/mklfm2golden.py @@ -0,0 +1,107 @@ +"""mklfm2golden.py MODELDIR OUT.h -- goldens for the LFM2-VL processor in tests/mm_test.cpp, every +number from transformers' own Lfm2VlProcessor as MODELDIR's processor_config.json sets it up: +smart_resize, the tile grid and the too-large test, and whole pictures -- each segment's patches +and the tokens that replace the picture's -- including one scaled down first by PIL's +bicubic to an area cap, as d1's runner does before the processor.""" +import sys, math, json +import numpy as np, torch +from PIL import Image +from transformers import AutoProcessor + +model_dir, out = sys.argv[1], sys.argv[2] +P = AutoProcessor.from_pretrained(model_dir) +IP = P.image_processor +tok = P.tokenizer +L = ["/* lfm2_golden.h -- GENERATED by mklfm2golden.py from transformers %s; do not edit. */" + % __import__("transformers").__version__, "#pragma once", "#include ", ""] +cfg = dict(downsample_factor=IP.downsample_factor, min_image_tokens=IP.min_image_tokens, + max_image_tokens=IP.max_image_tokens, encoder_patch_size=IP.encoder_patch_size) +L.append(f"static const int32_t kLfm2Patch = {IP.encoder_patch_size}, kLfm2Merge = {IP.downsample_factor}, " + f"kLfm2MinTok = {IP.min_image_tokens}, kLfm2MaxTok = {IP.max_image_tokens};") +L.append(f"static const int32_t kLfm2MinTiles = {IP.min_tiles}, kLfm2MaxTiles = {IP.max_tiles}, " + f"kLfm2Tile = {IP.tile_size}, kLfm2MaxPatches = {IP.max_num_patches};") +L.append(f"static const double kLfm2Tolerance = {IP.max_pixels_tolerance!r};") + +# ---- smart_resize (returns width, height) and the tiling decision +sizes = [(1, 1), (40, 30), (300, 500), (700, 700), (900, 1400), (2000, 600), (515, 1031), (512, 1024), + (1080, 1920), (4000, 300), (31, 4000), (777, 333), (1024, 1024), (1023, 2047), (64, 64), + (100, 5000), (3000, 3000), (720, 1280)] +L.append("struct GoldLfm2Size { int64_t h, w, oh, ow; int32_t large, cols, rows; };") +L.append("static const GoldLfm2Size kGoldLfm2Size[] = {") +for h, w in sizes: + ow, oh = IP.smart_resize(height=h, width=w, **cfg) + large = IP._is_image_too_large(height=h, width=w, max_image_tokens=IP.max_image_tokens, + encoder_patch_size=IP.encoder_patch_size, + downsample_factor=IP.downsample_factor, + max_pixels_tolerance=IP.max_pixels_tolerance) + gw, gh, *_ = IP._get_grid_layout(h, w, min_tiles=IP.min_tiles, max_tiles=IP.max_tiles, + tile_size=IP.tile_size) + L.append(f" {{ {h}, {w}, {oh}, {ow}, {int(large)}, {gw}, {gh} }},") +L.append("};") + +# ---- the markers, by name, for a token_id lookup with no tokenizer behind it +names = ["<|image_start|>", "<|image_end|>", "<|img_thumbnail|>"] +names += [f"<|img_row_{r}_col_{c}|>" for r in range(1, IP.max_tiles + 1) for c in range(1, IP.max_tiles + 1) + if r * c <= IP.max_tiles] +L.append("struct GoldLfm2Marker { const char* name; int32_t id; };") +L.append("static const GoldLfm2Marker kGoldLfm2Markers[] = {") +for n in names: + L.append(f' {{ "{n}", {tok.convert_tokens_to_ids(n)} }},') +L.append("};") +L.append(f"static const int32_t kLfm2ImageToken = {P.image_token_id};") + +# ---- whole pictures: splitmix pixels (as mkgolden.py's), optionally area-capped by PIL first +def frame(f, h, w): + y, x, c = np.meshgrid(np.arange(h, dtype=np.uint64), np.arange(w, dtype=np.uint64), + np.arange(3, dtype=np.uint64), indexing="ij") + with np.errstate(over="ignore"): + z = (np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9) + + x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345)) + z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9) + z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB) + z = z ^ (z >> np.uint64(31)) + return (z & np.uint64(255)).astype(np.uint8) +def fnv(b): + a = np.frombuffer(b, dtype=np.uint8).astype(np.uint64) + h = 0xcbf29ce484222325 + for v in a.tolist(): + h = ((h ^ v) * 0x100000001b3) & (2**64 - 1) + return h +def cap(im, max_pixels): # d1's runner, cap_pixels + w, h = im.size + if not max_pixels or w * h <= max_pixels: + return im + s = math.sqrt(max_pixels / (w * h)) + return im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.Resampling.BICUBIC) + +pics = [(0, 40, 30, 0), (1, 300, 500, 0), (2, 700, 700, 0), (3, 900, 1400, 0), (4, 2000, 600, 0), + (5, 1800, 1200, 1048576), (6, 515, 1031, 0)] +segs, idsall = [], [] +L.append("struct GoldLfm2Pic { int32_t f, h, w; int64_t cap; int32_t cols, rows, n_seg, seg0; " + "int32_t n_ids; uint64_t ids_fnv; };") +rows = [] +for f, h, w, mp in pics: + im = cap(Image.fromarray(frame(f, h, w)), mp) + o = P(text=[""], images=[[im]], return_tensors="pt", add_special_tokens=False) + ids = o["input_ids"][0].to(torch.int32).numpy() + mask = o["pixel_attention_mask"] + shapes = o["spatial_shapes"].tolist() + rc = IP(images=[[im]], return_row_col_info=True) + pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16) + seg0 = len(segs) + for s, (gh, gw) in enumerate(shapes): + n = int(mask[s].sum()) + assert n == gh * gw + segs.append((gh, gw, fnv(pv[s, :n].tobytes()))) + rows.append(f" {{ {f}, {h}, {w}, {mp}, {rc['image_cols'][0]}, {rc['image_rows'][0]}, {len(shapes)}, {seg0}, {len(ids)}, " + f"0x{fnv(ids.astype(' @@ -409,4 +411,111 @@ TEST(the_audio_front_end_is_the_references) { CHECK_EQ(it->expand.size(), (size_t)2); } +namespace { + +/* LiquidAI d1-3B's processor_config.json, as a container converted from it states it. */ +VisionConfig lfm2_cfg() { + VisionConfig c; + c.family = Family::Lfm2; + c.patch = kLfm2Patch; + c.merge = kLfm2Merge; + c.temporal = 1; + const int64_t f2 = (int64_t)c.factor() * c.factor(); + c.image_min_pixels = c.video_min_pixels = kLfm2MinTok * f2; + c.image_max_pixels = c.video_max_pixels = kLfm2MaxTok * f2; + c.min_tiles = kLfm2MinTiles; + c.max_tiles = kLfm2MaxTiles; + c.tile = kLfm2Tile; + c.use_thumbnail = true; + c.max_pixels_tolerance = kLfm2Tolerance; + c.max_segment_patches = kLfm2MaxPatches; + c.tok_image = kLfm2ImageToken; + c.max_patches = 4096; + return c; +} + +int32_t lfm2_marker(const std::string& name) { + for (const GoldLfm2Marker& m : kGoldLfm2Markers) + if (name == m.name) return m.id; + return -1; +} + +} /* namespace */ + +TEST(lfm2_sizes_and_tiles_are_the_references) { + for (const GoldLfm2Size& g : kGoldLfm2Size) { + int64_t oh = 0, ow = 0; + lfm2_size(g.h, g.w, kLfm2Patch * kLfm2Merge, (int64_t)kLfm2MinTok * 1024, + (int64_t)kLfm2MaxTok * 1024, &oh, &ow); + int32_t cols = 0, rows = 0; + lfm2_grid(g.h, g.w, kLfm2MinTiles, kLfm2MaxTiles, kLfm2Tile, &cols, &rows); + const bool large = lfm2_too_large(g.h, g.w, kLfm2Patch, kLfm2Patch * kLfm2Merge, + (int64_t)kLfm2MaxTok * 1024, kLfm2Tolerance); + if (oh != g.oh || ow != g.ow || cols != g.cols || rows != g.rows || large != (g.large != 0)) + std::fprintf(stderr, " %lld x %lld: %lld x %lld, %d x %d tiles, large %d; reference " + "%lld x %lld, %d x %d, %d\n", (long long)g.h, (long long)g.w, (long long)oh, + (long long)ow, cols, rows, (int)large, (long long)g.oh, (long long)g.ow, + g.cols, g.rows, g.large); + CHECK_EQ(oh, g.oh); + CHECK_EQ(ow, g.ow); + CHECK_EQ(cols, g.cols); + CHECK_EQ(rows, g.rows); + CHECK_EQ(large, g.large != 0); + } +} + +/* Whole pictures, small to tiled, one area-capped first as d1's runner caps it: every segment's + * size and patches, and the tokens that replace the picture. The processor keeps a segment's + * patches in merge-block order; the reference's are row-major, so they are put back in that order + * (Item::coords) before the hash. */ +TEST(lfm2_pictures_are_the_references) { + Processor p; + REQUIRE_EQ(p.init(lfm2_cfg(), [](const std::string&) { return std::vector{}; }, + lfm2_marker), RAD_OK); + for (const GoldLfm2Pic& g : kGoldLfm2Pics) { + Frame f = frame(g.f, g.h, g.w); + if (g.cap > 0) { + Frame capped; + cap_area(f, g.cap, &capped); + f = std::move(capped); + } + std::shared_ptr it; + std::string why; + CHECK_OK(p.image_from(f, &it, &why)); + REQUIRE(it != nullptr); + REQUIRE_EQ(it->n_seg, g.n_seg); + const int64_t pd = it->patch_dim; + REQUIRE_EQ(pd, (int64_t)3 * kLfm2Patch * kLfm2Patch); + for (int32_t s = 0; s < it->n_seg; ++s) { + const GoldLfm2Seg& gs = kGoldLfm2Segs[g.seg0 + s]; + CHECK_EQ(it->seg_h(s), gs.h); + CHECK_EQ(it->seg_w(s), gs.w); + const int64_t p0 = it->patch_at(s), np = it->patch_at(s + 1) - p0; + REQUIRE_EQ(np, (int64_t)gs.h * gs.w); + std::vector planes((size_t)(4 * np)); + it->coords(p0, np, planes.data()); + std::vector rowmajor((size_t)(np * pd)); + for (int64_t k = 0; k < np; ++k) { + const int64_t at = (int64_t)planes[(size_t)k] * gs.w + planes[(size_t)(np + k)]; + std::copy_n(it->pixels.data() + (p0 + k) * pd, pd, rowmajor.data() + at * pd); + } + if (fnv(rowmajor) != gs.fnv) + std::fprintf(stderr, " picture %d x %d, segment %d of %d (%d x %d): patches differ\n", + g.h, g.w, s, it->n_seg, gs.h, gs.w); + CHECK_EQ(fnv(rowmajor), gs.fnv); + } + uint64_t h = 0xcbf29ce484222325ull; + for (int32_t id : it->expand) + for (int b = 0; b < 4; ++b) h = (h ^ (uint8_t)((uint32_t)id >> (8 * b))) * 0x100000001b3ull; + CHECK_EQ((int32_t)it->expand.size(), g.n_ids); + CHECK_EQ(h, g.ids_fnv); + /* Each run of placeholders starts where Item::seg_at says, one merged row a token. */ + REQUIRE_EQ(it->seg_at.size(), (size_t)it->n_seg); + for (int32_t s = 0; s < it->n_seg; ++s) { + const int64_t at = it->seg_at[(size_t)s], n = it->row_at(s + 1) - it->row_at(s); + for (int64_t k = 0; k < n; ++k) CHECK_EQ(it->expand[(size_t)(at + k)], kLfm2ImageToken); + } + } +} + RAD_TEST_MAIN() diff --git a/tests/place_test.cpp b/tests/place_test.cpp index f2c0bb3d..0c8064e0 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -33,6 +33,7 @@ #include "place/planner.h" #include +#include #include #include #include @@ -91,6 +92,13 @@ int rad_memset_async(void* d, int v, int64_t n, RadStream) { if (n > 0) std::memset(d, v, (size_t)n); return RAD_OK; } +int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) { + for (int i = 0; i < n; ++i) + if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes); + return RAD_OK; +} +int rad_link_hold(RadStream, int) { return RAD_OK; } +void* rad_link_gate(RadStream) { return nullptr; } const char* rad_dev_last_error(void) { return ""; } } /* extern "C" */ #endif /* RAD_PLACE_TEST_FAKE_DEVICE */ @@ -766,11 +774,35 @@ TEST(heat_does_not_thrash_on_an_alternating_pattern) { CHECK(unguarded > 100); } +/* A PREFILL CHUNK IS CREDITED AS ONE CAPPED HISTOGRAM. Ten times the cap's selections credit a + * tenth of each count, so the experts keep their order and one chunk cannot outweigh the decode + * steps around it; a histogram under the cap is credited in full. */ +TEST(heat_caps_what_one_histogram_credits) { + HeatFixture hf; + HeatEngine h; + HeatParams hp; + hp.credit_cap = 512.0f; + CHECK_OK(h.init(hf.plan, hp)); + const int32_t a = hf.unit_of_expert(4), b = hf.unit_of_expert(5), c = hf.unit_of_expert(6); + + const int32_t big_ids[2] = {4, 5}; + const int32_t big[2] = {4000, 1120}; + h.observe_ids(0, big_ids, big, 2); + CHECK(std::fabs(h.heat(a) - 400.0f) < 1e-3f); + CHECK(std::fabs(h.heat(b) - 112.0f) < 1e-3f); + + const int32_t small_ids[1] = {6}; + const int32_t small[1] = {12}; + h.observe_ids(0, small_ids, small, 1); + CHECK_EQ(h.heat(c), 12.0f); + CHECK(std::fabs(h.heat(a) - 400.0f * hp.decay) < 1e-3f); +} + TEST(heat_respects_the_move_budget) { HeatFixture hf; HeatEngine h; HeatParams hp; - hp.moves_per_dispatch = 3; + hp.moves_per_step = 3; hp.min_gain = 0.5f; CHECK_OK(h.init(hf.plan, hp)); @@ -824,7 +856,7 @@ TEST(heat_step_proposes_exactly_what_repeated_picks_would) { int agreed = 0; for (int trial = 0; trial < 400; ++trial) { HeatParams hp; - hp.moves_per_dispatch = 1 + (int)rnd(8); + hp.moves_per_step = 1 + (int)rnd(8); hp.min_gain = (float)rnd(3); hp.hysteresis = 1.0f + 0.25f * (float)rnd(3); HeatEngine h; @@ -845,7 +877,7 @@ TEST(heat_step_proposes_exactly_what_repeated_picks_would) { HeatEngine ref = h; std::vector want; - for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) { + for (int mv = 0; mv < hp.moves_per_step; ++mv) { Swap sw; if (!ref.pick(&sw)) break; ref.set_busy(sw.promote, true); @@ -896,7 +928,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) { int agreed = 0, crossed = 0, proposed = 0; for (int trial = 0; trial < 400; ++trial) { HeatParams hp; - hp.moves_per_dispatch = 1 + (int)rnd(8); + hp.moves_per_step = 1 + (int)rnd(8); hp.min_gain = (float)rnd(3); hp.hysteresis = 1.0f + 0.25f * (float)rnd(3); HeatEngine h; @@ -920,7 +952,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) { } for (int k = 0; k < 5; ++k) h.set_busy((int32_t)rnd((uint32_t)n_unit), true); - /* The reference: repeated picks, each class taking at most `moves_per_dispatch` -- the + /* The reference: repeated picks, each class taking at most `moves_per_step` -- the * budget is per class. A pick from a class already at its budget is set aside, busy in * the copy only. */ HeatEngine ref = h; @@ -933,7 +965,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) { ref.set_busy(sw.promote, true); ref.set_busy(sw.demote, true); int& n = per[(size_t)plan.units[(size_t)sw.promote].slab_class]; - if (n >= hp.moves_per_dispatch) { + if (n >= hp.moves_per_step) { aside[(size_t)sw.promote] = aside[(size_t)sw.demote] = 1; continue; } @@ -987,7 +1019,7 @@ TEST(heat_step_agrees_with_picks_over_a_run_of_dispatches) { auto rnd = [&](uint32_t n) { x ^= x << 13; x ^= x >> 17; x ^= x << 5; return x % n; }; for (int run = 0; run < 20; ++run) { HeatParams hp; - hp.moves_per_dispatch = 1 + (int)rnd(3); + hp.moves_per_step = 1 + (int)rnd(3); hp.min_gain = 1.0f + (float)rnd(4); hp.hysteresis = 1.0f + 0.25f * (float)rnd(4); HeatEngine h; @@ -1005,7 +1037,7 @@ TEST(heat_step_agrees_with_picks_over_a_run_of_dispatches) { } HeatEngine ref = h; std::vector want; - for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) { + for (int mv = 0; mv < hp.moves_per_step; ++mv) { Swap sw; if (!ref.pick(&sw)) break; ref.set_busy(sw.promote, true); @@ -1075,7 +1107,7 @@ TEST(heat_credits_and_prices_every_layout_the_plan_can_have) { const int32_t n_unit = (int32_t)plan.units.size(); HeatParams hp; - hp.moves_per_dispatch = 3; + hp.moves_per_step = 3; HeatEngine h; CHECK_OK(h.init(plan, hp)); CHECK(h.enabled()); @@ -1118,7 +1150,7 @@ TEST(heat_credits_and_prices_every_layout_the_plan_can_have) { HeatEngine ref = h; std::vector expect; - for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) { + for (int mv = 0; mv < hp.moves_per_step; ++mv) { Swap sw; if (!ref.pick(&sw)) break; ref.set_busy(sw.promote, true); @@ -1249,6 +1281,23 @@ TEST(slot_pool_hands_out_and_takes_back) { CHECK(s.empty()); } +/* A TAKE RESTRICTED TO THE SLOTS A CALLER WANTS -- the lowest of them -- leaves every other free + * slot free and still handed out lowest first (Mover::pool_slot_for keeps a layer's pool slots + * together with it). */ +TEST(a_slot_pool_takes_the_lowest_slot_a_predicate_wants) { + SlotPool s; + s.init(8, 64); + for (int64_t k : {1, 3, 4, 6, 7}) s.add_free(k); + CHECK_EQ(s.take_where([](int64_t k) { return k % 3 == 0; }), (int64_t)3); + CHECK_EQ(s.take_where([](int64_t k) { return k == 5; }), (int64_t)-1); /* not free */ + CHECK_EQ(s.n_free(), (int64_t)4); + CHECK_EQ(s.take(), (int64_t)1); + CHECK_EQ(s.take_where([](int64_t k) { return k > 4; }), (int64_t)6); + CHECK_EQ(s.take(), (int64_t)4); + CHECK_EQ(s.take(), (int64_t)7); + CHECK(s.empty()); +} + TEST(a_slot_pool_grows_only_into_the_capacity_it_was_given) { SlotPool s; s.init(2, 64, 5); @@ -1650,11 +1699,17 @@ struct LoanRig { ComputeWork work; int d = 0; int32_t planned = 0; + /* None by default: these tests are about the loan's mechanics, and on a slab this small the + * production count would leave most of the loan empty. The turnover test sets its own. */ + int turnover = 0; + + explicit LoanRig(int n_expert = 8) : hf(n_expert) {} int build() { HeatParams hp; RAD_TRY(h.init(hf.plan, hp)); MoverConfig mc; + mc.turnover_slots = turnover; RAD_TRY(m.init(hf.f.prog, hf.plan, mc)); RAD_TRY(rad_stream_create(&compute, 0)); RAD_TRY(m.bind_compute_stream(compute)); @@ -1711,12 +1766,13 @@ TEST(the_lent_slots_hold_nothing_until_a_loan_covers_them) { } /* A LENT SLOT LEFT EMPTY IS VRAM BOUGHT AND WASTED ON EVERY STEP, so a loan is filled in the - * dispatch it arrives in -- every slot at once, hottest units first -- and not a few units a step. */ + * dispatch it arrives in -- every slot past the turnover slots at once, hottest units first -- and + * not a few units a step. */ TEST(every_lent_slot_is_filled_in_one_dispatch) { LoanRig r; CHECK_OK(r.build()); const int64_t slots = r.m.flex_capacity() / r.hf.plan.classes[0].stride; - const int64_t expect = std::min(slots, r.pooled()); + const int64_t expect = std::min(slots - r.m.turnover_slots(), r.pooled()); CHECK(expect > 1); CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); @@ -1752,6 +1808,194 @@ TEST(every_lent_slot_is_filled_in_one_dispatch) { CHECK(at[k] - at[k - 1] >= r.hf.plan.classes[0].stride); } +/* THE TURNOVER SLOTS STAY FREE, AND A SHRINKING LOAN DOES NOT TAKE THEM FOR GOOD. The fill stops + * that many slots short of the loan so the engine's swaps have somewhere to land. The free slots + * are the loan's top, which is what a cache that wants memory back takes first; the mover then + * rebuilds them by dropping the coldest lent units -- each still has its host copy, so nothing + * crosses the link -- rather than going without until the loan grows back. */ +TEST(the_turnover_slots_stay_free_and_are_rebuilt_by_drops) { + LoanRig r(24); + r.turnover = 2; + CHECK_OK(r.build()); + CHECK_EQ(r.m.turnover_slots(), (int64_t)2); + const int64_t slots = r.m.flex_capacity() / r.hf.plan.classes[0].stride; + CHECK(r.pooled() > slots); /* more to fill than there is room: only the reserve stops it */ + + CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); + for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + const int32_t full = resident_count(r.h, r.hf.plan); + CHECK_EQ(full, r.planned + (int32_t)(slots - 2)); + CHECK_EQ(r.m.flex_used_bytes(), (slots - 2) * r.hf.plan.classes[0].stride); + + /* The fill packs from the bottom, so the free slots are the loan's top: a loan cut to what is + * held takes exactly them, and the next dispatch drops two lent units to free two more. */ + const int64_t held = r.m.loan_held(Mover::kLendKV); + CHECK(held < Loan::kAll); + const uint64_t d2h = r.m.stats().d2h_bytes; + CHECK_OK(r.m.set_loan(Mover::kLendKV, held)); + for (Deadline dl; (r.m.stats().dropped < 2 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + for (int k = 0; k < 4; ++k) CHECK_OK(r.dispatch()); + CHECK_EQ(r.m.stats().dropped, (uint64_t)2); + CHECK_EQ(r.m.stats().d2h_bytes, d2h); /* nothing crossed the link */ + CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2); + CHECK_EQ(r.m.flex_used_bytes(), (slots - 4) * r.hf.plan.classes[0].stride); + + /* A STEP THAT STAGES FILLS THEM: it swaps nothing, and a unit left out is one its stager + * copies. The next ordinary step drops the two coldest back out. */ + CHECK_OK(r.m.begin_dispatch(r.d++, &r.h)); + r.work.run(r.compute); + CHECK_OK(r.m.balance(&r.h, /*turnover=*/false)); + for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) { + CHECK_OK(r.m.begin_dispatch(r.d++, &r.h)); + r.work.run(r.compute); + CHECK_OK(r.m.balance(&r.h, false)); + } + CHECK_EQ(resident_count(r.h, r.hf.plan), full); + for (Deadline dl; (r.m.stats().dropped < 4 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2); + CHECK_EQ(r.m.stats().d2h_bytes, d2h); + + /* HELD, AN IDLE TICK FILLS THEM as a staged step does; released, the next one drops them. */ + r.m.hold_turnover(true); + for (Deadline dl; (resident_count(r.h, r.hf.plan) < full || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.m.idle_tick(&r.h)); + CHECK_EQ(resident_count(r.h, r.hf.plan), full); + r.m.hold_turnover(false); + for (Deadline dl; (r.m.stats().dropped < 6 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.m.idle_tick(&r.h)); + CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2); + CHECK_EQ(r.m.stats().d2h_bytes, d2h); +} + +namespace { +/* Every weight of every unit stamped with its own bytes, through the device's copies so the same + * test runs on a card, and read back from wherever the residency table says it is now. */ +uint8_t stamp_byte(rad_weight w, size_t i) { + uint32_t v = (uint32_t)w * 0x9E3779B1u ^ (uint32_t)i * 0x85EBCA6Bu; + v ^= v >> 15; v *= 0x2C1B3C6Du; v ^= v >> 12; v *= 0x297A2D39u; v ^= v >> 15; + return (uint8_t)v; +} +int stamp_units(LoanRig& r, bool check, int* bad) { + RadStream s = nullptr; + RAD_TRY(rad_stream_create(&s, 0)); + std::vector buf; + for (const MoveUnit& mu : r.hf.plan.units) + for (rad_weight w : mu.weights) { + const size_t n = (size_t)r.hf.f.prog.weights[w].logical_bytes; + void* at = r.m.residency()->lookup(w)->ptr; + buf.resize(n); + if (check) { + RAD_TRY(rad_memcpy_async(buf.data(), at, (int64_t)n, s)); + RAD_TRY(rad_stream_sync(s)); + for (size_t i = 0; i < n; ++i) + if (buf[i] != stamp_byte(w, i)) { ++*bad; break; } + } else { + for (size_t i = 0; i < n; ++i) buf[i] = stamp_byte(w, i); + RAD_TRY(rad_memcpy_async(at, buf.data(), (int64_t)n, s)); + RAD_TRY(rad_stream_sync(s)); + } + } + rad_stream_destroy(s); + return RAD_OK; +} +/* A full loan, every unit stamped, then one swap whose budgeted victim finds the pool full: the + * promotion lands in a working slot and the victim takes the host copy of a unit in a lent slot. */ +int donate_once(LoanRig& r, bool held = false) { + RAD_TRY(stamp_units(r, false, nullptr)); + RAD_TRY(r.m.set_loan(Mover::kLendKV, Loan::kAll)); + for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + RAD_TRY(r.dispatch()); + int32_t hot = -1, cold = -1; + for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) { + if (!r.hf.plan.units[(size_t)u].movable) continue; + if (hot < 0 && r.h.tier(u) != Tier::VRAM) hot = u; + if (cold < 0 && r.h.tier(u) == Tier::VRAM && !r.loan.inside(r.addr(u))) cold = u; + } + if (hot < 0 || cold < 0) return RAD_E_STATE; + Swap sw; + sw.promote = hot; + sw.demote = cold; + r.h.set_busy(hot, true); + r.h.set_busy(cold, true); + r.m.hold_turnover(held); + RAD_TRY(r.m.issue(sw, &r.h)); + for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) RAD_TRY(r.dispatch()); + if (held) return r.h.tier(hot) == Tier::VRAM && r.h.tier(cold) == Tier::VRAM ? RAD_OK : RAD_E_STATE; + return r.h.tier(hot) == Tier::VRAM && r.h.tier(cold) != Tier::VRAM ? RAD_OK : RAD_E_STATE; +} +} /* namespace */ + +/* A BUDGETED VICTIM WITH NO POOL SLOT TO GO TO TAKES A LENT UNIT'S HOST COPY (Mover::donor_slot): + * the pool is sized to the units that live in it, so it has none free here, and without the + * donation the budgeted range would turn over only as fast as its working slots come round. A + * recall then moves the donor -- it has no host copy to drop to -- and every unit's bytes are + * where its table entry says, throughout. */ +TEST(a_budgeted_victim_takes_a_lent_units_host_copy_and_a_recall_moves_the_donor) { + LoanRig r(24); + r.turnover = 2; + CHECK_OK(r.build()); + CHECK_OK(donate_once(r)); + CHECK_EQ(r.m.stats().donated, (uint64_t)1); + CHECK_EQ(r.m.stats().starved_pool, (uint64_t)0); + int bad = 0; + CHECK_OK(stamp_units(r, true, &bad)); + CHECK_EQ(bad, 0); + + CHECK_OK(r.m.reclaim(Mover::kLendKV, 0, &r.h)); + CHECK_EQ(r.m.stats().relocated, (uint64_t)1); + CHECK_EQ(r.m.loan_held(Mover::kLendKV), (int64_t)0); + for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) + CHECK(!r.loan.inside(r.addr(u))); + /* The donor kept its place in VRAM: a working slot was free for it. */ + CHECK_EQ(resident_count(r.h, r.hf.plan), r.planned + 1); + CHECK_OK(stamp_units(r, true, &bad)); + CHECK_EQ(bad, 0); +} + +/* NO DONATION WHILE THE TURNOVER SLOTS ARE HELD -- through a prompt and the steps right after it: + * the demotion is starved as it was before donation, and the budgeted victim stays. */ +TEST(a_held_turnover_takes_no_host_copy) { + LoanRig r(24); + r.turnover = 2; + CHECK_OK(r.build()); + CHECK_OK(donate_once(r, /*held=*/true)); + CHECK_EQ(r.m.stats().donated, (uint64_t)0); + CHECK(r.m.stats().starved_pool >= 1); + int bad = 0; + CHECK_OK(stamp_units(r, true, &bad)); + CHECK_EQ(bad, 0); +} + +/* A LOAN THAT SHRINKS UNDER A DONOR moves it out before the slot is given back (balance's sweep): + * into the budgeted slot its victim left, a copy inside the card, and the shrink completes once + * that lands. The working slot it took is rebuilt the usual way, by demoting the coldest budgeted + * unit, and every unit's bytes are where its table entry says throughout. */ +TEST(a_shrinking_loan_moves_a_donor_out_before_its_slot_is_given_back) { + LoanRig r(24); + r.turnover = 2; + CHECK_OK(r.build()); + CHECK_OK(donate_once(r)); + CHECK_EQ(r.m.stats().donated, (uint64_t)1); + const uint64_t d2h = r.m.stats().d2h_bytes; + + CHECK_OK(r.m.set_loan(Mover::kLendKV, 0)); + for (Deadline dl; (r.m.loan_held(Mover::kLendKV) > 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + CHECK_EQ(r.m.loan_held(Mover::kLendKV), (int64_t)0); + CHECK_EQ(r.m.flex_used_bytes(), (int64_t)0); + CHECK_EQ(r.m.stats().relocated, (uint64_t)1); + CHECK_EQ(r.m.stats().d2h_bytes - d2h, (uint64_t)r.hf.plan.classes[0].stride); + CHECK_EQ(resident_count(r.h, r.hf.plan), r.planned); + for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) + CHECK(!r.loan.inside(r.addr(u))); + int bad = 0; + CHECK_OK(stamp_units(r, true, &bad)); + CHECK_EQ(bad, 0); +} + /* A UNIT IN A LENT SLOT KEEPS ITS HOST COPY, so giving the slot back is a change of address and * not a copy across the link. */ TEST(a_shrinking_loan_drops_units_without_copying_them) { @@ -1980,7 +2224,8 @@ TEST(mover_prefetches_staged_units_against_the_declared_order) { /* A ROUTED LAYER'S POOLED UNITS, STAGED FOR ONE PASS (Mover::stage_units). Each copied unit's * weights are published at the copy, settled -- the caller orders their readers with one wait -- * and hold the pool slot's bytes; a unit the buffer has no room for keeps its pool address and is - * counted; a resident unit is never copied; and unstaging publishes the pool addresses again. */ + * counted; neighbouring pool slots share a copy; a resident unit is never copied; and unstaging + * publishes the pool addresses again. */ TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) { HeatFixture hf; Mover m; @@ -2017,6 +2262,19 @@ TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) { CHECK_EQ(m.stats().staged_units, (uint64_t)staged.size()); CHECK_EQ(m.stats().stage_layers, (uint64_t)1); + /* Units on neighbouring pool slots go as one copy, so the copies are the runs of the staged + * units' pool addresses -- fewer than the units, since a fresh pool hands slots out in order. */ + uint64_t runs = 0; + const char* run_end = nullptr; + for (int32_t u : staged) { + const MoveUnit& mu = hf.plan.units[(size_t)u]; + const char* slot = (const char*)before[mu.weights[0]] - mu.offset[0]; + if (slot != run_end) ++runs; + run_end = slot + each; + } + CHECK_EQ(m.stats().stage_copies, runs); + CHECK(runs < (uint64_t)staged.size()); + /* The copies are on the mover's stream: on the host backend a worker thread runs them. */ CHECK_OK(rad_stream_sync(m.transfer_stream())); std::vector is_staged(hf.plan.units.size(), 0); @@ -2048,15 +2306,16 @@ TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) { rad_stream_destroy(compute); } -/* THE PREFILL STAGER'S ORDER over a pass of two routed layers: the first layer is staged at the - * pass's first op, the second at the first layer's first op, each layer is published back at its - * pool slots once the next layer starts, and nothing is staged in a pass it did not arm for. +/* THE PREFILL STAGER'S ORDER over a pass of two routed layers: at the pass's first op the first + * layer goes out and, with room left in the ring, the second behind it; each layer is published + * back at its pool slots once the next layer starts; and nothing is staged in a pass it did not + * arm for. * * NOT AT ITS OWN LAST OP. A step longer than the MoE block's pass of rows issues a layer's ops once * per pass, so its last op runs again; released at the first run, the second would read copies - * the mover is already overwriting with the layer two on, and every token past the first pass of - * a step would be garbage. */ -TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_starts) { + * the mover is already overwriting with a layer further on, and every token past the first pass + * of a step would be garbage. */ +TEST(the_stager_stages_ahead_and_releases_each_layer_when_the_next_starts) { Fixture f; const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); f.op("embed", {emb}, false); @@ -2103,9 +2362,12 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_ const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT); const int64_t half = each * 8; std::vector region((size_t)(2 * half)); - auto in_buf = [&](rad_weight w, int b) { - const char* p = (const char*)m.residency()->lookup(w)->ptr; - return p >= region.data() + b * half && p < region.data() + (b + 1) * half; + auto in_ring = [&](const std::vector& ws) { + for (rad_weight w : ws) { + const char* p = (const char*)m.residency()->lookup(w)->ptr; + if (p < region.data() || p >= region.data() + 2 * half) return false; + } + return true; }; auto at_home = [&](const std::vector& ws) { for (rad_weight w : ws) if (m.residency()->lookup(w)->ptr != home[w]) return false; @@ -2116,6 +2378,7 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_ CHECK_OK(st.init(f.prog, plan, &m, region.data(), 2 * half, 64)); REQUIRE(st.enabled()); CHECK_EQ(st.n_layers(), (size_t)2); + CHECK_EQ(st.ring_bytes(), 2 * half); RadBatch b{}; b.n_tok = 8; @@ -2128,38 +2391,39 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_ CHECK(st.begin_pass(&b)); bool resync = false; - CHECK_OK(st.before_op(0, compute, &resync)); /* embed: the first layer goes out */ + CHECK_OK(st.before_op(0, compute, &resync)); /* embed: both layers go out */ CHECK(resync); - for (rad_weight w : p0) CHECK(in_buf(w, 0)); - CHECK(at_home(p1)); + CHECK(in_ring(p0)); + CHECK(in_ring(p1)); CHECK_OK(st.after_op(0, compute)); CHECK_OK(st.before_op(1, compute, &resync)); /* attn0: nothing */ CHECK(!resync); - CHECK_OK(st.before_op(2, compute, &resync)); /* moe0: the second layer goes out */ - CHECK(resync); - for (rad_weight w : p1) CHECK(in_buf(w, 1)); - for (rad_weight w : p0) CHECK(in_buf(w, 0)); + CHECK_OK(st.before_op(2, compute, &resync)); /* moe0: nothing left to stage */ + CHECK(!resync); + CHECK(in_ring(p0)); + CHECK(in_ring(p1)); CHECK_OK(st.after_op(2, compute)); /* moe0 is layer 0's last op... */ - for (rad_weight w : p0) CHECK(in_buf(w, 0)); + CHECK(in_ring(p0)); CHECK_OK(st.before_op(2, compute, &resync)); /* ...and runs again for the next rows */ - for (rad_weight w : p0) CHECK(in_buf(w, 0)); + CHECK(in_ring(p0)); CHECK_OK(st.after_op(2, compute)); - for (rad_weight w : p0) CHECK(in_buf(w, 0)); - for (rad_weight w : p1) CHECK(in_buf(w, 1)); + CHECK(in_ring(p0)); + CHECK(in_ring(p1)); CHECK_OK(st.before_op(3, compute, &resync)); /* attn1 */ - for (rad_weight w : p0) CHECK(in_buf(w, 0)); + CHECK(in_ring(p0)); CHECK_OK(st.before_op(4, compute, &resync)); /* moe1: layer 0 is past every pass */ CHECK(at_home(p0)); - for (rad_weight w : p1) CHECK(in_buf(w, 1)); + CHECK(in_ring(p1)); CHECK_OK(st.after_op(4, compute)); CHECK_OK(st.end_pass(compute)); CHECK(at_home(p1)); CHECK_EQ(m.stats().stage_layers, (uint64_t)2); + CHECK_EQ(m.stats().stage_overflow, (uint64_t)0); - /* A pass that ends after its first layer went out leaves nothing published at a copy. */ + /* A pass that ends after its first op leaves nothing published at a copy. */ CHECK(st.begin_pass(&b)); CHECK_OK(st.before_op(0, compute, &resync)); - for (rad_weight w : p0) CHECK(in_buf(w, 0)); + CHECK(in_ring(p0)); CHECK_OK(st.end_pass(compute)); CHECK(at_home(p0)); CHECK(at_home(p1)); @@ -2168,6 +2432,289 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_ rad_stream_destroy(compute); } +/* THE RING OVER MANY LAYERS AND PASSES: room for three and a half layers, six layers a pass, three + * passes, so places lap the region and wrap past its end. At every op, the layers still published + * at copies sit in the ring without overlapping one another; at a layer's first op every one of + * its pooled units is published at a copy holding the pool slot's bytes and the layers before it + * are home; the copies go out more than one layer ahead whenever the room allows; and nothing + * spills to a read in place. */ +TEST(the_stager_ring_laps_without_overwriting_a_published_layer) { + Fixture f; + const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); + f.op("embed", {emb}, false); + constexpr int kL = 6, kE = 8; + std::vector> lw(kL); + for (int l = 0; l < kL; ++l) + for (int e = 0; e < kE; ++e) + lw[(size_t)l].push_back(f.weight("blk." + std::to_string(l) + ".ffn_gate_exps." + + std::to_string(e) + ".weight", 1 * MiB, + RAD_ACCESS_CONDITIONAL, l, e)); + for (int l = 0; l < kL; ++l) { + f.op("attn" + std::to_string(l), {}, false); + f.op("moe" + std::to_string(l), lw[(size_t)l], false); + } + Config cfg = base_config(); + cfg.placement = "expert_tiered"; + cfg.vram_weights_mib = 16; + cfg.host_pool_mib = 128; + Plan plan; + PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; + CHECK_OK(Planner(in).plan(&plan)); + REQUIRE(plan.dynamic); + + Mover m; + MoverConfig mc; + CHECK_OK(m.init(f.prog, plan, mc)); + RadStream compute = nullptr; + CHECK_OK(rad_stream_create(&compute, 0)); + CHECK_OK(m.bind_compute_stream(compute)); + + std::vector> pw(kL); + int64_t most = 0; + const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT); + for (int l = 0; l < kL; ++l) { + for (rad_weight w : lw[(size_t)l]) + if (plan.weight[w].tier == Tier::HostPinned) pw[(size_t)l].push_back(w); + most = std::max(most, each * (int64_t)pw[(size_t)l].size()); + } + REQUIRE(most > 0); + std::vector home(f.prog.weights.size(), nullptr); + for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w) + home[w] = m.residency()->lookup(w)->ptr; + + /* Three and a half of the heaviest layer: three go out at the pass's first op, and the fourth + * runs past the region's end. */ + const int64_t ring = most * 7 / 2 / (2 * RAD_ALIGN_UNIT) * (2 * RAD_ALIGN_UNIT); + std::vector region((size_t)ring); + PrefillStager st; + CHECK_OK(st.init(f.prog, plan, &m, region.data(), ring, 64)); + REQUIRE(st.enabled()); + CHECK_EQ(st.n_layers(), (size_t)kL); + REQUIRE(st.ring_bytes() == ring); + + auto in_ring = [&](rad_weight w) { + const char* p = (const char*)m.residency()->lookup(w)->ptr; + return p >= region.data() && p < region.data() + ring; + }; + /* The layers published at copies, and whether any two of their units share a byte. */ + auto published = [&](std::vector* ls) { + std::vector> spans; + ls->clear(); + for (int l = 0; l < kL; ++l) { + bool any = false; + for (rad_weight w : pw[(size_t)l]) + if (in_ring(w)) { + const char* p = (const char*)m.residency()->lookup(w)->ptr; + spans.emplace_back(p, p + f.prog.weights[w].logical_bytes); + any = true; + } + if (any) ls->push_back(l); + } + std::sort(spans.begin(), spans.end()); + for (size_t i = 1; i < spans.size(); ++i) + if (spans[i].first < spans[i - 1].second) return false; + return true; + }; + + RadBatch b{}; + b.n_tok = 128; + st.set_full_arena(true); + bool ran_ahead = false; + std::vector ls; + for (int pass = 0; pass < 3; ++pass) { + CHECK(st.begin_pass(&b)); + const int n_ops = 1 + 2 * kL; + for (int h = 0; h < n_ops; ++h) { + bool resync = false; + CHECK_OK(st.before_op(h, compute, &resync)); + CHECK(published(&ls)); + if (h >= 2 && h % 2 == 0) { + const int l = (h - 2) / 2; /* moe_l: the layer's first and last op */ + for (int k = 0; k < l; ++k) + for (rad_weight w : pw[(size_t)k]) CHECK(!in_ring(w)); + /* Its copies, settled: the wait the stager issued orders the op; here the test + * drains the mover's stream to read them. */ + CHECK_OK(rad_stream_sync(m.transfer_stream())); + for (rad_weight w : pw[(size_t)l]) { + CHECK(in_ring(w)); + CHECK(std::memcmp(m.residency()->lookup(w)->ptr, home[w], + (size_t)f.prog.weights[w].logical_bytes) == 0); + } + if (ls.size() > 2) ran_ahead = true; + } + CHECK_OK(st.after_op(h, compute)); + } + CHECK_OK(st.end_pass(compute)); + for (int l = 0; l < kL; ++l) + for (rad_weight w : pw[(size_t)l]) CHECK(m.residency()->lookup(w)->ptr == home[w]); + } + CHECK(ran_ahead); + CHECK_EQ(m.stats().stage_overflow, (uint64_t)0); + CHECK_OK(rad_stream_sync(m.transfer_stream())); + rad_stream_destroy(compute); +} + +/* THE NEXT STEP'S FIRST LAYERS AND THE DRAFT HEAD. Six trunk layers and a declared draft head's + * seventh. The head's layer is not staged at all. With the next step going on with a prompt, a + * pass's end stages the next trunk pass's first PrefillStager::lead() layers; a draft pass in + * between neither arms nor touches them; the next armed trunk pass reads them where they are, with + * the copies holding the pool's bytes; and a trunk pass that does not arm publishes them at home + * again before it resolves anything. */ +TEST(the_stager_stages_the_next_steps_first_layers_and_never_the_draft_head) { + Fixture f; + const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); + f.op("embed", {emb}, false); + constexpr int kL = 7, kE = 8; /* layer 6 is the draft head's */ + std::vector> lw(kL); + for (int l = 0; l < kL; ++l) + for (int e = 0; e < kE; ++e) + lw[(size_t)l].push_back(f.weight("blk." + std::to_string(l) + ".ffn_gate_exps." + + std::to_string(e) + ".weight", 1 * MiB, + RAD_ACCESS_CONDITIONAL, l, e)); + for (int l = 0; l < kL; ++l) { + f.op("attn" + std::to_string(l), {}, false); + f.op("moe" + std::to_string(l), lw[(size_t)l], false); + } + f.prog.drafter.kind = RAD_DRAFT_SERIAL; + f.prog.meta.n_layers = kL - 1; + Config cfg = base_config(); + cfg.placement = "expert_tiered"; + cfg.vram_weights_mib = 16; + cfg.host_pool_mib = 128; + Plan plan; + PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; + CHECK_OK(Planner(in).plan(&plan)); + REQUIRE(plan.dynamic); + + Mover m; + MoverConfig mc; + CHECK_OK(m.init(f.prog, plan, mc)); + RadStream compute = nullptr; + CHECK_OK(rad_stream_create(&compute, 0)); + CHECK_OK(m.bind_compute_stream(compute)); + + std::vector> pw(kL); + int64_t most = 0; + const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT); + for (int l = 0; l < kL; ++l) { + for (rad_weight w : lw[(size_t)l]) + if (plan.weight[w].tier == Tier::HostPinned) pw[(size_t)l].push_back(w); + most = std::max(most, each * (int64_t)pw[(size_t)l].size()); + } + REQUIRE(most > 0); + for (int l = 0; l < kL; ++l) REQUIRE(!pw[(size_t)l].empty()); + std::vector home(f.prog.weights.size(), nullptr); + for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w) + home[w] = m.residency()->lookup(w)->ptr; + + /* Room for every trunk layer at once: what the ring holds is the pace's doing, not its size. */ + const int64_t ring = most * 8 / (2 * RAD_ALIGN_UNIT) * (2 * RAD_ALIGN_UNIT); + std::vector region((size_t)ring); + PrefillStager st; + CHECK_OK(st.init(f.prog, plan, &m, region.data(), ring, 64)); + REQUIRE(st.enabled()); + CHECK_EQ(st.n_layers(), (size_t)(kL - 1)); + const int lead = (int)PrefillStager::lead(); + REQUIRE(lead >= 1 && lead < kL - 1); + + auto in_ring = [&](int l) { + for (rad_weight w : pw[(size_t)l]) { + const char* p = (const char*)m.residency()->lookup(w)->ptr; + if (p < region.data() || p >= region.data() + ring) return false; + } + return true; + }; + auto at_home = [&](int l) { + for (rad_weight w : pw[(size_t)l]) if (m.residency()->lookup(w)->ptr != home[w]) return false; + return true; + }; + auto copies_hold_the_pool = [&](int l) { + CHECK_OK(rad_stream_sync(m.transfer_stream())); + for (rad_weight w : pw[(size_t)l]) + if (std::memcmp(m.residency()->lookup(w)->ptr, home[w], + (size_t)f.prog.weights[w].logical_bytes) != 0) return false; + return true; + }; + /* A whole trunk pass, checking at each layer's MoE that it reads copies and that the head's + * layer is never anywhere but home. */ + const int n_ops = 1 + 2 * (kL - 1); + auto run_pass = [&]() { + for (int h = 0; h < n_ops; ++h) { + bool resync = false; + CHECK_OK(st.before_op(h, compute, &resync)); + if (h >= 2 && h % 2 == 0) { + const int l = (h - 2) / 2; + CHECK(in_ring(l)); + CHECK(copies_hold_the_pool(l)); + } + CHECK(at_home(kL - 1)); + CHECK_OK(st.after_op(h, compute)); + } + }; + + RadBatch b{}; + b.n_tok = 128; + st.set_full_arena(true); + + /* No next step: the end leaves everything home. The engine asks whether the step staged + * after the pass has ended, so the answer outlives end_pass. */ + CHECK(!st.staged()); + st.set_next_prefill(false); + CHECK(st.begin_pass(&b)); + run_pass(); + CHECK_OK(st.end_pass(compute)); + CHECK(st.staged()); + for (int l = 0; l < kL; ++l) CHECK(at_home(l)); + + /* The next step goes on: the first `lead` layers go out at the end. */ + st.set_next_prefill(true); + CHECK(st.begin_pass(&b)); + run_pass(); + CHECK_OK(st.end_pass(compute)); + for (int l = 0; l < kL; ++l) CHECK(l < lead ? in_ring(l) : at_home(l)); + for (int l = 0; l < lead; ++l) CHECK(copies_hold_the_pool(l)); + + /* A draft pass neither arms nor gives them back, and leaves the trunk pass's answer. */ + RadBatch d = b; + d.draft_pass = -1; + CHECK(!st.begin_pass(&d)); + CHECK(st.staged()); + for (int l = 0; l < lead; ++l) CHECK(in_ring(l)); + + /* The next armed trunk pass reads them there, and stages nothing at its first op that is + * already out. */ + const uint64_t layers_before = m.stats().stage_layers; + st.set_next_prefill(true); + CHECK(st.begin_pass(&b)); + { + bool resync = false; + CHECK_OK(st.before_op(0, compute, &resync)); + CHECK_EQ(m.stats().stage_layers, layers_before); + CHECK_OK(st.after_op(0, compute)); + } + for (int h = 1; h < n_ops; ++h) { + bool resync = false; + CHECK_OK(st.before_op(h, compute, &resync)); + if (h >= 2 && h % 2 == 0) { + const int l = (h - 2) / 2; + CHECK(in_ring(l)); + CHECK(copies_hold_the_pool(l)); + } + CHECK_OK(st.after_op(h, compute)); + } + CHECK_OK(st.end_pass(compute)); + for (int l = 0; l < kL; ++l) CHECK(l < lead ? in_ring(l) : at_home(l)); + + /* A trunk pass too small to arm: everything home before it resolves a table. */ + b.n_tok = 8; + CHECK(!st.begin_pass(&b)); + CHECK(!st.staged()); + for (int l = 0; l < kL; ++l) CHECK(at_home(l)); + CHECK_EQ(m.stats().stage_overflow, (uint64_t)0); + CHECK_OK(rad_stream_sync(m.transfer_stream())); + rad_stream_destroy(compute); +} + TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) { /* THE PRODUCTION PATH. Pools has already allocated the weights pool as one block; a mover * that called the allocator beside it would spend that budget twice and the overrun would diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index ec553ff0..c55b4cca 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -258,6 +258,7 @@ TEST(op_vocabulary) { "layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows", "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", + "causal_conv1d", "embed_lookup_q", "cast", "scale_rows", "softmax", @@ -269,6 +270,7 @@ TEST(op_vocabulary) { "gated_had_quant_i8", "dequant", "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", + "grid_embed_aa", "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key", "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", "row_topk", @@ -720,6 +722,110 @@ TEST(op_ple_conv) { } } +/* SigLIP2's position resample, against torch's own F.interpolate(bilinear, align_corners=False, + * antialias=True) of the same 4 x 4 x 2 table: shrinking to 2 x 3 (the filter widens), growing to + * 6 x 5 (half-pixel taps, edges clamped) and to 1 x 1 (the whole table, averaged). */ +TEST(op_grid_embed_aa_is_torchs_antialiased_bilinear) { + const int side = 4, n = 2; + T tab(RAD_F32, {side * side, n}); + tab.f({ 0.0f, -0.5f, 0.25f, 1.25f, 0.5f, 0.0f, 0.75f, 1.75f, 1.0f, 2.0f, 1.25f, 0.75f, 1.5f, 2.5f, + 1.75f, 1.25f, 2.0f, 1.5f, 2.25f, 3.25f, 2.5f, 2.0f, 2.75f, 3.75f, 3.0f, 4.0f, 3.25f, + 2.75f, 3.5f, 4.5f, 3.75f, 3.25f }); + struct G { int h, w; std::vector want; }; + const G cases[] = { + { 2, 3, { 0.789286f, 0.996429f, 1.089286f, 1.339286f, 1.389286f, 1.682143f, 2.360714f, + 2.653571f, 2.660714f, 2.910714f, 2.960714f, 3.167857f } }, + { 6, 5, { 0.0f, -0.5f, 0.175f, 0.725f, 0.375f, 0.625f, 0.575f, 0.525f, 0.75f, 1.75f, 0.5f, + 0.75f, 0.675f, 0.925f, 0.875f, 1.125f, 1.075f, 1.325f, 1.25f, 1.5f, 1.166667f, + 1.916667f, 1.341667f, 1.391667f, 1.541667f, 1.791667f, 1.741667f, 2.191667f, + 1.916667f, 1.666667f, 1.833333f, 1.583333f, 2.008333f, 2.458334f, 2.208333f, + 2.458333f, 2.408334f, 2.458333f, 2.583333f, 3.333334f, 2.5f, 2.75f, 2.675f, + 2.925f, 2.875f, 3.125f, 3.075f, 3.325f, 3.25f, 3.5f, 3.0f, 4.0f, 3.175f, 3.125f, + 3.375f, 3.625f, 3.575f, 4.125f, 3.75f, 3.25f } }, + { 1, 1, { 1.875f, 2.125f } }, + }; + for (const G& g : cases) { + const int M = g.h * g.w; + T x(RAD_F32, {M, n}); + std::vector zero((size_t)(M * n), 0.0f); + x.f(zero); + T crd(RAD_I32, {4, M}); + std::vector c((size_t)(4 * M)); + for (int r = 0; r < M; ++r) { + c[(size_t)r] = r / g.w; + c[(size_t)(M + r)] = r % g.w; + c[(size_t)(2 * M + r)] = g.h; + c[(size_t)(3 * M + r)] = g.w; + } + crd.n(c); + A a; a.t(x).t(tab).t(crd).i("M", M).i("n", n).i("side", side).s("dtype", "f32"); + CHECK_OK(run("grid_embed_aa", a)); + for (int i = 0; i < M * n; ++i) CHECK_NEAR(x.at(i), g.want[(size_t)i], 2e-5); + } +} + +/* LFM2's short convolution: ple_conv's window at dilation one, with no activation. */ +TEST(op_causal_conv1d) { + const int n = 1, wid = 3; + /* COLD: zeros in front of the sequence, and the last width-1 inputs left at offset zero. */ + { + T x(RAD_F32, {4, 1}); x.f({ 1, 2, 3, 4 }); + T w(RAD_F32, {1, 3}); w.f({ 100, 10, 1 }); + T cs(RAD_F32, {1, 1, 2}); cs.f({ 7, 7 }); /* a recycled slot's leftovers */ + T cu(RAD_I32, {2}); cu.n({ 0, 4 }); + T ci(RAD_I32, {1}); ci.n({ 0 }); + T hi(RAD_I32, {1}); hi.n({ 0 }); + T y(RAD_F32, {4, 1}); + A a; a.t(x).t(w).t(cs).t(cu).t(ci).t(hi).tnull().t(y) + .i("M", 4).i("n", n).i("width", wid).s("dtype", "f32"); + CHECK_OK(run("causal_conv1d", a)); + CHECK_NEAR(y.at(0), 1.0f, 1e-5); /* 0, 0, 1 -- no silu */ + CHECK_NEAR(y.at(1), 12.0f, 1e-5); /* 0, 1, 2 */ + CHECK_NEAR(y.at(3), 234.0f, 1e-5); /* 2, 3, 4 */ + CHECK_EQ(cs.at(0), 3.0f); + CHECK_EQ(cs.at(1), 4.0f); + } + /* WARM, as two chunks, then a decode step read at num_accepted - 1. */ + { + T w(RAD_F32, {1, 3}); w.f({ 100, 10, 1 }); + T cs(RAD_F32, {1, 1, 4}); cs.f({ 0, 0, 0, 0 }); + T ci(RAD_I32, {1}); ci.n({ 0 }); + T cold(RAD_I32, {1}); cold.n({ 0 }); + T warm(RAD_I32, {1}); warm.n({ 1 }); + T x1(RAD_F32, {3, 1}); x1.f({ 1, 2, 3 }); + T cu1(RAD_I32, {2}); cu1.n({ 0, 3 }); + T y1(RAD_F32, {3, 1}); + A a; a.t(x1).t(w).t(cs).t(cu1).t(ci).t(cold).tnull().t(y1) + .i("M", 3).i("n", n).i("width", wid).s("dtype", "f32"); + CHECK_OK(run("causal_conv1d", a)); + T x2(RAD_F32, {1, 1}); x2.f({ 4 }); + T cu2(RAD_I32, {2}); cu2.n({ 0, 1 }); + T y2(RAD_F32, {1, 1}); + A b; b.t(x2).t(w).t(cs).t(cu2).t(ci).t(warm).tnull().t(y2) + .i("M", 1).i("n", n).i("width", wid).s("dtype", "f32"); + CHECK_OK(run("causal_conv1d", b)); + CHECK_NEAR(y2.at(0), 234.0f, 1e-5); /* the one-pass t=3 */ + /* A verify of two drafts (5, 6) behind it, then a step that kept one of them. */ + T x3(RAD_F32, {2, 1}); x3.f({ 5, 6 }); + T cu3(RAD_I32, {2}); cu3.n({ 0, 2 }); + T na1(RAD_I32, {1}); na1.n({ 1 }); + T y3(RAD_F32, {2, 1}); + A c; c.t(x3).t(w).t(cs).t(cu3).t(ci).t(warm).t(na1).t(y3) + .i("M", 2).i("n", n).i("width", wid).s("dtype", "f32"); + CHECK_OK(run("causal_conv1d", c)); + CHECK_NEAR(y3.at(0), 345.0f, 1e-5); + CHECK_NEAR(y3.at(1), 456.0f, 1e-5); + T x4(RAD_F32, {1, 1}); x4.f({ 9 }); + T cu4(RAD_I32, {2}); cu4.n({ 0, 1 }); + T na2(RAD_I32, {1}); na2.n({ 1 }); /* only 5 was kept: history is (4, 5) */ + T y4(RAD_F32, {1, 1}); + A d; d.t(x4).t(w).t(cs).t(cu4).t(ci).t(warm).t(na2).t(y4) + .i("M", 1).i("n", n).i("width", wid).s("dtype", "f32"); + CHECK_OK(run("causal_conv1d", d)); + CHECK_NEAR(y4.at(0), 459.0f, 1e-5); + } +} + /* PLE's n-gram ids, ON THE REAL CHECKPOINT CONSTANTS. * * The multipliers, vocab sizes and offsets below are the bytes of diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index e1818715..3c3bca05 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -90,6 +90,13 @@ WEAKDEF int rad_memcpy_2d_async(void* d, int64_t dp, const void* s, int64_t sp, WEAKDEF int rad_memset_async(void* d, int v, int64_t n, RadStream) { std::memset(d, v, (size_t)n); return RAD_OK; } +WEAKDEF int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) { + for (int i = 0; i < n; ++i) + if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes); + return RAD_OK; +} +WEAKDEF int rad_link_hold(RadStream, int) { return RAD_OK; } +WEAKDEF void* rad_link_gate(RadStream) { return nullptr; } WEAKDEF const char* rad_dev_last_error(void) { return "none"; } } /* extern "C" */ diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 0737c421..eaf869fb 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -82,6 +82,13 @@ __attribute__((weak)) int rad_memcpy_ranges_async(void* d, const void* s, int64_ std::memcpy((char*)d + r[i].dst, (const char*)s + r[i].src, (size_t)r[i].bytes); return RAD_OK; } +__attribute__((weak)) int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) { + for (int i = 0; i < n; ++i) + if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes); + return RAD_OK; +} +__attribute__((weak)) int rad_link_hold(RadStream, int) { return RAD_OK; } +__attribute__((weak)) void* rad_link_gate(RadStream) { return nullptr; } static int g_fake_event; __attribute__((weak)) int rad_event_create(RadEvent* e) { *e = &g_fake_event; return RAD_OK; } @@ -501,6 +508,7 @@ struct Fixture { g_gdn_row = KernelRow{ &g_gdn_ki, "fake", 0, 0 }; prog.meta.n_ctx_train = 4096; + prog.meta.n_vocab = 512; /* index 0 is the sentinel every handle table in Program carries */ prog.ops.emplace_back(); @@ -698,6 +706,38 @@ TEST(prefill_chunks_split_at_the_checkpoint_interval) { CHECK_EQ(f.sch.plan_chunk(0, 1000, 50, &ck), 0); } +/* A REQUEST'S OWN CHECKPOINT (Request::checkpoint_at): the end of a head other requests share, + * on the quantum below it. It splits a chunk the way the interval does and gives way to nothing. */ +TEST(prefill_chunks_split_where_the_request_asks_for_a_checkpoint) { + Fixture f; + f.build(); + CHECK_OK(f.start()); + + int64_t ck = -1; + /* Inside the first interval, where nothing else would write one: split at 128, the quantum + * under 150, then the rest with none. */ + CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck, 150), 128); + CHECK_EQ(ck, 128); + CHECK_EQ(f.sch.plan_chunk(128, 200, 512, &ck, 150), 72); + CHECK_EQ(ck, -1); + /* Past the interval checkpoint that comes first, and before the next one. */ + CHECK_EQ(f.sch.plan_chunk(0, 1000, 512, &ck, 600), 256); + CHECK_EQ(ck, 256); + CHECK_EQ(f.sch.plan_chunk(512, 1000, 512, &ck, 600), 64); + CHECK_EQ(ck, 576); + /* On a boundary the chunk would end on anyway, it is that boundary's checkpoint. */ + CHECK_EQ(f.sch.plan_chunk(0, 1000, 512, &ck, 256), 256); + CHECK_EQ(ck, 256); + /* A head shorter than a quantum has no boundary to keep. */ + CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck, 40), 200); + CHECK_EQ(ck, -1); + /* And a budget short of it still ends on a quantum, the checkpoint left for a later chunk. */ + CHECK_EQ(f.sch.plan_chunk(0, 1000, 100, &ck, 150), 64); + CHECK_EQ(ck, -1); + CHECK_EQ(f.sch.plan_chunk(64, 1000, 512, &ck, 150), 64); + CHECK_EQ(ck, 128); +} + TEST(a_chunk_ending_on_a_checkpoint_carries_it_into_the_batch) { Fixture f; f.build(); @@ -802,6 +842,33 @@ TEST(add_all_queues_a_set_under_one_lock_and_refuses_members_singly) { CHECK_EQ(f.sch.metrics().admitted, 2); } +/* A scored prompt (Request::token_scores) names real vocabulary rows, and drafts nothing. */ +TEST(a_scored_request_names_real_vocabulary_rows) { + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + const int32_t n_vocab = (int32_t)f.prog.meta.n_vocab; + REQUIRE(n_vocab > 2); + std::unique_ptr rs[4]; + const std::vector> ids = { { 1, 2 }, {}, { n_vocab }, { -1 } }; + for (int i = 0; i < 4; ++i) { + rs[i] = std::make_unique(); + rs[i]->id = f.next_id++; + rs[i]->max_tokens = 1; + rs[i]->prompt.assign(16, 7); + rs[i]->token_scores = std::make_shared(); + rs[i]->token_scores->tokens = ids[(size_t)i]; + } + Request* kept = rs[0].get(); + int rc[4] = { -1, -1, -1, -1 }; + f.sch.add_all(rs, 4, rc); + CHECK_EQ(rc[0], RAD_OK); + CHECK_EQ(rc[1], RAD_E_INVAL); + CHECK_EQ(rc[2], RAD_E_INVAL); + CHECK_EQ(rc[3], RAD_E_INVAL); + CHECK(!kept->may_speculate); +} + TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) { Fixture f; f.build(); diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 3a9e8f41..ac437241 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2888,6 +2888,41 @@ TEST(server_info_drops_an_engine_blob_that_is_not_an_object) { CHECK(has(r2.body, "\"arch\":\"testarch\"")); } +/* /diagnostics DESCRIBES THE HOST, so without a key it answers this machine only. With a key the + * transport's gate has already checked the caller, and any address may ask. */ +TEST(diagnostics_without_a_key_answers_loopback_only) { + FakeScheduler sched; + FakeTokenizer tok; + Deps d; + d.sched = &sched; + d.tok = &tok; + ServerOptions o; + o.model_id = "test-model"; + o.diagnostics_json = [] { return std::string(R"({"findings":[]})"); }; + Server srv(d, o); + auto from = [](Server& s, const char* peer) { + HttpRequest q; + q.path = "/diagnostics"; + q.peer = peer; + return s.router().dispatch(q).status; + }; + CHECK_EQ(from(srv, "127.0.0.1:50122"), 200); + CHECK_EQ(from(srv, "127.8.9.10:50122"), 200); + CHECK_EQ(from(srv, "::1:50122"), 200); + CHECK_EQ(from(srv, "[::1]:50122"), 200); + CHECK_EQ(from(srv, "::ffff:127.0.0.1:50122"), 200); + CHECK_EQ(from(srv, ""), 200); /* in-process */ + CHECK_EQ(from(srv, "192.168.1.20:50122"), 403); + CHECK_EQ(from(srv, "::ffff:10.0.0.7:50122"), 403); + CHECK_EQ(from(srv, "fe80::1:50122"), 403); + CHECK_EQ(from(srv, "128.0.0.1:50122"), 403); + + ServerOptions ok = o; + ok.api_key = "k"; + Server keyed(d, ok); + CHECK_EQ(from(keyed, "192.168.1.20:50122"), 200); +} + TEST(tokenize_takes_a_prompt_or_messages_and_never_both) { Fixture f; diff --git a/tests/systemone_test.cpp b/tests/systemone_test.cpp new file mode 100644 index 00000000..96ab20a7 --- /dev/null +++ b/tests/systemone_test.cpp @@ -0,0 +1,310 @@ +/* systemone_test.cpp -- /v1/systemone's adapter (core/server/systemone.h) and its handler. + * + * What d1 reads is exact text: a reworded instruction or a different option code is a different + * question to a model trained on its own prompts. So the rendering is checked as text, against + * strings written out from d1's prompt.py, and the readout against hand-computed softmaxes. The + * end-to-end parity with d1 itself is a serve against the model (docs/SYSTEMONE.md). + */ +#include "rad_test.h" + +#include "server/server.h" +#include "server/sink.h" +#include "server/systemone.h" + +#include + +#include +#include +#include +#include + +using namespace rad; +using namespace rad::server; + +namespace { + +/* A vocabulary in which d1's answer spellings are single tokens -- yes/no in three cases, the + * letters, " A".." Z", the digits -- and everything else is one id a byte, 1000 up, so a prompt + * decodes back to its exact text. "Q" and "07" are NOT single tokens, which drives the fallback + * codebook. Every string handed to encode is logged, which is how the tokenisation split is seen. */ +struct DictTokenizer : ITokenizer { + std::map whole; + mutable std::vector log; + mutable std::mutex mu; + DictTokenizer() { + int32_t id = 1; + for (const char* s : { "yes", "Yes", "YES", "no", "No", "NO", "<|startoftext|>" }) + whole[s] = id++; + for (char c = 'A'; c <= 'Z'; ++c) { + if (c == 'Q') continue; + whole[std::string(1, c)] = id++; + whole[" " + std::string(1, c)] = id++; + } + for (char c = '0'; c <= '9'; ++c) whole[std::string(1, c)] = id++; + whole["00"] = id++; + } + std::vector encode(const std::string& s, bool, bool) const override { + { std::lock_guard lk(mu); log.push_back(s); } + auto it = whole.find(s); + if (it != whole.end()) return { it->second }; + if (s == "Q") return { 1000 + 'Q', 3000 }; /* two ids, the second spelled "" */ + std::vector v; + for (unsigned char c : s) v.push_back(1000 + c); + return v; + } + std::string token_bytes(int32_t id) const override { + if (id == 3000) return ""; + if (id >= 1000) return std::string(1, (char)(id - 1000)); + for (const auto& kv : whole) if (kv.second == id) return kv.first; + return ""; + } + std::string decode(const std::vector& t) const override { + std::string s; + for (int32_t x : t) s += token_bytes(x); + return s; + } + int32_t eos() const override { return 0; } + int32_t bos() const override { return whole.at("<|startoftext|>"); } + std::unique_ptr detokenizer(const std::vector&, + const std::vector&) const override { + return nullptr; + } + int32_t id(const std::string& s) const { return whole.at(s); } +}; + +OaiLimits limits(int64_t max_ctx = 0) { + OaiLimits l; + l.model_id = "d1"; + l.max_ctx = max_ctx; + return l; +} + +int parse(DictTokenizer& tok, const std::string& body, DecisionRequest* r, ApiError* e, + int64_t max_ctx = 0) { + OaiDeps d; + d.tok = &tok; + return parse_decision_request(body, d, limits(max_ctx), "d1", r, e); +} + +} /* namespace */ + +TEST(a_single_question_is_d1s_prompt_as_one_text) { + DictTokenizer tok; + DecisionRequest r; + ApiError e; + CHECK_OK(parse(tok, R"({"state": "I was charged twice.", + "questions": {"refund": {"type": "noul", "instructions": "Is a refund requested?"}}})", + &r, &e)); + REQUIRE(r.questions.size() == 1); + CHECK_EQ(tok.decode(r.questions[0].tokens), + "<|startoftext|><|im_start|>user\nI was charged twice.\n\n\nQUESTION:\n" + "Is a refund requested?\n\nReply with yes or no only.<|im_end|>\n" + "<|im_start|>assistant\n"); + CHECK_EQ(r.trunk, 0); + CHECK_EQ(r.input_tokens, (int64_t)r.questions[0].tokens.size()); + /* One encode of the whole prompt, after the candidates' single-token probes. */ + CHECK_EQ(tok.log.back(), tok.decode(r.questions[0].tokens)); + /* yes/Yes/YES then no/No/NO, max-pooled per answer. */ + CHECK(r.questions[0].labels == (std::vector{ "true", "false" })); + CHECK_EQ(r.questions[0].candidates.size(), (size_t)6); + REQUIRE(r.questions[0].groups.size() == 2); + CHECK_EQ(r.questions[0].groups[0].size(), (size_t)3); +} + +TEST(several_questions_share_a_head_tokenised_on_its_own) { + DictTokenizer tok; + DecisionRequest r; + ApiError e; + CHECK_OK(parse(tok, R"({"state": {"b": 1, "a": [true, null]}, + "questions": { + "z": {"type": "score", "instructions": "How urgent?", "criteria": ["Low", "High"]}, + "a": {"type": "noul", "instructions": "Late?", + "criteria": {"true": "Not on time", "false": null}}}})", &r, &e)); + REQUIRE(r.questions.size() == 2); + /* Insertion order, for the questions and for the state's keys (indented JSON). */ + CHECK_EQ(r.questions[0].name, "z"); + const std::string head = "<|startoftext|><|im_start|>user\n{\n \"b\": 1,\n \"a\": [\n true,\n" + " null\n ]\n}\n\n\nQUESTION:\n"; + CHECK_EQ(r.trunk, (int32_t)head.size()); /* one id a byte in this vocabulary */ + CHECK_EQ(tok.decode(r.questions[0].tokens), + head + "How urgent?\n\n0 Low\n1 High\n\nReply with a single digit 0-1 only." + "<|im_end|>\n<|im_start|>assistant\n"); + CHECK_EQ(tok.decode(r.questions[1].tokens), + head + "Late?\nYes: Not on time\nNo: None\n\nReply with yes or no only." + "<|im_end|>\n<|im_start|>assistant\n"); + /* The head was encoded once, as itself; usage counts it once. */ + int heads = 0; + for (const std::string& s : tok.log) heads += s == head; + CHECK_EQ(heads, 1); + CHECK_EQ(r.input_tokens, (int64_t)(r.questions[0].tokens.size() + r.questions[1].tokens.size()) - + r.trunk); +} + +TEST(choice_codes_follow_d1s_codebook) { + DictTokenizer tok; + { /* Names that are not letters: A, B, C, and a description falling back to the name. */ + DecisionRequest r; + ApiError e; + CHECK_OK(parse(tok, R"({"state": null, "questions": {"team": {"instructions": "Who?", + "criteria": {"billing": "Charges", "tech_support": null, "fraud": ""}}}})", &r, &e)); + const DecisionQuestion& q = r.questions[0]; + CHECK_EQ(q.type, "choice"); /* d1's default type */ + CHECK_EQ(tok.decode(q.tokens), "<|startoftext|><|im_start|>user\nWho?\n\nOptions:\nA Charges\n" + "B tech support\nC fraud\n\nReply with the option code only.<|im_end|>\n" + "<|im_start|>assistant\n"); + REQUIRE(q.groups.size() == 3); + /* Each option reads its code and " code". */ + CHECK_EQ(q.candidates[q.groups[1][0]], tok.id("B")); + CHECK_EQ(q.candidates[q.groups[1][1]], tok.id(" B")); + } + { /* Letters are their own codes, except one that is not a token: Q takes the first free + * fallback, which is A -- not yet used, because the codes are taken in option order. */ + DecisionRequest r; + ApiError e; + CHECK_OK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "choice", + "instructions": "Pick.", "criteria": {"Q": "first", " B ": "second"}}}})", &r, &e)); + const std::string text = tok.decode(r.questions[0].tokens); + CHECK(text.find("Options:\nA first\nB second\n") != std::string::npos); + CHECK(r.questions[0].labels == (std::vector{ "Q", " B " })); + } + { /* Over 26 options: 00, 01, ... and every two-digit code but 00 falls back. */ + std::string crit; + for (int i = 0; i < 27; ++i) crit += (i ? "," : "") + std::string("\"o") + std::to_string(i) + "\": null"; + DecisionRequest r; + ApiError e; + CHECK_OK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "choice", + "instructions": "Pick.", "criteria": {)" + crit + "}}}}", &r, &e)); + const std::string text = tok.decode(r.questions[0].tokens); + CHECK(text.find("Options:\n00 o0\nA o1\nB o2\n") != std::string::npos); + CHECK_EQ(r.questions[0].groups.size(), (size_t)27); + } +} + +TEST(the_readout_is_a_softmax_over_each_answers_best_spelling) { + DecisionQuestion q; + q.name = "n"; q.type = "noul"; q.labels = { "true", "false" }; + q.candidates = { 10, 11, 20, 21 }; + q.groups = { { 0, 1 }, { 2, 3 } }; + json a; + ApiError e; + CHECK_OK(decision_answer(q, { 1.0f, 3.0f, 2.0f, -5.0f }, &a, &e)); + CHECK_NEAR(a["noul"].get(), 1.0 / (1.0 + std::exp(-1.0)), 1e-12); /* 3 vs 2 */ + + DecisionQuestion s; + s.name = "s"; s.type = "score"; s.labels = { "0", "1", "2" }; s.legend = { "a", "b", "c" }; + s.candidates = { 1, 2, 3 }; + s.groups = { { 0 }, { 1 }, { 2 } }; + CHECK_OK(decision_answer(s, { 0.0f, 0.0f, std::log(2.0f) }, &a, &e)); + CHECK_NEAR(a["score"].get(), (0.25 + 2 * 0.5), 1e-6); + CHECK_NEAR(a["confidence"].get(), 0.5, 1e-6); + CHECK_EQ(a["legend"]["2"].get(), "c"); + CHECK_EQ(a.dump().substr(0, 26), "{\"type\":\"score\",\"score\":1."); + + CHECK(decision_answer(s, { 0.0f, NAN, 1.0f }, &a, &e) < 0); + CHECK_EQ(e.status, 500); + CHECK(decision_answer(s, { 0.0f }, &a, &e) < 0); +} + +TEST(requests_d1_cannot_answer_are_refused_by_field) { + DictTokenizer tok; + struct Case { const char* body; const char* param; }; + const Case cases[] = { + { R"({"questions": {"a": {"type": "noul", "instructions": "x"}}})", "state" }, + { R"({"state": "s", "questions": {}})", "questions" }, + { R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x"}}, "stream": true})", + "stream" }, + { R"({"state": "s", "model": "other", "questions": {"a": {"type": "noul", "instructions": "x"}}})", + "model" }, + { R"({"state": "s", "questions": {"a": {"type": "vote", "instructions": "x"}}})", "questions.a.type" }, + { R"({"state": "s", "questions": {"a": {"type": "score", "instructions": "x", "criteria": ["one"]}}})", + "questions.a.criteria" }, + { R"({"state": "s", "questions": {"a": {"type": "choice", "instructions": "x", "criteria": {}}}})", + "questions.a.criteria" }, + { R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x", "criteria": {"maybe": "?"}}}})", + "questions.a.criteria.maybe" }, + { R"({"state": "s", "questions": {"a": {"type": "noul"}}})", "questions.a.instructions" }, + }; + for (const Case& c : cases) { + DecisionRequest r; + ApiError e; + CHECK(parse(tok, c.body, &r, &e) < 0); + CHECK_EQ(e.param, c.param); + } + /* Pictures without an encoder are the deployment's refusal, not the request's. */ + DecisionRequest r; + ApiError e; + CHECK(parse(tok, R"({"state": null, "images": ["data:image/png;base64,AAAA"], + "questions": {"a": {"type": "noul", "instructions": "x"}}})", &r, &e) < 0); + CHECK_EQ(e.status, 501); + /* A prompt must leave one position for the token the request samples. */ + CHECK(parse(tok, R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x"}}})", + &r, &e, 40) < 0); + CHECK_EQ(e.code, "context_length_exceeded"); +} + +/* ------------------------------------------------------------------ the handler */ +namespace { + +/* Answers every scored request with logits that make the first spelling of the first answer + * win by ln 3 -- P = 0.75 at two answers -- and records what it was handed. */ +struct ScoringScheduler : IScheduler { + std::mutex mu; + std::vector seen; + std::vector workers; + std::atomic next{ 1 }; + ~ScoringScheduler() override { for (auto& t : workers) if (t.joinable()) t.join(); } + uint64_t submit(Request&& r) override { + std::lock_guard lk(mu); + auto ts = r.token_scores; + void* sink = r.sink; + seen.push_back(std::move(r)); + workers.emplace_back([ts, sink] { + sink_admitted(sink); + if (ts) { + ts->logits.assign(ts->tokens.size(), 0.0f); + ts->logits[0] = std::log(3.0f); + } + sink_push(sink, 'x', nullptr); + sink_finish(sink, Finish::Length); + }); + return next++; + } + void cancel(uint64_t) override {} + SchedMetrics metrics() const override { return {}; } +}; + +} /* namespace */ + +TEST(the_endpoint_answers_only_for_a_declared_d1) { + for (const char* type : { "", "d1" }) { + ScoringScheduler sched; + DictTokenizer tok; + Deps d; + d.sched = &sched; + d.tok = &tok; + ServerOptions o; + o.model_id = "d1"; + o.decision_type = type; + Server srv(d, o); + HttpResponse res = srv.router().call("POST", "/v1/systemone", + R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x"}, + "c": {"type": "choice", "instructions": "y", + "criteria": {"one": null, "two": null}}}})"); + if (!*type) { CHECK_EQ(res.status, 501); continue; } + REQUIRE(res.status == 200); + const json j = json::parse(res.body); + CHECK_NEAR(j["answers"]["q"]["noul"].get(), 0.75, 1e-6); + CHECK_EQ(j["answers"]["c"]["choice"].get(), "one"); + CHECK_EQ(j["usage"]["output_tokens"].get(), 0); + /* One request a question, scored, one token long, greedy. */ + std::lock_guard lk(sched.mu); + REQUIRE(sched.seen.size() == 2); + for (const Request& rq : sched.seen) { + CHECK(rq.token_scores != nullptr); + CHECK_EQ(rq.max_tokens, 1); + CHECK_EQ(rq.sp.temp, 0.0f); + } + } +} + +RAD_TEST_MAIN() diff --git a/tests/text_test.cpp b/tests/text_test.cpp index 91559abd..4ce1292d 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -706,6 +706,7 @@ TEST(vocab_section_round_trip) { in.bos = -1; in.eos = 2; in.eot = 2; in.unk = 0; in.pad = -1; in.sep = -1; in.add_bos = false; in.add_eos = true; + in.ignore_merges = true; in.chat_template = "{{ messages }}"; VocabStep s0; s0.kind = RAD_NORM_NFC; in.steps.push_back(s0); VocabStep s1; s1.kind = RAD_PRE_SPLIT; s1.arg0 = "\\p{N}"; s1.iarg = 1; in.steps.push_back(s1); @@ -749,6 +750,7 @@ TEST(vocab_section_round_trip) { CHECK_EQ(out.eos, in.eos); CHECK_EQ(out.unk, in.unk); CHECK_EQ(out.add_eos, in.add_eos); + CHECK_EQ(out.ignore_merges, in.ignore_merges); CHECK_EQ(out.chat_template, in.chat_template); CHECK_EQ(out.steps.size(), in.steps.size()); for (size_t i = 0; i < out.steps.size(); ++i) { diff --git a/tests/tokenizer_test.cpp b/tests/tokenizer_test.cpp index d6197ab2..7feb04d4 100644 --- a/tests/tokenizer_test.cpp +++ b/tests/tokenizer_test.cpp @@ -23,6 +23,7 @@ #include "llama/src/unicode.h" #include +#include #include #include #include @@ -348,6 +349,58 @@ TEST(bpe_merges_as_worked_out_by_hand) { } } +/* `ignore_merges`: "abc" is a vocabulary entry the one merge cannot reach, so the flag is the only + * way to get it. It applies to each pre-token after the declared chain (the Lowercase normalizer + * and the whitespace split run first), and on both ByteLevel paths: the deferred one that merges + * raw bytes, and the materialised one a later Split forces. */ +TEST(bpe_ignore_merges_takes_a_whole_pretoken) { + const char* chains[] = { + R"({"type":"WhitespaceSplit"})", + R"({"type":"Sequence","pretokenizers":[{"type":"WhitespaceSplit"},)" + R"({"type":"ByteLevel","add_prefix_space":false,"use_regex":false}]})", + R"({"type":"Sequence","pretokenizers":[{"type":"WhitespaceSplit"},)" + R"({"type":"ByteLevel","add_prefix_space":false,"use_regex":false},)" + R"({"type":"Split","pattern":{"String":" "},"behavior":"Removed"}]})", + }; + for (const char* chain : chains) + for (const char* flag : { "", "\"ignore_merges\":false,", "\"ignore_merges\":true," }) { + const bool ignore = std::strstr(flag, "true") != nullptr; + const std::string js = std::string(R"({"normalizer":{"type":"Lowercase"},"pre_tokenizer":)") + + chain + R"(,"model":{"type":"BPE",)" + flag + + R"("vocab":{"a":0,"b":1,"c":2,"ab":3,"abc":4,"abc abc":5},"merges":["a b"]}})"; + auto v = from_json(js.c_str()); + REQUIRE(v != nullptr); + CHECK_EQ(v->build().ignore_merges, ignore); + Tokenizer t; + CHECK_OK(t.init(v)); + const std::vector whole{ 4 }, merged{ 3, 2 }; + for (int repeat = 0; repeat < 2; ++repeat) { /* the second pass reads the caches */ + CHECK(encode_new(t, "ABC") == (ignore ? whole : merged)); + CHECK(encode_new(t, "ABCABC") == (std::vector{ 3, 2, 3, 2 })); + CHECK(encode_new(t, "ABC ABC") == (ignore ? std::vector{ 4, 4 } + : std::vector{ 3, 2, 3, 2 })); + } + CHECK(encode_ref(*v, "ABC ABC") == encode_new(t, "ABC ABC")); + } +} + +/* A control token read as text stays text: the flag must not turn its spelling back into the + * marker when the caller asked for specials not to be parsed. */ +TEST(bpe_ignore_merges_leaves_unparsed_control_tokens_as_text) { + auto v = from_json(R"JSON({ + "added_tokens":[{"id":4,"content":"abc","special":true}], + "pre_tokenizer":{"type":"WhitespaceSplit"}, + "model":{"type":"BPE","ignore_merges":true, + "vocab":{"a":0,"b":1,"c":2,"ab":3},"merges":["a b"]} + })JSON"); + REQUIRE(v != nullptr); + Tokenizer t; + CHECK_OK(t.init(v)); + CHECK(encode_new(t, "abc", true) == (std::vector{ 4 })); + CHECK(encode_new(t, "abc", false) == (std::vector{ 3, 2 })); + CHECK(encode_ref(*v, "abc", false) == (std::vector{ 3, 2 })); +} + TEST(byte_fallback_and_unk_follow_the_declared_chain) { auto v = from_json(k_spm); REQUIRE(v != nullptr); diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp index ac6e7430..ccfc9290 100644 --- a/tools/rad_kbench.cpp +++ b/tools/rad_kbench.cpp @@ -155,7 +155,7 @@ double tolerance_for(const std::string& op, const char* dtype, const char* opera /* ================================================================== the run */ struct Stats { int checked = 0, passed = 0, failed = 0, skipped = 0, capped = 0, diverged = 0, - overrun = 0, guarded = 0; + overrun = 0, guarded = 0, timed = 0; double worst = 0; }; struct Row { @@ -293,6 +293,85 @@ RadStream run_stream() { * * Returns the median microseconds per launch, or < 0 if any launch refused the shape. */ +/* ---- COLD TIMING (--bench-flush): the caches emptied before every timed launch. + * + * Every launch of a timed window reuses one set of operands, so from the second launch on a weight + * that fits in L2 (8 MiB here) or the last-level cache (64 MiB) is read from cache. The engine never + * sees that: a step streams every layer's weights once, far more than the caches hold, so each + * kernel reads its weight cold. A change that only moves how a kernel waits on DRAM can then look + * free in this tool and cost microseconds in the engine, and the reverse. + * + * So the flush READS `g_bench_flush` bytes through the hierarchy before each launch, and writes + * them into one kFlushChunk destination over and over. Read and written in full -- a plain copy or + * fill -- the span would leave that many dirty lines behind, and the timed kernel would pay their + * write-back as traffic it never asked for, which inflates exactly the bandwidth-bound kernels + * this mode is for. Bounded this way the dirty footprint is one chunk. + * + * A launch is then timed ALONE, between two events on the device, because a flush inside the + * window would otherwise be in the number. The figure is the device's, launch latency included + * and the host's submission gaps excluded, so it is not the same quantity as the warm window's. */ +int64_t g_bench_flush = 0; +constexpr int64_t kFlushChunk = 4ll << 20; + +/* The flush source and destination, allocated once for the run: an allocation per case would put + * the allocator into every case's wall time and churn VRAM the case budget is sized against. */ +bool flush_bufs(void** src, void** dst) { + static void* s = nullptr; + static void* d = nullptr; + if (!s) { + s = rad_dev_alloc(g_bench_flush, RAD_MEM_DEVICE); + d = rad_dev_alloc(std::min(g_bench_flush, kFlushChunk), RAD_MEM_DEVICE); + if (!s || !d) { + std::fprintf(stderr, "rad-kbench: --bench-flush: no %lld MiB of device memory for the " + "flush: %s\n", (long long)(g_bench_flush >> 20), + rad_dev_last_error()); + return false; + } + } + *src = s; + *dst = d; + return true; +} + +double time_cold(const RadKernelInfo* info, RadArgs* a, RadStream stream, int iters, int reps, + double* spread_pct) { + void* fsrc = nullptr; + void* fdst = nullptr; + if (!flush_bufs(&fsrc, &fdst)) return -1; + static std::vector ev; + while (ev.size() < 2 * (size_t)iters) { + RadEvent e = nullptr; + if (rad_event_create(&e) < 0) return -1; + ev.push_back(e); + } + std::vector us; + us.reserve((size_t)reps); + std::vector one((size_t)iters); + for (int rep = 0; rep < reps; ++rep) { + for (int it = 0; it < iters; ++it) { + for (int64_t off = 0; off < g_bench_flush; off += kFlushChunk) + if (rad_memcpy_async(fdst, (const uint8_t*)fsrc + off, + std::min(kFlushChunk, g_bench_flush - off), stream) < 0) + return -1; + if (rad_event_record(ev[2 * (size_t)it], stream) < 0) return -1; + if (info->launch(a, stream) < 0) return -1; + if (rad_event_record(ev[2 * (size_t)it + 1], stream) < 0) return -1; + } + if (rad_stream_sync(stream) < 0) return -1; + for (int it = 0; it < iters; ++it) { + float ms = 0.0f; + if (rad_event_elapsed_ms(ev[2 * (size_t)it], ev[2 * (size_t)it + 1], &ms) < 0) return -1; + one[(size_t)it] = 1e3 * (double)ms; + } + std::sort(one.begin(), one.end()); + us.push_back(one[one.size() / 2]); + } + std::sort(us.begin(), us.end()); + const double med = us[us.size() / 2]; + if (spread_pct) *spread_pct = med > 0 ? 100.0 * (us.back() - us.front()) / med : 0.0; + return med; +} + double time_launch(const RadKernelInfo* info, RadArgs* a, RadStream stream, int iters, int reps, int warm_ms, double* spread_pct) { if (spread_pct) *spread_pct = -1; @@ -304,6 +383,7 @@ double time_launch(const RadKernelInfo* info, RadArgs* a, RadStream stream, for (int i = 0; i < iters; ++i) if (info->launch(a, stream) < 0) return -1; if (rad_stream_sync(stream) < 0) return -1; } + if (g_bench_flush > 0) return time_cold(info, a, stream, iters, reps, spread_pct); std::vector us; us.reserve((size_t)reps); @@ -377,7 +457,8 @@ void fold_run(std::vector& libs, const std::vector& rows) { LibRow& l = *it->second; ++l.cases; if (!r.kernel.empty()) l.ran.insert(r.kernel); - if (r.verdict == "ok") ++l.passed; else ++l.failed; + if (r.verdict == "ok") ++l.passed; + else if (r.verdict != "timed") ++l.failed; l.worst = std::max(l.worst, r.rel_l2); if (r.us >= 0) l.us.push_back(r.us); } @@ -471,6 +552,9 @@ int write_report(const std::string& path, const std::vector& rows, "has none of its own\n"; s += fmt("- %d case(s) checked, %d passed, %d failed, %d skipped, %d capped; worst rel_l2 " "%.3e\n", st.checked, st.passed, st.failed, st.skipped, st.capped, st.worst); + if (st.timed) + s += fmt("- %d case(s) timed and NOT checked (`--timing-only`): this report ranks speed " + "only\n", st.timed); if (st.diverged) s += fmt("- %d case(s) where two libraries describe the same output differently -- not a\n" " correctness result, see **Divergences** below\n", st.diverged); @@ -599,6 +683,7 @@ int write_report(const std::string& path, const std::vector& rows, int n = 0; double worst_rel = -1; bool any_fail = false; + bool any_timed = false; /* --timing-only: ran and was timed, checked by nothing */ bool any_synth = false; std::vector us, ref_us; /* The WORST spread any rep of any run in the group showed, for the same reason the error @@ -617,7 +702,8 @@ int write_report(const std::string& path, const std::vector& rows, Agg& a = it->second; ++a.n; a.worst_rel = std::max(a.worst_rel, r.rel_l2); - a.any_fail = a.any_fail || r.verdict != "ok"; + a.any_fail = a.any_fail || (r.verdict != "ok" && r.verdict != "timed"); + a.any_timed = a.any_timed || r.verdict == "timed"; a.any_synth = a.any_synth || r.synthesised; if (r.us >= 0) a.us.push_back(r.us); if (r.ref_us >= 0) a.ref_us.push_back(r.ref_us); @@ -638,7 +724,8 @@ int write_report(const std::string& path, const std::vector& rows, s += "| `" + md_escape(r.op) + "` | `" + md_escape(r.kernel) + "` | " + md_escape(r.plugin) + " | " + r.domain + " | `" + md_escape(r.geom) + "` | " + md_escape(r.choice.empty() ? "-" : r.choice) + " | " + fmt("%d", a.n) + " | " + - (a.any_fail ? "**FAIL**" : "ok") + (a.any_synth ? " (synth w)" : "") + " | " + + (a.any_fail ? "**FAIL**" : a.any_timed ? "timed" : "ok") + + (a.any_synth ? " (synth w)" : "") + " | " + (a.worst_rel < 0 ? "-" : fmt("%.2e", a.worst_rel)) + " | " + fmt("%.0e", r.tol) + " |\n"; } @@ -646,11 +733,20 @@ int write_report(const std::string& path, const std::vector& rows, /* ================================================================ 4. speed */ if (benched) { s += "\n## Speed\n\n"; - s += "> **These times rank kernels; they do not size a roofline.** Every launch in a " - "timed\n> run reuses one set of operands, so a weight that fits in the last-level " - "cache is\n> read from cache after the first launch, and a bandwidth-bound kernel " - "can read\n> several times its true rate. Ranking two kernels at one shape is what " - "these times are\n> for; a roofline is not.\n>\n> `operands` is the total the case ALLOCATED, not what the kernel read: a " + if (g_bench_flush > 0) + s += fmt("> **Timed cold (`--bench-flush %lld`).** Before every timed launch %lld MiB " + "were read\n> through the caches, so each launch read its operands from " + "memory as the engine's\n> kernels read their weights, and each was timed " + "alone between two device events:\n> launch latency is in the number, the " + "host's submission gaps are not.\n>\n", + (long long)(g_bench_flush >> 20), (long long)(g_bench_flush >> 20)); + else + s += "> **These times rank kernels; they do not size a roofline.** Every launch in a " + "timed\n> run reuses one set of operands, so a weight that fits in the last-level " + "cache is\n> read from cache after the first launch, and a bandwidth-bound kernel " + "can read\n> several times its true rate. Ranking two kernels at one shape is what " + "these times are\n> for; a roofline is not. `--bench-flush` times them cold.\n>\n"; + s += "> `operands` is the total the case ALLOCATED, not what the kernel read: a " "gather\n> touches M rows of a table, not the table. Dividing the two columns " "produces a\n> bandwidth figure this tool cannot stand behind, which is why it does " "not print one.\n>\n> The `" + ref_name + "` column is ONE untimed-warmup call, not a " @@ -801,7 +897,7 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, const std::vector>>& planes, const KernelRow* row, const std::string& lib, int dom, const RadOpSchema* schema, double tol_override, bool bench, int bench_iters, int bench_reps, - int bench_warm_ms, bool verbose, + int bench_warm_ms, bool verbose, bool timing_only, Stats* st, std::vector* rows, std::map* skipped, /* The device-side weight cache, owned by the replay driver and shared across every * case: a 206 MB upload repeated once per sweep point is most of a run. */ @@ -1006,8 +1102,8 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, /* The outputs back on the host BEFORE anything is timed: many ops are in place, and a timed * loop of twenty launches would leave `rope` rotated twenty-one times and report a large - * error on a correct kernel. */ - if (dom == RAD_DOMAIN_DEVICE) { + * error on a correct kernel. A timing-only run checks nothing, so it reads nothing back. */ + if (dom == RAD_DOMAIN_DEVICE && !timing_only) { for (size_t k = 0; k < n_opd; ++k) { if (!dev[k].on) continue; const int role = schema->operands[k].role; @@ -1054,7 +1150,7 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, int64_t nonfinite_gap = 0; int n_out = 0; std::string per_opd; - for (size_t k = 0; k < n_opd; ++k) { + for (size_t k = 0; k < n_opd && !timing_only; ++k) { const KfOperand& d = c.opd[k]; if (d.absent || !d.have_ref) continue; const int role = schema->operands[k].role; @@ -1109,13 +1205,17 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, } ++n_out; } - if (n_out == 0) { ++st->skipped; release(); return RAD_OK; } + if (n_out == 0 && !timing_only) { ++st->skipped; release(); return RAD_OK; } const double tol = worst_tol; const bool ok = nonfinite_gap == 0 && all_ok; - ++st->checked; - st->worst = std::max(st->worst, worst_rel); - if (ok) ++st->passed; else ++st->failed; + if (timing_only) { + ++st->timed; + } else { + ++st->checked; + st->worst = std::max(st->worst, worst_rel); + if (ok) ++st->passed; else ++st->failed; + } /* ---------------------------------------------------------------- and the clock */ double case_us = -1, case_spread = -1; @@ -1130,7 +1230,7 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, rw.plugin = lib; rw.geom = g.str(); rw.domain = domain_name(dom); - rw.verdict = ok ? "ok" : "**FAIL**"; + rw.verdict = timing_only ? "timed" : ok ? "ok" : "**FAIL**"; rw.rel_l2 = worst_rel; rw.tol = tol; rw.us = case_us; @@ -1140,11 +1240,11 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M, if (!d.absent) rw.bytes += rad_dtype_bytes(d.dtype, rad_numel(d.shape)); rows->push_back(std::move(rw)); - if (!ok || verbose) + if (!timing_only && (!ok || verbose)) std::printf(" %-22s %-44s %-8s %-28s rel=%.3e max_abs=%.3e max_rel=%.3e tol=%.1e %s\n", c.op.c_str(), g.str().c_str(), domain_name(dom), row->info->name, worst_rel, worst_abs, worst_max_rel, tol, ok ? "ok" : "FAIL"); - if (!ok && n_out > 1) std::printf(" per operand: %s\n", per_opd.c_str()); + if (!timing_only && !ok && n_out > 1) std::printf(" per operand: %s\n", per_opd.c_str()); return RAD_OK; } @@ -1189,6 +1289,7 @@ int replay(const Kfixture& fx, const std::string& home, const std::vector& op_filters, double tol_override, int max_cases, int64_t max_case_bytes, bool bench, int bench_iters, int bench_reps, int bench_warm_ms, bool verbose, + bool timing_only, const std::string& report_path, const std::string& fixture_path, const std::string& analysis_path) { /* The plugins, and NOT an architecture: a kernel library is checked without one, which is @@ -1380,6 +1481,8 @@ int replay(const Kfixture& fx, const std::string& home, for (const std::string& lib : libs) { for (int dom = 0; dom < RAD_N_DOMAINS; ++dom) { + /* A timing-only run times device kernels; a host row has no clock here. */ + if (timing_only && dom != RAD_DOMAIN_DEVICE) continue; const KernelRow* row = row_in(lib, c.op, g, dom); if (!row) continue; if (max_cases > 0) { @@ -1424,7 +1527,7 @@ int replay(const Kfixture& fx, const std::string& home, } const int rc = replay_one(c, g, M, in, planes, row, lib, dom, schema, tol_override, bench, bench_iters, bench_reps, bench_warm_ms, verbose, - &st, &report_rows, &skipped_ops, + timing_only, &st, &report_rows, &skipped_ops, &dcache, &dcache_bytes, dcache_budget, &overruns); (void)rc; } @@ -1446,6 +1549,9 @@ int replay(const Kfixture& fx, const std::string& home, std::printf("\n%d checked, %d passed, %d failed, %d skipped, %d diverged, %d capped. " "worst rel_l2 = %.3e\n", st.checked, st.passed, st.failed, st.skipped, st.diverged, st.capped, st.worst); + if (timing_only) + std::printf("%d timed. Timing only: nothing was checked against a reference.\n", + st.timed); std::printf("memory: %d case(s) ran inside guarded allocations, %d wrote outside one\n", st.guarded, st.overrun); print_row_coverage(census(reg, ref_name), report_rows); @@ -1521,6 +1627,13 @@ void usage() { " Also bounds the weight caches.\n" " --bench time each case that passes, in the same pass and on the same\n" " bytes. See the caveat the report prints about the GB/s column.\n" + " --timing-only time every device kernel and check nothing: no reference run, no\n" + " comparison, no margins, no fusion chain, host rows skipped. For\n" + " comparing builds a full run has already checked. Implies --bench.\n" + " --bench-flush MIB time cold: read MIB through the caches before every timed\n" + " launch (256 empties this card's 8 MiB L2 and 64 MiB last level),\n" + " and time each launch alone on the device. The engine reads its\n" + " weights cold; a warm loop can hide or invent a difference.\n" " --bench-iters N launches per timed rep (default 20)\n" " --bench-reps N timed reps, median reported (default 3)\n" " --bench-warm-ms N untimed launches before each timed window, in ms (default 500).\n" @@ -1600,6 +1713,10 @@ int main(int argc, char** argv) { * nothing checks is a comment. --no-fusion is for bisecting, not for passing. */ bool fuse_check = true; bool bench = false; + /* TIME, DO NOT CHECK: for comparing builds whose correctness a full run has already shown. + * The reference implementation is what a run spends most of its time in -- every case is also + * run on the host -- and a timing comparison between two builds repeats it for nothing. */ + bool timing_only = false; std::string report_path; int bench_iters = 20, bench_reps = 3; /* Untimed launches before the timed window. Half a second, which is what libr4d's own @@ -1643,6 +1760,11 @@ int main(int argc, char** argv) { max_case_bytes = (int64_t)std::atoll(next("--max-bytes")) << 20; else if (a == "--no-fusion") fuse_check = false; else if (a == "--bench") bench = true; + else if (a == "--timing-only") timing_only = true; + else if (a == "--bench-flush") { + g_bench_flush = (int64_t)std::atoll(next("--bench-flush")) << 20; + bench = true; + } else if (a == "--bench-iters") bench_iters = std::atoi(next("--bench-iters")); else if (a == "--bench-reps") bench_reps = std::atoi(next("--bench-reps")); else if (a == "--bench-warm-ms") bench_warm_ms = std::atoi(next("--bench-warm-ms")); @@ -1653,6 +1775,16 @@ int main(int argc, char** argv) { a.c_str()); return 2; } } + if (timing_only) { + if (!record_path.empty()) { + std::fprintf(stderr, "rad-kbench: --timing-only runs no reference, so it has nothing to " + "record; drop one of --timing-only and --record\n"); + return 2; + } + bench = true; /* it is the clock or nothing */ + fuse_check = false; /* the fusion oracle is a check too */ + } + /* THE CASE BUDGET, RESOLVED FROM WHAT THE MACHINE HAS IF NOBODY SAID. * * Half of what is free right now, and never more than 8 GiB -- so a machine with room checks @@ -1695,8 +1827,8 @@ int main(int argc, char** argv) { return 1; } return replay(fx, home, hierarchy, ref_name, op_filters, tol_override, max_cases, max_case_bytes, - bench, bench_iters, bench_reps, bench_warm_ms, verbose, report_path, fixture_path, - analysis_path); + bench, bench_iters, bench_reps, bench_warm_ms, verbose, timing_only, + report_path, fixture_path, analysis_path); } RadFile f; @@ -2043,9 +2175,12 @@ int main(int argc, char** argv) { * oracle with it, and a better one: the claim is byte-identity against its own * plugin's chain, not closeness to a host reference. On a model with many fused * ops this is the difference between a page of skips and a page of checks. */ + /* A timing-only run times the device kernels: a host row has no clock here, and a + * kernel with no oracle is timed on its own description of its operands. */ + if (timing_only && dom != RAD_DOMAIN_DEVICE) continue; const bool fuse_only = !oracle && fuse_check && dom == RAD_DOMAIN_DEVICE && r.row->info->replaces; - if (!oracle && !fuse_only) { + if (!oracle && !fuse_only && !timing_only) { /* ref's op list is the conventional vocabulary; an op outside it has no * fallback AND no oracle, and that is a deliberate decision (spec ยง17). */ skipped_ops[o.op + " (no " + ref_name + " kernel: no oracle exists for it)"]++; @@ -2557,9 +2692,9 @@ int main(int argc, char** argv) { * no median -- libref is the definition of the op and not a contender, and a * column that pretended otherwise would invite tuning it. */ const auto tref0 = std::chrono::steady_clock::now(); - const int s_ref = oracle ? launch(oracle, t_ref, scratch_b) : RAD_OK; + const int s_ref = oracle && !timing_only ? launch(oracle, t_ref, scratch_b) : RAD_OK; const double ref_us = - oracle && s_ref >= 0 + oracle && !timing_only && s_ref >= 0 ? std::chrono::duration( std::chrono::steady_clock::now() - tref0).count() : -1.0; @@ -2580,8 +2715,8 @@ int main(int argc, char** argv) { * * So: copy the outputs the checked launch produced into the host buffers first, * then time on the device tensors, which are still bound to device memory and are - * repointed at the host only afterwards. */ - if (dom == RAD_DOMAIN_DEVICE && s_test >= 0) { + * repointed at the host only afterwards. A timing-only run reads nothing back. */ + if (dom == RAD_DOMAIN_DEVICE && s_test >= 0 && !timing_only) { for (size_t k = 0; k < sh.size(); ++k) { if (!dev[k].p) continue; const int role = o.schema->operands[k].role; @@ -2598,7 +2733,7 @@ int main(int argc, char** argv) { * correctness verdict is about did. The margin is reported by the side it is on * and by how far in it was touched, because "wrote 4 bytes past the end" and * "wrote 208 bytes past the end" are different bugs. */ - if (dom == RAD_DOMAIN_DEVICE && s_test >= 0) { + if (dom == RAD_DOMAIN_DEVICE && s_test >= 0 && !timing_only) { auto margin_check = [&](const DevBuf& d, const std::string& what) { if (!d.on) return; uint8_t lo[RED_BYTES], hi[RED_BYTES]; @@ -2935,6 +3070,25 @@ int main(int argc, char** argv) { continue; } + if (timing_only) { + ++st.timed; + Row rw; + rw.op = o.op; + rw.kernel = r.row->info->name; + rw.plugin = r.row->plugin; + rw.geom = g.str(); + rw.domain = domain_name(dom); + rw.choice = r.choice; + rw.verdict = "timed"; + rw.us = case_us; + rw.us_spread = case_spread; + rw.synthesised = !from_container; + for (size_t k = 0; k < sh.size(); ++k) + if (!sh[k].absent) rw.bytes += (int64_t)bufs[k].size(); + report_rows.push_back(std::move(rw)); + continue; + } + /* Compare every OUT and INOUT operand, AND NAME THE WORST ONE. An op with five * outputs reports one number, and which output carries it is most of the * diagnosis: `gdn_conv_update` writing a correct q and k and a wrong conv_state is @@ -3117,13 +3271,16 @@ int main(int argc, char** argv) { std::printf("\n%d checked, %d passed, %d failed, %d skipped, %d diverged, %d capped. " "worst rel_l2 = %.3e\n", st.checked, st.passed, st.failed, st.skipped, st.diverged, st.capped, st.worst); + if (timing_only) + std::printf("%d timed. Timing only: nothing was checked against a reference.\n", + st.timed); std::printf("memory: %d case(s) ran inside guarded allocations, %d wrote outside one\n", st.guarded, st.overrun); print_row_coverage(census(reg, ref_name), report_rows); if (st.failed == 0 && st.checked > 0) std::printf("every resolved kernel agrees with %s on this container's bytes\n", ref_name.c_str()); - if (st.checked == 0) + if (st.checked == 0 && !timing_only) std::printf("NOTHING WAS CHECKED. Either every op resolved to %s (so there is nothing to " "falsify) or no op has a shape recipe.\n", ref_name.c_str()); if (!report_path.empty()) { diff --git a/tools/tokref.cpp b/tools/tokref.cpp index c3f6d596..eae562b1 100644 --- a/tools/tokref.cpp +++ b/tools/tokref.cpp @@ -424,14 +424,12 @@ void bpe(const Vocab& v, const std::vector& words, std::vector= 0 && v.type(v.find(word)) == RAD_TT_USER_DEFINED) { + * ORDINARY VOCABULARY ENTRIES GO THROUGH THE MERGE LOOP unless the vocabulary sets + * `ignore_merges`, which takes any non-control entry whole (core/text/tokenizer.cpp, + * bpe_word, says why control entries are excluded). */ + const int32_t whole = v.find(word); + if (whole >= 0 && (v.type(whole) == RAD_TT_USER_DEFINED || + (v.build().ignore_merges && v.type(whole) != RAD_TT_CONTROL))) { symbols.push_back({ -1, -1, word.c_str(), word.size() }); offset = word.size(); }