diff --git a/.agents/skills/benchmark-model/SKILL.md b/.agents/skills/benchmark-model/SKILL.md index b1ea73261c..4c6e0f23d9 100644 --- a/.agents/skills/benchmark-model/SKILL.md +++ b/.agents/skills/benchmark-model/SKILL.md @@ -7,10 +7,10 @@ metadata: # Benchmark a model -Fill or refresh `docs/models//BENCHMARKS.md` for one model. Which +Fill or refresh `docs/internal/models//BENCHMARKS.md` for one model. Which tables exist and which external project is the comparison baseline depend on the model category below. Read the model's `README.md`, `BENCHMARKS.md` and -`QUALITY.md` first, then [docs/BENCHMARKS.md](../../../docs/BENCHMARKS.md) +`QUALITY.md` first, then [docs/internal/benchmarks.md](../../../docs/internal/benchmarks.md) for methodology. Follow the user's machine, time and Git instructions. ## Start @@ -46,12 +46,12 @@ Match prompt tokens, prefill interval, decode accounting and cache frontier firs label the native timing scope. Never silently compare it with whole-request HTTP wall time. `ds4-bench` does not implement C>1. -The driver is `tools/bench/model-bench.py`. `docs/models//artifacts/bench.json` +The driver is `tools/bench/model-bench.py`. `docs/internal/models//artifacts/bench.json` declares the category, variant ids, sweep grid, workloads and reference server flags; model file paths are passed on the command line. The driver launches the right server itself on a private port, runs one target at a time, writes one JSON per table (and per mode for concurrency tables) into -`docs/models//artifacts/`, and renders the Markdown tables between +`docs/internal/models//artifacts/`, and renders the Markdown tables between `` markers in `BENCHMARKS.md`: ```sh @@ -91,14 +91,16 @@ in a refresh, blank those cells to `TODO` by hand rather than leave an old number next to a fresh reference. Reference cells always come from artifacts. It draws one SVG chart per table with data into -`docs/models//artifacts/charts/` (matplotlib, deterministic output), +`docs/internal/models//artifacts/charts/` (matplotlib, deterministic output), placed as an image line right after the table. Tables stay the source of truth for agents; charts are an addition for readers. `--no-charts` skips them. Starting a new model: copy `assets/llm-bench-template.json` to -`docs/models//artifacts/bench.json` and +`docs/internal/models//artifacts/bench.json` and `assets/llm-benchmarks-template.md` to the card, replace the placeholders, -delete the tables the model does not have, and render. The template mirrors +delete the tables the model does not have (and the `speculative` block for a +model without a speculative mode; its loading table then loads AR), and render. +The template mirrors the Qwen3.8-Flash-Next card, including which prose belongs next to each table. @@ -171,7 +173,7 @@ and the table says so. 5. A supported cell without a current qualified measurement is `TODO`, never a stale number; an unsupported comparison is `N/A`. Keep measurement dates; do not sum stage medians into a headline. -6. Retained JSON goes to `docs/models//artifacts/`; raw samples, +6. Retained JSON goes to `docs/internal/models//artifacts/`; raw samples, traces, audio, images and videos stay in the ignored top-level `artifacts/`. ## Results-card format @@ -221,7 +223,7 @@ Every headline table carries the reference project next to Gufo: - A reference cell the host cannot produce for hardware reasons — the reference is OOM-killed at the required context, the model does not fit — is `N/A`. Missing reference features that prevent a close comparison are also - `N/A`, with a concise reason. `TODO` means a supported measurement is pending. Declare `N/A` cells in `docs/models//artifacts/unavailable.json` + `N/A`, with a concise reason. `TODO` means a supported measurement is pending. Declare `N/A` cells in `docs/internal/models//artifacts/unavailable.json` (`{"": {"" | "*": ""}}`; the suffix `-speculative` on a concurrency table id targets only its speculative reference column) and state the reason under the table. `render` prints diff --git a/.agents/skills/optimize-kernel/SKILL.md b/.agents/skills/optimize-kernel/SKILL.md index 3962d24963..c61eeb9438 100644 --- a/.agents/skills/optimize-kernel/SKILL.md +++ b/.agents/skills/optimize-kernel/SKILL.md @@ -7,7 +7,7 @@ metadata: # Optimize gfx1151 kernels -Read the affected model's `docs/models//{BENCHMARKS,QUALITY,EXPERIMENTS}.md` +Read the affected model's `docs/internal/models//{BENCHMARKS,QUALITY,EXPERIMENTS}.md` and its launch code. Establish the timed scope and arithmetic contract before changing dispatch. Follow the user's machine, time, and Git instructions. diff --git a/.clang-tidy b/.clang-tidy index 664feaada7..9b82f8802f 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,25 +1,14 @@ --- +# Block on correctness defects; the broader style/performance audit is opt-in. Checks: > -*, - bugprone-*, - cert-*, clang-analyzer-*, - cppcoreguidelines-*, - misc-*, - performance-*, - -cppcoreguidelines-avoid-c-arrays, - -cppcoreguidelines-pro-bounds-pointer-arithmetic, - -cppcoreguidelines-pro-bounds-array-to-pointer-decay, - -cppcoreguidelines-pro-bounds-constant-array-index, - -cppcoreguidelines-pro-type-reinterpret-cast, - -cppcoreguidelines-pro-type-vararg, - -cppcoreguidelines-avoid-magic-numbers, - -cppcoreguidelines-init-variables, - -bugprone-easily-swappable-parameters, - -misc-include-cleaner, - -misc-use-anonymous-namespace, - -misc-non-private-member-variables-in-classes - + bugprone-use-after-move, + bugprone-dangling-handle, + bugprone-sizeof-expression, + bugprone-suspicious-memset-usage, + bugprone-undefined-memory-manipulation, + bugprone-suspicious-string-compare WarningsAsErrors: '*' HeaderFilterRegex: 'src/.*' FormatStyle: file diff --git a/.devops/nix/extension-modules.nix b/.devops/nix/extension-modules.nix new file mode 100644 index 0000000000..5dfc4fc538 --- /dev/null +++ b/.devops/nix/extension-modules.nix @@ -0,0 +1,65 @@ +# Extensions built as loadable modules for one gufo package (gufo-org/gufo#1075), +# with the same `gufo extension install` that users run, against the package's +# own SDK output. +{ + lib, + runCommand, + makeWrapper, +}: + +rec { + # `gufo` with its SDK: `gufo extension install` works out of the box. + withSdk = + gufo: + runCommand "gufo-sdk-${gufo.version}" + { + nativeBuildInputs = [ makeWrapper ]; + meta.mainProgram = "gufo"; + } + '' + mkdir -p $out/bin + makeWrapper ${gufo}/bin/gufo $out/bin/gufo \ + --set-default GUFO_SDK_DIR ${gufo.sdk}/lib/gufo/sdk + ln -s gufo $out/bin/gufo-server + ''; + + # A read-only extension store holding `extensions`, pinned sources such as + # non-flake inputs. Unvalidated code: review each source before adding it. + store = + { + gufo, + extensions, + }: + runCommand "gufo-extension-modules-${gufo.version}" { } '' + export HOME=$TMPDIR + export GUFO_SDK_DIR=${gufo.sdk}/lib/gufo/sdk + export GUFO_EXTENSIONS_DIR=$out + ${lib.concatMapStringsSep "\n" ( + extension: "${gufo}/bin/gufo extension install ${extension} --yes" + ) extensions} + rm -f $out/.lock + ${gufo}/bin/gufo extension list + ''; + + # `gufo` that loads `extensions` as modules in every command. + withExtensions = + { + gufo, + extensions, + }: + let + modules = store { inherit gufo extensions; }; + in + runCommand "gufo-with-extensions-${gufo.version}" + { + nativeBuildInputs = [ makeWrapper ]; + passthru = { inherit modules; }; + meta.mainProgram = "gufo"; + } + '' + mkdir -p $out/bin + makeWrapper ${gufo}/bin/gufo $out/bin/gufo \ + --set-default GUFO_EXTENSIONS_DIR ${modules} + ln -s gufo $out/bin/gufo-server + ''; +} diff --git a/.devops/nix/hrx/README.md b/.devops/nix/hrx/README.md new file mode 100644 index 0000000000..a288f731ff --- /dev/null +++ b/.devops/nix/hrx/README.md @@ -0,0 +1,36 @@ +# HRX staging + +Gufo's experimental HRX packages use +[`gufo-org/hrx-system`](https://github.com/gufo-org/hrx-system). The source +revision in `default.nix` is an exact commit from +[`gufo-staging`](https://github.com/gufo-org/hrx-system/tree/gufo-staging), +so advancing that branch does not silently change a Gufo build. + +Each upstream candidate starts from upstream `main` on its own `fix/` +branch, containing only that fix and its regression coverage. Combine validated +candidates on `gufo-staging`; keep the fix branches independent so upstream can +review and merge them separately. Staging merges the independent candidates +without adding unrelated changes. + +| Fix branch | Purpose | +| --- | --- | +| [`fix/cached-kernel-arguments`](https://github.com/gufo-org/hrx-system/tree/fix/cached-kernel-arguments) ([upstream PR #3035](https://github.com/ROCm/hrx-system/pull/3035)) | Give PM4 argument generations GPU-cached host-coherent backing independently of native queue control cells. | +| [`fix/upload-cache-state`](https://github.com/gufo-org/hrx-system/tree/fix/upload-cache-state) ([upstream PR #3036](https://github.com/ROCm/hrx-system/pull/3036)) | Use native transfers for synchronous uploads into device allocations, preserving GPU read performance. Experimental; small-copy preparation can cost more. | + +The staging base includes upstream's loader search-path and queue-policy fixes, +so Gufo no longer applies its corresponding patches. The two remaining local +patches enable optional capture diagnostics and unfinished profile-session +reading; neither changes normal runtime behavior. + +After staging changes: + +1. Update `revision` and the source `hash` in `default.nix` to the tested staging + commit. Keep the commit immutable once Gufo pins it. +2. If dependency pins changed, temporarily set the dependency `outputHash` to + `lib.fakeHash`, build `.#hrx.passthru.deps`, and retain the reported hash. +3. Build `.#gufo-hrx`, check correctness and matched timings for affected + workloads, and record the revisions and results in + `docs/internal/hrx-migration.md`. +4. When upstream incorporates a fix, merge the updated upstream base into + staging, resolve any duplicated implementation, and repeat qualification. + Do not add another local copy of an upstreamed fix. diff --git a/.devops/nix/hrx/default.nix b/.devops/nix/hrx/default.nix new file mode 100644 index 0000000000..86538b275e --- /dev/null +++ b/.devops/nix/hrx/default.nix @@ -0,0 +1,163 @@ +# Experimental: HRX (https://github.com/ROCm/hrx-system), AMD's alternative HIP +# runtime, built for gfx1151 on its native libamdf driver. It installs a +# drop-in `libamdhip64.so.7` plus the `hrx-info` and `iree-profile` tools. +# Not part of the default package, hosted checks or releases; see +# docs/internal/hrx-migration.md for the measurements behind the patches. +{ + lib, + fetchFromGitHub, + stdenvNoCC, + cacert, + cmake, + curl, + git, + ninja, + python3, + rocmPackages, + # Also build Loom's compiler and serving tools with AMD GPU (gfx1151) and + # XDNA NPU targets, plus `loom-fetch`. + withLoom ? false, +}: + +let + # Exact commit of gufo-org/hrx-system's gufo-staging branch. Individual + # fixes remain on independent branches for upstream review; see README.md. + revision = "2ebcaaece8fa731cf2e14e978c9f6242540c3341"; + + src = fetchFromGitHub { + owner = "gufo-org"; + repo = "hrx-system"; + rev = revision; + hash = "sha256-da6x7wU4whbgVNSIaUrQsbIl0x529gyMiUQHEkTjJwc="; + }; + + # Every download pinned in MODULE.cmake.lock and Loom's ISA XML descriptor, + # fetched once so the configure step can run without network access. + deps = stdenvNoCC.mkDerivation { + pname = "hrx-system-deps"; + version = "0-unstable-2026-11-11"; + inherit src; + nativeBuildInputs = [ + cacert + curl + python3 + ]; + dontConfigure = true; + buildPhase = '' + runHook preBuild + python3 ${./hrx-deps.py} fetch . $out + runHook postBuild + ''; + dontInstall = true; + dontFixup = true; + outputHashMode = "recursive"; + outputHashAlgo = "sha256"; + outputHash = "sha256-yIMgpPVc9lnSaGnkGgOIeUUiweN04uj+sHVm49WWAH8="; + }; + + llvm = rocmPackages.llvm; + loomTools = [ + "loom-serve" + "loom-compile" + "loom-import-cxx" + "loom-format" + "loom-benchmark" + "loom-test" + ]; +in +llvm.rocmClangStdenv.mkDerivation { + pname = if withLoom then "hrx-system-loom" else "hrx-system"; + version = "0-unstable-2026-11-11"; + inherit src; + + patches = [ + # HRX_DEBUG_CAPTURE=1 prints a backtrace where a graph capture is + # invalidated, naming the HIP call that broke it. + ../patches/hrx-debug-capture.patch + # IREE_PROFILE_ALLOW_OPEN_SESSION=1 lets iree-profile read a trace whose + # process exited without ending the profiling session, as Gufo does. + ../patches/hrx-profile-open-session.patch + ]; + + postPatch = '' + python3 ${./hrx-deps.py} rewrite . ${deps} + ''; + + # The pinned ROCm toolchain already includes lld. Depending on the separate + # llvm.lld derivation needlessly rebuilds LLVM instead of using that linker. + nativeBuildInputs = [ + cmake + ninja + git + python3 + llvm.clang + ]; + + cmakeFlags = [ + "-DCMAKE_BUILD_TYPE=Release" + "-DIREE_ROCM_DEPENDENCY_MODE=pinned" + "-DIREE_HAL_AMDGPU_TARGETS=gfx1151" + "-DIREE_HAL_AMDGPU_DEVICE_TOOLCHAIN=llvm-tools" + "-DIREE_HAL_AMDGPU_DEVICE_TOOLCHAIN_LLVM_TOOLS_DIR=${llvm.clang}/bin" + "-DIREE_HAL_AMDGPU_DEVICE_TOOLCHAIN_ROCM_DEVICE_LIB_PATH=${rocmPackages.rocm-device-libs}/amdgcn/bitcode" + "-DIREE_BUILD_TESTS=OFF" + "-DIREE_ENABLE_WERROR_FLAG=OFF" + "-DCMAKE_EXE_LINKER_FLAGS=-fuse-ld=lld" + "-DCMAKE_SHARED_LINKER_FLAGS=-fuse-ld=lld" + "-DCMAKE_MODULE_LINKER_FLAGS=-fuse-ld=lld" + ] + ++ lib.optionals withLoom [ + "-DLOOM_TARGET_ALL_AMD=ON" + "-DLOOM_ARCH_AMDGPU_TARGETS=gfx1151" + "-DLOOM_IMPORT_CXX=ON" + ]; + + ninjaFlags = [ + "libhrx/src/binding/hip/libamdhip64.so" + "hrx-info" + "iree-profile" + ] + ++ lib.optionals withLoom (map (tool: "loom/src/loom/tools/${tool}/${tool}") loomTools); + + installPhase = '' + runHook preInstall + install -Dm755 libhrx/src/binding/hip/libamdhip64.so.7.9999.0 \ + $out/lib/libamdhip64.so.7.9999.0 + ln -s libamdhip64.so.7.9999.0 $out/lib/libamdhip64.so.7 + ln -s libamdhip64.so.7 $out/lib/libamdhip64.so + install -Dm755 libhrx/tools/hrx-info $out/bin/hrx-info + install -Dm755 runtime/src/iree/tools/iree-profile/iree-profile \ + $out/bin/iree-profile + '' + + lib.optionalString withLoom '' + for tool in ${lib.concatStringsSep " " loomTools}; do + install -Dm755 loom/src/loom/tools/$tool/$tool $out/bin/$tool + done + # loom-fetch is the pure-Python model acquisition tool. + mkdir -p $out/share/loom + cp -r $src/loom/py $out/share/loom/py + cat > $out/bin/loom-fetch < + hrx-deps.py rewrite +""" + +import hashlib +import os +import re +import subprocess +import sys + +LOCK = "MODULE.cmake.lock" +ARCHIVE_DESCRIPTORS = ["loom/build_tools/amdgpu/isa_xml/archive.bzl"] + + +def pinned_downloads(source): + """Returns [(sha256, [urls])] for every pinned download.""" + downloads = [] + with open(os.path.join(source, LOCK), encoding="utf-8") as lock: + text = lock.read() + hashes = dict(re.findall(r'set\(IREE_DEP_(\w+)_SHA256 "([0-9a-f]{64})"\)', text)) + for name, block in re.findall(r"set\(IREE_DEP_(\w+)_URLS\n(.*?)\)", text, re.S): + urls = re.findall(r'"([^"]+)"', block) + if urls and name in hashes: + downloads.append((hashes[name], urls)) + for descriptor in ARCHIVE_DESCRIPTORS: + with open(os.path.join(source, descriptor), encoding="utf-8") as f: + text = f.read() + sha256 = re.search(r'"sha256": "([0-9a-f]{64})"', text).group(1) + urls = re.findall(r'"(https://[^"]+)"', text) + downloads.append((sha256, urls)) + return downloads + + +def store_name(sha256, url): + # Keep the URL's file name so CMake recognizes the archive type. + base = url.split("?")[0].rstrip("/").split("/")[-1] or "file" + return f"{sha256}-{base}" + + +def fetch(source, out): + os.makedirs(out, exist_ok=True) + for sha256, urls in pinned_downloads(source): + target = os.path.join(out, store_name(sha256, urls[0])) + for url in urls: + partial = target + ".partial" + result = subprocess.run( + ["curl", "-fsSL", "--retry", "3", "-o", partial, url]) + if result.returncode != 0: + continue + with open(partial, "rb") as f: + digest = hashlib.sha256(f.read()).hexdigest() + if digest == sha256: + os.rename(partial, target) + break + os.remove(partial) + else: + sys.exit(f"no URL matched {sha256}: {urls}") + + +def rewrite(source, deps): + replacements = {} + for sha256, urls in pinned_downloads(source): + local = "file://" + os.path.join(deps, store_name(sha256, urls[0])) + if not os.path.exists(local[len("file://"):]): + sys.exit(f"missing prefetched download for {urls[0]}") + for url in urls: + replacements[url] = local + files = [LOCK] + ARCHIVE_DESCRIPTORS + for relative in files: + path = os.path.join(source, relative) + with open(path, encoding="utf-8") as f: + text = f.read() + for url, local in replacements.items(): + text = text.replace(f'"{url}"', f'"{local}"') + with open(path, "w", encoding="utf-8") as f: + f.write(text) + + +if __name__ == "__main__": + command, source, directory = sys.argv[1:4] + {"fetch": fetch, "rewrite": rewrite}[command](source, directory) diff --git a/.devops/nix/mk-serve.nix b/.devops/nix/mk-serve.nix index 8275920941..7586a32493 100644 --- a/.devops/nix/mk-serve.nix +++ b/.devops/nix/mk-serve.nix @@ -356,19 +356,27 @@ let "--speculative" speculative ] - ++ lib.optionals (draftTokens != null) [ + ++ lib.optionals (lib.warnIf (draftTokens != null) + "gufo serve: draftTokens is deprecated and ignored; each model sets its draft length" + (draftTokens != null)) [ "--draft-tokens" (toString draftTokens) ] - ++ lib.optionals (draftPolicy != null) [ + ++ lib.optionals (lib.warnIf (draftPolicy != null) + "gufo serve: draftPolicy is deprecated and ignored; each model sets its draft length" + (draftPolicy != null)) [ "--draft-policy" draftPolicy ] - ++ lib.optionals (minDraftTokens != null) [ + ++ lib.optionals (lib.warnIf (minDraftTokens != null) + "gufo serve: minDraftTokens is deprecated and ignored; each model sets its draft length" + (minDraftTokens != null)) [ "--min-draft-tokens" (toString minDraftTokens) ] - ++ lib.optionals (prefillChunk != null) [ + ++ lib.optionals (lib.warnIf (prefillChunk != null) + "gufo serve: prefillChunk is deprecated and ignored; prompts beside decoders are split by layers" + (prefillChunk != null)) [ "--prefill-chunk" (toString prefillChunk) ] diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index a3462037b2..7628e3b30d 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -10,12 +10,17 @@ libpng, libjpeg, libwebp, + libopus, libsndfile, soxr, openssl, ffmpeg-headless, ccache, + rustToolchain, + rustPlatform, rocmPackages, + rdma-core ? null, + enableTp2Rdma ? false, releaseVersion ? null, extensionsFromLock ? false, extensions ? [ ], @@ -30,6 +35,35 @@ let rocmRuntime = rocmPackages.rocm-runtime.overrideAttrs (old: { patches = (old.patches or [ ]) ++ [ ./patches/rocr-fixed-cwsr-rocm10.patch ]; }); + # The CI timing baseline builds an older revision with this definition; before + # the Cargo workspace, the lockfile sat next to the PNG decoder. + cargoSetup = import ./rust-cargo.nix { + inherit lib rustPlatform; + lockFile = + if builtins.pathExists (sourceRoot + "/Cargo.lock") then + sourceRoot + "/Cargo.lock" + else + sourceRoot + "/src/core/png_decode/Cargo.lock"; + }; + # The CI timing baseline builds an older revision with this definition; + # before the Rust audio decoder, EmbeddingGemma 2 linked libsndfile and soxr. + hasRustAudio = builtins.pathExists (sourceRoot + "/src/core/audio_decode/Cargo.toml"); + # A store path has no Git metadata. A flake input or fetcher result still + # names its commit (`dirtyRev` ends in "-dirty") or at least the hash of its + # tree; a plain path names nothing. + extensionRevision = + ext: + let + revision = + if builtins.isAttrs ext then + ext.rev or ext.dirtyRev or ext.narHash or ext.outputHash or "unknown" + else + "unknown"; + in + if builtins.isString revision && revision != "" && !(lib.hasInfix ";" revision) then + revision + else + "unknown"; versionLabel = if releaseVersion == null then "development" else releaseVersion; packageVersion = if releaseVersion == null then "0-unstable-${revision}" else releaseVersion; @@ -37,6 +71,8 @@ let # Revisions before model extensions have no extensions.lock, keep the eval # fixture under the DeepSeek tests and report no extension selection. hasExtensions = builtins.pathExists (sourceRoot + "/extensions.lock"); + # Revisions before extension modules have no SDK to install. + hasExtensionSdk = builtins.pathExists (sourceRoot + "/cmake/GufoExtensionSdk.cmake"); evalFixture = if hasExtensions then "tests/fixtures/eval/antirez-ds4.json" @@ -52,7 +88,7 @@ let relativePath = lib.removePrefix "${root}/" pathString; in pathString == root - || builtins.elem relativePath [ "CMakeLists.txt" "LICENSE" "NOTICE" "THIRD_PARTY_NOTICES.md" "extensions.lock" ] + || builtins.elem relativePath [ "CMakeLists.txt" "LICENSE" "NOTICE" "THIRD_PARTY_NOTICES.md" "extensions.lock" "rust-toolchain.toml" "Cargo.toml" "Cargo.lock" ] || relativePath == "licenses" || lib.hasPrefix "licenses/" relativePath || relativePath == "cmake" @@ -86,12 +122,16 @@ stdenv.mkDerivation { pname = "gufo"; version = packageVersion; src = productionSource; + # The extension SDK pins the build toolchain, so it lives in its own output: + # the runtime closure stays free of compilers and development libraries. + outputs = [ "out" ] ++ lib.optional hasExtensionSdk "sdk"; nativeBuildInputs = [ cmake ninja pkg-config makeWrapper + rustToolchain rocmPackages.clr ]; @@ -101,8 +141,7 @@ stdenv.mkDerivation { libpng libjpeg libwebp - libsndfile - soxr + libopus openssl ffmpeg-headless rocmPackages.clr @@ -112,6 +151,10 @@ stdenv.mkDerivation { rocmPackages.rocprim rocmPackages.rocwmma rocmPackages.rocblas + ] ++ lib.optionals enableTp2Rdma [ rdma-core rdma-core.dev ] + ++ lib.optionals (!hasRustAudio) [ + libsndfile + soxr ]; cmakeFlags = [ @@ -123,13 +166,18 @@ stdenv.mkDerivation { "-DGUFO_FFMPEG_EXECUTABLE=${ffmpeg-headless}/bin/ffmpeg" "-DGUFO_FFPROBE_EXECUTABLE=${ffmpeg-headless}/bin/ffprobe" "-DCMAKE_HIP_COMPILER=${rocmPackages.llvm.clang}/bin/clang" - ] ++ lib.optional (extensions != [ ]) "-DGUFO_EXTENSION_DIRS=${lib.concatMapStringsSep ";" (ext: "${ext}") extensions}"; + ] ++ lib.optionals enableTp2Rdma [ "-DGUFO_ENABLE_TP2_RDMA=ON" ] + ++ lib.optional hasExtensionSdk "-DGUFO_SDK_INSTALL_DIR=${placeholder "sdk"}/lib/gufo/sdk" + ++ lib.optionals (extensions != [ ]) [ + "-DGUFO_EXTENSION_DIRS=${lib.concatMapStringsSep ";" (ext: "${ext}") extensions}" + "-DGUFO_EXTENSION_DIR_REVISIONS=${lib.concatMapStringsSep ";" extensionRevision extensions}" + ]; # CI exposes a persistent /tmp/gufo-ccache through extra-sandbox-paths for # C/C++ sources. Keep HIP uncached: Clang emits a bundled preprocessor output # whose included headers ccache 4.13.6 does not record. A header-only change # can then reuse a stale HIP object, including one from the timing baseline. - preConfigure = '' + preConfigure = cargoSetup + '' ccache_dir=/tmp/gufo-ccache if [[ -d "$ccache_dir" && -w "$ccache_dir" ]]; then export CCACHE_DIR="$ccache_dir" @@ -170,6 +218,16 @@ stdenv.mkDerivation { test ! -e $out/bin/gufo-kernel-bench test -f $out/share/licenses/gufo/LICENSE test -f $out/share/licenses/gufo/third-party/LICENSE.ds4 + ${lib.optionalString enableTp2Rdma '' + test -e ${lib.getLib rdma-core}/lib/libibverbs.so + test -f $out/share/licenses/gufo/third-party/rdma-core/COPYING.GPL2 + ''} + '' + lib.optionalString hasExtensionSdk '' + test ! -e $out/lib/gufo/sdk + test -f $sdk/lib/gufo/sdk/profile.cmake + GUFO_SDK_DIR=$sdk/lib/gufo/sdk GUFO_EXTENSIONS_DIR=$TMPDIR/extensions \ + $out/bin/gufo extension list --json > extension-list.json + '' + '' runHook postInstallCheck ''; diff --git a/.devops/nix/patches/hrx-debug-capture.patch b/.devops/nix/patches/hrx-debug-capture.patch new file mode 100644 index 0000000000..b1b157d83e --- /dev/null +++ b/.devops/nix/patches/hrx-debug-capture.patch @@ -0,0 +1,35 @@ +diff --git a/libhrx/src/binding/common/graph.c b/libhrx/src/binding/common/graph.c +index ad848e9832..e256be63bc 100644 +--- a/libhrx/src/binding/common/graph.c ++++ b/libhrx/src/binding/common/graph.c +@@ -2433,8 +2433,22 @@ static void iree_hal_streaming_capture_transaction_unlock( + *transaction = (iree_hal_streaming_capture_transaction_t){0}; + } + ++ ++// Debug patch: HRX_DEBUG_CAPTURE=1 prints a backtrace where a capture is ++// invalidated, naming the HIP entry point that caused it. ++#include ++#include ++#include ++static void hrx_debug_capture_invalidation(const char* where) { ++ if (!getenv("HRX_DEBUG_CAPTURE")) return; ++ void* frames[24]; ++ int count = backtrace(frames, 24); ++ fprintf(stderr, "hrx capture invalidated in %s:\n", where); ++ backtrace_symbols_fd(frames, count, 2); ++} + static void iree_hal_streaming_capture_transaction_invalidate( + iree_hal_streaming_capture_transaction_t* transaction) { ++ hrx_debug_capture_invalidation("capture_transaction_invalidate"); + iree_atomic_store(&transaction->graph->capture_state, + IREE_HAL_STREAMING_GRAPH_CAPTURE_STATE_INVALIDATED, + iree_memory_order_release); +@@ -2444,6 +2458,7 @@ static void iree_hal_streaming_capture_transaction_invalidate( + + bool iree_hal_streaming_capture_graph_invalidate( + iree_hal_streaming_graph_t* graph, unsigned long long capture_id) { ++ hrx_debug_capture_invalidation("capture_graph_invalidate"); + IREE_ASSERT_ARGUMENT(graph); + bool invalidated = false; + iree_slim_mutex_lock(&graph->capture_mutex); diff --git a/.devops/nix/patches/hrx-profile-open-session.patch b/.devops/nix/patches/hrx-profile-open-session.patch new file mode 100644 index 0000000000..a70e7fd7fd --- /dev/null +++ b/.devops/nix/patches/hrx-profile-open-session.patch @@ -0,0 +1,22 @@ +diff --git a/runtime/src/iree/tooling/profile/reader.c b/runtime/src/iree/tooling/profile/reader.c +index 853296546d..d08ff89a94 100644 +--- a/runtime/src/iree/tooling/profile/reader.c ++++ b/runtime/src/iree/tooling/profile/reader.c +@@ -4,6 +4,7 @@ + // See https://llvm.org/LICENSE.txt for license information. + // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + ++#include + #include "iree/tooling/profile/reader.h" + + #include +@@ -345,7 +346,8 @@ iree_status_t iree_profile_file_for_each_record( + ++record_index; + } + } +- if (iree_status_is_ok(status) && validate_session_lifecycle) { ++ if (iree_status_is_ok(status) && validate_session_lifecycle && ++ !getenv("IREE_PROFILE_ALLOW_OPEN_SESSION")) { + for (iree_host_size_t i = 0; i < session_count; ++i) { + if (sessions[i].is_active) { + status = iree_make_status( diff --git a/.devops/nix/rust-cargo.nix b/.devops/nix/rust-cargo.nix new file mode 100644 index 0000000000..1c9db058d5 --- /dev/null +++ b/.devops/nix/rust-cargo.nix @@ -0,0 +1,25 @@ +# Offline Cargo setup for the Rust components. The vendored crates follow the +# lockfile of the source being built, so a baseline built from another revision +# (tools/ci/linux-baseline.nix) gets its own pinned crates, or none before the +# Rust components existed. +{ + lib, + rustPlatform, + lockFile ? ../../Cargo.lock, +}: + +let + vendor = rustPlatform.importCargoLock { inherit lockFile; }; +in +lib.optionalString (builtins.pathExists lockFile) '' + export CARGO_HOME="$TMPDIR/cargo-home" + mkdir -p "$CARGO_HOME" + cat > "$CARGO_HOME/config.toml" <- ${{ steps.release-please.outputs.prs_created == 'true' && @@ -80,7 +91,7 @@ jobs: fi required_checks=( - "Validate PR title" + "Validate PR title and extension API" "Run CPU and repository checks" # The full functional suite on Strix Halo; only releases require it. "devlab/functional" @@ -148,6 +159,7 @@ jobs: repositories: | gufo toolboxes + website permission-actions: read permission-contents: write permission-issues: write @@ -198,3 +210,15 @@ jobs: jq -n --arg tag "$RELEASE_TAG" \ '{event_type: "gufo-release", client_payload: {tag: $tag}}' \ | gh api --method POST repos/gufo-org/toolboxes/dispatches --input - + + - name: Request website docs for new release + if: ${{ steps.publish-release.outputs.release_created == 'true' }} + env: + GH_TOKEN: ${{ steps.release-token.outputs.token }} + RELEASE_TAG: ${{ steps.publish-release.outputs.tag_name }} + shell: bash + run: | + set -euo pipefail + jq -n --arg tag "$RELEASE_TAG" \ + '{event_type: "gufo-release", client_payload: {tag: $tag}}' \ + | gh api --method POST repos/gufo-org/website/dispatches --input - diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml index 7a2e9fdc00..83ffd34704 100644 --- a/.github/workflows/windows-build.yml +++ b/.github/workflows/windows-build.yml @@ -281,8 +281,15 @@ jobs: # here; the Devlab job runs the full diagnosis on the device. & $gufo diagnose --section platform if ($LASTEXITCODE -ne 0) { throw 'gufo diagnose --section platform failed' } + ccache --zero-stats cmake --build --preset windows-release --parallel $env:NUMBER_OF_PROCESSORS --target check-pr - if ($LASTEXITCODE -ne 0) { throw 'check-pr failed' } + $checkExit = $LASTEXITCODE + ccache --show-stats + if (Test-Path build/windows-release/Testing/Temporary/LastTest.log) { + Get-Content build/windows-release/Testing/Temporary/LastTest.log | + Select-String 'discovery timing:' + } + if ($checkExit -ne 0) { throw 'check-pr failed' } ctest --test-dir build/windows-release --output-on-failure --no-tests=error --timeout 60 -R '^(qwen38_flash_next\.ngram|gpu_queues_test|bandwidth_test|allocation_benchmark_test)$' if ($LASTEXITCODE -ne 0) { throw 'diagnostics and ngram tests failed' } diff --git a/.gitignore b/.gitignore index 1d4a110a91..69cf4a7b04 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,9 @@ build/ Build/ build-*/ +# Cargo output when the Rust workspace is built outside CMake +/target/ + # CMake generated files CMakeFiles/ CMakeCache.txt diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ad166586ae..8878352c7d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.28.1" + ".": "0.34.0" } diff --git a/AGENTS.md b/AGENTS.md index 8d1fa734a0..513e958cff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,13 +5,13 @@ Production packages target Linux x86-64 AMD Strix Halo (`gfx1151`); Windows is a supported native build target for development. CMake owns compiler flags, dependencies and installation; Nix supplies the pinned toolchain. -Linux source-build prerequisites are in [README.md](README.md#build-from-source). +Linux source-build prerequisites are in [docs/install.md](docs/install.md#build-from-source). ```sh nix build # development package, all discovered extensions nix build .#release # shipped lock-mode package, no tests/tools ./result/bin/gufo diagnose -nix build .#checks.x86_64-linux.pr # bounded hosted CPU/repository checks +nix flake check # hosted CPU/repository checks nix develop # GPU development and reference tools # Same production build without Nix, with the documented dependencies installed @@ -34,6 +34,12 @@ nix shell --inputs-from . nixpkgs#clang-tools -c python3 tools/ci/check-format.p # Add --fix to apply formatting, then rerun the check. ``` +Tests selected by `nix flake check` should stay fast and cache-friendly where +possible. Reuse expensive setup and compiler caches when valid, use the smallest +deterministic fixtures that preserve the assertions, and avoid redundant builds, +fixed sleeps and repeated whole-tree work. Measure added wall time; keep expensive +stress/model qualification explicitly selectable without weakening correctness. + Run the smallest check covering the change. `gpu-test` is RelWithDebInfo with assertions enabled. Build only the affected target during iteration: @@ -44,9 +50,10 @@ nix develop -c ctest --preset gpu-full -R '^$' --output-on-failure ``` The same CMake/CTest commands work outside Nix. `cmake --build --preset pr` -runs the hosted contract suite after configuring `cpu-test`. Full CPU checks, +runs the focused contract subset after configuring `cpu-test`; `nix flake check` +runs the canonical CPU/repository gate. Full CPU checks, sanitisers, GPU/operator/model checks and H3 quality tools remain available -locally; see [docs/TESTING.md](docs/TESTING.md). Do not run full model sweeps, +locally; see [docs/internal/testing.md](docs/internal/testing.md). Do not run full model sweeps, video generation or duplicate suites for routine edits. A missing-model skip is not a quality pass. Broaden checks when shared behavior changes or failures expose risk. @@ -84,6 +91,7 @@ quality; successful optimizations become the default, without extra switches. ## Development - Keep model code, tests, tools and numerical contracts with their model. +- Follow [docs/AGENTS.md](docs/AGENTS.md) when writing or changing documentation. - Use the shared Qwen control-token constants for framing; see [src/families/qwen/AGENTS.md](src/families/qwen/AGENTS.md). Inspect their definitions when reviewing or changing behavior, and keep reference fixtures independent. @@ -97,7 +105,7 @@ quality; successful optimizations become the default, without extra switches. - Use one canonical long option and backend name per behavior; avoid aliases. - Use `gh` for GitHub operations after checking `gh auth status`. - Follow Conventional Commits with a single-line message. Title pull requests - according to [the release policy](docs/RELEASING.md); squash merging retains + according to [the release policy](docs/internal/releasing.md); squash merging retains that title on `main`. Mark breaking changes with `!` in the title, and leave version and changelog updates to the release workflow. - Prefer `jj` when available (`jj version`); otherwise use Git. @@ -118,5 +126,5 @@ quality; successful optimizations become the default, without extra switches. and add a record in the new series, retaining all historical records. Extension API and the future experimental flake `extensions` argument are excluded from Gufo's release compatibility surface; CLI/HTTP/public existing flake breaks still - require `!`. See [the release policy](docs/RELEASING.md). + require `!`. See [the release policy](docs/internal/releasing.md). - Follow the user's remote workflow and preserve unrelated work. diff --git a/BUILD-WINDOWS.md b/BUILD-WINDOWS.md index 3e4319addf..4685ce3fa2 100644 --- a/BUILD-WINDOWS.md +++ b/BUILD-WINDOWS.md @@ -35,6 +35,9 @@ release packaging builds the upstream runtime instead. workload (MSVC x64). - **Git**, **CMake ≥ 3.29**, **Ninja** (Visual Studio bundles both; `vs-env.cmd` puts them on `PATH`) and **Python 3**. +- **Rust 1.88 or newer** from [rustup](https://rustup.rs), with the + `x86_64-pc-windows-msvc` target. Rustup reads the pinned version from + `rust-toolchain.toml`; Cargo builds the Rust components. - **vcpkg**, a full clone (the manifest baseline resolves through its history), with `VCPKG_ROOT` set to it: @@ -153,7 +156,7 @@ EmbeddingGemma 2, Qwen3-ASR, Qwen3-TTS and Qwen3.8-27B. ## External source extensions -Use the [extension distribution recipe](docs/model-extensions/DISTRIBUTION.md#native-windows-and-zip-recipe) +Use the [extension distribution recipe](docs/internal/extension-distribution.md#native-windows-and-zip-recipe) for vcpkg dependency preflight, external source selection, CMake installation, license/data staging and fresh-ZIP runtime checks. Declared metadata dependencies do not install additional vcpkg ports automatically. diff --git a/CHANGELOG.md b/CHANGELOG.md index 18b599d139..c7bfbb7eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,254 @@ Notable user-facing changes are recorded here. Gufo follows [Semantic Versioning](https://semver.org/) under the compatibility policy in -[the release guide](docs/RELEASING.md). +[the release guide](docs/internal/releasing.md). + +## [0.34.0](https://github.com/gufo-org/gufo/compare/v0.33.0...v0.34.0) (2026-11-11) + + +### ⚠ BREAKING CHANGES + +* **audio:** decode EmbeddingGemma 2 audio in Rust and drop libsndfile and soxr ([#1118](https://github.com/gufo-org/gufo/issues/1118)) + +### Features + +* **cli:** deprecate --draft-tokens, --min-draft-tokens and --draft-policy ([#1124](https://github.com/gufo-org/gufo/issues/1124)) ([f4bc1ad](https://github.com/gufo-org/gufo/commit/f4bc1adbba91a09788d71523c3212b4fdcb01c16)) +* **extensions:** record the source revision of external extensions ([#1162](https://github.com/gufo-org/gufo/issues/1162)) ([5253acc](https://github.com/gufo-org/gufo/commit/5253acc43ddcd4c0bfe17843d6cb7841e7e10c6d)) +* **h3:** add FL2VA first- and last-frame keyframe conditioning ([#998](https://github.com/gufo-org/gufo/issues/998)) ([92b3f1b](https://github.com/gufo-org/gufo/commit/92b3f1b9ddbaf3f247f6ceb8711198073b64d244)) + + +### Bug Fixes + +* **cache:** remove disk-only metadata admission limits ([#934](https://github.com/gufo-org/gufo/issues/934)) ([12e8b99](https://github.com/gufo-org/gufo/commit/12e8b99f1e01f336a00b1aef5db55ba4a1da18de)) +* **cache:** size disk publication validation by the candidate, not the whole tier ([#1121](https://github.com/gufo-org/gufo/issues/1121)) ([b97f3b5](https://github.com/gufo-org/gufo/commit/b97f3b5cf5f507cbfa86a061b9dd380104e84547)) +* **ext:** install extension sources that contain file symlinks ([#1151](https://github.com/gufo-org/gufo/issues/1151)) ([7c9328d](https://github.com/gufo-org/gufo/commit/7c9328dca8aa283154bafd547abd5c4be787f54e)) +* **qwen38-flash-next:** recover stale MTP backoff after batch observations ([#912](https://github.com/gufo-org/gufo/issues/912)) ([49b5df1](https://github.com/gufo-org/gufo/commit/49b5df18923ad0445b9ff69b3cd9bda213715ff3)) +* **serve:** continue the live frontier after a re-tokenized answer ([#1154](https://github.com/gufo-org/gufo/issues/1154)) ([#1158](https://github.com/gufo-org/gufo/issues/1158)) ([850b527](https://github.com/gufo-org/gufo/commit/850b5271258f050847b928d68ab4bbb7c8d83c96)) +* **serve:** deprecate the unused shared-byte cache metric ([#1129](https://github.com/gufo-org/gufo/issues/1129)) ([b62b167](https://github.com/gufo-org/gufo/commit/b62b1674ca7f8134a5c1f6487d3dd7690565296c)) +* **serve:** do not charge prompt state for preallocated session runners ([#1164](https://github.com/gufo-org/gufo/issues/1164)) ([be3a81a](https://github.com/gufo-org/gufo/commit/be3a81af6283b28641652d231c0e551db8343a97)) +* **serve:** refuse prompts that exceed the host prompt-state budget ([#1083](https://github.com/gufo-org/gufo/issues/1083)) ([017e924](https://github.com/gufo-org/gufo/commit/017e92490899d4b5b28ded6eaeb2a25f4f597fee)) +* **serve:** return tool-call numbers as the model wrote them ([#1146](https://github.com/gufo-org/gufo/issues/1146)) ([4e95aec](https://github.com/gufo-org/gufo/commit/4e95aecbaec2c61bd2c06900d35c6a51ee4b9f24)) +* **tools:** cap JSON numbers at llama.cpp's 16 digits ([#1168](https://github.com/gufo-org/gufo/issues/1168)) ([5319381](https://github.com/gufo-org/gufo/commit/53193819c5fa7e8d01771a3a9e65e0a5f2520a4f)) +* **tools:** match llama.cpp nested object defaults ([#1128](https://github.com/gufo-org/gufo/issues/1128)) ([bd6b0fd](https://github.com/gufo-org/gufo/commit/bd6b0fdd083568d5eb485a2f3ba37a118a0a15c4)) + + +### Performance + +* **core:** reduce CPU overhead in sampling and n-gram lookups ([#1127](https://github.com/gufo-org/gufo/issues/1127)) ([ca6955c](https://github.com/gufo-org/gufo/commit/ca6955c4c87bd7b2fe67ad3d878424812c0ef807)) +* **qwen38:** reuse Q8 activations from batched HC mixing ([#958](https://github.com/gufo-org/gufo/issues/958)) ([5f12c75](https://github.com/gufo-org/gufo/commit/5f12c75390437253366229bfe269a3999b366d0b)) +* **qwen:** fuse the batched target FFN HC pair ([#969](https://github.com/gufo-org/gufo/issues/969)) ([f01a457](https://github.com/gufo-org/gufo/commit/f01a457022a3abd180f5eb1bc4315f918b1bdc24)) +* **qwen:** Windows table for the Qwen3.8-27B verification GEMM shapes ([#1122](https://github.com/gufo-org/gufo/issues/1122)) ([b1899cf](https://github.com/gufo-org/gufo/commit/b1899cfac066358fcbce2e09030ebd7bc6e9a96d)) + + +### Documentation + +* log the first HRX runtime experiments ([#1145](https://github.com/gufo-org/gufo/issues/1145)) ([2e8098f](https://github.com/gufo-org/gufo/commit/2e8098f0d65049e6b0f9a7255241bf363f9b266b)) +* **qwen27b:** pin the Unsloth Dynamic 3.1 Q4_K_XL revision ([#1167](https://github.com/gufo-org/gufo/issues/1167)) ([dbfe834](https://github.com/gufo-org/gufo/commit/dbfe834daf92ddf002c9a6872f63bc8a371dce03)) + + +### Code Refactoring + +* **audio:** decode EmbeddingGemma 2 audio in Rust and drop libsndfile and soxr ([#1118](https://github.com/gufo-org/gufo/issues/1118)) ([77b6ccf](https://github.com/gufo-org/gufo/commit/77b6ccf6ebf9a5841b44bc4ba1ee914906a85e9d)) +* **serve:** parse WebSocket frames and base64 in Rust ([#1149](https://github.com/gufo-org/gufo/issues/1149)) ([b50ef15](https://github.com/gufo-org/gufo/commit/b50ef15966d5ac73fbe63914f583daf80da73f09)) + +## [0.33.0](https://github.com/gufo-org/gufo/compare/v0.32.0...v0.33.0) (2026-11-09) + + +### Features + +* **ext:** add image provider startup options and request capability validation ([#1050](https://github.com/gufo-org/gufo/issues/1050)) ([00d7ccb](https://github.com/gufo-org/gufo/commit/00d7ccb0939f415df151418cc03f7667e9ee5c7e)) +* **ext:** let component caches set their transfer stream count ([#1108](https://github.com/gufo-org/gufo/issues/1108)) ([2fd9e46](https://github.com/gufo-org/gufo/commit/2fd9e460973399befa7da01eeba9ce3db7ededbf)) + + +### Bug Fixes + +* **cache:** keep snapshot copies inside one host registration ([#1117](https://github.com/gufo-org/gufo/issues/1117)) ([3016d65](https://github.com/gufo-org/gufo/commit/3016d6520585027916f844292aa1d019f9a04cc2)) +* **cache:** let optional copies displace conversations unused for one record turnover ([#1104](https://github.com/gufo-org/gufo/issues/1104)) ([fe2694b](https://github.com/gufo-org/gufo/commit/fe2694bce83008910fe135d6f800846b5d5673cb)) +* **ds4:** keep DSpark greedy output equal to plain decoding ([#1105](https://github.com/gufo-org/gufo/issues/1105)) ([8c332a0](https://github.com/gufo-org/gufo/commit/8c332a023d522f9c8ad9ad75717d66259deabdd7)) +* **functional:** let the text suites run models without a Qwen or DeepSeek preset ([#1103](https://github.com/gufo-org/gufo/issues/1103)) ([718a388](https://github.com/gufo-org/gufo/commit/718a388d031364e5707f11fc21890b6b4f54c24a)) +* **qwen38-flash-next:** measure the decode shared-expert overlap before using it ([#1107](https://github.com/gufo-org/gufo/issues/1107)) ([#1112](https://github.com/gufo-org/gufo/issues/1112)) ([365cc5a](https://github.com/gufo-org/gufo/commit/365cc5a5f8f16f8c83d585d7d794a5b2983be900)) +* **serve:** read the DXGI budget for state capacity on Windows iGPUs ([#910](https://github.com/gufo-org/gufo/issues/910)) ([3a89a05](https://github.com/gufo-org/gufo/commit/3a89a056ba660aee54413443aa8e78b80b5992c6)) + + +### Performance + +* **ds4:** faster DeepSeek V4 Flash decode from two HC kernel changes ([#1106](https://github.com/gufo-org/gufo/issues/1106)) ([5f9612c](https://github.com/gufo-org/gufo/commit/5f9612c3b19ab6676b842095bc88bb9b32da5cf0)) + + +### Documentation + +* rewrite the README as a short front page ([#1115](https://github.com/gufo-org/gufo/issues/1115)) ([2dac5ee](https://github.com/gufo-org/gufo/commit/2dac5eeb470f5939243375674efab2ae70ec4b85)) + + +### Code Refactoring + +* **audio:** decode WAV with one Rust decoder for serve, Qwen3-ASR and Qwen3-TTS ([#1110](https://github.com/gufo-org/gufo/issues/1110)) ([768a482](https://github.com/gufo-org/gufo/commit/768a482f780bc17c08a740855d35de2de5846e09)) + +## [0.32.0](https://github.com/gufo-org/gufo/compare/v0.31.0...v0.32.0) (2026-11-08) + + +### Features + +* **ds4:** split prompt passes by layers so other sessions keep decoding ([#1080](https://github.com/gufo-org/gufo/issues/1080)) ([cf68c63](https://github.com/gufo-org/gufo/commit/cf68c63f1e9e370dd6f799dc468ff5bd2b4c2516)) +* **ext:** add optional text hidden-state encoding to text runners ([#1073](https://github.com/gufo-org/gufo/issues/1073)) ([aac3f84](https://github.com/gufo-org/gufo/commit/aac3f843f9348dcf474e8bc4c126dbcb3a0e9d75)) +* **ext:** deliver declared provider options to text runners and commands ([#1046](https://github.com/gufo-org/gufo/issues/1046)) ([832ecdb](https://github.com/gufo-org/gufo/commit/832ecdbbd3d6f4886f25ae19cc2a8b157f5dece9)) +* **ext:** experiment with extensions built as loadable modules ([#1077](https://github.com/gufo-org/gufo/issues/1077)) ([0fb50ce](https://github.com/gufo-org/gufo/commit/0fb50ce436044a9687c78635e7afbc2bb65fc6f4)) +* **ext:** let text providers declare their speculation defaults ([#1047](https://github.com/gufo-org/gufo/issues/1047)) ([4938016](https://github.com/gufo-org/gufo/commit/49380168782f37d3967c3687ea07d7c78d86b3b9)) +* **ext:** let text runners see the whole prompt end during prefill ([#1069](https://github.com/gufo-org/gufo/issues/1069)) ([fb619ba](https://github.com/gufo-org/gufo/commit/fb619ba141ae4fcf70c43e27de43662622c94ddf)) +* **ext:** let text runners split prompt passes by layers so other sessions keep decoding ([#1039](https://github.com/gufo-org/gufo/issues/1039)) ([1e74ffa](https://github.com/gufo-org/gufo/commit/1e74ffa49188eee250e5ebd1a11b08975c0f1318)) +* **ext:** open GGUF tensors core cannot size for providers that accept them ([#966](https://github.com/gufo-org/gufo/issues/966)) ([e120193](https://github.com/gufo-org/gufo/commit/e1201933cac8e243a92777515c340fcdffb3490a)) +* **qwen27b:** split prompt passes by layers so other sessions keep decoding ([#1079](https://github.com/gufo-org/gufo/issues/1079)) ([90b9745](https://github.com/gufo-org/gufo/commit/90b9745fd6692b53eb3359458fc933cdb2037615)) +* **qwen38-flash-next:** split prompt passes by layers so other sessions keep decoding ([#1042](https://github.com/gufo-org/gufo/issues/1042)) ([3888e22](https://github.com/gufo-org/gufo/commit/3888e22eff4f63851c46c51107a82ca892f494a9)) +* **serve:** add llama-server's /tokenize ([#1082](https://github.com/gufo-org/gufo/issues/1082)) ([6d79381](https://github.com/gufo-org/gufo/commit/6d79381486b6213c726cd9f57ecedde75645b649)) +* **server:** deprecate --prefill-chunk now that prompts beside decoders are split by layers ([#1095](https://github.com/gufo-org/gufo/issues/1095)) ([12f8d8a](https://github.com/gufo-org/gufo/commit/12f8d8ab9a944b2df3efe388b44246ec37923c53)) + + +### Bug Fixes + +* **bench:** let model-bench measure models without a speculative mode ([#1099](https://github.com/gufo-org/gufo/issues/1099)) ([17d6fa2](https://github.com/gufo-org/gufo/commit/17d6fa256158096b3452d31fd157b2e78134ff32)) +* **ds4:** build the Q8 to F16 weight cache in one pass so output never depends on free memory ([#1045](https://github.com/gufo-org/gufo/issues/1045)) ([211dba4](https://github.com/gufo-org/gufo/commit/211dba49fa736466d55feb66870aeeff05bef38a)) +* **ds4:** compare GGUF float metadata with a relative tolerance ([#1065](https://github.com/gufo-org/gufo/issues/1065)) ([800eb68](https://github.com/gufo-org/gufo/commit/800eb68d1245098553619df4ccc1ace3d71495d8)) +* **json:** accept annotation keywords such as $schema in strict schemas ([#1059](https://github.com/gufo-org/gufo/issues/1059)) ([de29d6a](https://github.com/gufo-org/gufo/commit/de29d6a7b2f95ecb2fb756d8f8ad632e5569061a)) +* **json:** accept general type unions in strict tool schemas ([#1052](https://github.com/gufo-org/gufo/issues/1052)) ([0f251d4](https://github.com/gufo-org/gufo/commit/0f251d4a850328b3e4e76eda4170e5cab730c014)) +* **qwen38_flash_next:** decline checkpoints with unsupported expert formats in the probe ([#1041](https://github.com/gufo-org/gufo/issues/1041)) ([b7cf081](https://github.com/gufo-org/gufo/commit/b7cf081da29d8757de139399989ee6849c24b173)) +* **sampling:** end a reasoning budget when the constraint grammar leaves reasoning ([#1064](https://github.com/gufo-org/gufo/issues/1064)) ([f07fd2f](https://github.com/gufo-org/gufo/commit/f07fd2fefcc72f538beed6bcd7c8f4d88b788f3e)) +* **serve:** keep a tool opener's leading separator out of required structured replies ([#1043](https://github.com/gufo-org/gufo/issues/1043)) ([1175eeb](https://github.com/gufo-org/gufo/commit/1175eebeb8eb069809fd5fe2582d7bcb448adaa2)) +* **serve:** refuse a RAM cache the host cannot hold with the remedies instead of bad_alloc ([#1063](https://github.com/gufo-org/gufo/issues/1063)) ([0d12f7b](https://github.com/gufo-org/gufo/commit/0d12f7b7f2e1518375d5b649026997f030b29cd6)) + + +### Performance + +* **ds4:** faster DeepSeek V4 Flash decode at long context ([#1062](https://github.com/gufo-org/gufo/issues/1062)) ([0e2cab6](https://github.com/gufo-org/gufo/commit/0e2cab6cc2e86a03082df4381662d66b4317384f)) +* **image:** decode PNG with new Rust png crate ([#913](https://github.com/gufo-org/gufo/issues/913)) ([c229292](https://github.com/gufo-org/gufo/commit/c229292182781568ec10c769ef6315f064a0f21f)) +* **qwen38-flash-next:** overlap the shared expert with routed experts on decode ([#1048](https://github.com/gufo-org/gufo/issues/1048)) ([80786f7](https://github.com/gufo-org/gufo/commit/80786f73d9287abc9a00a68207b387383242ef89)) + + +### Documentation + +* keep installed extensions in a container volume ([#1094](https://github.com/gufo-org/gufo/issues/1094)) ([53cc9a5](https://github.com/gufo-org/gufo/commit/53cc9a51bbd1a41bceb63ec3b4c5303c99f31877)) +* rework documentation into public and internal pages ([#1090](https://github.com/gufo-org/gufo/issues/1090)) ([cf86cb2](https://github.com/gufo-org/gufo/commit/cf86cb2717ef1275ddbf1506ff3ab7a6df88785c)) +* say where each documentation version is published ([#1093](https://github.com/gufo-org/gufo/issues/1093)) ([8d72025](https://github.com/gufo-org/gufo/commit/8d7202502ba816d14278673f72c0095c194a9987)) + + +### Code Refactoring + +* **sched:** move the text scheduler's work-unit policy into src/sched ([#1037](https://github.com/gufo-org/gufo/issues/1037)) ([6cc8a42](https://github.com/gufo-org/gufo/commit/6cc8a42ca84438a0566ee498a315f35c6190dc8e)) + +## [0.31.0](https://github.com/gufo-org/gufo/compare/v0.30.0...v0.31.0) (2026-11-05) + + +### Features + +* **cache:** add window-row components for sliding-window attention ([#1010](https://github.com/gufo-org/gufo/issues/1010)) ([555f859](https://github.com/gufo-org/gufo/commit/555f859fc3f6d4dd0c74cb42f4a3f7fbca8bef3a)) +* **ext:** add public link targets for extension executables ([#1032](https://github.com/gufo-org/gufo/issues/1032)) ([55c21af](https://github.com/gufo-org/gufo/commit/55c21af0753a9baff538373078f753b5878ae15f)) +* **ext:** keep indivisible prompt spans whole across prefill stops and checkpoints ([#1011](https://github.com/gufo-org/gufo/issues/1011)) ([d02a1d2](https://github.com/gufo-org/gufo/commit/d02a1d2d5fe36f6e5683b762cda05618283d13f5)) +* **ext:** let text providers declare their reasoning delimiters ([#1008](https://github.com/gufo-org/gufo/issues/1008)) ([2728aa7](https://github.com/gufo-org/gufo/commit/2728aa7e221f01e85792b4f9745834c76651a6f4)) +* **ext:** let text providers register native tool dialects ([#1013](https://github.com/gufo-org/gufo/issues/1013)) ([2c97b72](https://github.com/gufo-org/gufo/commit/2c97b72d8671ddd0c74ae7d517b8cef4ebb78871)) +* **ext:** let text providers supply sampling defaults and restore them in prompt and chat ([#1009](https://github.com/gufo-org/gufo/issues/1009)) ([3115315](https://github.com/gufo-org/gufo/commit/311531543e0470cc666097eabf1940be61378218)) + + +### Bug Fixes + +* **gguf:** open tensorless split shards that end without data padding ([#1021](https://github.com/gufo-org/gufo/issues/1021)) ([118b7c6](https://github.com/gufo-org/gufo/commit/118b7c63f825bb9dde2e6de2285ed2c9be005019)) + + +### Code Refactoring + +* **ext:** make the component cache the only continuation contract ([#1026](https://github.com/gufo-org/gufo/issues/1026)) ([65fe68a](https://github.com/gufo-org/gufo/commit/65fe68a9f39650a98a65ba80d6adcc80129992de)) + +## [0.30.0](https://github.com/gufo-org/gufo/compare/v0.29.0...v0.30.0) (2026-11-04) + + +### Features + +* **cache:** migrate DeepSeek V4 Flash to the component cache ([#1003](https://github.com/gufo-org/gufo/issues/1003)) ([b29229e](https://github.com/gufo-org/gufo/commit/b29229e349c8a36ac284c8ff0134b9e0c1cf808f)) +* **cache:** remove the legacy continuation cache ([#1014](https://github.com/gufo-org/gufo/issues/1014)) ([4fc4a22](https://github.com/gufo-org/gufo/commit/4fc4a2236b5421b8feb13269c2acd55b30b5a804)) +* **ext:** add a public link target for the component cache ([#1006](https://github.com/gufo-org/gufo/issues/1006)) ([346db1d](https://github.com/gufo-org/gufo/commit/346db1d075fcb7fd47964b155ab9dda6bd7354a9)) + + +### Bug Fixes + +* **json:** keep tool argument schemas beside arrays without items ([#1012](https://github.com/gufo-org/gufo/issues/1012)) ([da04ba5](https://github.com/gufo-org/gufo/commit/da04ba521b801398facede6d323a6b2b77c3e9bc)) +* **qwen38-flash-next:** end capacity-limited prefill steps on the selection block ([#1016](https://github.com/gufo-org/gufo/issues/1016)) ([186a507](https://github.com/gufo-org/gufo/commit/186a507da77bcbb3e8f0cfbd49f688f88535e9e2)) + + +### Performance + +* **qwen38-flash-next:** capture prompt checkpoints inside prefill passes without splitting them ([#963](https://github.com/gufo-org/gufo/issues/963)) ([6667372](https://github.com/gufo-org/gufo/commit/6667372738422619691663e9afefd6e0d4c16c3d)) + +## [0.29.0](https://github.com/gufo-org/gufo/compare/v0.28.1...v0.29.0) (2026-11-04) + + +### ⚠ BREAKING CHANGES + +* make nix flake check the canonical hosted gate ([#981](https://github.com/gufo-org/gufo/issues/981)) + +### Features + +* **core:** open IQ2_XS, IQ2_S, IQ3_XXS, IQ1_S and IQ1_M tensors and dequantize every GGML block format ([#930](https://github.com/gufo-org/gufo/issues/930)) ([b20b5bd](https://github.com/gufo-org/gufo/commit/b20b5bd49b970024493241f15d1e5d73ac605e5d)) +* **embedding:** select the EmbeddingGemma 2 video frame budget per request ([#888](https://github.com/gufo-org/gufo/issues/888)) ([eddcfea](https://github.com/gufo-org/gufo/commit/eddcfea65bd836f75eaa79c4203171ab8478c797)) +* **extensions:** add realtime speech, speak and decision contracts ([#942](https://github.com/gufo-org/gufo/issues/942)) ([13f6456](https://github.com/gufo-org/gufo/commit/13f6456628bfaa17aa5d5cef1ed0922a738a1f39)) +* **extensions:** add source extension infrastructure and separate model execution ([#911](https://github.com/gufo-org/gufo/issues/911)) ([6b6a6b0](https://github.com/gufo-org/gufo/commit/6b6a6b04fab46f610d1725368cdd2db3e5b2c3ce)) +* **extensions:** derive API revisions from permanent change records ([#940](https://github.com/gufo-org/gufo/issues/940)) ([f25f474](https://github.com/gufo-org/gufo/commit/f25f4744a6348e6c9670e2684a0a1f898c1b69ca)) +* **extensions:** generate infrastructure from model metadata ([#927](https://github.com/gufo-org/gufo/issues/927)) ([2ea2ccd](https://github.com/gufo-org/gufo/commit/2ea2ccd39efbea790957a8cc1215cd66ce27fee9)) +* **extensions:** generate Nix serving options from metadata ([#947](https://github.com/gufo-org/gufo/issues/947)) ([6bbb6bb](https://github.com/gufo-org/gufo/commit/6bbb6bb6bddcb26f18f9f845331c2f8755f3fd7c)) +* **extensions:** migrate embeddinggemma pilot to isolated extension ([#924](https://github.com/gufo-org/gufo/issues/924)) ([8fec1ce](https://github.com/gufo-org/gufo/commit/8fec1ce96bffc728e03a9e271e787cef4a48bbda)) +* **extensions:** migrate speech, audio, image, and video models to extensions ([#931](https://github.com/gufo-org/gufo/issues/931)) ([8f5aece](https://github.com/gufo-org/gufo/commit/8f5aece0c27ca35e3a0831da9ff960e8be78b30e)) +* **extensions:** migrate text generation models (Cards 19-22) ([#935](https://github.com/gufo-org/gufo/issues/935)) ([385d9a7](https://github.com/gufo-org/gufo/commit/385d9a7f83c0328fa2655bec1aee681606d53445)) +* **extensions:** publish public api surface, migrate model includes, and add test support ([#922](https://github.com/gufo-org/gufo/issues/922)) ([0071637](https://github.com/gufo-org/gufo/commit/00716376fd949c3c867b08497d5848ad9ccd57f5)) +* **extensions:** support external extension source trees (Card 23) ([#936](https://github.com/gufo-org/gufo/issues/936)) ([9d1e7c8](https://github.com/gufo-org/gufo/commit/9d1e7c8ef74f831aeb833befb522d3a31fb9cc33)) +* **image:** support Qwen Image 2.1 Turbo generation and editing ([#784](https://github.com/gufo-org/gufo/issues/784)) ([05f0a9a](https://github.com/gufo-org/gufo/commit/05f0a9a0f7cf9b72f7cfd92eca018265ad323aec)) +* **qwen38-flash-next:** read Q8_0 PLE n-gram tables ([#884](https://github.com/gufo-org/gufo/issues/884)) ([2a9dd9c](https://github.com/gufo-org/gufo/commit/2a9dd9c5d4e38289378ac98cc243899670b21418)) +* **qwen38-flash-next:** scale YaRN with the context a session holds ([#905](https://github.com/gufo-org/gufo/issues/905)) ([e28fef4](https://github.com/gufo-org/gufo/commit/e28fef40aaa4baa7d8a169e93214e145f888c0cf)) +* **serve:** drop API-key auth, accept model aliases in every modality, answer GET / with health ([#957](https://github.com/gufo-org/gufo/issues/957)) ([#967](https://github.com/gufo-org/gufo/issues/967)) ([9bd24d2](https://github.com/gufo-org/gufo/commit/9bd24d26b066ce08a463c2def8da9acb95c75338)) +* **serve:** report completion_tokens_details.reasoning_tokens on chat completions ([#915](https://github.com/gufo-org/gufo/issues/915)) ([6ab4569](https://github.com/gufo-org/gufo/commit/6ab4569ba127c4324f85aa8298f856c7eadb085a)) +* **tts:** declare voice and reference conditioning capabilities independently of Qwen variants ([#984](https://github.com/gufo-org/gufo/issues/984)) ([159f2b8](https://github.com/gufo-org/gufo/commit/159f2b846471355d9af3010edffa7943a0e3efb9)) + + +### Bug Fixes + +* **cache:** align Flash-Next prefill and keep disk readahead progressing ([#877](https://github.com/gufo-org/gufo/issues/877)) ([18c89e3](https://github.com/gufo-org/gufo/commit/18c89e3ba1308ae82b4d77c1b0f586c7002fc4dd)) +* **cache:** refuse a RAM-cache segment only when registering it cuts the heap below the reserve ([#903](https://github.com/gufo-org/gufo/issues/903)) ([8ab834a](https://github.com/gufo-org/gufo/commit/8ab834a5902bf19341750daecf27516a57840dd1)) +* **ds4:** default the served context to the GGUF native length ([#946](https://github.com/gufo-org/gufo/issues/946)) ([b6336a3](https://github.com/gufo-org/gufo/commit/b6336a34575e80ab0a8cc00b393d0988586ba92d)) +* **ds4:** keep caller text out of DeepSeek control tokens ([#691](https://github.com/gufo-org/gufo/issues/691)) ([6246d77](https://github.com/gufo-org/gufo/commit/6246d77a2214c08e813def5fe078779da34fee34)) +* **qwen38_flash_next:** restore serving concurrency and GPU tests ([#953](https://github.com/gufo-org/gufo/issues/953)) ([6a02743](https://github.com/gufo-org/gufo/commit/6a027439d7a00dd8fcd3717ef2bdf3795dc21818)) +* **qwen38-flash-next:** count the draft block's hidden row beside wide copy rows in session bytes ([#993](https://github.com/gufo-org/gufo/issues/993)) ([805c942](https://github.com/gufo-org/gufo/commit/805c9421550ab1379b6d83d277bd8957c4e2b4b2)) +* **qwen38-flash-next:** keep cached requests alive without snapshot device headroom and return to 4,096-row prefill passes ([#954](https://github.com/gufo-org/gufo/issues/954)) ([abb6aca](https://github.com/gufo-org/gufo/commit/abb6acabce3e7fed3bdf819e73c62c4e4518d16a)) +* **qwen38-flash-next:** sweep pre-budget rows densely in budget-crossing chains ([#876](https://github.com/gufo-org/gufo/issues/876)) ([2e6aa96](https://github.com/gufo-org/gufo/commit/2e6aa96ce20a0e244561cb86915dd79260042eac)) +* **qwen38-flash-next:** widen BF16 HC inject rows to F32 and keep the mixer's F32 rows beside a separate inject projection ([#950](https://github.com/gufo-org/gufo/issues/950)) ([67dd635](https://github.com/gufo-org/gufo/commit/67dd6354c73fb1325809c7a8f47dd3d30105638c)) +* **serve:** ignore unknown request fields on embeddings, audio, image and video routes ([#968](https://github.com/gufo-org/gufo/issues/968)) ([9b3b1f4](https://github.com/gufo-org/gufo/commit/9b3b1f4844c5845d007d762b0a33d8c346686a4d)) +* **serve:** mark realtime responses active before announcing them ([#999](https://github.com/gufo-org/gufo/issues/999)) ([6905be2](https://github.com/gufo-org/gufo/commit/6905be287ea9945e2f59ecb63a6d59b912ad5b58)) +* **serve:** report sizes and fitting sessions when request states exceed capacity ([#964](https://github.com/gufo-org/gufo/issues/964)) ([b911c15](https://github.com/gufo-org/gufo/commit/b911c150e9cd6e4d6daf842826d0df5242c5387f)) +* **tts:** use provider output sample rates in streaming metadata and metrics ([#983](https://github.com/gufo-org/gufo/issues/983)) ([6b58387](https://github.com/gufo-org/gufo/commit/6b583876e9b4d7c32f212b63d4e672b9d883a12f)) +* **windows:** keep same-named HIP sources from swapping device code ([#914](https://github.com/gufo-org/gufo/issues/914)) ([eb31391](https://github.com/gufo-org/gufo/commit/eb313910a53e9fa9029a488d68f17591cf935d39)) + + +### Performance + +* **cache:** back off idle-spill polling while another slot keeps the device busy ([#881](https://github.com/gufo-org/gufo/issues/881)) ([31c3b3a](https://github.com/gufo-org/gufo/commit/31c3b3a0f2def671a5d009eabed546678687524b)) +* **ds4:** faster DeepSeek V4 Flash decode, top-p sampling, and unaligned resumed prefill ([#897](https://github.com/gufo-org/gufo/issues/897)) ([bdf800d](https://github.com/gufo-org/gufo/commit/bdf800de477e980904c26aad483123af7dfa6583)) +* **qwen27b:** draft DFlash2 through the shared prefix-plus-table output head ([#988](https://github.com/gufo-org/gufo/issues/988)) ([49eeada](https://github.com/gufo-org/gufo/commit/49eeada660a08fbdb11b33eada60a79f4695bfe2)) +* **qwen27b:** verify long prompt-lookup copies in one wide pass ([#992](https://github.com/gufo-org/gufo/issues/992)) ([d2b01f2](https://github.com/gufo-org/gufo/commit/d2b01f24a9a70104170bfe69bd4752fb7ce8e4e1)) +* **qwen38-flash-next:** fuse the prefill DeltaNet norms, gates, recurrence and epilogue ([#895](https://github.com/gufo-org/gufo/issues/895)) ([a6c53a6](https://github.com/gufo-org/gufo/commit/a6c53a62736cb634c881cedc8b708ca739c0cbb9)) +* **qwen38-flash-next:** prefill lone prompts in 16,384-row passes with grouped GEMM rasters ([#933](https://github.com/gufo-org/gufo/issues/933)) ([0bc453f](https://github.com/gufo-org/gufo/commit/0bc453f22162bde72bbe6c32824caa797396dd15)) +* **qwen38-flash-next:** register-resident routed prefill experts over one 128-token map ([#890](https://github.com/gufo-org/gufo/issues/890)) ([9fbe751](https://github.com/gufo-org/gufo/commit/9fbe75107e9e1b6a662d4f3eae3d7510b247c3c5)) +* **qwen38-flash-next:** run a decode batch's HC combine and Q8_0 mixer in one launch ([#894](https://github.com/gufo-org/gufo/issues/894)) ([eb1d52e](https://github.com/gufo-org/gufo/commit/eb1d52e68a9e57a1dc03d2176ab2e10e5fbbcbac)) +* **qwen38-flash-next:** verify long prompt-lookup copies in one wide pass ([#961](https://github.com/gufo-org/gufo/issues/961)) ([96c9a0f](https://github.com/gufo-org/gufo/commit/96c9a0f535945a0a2c6330a1aa4ab4ad48aae052)) +* **qwen:** specialize the K-quant warp dot and run K-quant GEMV one row per warp ([#995](https://github.com/gufo-org/gufo/issues/995)) ([1c75887](https://github.com/gufo-org/gufo/commit/1c75887ba3e4c009c07518b7ffdc9b324ccf78e8)) +* **qwen:** step IQ4 small-batch K-quant tokens so ROCm 10.1 does not spill ([#990](https://github.com/gufo-org/gufo/issues/990)) ([56ed8f4](https://github.com/gufo-org/gufo/commit/56ed8f4d2308da6ff30b4502a850b4e5d2113d94)) + + +### Documentation + +* **extensions:** mark cards 27-29 won't do ([#955](https://github.com/gufo-org/gufo/issues/955)) ([c32136f](https://github.com/gufo-org/gufo/commit/c32136f87c29e83dd55ab66c5e703e895ab8f03e)) +* **extensions:** record Card 24 external LFM3 text provider conformance ([#938](https://github.com/gufo-org/gufo/issues/938)) ([7b9122f](https://github.com/gufo-org/gufo/commit/7b9122f279e953fb4dbf4d8006c7e856007e752f)) +* **serve:** document usage.gufo cache snapshot, disk and shared-prefix fields ([#919](https://github.com/gufo-org/gufo/issues/919)) ([c7c4177](https://github.com/gufo-org/gufo/commit/c7c4177ef0fc931cf928283e70cdbcf898171483)) +* **server:** document llama-swap readiness configuration ([#941](https://github.com/gufo-org/gufo/issues/941)) ([9be1f72](https://github.com/gufo-org/gufo/commit/9be1f725d8b9564ea3172ca4c08e6af10c5982e9)) + + +### Continuous Integration + +* make nix flake check the canonical hosted gate ([#981](https://github.com/gufo-org/gufo/issues/981)) ([108ade2](https://github.com/gufo-org/gufo/commit/108ade2718a7a2e2130cb2df02a568c228ec03f1)) ## [0.28.1](https://github.com/gufo-org/gufo/compare/v0.28.0...v0.28.1) (2026-10-31) diff --git a/CMakeLists.txt b/CMakeLists.txt index a363ba2778..e8a021e02f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,23 +31,7 @@ include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/include) # Reuse the compiler cache whenever it is installed, as the CPU check # derivations do. HIP kernels stay uncached: hipcc drive files and bitcode # paths need their own hit-rate measurement before they join the cache. -find_program(GUFO_CCACHE_PROGRAM NAMES ccache) -if (GUFO_CCACHE_PROGRAM) - set(CMAKE_C_COMPILER_LAUNCHER "${GUFO_CCACHE_PROGRAM}") - set(CMAKE_CXX_COMPILER_LAUNCHER "${GUFO_CCACHE_PROGRAM}") - # Newer CMake gives clang-cl gcc-style depfiles (-clang:-MD), which ccache - # rejects as unsupported; /showIncludes is cacheable. - if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") - set(GUFO_CCACHE_CLANG_CL ON) - foreach(lang C CXX) - set(CMAKE_DEPFILE_FLAGS_${lang} "/showIncludes") - set(CMAKE_${lang}_DEPFILE_FORMAT msvc) - endforeach() - endif() - message(STATUS "gufo: compiling C and CXX through ${GUFO_CCACHE_PROGRAM}") -else() - message(STATUS "gufo: ccache not found, compiling without a launcher") -endif() +include(cmake/CompilerCache.cmake) # Windows host checks build only the OS leaves, the CPU cache library and # their portable tests. The rest of the tree targets Linux only. @@ -55,7 +39,11 @@ option(GUFO_PLATFORM_ONLY "Build only the platform leaves, the CPU cache and their portable tests" OFF) if (GUFO_PLATFORM_ONLY) find_package(Threads REQUIRED) - add_compile_options(-Wall -Wextra -Wpedantic -UNDEBUG) + if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + add_compile_options(/W4 /UNDEBUG) + else() + add_compile_options(-Wall -Wextra -Wpedantic -UNDEBUG) + endif() add_subdirectory(src/core/platform) add_subdirectory(src/cache) include(CTest) @@ -87,9 +75,8 @@ if (WIN32) endif() find_package(PkgConfig REQUIRED) pkg_check_modules(WEBP REQUIRED IMPORTED_TARGET libwebp) -pkg_check_modules(SNDFILE REQUIRED IMPORTED_TARGET sndfile) -pkg_check_modules(SOXR REQUIRED IMPORTED_TARGET soxr) -pkg_check_modules(AV REQUIRED IMPORTED_TARGET libavformat libavcodec libavutil libswscale) +# Extension-only libraries come from each selected extension's manifest +# `packages` (gufo_build_discovered_extensions). find_package(OpenSSL REQUIRED COMPONENTS Crypto) set(GUFO_FFMPEG_EXECUTABLE "ffmpeg" CACHE STRING "FFmpeg executable used for generated media") @@ -183,7 +170,11 @@ option(GUFO_ENABLE_WARNINGS "Enable compiler warnings" ON) option(GUFO_ENABLE_SANITIZERS "Enable AddressSanitizer and UndefinedBehaviorSanitizer" OFF) if (GUFO_ENABLE_WARNINGS) - if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + # clang-cl interprets -Wall as /Wall, enabling compatibility warnings and + # diagnostics in SDK headers. Use the frontend's normal warning level. + if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + add_compile_options(/W4) + elseif (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") add_compile_options(-Wall -Wextra -Wpedantic) endif() endif() @@ -225,6 +216,7 @@ if (WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang") endif() add_subdirectory(src/cache) +add_subdirectory(src/sched) if (ENGINE_ENABLE_HIP) add_library(gufo_hip_host STATIC src/core/hip/host_allocations.cpp) @@ -251,6 +243,7 @@ if (ENGINE_ENABLE_HIP) add_library(gufo_cache_hip STATIC src/core/hip/committed_backing.cpp src/core/hip/component_cache_resources.cpp + src/core/hip/snapshot_copy.hip src/core/hip/staging.cpp src/core/hip/transfer_pool.cpp) target_link_libraries(gufo_cache_hip PUBLIC gufo_cache gufo_hip_host hip::host) @@ -297,8 +290,10 @@ if (ENGINE_ENABLE_HIP) endif() add_subdirectory(src/core/platform) +add_subdirectory(src/core/rust) add_library(gufo_core STATIC + src/core/base64.cpp src/core/image.cpp src/core/crypto/sha256.cpp src/core/gguf_reader.cpp @@ -306,15 +301,17 @@ add_library(gufo_core STATIC src/core/json_constraint.cpp src/core/json_schema_lexeme.cpp src/core/json_schema_regex.cpp + src/core/lora/adapter.cpp src/core/sampling.cpp src/core/sampling_logit_row.cpp src/core/hip/hipblaslt_plan_database.cpp src/core/quant/ggml_dequant.cpp src/core/quant/ggml_gemm.cpp + src/core/audio.cpp ) target_include_directories(gufo_core PUBLIC ${CMAKE_SOURCE_DIR}) target_link_libraries(gufo_core PUBLIC gufo_platform ICU::uc ICU::i18n - Threads::Threads PNG::PNG JPEG::JPEG PkgConfig::WEBP CURL::libcurl + Threads::Threads gufo_rust JPEG::JPEG PkgConfig::WEBP CURL::libcurl OpenSSL::Crypto) # Family libraries come before the model that needs them; they may depend on @@ -338,7 +335,6 @@ endif() if (ENGINE_ENABLE_HIP) target_sources(gufo_core PRIVATE - src/core/hip/snapshot_copy.hip src/core/hip/weight_upload.cpp src/core/speculative/speculative_verifier.cpp ) @@ -350,6 +346,26 @@ if (ENGINE_ENABLE_HIP) roc::hipblaslt roc::rocblas) endif() +# The link contracts for extensions. They add no Gufo include path: the headers +# come from the audited public surface of gufo_ext_runtime. +add_library(gufo_ext_core INTERFACE) +target_link_libraries(gufo_ext_core INTERFACE $ + OpenSSL::Crypto) +add_library(gufo_ext_cache INTERFACE) +if (ENGINE_ENABLE_HIP) + target_link_libraries(gufo_ext_cache INTERFACE $) + add_library(gufo_ext_hip INTERFACE) + target_compile_definitions(gufo_ext_hip INTERFACE ENGINE_ENABLE_HIP=1) + target_include_directories(gufo_ext_hip SYSTEM INTERFACE + ${HIPCUB_INCLUDE_DIR} + ${ROCPRIM_INCLUDE_DIR}) + # `hip_utils.hpp` in the public surface includes hipBLAS. + target_link_libraries(gufo_ext_hip INTERFACE $ + hip::host roc::hipblas) +else() + target_link_libraries(gufo_ext_cache INTERFACE $) +endif() + # Card 08 (RFC step 5): the model, comparison and eval tiers that used to be # object files of gufo_core are separate targets now. They are added here, # after the warning/sanitizer block, so their sources keep the compile @@ -359,11 +375,19 @@ add_subdirectory(src/eval) add_library(gufo_llm_cli STATIC src/cli/bench/bench.cpp - src/cli/prompt/prompt.cpp) + src/cli/prompt/prompt.cpp + src/cli/provider_options.cpp + src/cli/speculative_settings.cpp) target_link_libraries(gufo_llm_cli PUBLIC gufo_core gufo_compare gufo_ext_runtime) add_subdirectory(src/ext) +add_library(gufo_tp_control STATIC src/cli/serve/tp_control.cpp) +target_include_directories(gufo_tp_control PUBLIC ${PROJECT_SOURCE_DIR}) +target_compile_features(gufo_tp_control PUBLIC cxx_std_20) +target_link_libraries(gufo_tp_control PUBLIC gufo_core Threads::Threads) +target_link_libraries(gufo_tp_control PRIVATE OpenSSL::Crypto) + # RFC step 6: the text-serving tier the gufo executable used to compile into # itself. Scheduler, runner pool, component text cache and InferenceBackend # live here; queueing, retention/admission and API policy stay on this core @@ -374,9 +398,11 @@ add_library(gufo_serving STATIC src/cli/serve/component_text_cache.cpp src/cli/serve/text_model_runner.cpp src/cli/serve/text_generation_scheduler.cpp + src/cli/serve/tp_executor.cpp + src/cli/serve/tp_disk_store.cpp src/cli/serve/inference_backend.cpp) target_link_libraries(gufo_serving PUBLIC gufo_ext_runtime gufo_logging - gufo_core gufo_cache) + gufo_core gufo_cache gufo_tp_control gufo_sched) # The executable's own objects carried production NDEBUG, the test binaries that # re-compiled these sources forced assertions on. One library can only pick # one: test builds keep assertions, so a test-preset `gufo` now asserts where it @@ -412,7 +438,7 @@ add_library(gufo_http STATIC src/cli/serve/tts_websocket.cpp src/cli/serve/openai_chat.cpp ) -target_link_libraries(gufo_http PUBLIC gufo_logging gufo_ext_runtime gufo_core gufo_qwen_text) +target_link_libraries(gufo_http PUBLIC gufo_logging gufo_ext_runtime gufo_core gufo_qwen_text PNG::PNG) add_executable(gufo src/cli/main.cpp @@ -432,8 +458,26 @@ target_link_libraries(gufo PRIVATE gufo_cache gufo_diagnostics gufo_core gufo_ev # they are added. include(CTest) gufo_build_discovered_extensions() + get_property(gufo_selected_extensions GLOBAL PROPERTY GUFO_SELECTED_EXTENSIONS) -gufo_target_extensions(gufo EXTENSIONS ${gufo_selected_extensions}) +if (GUFO_EXTENSION_MODULES) + list(REMOVE_ITEM gufo_selected_extensions ${GUFO_EXTENSION_MODULES}) +endif() +gufo_target_extensions(gufo LOAD_MODULES EXTENSIONS ${gufo_selected_extensions}) +set(GUFO_EXTENSION_MODULE_HOST gufo) +gufo_extension_modules(EXTENSIONS ${GUFO_EXTENSION_MODULES}) +gufo_extension_build_id(gufo_extension_build_id) +include(cmake/GufoExtensionSdk.cmake) +gufo_extension_sdk(gufo) +target_sources(gufo PRIVATE src/cli/extension/modules.cpp + src/cli/extension/store.cpp src/cli/extension/extension.cpp + src/cli/extension/registry.cpp) +set_property(SOURCE src/cli/extension/modules.cpp + src/cli/extension/store.cpp APPEND PROPERTY + COMPILE_DEFINITIONS GUFO_EXTENSION_BUILD_ID="${gufo_extension_build_id}" + GUFO_EXECUTABLE_FILE_NAME="$") +include(cmake/GufoExtensionHost.cmake) +gufo_extension_host(gufo) gufo_stage_hip_runtime(gufo) target_compile_definitions(gufo PRIVATE GUFO_RELEASE_VERSION="${GUFO_RELEASE_VERSION}" @@ -465,22 +509,33 @@ if (BUILD_TESTING OR GUFO_BUILD_TOOLS) endif() if (ENGINE_ENABLE_HIP AND GUFO_BUILD_TOOLS) - find_path(ROCTX_INCLUDE_DIR rocprofiler-sdk-roctx/roctx.h REQUIRED) - find_library(ROCTX_LIBRARY NAMES rocprofiler-sdk-roctx REQUIRED) - add_executable(gufo-kernel-bench - src/cli/bench/kernel_bench_main.cpp - ) - target_compile_definitions(gufo-kernel-bench PRIVATE - GUFO_REVISION="${GUFO_REVISION}") - target_include_directories(gufo-kernel-bench SYSTEM PRIVATE - ${ROCTX_INCLUDE_DIR}) - target_link_libraries(gufo-kernel-bench PRIVATE - gufo_kernel_bench_support - gufo_diagnostics - gufo_core - ${GUFO_QWEN_LIBRARIES} - gufo_qwen_kernels - ${ROCTX_LIBRARY}) + # TheRock for Windows ships no roctx; skip only gufo-kernel-bench there so + # the other tools (e.g. qwen27b_verify_sweep) still build. + if (WIN32) + find_path(ROCTX_INCLUDE_DIR rocprofiler-sdk-roctx/roctx.h) + find_library(ROCTX_LIBRARY NAMES rocprofiler-sdk-roctx) + else() + find_path(ROCTX_INCLUDE_DIR rocprofiler-sdk-roctx/roctx.h REQUIRED) + find_library(ROCTX_LIBRARY NAMES rocprofiler-sdk-roctx REQUIRED) + endif() + if (ROCTX_INCLUDE_DIR AND ROCTX_LIBRARY) + add_executable(gufo-kernel-bench + src/cli/bench/kernel_bench_main.cpp + ) + target_compile_definitions(gufo-kernel-bench PRIVATE + GUFO_REVISION="${GUFO_REVISION}") + target_include_directories(gufo-kernel-bench SYSTEM PRIVATE + ${ROCTX_INCLUDE_DIR}) + target_link_libraries(gufo-kernel-bench PRIVATE + gufo_kernel_bench_support + gufo_diagnostics + gufo_core + ${GUFO_QWEN_LIBRARIES} + gufo_qwen_kernels + ${ROCTX_LIBRARY}) + else() + message(STATUS "gufo: roctx not found, skipping gufo-kernel-bench") + endif() add_executable(tune_hipblaslt tools/bench/tune_hipblaslt.cpp) target_link_libraries(tune_hipblaslt PRIVATE gufo_core gufo_qwen_kernels @@ -502,8 +557,10 @@ else() install(CODE "execute_process(COMMAND \"${CMAKE_COMMAND}\" -E copy \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/gufo.exe\" \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/gufo-server.exe\")") endif() if (ENGINE_ENABLE_HIP AND GUFO_BUILD_TOOLS) - install(TARGETS gufo-kernel-bench tune_hipblaslt - DESTINATION bin) + install(TARGETS tune_hipblaslt DESTINATION bin) + if (TARGET gufo-kernel-bench) + install(TARGETS gufo-kernel-bench DESTINATION bin) + endif() endif() # CTest integration @@ -521,11 +578,13 @@ if (BUILD_TESTING) # In-tree test support for model API tests (RFC Step 7b, Card 12). # Wraps HTTP and serving fixtures so tests stop reaching src/cli/ directly. # Excluded from production, external extensions, and installation. - add_library(gufo_test_support STATIC tests/support/test_support.cpp) + add_library(gufo_test_support STATIC tests/support/test_support.cpp + tests/support/layered_prefill_conformance.cpp) target_include_directories(gufo_test_support PUBLIC ${CMAKE_SOURCE_DIR}) target_link_libraries(gufo_test_support PUBLIC gufo_http gufo_serving) add_subdirectory(tests/cache) + add_subdirectory(tests/sched) add_subdirectory(tests/extensions) # Opt-in live process-failure checks, never preloaded into hosted tests or @@ -648,6 +707,11 @@ function(gufo_qwen_image_21_register_tests) target_link_libraries(qwen_image_21_test PRIVATE gufo_qwen_image_21 gufo_test_support) add_test(NAME qwen_image_21_test COMMAND qwen_image_21_test) set_tests_properties(qwen_image_21_test PROPERTIES LABELS "cpu;models;qwen-image") + add_executable(qwen_image_21_lora_test + ${PROJECT_SOURCE_DIR}/tests/models/qwen_image_21/lora_test.cpp) + target_link_libraries(qwen_image_21_lora_test PRIVATE gufo_qwen_image_21) + add_test(NAME qwen_image_21_lora_test COMMAND qwen_image_21_lora_test) + set_tests_properties(qwen_image_21_lora_test PROPERTIES LABELS "cpu;models;qwen-image") if(ENGINE_ENABLE_HIP AND TARGET gufo_qwen_image_21_hip) add_executable(qwen_image_21_weight_upload_test ${PROJECT_SOURCE_DIR}/tests/models/qwen_image_21/weights_test.cpp) @@ -659,13 +723,18 @@ function(gufo_qwen_image_21_register_tests) LABELS "gpu;qwen-image" SKIP_RETURN_CODE 77) add_executable(qwen_image_21_kernel_test ${PROJECT_SOURCE_DIR}/tests/models/qwen_image_21/kernel_test.hip) - target_link_libraries(qwen_image_21_kernel_test PRIVATE gufo_qwen_image_21 gufo_qwen_image_21_hip) + target_link_libraries(qwen_image_21_kernel_test PRIVATE gufo_qwen_image_21 gufo_qwen_image_21_hip + hip::host roc::hipblas) add_test(NAME qwen_image_21_kernel_test COMMAND qwen_image_21_kernel_test) set_tests_properties(qwen_image_21_kernel_test PROPERTIES LABELS "gpu;qwen-image" SKIP_RETURN_CODE 77) add_executable(qwen_image_21_probe ${PROJECT_SOURCE_DIR}/tools/models/qwen_image_21/probe.cpp) target_link_libraries(qwen_image_21_probe PRIVATE gufo_qwen_image_21 gufo_qwen_image_21_hip) + add_executable(qwen_image_21_lora_dump + ${PROJECT_SOURCE_DIR}/tools/models/qwen_image_21/lora_dump.cpp) + target_link_libraries(qwen_image_21_lora_dump PRIVATE gufo_qwen_image_21 gufo_qwen_image_21_hip + hip::host roc::hipblas OpenSSL::Crypto) endif() endfunction() @@ -738,6 +807,38 @@ endfunction() "${CMAKE_CURRENT_SOURCE_DIR}/tests/functional/fixtures/audio/clear-english-voice.wav") set_tests_properties(transcribe_cli_test PROPERTIES LABELS "cpu;cli;audio") + add_executable(tp_control_test tests/cli/tp_control_test.cpp) + target_link_libraries(tp_control_test PRIVATE gufo_tp_control) + add_test(NAME tp_control_test COMMAND tp_control_test) + set_tests_properties(tp_control_test PROPERTIES LABELS "cpu;tp2" TIMEOUT 10) + + add_executable(tp_disk_store_test tests/cli/tp_disk_store_test.cpp) + target_link_libraries(tp_disk_store_test PRIVATE gufo_serving) + add_test(NAME tp_disk_store_test COMMAND tp_disk_store_test) + set_tests_properties(tp_disk_store_test PROPERTIES + LABELS "cpu;tp2;cache;disk" TIMEOUT 10) + + # A measurement, not a gate: it asserts no threshold and never fails on a + # slow result, so it is labelled `perf` and kept out of the correctness run. + add_executable(tp_instruction_latency_test + tests/cli/tp_instruction_latency_test.cpp) + target_link_libraries(tp_instruction_latency_test PRIVATE gufo_tp_control) + add_test(NAME tp_instruction_latency_test + COMMAND tp_instruction_latency_test) + set_tests_properties(tp_instruction_latency_test PROPERTIES + LABELS "cpu;tp2;perf" TIMEOUT 300) + + add_executable(tp_executor_test tests/cli/tp_executor_test.cpp) + target_link_libraries(tp_executor_test PRIVATE gufo_serving gufo_tp_control) + add_test(NAME tp_executor_test COMMAND tp_executor_test) + set_tests_properties(tp_executor_test PROPERTIES LABELS "cpu;tp2" TIMEOUT 60) + + add_executable(tp_snapshot_gate_test tests/cli/tp_snapshot_gate_test.cpp) + target_link_libraries(tp_snapshot_gate_test PRIVATE Threads::Threads) + add_test(NAME tp_snapshot_gate_test COMMAND tp_snapshot_gate_test) + set_tests_properties(tp_snapshot_gate_test PROPERTIES + LABELS "cpu;tp2" TIMEOUT 20) + add_executable(json_constraint_test tests/core/json_constraint_test.cpp) target_link_libraries(json_constraint_test PRIVATE gufo_core) target_compile_definitions(json_constraint_test PRIVATE @@ -750,11 +851,39 @@ endfunction() add_test(NAME json_test COMMAND json_test) set_tests_properties(json_test PROPERTIES LABELS "cpu;json") + # The test writes its PNG cases with zlib directly. + find_package(ZLIB REQUIRED) + add_executable(png_decode_test + tests/core/png_decode_test.cpp + tests/core/png_reference.cpp) + target_link_libraries(png_decode_test PRIVATE gufo_core PNG::PNG ZLIB::ZLIB) + add_test(NAME png_decode_test COMMAND png_decode_test) + set_tests_properties(png_decode_test PROPERTIES LABELS "cpu;image;correctness") + + add_executable(audio_decode_test tests/core/audio_decode_test.cpp) + target_link_libraries(audio_decode_test PRIVATE gufo_core) + target_compile_definitions(audio_decode_test PRIVATE + GUFO_AUDIO_DECODE_FIXTURES="${PROJECT_SOURCE_DIR}/tests/fixtures/audio") + add_test(NAME audio_decode_test COMMAND audio_decode_test) + set_tests_properties(audio_decode_test PROPERTIES LABELS "cpu;audio;correctness") + + add_executable(wav_decode_test + tests/core/wav_decode_test.cpp + tests/core/wav_reference.cpp) + target_link_libraries(wav_decode_test PRIVATE gufo_core) + add_test(NAME wav_decode_test COMMAND wav_decode_test) + set_tests_properties(wav_decode_test PROPERTIES LABELS "cpu;audio;correctness") + add_executable(heap_placement_test tests/core/heap_placement_test.cpp) target_link_libraries(heap_placement_test PRIVATE gufo_core) add_test(NAME heap_placement_test COMMAND heap_placement_test) set_tests_properties(heap_placement_test PROPERTIES LABELS "cpu;hip;core") + add_executable(admission_memory_test tests/core/admission_memory_test.cpp) + target_link_libraries(admission_memory_test PRIVATE gufo_core) + add_test(NAME admission_memory_test COMMAND admission_memory_test) + set_tests_properties(admission_memory_test PROPERTIES LABELS "cpu;hip;core") + add_executable(sampling_test tests/core/sampling_test.cpp) target_link_libraries(sampling_test PRIVATE gufo_core) add_test(NAME sampling_test COMMAND sampling_test) @@ -782,6 +911,13 @@ endfunction() add_test(NAME quote_tracker_test COMMAND quote_tracker_test) set_tests_properties(quote_tracker_test PROPERTIES LABELS "cpu;server;api") + # Image provider startup options and request capabilities with fake + # providers; no sockets, so it runs on every host. + add_executable(image_api_test tests/cli/image_api_test.cpp) + target_link_libraries(image_api_test PRIVATE gufo_http gufo_llm_cli) + add_test(NAME image_api_test COMMAND image_api_test) + set_tests_properties(image_api_test PROPERTIES LABELS "cpu;server;api;image") + # the trace suite simulates RLIMIT_FSIZE if (NOT WIN32) add_executable(trace_test tests/cli/trace_test.cpp) @@ -790,6 +926,29 @@ endfunction() set_tests_properties(trace_test PROPERTIES LABELS "cpu;server;trace") endif() + add_executable(base64_test + tests/core/base64_test.cpp + tests/core/base64_reference.cpp) + target_link_libraries(base64_test PRIVATE gufo_http) + add_test(NAME base64_test COMMAND base64_test) + set_tests_properties(base64_test PROPERTIES LABELS "cpu;server;correctness") + + add_executable(websocket_frame_test + tests/cli/websocket_frame_test.cpp + tests/cli/websocket_frame_reference.cpp) + target_link_libraries(websocket_frame_test PRIVATE gufo_core) + add_test(NAME websocket_frame_test COMMAND websocket_frame_test) + set_tests_properties(websocket_frame_test PROPERTIES + LABELS "cpu;server;correctness") + + add_executable(http_request_test + tests/cli/http_request_test.cpp + tests/cli/http_request_reference.cpp) + target_link_libraries(http_request_test PRIVATE gufo_core) + add_test(NAME http_request_test COMMAND http_request_test) + set_tests_properties(http_request_test PROPERTIES + LABELS "cpu;server;http;correctness") + # These HTTP/WebSocket suites drive raw POSIX sockets or fork() directly. if (NOT WIN32) add_executable(http_server_test tests/cli/http_server_test.cpp) @@ -825,28 +984,41 @@ endfunction() ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/check_extension_isolation_test.py) add_test(NAME extension_isolation_report COMMAND ${Python3_EXECUTABLE} - ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py --mode report) + ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py --mode report + --json-report "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json") add_test(NAME extension_core_model_includes_gate COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py + --inventory "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json" --fail-on-core-model-includes) add_test(NAME extension_serving_boundary_gate COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py + --inventory "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json" --fail-on-serving-boundary) add_test(NAME extension_model_core_includes_gate COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py + --inventory "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json" --fail-on-model-core-includes) add_test(NAME extension_family_graph_gate COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py + --inventory "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json" --fail-on-family-graph) add_test(NAME extension_target_ownership_gate COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/ci/check-extension-isolation.py + --inventory "${CMAKE_CURRENT_BINARY_DIR}/extension-isolation.json" --fail-on-target-ownership) - # The checker's own tests scan the tree many times: about 25 s on Linux. + # CTest refreshes the snapshot once per invocation, including when a single + # gate is selected with -R. Gates keep separate names and failure output. + set_tests_properties(extension_isolation_report PROPERTIES + FIXTURES_SETUP gufo_extension_inventory) + set_tests_properties(extension_core_model_includes_gate + extension_serving_boundary_gate extension_model_core_includes_gate + extension_family_graph_gate extension_target_ownership_gate PROPERTIES + FIXTURES_REQUIRED gufo_extension_inventory) set_tests_properties(check_extension_isolation_test PROPERTIES LABELS "cpu;repository" TIMEOUT 180) set_tests_properties(extension_isolation_report @@ -915,29 +1087,49 @@ endfunction() set_tests_properties(continuation_cache_test PROPERTIES LABELS "cpu;server;cache;state;lifecycle") + if (NOT WIN32) + add_executable(continuation_disk_store_test + tests/cli/continuation_disk_store_test.cpp) + target_link_libraries(continuation_disk_store_test PRIVATE gufo_serving) + add_test(NAME continuation_disk_store_test + COMMAND continuation_disk_store_test) + set_tests_properties(continuation_disk_store_test PROPERTIES + LABELS "cpu;server;cache;disk;state;lifecycle") + endif() + add_executable(component_text_cache_test tests/cli/component_text_cache_test.cpp) target_link_libraries(component_text_cache_test PRIVATE gufo_cache_fake gufo_serving) add_test(NAME component_text_cache_test COMMAND component_text_cache_test) - set_tests_properties(component_text_cache_test PROPERTIES LABELS "cpu;server;cache;state;lifecycle") + # Start the long persistence suite early while other contracts fill the + # remaining CTest slots. Costs order tests; they do not change timeouts. + set_tests_properties(component_text_cache_test PROPERTIES + LABELS "cpu;server;cache;state;lifecycle" COST 70) + + add_executable(legacy_text_model_runner_test tests/cli/legacy_text_model_runner_test.cpp) + target_link_libraries(legacy_text_model_runner_test PRIVATE gufo_serving ${GUFO_QWEN_LIBRARIES}) + add_test(NAME legacy_text_model_runner_test COMMAND legacy_text_model_runner_test) + set_tests_properties(legacy_text_model_runner_test PROPERTIES LABELS "cpu;server;tp2;cache;lifecycle") add_executable(text_model_runner_test tests/cli/text_model_runner_test.cpp) - target_link_libraries(text_model_runner_test PRIVATE gufo_serving + target_link_libraries(text_model_runner_test PRIVATE gufo_cache_fake gufo_serving ${GUFO_QWEN_LIBRARIES}) add_test(NAME text_model_runner_test COMMAND text_model_runner_test) set_tests_properties(text_model_runner_test PROPERTIES LABELS "cpu;server;runner;cache;state;lifecycle") + add_executable(layered_prefill_conformance_test + tests/cli/layered_prefill_conformance_test.cpp) + target_link_libraries(layered_prefill_conformance_test PRIVATE + gufo_cache_fake gufo_test_support) + add_test(NAME layered_prefill_conformance_test + COMMAND layered_prefill_conformance_test) + set_tests_properties(layered_prefill_conformance_test PROPERTIES + LABELS "cpu;server;scheduler;runner" TIMEOUT 30) + # the disk-store suite exercises permission faults with chmod and lstat if (NOT WIN32) - add_executable(continuation_disk_store_test - tests/cli/continuation_disk_store_test.cpp) - target_link_libraries(continuation_disk_store_test PRIVATE gufo_serving) - add_test(NAME continuation_disk_store_test - COMMAND continuation_disk_store_test) - set_tests_properties(continuation_disk_store_test PROPERTIES - LABELS "cpu;server;cache;disk;state;lifecycle") endif() add_executable(logit_sampler_test tests/cli/logit_sampler_test.cpp) @@ -948,7 +1140,20 @@ endfunction() add_executable(text_generation_scheduler_test tests/cli/text_generation_scheduler_test.cpp) - target_link_libraries(text_generation_scheduler_test PRIVATE gufo_serving) + target_link_libraries(text_generation_scheduler_test PRIVATE gufo_cache_fake + gufo_serving) + # Text models load only in HIP builds; the CPU build rejects every load. + if (ENGINE_ENABLE_HIP) + add_executable(serve_provider_options_test + tests/cli/serve_provider_options_test.cpp) + target_link_libraries(serve_provider_options_test PRIVATE gufo_serving + gufo_llm_cli) + add_test(NAME serve_provider_options_test + COMMAND serve_provider_options_test) + set_tests_properties(serve_provider_options_test PROPERTIES + LABELS "gpu;server;cli;extensions") + endif() + add_test(NAME text_generation_scheduler_test COMMAND text_generation_scheduler_test) set_tests_properties(text_generation_scheduler_test PROPERTIES @@ -980,6 +1185,13 @@ endfunction() set_tests_properties(text_cli_dispatch_${command} PROPERTIES LABELS "cpu;cli;extensions") endforeach() + add_executable(extension_diagnostics_test + tests/cli/extension_diagnostics_test.cpp + src/cli/extension_diagnostics.cpp) + target_link_libraries(extension_diagnostics_test PRIVATE gufo_ext_runtime) + add_test(NAME extension_diagnostics_test COMMAND extension_diagnostics_test) + set_tests_properties(extension_diagnostics_test PROPERTIES LABELS "cpu;cli;extensions") + # H3 host contracts share an object with generation. In HIP builds that # object references the backend implementations, so tests need both tiers. set(gufo_minimax_h3_test_libraries gufo_minimax_h3) @@ -993,6 +1205,7 @@ endfunction() src/cli/video/video.cpp ) target_link_libraries(video_cli_test PRIVATE gufo_core ${gufo_minimax_h3_test_libraries} gufo_ext_runtime) + gufo_target_extensions(video_cli_test EXTENSIONS ${gufo_selected_extensions}) add_test(NAME video_cli_test COMMAND video_cli_test) set_tests_properties(video_cli_test PROPERTIES LABELS "cpu;server;cli;minimax-h3;quality") @@ -1023,37 +1236,37 @@ endfunction() COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_profile_test.py) set_tests_properties(h3_profile_test PROPERTIES - LABELS "cpu;profiling;video;minimax-h3;quality") + LABELS "cpu;profiling;video;minimax-h3;quality;h3-qualification") add_test(NAME h3_preset_quality_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_preset_quality_test.py) set_tests_properties(h3_preset_quality_test PROPERTIES - LABELS "cpu;tools;models;minimax-h3;quality;video;audio") + LABELS "cpu;tools;models;minimax-h3;quality;video;audio;h3-qualification") add_test(NAME h3_rng_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_rng_test.py) set_tests_properties(h3_rng_test PROPERTIES - LABELS "cpu;tools;models;minimax-h3;quality") + LABELS "cpu;tools;models;minimax-h3;quality;h3-qualification") add_test(NAME h3_latent_quality_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_latent_quality_test.py) set_tests_properties(h3_latent_quality_test PROPERTIES - LABELS "cpu;tools;models;minimax-h3;quality") + LABELS "cpu;tools;models;minimax-h3;quality;h3-qualification") add_test(NAME h3_cache_control_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_cache_control_test.py) set_tests_properties(h3_cache_control_test PROPERTIES - LABELS "cpu;tools;models;minimax-h3;profiling") + LABELS "cpu;tools;models;minimax-h3;profiling;h3-qualification") add_test(NAME h3_profile_report_test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/h3_profile_report_test.py) set_tests_properties(h3_profile_report_test PROPERTIES - LABELS "cpu;tools;models;minimax-h3;profiling") + LABELS "cpu;tools;models;minimax-h3;profiling;h3-qualification") add_test(NAME serving_bench_test COMMAND ${Python3_EXECUTABLE} @@ -1209,6 +1422,14 @@ endfunction() set_tests_properties(minimax_h3_sampling_test PROPERTIES LABELS "cpu;models;minimax-h3;layout;schedule;rng;quality") + add_executable(minimax_h3_presentation_test + tests/models/minimax_h3_presentation_test.cpp) + target_link_libraries(minimax_h3_presentation_test PRIVATE gufo_core ${gufo_minimax_h3_test_libraries}) + add_test(NAME minimax_h3_presentation_test COMMAND minimax_h3_presentation_test) + set_tests_properties(minimax_h3_presentation_test PROPERTIES + LABELS "cpu;models;minimax-h3;presentation;tokenizer;external-model" + SKIP_RETURN_CODE 77) + add_executable(minimax_h3_generation_test tests/models/minimax_h3_generation_test.cpp) target_link_libraries(minimax_h3_generation_test PRIVATE gufo_core ${gufo_minimax_h3_test_libraries}) @@ -1311,13 +1532,11 @@ endfunction() set_tests_properties(platform_publish_test PROPERTIES LABELS "cpu;platform") endif() - # the prefault fixture maps pages with mmap - if (NOT WIN32) + # POSIX checks with mmap, Windows with a file view and QueryWorkingSetEx add_executable(platform_prefault_test tests/core/platform_prefault_test.cpp) target_link_libraries(platform_prefault_test PRIVATE Threads::Threads) add_test(NAME platform_prefault_test COMMAND platform_prefault_test) set_tests_properties(platform_prefault_test PROPERTIES LABELS "cpu;platform") - endif() include(cmake/PlatformTests.cmake) @@ -1468,6 +1687,32 @@ endfunction() LABELS "gpu;hip;gfx1151;minimax-h3;video;vae;quality;external-model;very-slow" SKIP_RETURN_CODE 77) + add_executable(minimax_h3_video_vae_encoder_hip_test + tests/models/minimax_h3_video_vae_encoder_hip_test.hip) + target_compile_definitions(minimax_h3_video_vae_encoder_hip_test PRIVATE + GUFO_H3_SOURCE_MANIFEST="${CMAKE_CURRENT_SOURCE_DIR}/src/models/minimax_h3/MINIMAX_H3_FL2VA_BF16.source-manifest.json" + GUFO_H3_VAE_ENCODER_FIXTURE="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/minimax_h3/video-vae-encoder-oracle-v1.json") + target_link_libraries(minimax_h3_video_vae_encoder_hip_test PRIVATE + gufo_core gufo_minimax_h3 gufo_minimax_h3_hip hip::host) + add_test(NAME minimax_h3_video_vae_encoder_real + COMMAND minimax_h3_video_vae_encoder_hip_test) + set_tests_properties(minimax_h3_video_vae_encoder_real PROPERTIES + LABELS "gpu;hip;gfx1151;minimax-h3;video;vae;encoder;quality;external-model;slow" + SKIP_RETURN_CODE 77) + + add_executable(minimax_h3_vision_tower_hip_test + tests/models/minimax_h3_vision_tower_hip_test.hip) + target_compile_definitions(minimax_h3_vision_tower_hip_test PRIVATE + GUFO_H3_SOURCE_MANIFEST="${CMAKE_CURRENT_SOURCE_DIR}/src/models/minimax_h3/MINIMAX_H3_FL2VA_BF16.source-manifest.json" + GUFO_H3_VISION_FIXTURE="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/minimax_h3/vision-tower-oracle-v1.json") + target_link_libraries(minimax_h3_vision_tower_hip_test PRIVATE + gufo_core gufo_minimax_h3 gufo_minimax_h3_hip hip::host) + add_test(NAME minimax_h3_vision_tower_real + COMMAND minimax_h3_vision_tower_hip_test) + set_tests_properties(minimax_h3_vision_tower_real PROPERTIES + LABELS "gpu;hip;gfx1151;minimax-h3;vision;tower;quality;external-model;slow" + SKIP_RETURN_CODE 77) + add_executable(minimax_h3_audio_vae_hip_test tests/models/minimax_h3_audio_vae_hip_test.hip) target_compile_definitions(minimax_h3_audio_vae_hip_test PRIVATE diff --git a/CMakePresets.json b/CMakePresets.json index 2654cd0506..db9a5bcebb 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -101,6 +101,15 @@ "ENGINE_ENABLE_HIP": "ON", "GUFO_BUILD_TOOLS": "ON" } + }, + { + "name": "gpu-tp2", + "displayName": "gfx1151 TP=2 RDMA Tests", + "description": "GPU correctness build with the optional native RDMA adapter", + "inherits": "gpu-test", + "cacheVariables": { + "GUFO_ENABLE_TP2_RDMA": "ON" + } } ], "buildPresets": [ @@ -134,6 +143,11 @@ "displayName": "gfx1151 GPU Tests", "configurePreset": "gpu-test" }, + { + "name": "gpu-tp2", + "displayName": "gfx1151 TP=2 RDMA Tests", + "configurePreset": "gpu-tp2" + }, { "name": "pr", "configurePreset": "cpu-test", diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000000..8ce073c89b --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,345 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "extended" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "gufo-audio-decode" +version = "0.0.0" +dependencies = [ + "gufo-resample", + "gufo-wav-decode", + "symphonia", +] + +[[package]] +name = "gufo-base64" +version = "0.0.0" + +[[package]] +name = "gufo-http" +version = "0.0.0" +dependencies = [ + "httparse", +] + +[[package]] +name = "gufo-png-decode" +version = "0.0.0" +dependencies = [ + "png", +] + +[[package]] +name = "gufo-resample" +version = "0.0.0" + +[[package]] +name = "gufo-rust" +version = "0.0.0" +dependencies = [ + "gufo-audio-decode", + "gufo-base64", + "gufo-http", + "gufo-png-decode", + "gufo-websocket", +] + +[[package]] +name = "gufo-wav-decode" +version = "0.0.0" + +[[package]] +name = "gufo-websocket" +version = "0.0.0" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "symphonia" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac", + "symphonia-bundle-mp3", + "symphonia-codec-adpcm", + "symphonia-codec-pcm", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-ogg", + "symphonia-format-riff", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-flac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6405d5c34ff6f8f7ca08a4101efe66d21e180f7322ef9359900a0e55698a7892" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ea5ffc8716bff677dfb3b01b420c7b758de901a72b8c330bf2040ab74b4add" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-adpcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445932ecb0c59362fde9c082dd63a75380650c5077fdb8b80b8cac850442a74c" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e04ba75686acbe43542fdd374571195f0530c0b7785ca25cc6840e9c6c4b6eea" +dependencies = [ + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73d90b4fcf796137cc683c538282804ff9629f8ad9dbfd881fcbba331ac4e986" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", +] + +[[package]] +name = "symphonia-common" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acc3fcc18ec9b8cdd48614e259c4cf0d27b71d41e5d9b120b42c5adab12d7c4" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-core" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c412864d599d4750d0c3d684d7e093ec05e5309681ef5252cc1096a437f6e0" +dependencies = [ + "bitflags", + "bytemuck", + "lazy_static", + "log", + "num-complex", + "smallvec", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5495e7f7e3c7035328d82b6d6e377eef289bb0c4105bdeb557fc93a833f994" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ff70929083a8c1a5f6cd7c904b6071c7914ad04739b510c2f7239dfc9b7dabe" +dependencies = [ + "extended", + "log", + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-metadata" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83713a97705d77bdef7cdbc0768fd6e5a54e4cd7e48d60a806ae85639e2c87c6" +dependencies = [ + "lazy_static", + "log", + "regex-lite", + "smallvec", + "symphonia-core", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000000..c13fb3372d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +# The Rust components. Each one is a crate with a small C ABI; the gufo-rust +# crate in src/core/rust links them into the single static library that C++ +# links, so the standard library and shared crates are built once. +[workspace] +resolver = "3" +members = ["src/core/rust", "src/core/audio_decode", "src/core/base64", "src/core/http", "src/core/png_decode", "src/core/resample", "src/core/wav_decode", "src/core/websocket"] + +[workspace.package] +version = "0.0.0" +edition = "2024" +rust-version = "1.88" +publish = false +license = "MIT" + +[profile.release] +debug = 1 + +# CMake RelWithDebInfo, the shipped configuration. +[profile.relwithdebinfo] +inherits = "release" +debug = 2 + +# Optimized test builds (BUILD_TESTING=ON), which keep C++ assertions on too. +[profile.checked] +inherits = "relwithdebinfo" +debug-assertions = true +overflow-checks = true diff --git a/NOTICE b/NOTICE index 2278bdcfb7..f5394f02c2 100644 --- a/NOTICE +++ b/NOTICE @@ -29,6 +29,13 @@ Copyright (c) 2026 notice is retained in licenses/strix-halo-llamacpp.txt This software is based in part on the work of the Independent JPEG Group. +The optional TP=2 RDMA build (GUFO_ENABLE_TP2_RDMA) dynamically links +libibverbs from rdma-core (https://github.com/linux-rdma/rdma-core): +Copyright (c) 2004-2012 Intel Corporation, Topspin Communications, Cisco +Systems, PathScale, Mellanox Technologies, Voltaire and others, available +under GPL-2.0-only or the OpenIB.org BSD license (SPDX Linux-OpenIB). Notices +and license texts are in licenses/rdma-core/ (installed in third-party/). + Gufo invokes FFmpeg/ffprobe as separate executables. Their license and source obligations, and those of any other bundled dependency, remain applicable to redistributed packages. Gufo's MIT license does not replace those obligations. diff --git a/README.md b/README.md index fb80295a2e..cb89471bdb 100644 --- a/README.md +++ b/README.md @@ -1,257 +1,157 @@ -# Gufo: The ***Open Source*** Strix Halo AI engine +# Gufo: The ***Open Source*** Strix Halo AI engine

- Gufo logo + Gufo logoGufo logo

-Gufo is a vertical local inference engine for Linux and Windows, specifically built and optimized for AMD Strix Halo hardware: -Ryzen AI MAX+ 395 systems with Radeon 8060S (`gfx1151`), up to 128 GiB of unified memory. - -**Contributions are welcome!** - -See the [changelog](CHANGELOG.md) and [GitHub Releases](https://github.com/gufo-org/gufo/releases) -for user-facing changes and release history. - -> [!TIP] -> Check out **[Gufo RDMA for Dual Strix Halo](https://github.com/neuhaus/gufo)**, a Gufo variant that has not been merged yet! - -## Models and benchmarks - -All model documentation lives under [docs/models](docs/models/README.md): - -| Model | Inference modes | Hugging Face weights | Benchmarks | Quality | -| --- | --- | --- | --- | --- | -| [Qwen3.8 27B](docs/models/qwen3.8-27b/README.md) | Q4/Q8, images, AR, DFlash2 | Unsloth [Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/blob/4ca720788d1e01f1bff70c033e0d0028fd02e502/Qwen3.8-27B-UD-Q4_K_XL.gguf) / [Q8_K_XL](https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/blob/4ca720788d1e01f1bff70c033e0d0028fd02e502/Qwen3.8-27B-UD-Q8_K_XL.gguf) · [DFlash2 Q4_K_M](https://huggingface.co/z-lab/Qwen3.8-27B-DFlash2-GGUF/blob/2d9571f8ce46e151f61c6499c99dee6079e1d610/Qwen3.8-27B-DFlash2-Q4_K_M.gguf) | Q4: **648.89 tok/s pp**; up to **71.55 tok/s tg** single user and **128.42 aggregated tok/s** on 8 concurrent requests with DFlash2 · [Benchmarks](docs/models/qwen3.8-27b/BENCHMARKS.md) | [Quality](docs/models/qwen3.8-27b/QUALITY.md) | -| [Qwen3.8 Flash-Next](docs/models/qwen3.8-flash-next/README.md) | Q4, images, AR, MTP | Unsloth [Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/tree/38bb39ee97821de2c9009abb7e93950eec396e66/UD-Q4_K_XL) · [MTP Q8_0](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/blob/38bb39ee97821de2c9009abb7e93950eec396e66/MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf) | **1,801.01 tok/s pp** (AR); up to **116.93 tok/s tg** single user and **245.81 aggregated tok/s** on 8 concurrent requests with MTP · [Benchmarks](docs/models/qwen3.8-flash-next/BENCHMARKS.md) | [Quality](docs/models/qwen3.8-flash-next/QUALITY.md) | -| [DeepSeek V4 Flash](docs/models/deepseek-v4-flash/README.md) | AR, DSpark | [antirez Flash 0731 IQ2XXS](https://huggingface.co/antirez/deepseek-v4-gguf/blob/1cd7b564460821938add0475a60b942c409295e0/DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix-0731.gguf) · [DSpark](https://huggingface.co/antirez/deepseek-v4-gguf/blob/e7f04037032990db0346398d249baf9fb9df1ccc/DeepSeek-V4-Flash-DSpark-support-0731.gguf) | **474.87 tok/s pp**; up to **29.57 tok/s tg** single user with DSpark and **77.12 aggregated tok/s** on 8 concurrent requests with AR · [Benchmarks](docs/models/deepseek-v4-flash/BENCHMARKS.md) | [Quality](docs/models/deepseek-v4-flash/QUALITY.md) | -| [Qwen3-ASR 1.7B](docs/models/qwen3-asr/README.md) | Speech recognition | [BF16](https://huggingface.co/Qwen/Qwen3-ASR-1.7B/tree/7278e1e70fe206f11671096ffdd38061171dd6e5) | **15.27× realtime** · [Benchmarks](docs/models/qwen3-asr/BENCHMARKS.md) | [Quality](docs/models/qwen3-asr/QUALITY.md) | -| [EmbeddingGemma 2](docs/models/embeddinggemma-2/README.md) | Text and image embeddings | [BF16](https://huggingface.co/google/embeddinggemma-2/tree/914f7f89142e33e77833254d9c9b90c3cef7303b) | Up to **41.5k tokens/s** over HTTP; **13.0 ms** for a 404-token request · [Benchmarks](docs/models/embeddinggemma-2/BENCHMARKS.md) | [Quality](docs/models/embeddinggemma-2/QUALITY.md) | -| [Qwen3-TTS 1.7B](docs/models/qwen3-tts/README.md) | Speech synthesis and voice cloning | BF16 [CustomVoice](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice) / [VoiceDesign](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign) / [Base](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-Base) | Up to **2.54× realtime**; **201 ms** to first audio (CustomVoice) · [Benchmarks](docs/models/qwen3-tts/BENCHMARKS.md) | [Quality](docs/models/qwen3-tts/QUALITY.md) | -| [Qwen-Image-2.1](docs/models/qwen-image-2.1/README.md) | BF16 image generation and editing | [Complete pipeline](https://huggingface.co/Qwen/Qwen-Image-2.1/tree/b3179ad355be050328e483a9dfdd9e60cd62adfa) | In progress · [Benchmarks](docs/models/qwen-image-2.1/BENCHMARKS.md) | [Quality](docs/models/qwen-image-2.1/QUALITY.md) | -| [Qwen-Image-2.1-Turbo](docs/models/qwen-image-2.1/README.md#qwen-image-21-turbo) | BF16 eight-step image generation and editing | [Complete pipeline](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/tree/fc13ba1986fcb905854dc8de2f52eee395f49b5b) | **18.6 s** per 1024² image, **4.8×** faster than the 40-step base model · [Benchmarks](docs/models/qwen-image-2.1/BENCHMARKS.md#qwen-image-21-turbo) | [Quality](docs/models/qwen-image-2.1/QUALITY.md#qwen-image-21-turbo) | -| [MiniMax H3](docs/models/minimax-h3/README.md) | BF16 text to video/audio | [FL2VA pipeline](https://huggingface.co/MiniMaxAI/MiniMax-H3/tree/42ed227ee7df40d41602854ae760620d6eb651fe/FL2VA) | In progress · [Benchmarks](docs/models/minimax-h3/BENCHMARKS.md) | [Quality](docs/models/minimax-h3/QUALITY.md) | - -Peak measured workloads; text pp is autoregressive (AR), while tg uses the -named speculative mode. Peaks include repetitive output; aggregate tg sums -individual request decode rates. Qwen27B's single-user peak uses the short-prompt -C1 workload. Audio excludes loading. -Each model guide lists the required files and complete benchmark settings. - -To add or maintain a model, start with the [source extension guide](docs/extensions.md). - -## Philosophy +

+ Latest release + Documentation + Extension API series + MIT license +

-- Contributions are welcome! We need the help of Strix Halo community to keep improving gufo! -- We would like this to be the one-stop shop for Strix Halo Local AI enthusiasts: batteries included for text, audio, image, and video models. -- Build and optimize specifically for the Strix Halo 128 GiB hardware. Smaller memory configurations should still work and preserve the speed benefits for models that can fit on memory. -- Support only the best available models for their size that can run on this hardware: less code to maintain, more focused optimization and testing work. -- Preserve quality when optimizing. Each model's quality report records independent numerical checks, execution consistency and unresolved gaps. Don't reuse kernels across different models to limit blast radius of a code change. -- Treat concurrent requests, cancellation and conversation caching as first-class workloads. -- Keep production dependencies small and development tools separate. - -## Quickstart +Gufo is an open-source inference engine for one machine: AMD Strix Halo, the +Ryzen AI MAX+ 395 with its Radeon 8060S (`gfx1151`) and up to 128 GiB of +unified memory. It serves text, embedding, speech, image and video models over +OpenAI-compatible APIs, from a single binary with kernels tuned for that chip. +It runs on Linux, where releases are built and tested, and natively on +Windows. + +Gufo supports one model per use case, the best that fits, and checks each one +against the original before optimizing it. Its cache is built for coding agents +that resend long conversations, and extensions let you bring your own model. + +This fork includes an experimental two-host tensor-parallel RDMA path. +Canonical upstream is [gufo-org/gufo](https://github.com/gufo-org/gufo). +See the [TP2 setup guide](docs/internal/models/qwen3.8-flash-next/TP2.md) for +matching builds, transport requirements and validation limits. + +## Models + +| Model | What it does | Weights license | +| --- | --- | --- | +| [Qwen3.8 Flash-Next](docs/models/qwen3.8-flash-next.md) | Text and images | [Qwen Community License 1.0](https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/main/LICENSE) | +| [Qwen3.8 27B](docs/models/qwen3.8-27b.md) | Text and images | Apache 2.0 | +| [DeepSeek V4 Flash](docs/models/deepseek-v4-flash.md) | Text | MIT | +| [EmbeddingGemma 2](docs/models/embeddinggemma-2.md) | Embeddings for text, images, audio and video | Apache 2.0 | +| [Qwen3-ASR 1.7B](docs/models/qwen3-asr.md) | Speech to text | Apache 2.0 | +| [Qwen3-TTS 1.7B](docs/models/qwen3-tts.md) | Text to speech and voice cloning | Apache 2.0 | +| [Qwen-Image-2.1](docs/models/qwen-image-2.1.md) | Image generation and editing | [Qwen Research License](https://huggingface.co/Qwen/Qwen-Image-2.1/blob/main/LICENSE), non-commercial | +| [Qwen-Image-2.1-Turbo](docs/models/qwen-image-2.1.md#qwen-image-21-turbo) | Eight-step image generation and editing | [Qwen Research License](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo/blob/main/LICENSE), non-commercial | +| [MiniMax H3](docs/models/minimax-h3.md) | Video with sound | [MiniMax H3 Community License](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE) | + +Each model page lists the files to download, the modes and the measured speed. +Gufo's own code is MIT; the weights keep their publishers' terms. + +Extensions add more models without changing Gufo. With `gufo` set up as in the +[quickstart](#quickstart), install a reviewed one from the +[extension registry](https://github.com/gufo-org/gufo-extension): ```sh -hf download unsloth/Qwen3.8-27B-GGUF \ - Qwen3.8-27B-UD-Q8_K_XL.gguf \ - --revision 4ca720788d1e01f1bff70c033e0d0028fd02e502 \ - --repo-type model \ - --local-dir models/Qwen3.8-27B-GGUF -hf download z-lab/Qwen3.8-27B-DFlash2-GGUF \ - Qwen3.8-27B-DFlash2-Q4_K_M.gguf \ - --revision 2d9571f8ce46e151f61c6499c99dee6079e1d610 \ - --repo-type model \ - --local-dir models/Qwen3.8-27B-DFlash2-GGUF -podman pull ghcr.io/gufo-org/toolboxes/gufo-runtime:latest -podman run --rm \ - --userns=keep-id:uid=1000,gid=1000 \ - --device /dev/kfd \ - --device /dev/dri \ - --group-add keep-groups \ - --ulimit memlock=-1 \ - -p 8080:8080 \ - -v ./models:/models:ro \ - ghcr.io/gufo-org/toolboxes/gufo-runtime:latest \ - gufo serve --host 0.0.0.0 --port 8080 llm \ - --model /models/Qwen3.8-27B-GGUF/Qwen3.8-27B-UD-Q8_K_XL.gguf \ - --speculative dflash2 \ - --dflash-model /models/Qwen3.8-27B-DFlash2-GGUF/Qwen3.8-27B-DFlash2-Q4_K_M.gguf +gufo extension install lfm3 ``` -Rootless Podman needs `crun` for `--group-add keep-groups`. Your host user must -have read/write access to `/dev/kfd` and `/dev/dri/renderD*`, usually through the -`render` and `video` groups; log out and back in after changing membership. -Container groups named `video`/`render` do not preserve host supplementary -groups. Check `id`, `ls -l /dev/kfd /dev/dri/renderD*`, and -`podman info --format '{{.Host.OCIRuntime.Name}}'` if ROCm reports no device. -See [Podman's rootless group-access guidance](https://github.com/containers/podman/blob/main/troubleshooting.md#20-passed-in-devices-or-files-cant-be-accessed-in-rootless-container). +[Extensions](docs/extensions.md) explains what that runs and how to trust it; +the [catalogue](https://gufo.blog/extensions) lists the official and community +extensions. -On Fedora or another SELinux-enforcing host, GPU enumeration can succeed while -SELinux blocks mapping `/dev/kfd`, causing ROCr to report a misleading -“Memory critical” error. Check the **host** audit log: +Qwen3.8 Flash-Next also supports experimental tensor parallelism across two +hosts over InfiniBand, RoCE v2 or USB4. It requires libibverbs and an optional +`-DGUFO_ENABLE_TP2_RDMA=ON` build; see the +[TP2 guide](docs/internal/models/qwen3.8-flash-next/TP2.md). -```sh -sudo ausearch -m avc -ts recent | grep -E '/dev/kfd|hsa_device_t' -``` - -If it shows a denied `map` for the container, Podman documents this fix: - -```sh -sudo setsebool -P container_use_devices true -``` -This persistently allows containers to access device labels for devices passed -into them; it affects all containers on that host. Review that policy scope -before enabling it. See [Podman's device documentation](https://docs.podman.io/en/latest/markdown/podman-run.1.html#device-host-device-container-device-permissions) -and the [SELinux container policy](https://github.com/containers/container-selinux/blob/main/container.te). +## Quickstart -Then, from another terminal, ask it something through the OpenAI-compatible API: +Download Qwen3.8 Flash-Next and its MTP head: ```sh -curl http://localhost:8080/v1/chat/completions \ - -H "Content-Type: application/json" \ - -d '{ - "model": "Qwen3.8-27B-UD-Q8_K_XL", - "messages": [{"role": "user", "content": "Say something"}] - }' +hf download unsloth/Qwen3.8-Flash-Next-GGUF \ + --revision d96201194f103c906994f283f504209dc8d2a10c \ + --include "UD-Q4_K_XL/*" \ + --include "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf" \ + --local-dir models/flash-next ``` -For Open WebUI, VS Code, OpenAI SDK and Responses-API clients (for example -Codex), set the API base URL to `http://localhost:8080/v1`. Chat Completions and -Responses support text, images, function tools, structured output and streaming. -See the [API contract](docs/SERVER.md). - -The text server uses the model's native context by default and generates until -EOS or the context is full. `--context N` sets context capacity per session; -`--max-tokens N` sets a default response limit that clients can override. -Reasoning tokens count toward that response limit. - -## Harness notes - -- **Qwen with Codex:** Codex sends developer messages mid-conversation, after - compaction or a settings change. Qwen's template accepts only one leading - system turn, so Gufo moves them there. The request that introduces one is - prefilled again; later requests reuse the cache. See the - [API contract](docs/SERVER.md). -- **Qwen with Claude Code:** not supported. Claude Code adds a system message - to `messages` on every turn, so Gufo moves a new one to the leading system - turn each time and every request prefills the whole history again (#522). - -## Build from source - -Production packages target Linux x86-64 on AMD Strix Halo (`gfx1151`). -Windows x86-64 is a supported native build target for development; see -[BUILD-WINDOWS.md](BUILD-WINDOWS.md). CMake owns -one production configuration for both Nix and ordinary Linux builds. Tests, -profilers, tuning executables and Python reference runners are not installed -with the production package. No `build.sh` wrapper is needed. - -### With Nix +Define `gufo` to run in the container, with the GPU and the models folder: ```sh -nix build -./result/bin/gufo diagnose -./result/bin/gufo serve llm --model /path/to/model.gguf -``` - -[flake.lock](flake.lock) pins the dependencies. `nix develop` adds profiling, -model-download and independent evaluation tools; these are not runtime -requirements. Optional benchmark baselines are selected separately with -`nix shell .#ds4-reference`, `.#llama-cpp-reference` or -`.#llama-cpp-mtp-reference`; see [benchmarking](docs/BENCHMARKS.md). -See [testing](docs/TESTING.md) for the small hosted CI suite and -explicit local quality checks. - -Prebuilt store paths are published to the `gufo` Cachix cache. The flake -declares it in `nixConfig`: users listed in `trusted-users` are asked to accept -it, or pass `--accept-flake-config`. Nix ignores it for other users; add it -system-wide with `cachix use gufo` or in `/etc/nix/nix.conf`: - -``` -extra-substituters = https://gufo.cachix.org -extra-trusted-public-keys = gufo.cachix.org-1:rfZe3n4lHINgyoACKzs5EthIZmBNvEyCCtufUpth0PE= +gufo() { + podman run --rm -it --network host \ + --userns=keep-id:uid=1000,gid=1000 --group-add keep-groups \ + --device /dev/kfd --device /dev/dri --ulimit memlock=-1 \ + -v ./models:/models:ro \ + -v gufo-extensions:/home/gufo/.local/share/gufo/extensions \ + ghcr.io/gufo-org/toolboxes/gufo-runtime:latest gufo "$@" +} ``` -The Nix package and development shell use ROCm 10.1.0 (HIP Clang 24) -from the pinned [nixpkgs ROCm 10.1 update](https://github.com/NixOS/nixpkgs/pull/573885). -Python, Python packages and general build dependencies come from the pinned -`nixos-unstable` input. The ROCm package set comes from the separate fork, -retaining its compiler/runtime dependencies to reuse the gfx1151 binaries on -`gufo.cachix.org`. All Nix workflows configure this cache explicitly. -Both include a [queue-memory patch](.devops/nix/patches/rocr-fixed-cwsr-rocm10.patch) -for Strix Halo. It keeps queue save/restore buffers, launch/copy arenas and -code-loading staging resident during host memory compaction, while retaining -managed-memory support and the ordinary fine-grained host-allocation policy. - -### Without Nix - -Install a C++20 compiler, CMake 3.21+, Ninja, pkg-config and the -following development libraries. The pinned Nix toolchain uses GCC -16.2 and ROCm 10.1.0 (HIP Clang 24). Attention and audio convolution kernels are compiled -directly from HIP. Python, Triton/AOTriton, Composable Kernel and MIOpen are -not production build or runtime requirements. -For the same protection against queue evictions as the Nix build, apply the -ROCr patch above when building your runtime. Flash-Next's host buffers also use -Linux long-term pins, with ordinary HIP registration retained when system -limits disallow those pins. Gufo leaves `HSA_USERPTR_FOR_PAGED_MEM` unchanged. - -| Dependency | Used for | -| --- | --- | -| ROCm HIP compiler/runtime, hipBLAS, hipBLASLt, rocBLAS | GPU execution and matrix multiplication | -| hipCUB, rocPRIM, rocWMMA headers | Compiled GPU kernels | -| ICU, libcurl, OpenSSL, libpng, libjpeg, libwebp | Tokenization, HTTPS, hashing and images | -| FFmpeg development libraries | Video embedding decoding and RGB conversion | -| libsndfile, libsoxr | Audio decoding and reference-compatible resampling | -| FFmpeg and ffprobe | Video/audio output; invoked as separate executables | - -Install ROCm using [AMD's Linux instructions](https://rocm.docs.amd.com/projects/install-on-linux/en/latest/). -Use the development packages for the libraries above. ROCm normally installs -under `/opt/rocm`. - -For example, on Debian/Ubuntu the ordinary system libraries are: +Serve the model, then ask it something from another terminal: ```sh -sudo apt install build-essential cmake ninja-build pkg-config \ - libicu-dev libcurl4-openssl-dev libssl-dev libpng-dev libjpeg-dev libwebp-dev libsndfile1-dev libsoxr-dev libavformat-dev libavcodec-dev libavutil-dev libswscale-dev ffmpeg - -# ROCm libraries from the table, named as AMD's repository ships them. -sudo apt install hipblas-dev hipblaslt-dev rocblas-dev \ - hipcub-dev rocprim-dev rocwmma-dev +gufo serve llm --served-model-name flash-next \ + --model /models/flash-next/UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf \ + --speculative mtp --mtp-model /models/flash-next/MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf -cmake --preset release -DCMAKE_INSTALL_PREFIX="$HOME/.local" -cmake --build --preset release --parallel 4 -./build/release/gufo diagnose -./build/release/gufo serve llm --model /path/to/model.gguf +curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" \ + -d '{"model": "flash-next", "messages": [{"role": "user", "content": "Say something"}]}' ``` -Configuring fails at `find_package(hipblas)` when those ROCm packages are -missing. Other distributions name them `-devel` instead of `-dev`. -For nonstandard installations, pass ordinary CMake paths, for example -`cmake --preset release -DCMAKE_PREFIX_PATH="/opt/rocm"`. -If compiler discovery picks a system Clang, also pass -`-DCMAKE_HIP_COMPILER=/opt/rocm/llvm/bin/clang++`. -Use `cmake --install build/release` to install Gufo, -its runtime data and license notices. The GPU driver must allow your user to -access `/dev/kfd` and `/dev/dri`; model weights are acquired separately. - -The same source, compiler flags and install rules serve both builds. Nix pins -the complete toolchain for reproducible comparisons; changing the compiler or -math libraries requires the affected model's quality checks. +Any OpenAI client works with the base URL `http://localhost:8080/v1`: Open +WebUI, the OpenAI SDKs, Codex and other agents. If the GPU isn't found, see +[troubleshooting](docs/troubleshooting.md#the-gpu-isnt-found). For the Debian +package, Nix, a source build or Windows, see [install](docs/install.md). + +## Documentation + +The documentation is on [gufo.blog/docs](https://gufo.blog/docs), one version +per release, and in [`docs/`](docs/README.md) for the development version. + +- **Get started:** [install](docs/install.md), [models](docs/models/README.md), + [command line](docs/cli.md), [server API](docs/server.md). +- **Run it well:** [cache](docs/cache.md), + [troubleshooting](docs/troubleshooting.md), [benchmarks](docs/benchmarks.md), + [versions](docs/versions.md). +- **Extend it:** [extensions](docs/extensions.md), + [writing an extension](docs/writing-extensions.md), + [extension API](docs/extension-api.md). + +The [changelog](CHANGELOG.md) and [releases](https://github.com/gufo-org/gufo/releases) +list what changed. + +## Principles + +- **One machine.** Every kernel is tuned for Strix Halo with 128 GiB. Smaller + memory configurations work for the models that fit. +- **The best model per use case.** Fewer models means less code to maintain and + more time to optimize and test each one. Each model keeps its own kernels, so + a change to one can't break another. +- **Quality before speed.** Every model has a quality report that compares it + with an independent reference; an optimization that changes the output isn't + one. +- **Real workloads.** Concurrent requests, cancellation and long conversations + are first-class, not afterthoughts. +- **Small production footprint.** Few runtime dependencies; development and + reference tools stay out of the package. + +## Contributing + +Contributions are welcome: Gufo needs the Strix Halo community to keep +improving. Start with [development](docs/internal/development.md) and +[testing](docs/internal/testing.md); [AGENTS.md](AGENTS.md) holds the rules +that people and coding agents follow. To add a model without changing Gufo, +[write an extension](docs/writing-extensions.md). + +Community projects built on Gufo include +[Gufo RDMA for Dual Strix Halo](https://github.com/neuhaus/gufo), which runs +models across two machines and isn't merged yet. ## License -Gufo's original code is [MIT licensed](LICENSE). Adapted code and dependencies -retain their own notices in [NOTICE](NOTICE), [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) -and `licenses/`, installed under `share/licenses/gufo`. Model weights are not -bundled and retain their publishers' terms. - -## Reference Projects - -The initial design is informed by the following open source projects: - -- [llama.cpp](https://github.com/ggml-org/llama.cpp) for compact model serving, GGUF, and CPU/GPU correctness paths. -- [LaurentZuijdwijk/llama.cpp](https://github.com/LaurentZuijdwijk/llama.cpp), [Nathanw1014/strix-halo-llamacpp](https://github.com/Nathanw1014/strix-halo-llamacpp), and [gaetan-puleo/llama-cpp-strix-halo](https://github.com/gaetan-puleo/llama-cpp-strix-halo) for Strix Halo optimization inspiration. -- [vLLM](https://github.com/vllm-project/vllm) for continuous batching and paged request scheduling. -- [hipEngine](https://github.com/shisa-ai/hipEngine) for torch-free HIP execution, and native speculative-cycle work. -- [ds4](https://github.com/antirez/ds4) for DeepSeek V4 Flash, MoE scheduling, and DSpark. -- [audio.cpp](https://github.com/0xShug0/audio.cpp) for audio models for tts and asr tasks. +Gufo's original code is [MIT licensed](LICENSE). Its design builds on other +open-source engines, listed in [reference projects](docs/reference-projects.md). Adapted code and dependencies +keep their own notices in [NOTICE](NOTICE), +[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and `licenses/`, installed +under `share/licenses/gufo`. Model weights aren't bundled and keep their +publishers' terms. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e23911e50b..5b0f01d099 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -19,15 +19,19 @@ Non-Nix builds must retain the notices of the versions they actually distribute. | hipCUB | Headers compiled into kernels | `BSD-3-Clause` | ROCm 7.2.3; flake.lock | [ROCm/hipCUB](https://github.com/ROCm/hipCUB) | | rocPRIM | Headers compiled into kernels | `MIT` | ROCm 7.2.3; flake.lock | [ROCm/rocm-libraries](https://github.com/ROCm/rocm-libraries) | | rocWMMA | Headers compiled into kernels | `MIT` | ROCm 7.2.3; flake.lock | [ROCm/rocWMMA](https://github.com/ROCm/rocWMMA) | +| rdma-core / libibverbs | Optional TP=2 RDMA adapter; dynamically linked | `GPL-2.0-only OR Linux-OpenIB` | 63.0; pinned nixpkgs | [linux-rdma/rdma-core](https://github.com/linux-rdma/rdma-core) | | Composable Kernel | Adapted short-attention arithmetic; no library/header dependency | `MIT` | ROCm 7.2.3; flake.lock | [ROCm/composable_kernel](https://github.com/ROCm/composable_kernel) | | ICU | Linked; Unicode normalization/tokenization | `Unicode-3.0` | 78.3; flake.lock | [unicode-org/icu](https://github.com/unicode-org/icu) | | curl / libcurl | Linked; image HTTPS and evaluation client | `curl` | 8.21.0; flake.lock | [curl/curl](https://github.com/curl/curl) | | OpenSSL | Linked; cryptographic hashes and HTTPS dependency | `Apache-2.0` | 3.6.3; flake.lock | [openssl/openssl](https://github.com/openssl/openssl) | -| libpng | Linked; image decoding | `libpng-2.0` | 1.6.58; flake.lock | [pnggroup/libpng](https://github.com/pnggroup/libpng) | +| libpng | Linked; Qwen-Image PNG input decoding and output encoding | `libpng-2.0` | 1.6.58; flake.lock | [pnggroup/libpng](https://github.com/pnggroup/libpng) | | libjpeg-turbo | Linked; JPEG decoding | `IJG AND BSD-3-Clause AND Zlib` | 3.1.4.1; flake.lock | [libjpeg-turbo](https://github.com/libjpeg-turbo/libjpeg-turbo) | | libwebp | Linked; WebP decoding | `BSD-3-Clause` | 1.6.0; flake.lock | [webmproject/libwebp](https://chromium.googlesource.com/webm/libwebp) | -| libsndfile | Linked; audio decoding | `LGPL-2.1-or-later` | 1.2.2; flake.lock | [libsndfile](https://github.com/libsndfile/libsndfile) | -| libsoxr | Linked; audio resampling | `LGPL-2.1-or-later` | 0.1.3; flake.lock | [SoX Resampler](https://sourceforge.net/projects/soxr/) | +| libopus | Linked; Ogg Opus audio decoding; [license text](licenses/libopus.txt) | `BSD-3-Clause` | 1.6.1; flake.lock | [xiph/opus](https://github.com/xiph/opus) | +| httparse (Rust crate) | Statically linked; HTTP request heads | `MIT OR Apache-2.0` | 1.10.1; Cargo.lock | [seanmonstar/httparse](https://github.com/seanmonstar/httparse) | +| png (Rust crate) | Statically linked; PNG decoding | `MIT OR Apache-2.0` | 0.18.1; Cargo.lock | [image-rs/image-png](https://github.com/image-rs/image-png) | +| symphonia (Rust crates) | Statically linked, unmodified; audio decoding; [license text and source](licenses/rust.txt) | `MPL-2.0` | 0.6.1; Cargo.lock | [pdeljanov/Symphonia](https://github.com/pdeljanov/Symphonia) | +| Rust standard library and crates | Statically linked into the Rust library; [license texts](licenses/rust.txt) | `MIT OR Apache-2.0` and per-crate terms | rustc in rust-toolchain.toml, with the crates its standard library bundles; crates in Cargo.lock | [rust-lang/rust](https://github.com/rust-lang/rust) | | FFmpeg | Linked libavformat/libavcodec/libavutil/libswscale for video embeddings; ffmpeg/ffprobe executables for media | `GPL-3.0-or-later` (Nix build with GPL/version3 components) | 9.0.2; flake.lock | [FFmpeg](https://github.com/FFmpeg/FFmpeg) | | LLVM OpenMP | Windows runtime built from upstream source; Microsoft-compatible DLL naming | `Apache-2.0 WITH LLVM-exception` | 18.1.8 (`3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff`) | [LLVM](https://github.com/llvm/llvm-project/tree/llvmorg-18.1.8/openmp); [license](licenses/llvm-openmp.txt) | | GNU C/C++/OpenMP runtimes | System runtime libraries; no Gufo source import | `LGPL-2.1-or-later AND (GPL-3.0-or-later WITH GCC-exception-3.1)` | glibc/GCC packages in flake.lock | [GNU](https://www.gnu.org/software/) | @@ -41,13 +45,16 @@ Non-Nix builds must retain the notices of the versions they actually distribute. Upstream license texts are retained in `licenses/` and [src/models/deepseek_v4_flash/LICENSE.ds4](src/models/deepseek_v4_flash/LICENSE.ds4). +The optional TP=2 adapter retains the rdma-core dual-license, GPL-2 and +OpenIB.org BSD texts and the libibverbs copyright notice under +`licenses/rdma-core/`. CMake installs these with `LICENSE`, `NOTICE` and this inventory under `share/licenses/gufo`. Preserve embedded copyright notices when modifying adapted code. Model-private changes and import boundaries are recorded in the [DS4 provenance](src/models/deepseek_v4_flash/UPSTREAM.md), [DS4 HIP import](src/models/deepseek_v4_flash/kernels/rocm/mmq/VENDOR.md), [Flash-Next HIP import](src/models/qwen38_flash_next/kernels/rocm/mmq/VENDOR.md) -and [H3 quality record](docs/models/minimax-h3/QUALITY.md). +and [H3 quality record](docs/internal/models/minimax-h3/QUALITY.md). This software is based in part on the work of the Independent JPEG Group. @@ -178,5 +185,5 @@ determination about a downstream operator. - **Relationship**: External model component within the operator-supplied H3 checkpoint; not distributed by gufo -See [the MiniMax H3 guide](docs/models/minimax-h3/README.md) for the acquisition, release, and +See [the MiniMax H3 guide](docs/models/minimax-h3.md) for the acquisition, release, and runtime boundary. diff --git a/cmake/Checks.cmake b/cmake/Checks.cmake index eee41f58ee..3835c9388a 100644 --- a/cmake/Checks.cmake +++ b/cmake/Checks.cmake @@ -13,19 +13,25 @@ set(gufo_pr_targets cache_streaming_test cache_tiered_test cache_retention_test + sched_policy_test extension_runtime_test extension_role_test - arg_parser_test transcribe_cli_test json_test json_constraint_test gguf_reader_test qwen_config_test + arg_parser_test transcribe_cli_test json_test json_constraint_test gguf_reader_test qwen_config_test qwen_draft_vocab_test gguf_identity_test + png_decode_test wav_decode_test audio_decode_test base64_test websocket_frame_test + http_request_test heap_placement_test + admission_memory_test platform_publish_test platform_prefault_test platform_mapped_file_test platform_fs_test platform_library_test logit_sampler_test ggml_dequant_test - quote_tracker_test logprobs_test sampling_test + quote_tracker_test logprobs_test sampling_test image_api_test openai_chat_test http_server_test http_server_signals_test trace_test audio_websocket_test - text_generation_scheduler_test - component_text_cache_test text_model_runner_test continuation_disk_store_test + text_generation_scheduler_test layered_prefill_conformance_test + component_text_cache_test text_model_runner_test legacy_text_model_runner_test continuation_cache_test continuation_disk_store_test bench_cli_test prompt_cli_test text_cli_dispatch_test eval_http_client_test + tp_control_test tp_disk_store_test tp_snapshot_gate_test + extension_diagnostics_test # BEGIN GENERATED MODEL PR TARGETS deepseek_v4_flash_continuation_identity_test ds4_chat_template_test ds4_cli_test ds4_sampling_test embedding_gemma2_batch_scheduler_test embedding_gemma2_config_test @@ -33,10 +39,11 @@ set(gufo_pr_targets embedding_gemma2_video_processor_test minimax_h3_runtime_test minimax_h3_sampling_test qwen27b_continuation_identity_test qwen27b_continuation_layout_test qwen38_flash_next_config_test qwen38_flash_next_continuation_identity_test qwen38_flash_next_continuation_layout_test - qwen38_flash_next_mtp_sampling_test qwen38_flash_next_rope_scaling_test - qwen38_flash_next_runner_options_test qwen3_asr_audio_api_test qwen3_asr_config_test - qwen3_tts_audio_api_test qwen3_tts_config_test qwen_chat_template_test qwen_image_21_test - qwen_image_21_weights_test qwen_tokenizer_test video_api_test + qwen38_flash_next_mtp_sampling_test qwen38_flash_next_probe_test qwen38_flash_next_rdma_gid_test + qwen38_flash_next_rope_scaling_test qwen38_flash_next_runner_options_test + qwen38_flash_next_tp_partition_test qwen3_asr_audio_api_test qwen3_asr_config_test + qwen3_tts_audio_api_test qwen3_tts_config_test qwen_chat_template_test qwen_image_21_lora_test + qwen_image_21_test qwen_image_21_weights_test qwen_tokenizer_test video_api_test # END GENERATED MODEL PR TARGETS ) set(gufo_pr_tests ${gufo_pr_targets}) @@ -49,16 +56,18 @@ endif() list(REMOVE_ITEM gufo_pr_tests ds4_chat_template_test ds4_cli_test ds4_sampling_test qwen38_flash_next_config_test qwen38_flash_next_continuation_layout_test qwen38_flash_next_mtp_sampling_test - qwen38_flash_next_rope_scaling_test qwen38_flash_next_runner_options_test) + qwen38_flash_next_probe_test qwen38_flash_next_rdma_gid_test qwen38_flash_next_rope_scaling_test + qwen38_flash_next_runner_options_test qwen38_flash_next_tp_partition_test) list(APPEND gufo_pr_tests "ds4\.template" "ds4\.cli" "ds4\.sampling" "qwen38_flash_next\.config" "qwen38_flash_next\.continuation_layout" "qwen38_flash_next\.mtp_sampling" - "qwen38_flash_next\.rope_scaling" "qwen38_flash_next\.runner_options") + "qwen38_flash_next\.probe" "qwen38_flash_next\.rdma_gid" "qwen38_flash_next\.rope_scaling" + "qwen38_flash_next\.runner_options" "qwen38_flash_next\.tp_partition") # END GENERATED MODEL CTEST OVERRIDES list(APPEND gufo_pr_tests gufo_version gufo_help serve_cli_test eval_http_test functional_runner_test cache_workloads_test cache_disk_faults_test - cache_boundary_test + cache_boundary_test sched_boundary_test kernel_resources_parser_test check_docs_test check_pr_title_test generate_infrastructure_test extension_distribution_test check_extension_isolation_test extension_isolation_report @@ -66,27 +75,40 @@ list(APPEND gufo_pr_tests extension_family_graph_gate extension_metadata_test check_target_graph_test extension_link_graph_gate extension_discovery_test extension_api_policy_test extension_api_surface - extension_cli_provenance_test) + extension_cli_provenance_test extension_module_cli_test) if (WIN32) # Linux-only hosted suites: RLIMIT_FSIZE and fork()-based tests, the # dup2/mmap/socket fixture tests, the permission-fault disk-store cases, # the cache tests that fork or wrap libc symbols, and the 1,250-chunk # per-file fsync stress in component_text_cache_test. set(gufo_pr_linux_only + # These control/disk fixtures use POSIX sockets and mkdtemp. + tp_control_test tp_disk_store_test continuation_disk_store_test gguf_reader_test gguf_identity_test platform_publish_test - platform_prefault_test trace_test http_server_signals_test - http_server_test audio_websocket_test continuation_disk_store_test + trace_test http_server_signals_test + http_server_test audio_websocket_test component_text_cache_test eval_http_client_test cache_disk_faults_test - cache_boundary_test cache_adapter_test cache_slot_test cache_disk_test + cache_boundary_test sched_boundary_test cache_adapter_test cache_slot_test + cache_disk_test cache_streaming_test cache_tiered_test cache_disk_publication_test) list(REMOVE_ITEM gufo_pr_targets ${gufo_pr_linux_only}) list(REMOVE_ITEM gufo_pr_tests ${gufo_pr_linux_only}) endif() +# Keep hosted tests within the runner's CPU budget. Nested compilation tests +# consume two slots each; ordinary contracts can fill the remaining slots. +include(ProcessorCount) +ProcessorCount(gufo_pr_jobs) +if(gufo_pr_jobs LESS 1) + set(gufo_pr_jobs 1) +elseif(gufo_pr_jobs GREATER 4) + set(gufo_pr_jobs 4) +endif() + list(JOIN gufo_pr_tests "|" gufo_pr_pattern) add_custom_target(check-pr COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure --no-tests=error - --timeout 180 -R "^(${gufo_pr_pattern})$" + --parallel ${gufo_pr_jobs} --timeout 180 -R "^(${gufo_pr_pattern})$" DEPENDS gufo ${gufo_pr_targets} $<$>:cache_disk_faults> USES_TERMINAL VERBATIM) diff --git a/cmake/CompilerCache.cmake b/cmake/CompilerCache.cmake new file mode 100644 index 0000000000..f8fff7c2d9 --- /dev/null +++ b/cmake/CompilerCache.cmake @@ -0,0 +1,18 @@ +# Shared by the application and standalone contract fixtures. +find_program(GUFO_CCACHE_PROGRAM NAMES ccache) +if (GUFO_CCACHE_PROGRAM) + set(CMAKE_C_COMPILER_LAUNCHER "${GUFO_CCACHE_PROGRAM}") + set(CMAKE_CXX_COMPILER_LAUNCHER "${GUFO_CCACHE_PROGRAM}") + # Newer CMake gives clang-cl gcc-style depfiles (-clang:-MD), which ccache + # rejects as unsupported; /showIncludes is cacheable. + if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + set(GUFO_CCACHE_CLANG_CL ON) + foreach(lang C CXX) + set(CMAKE_DEPFILE_FLAGS_${lang} "/showIncludes") + set(CMAKE_${lang}_DEPFILE_FORMAT msvc) + endforeach() + endif() + message(STATUS "gufo: compiling C and CXX through ${GUFO_CCACHE_PROGRAM}") +else() + message(STATUS "gufo: ccache not found, compiling without a launcher") +endif() diff --git a/cmake/GufoExtension.cmake b/cmake/GufoExtension.cmake index 7c559d0efc..10fc0e286f 100644 --- a/cmake/GufoExtension.cmake +++ b/cmake/GufoExtension.cmake @@ -480,6 +480,23 @@ function(gufo_extension_target) return() endif() get_property(role GLOBAL PROPERTY "GUFO_EXT_TARGET_${ARG_NAME}_ROLE") + get_property(owner GLOBAL PROPERTY "GUFO_EXT_TARGET_${ARG_NAME}_OWNER") + # A loadable module resolves the host services from the gufo executable, so + # its libraries take only the usage requirements of the link contracts. + # Tests remain executables and still link every implementation they list. + set(as_module FALSE) + if(owner IN_LIST GUFO_EXTENSION_MODULES AND NOT role STREQUAL test) + set(as_module TRUE) + set(links) + foreach(dependency IN LISTS ARG_LINK_LIBRARIES) + if(dependency MATCHES "^(gufo_ext_runtime|gufo_ext_core|gufo_ext_cache|gufo_ext_hip)$") + list(APPEND links "$") + else() + list(APPEND links "${dependency}") + endif() + endforeach() + set(ARG_LINK_LIBRARIES "${links}") + endif() if(DEFINED GUFO_EXTENSION_BUILD_ROOT) set(sources) foreach(source IN LISTS ARG_SOURCES) @@ -493,8 +510,20 @@ function(gufo_extension_target) else() add_library(${ARG_NAME} STATIC ${ARG_SOURCES}) endif() - get_property(owner GLOBAL PROPERTY "GUFO_EXT_TARGET_${ARG_NAME}_OWNER") + if(as_module) + set_target_properties(${ARG_NAME} PROPERTIES POSITION_INDEPENDENT_CODE ON) + endif() get_property(is_external GLOBAL PROPERTY "GUFO_EXT_${owner}_IS_EXTERNAL") + # A manifest module is global once any selected extension declares it; an + # extension that links it must declare it too, or it builds only beside one. + get_property(package_modules GLOBAL PROPERTY GUFO_EXT_PKG_CONFIG_MODULES) + get_property(declared_modules GLOBAL PROPERTY "GUFO_EXT_${owner}_PKG_CONFIG") + foreach(dependency IN LISTS ARG_LINK_LIBRARIES) + if(dependency MATCHES "^PkgConfig::(.+)$" AND CMAKE_MATCH_1 IN_LIST package_modules + AND NOT CMAKE_MATCH_1 IN_LIST declared_modules) + message(FATAL_ERROR "extension target ${ARG_NAME} links ${dependency}, which extension ${owner} does not declare in packages") + endif() + endforeach() if(is_external) target_include_directories(${ARG_NAME} BEFORE PRIVATE "${GUFO_EXTENSION_BUILD_ROOT}") target_include_directories(${ARG_NAME} SYSTEM PRIVATE "${PROJECT_SOURCE_DIR}/include") @@ -640,11 +669,158 @@ function(_gufo_provider_constant out json index enabled reason) set(${out} "{.id=\"${id}\", .capability=Capability::${capability_${capability}}, .keys=${keys}, .model_ids=${model_ids}, .speculative=${speculative}, .options=${option_values}, .available=${available}, .unavailable_reason=\"${reason}\", .extension=\"\"}" PARENT_SCOPE) endfunction() +# Record the source revision of an external extension: the commit of its Git +# work tree and whether that tree has uncommitted changes, else the revision +# declared for its directory (a trailing "-dirty" marks uncommitted changes), +# else "unknown". Configure reruns when the work tree's HEAD or index changes. +function(_gufo_extension_source_revision name root declared) + set(revision "unknown") + set(dirty false) + find_package(Git QUIET) + if(Git_FOUND) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${root}" ls-files --error-unmatch extension.json + RESULT_VARIABLE untracked OUTPUT_QUIET ERROR_QUIET) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${root}" rev-parse --verify HEAD + RESULT_VARIABLE no_commit OUTPUT_VARIABLE commit ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(untracked EQUAL 0 AND no_commit EQUAL 0 AND commit MATCHES "^[0-9a-f]+$") + set(revision "${commit}") + execute_process(COMMAND "${GIT_EXECUTABLE}" --no-optional-locks -C "${root}" status --porcelain + RESULT_VARIABLE failed OUTPUT_VARIABLE changes ERROR_QUIET) + if(NOT failed EQUAL 0 OR NOT "${changes}" STREQUAL "") + set(dirty true) + endif() + set(tracked HEAD index packed-refs logs/HEAD) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${root}" symbolic-ref -q HEAD + RESULT_VARIABLE detached OUTPUT_VARIABLE branch ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + if(detached EQUAL 0) + list(APPEND tracked "${branch}") + endif() + foreach(file IN LISTS tracked) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${root}" rev-parse --git-path "${file}" + RESULT_VARIABLE failed OUTPUT_VARIABLE path ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + get_filename_component(path "${path}" ABSOLUTE BASE_DIR "${root}") + # A missing dependency would rerun configure on every build. + if(failed EQUAL 0 AND EXISTS "${path}" AND NOT IS_DIRECTORY "${path}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${path}") + endif() + endforeach() + endif() + endif() + if(revision STREQUAL "unknown" AND NOT "${declared}" STREQUAL "") + if(declared MATCHES "^(.+)-dirty$") + set(revision "${CMAKE_MATCH_1}") + set(dirty true) + else() + set(revision "${declared}") + endif() + endif() + set_property(GLOBAL PROPERTY "GUFO_EXT_${name}_REVISION" "${revision}") + set_property(GLOBAL PROPERTY "GUFO_EXT_${name}_DIRTY" "${dirty}") +endfunction() + +# The C++ initializer of an extension's ExtensionInfo. Only an external +# extension records a revision. +function(_gufo_extension_info_cpp out name version source_cpp) + set(info "{\"${name}\", \"${version}\", ${source_cpp}") + get_property(revision GLOBAL PROPERTY "GUFO_EXT_${name}_REVISION") + if(NOT "${revision}" STREQUAL "") + get_property(dirty GLOBAL PROPERTY "GUFO_EXT_${name}_DIRTY") + # A declared revision is free text, such as a tag name. + string(REPLACE "\\" "\\\\" revision "${revision}") + string(REPLACE "\"" "\\\"" revision "${revision}") + string(APPEND info ", \"${revision}\", ${dirty}") + endif() + set(${out} "${info}}" PARENT_SCOPE) +endfunction() + +# Append one extension's registration to generated declarations and body, and +# link its enabled targets into the registering target. A non-empty source +# expression replaces the recorded source directory, for runtime-loaded modules. +function(_gufo_extension_registration out_declarations out_body target name directory source_expression) + set(declarations "${${out_declarations}}") + set(body "${${out_body}}") + get_property(json GLOBAL PROPERTY "GUFO_EXT_${name}_JSON") + get_property(root GLOBAL PROPERTY "GUFO_EXT_${name}_ROOT") + get_property(targets GLOBAL PROPERTY "GUFO_EXT_${name}_TARGETS") + foreach(library IN LISTS targets) + get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${library}_ENABLED") + get_property(created GLOBAL PROPERTY "GUFO_EXT_TARGET_${library}_CREATED") + if(NOT created) + message(FATAL_ERROR "registry: declared target ${library} was not defined by gufo_extension_target") + endif() + if(enabled AND NOT TARGET ${library}) + message(FATAL_ERROR "registry: missing enabled target ${library}") + endif() + endforeach() + _gufo_optional(kind "${json}" kind extension) + if(kind STREQUAL library) + _gufo_json(version "${json}" STRING version) + file(RELATIVE_PATH source "${PROJECT_SOURCE_DIR}" "${root}") + _gufo_extension_info_cpp(info "${name}" "${version}" "\"${source}\"") + string(APPEND body " registry.BeginExtension(${info});\n") + set(${out_declarations} "${declarations}" PARENT_SCOPE) + set(${out_body} "${body}" PARENT_SCOPE) + return() + endif() + _gufo_json(entry "${json}" STRING entry) + _gufo_json(registration_target "${json}" STRING registration_target) + _gufo_json(version "${json}" STRING version) + get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${registration_target}_ENABLED") + if(NOT enabled) + message(FATAL_ERROR "registry: extension ${name} is not supported on this platform") + endif() + file(RELATIVE_PATH source "${PROJECT_SOURCE_DIR}" "${root}") + string(REPLACE "\\" "/" source "${source}") + string(REPLACE "\"" "\\\"" source "${source}") + if(NOT "${source_expression}" STREQUAL "") + set(info "{\"${name}\", \"${version}\", ${source_expression}}") + else() + _gufo_extension_info_cpp(info "${name}" "${version}" "\"${source}\"") + endif() + string(APPEND declarations "#include \nvoid ${entry}(gufo::ext::Registry&);\n") + string(APPEND body " registry.BeginExtension(${info});\n ::${entry}(registry);\n") + target_link_libraries(${target} PRIVATE ${registration_target}) + set(constants "// Generated. Do not edit.\n#pragma once\n#include \nnamespace gufo::ext::generated::extension_${name} {\n") + string(JSON count LENGTH "${json}" providers) + math(EXPR last "${count}-1") + foreach(i RANGE ${last}) + _gufo_json(provider_target "${json}" STRING providers ${i} target) + _gufo_json(provider_entry "${json}" STRING providers ${i} entry) + _gufo_json(id "${json}" STRING providers ${i} id) + string(REPLACE "-" "_" identifier "${id}") + get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${provider_target}_ENABLED") + get_property(requires GLOBAL PROPERTY "GUFO_EXT_TARGET_${provider_target}_REQUIRES") + if(enabled) + set(reason "") + else() + string(JOIN ", " conditions ${requires}) + set(reason "requires ${conditions}") + endif() + _gufo_provider_constant(value "${json}" ${i} "${enabled}" "${reason}") + string(APPEND constants "inline const ProviderInfo kProvider_${identifier} = ${value};\n") + if(enabled) + string(APPEND declarations "void ${provider_entry}(gufo::ext::Registry&);\n") + string(APPEND body " ::${provider_entry}(registry);\n") + target_link_libraries(${target} PRIVATE ${provider_target}) + else() + string(APPEND body " registry.AddProvider(gufo::ext::generated::extension_${name}::kProvider_${identifier});\n") + endif() + target_include_directories(${registration_target} PRIVATE "${directory}") + if(enabled) + target_include_directories(${provider_target} PRIVATE "${directory}") + endif() + endforeach() + string(APPEND constants "}\n") + _gufo_write_if_different("${directory}/gufo/ext/generated/${name}_constants.hpp" "${constants}") + set(${out_declarations} "${declarations}" PARENT_SCOPE) + set(${out_body} "${body}" PARENT_SCOPE) +endfunction() + # Generate a registry per executable. No process-global constructors or implicit # whole-archive links are used. The provider entry lives with its actual factory; # an unavailable provider produces metadata only and no declaration/reference. function(gufo_target_extensions target) - cmake_parse_arguments(ARG "" "" "EXTENSIONS" ${ARGN}) + cmake_parse_arguments(ARG "LOAD_MODULES" "" "EXTENSIONS" ${ARGN}) if(NOT TARGET ${target} OR NOT "${ARG_UNPARSED_ARGUMENTS}" STREQUAL "") message(FATAL_ERROR "gufo_target_extensions requires an existing target") endif() @@ -670,71 +846,14 @@ function(gufo_target_extensions target) if(NOT name IN_LIST ARG_EXTENSIONS) continue() endif() - get_property(json GLOBAL PROPERTY "GUFO_EXT_${name}_JSON") - get_property(root GLOBAL PROPERTY "GUFO_EXT_${name}_ROOT") - get_property(targets GLOBAL PROPERTY "GUFO_EXT_${name}_TARGETS") - foreach(library IN LISTS targets) - get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${library}_ENABLED") - get_property(created GLOBAL PROPERTY "GUFO_EXT_TARGET_${library}_CREATED") - if(NOT created) - message(FATAL_ERROR "registry: declared target ${library} was not defined by gufo_extension_target") - endif() - if(enabled AND NOT TARGET ${library}) - message(FATAL_ERROR "registry: missing enabled target ${library}") - endif() - endforeach() - _gufo_optional(kind "${json}" kind extension) - if(kind STREQUAL library) - _gufo_json(version "${json}" STRING version) - file(RELATIVE_PATH source "${PROJECT_SOURCE_DIR}" "${root}") - string(APPEND body " registry.BeginExtension({\"${name}\", \"${version}\", \"${source}\"});\n") - continue() - endif() - _gufo_json(entry "${json}" STRING entry) - _gufo_json(registration_target "${json}" STRING registration_target) - _gufo_json(version "${json}" STRING version) - get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${registration_target}_ENABLED") - if(NOT enabled) - message(FATAL_ERROR "registry: extension ${name} is not supported on this platform") + if(ARG_LOAD_MODULES) + # An installed module may replace this built-in extension. + set(extension_body "") + _gufo_extension_registration(declarations extension_body ${target} ${name} "${directory}" "") + string(APPEND body " if (!gufo::ext::ExtensionModuleShadows(\"${name}\")) {\n${extension_body} }\n") + else() + _gufo_extension_registration(declarations body ${target} ${name} "${directory}" "") endif() - file(RELATIVE_PATH source "${PROJECT_SOURCE_DIR}" "${root}") - string(REPLACE "\\" "/" source "${source}") - string(REPLACE "\"" "\\\"" source "${source}") - string(APPEND declarations "#include \nvoid ${entry}(gufo::ext::Registry&);\n") - string(APPEND body " registry.BeginExtension({\"${name}\", \"${version}\", \"${source}\"});\n ::${entry}(registry);\n") - target_link_libraries(${target} PRIVATE ${registration_target}) - set(constants "// Generated. Do not edit.\n#pragma once\n#include \nnamespace gufo::ext::generated::extension_${name} {\n") - string(JSON count LENGTH "${json}" providers) - math(EXPR last "${count}-1") - foreach(i RANGE ${last}) - _gufo_json(provider_target "${json}" STRING providers ${i} target) - _gufo_json(provider_entry "${json}" STRING providers ${i} entry) - _gufo_json(id "${json}" STRING providers ${i} id) - string(REPLACE "-" "_" identifier "${id}") - get_property(enabled GLOBAL PROPERTY "GUFO_EXT_TARGET_${provider_target}_ENABLED") - get_property(requires GLOBAL PROPERTY "GUFO_EXT_TARGET_${provider_target}_REQUIRES") - if(enabled) - set(reason "") - else() - string(JOIN ", " conditions ${requires}) - set(reason "requires ${conditions}") - endif() - _gufo_provider_constant(value "${json}" ${i} "${enabled}" "${reason}") - string(APPEND constants "inline const ProviderInfo kProvider_${identifier} = ${value};\n") - if(enabled) - string(APPEND declarations "void ${provider_entry}(gufo::ext::Registry&);\n") - string(APPEND body " ::${provider_entry}(registry);\n") - target_link_libraries(${target} PRIVATE ${provider_target}) - else() - string(APPEND body " registry.AddProvider(gufo::ext::generated::extension_${name}::kProvider_${identifier});\n") - endif() - target_include_directories(${registration_target} PRIVATE "${directory}") - if(enabled) - target_include_directories(${provider_target} PRIVATE "${directory}") - endif() - endforeach() - string(APPEND constants "}\n") - _gufo_write_if_different("${directory}/gufo/ext/generated/${name}_constants.hpp" "${constants}") endforeach() get_property(mode GLOBAL PROPERTY GUFO_EXTENSION_SELECTION_MODE) if("${mode}" STREQUAL "") @@ -751,11 +870,119 @@ function(gufo_target_extensions target) _gufo_extension_values(values "${json}" "${field}") _gufo_cpp_strings(${field} ${values}) endforeach() - string(APPEND body " registry.AddExcluded({{\"${name}\", \"${version}\", \"${source}\"}, ${keys}, ${model_ids}, ${options}, \"${reason}\"});\n") + _gufo_extension_info_cpp(info "${name}" "${version}" "\"${source}\"") + string(APPEND body " registry.AddExcluded({${info}, ${keys}, ${model_ids}, ${options}, \"${reason}\"});\n") endforeach() + if(ARG_LOAD_MODULES) + # The executable defines the loader; it registers modules after built-ins. + string(APPEND declarations "namespace gufo::ext {\nbool ExtensionModuleShadows(std::string_view name);\nvoid RegisterExtensionModules(Registry& registry);\n}\n") + string(APPEND body " gufo::ext::RegisterExtensionModules(registry);\n") + endif() string(APPEND body "}\nstd::string_view gufo::ext::ExtensionSelectionMode() { return \"${mode}\"; }\n") _gufo_write_if_different("${directory}/extension_registry.cpp" "${declarations}\n${body}") target_sources(${target} PRIVATE "${directory}/extension_registry.cpp") target_include_directories(${target} PRIVATE "${directory}") target_link_libraries(${target} PRIVATE gufo_ext_runtime) endfunction() + +# Identity of everything a loadable module shares with its host: the audited +# source surface, the API version, toolchain, ROCm and global compile flags. +# A module loads only into an executable with the same identity. +function(gufo_extension_build_id out) + get_property(id GLOBAL PROPERTY GUFO_EXTENSION_BUILD_ID) + if(NOT id) + include(${CMAKE_CURRENT_FUNCTION_LIST_DIR}/GufoExtensionVersion.cmake) + set(material "api=${GUFO_EXTENSION_API_VERSION}\n") + file(STRINGS "${PROJECT_SOURCE_DIR}/include/gufo/ext/SURFACE" headers REGEX "^[^#].+") + # The SDK keeps the private surface headers under its public include. + if(NOT DEFINED GUFO_SURFACE_SOURCE_ROOT) + set(GUFO_SURFACE_SOURCE_ROOT "${PROJECT_SOURCE_DIR}") + endif() + foreach(header IN LISTS headers) + if(header MATCHES "^include/") + file(SHA256 "${PROJECT_SOURCE_DIR}/${header}" digest) + else() + file(SHA256 "${GUFO_SURFACE_SOURCE_ROOT}/${header}" digest) + endif() + string(APPEND material "${header}=${digest}\n") + endforeach() + string(TOUPPER "${CMAKE_BUILD_TYPE}" config) + set(variables CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PROCESSOR CMAKE_BUILD_TYPE + CMAKE_CXX_COMPILER CMAKE_CXX_COMPILER_ID CMAKE_CXX_COMPILER_VERSION + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_${config} ENGINE_ENABLE_HIP + GUFO_ENABLE_SANITIZERS) + if(ENGINE_ENABLE_HIP) + list(APPEND variables CMAKE_HIP_COMPILER CMAKE_HIP_COMPILER_VERSION + CMAKE_HIP_FLAGS CMAKE_HIP_FLAGS_${config} CMAKE_HIP_ARCHITECTURES + hip_VERSION) + endif() + foreach(variable IN LISTS variables) + string(APPEND material "${variable}=${${variable}}\n") + endforeach() + string(SHA256 id "${material}") + file(WRITE "${CMAKE_BINARY_DIR}/extension-build-id.txt" "${id}\n${material}") + set_property(GLOBAL PROPERTY GUFO_EXTENSION_BUILD_ID "${id}") + endif() + set(${out} "${id}" PARENT_SCOPE) +endfunction() + +# Build each listed extension as a loadable module. The module exports a build +# identity, its manifest and a registration entry; the host services resolve +# from the loading gufo executable, never from a copy inside the module. +function(gufo_extension_modules) + cmake_parse_arguments(ARG "" "" "EXTENSIONS" ${ARGN}) + if(NOT "${ARG_UNPARSED_ARGUMENTS}" STREQUAL "") + message(FATAL_ERROR "gufo_extension_modules: unexpected arguments ${ARG_UNPARSED_ARGUMENTS}") + endif() + # On Windows a module imports the host services from the executable's + # import library: the `gufo` target in a source tree, the SDK's copy there. + if(ARG_EXTENSIONS AND WIN32 AND NOT GUFO_EXTENSION_MODULE_HOST) + message(FATAL_ERROR "gufo_extension_modules: set GUFO_EXTENSION_MODULE_HOST to the host import library target") + endif() + gufo_extensions_validate() + get_property(selected GLOBAL PROPERTY GUFO_SELECTED_EXTENSIONS) + gufo_extension_build_id(build_id) + foreach(name IN LISTS ARG_EXTENSIONS) + if(NOT name IN_LIST selected) + message(FATAL_ERROR "GUFO_EXTENSION_MODULES: ${name} is not a selected extension") + endif() + get_property(json GLOBAL PROPERTY "GUFO_EXT_${name}_JSON") + get_property(depends GLOBAL PROPERTY "GUFO_EXT_${name}_DEPENDS") + _gufo_optional(kind "${json}" kind extension) + if(kind STREQUAL library OR depends) + message(FATAL_ERROR "GUFO_EXTENSION_MODULES: ${name} has extension dependencies or is a library; modules support standalone extensions only") + endif() + set(target "gufo_ext_module_${name}") + add_library(${target} MODULE) + set(directory "${CMAKE_CURRENT_BINARY_DIR}/extensions/${target}") + file(MAKE_DIRECTORY "${directory}/gufo/ext/generated") + set(declarations "// Generated. Do not edit.\n#include \n") + set(body "") + _gufo_extension_registration(declarations body ${target} ${name} "${directory}" "source") + set(delimiter "gufo_manifest") + string(FIND "${json}" ")${delimiter}\"" collision) + if(NOT collision EQUAL -1) + message(FATAL_ERROR "GUFO_EXTENSION_MODULES: ${name} manifest contains the raw string delimiter") + endif() + if(WIN32) + set(exported "extern \"C\" __declspec(dllexport)") + else() + set(exported "extern \"C\" __attribute__((visibility(\"default\")))") + endif() + string(APPEND declarations "\n${exported} const char* gufo_ext_module_build_id_v1() {\n return \"${build_id}\";\n}\n") + string(APPEND declarations "${exported} const char* gufo_ext_module_manifest_v1() {\n return R\"${delimiter}(${json})${delimiter}\";\n}\n") + string(APPEND declarations "${exported} void gufo_ext_module_register_v1(gufo::ext::Registry* host, const char* source) {\n gufo::ext::Registry& registry = *host;\n${body}}\n") + _gufo_write_if_different("${directory}/module.cpp" "${declarations}") + target_sources(${target} PRIVATE "${directory}/module.cpp") + target_include_directories(${target} PRIVATE "${directory}") + target_link_libraries(${target} PRIVATE $) + if(WIN32) + target_link_libraries(${target} PRIVATE ${GUFO_EXTENSION_MODULE_HOST}) + endif() + target_compile_features(${target} PRIVATE cxx_std_20) + set_target_properties(${target} PROPERTIES + PREFIX "" + OUTPUT_NAME "gufo-ext-${name}" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/extension-modules") + endforeach() +endfunction() diff --git a/cmake/GufoExtensionDiscovery.cmake b/cmake/GufoExtensionDiscovery.cmake index f8f2d12824..4b7eead103 100644 --- a/cmake/GufoExtensionDiscovery.cmake +++ b/cmake/GufoExtensionDiscovery.cmake @@ -6,6 +6,8 @@ include(${CMAKE_CURRENT_LIST_DIR}/GufoExtension.cmake) set(GUFO_EXTENSIONS "*" CACHE STRING "Exact extension list, or * for all supported discovered extensions") option(GUFO_EXTENSIONS_FROM_LOCK "Select official extensions.lock instead of discovery" OFF) set(GUFO_EXTENSION_DIRS "" CACHE STRING "Semicolon-separated list of external extension root directories") +set(GUFO_EXTENSION_DIR_REVISIONS "" CACHE STRING "One source revision per GUFO_EXTENSION_DIRS entry, in the same order, for directories without Git metadata; 'unknown' for none") +set(GUFO_EXTENSION_MODULES "" CACHE STRING "Selected extensions built as loadable modules instead of linked into gufo") function(_gufo_extension_lock out path) if(NOT EXISTS "${path}") @@ -36,22 +38,37 @@ function(gufo_discover_extensions) "${PROJECT_SOURCE_DIR}/src/models/*/extension.json" "${PROJECT_SOURCE_DIR}/src/families/*/*/extension.json") if(GUFO_EXTENSION_DIRS) + list(LENGTH GUFO_EXTENSION_DIRS dir_count) + list(LENGTH GUFO_EXTENSION_DIR_REVISIONS revision_count) + if(revision_count GREATER 0 AND NOT revision_count EQUAL dir_count) + message(FATAL_ERROR "GUFO_EXTENSION_DIR_REVISIONS needs one entry per GUFO_EXTENSION_DIRS entry (${dir_count}), got ${revision_count}") + endif() + set(dir_index 0) foreach(ext_dir IN LISTS GUFO_EXTENSION_DIRS) + set(declared "") + if(revision_count GREATER 0) + list(GET GUFO_EXTENSION_DIR_REVISIONS ${dir_index} declared) + endif() + math(EXPR dir_index "${dir_index}+1") if(NOT IS_ABSOLUTE "${ext_dir}") get_filename_component(ext_dir "${ext_dir}" ABSOLUTE BASE_DIR "${PROJECT_SOURCE_DIR}") endif() if(EXISTS "${ext_dir}/extension.json") list(APPEND manifests "${ext_dir}/extension.json") set_property(GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_${ext_dir}" TRUE) + set_property(GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_REVISION_${ext_dir}" "${declared}") else() file(GLOB sub_manifests CONFIGURE_DEPENDS "${ext_dir}/*/extension.json") foreach(sub_m IN LISTS sub_manifests) cmake_path(GET sub_m PARENT_PATH sub_root) set_property(GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_${sub_root}" TRUE) + set_property(GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_REVISION_${sub_root}" "${declared}") list(APPEND manifests "${sub_m}") endforeach() endif() endforeach() + elseif(GUFO_EXTENSION_DIR_REVISIONS) + message(FATAL_ERROR "GUFO_EXTENSION_DIR_REVISIONS requires GUFO_EXTENSION_DIRS") endif() list(REMOVE_DUPLICATES manifests) list(SORT manifests) @@ -69,6 +86,8 @@ function(gufo_discover_extensions) get_property(is_ext_dir GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_${root}") if(is_ext_dir OR NOT "${root}" MATCHES "^${PROJECT_SOURCE_DIR}/") set_property(GLOBAL PROPERTY "GUFO_EXT_${name}_IS_EXTERNAL" TRUE) + get_property(declared GLOBAL PROPERTY "GUFO_EXT_EXTERNAL_DIR_REVISION_${root}") + _gufo_extension_source_revision("${name}" "${root}" "${declared}") endif() set(has_cmake FALSE) if(EXISTS "${root}/extension.cmake") @@ -171,7 +190,7 @@ function(gufo_discover_extensions) message(STATUS "gufo: unshipped discovered extension ${name}") endif() get_property(json GLOBAL PROPERTY "GUFO_EXT_${name}_JSON") - foreach(field keys model_ids options) + foreach(field keys model_ids) _gufo_extension_values(values "${json}" "${field}") foreach(value IN LISTS values) string(SHA256 key "${field}:${value}") @@ -184,8 +203,10 @@ function(gufo_discover_extensions) # the diagnostic names the extension that actually holds the value. Two # extensions in the same tier may share an artifact key: overlapping keys # are resolved by probes later. Provider IDs and entry symbols may not - # collide (GufoExtension.cmake) and option types may not disagree - # (Registry::AddProvider); both fail elsewhere, not here. + # collide (GufoExtension.cmake); that fails elsewhere, not here. Options + # are absent because any extensions may share one name with one type, + # such as a draft model path; GufoExtension.cmake and + # Registry::AddProvider reject disagreeing types. get_property(other_owner GLOBAL PROPERTY "GUFO_DISCOVERY_${key}_${other}") if(other_owner) message(FATAL_ERROR "gufo: shipped/unshipped ${field} collision '${value}' (${other_owner}, ${name})") @@ -246,7 +267,7 @@ endfunction() function(_gufo_external_items out tgt) set(items) foreach(item IN LISTS ARGN) - if(item MATCHES "^\\$<(BUILD_INTERFACE|LINK_ONLY):(.*)>$") + if(item MATCHES "^\\$<(BUILD_INTERFACE|LINK_ONLY|COMPILE_ONLY):(.*)>$") _gufo_external_items(nested "${tgt}" "${CMAKE_MATCH_2}") list(APPEND items ${nested}) elseif(item MATCHES "^\\$<\\$<(CONFIG|COMPILE_LANGUAGE|COMPILE_LANG_AND_ID|PLATFORM_ID|CXX_COMPILER_ID):[^<>]+>:(.*)>$") @@ -338,6 +359,8 @@ function(_gufo_validate_external_target tgt) gufo_cli gufo_compare gufo_bench gufo_diagnostics gufo_runtime_storage gufo_prompt_cache gufo_audio_cache gufo_tool_calls gufo_kernel_bench_support) + # Audited link contracts: their closure reaches private targets by design. + set(public_link_targets gufo_ext_core gufo_ext_cache gufo_ext_hip) get_target_property(directory "${tgt}" SOURCE_DIR) set(base "${CMAKE_BINARY_DIR}") _gufo_external_property("${tgt}" "${tgt}" INCLUDE_DIRECTORIES paths) @@ -414,6 +437,9 @@ function(_gufo_validate_external_target tgt) set(current "${alias}") endif() endif() + if(current IN_LIST public_link_targets) + continue() + endif() if(current IN_LIST prohibited_private_targets) message(FATAL_ERROR "external extension target ${tgt} violates allowlist: links prohibited target '${current}'") endif() @@ -471,6 +497,40 @@ endfunction() function(gufo_build_discovered_extensions) get_property(selected GLOBAL PROPERTY GUFO_SELECTED_EXTENSIONS) + # Only selected extensions require their `packages[].pkg_config` modules. + # Each becomes the global imported target PkgConfig::, with the + # _* variables pkg_check_modules sets, before any extension builds. + # Its non-cached results (_LINK_LIBRARIES) reach the extension + # directories because they are added from this same function scope. + foreach(name IN LISTS selected) + get_property(json GLOBAL PROPERTY "GUFO_EXT_${name}_JSON") + _gufo_optional(packages "${json}" packages "[]") + string(JSON count LENGTH "${packages}") + if(count EQUAL 0) + continue() + endif() + math(EXPR last "${count}-1") + foreach(i RANGE ${last}) + string(JSON module ERROR_VARIABLE absent GET "${packages}" ${i} pkg_config) + if(absent) + continue() + endif() + # A leading '-' would reach pkg-config as an option. + _gufo_identifier("${module}" "^[A-Za-z0-9_][A-Za-z0-9_.+-]*$" "pkg-config module") + set_property(GLOBAL APPEND PROPERTY "GUFO_EXT_${name}_PKG_CONFIG" "${module}") + set_property(GLOBAL APPEND PROPERTY GUFO_EXT_PKG_CONFIG_MODULES "${module}") + if(TARGET PkgConfig::${module}) + continue() + endif() + if(NOT PKG_CONFIG_FOUND) + find_package(PkgConfig REQUIRED) + endif() + pkg_check_modules(${module} IMPORTED_TARGET GLOBAL ${module}) + if(NOT ${module}_FOUND) + message(FATAL_ERROR "extension ${name} requires pkg-config module ${module}") + endif() + endforeach() + endforeach() foreach(name IN LISTS selected) get_property(root GLOBAL PROPERTY "GUFO_EXT_${name}_ROOT") if(NOT EXISTS "${root}/extension.cmake") diff --git a/cmake/GufoExtensionHost.cmake b/cmake/GufoExtensionHost.cmake new file mode 100644 index 0000000000..c6509cb69c --- /dev/null +++ b/cmake/GufoExtensionHost.cmake @@ -0,0 +1,57 @@ +# The gufo executable as the host of extension modules: modules resolve the +# public extension services from it, never from a copy of their own. +include_guard(GLOBAL) + +function(gufo_extension_host target) + # Keep every object of the libraries behind the public extension surface, + # including ones no built-in extension uses. + set(libraries gufo_ext_runtime gufo_logging gufo_platform gufo_core gufo_cache) + if(ENGINE_ENABLE_HIP) + list(APPEND libraries gufo_cache_hip gufo_hip_host) + endif() + set(archives) + foreach(library IN LISTS libraries) + list(APPEND archives "$") + endforeach() + add_dependencies(${target} ${libraries}) + if(WIN32) + # Windows resolves a DLL's imports through the executable's import + # library. Export Gufo's own symbols from the host archives (MSVC names + # carry their namespace as `@gufo@@`), data with DATA, through a .def file. + set_target_properties(${target} PROPERTIES ENABLE_EXPORTS ON) + get_filename_component(compiler_dir "${CMAKE_CXX_COMPILER}" DIRECTORY) + find_program(GUFO_LLVM_NM NAMES llvm-nm HINTS "${compiler_dir}" REQUIRED) + set(definition "${CMAKE_CURRENT_BINARY_DIR}/${target}-exports.def") + string(JOIN "|" archive_list ${archives}) + add_custom_command(OUTPUT "${definition}" + COMMAND "${CMAKE_COMMAND}" "-DNM=${GUFO_LLVM_NM}" "-DOUTPUT=${definition}" + "-DARCHIVES=${archive_list}" + -P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/GufoWindowsExports.cmake" + DEPENDS ${libraries} "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/GufoWindowsExports.cmake" + COMMENT "Exporting Gufo symbols for extension modules" + VERBATIM) + add_custom_target(${target}_exports DEPENDS "${definition}") + add_dependencies(${target} ${target}_exports) + target_link_options(${target} PRIVATE "LINKER:/DEF:${definition}") + set_property(TARGET ${target} APPEND PROPERTY LINK_DEPENDS "${definition}") + foreach(archive IN LISTS archives) + target_link_options(${target} PRIVATE "LINKER:/WHOLEARCHIVE:${archive}") + endforeach() + return() + endif() + # Export Gufo's own C++ symbols, with the typeinfo, vtables and guards that + # keep classes and inline statics unified, but no vendored or third-party + # code. Mangled-name globs: quoted demangled patterns match only literally. + set(list "${CMAKE_CURRENT_BINARY_DIR}/${target}-exports.list") + set(patterns + _ZN4gufo* _ZNK4gufo* _ZNR4gufo* _ZNO4gufo* _ZNKR4gufo* _ZNKO4gufo* + _ZTIN4gufo* _ZTSN4gufo* _ZTVN4gufo* _ZTTN4gufo* _ZTCN4gufo* + _ZGVN4gufo* _ZGVZN4gufo* _ZGVZNK4gufo* _ZZN4gufo* _ZZNK4gufo* + _ZTh*N4gufo* _ZTv*N4gufo* _ZTHN4gufo* _ZTWN4gufo*) + list(JOIN patterns ";\n " lines) + file(WRITE "${list}" "{\n ${lines};\n};\n") + target_link_options(${target} PRIVATE "LINKER:--dynamic-list=${list}") + set_property(TARGET ${target} APPEND PROPERTY LINK_DEPENDS "${list}") + target_link_options(${target} PRIVATE "LINKER:--whole-archive" ${archives} + "LINKER:--no-whole-archive") +endfunction() diff --git a/cmake/GufoExtensionSdk.cmake b/cmake/GufoExtensionSdk.cmake new file mode 100644 index 0000000000..a3ec45aa56 --- /dev/null +++ b/cmake/GufoExtensionSdk.cmake @@ -0,0 +1,188 @@ +# The extension SDK: what `gufo extension install` needs to build a module for +# this exact gufo build, without its source tree. It is staged in the build +# tree (`/sdk`) and installed beside the executable +# (`/lib/gufo/sdk`). +include_guard(GLOBAL) + +# Plain copies: configure_file would add each source as a configure dependency +# under a second spelling of paths the extension scripts already depend on. +function(_gufo_sdk_copy source destination) + get_filename_component(directory "${destination}" DIRECTORY) + file(MAKE_DIRECTORY "${directory}") + file(COPY_FILE "${source}" "${destination}" ONLY_IF_DIFFERENT) +endfunction() + +function(_gufo_sdk_cache out) + set(text "") + foreach(variable IN LISTS ARGN) + string(REPLACE "\\" "\\\\" value "${${variable}}") + string(REPLACE "\"" "\\\"" value "${value}") + string(APPEND text "set(${variable} \"${value}\" CACHE STRING \"\" FORCE)\n") + endforeach() + set(${out} "${text}" PARENT_SCOPE) +endfunction() + +# Stage the SDK for the executable `target`. Call after HIP and the extension +# build identity are configured. +function(gufo_extension_sdk target) + set(sdk "${CMAKE_BINARY_DIR}/sdk") + set(root "${PROJECT_SOURCE_DIR}") + _gufo_sdk_copy("${root}/cmake/sdk/CMakeLists.txt" "${sdk}/CMakeLists.txt") + foreach(file GufoExtension.cmake GufoExtensionDiscovery.cmake + GufoExtensionVersion.cmake GufoExtensionVersion.hpp.in) + _gufo_sdk_copy("${root}/cmake/${file}" "${sdk}/cmake/${file}") + endforeach() + # Official selection is fixed in the host; modules are never part of it. + file(WRITE "${sdk}/extensions.lock" "{\"schema\": 1, \"extensions\": []}\n") + _gufo_sdk_copy("${root}/src/core/hip/libstdcxx_noinline.hpp" + "${sdk}/support/libstdcxx_noinline.hpp") + file(GLOB_RECURSE api_files RELATIVE "${root}" + "${root}/include/gufo/ext/*") + set(staged) + foreach(file IN LISTS api_files) + _gufo_sdk_copy("${root}/${file}" "${sdk}/${file}") + list(APPEND staged "${sdk}/${file}") + endforeach() + file(STRINGS "${root}/include/gufo/ext/SURFACE" headers REGEX "^[^#].+") + foreach(header IN LISTS headers) + if(NOT header MATCHES "^include/") + _gufo_sdk_copy("${root}/${header}" "${sdk}/public-include/${header}") + list(APPEND staged "${sdk}/public-include/${header}") + endif() + endforeach() + # A removed API header must not stay reachable in a reused build tree. + file(GLOB_RECURSE previous LIST_DIRECTORIES FALSE "${sdk}/include/*" "${sdk}/public-include/*") + foreach(file IN LISTS previous) + if(NOT file IN_LIST staged) + file(REMOVE "${file}") + endif() + endforeach() + + gufo_extension_build_id(build_id) + string(TOUPPER "${CMAKE_BUILD_TYPE}" config) + set(GUFO_SDK_BUILD_ID "${build_id}") + # Nix's CMake searches NIXPKGS_CMAKE_PREFIX_PATH instead of the usual list. + set(prefix_path ${CMAKE_PREFIX_PATH} $ENV{CMAKE_PREFIX_PATH} + $ENV{NIXPKGS_CMAKE_PREFIX_PATH}) + if(NOT WIN32) + string(REPLACE ":" ";" prefix_path "${prefix_path}") + endif() + list(REMOVE_DUPLICATES prefix_path) + set(CMAKE_PREFIX_PATH "${prefix_path}") + set(GUFO_SDK_PKG_CONFIG_PATH "$ENV{PKG_CONFIG_PATH}") + set(GUFO_SDK_HIP_DEVICE_LIB_PATH "$ENV{HIP_DEVICE_LIB_PATH}") + set(variables GUFO_SDK_BUILD_ID GUFO_SDK_PKG_CONFIG_PATH + GUFO_SDK_HIP_DEVICE_LIB_PATH CMAKE_PREFIX_PATH CMAKE_BUILD_TYPE + CMAKE_C_COMPILER CMAKE_CXX_COMPILER CMAKE_C_FLAGS CMAKE_C_FLAGS_${config} + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_${config} ENGINE_ENABLE_HIP + GUFO_ENABLE_WARNINGS GUFO_ENABLE_SANITIZERS) + if(ENGINE_ENABLE_HIP) + list(APPEND variables CMAKE_HIP_COMPILER CMAKE_HIP_FLAGS + CMAKE_HIP_FLAGS_${config} CMAKE_HIP_ARCHITECTURES CMAKE_HIP_COMPILER_ROCM_ROOT) + endif() + # Pin the dependencies the host found, so the SDK resolves the same ones + # outside the environment that configured gufo. + set(dependencies) + get_cmake_property(cache_variables CACHE_VARIABLES) + foreach(variable IN LISTS cache_variables) + if(variable MATCHES "^[A-Za-z0-9_-]+_DIR$" AND NOT variable MATCHES "^(CMAKE|gufo|GUFO)_" + OR variable MATCHES "^(ICU|OPENSSL|PNG|JPEG|ZLIB|CURL|HIPCUB|ROCPRIM|ROCWMMA)_(INCLUDE_DIR|LIBRARY|.*_LIBRARY|.*_LIBRARY_RELEASE|LIBRARY_RELEASE)$" + OR variable MATCHES "^(VCPKG_|OpenMP_)") + get_property(type CACHE "${variable}" PROPERTY TYPE) + if(NOT type STREQUAL "INTERNAL" AND NOT "${${variable}}" MATCHES "-NOTFOUND$") + list(APPEND variables "${variable}") + foreach(item IN LISTS ${variable}) + if(IS_ABSOLUTE "${item}") + list(APPEND dependencies "${item}") + endif() + endforeach() + endif() + endif() + endforeach() + # A toolchain file (vcpkg's on Windows) stays where the build found it. + foreach(variable CMAKE_TOOLCHAIN_FILE CMAKE_MSVC_RUNTIME_LIBRARY + CMAKE_MSVC_DEBUG_INFORMATION_FORMAT CMAKE_POLICY_DEFAULT_CMP0141) + if(DEFINED ${variable} AND NOT "${${variable}}" STREQUAL "") + list(APPEND variables ${variable}) + endif() + endforeach() + if(CMAKE_TOOLCHAIN_FILE) + list(APPEND dependencies "${CMAKE_TOOLCHAIN_FILE}") + endif() + _gufo_sdk_cache(profile ${variables}) + file(WRITE "${sdk}/profile.cmake" + "# Generated. The build profile of the gufo executable this SDK belongs to.\n${profile}") + + # What `gufo extension` checks and runs before configuring a module. + string(JSON sdk_json SET "{}" schema 1) + string(JSON sdk_json SET "${sdk_json}" build_id "\"${build_id}\"") + foreach(field cmake generator make_program hip_device_lib_path) + if(field STREQUAL cmake) + set(value "${CMAKE_COMMAND}") + elseif(field STREQUAL generator) + set(value "${CMAKE_GENERATOR}") + elseif(field STREQUAL make_program) + set(value "${CMAKE_MAKE_PROGRAM}") + else() + set(value "${GUFO_SDK_HIP_DEVICE_LIB_PATH}") + endif() + string(REPLACE "\\" "/" value "${value}") + string(JSON sdk_json SET "${sdk_json}" ${field} "\"${value}\"") + endforeach() + string(JSON sdk_json SET "${sdk_json}" compilers "{}") + foreach(tool c:CMAKE_C_COMPILER cxx:CMAKE_CXX_COMPILER hip:CMAKE_HIP_COMPILER) + string(REPLACE ":" ";" pair "${tool}") + list(GET pair 0 key) + list(GET pair 1 variable) + if(DEFINED ${variable} AND NOT "${${variable}}" STREQUAL "") + string(REPLACE "\\" "/" value "${${variable}}") + string(JSON sdk_json SET "${sdk_json}" compilers ${key} "\"${value}\"") + endif() + endforeach() + # The environment a toolchain wrapper reads (Nix's hipClang and cc-wrapper + # take their ROCm and library paths from it). `gufo extension` exports each + # one that is unset when it runs the SDK. + string(JSON sdk_json SET "${sdk_json}" environment "{}") + execute_process(COMMAND "${CMAKE_COMMAND}" -E environment + OUTPUT_VARIABLE environment_text) + string(REGEX MATCHALL "(^|\n)[A-Za-z_][A-Za-z0-9_]*=" names "${environment_text}") + set(environment) + foreach(name IN LISTS names) + string(REGEX REPLACE "^\n?([^=]+)=$" "\\1" name "${name}") + if(name MATCHES "^(HIP_PATH|HSA_PATH|ROCM_PATH|HIP_PLATFORM|HIP_CLANG_PATH|HIP_DEVICE_LIB_PATH|PKG_CONFIG_PATH|NIXPKGS_CMAKE_PREFIX_PATH|NIX_CFLAGS_COMPILE|NIX_LDFLAGS|NIX_HARDENING_ENABLE|NIX_ENFORCE_NO_NATIVE|NIX_(CC|BINTOOLS|PKG_CONFIG)_WRAPPER_TARGET_HOST_.*)$") + list(APPEND environment "${name}") + endif() + endforeach() + foreach(variable IN LISTS environment) + if(DEFINED ENV{${variable}}) + set(value "$ENV{${variable}}") + string(REPLACE "\\" "/" value "${value}") + string(REPLACE "\"" "\\\"" value "${value}") + string(JSON sdk_json SET "${sdk_json}" environment ${variable} "\"${value}\"") + endif() + endforeach() + # Paths the profile pins; `gufo extension install` checks they still exist. + string(JSON sdk_json SET "${sdk_json}" dependencies "[]") + set(index 0) + foreach(dependency IN LISTS dependencies) + string(REPLACE "\\" "/" dependency "${dependency}") + string(JSON sdk_json SET "${sdk_json}" dependencies ${index} "\"${dependency}\"") + math(EXPR index "${index}+1") + endforeach() + file(WRITE "${sdk}/sdk.json" "${sdk_json}\n") + _gufo_sdk_copy("${CMAKE_BINARY_DIR}/extension-build-id.txt" + "${sdk}/extension-build-id.txt") + + # Packages that split the SDK from the runtime install it elsewhere and point + # gufo at it with GUFO_SDK_DIR. + set(GUFO_SDK_INSTALL_DIR lib/gufo/sdk CACHE STRING "Extension SDK install directory") + if(WIN32) + # Modules link the executable's import library. + add_custom_command(TARGET ${target} POST_BUILD + COMMAND "${CMAKE_COMMAND}" -E make_directory "${sdk}/lib" + COMMAND "${CMAKE_COMMAND}" -E copy_if_different + "$" "${sdk}/lib/$" + VERBATIM) + endif() + install(DIRECTORY "${sdk}/" DESTINATION "${GUFO_SDK_INSTALL_DIR}") +endfunction() diff --git a/cmake/GufoWindowsExports.cmake b/cmake/GufoWindowsExports.cmake new file mode 100644 index 0000000000..b9225f4272 --- /dev/null +++ b/cmake/GufoWindowsExports.cmake @@ -0,0 +1,44 @@ +# cmake -DNM= -DOUTPUT= -DARCHIVES= -P +# Writes the exports of Gufo's own symbols (MSVC names containing `@gufo@@`). +string(REPLACE "|" ";" archives "${ARCHIVES}") +set(functions) +set(data) +foreach(archive IN LISTS archives) + execute_process(COMMAND "${NM}" --defined-only --extern-only --format=posix + --no-sort "${archive}" + OUTPUT_VARIABLE symbols RESULT_VARIABLE result ERROR_VARIABLE error) + if(result) + message(FATAL_ERROR "llvm-nm ${archive} failed: ${error}") + endif() + string(REPLACE ";" "\;" symbols "${symbols}") + string(REGEX MATCHALL "[^\n]*@gufo@@[^\n]*" lines "${symbols}") + foreach(line IN LISTS lines) + if(line MATCHES "^([^ ]+) ([A-Za-z]) ") + set(name "${CMAKE_MATCH_1}") + set(type "${CMAKE_MATCH_2}") + if(type MATCHES "^[TW]$") + list(APPEND functions "${name}") + elseif(type MATCHES "^[DBRV]$") + list(APPEND data "${name}") + endif() + endif() + endforeach() +endforeach() +list(REMOVE_DUPLICATES functions) +list(REMOVE_DUPLICATES data) +list(REMOVE_ITEM functions ${data}) +list(LENGTH functions function_count) +list(LENGTH data data_count) +math(EXPR total "${function_count}+${data_count}") +if(total GREATER 65535) + message(FATAL_ERROR "${total} Gufo symbols exceed the Windows limit of 65535 exports") +endif() +set(text "EXPORTS\n") +foreach(name IN LISTS functions) + string(APPEND text " ${name}\n") +endforeach() +foreach(name IN LISTS data) + string(APPEND text " ${name} DATA\n") +endforeach() +file(WRITE "${OUTPUT}" "${text}") +message(STATUS "Exported ${function_count} functions and ${data_count} data symbols") diff --git a/cmake/TargetGraph.cmake b/cmake/TargetGraph.cmake index dd4c15925d..785edac256 100644 --- a/cmake/TargetGraph.cmake +++ b/cmake/TargetGraph.cmake @@ -13,17 +13,24 @@ set(GUFO_LINK_GRAPH_PROTECTED gufo_cache gufo_cache_hip gufo_core - gufo_ext_runtime) + gufo_ext_runtime + gufo_ext_core + gufo_ext_cache + gufo_ext_hip) set(GUFO_LINK_GRAPH_FORBIDDEN gufo_serving gufo_http) # Link items that name a system library rather than a project target. The -# platform leaf's own list joins it, so a new OS library stays classified. +# platform leaf's and the Rust library's own lists join it, so a new OS +# library stays classified. set(GUFO_LINK_GRAPH_SYSTEM_LIBS dl m pthread rt atomic stdc++ gcc_s ws2_32 iphlpapi bcrypt advapi32) if (DEFINED GUFO_PLATFORM_LIBS) list(APPEND GUFO_LINK_GRAPH_SYSTEM_LIBS ${GUFO_PLATFORM_LIBS}) endif() +if (DEFINED GUFO_RUST_LIBS) + list(APPEND GUFO_LINK_GRAPH_SYSTEM_LIBS ${GUFO_RUST_LIBS}) +endif() list(REMOVE_DUPLICATES GUFO_LINK_GRAPH_SYSTEM_LIBS) # One INTERFACE_LINK_LIBRARIES entry per line, with the generated-expression @@ -56,8 +63,13 @@ function(gufo_link_graph_entry TARGET OUT) elseif("${item}" MATCHES "^\\$<(LINK_ONLY|BUILD_INTERFACE):([^>]+)>$") # CMAKE_MATCH_ is only valid after the enclosing if() finished, so the # target test goes in its own command. - if(TARGET "${CMAKE_MATCH_2}") - list(APPEND entries "${CMAKE_MATCH_2}") + set(unwrapped "${CMAKE_MATCH_2}") + if(TARGET "${unwrapped}") + list(APPEND entries "${unwrapped}") + elseif(IS_ABSOLUTE "${unwrapped}" OR "${unwrapped}" MATCHES "^-" OR + "${unwrapped}" IN_LIST GUFO_LINK_GRAPH_SYSTEM_LIBS) + # Static PRIVATE links wrap legitimate system libraries too. Apply + # the same classification as plain items without hiding target edges. else() message(FATAL_ERROR "Link graph: unclassified interface item '${item}' on ${TARGET}") endif() diff --git a/cmake/sdk/CMakeLists.txt b/cmake/sdk/CMakeLists.txt new file mode 100644 index 0000000000..4b6581066e --- /dev/null +++ b/cmake/sdk/CMakeLists.txt @@ -0,0 +1,137 @@ +# Gufo extension SDK: builds extensions as modules for the one gufo build that +# installed this SDK. `gufo extension install` drives it: +# +# cmake -S -B -C /profile.cmake \ +# -DGUFO_EXTENSION_DIRS= -DGUFO_EXTENSION_MODULES= +# +# The profile pins the host's compilers, flags and dependency prefixes; the +# configure step fails when the resulting build identity differs from the +# host's, before anything is compiled. +cmake_minimum_required(VERSION 3.27) +if(NOT DEFINED GUFO_SDK_BUILD_ID) + message(FATAL_ERROR "configure the Gufo extension SDK with -C /profile.cmake") +endif() +project(gufo_extension_module LANGUAGES C CXX) +if(WIN32) + add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN PSAPI_VERSION=2) +endif() +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS ON) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(BUILD_TESTING OFF CACHE BOOL "Extension tests build with a Gufo checkout" FORCE) +if(GUFO_SDK_PKG_CONFIG_PATH) + set(ENV{PKG_CONFIG_PATH} "${GUFO_SDK_PKG_CONFIG_PATH}") +endif() +# Linux libstdc++ must be parsed before HIP defines its __noinline__ macro. +if(NOT WIN32) + add_compile_options( + "$<$:SHELL:-include \"${CMAKE_CURRENT_LIST_DIR}/support/libstdcxx_noinline.hpp\">") +endif() + +# The dependencies the gufo build offers extensions. Only the toolchain and the +# libraries behind the public link contracts are required. +find_package(Threads REQUIRED) +find_package(ICU REQUIRED COMPONENTS uc i18n) +find_package(OpenSSL REQUIRED COMPONENTS Crypto) +foreach(package CURL PNG JPEG ZLIB OpenMP) + find_package(${package} QUIET) +endforeach() +# Extension-only libraries come from each extension's manifest `packages`. +find_package(PkgConfig QUIET) +if(PkgConfig_FOUND) + pkg_check_modules(WEBP QUIET IMPORTED_TARGET libwebp) +endif() + +include(${CMAKE_CURRENT_LIST_DIR}/cmake/GufoExtensionDiscovery.cmake) +gufo_discover_extensions() +if(EXISTS /opt/rocm) + list(APPEND CMAKE_SYSTEM_PREFIX_PATH /opt/rocm) +endif() +if(ENGINE_ENABLE_HIP) + enable_language(HIP) + if(WIN32) + string(REPLACE "/Fo" "-o " CMAKE_HIP_COMPILE_OBJECT + "${CMAKE_HIP_COMPILE_OBJECT}") + endif() + find_package(hip REQUIRED) + find_package(hipblas REQUIRED) + find_package(hipblaslt REQUIRED) + find_package(rocblas REQUIRED) + find_package(rocm-core CONFIG QUIET) + find_path(HIPCUB_INCLUDE_DIR hipcub/hipcub.hpp REQUIRED) + find_path(ROCPRIM_INCLUDE_DIR rocprim/rocprim.hpp REQUIRED) + find_path(ROCWMMA_INCLUDE_DIR rocwmma/rocwmma.hpp REQUIRED) + # Outside a development shell nothing exports the device library path. + if(GUFO_SDK_HIP_DEVICE_LIB_PATH AND NOT DEFINED ENV{HIP_DEVICE_LIB_PATH}) + add_compile_options( + "$<$:--rocm-device-lib-path=${GUFO_SDK_HIP_DEVICE_LIB_PATH}>") + endif() +endif() +if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + # As in the gufo build: lld-link skips the clang-cl runtime selection. + execute_process(COMMAND "${CMAKE_CXX_COMPILER}" /clang:-print-runtime-dir + OUTPUT_VARIABLE clang_rt_dir OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) + if(EXISTS "${clang_rt_dir}/clang_rt.builtins-x86_64.lib") + add_link_options("${clang_rt_dir}/clang_rt.builtins-x86_64.lib") + endif() +endif() +if(GUFO_ENABLE_WARNINGS) + if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + add_compile_options(/W4) + elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_compile_options(-Wall -Wextra -Wpedantic) + endif() +endif() +if(GUFO_ENABLE_SANITIZERS AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer) + add_link_options(-fsanitize=address,undefined) +endif() + +# The public link contracts carry headers only: the loading gufo executable +# supplies every implementation. +set(generated "${CMAKE_CURRENT_BINARY_DIR}/generated") +include(${CMAKE_CURRENT_LIST_DIR}/cmake/GufoExtensionVersion.cmake) +configure_file("${CMAKE_CURRENT_LIST_DIR}/cmake/GufoExtensionVersion.hpp.in" + "${generated}/gufo/ext/detail/api_version.hpp" @ONLY) +add_library(gufo_ext_runtime INTERFACE) +target_include_directories(gufo_ext_runtime INTERFACE + "${CMAKE_CURRENT_LIST_DIR}/include" "${CMAKE_CURRENT_LIST_DIR}/public-include" + "${generated}") +target_compile_features(gufo_ext_runtime INTERFACE cxx_std_20) +# `sha256.hpp` in the runtime surface exposes OpenSSL types. +target_link_libraries(gufo_ext_runtime INTERFACE $) +add_library(gufo_ext_core INTERFACE) +target_link_libraries(gufo_ext_core INTERFACE OpenSSL::Crypto) +add_library(gufo_ext_cache INTERFACE) +if(ENGINE_ENABLE_HIP) + add_library(gufo_ext_hip INTERFACE) + target_compile_definitions(gufo_ext_hip INTERFACE ENGINE_ENABLE_HIP=1) + target_include_directories(gufo_ext_hip SYSTEM INTERFACE + ${HIPCUB_INCLUDE_DIR} ${ROCPRIM_INCLUDE_DIR}) + # `hip_utils.hpp` in the public surface includes hipBLAS. + target_link_libraries(gufo_ext_hip INTERFACE hip::host roc::hipblas) +endif() + +if(WIN32) + # Windows modules import the host services from gufo's import library. + add_library(gufo_host_import UNKNOWN IMPORTED) + set_target_properties(gufo_host_import PROPERTIES + IMPORTED_LOCATION "${CMAKE_CURRENT_LIST_DIR}/lib/gufo.lib") + set(GUFO_EXTENSION_MODULE_HOST gufo_host_import) +endif() +if(NOT GUFO_EXTENSION_MODULES) + message(FATAL_ERROR "GUFO_EXTENSION_MODULES names the extensions to build") +endif() +set(GUFO_SURFACE_SOURCE_ROOT "${CMAKE_CURRENT_LIST_DIR}/public-include") +gufo_extension_build_id(build_id) +if(NOT build_id STREQUAL GUFO_SDK_BUILD_ID) + message(FATAL_ERROR "this toolchain does not match the gufo build that " + "installed this SDK: build identity ${build_id}, gufo ${GUFO_SDK_BUILD_ID}. " + "Compare ${CMAKE_BINARY_DIR}/extension-build-id.txt with " + "${CMAKE_CURRENT_LIST_DIR}/extension-build-id.txt.") +endif() +gufo_build_discovered_extensions() +gufo_extension_modules(EXTENSIONS ${GUFO_EXTENSION_MODULES}) diff --git a/docs/AGENTS.md b/docs/AGENTS.md new file mode 100644 index 0000000000..54031398e0 --- /dev/null +++ b/docs/AGENTS.md @@ -0,0 +1,117 @@ +# Documentation + +These rules apply to everything under `docs/`. They keep the documentation +short, consistent and readable by people and agents alike. + +## Layout + +| Path | Audience | Published | +| --- | --- | --- | +| `docs/*.md`, `docs/models/*.md` | People using or extending Gufo | Website, one copy per release | +| `docs/figures/` | Figures for public pages | Website, with the pages | +| `docs/internal/` | Contributors and agents working on Gufo | Repository only | +| `docs/internal/models//` | Implementation notes (`README.md`), benchmarks, quality and experiment evidence | Repository only | +| `docs/internal/server.md`, `docs/internal/cache.md` | Complete server and cache references behind the public pages | Repository only | +| `docs/internal/design/` | Design RFCs | Repository only | + +A public page explains how to use something. An internal page explains how it +is built, measured or changed. When a page needs both, split it: the public +page links to the internal one. + +Every public page starts with a `# Title` line, a blank line and a one- or +two-sentence summary; the website uses both for the page title and +description. [`README.md`](README.md) is the documentation home: it lists every +public page in reading order, and the website builds its navigation from it. +Model pages are listed in [`models/README.md`](models/README.md) instead. + +## Style + +Write like the [Gufo blog](https://gufo.blog/blog): plain, direct and exact. + +- Address the reader as "you". Use the active voice. Contractions are fine. +- Prefer plain words to jargon. When a term is needed, put it in **bold** and + define it the first time it appears on the page. Use one name for one concept + across all pages. +- Lead with what the reader does or gets; follow with why only when the reader + needs it to decide something. +- Give numbers exactly, with units, and date measurements: "As of November + 2026, ...". Link the evidence under `docs/internal/` instead of repeating it. +- Use tables only to compare things across the same columns. Use a numbered list + only when order matters. +- Mark warnings (trust, exposure, data loss) with a blockquote starting with + `**Warning:**`. +- Use plain Markdown that renders on GitHub: no MDX, HTML components or + scripts. Code blocks name their language. + +## Concision + +Every sentence must earn its place; a reader should find the answer without +reading the whole page. + +- One topic per page. One fact lives in one place; elsewhere, link to it. +- Budgets: 250 lines for a public page, 120 for a model page. Over budget means + split the page or move detail to `docs/internal/`. +- Public pages hold current behavior only: no history ("used to", "now", + "recently"), no PR or issue numbers, no design rationale. Rationale belongs in + `docs/internal/design/`. +- Don't list every flag or field; show the ones a reader needs and point to + `gufo --help` for the rest. +- Cut filler: "simply", "just", "easily", "basically", "obviously", "note + that", "it is worth", "seamless", "blazing". + +## Keeping docs current + +- A change in user-visible behavior updates the page that owns it in the same + pull request. +- A new public page needs a maintainer's agreement; prefer extending an + existing page. +- Evidence files (JSON, logs, archives, charts) live only under + `docs/internal/`. +- Run `python3 tools/ci/check-docs.py` after editing. It enforces the title and + summary, the index listing, line budgets, filler words, issue numbers on + public pages and the figure rules below. + +## Figures + +Figures are static SVG files in `docs/figures/`, named after what they show +(`cache-reuse.svg`). They render as images on GitHub and are inlined on the +website, where they pick up its fonts. Copy +[`figures/cache-reuse.svg`](figures/cache-reuse.svg) as a starting point. + +Add a figure only when it shows a structure or flow faster than prose: what +sits where, what happens in which order, what is reused. The prose must still +say everything the figure says, because agents read the text, not the +picture. + +Reference a figure as an image followed by an italic caption line: + +```md +![The second request restores the shared prefix and prefills only its new turn.](figures/cache-reuse.svg) + +*Figure 1. A repeated prefix is restored, not recomputed.* +``` + +The alt text describes what the figure shows in one sentence; the caption +states its point. + +Each SVG must: + +- set `width` and `height` equal to its `viewBox` size, 760 wide, and draw + `` as its first shape so it reads on both light + and dark GitHub themes; +- embed [`figures/style.css`](figures/style.css) verbatim in its ` + + + + + + + +Request 1 + +system prompt + conversation +prefilled +computed from scratch + + +state kept in the cache + +Request 2 + +same prefix +restored, not recomputed + +new turn +prefilled +The second request pays only for the tokens it adds. + diff --git a/docs/figures/style.css b/docs/figures/style.css new file mode 100644 index 0000000000..62dd477290 --- /dev/null +++ b/docs/figures/style.css @@ -0,0 +1,22 @@ +/* Canonical figure style. Every SVG under docs/ embeds this block verbatim + inside its style element; tools/ci/check-docs.py compares it. Colors match the + website (gufo.blog) tokens and the blog figure palette. Fonts read the + site's variables when the SVG is inlined there and fall back to system + fonts inside a GitHub image. */ +.fig-bg { fill: #eceee6; stroke: #c0c5b8; stroke-width: 1; } +.fig-panel { fill: #f7f8f3; stroke: #c0c5b8; stroke-width: 1; } +.fig-head { font: 10.5px var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); letter-spacing: 0.06em; text-transform: uppercase; fill: #737a72; } +.fig-title { font: 11px var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); fill: #141714; } +.fig-sub { font: italic 10.5px var(--font-sans, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif); fill: #545a54; } +.fig-note { font: italic 11px var(--font-sans, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif); fill: #3a3f3a; } +.fig-flow { fill: none; stroke: #545a54; stroke-width: 1.2; stroke-opacity: 0.6; } +.fig-dash { fill: none; stroke: #545a54; stroke-width: 1.2; stroke-dasharray: 5 3; } +.fig-arrowhead { fill: #545a54; } +.fig-box { stroke-width: 1.4; } +.fig-green { fill: #e8efea; stroke: #3f7a4f; } +.fig-blue { fill: #eaf0f6; stroke: #4f86b8; } +.fig-teal { fill: #e8f1f1; stroke: #3d8a8a; } +.fig-amber { fill: #f8efe6; stroke: #c27a2c; } +.fig-plum { fill: #f3ebf1; stroke: #9a5c8a; } +.fig-rose { fill: #f6e7ed; stroke: #b8336a; } +.fig-muted { fill: #e2e5db; stroke: #c0c5b8; } diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 0000000000..d37c2551ab --- /dev/null +++ b/docs/install.md @@ -0,0 +1,129 @@ +# Install + +Gufo runs on Linux x86-64 with an AMD Strix Halo GPU (`gfx1151`). This page +covers the container, the Debian package, Nix, a build from source and the +Windows ZIP. + +## Prepare the host + +Gufo needs a recent kernel and firmware, and access to the GPU devices: + +```sh +sudo usermod -aG video,render "$USER" # then log out and back in +ls -l /dev/kfd /dev/dri/renderD* +``` + +As of November 2026, use Linux 6.18.4 or newer and linux-firmware 20260110 or +newer. The [host configuration guide](https://github.com/gufo-org/toolboxes/blob/main/docs/host-configuration.md) +lists the kernel parameters and known bad versions. After installing, run +`gufo diagnose` to check the setup; [troubleshooting](troubleshooting.md) +explains its findings. + +## Container + +The `gufo-runtime` image holds Gufo and everything it needs. Use `latest` for +the newest release, `X.Y.Z` to pin one, or `edge` to follow development. + +```sh +podman pull ghcr.io/gufo-org/toolboxes/gufo-runtime:latest +podman run --rm \ + --userns=keep-id:uid=1000,gid=1000 \ + --device /dev/kfd --device /dev/dri --group-add keep-groups \ + --ulimit memlock=-1 \ + -p 8080:8080 -v ./models:/models:ro \ + -v gufo-extensions:/home/gufo/.local/share/gufo/extensions \ + ghcr.io/gufo-org/toolboxes/gufo-runtime:latest \ + gufo serve --host 0.0.0.0 --port 8080 llm --model /models/model.gguf +``` + +- Rootless Podman needs the `crun` runtime for `--group-add keep-groups`; + check with `podman info --format '{{.Host.OCIRuntime.Name}}'`. +- Inside a container, Gufo must listen on `0.0.0.0`, or the published port + won't answer. +- The `gufo-extensions` volume keeps [extension modules](extensions.md#modules) + you install with `gufo extension install` across container restarts. +- On Fedora and other SELinux hosts, a misleading "Memory critical" error from + ROCm can mean SELinux blocked `/dev/kfd`; see + [troubleshooting](troubleshooting.md#the-gpu-isnt-found). + +## Debian package + +Each release attaches `gufo_-1_amd64.deb` to its +[GitHub release](https://github.com/gufo-org/gufo/releases), built for Debian +13 (trixie) with AMD's ROCm 10.1 packages: + +```sh +sudo apt install ./gufo_-1_amd64.deb +gufo diagnose +``` + +## Nix + +```sh +nix profile install github:gufo-org/gufo#release +gufo diagnose +``` + +`#release` is the shipped build with the official extensions; the default +package also builds every extension it finds. Prebuilt packages come from the +`gufo` Cachix cache. Nix asks trusted users to accept it; for other users add +it system-wide: + +```text +extra-substituters = https://gufo.cachix.org +extra-trusted-public-keys = gufo.cachix.org-1:rfZe3n4lHINgyoACKzs5EthIZmBNvEyCCtufUpth0PE= +``` + +## Build from source + +From a checkout, `nix build` gives `./result/bin/gufo` with the pinned +toolchain: GCC 16.2 and ROCm 10.1.0. Without Nix, install these first: + +| Dependency | Used for | +| --- | --- | +| C++20 compiler, CMake 3.21+, Ninja, pkg-config | Building | +| ROCm HIP, hipBLAS, hipBLASLt, rocBLAS, hipCUB, rocPRIM, rocWMMA | GPU execution | +| ICU, libcurl, OpenSSL, libpng, libjpeg, libwebp | Tokenization, HTTPS, hashing, images | +| Rust 1.88 or newer, libopus | PNG, WAV and audio decoding | +| FFmpeg libraries | EmbeddingGemma 2 only | +| `ffmpeg` and `ffprobe` | Video and audio output | + +On Debian or Ubuntu, with +[AMD's ROCm repository](https://rocm.docs.amd.com/projects/install-on-linux/en/latest/) +set up: + +```sh +sudo apt install build-essential cmake ninja-build pkg-config \ + libicu-dev libcurl4-openssl-dev libssl-dev libpng-dev libjpeg-dev libwebp-dev \ + libopus-dev \ + libavformat-dev libavcodec-dev libavutil-dev libswscale-dev ffmpeg \ + hipblas-dev hipblaslt-dev rocblas-dev \ + hipcub-dev rocprim-dev rocwmma-dev +cmake --preset release -DCMAKE_INSTALL_PREFIX="$HOME/.local" +cmake --build --preset release --parallel 4 +cmake --install build/release +``` + +- Add `-DGUFO_EXTENSIONS_FROM_LOCK=ON` to build only the official extensions, + as releases do, or `-DGUFO_EXTENSIONS=` to choose; each extension + needs only its own libraries. +- If CMake can't find ROCm, pass `-DCMAKE_PREFIX_PATH=/opt/rocm`, and + `-DCMAKE_HIP_COMPILER=/opt/rocm/llvm/bin/clang++` if it picks a system Clang. +- The Nix build applies a [ROCm runtime patch](../.devops/nix/patches/rocr-fixed-cwsr-rocm10.patch) + that keeps GPU queues resident under memory pressure on Strix Halo. Apply it + to your ROCm for the same behavior. + +Different compilers or math libraries can change results slightly; Gufo's +published numbers use the Nix toolchain. + +## Windows + +Windows x86-64 is a development target. Each release attaches +`gufo-vX.Y.Z-windows-x86_64.zip`. Extract the whole ZIP and keep `gufo.exe` +next to its DLLs and kernel folders. To build it yourself, see +[building on Windows](../BUILD-WINDOWS.md). + +## Model files + +Gufo doesn't download models. Each [model page](models/README.md) lists the +files and pinned revisions to fetch with `hf download`. diff --git a/docs/internal/benchmarks.md b/docs/internal/benchmarks.md new file mode 100644 index 0000000000..c38e08100b --- /dev/null +++ b/docs/internal/benchmarks.md @@ -0,0 +1,163 @@ +# Benchmark methodology + +How benchmark numbers are produced, compared and retained. The public summary +is [benchmarks](../benchmarks.md). Measure release binaries (`nix build`, then +`result/bin`). Per-model results and qualification gaps live in: + +- [DeepSeek V4 Flash](models/deepseek-v4-flash/BENCHMARKS.md) +- [EmbeddingGemma 2](models/embeddinggemma-2/BENCHMARKS.md) +- [MiniMax H3](models/minimax-h3/BENCHMARKS.md) +- [Qwen-Image-2.1](models/qwen-image-2.1/BENCHMARKS.md) +- [Qwen3.8 27B](models/qwen3.8-27b/BENCHMARKS.md) +- [Qwen3.8 Flash-Next](models/qwen3.8-flash-next/BENCHMARKS.md) +- [Qwen3-ASR](models/qwen3-asr/BENCHMARKS.md) +- [Qwen3-TTS](models/qwen3-tts/BENCHMARKS.md) + +## Model benchmark driver + +`tools/bench/model-bench.py` measures the tables of a model's `BENCHMARKS.md` +over HTTP for Gufo and for the reference project of its category (llama.cpp +for Qwen; antirez/ds4 for DeepSeek), writes per-table artifacts, and renders the tables +and SVG charts between the `` markers. Workloads and table +layouts are declared in `docs/internal/models//artifacts/bench.json`; the +`benchmark-model` skill in `.agents/skills` describes the procedure. + +Reference runtimes are explicitly selected Nix packages, excluded from Gufo, +the normal development shell and hosted checks: + +| Reference | Package | Executable | +| --- | --- | --- | +| Qwen AR / DFlash2 | `.#llama-cpp-reference` | `llama-server` | +| Flash-Next MTP | `.#llama-cpp-mtp-reference` | `llama-server-mtp` | +| DeepSeek AR / DSpark | `.#ds4-reference` | `ds4-server`, `ds4-bench` | + +For example, enter the development shell and add only the needed baseline: + +```sh +nix develop +nix shell .#llama-cpp-reference .#llama-cpp-mtp-reference +python3 tools/bench/model-bench.py --model qwen3.8-flash-next --gguf "$MODEL" \ + --mtp "$MTP" run --target reference --table single-mtp +``` + +DeepSeek's HTTP payload omits pp/tg durations. The driver reads the pinned +server's existing stage timers from its log and checks them against HTTP token +counts. Native `ds4-bench` also supports single-session AR/DSpark, but not +concurrency. The pinned ROCm server disables DSpark when batching, so C>1 +DSpark comparisons are **N/A**. See the +[DS4 method](models/deepseek-v4-flash/QUALITY.md#benchmark-method). + +New or refreshed text-model cards use the same pp2048 prose/copying prompts +for single-user d0 and concurrency, with tg128. The driver shares their prompt +generator and records prompt hashes. C1 should cross-check d0; investigate +input, cache, controller and timing differences before attributing a gap to +batching. Short repeated-word corpora remain useful quality probes, but their +rates cannot replace these matched workloads. + +For decode comparisons, set `prefill_first: true` in the concurrency table. +Prepare every session with the full prompt and one output token, wait for all +preparations, then time identical tg128 requests with prefix reuse. The driver +pins llama.cpp slots and rejects replay exceeding four prompt tokens. This keeps +peers' long prefills outside llama.cpp's elapsed generation timer; Gufo reports +active decode time. Preserve a separate fresh AR completion-hash control. + +## Direct and serving measurements + +`gufo bench` measures the model path. Keep model artifact, prompt length, +generation length, context depth, speculative mode, and sampling controls +fixed when comparing runs. `pp2048` means 2,048 new prompt tokens; context +depth is separate from the amount of new prefill work. + +`tools/serving/gufo-serving-bench.py` measures HTTP serving with synchronized +requests. It distinguishes server-stage prefill/decode throughput, scheduler +and client TTFT, token ITL, whole-request throughput, and aggregate concurrency +throughput. C1 serving and a direct single-user benchmark are comparable only +when prompt, cache state, sampling, speculation, and timed scope match. + +Model tables report the **sum of individual request decode rates** in each +concurrent group, averaged across measured groups. Prefill and queue time +remain in the latency diagnostics. Pending measurements are **TODO**; +comparisons prevented by missing reference features are **N/A**, with a reason. +Whole-request throughput is not a substitute for decode timings. + +`--endpoint-profile openai` supports other OpenAI-compatible servers. Missing +server-stage metrics remain null. `--reference-report` compares completion +hashes against an existing C1 reference; category filters select a focused +subset. Qualify acceptance with a fresh server so prompt-cache hits do not +hide work. See [serving benchmark commands](performance.md) for invocation. + +`tools/bench/speculative-corpus.py` compares direct autoregressive and +speculative token traces. Request correctness, acceptance, and end-to-end +speed are separate requirements. + +## Quality method (matched-token, per position) + +Use the independent references and model-owned limits described in +[testing](testing.md). Tokenize once and feed teacher and candidate the same +predetermined history. Compare full next-token distributions before appending +the next evaluation token. Free-running text cannot isolate numerical error +after the first differing choice. + +```text +p_t = softmax(teacher_logits) +p_c = softmax(candidate_logits) +KL = sum_v p_t[v] * (log p_t[v] - log p_c[v]) +NLL = -log(p_c[target_token]) +``` + +Record non-finite counts, normalized-logit error, KL, teacher-token +NLL/perplexity, top-1 agreement, and top-k overlap as applicable. Aggregates +are over scored positions. A changed tokenizer, template, suite, or history +changes the comparison identity. + +Capability evaluation is separate: [gufo eval](../cli.md#measuring) grades free-running +answers through the OpenAI-compatible server. + +## Focused kernel measurements + +Build development tools with `cmake --preset gpu-test` and +`cmake --build --preset gpu-test --target gufo-kernel-bench tune_hipblaslt`. +They are omitted from the production package. + +`gufo-kernel-bench` exercises production HIP entry points without loading a +model. Correctness sentinels run outside the timed interval: + +```sh +./build/gpu-test/gufo-kernel-bench --help +./build/gpu-test/gufo-kernel-bench \ + --case decode-attention --context 4096,8192,12288,16384 \ + --warmup 5 --repetitions 30 --json +``` + +Standalone microbenchmarks under `tools/bench` and model-specific tool folders +report component correctness alongside timing. Their numbers do not replace +end-to-end model measurements. Collect profiler traces separately and use +[the performance guide](performance.md) to identify the limiting operation. + +## Reporting and artifact retention + +Record model/engine revisions, artifact hashes, hardware/software fingerprint, +power profile and CPU/GPU temperatures, input identity, context, output count, +sampling, concurrency, cache state, oracle identity, and the exact timed scope. +A numerical mismatch or device failure is not a passing result. Add repetitions +when timing noise or a suspected regression requires them. + +Checked-in JSON retains fixtures, model provenance, controller calibration, +and bounded result summaries. Serving summaries preserve aggregate metrics, +per-case completion hashes, and the original report digest. Raw samples, +profiler traces, generated tuning databases, and full-logit captures stay in +ignored `artifacts/`, except for independent reference data needed by a +maintained correctness test. + +Serving reports exclude endpoint hosts, prompts, generated text, model paths, +raw token IDs, and timestamps. The canonical machine fingerprint excludes +hostnames, usernames, secrets, timestamps, and private paths. +`gufo diagnose --validate-artifact` validates its supported diagnostic schema; +each model/tool owns the validation of its own result schema. + +Downloaded tokenizer files and `.direnv` shell state are local artifacts. +Count tracked source, including HIP translation units, with: + +```sh +nix run nixpkgs#cloc -- --vcs=git --force-lang=C++,hip +``` diff --git a/docs/internal/cache.md b/docs/internal/cache.md new file mode 100644 index 0000000000..bd78f9ecb1 --- /dev/null +++ b/docs/internal/cache.md @@ -0,0 +1,708 @@ +# Cache reference + +How the cross-request cache works inside: components, checkpoints, retention, +budgets, the disk tier, invariants and log lines. The user-facing summary is +[cache](../cache.md). + +## What "KV cache" means here + +Two different things share the name. Keeping them apart avoids most of the +confusion. + +**Within one request.** The standard transformer mechanism. Prefill computes +key and value tensors for every prompt token once; decode then appends one K/V +pair per generated token and attends over the stored set. Without it, each new +token would re-run attention across the whole sequence. This is intrinsic to +inference and is not configurable. + +**Across requests.** Keeping that state alive after a response finishes, so +the next turn of the same conversation does not recompute the prefix it shares +with the previous one. This is what the rest of this document is about: the +component cache, and its optional on-disk tier behind `--cache-disk`. + +The second is where the important subtlety lives. What Gufo retains is **not** +only K/V tensors. Each model's adapter describes its state as components: +append rows that are final once written, which checkpoints share, and private +state such as recurrent or sliding-window state, which each checkpoint copies. +The cache moves those bytes without interpreting them. + +That choice buys one retention, admission, eviction and persistence mechanism +that is correct for every model, including hybrid-recurrent ones. It costs the +ability to trim a checkpoint: private state exists only at its exact boundary, +so a checkpoint is reused only when its tokens are an exact prefix of the new +prompt. + +Every text model serves through the component cache of the +[cache redesign](design/cache-redesign/RFC.md). Its backing +and disk options are described under [component-cache budgets](#component-cache-budgets). +Qwen27B retains target KV, convolution and recurrent state, image identity, +sampled frontier and pending output tokens. DFlash2 adds private ring KV with +its own injected frontier, pending target features and draft controller state. +Borrowed target KV rows are preserved before mutation or rollback; private +frontiers are captured into committed host backing. Disk transfers use fixed +1 MiB staging regardless of checkpoint size. + +DeepSeek shares its compressed attention and indexer rows, which are final once +emitted, one row per `ratio` tokens. Each layer's sliding window and compressor +frontiers are private, as are logits and the DSpark windows, so a checkpoint +carries a fixed private cost whatever its depth. Rows are copied at capture +rather than borrowed, because compressed caches grow by reallocation. + +## Why it exists + +Prefill cost scales with prompt length. Decode cost scales with tokens +generated. Agent conversations have a large prompt and a small output, and +turn *N*'s prompt is nearly all of turn *N−1*'s prompt. Without cross-request +reuse, every turn pays for the whole conversation again and total cost grows +quadratically with conversation length. + +What reuse is worth, same conversation, second turn against a cold start +**(measured)**: + +| Model | Prompt | Cold | Reused | +| --- | ---: | ---: | ---: | +| Qwen3.8-27B | 101,545 | 280.4 s | 2.4 s | +| Qwen3.8-Flash-Next | 203,047 | 184.4 s | 0.7 s | + +A recorded 28-turn `pi` coding session reused 95.9% of its prompt tokens. The +same session replayed with reuse broken reprocessed 9.3x the tokens and took +2.5x the wall time, at only 15k tokens **(measured)**. + +## The shape of the system + +```mermaid +flowchart LR + REQ[Request] --> MEM{In-memory cache} + MEM -->|exact prefix hit| USE[Reuse live state
or restore a snapshot] + MEM -->|miss| DISK{Disk store
optional} + DISK -->|hit| USE + DISK -->|miss| COLD[No reuse] + USE --> SUF[Prefill only the new suffix] + COLD --> ALL[Prefill the whole prompt] +``` + +The in-memory tier is always on. The disk tier is opt-in, adds restart safety, +and can additionally *learn* boundaries between conversations that merely share +a prefix. + +## Finding reuse + +A request arrives with a token sequence. The cache looks for the longest +retained prefix of it, in two different forms. + +```mermaid +flowchart TD + A[New prompt] --> B{Is a live frontier
a prefix of it?} + B -->|yes| C[Reuse that session in place
no restore, no copy] + B -->|no| D{Is a retained snapshot
a prefix of it?} + D -->|yes| E[Restore the snapshot
into a free session] + D -->|no| F[Miss
report reason and common prefix] + C --> G[Prefill the suffix only] + E --> G + F --> H[Prefill everything] +``` + +A **live frontier** is where a session's state actually ended up after its last +request, including the tokens it generated. It is preferred even when a +snapshot matches the same length, because the state is already sitting there: +no restore and no device copy. This is why continuing the previous turn of a +conversation is nearly free, and why reuse can cover generated tokens and not +just prompt tokens. A request that continues no live frontier takes the least +recently used idle session (Flash-Next prefers one without a frontier), so +it does not replace the frontier of a conversation that has just replied. + +A **snapshot** is an immutable retained checkpoint. Reusing one means restoring +it into a session, which costs a copy. + +Both require an **exact prefix match**. The cache still computes the longest +common prefix on a miss and reports it, which is why a miss can say "we agreed +on 7,094 of your 7,103 tokens" and still re-prefill everything: it had no +checkpoint at that position to resume from. + +### Worked example + +A conversation with a 5,000-token system prompt, thinking off, client replaying +the assistant turn verbatim: + +| Turn | Prompt | Reused | Prefilled | Why | +| --- | ---: | ---: | ---: | --- | +| 1 | 5,020 | 0 | 5,020 | nothing retained yet | +| 2 | 5,320 | 5,020 | 300 | live frontier from turn 1 | +| 3 | 5,620 | 5,320 | 300 | live frontier from turn 2 | + +Now change one thing: edit the *last user message* of turn 3 and resend. The +first 5,320 tokens are byte-identical. The longest usable retained checkpoint +wins, which can be the previous turn's frontier. If the longest usable +checkpoint is instead the intermediate position at 4,096 tokens, that prefix +can be restored and only the suffix is prefilled. If earlier checkpoints have +been evicted or refused by the byte budget, +and all remaining checkpoints fall after the edit, reuse is impossible: + +| Turn | Prompt | Reused | Prefilled | Common prefix | +| --- | ---: | ---: | ---: | ---: | +| 3', intermediate checkpoint retained | 5,620 | 4,096 | 1,524 | 5,599 | +| 3', no usable earlier checkpoint | 5,620 | 0 | 5,620 | 5,599 | + +That gap between "common prefix" and "reused" is the signature of the +exact-prefix limitation. + +## Concurrent requests sharing a prefix + +Checkpoints help a request only once they exist. When several requests that +share a prefix arrive together, such as subagents started from one system +prompt or a retry sent before the first attempt returns, none of them finds a +checkpoint, and each would prefill the shared tokens again. Prefill runs one +request at a time, so the copies cost the sum of all prefills, and all +requests finish together at the end. + +Instead, a cold request that shares a long prefix with a request already +prefilling it waits for that one: + +```mermaid +sequenceDiagram + participant L as Leader (resident) + participant S as Scheduler + participant F as Follower (arrives later) + F->>S: arrives, shares N tokens with L + S->>L: publish a checkpoint at N + Note over F: parked, holds no session + L->>L: prefill to N, capture + S->>F: admit + F->>F: restore N, prefill its own tail +``` + +1. On admission, the scheduler compares the new prompt with every resident + request still prefilling and takes the longest exact token prefix with + matching input identity. +2. It waits only when the shared prefix is at least 512 tokens longer than + what the request could already restore, the resident request has not yet + prefilled past that point, and the runner supports snapshots. A + conversation continuing from its own retained turn therefore never waits + for a newcomer that shares only its system prompt. +3. The resident request stops its prefill at the shared position and + publishes a RAM checkpoint there, as for intermediate checkpoints. A + checkpoint it already plans within 64 tokens is used instead. Identical + prompts share up to the leader's last prompt token or its stable boundary. +4. The waiting request holds no session. Once the checkpoint is retained, or + the leader passes the position, finishes or is cancelled, it is admitted + ahead of newer requests and acquires its cache as usual. + +Because requests are waiting for it, that checkpoint is retained with the +priority of a conversation's stable boundary: on a full cache it replaces the +least recently used checkpoint rather than being refused as an optional copy. +Waiting is still advisory, like admission: if the checkpoint does not fit at +all or the leader is cancelled, the request prefills by itself. A request +waits at most once, and at most `--sessions - 1` requests wait at a time. With +`--sessions 1` nothing waits, because a second request is never admitted +while the first prefills. + +Measured on Flash-Next with `--sessions 4` and a 3.8k-token shared system +prompt, four concurrent requests took 13.4 s with each prefilling 3.9k tokens. +Prefilling the shared prefix once and restoring it took 4.6 s, each request +then prefilling 115 tokens **(measured)**. With a 242-token shared prefix the +gain was about 1 s of 9 s, which is why short prefixes do not wait. + +## What gets retained + +The unit of retention is a **checkpoint**, not a conversation. A single request +can retain up to four intermediate checkpoints in addition to its branching +fallback and complete prompt. Prefill stops at those positions and captures the +whole model state before advancing. Positions lie on a 2,048-token grid spread +across the prompt; the final grid point is within 2,048 tokens of its end. +Warm continuations skip grid positions less than 2,048 tokens beyond the reused +frontier, and every request skips grid positions within 128 tokens of its end: +such a point would split the final prefill pass for a checkpoint next to the +complete prompt. Capture runs asynchronously while that session is frozen, so other +requests can continue; a single execution slot skips the extra worker. A +request whose first token is already published decodes as soon as its capture +finishes, before the next bounded prefill chunk of a peer. +Coincident RAM and disk boundaries share one copy. Admission +remains subject to the existing byte budget, and intermediate copies preserve +the original branching fallback. These intermediate checkpoints live in RAM; +the disk tier continues to retain prompt and learned shared-prefix boundaries. + +### Learned divergence points + +Grid checkpoints sit at fixed positions, not where conversations actually +diverge. Agents start many conversations with the same system prompt and tool +definitions, then a different task: + +```text +Conversation 1: [ shared 4,500 tokens ][ task A, 10,000 tokens ] +grid checkpoints: ^2,048 ^6,144 ^10,240 ^14,336 +``` + +Only the 2,048 checkpoint lies inside the shared part, so a second +conversation would restore 2,048 tokens and prefill the other 2,450 shared +tokens again. The longer the tasks, the further the grid spreads. + +The point that matters, token 4,500, is unknown until a second prompt shows +where the two differ. When a request arrives, the cache compares it with the +tokens of every retained checkpoint and live frontier of the same input +identity. If the longest common prefix adds at least 512 tokens to what the +request can already restore, the request stops its prefill there and retains +an extra checkpoint. Other conversations depend on it, so it is retained like a +stable boundary, not as an optional copy, and the branch-point rule below keeps +it while it is shared. From the third conversation on, every new one restores +the whole shared prefix and prefills only its own task. A divergence within +the request's last 64 tokens, such as an edited final message, is covered by +its own stable checkpoint and takes no extra copy. The same position from the same prefix family is captured +once; records whose images differ from the prompt are not used to find it. +Without disk, this needs no configuration. + +Execution and retention have separate limits. `--sessions N` allocates N +mutable execution states and controls active request concurrency. A separate +pool holds **128 immutable checkpoint records**, regardless of session count. +These records allocate no extra execution states: with `--sessions 1`, several +inactive conversations can still be remembered. + +This is a checkpoint limit, not a guaranteed conversation count. One history +can occupy several records, and the byte budget may bind before all 128 are +used. The server identifies related checkpoints by exact token prefixes and +matching input identities, not a client-supplied conversation ID. + +When space is needed, RAM retention prefers removing: + +1. A full-prompt retry copy with a stable fallback still retained. +2. An intermediate copy with a related stable continuation retained. +3. An older stable boundary covered by a newer one. A checkpoint that two + retained conversations extend and then diverge after is the prefix they + share, not an older turn, and never counts as covered. +4. Remaining checkpoints, oldest-used first within each priority. + +Under entry pressure, an edited branch can first replace its incompatible +tail, preserving earlier shared checkpoints. Optional history/retry copies +are skipped rather than removing another prefix family's last useful copy. +Retry copies cannot displace earlier history or stable boundaries either. +An unchanged retry then restores the stable boundary and prefills only the +assistant opening, such as `<|im_start|>assistant\n\n`, again. If +the prompt ends with a text-only user turn after a tool result or another user +turn, Qwen templates place the stable boundary before that turn, so the retry +prefills it too. The server logs `event=snapshot action=skipped` with that +prompt's length. +A new stable boundary can replace its own older boundary when that avoids +removing another family's last copy. Sources are rechecked before replacement +because another request may have changed the record. + +TP2's model-owned cache opts into a different record-pressure policy: a new +checkpoint may replace the least recently used copy of another idle conversation. +It preserves its source, shared branch points and its own earlier boundaries. +This private serving setting applies to the legacy TP cache; component-cache +retention and the ordinary model-owned default keep their own policies. + +The original resume point stays protected during intermediate/retry admission. +Earlier checkpoints remain best-effort: under pressure, edits and rewind may +need more prefill. Rotation beyond the actual memory or record capacity can +still lose reuse; this is not unlimited retention. + +The actual selected limits are reported at startup: + +```text +schema=component-cache-v1 event=configured sessions=1 snapshot_entries=128 capacity_bytes=8589934592 automatic_bytes=8589934592 max_bytes=13958643712 +``` + +## Invariants + +These constraints are why several design choices are not preferences. Change +them deliberately or not at all. + +**A checkpoint must contain the state at its exact token boundary.** Most +runners stop prefill at that boundary before capturing it. Flash-Next can +capture a text prompt's stable boundary within the final prefill pass: its +recurrent kernels retain the boundary state, convolution and PLE retain their +history, and a one-row head computes the boundary logits. Attention queries +on either side keep the grouping of separate passes. The final batch can +include up to 128 tokens beyond the normal 2,048-token chunk, so a prompt that +ends just past a chunk needs no separate tail pass; the stable boundary must be +within eleven tokens of that batch's end (an eight-token assistant suffix plus +the up to three tokens a four-token-aligned boundary falls back). +The cache reserves the full payload before enabling this capture. Disk, +image, intermediate and learned-prefix checkpoints still stop prefill at +their boundary. + +**A checkpoint never splits an indivisible input.** A model whose prompt +context declares spans through `TextPromptContext::PrefillStop`, such as image +rows that must share one forward, never has a prefill step, planned checkpoint, +stable snapshot or shared-prefix boundary end inside one, and never restores a +checkpoint inside one. Such a position moves to the span's first row, and a step +that starts at a span takes it whole even beyond its token budget. Contexts that +declare no spans change no position. + +**A checkpoint may hold less than a cold request would.** Each prefill step's +prompt ends at its own frontier, and `TextRunnerState::prefill_prompt_end()` +gives the whole prompt's end. A model that runs some work only near that end +can skip it in steps ending at earlier cache boundaries, so their checkpoints +lack those rows. Its `TextModelRunner::CanContinue` then refuses prompts that +would need them, and the cache serves those from a shallower boundary. By +default every state continues every prompt. + +**The reused frontier must be frozen before prefill.** Prefill mutates the +leased state in place, so a frontier another request might branch from has to +be captured first. + +Flash-Next copies its mutable recurrent, convolution and PLE state into +private device storage at capture; the small indexer-ring, draft-residual and +kept-row regions go directly into the host payload. Committed K/V and pooled +rows remain in the live session while it appends, without a K/V copy. +A same-session rewind allocates backing blocks for only the rows it would +overwrite and copies them once for checkpoints sharing those rows. Appending +allocates no K/V backing blocks. Restore keeps the still-live prefix without +a K/V upload. + +A model with a sliding attention window declares that attention as a +window-rows component (`ComponentKind::kWindowRows` with `window_rows`) instead +of private state. A checkpoint at row n keeps only the chunks from the one +containing row n - `window_rows` to n and shares them with neighbouring +checkpoints. Restore loads just those chunks, and the disk manifest records the +window size (format version 3, written only when a window component is +present; version 2 manifests remain readable). Retention counts the window as +a fixed cost per checkpoint, like private state, and frees a chunk once no +checkpoint's window reaches it. + +Reset leaves append-only rows intact; the first write that would overwrite +them preserves pending checkpoints. Session destruction preserves remaining +rows before releasing device buffers. Byte readers assemble a complete +payload before export. Forks copy the live prefix directly between device +buffers, including detached rows in the shared backing blocks. When both +sessions branch from a shared checkpoint, restore retains their proven shared +rows and copies only the different suffix. Equal token histories alone do not +prove identical K/V, since prefill shapes can change rounding. +A private HIP pool shared by the executor's sessions allocates and releases +snapshot storage without synchronizing peer inference streams. Each fresh +allocation commits device pages, about 4.5 ms per 111 MB on gfx1151, so a +restore into a slot whose rows other checkpoints still borrow pays that cost +for the rows it protects. A retained +Flash-Next snapshot prefers its source execution slot when +that slot is available, avoiding a full-prefix copy for a rewritten turn. +A busy source never blocks a branch into another slot; other choices use LRU. +RAM admission continues to charge the complete payload size, and the disk +byte format is unchanged. Captures intended for disk complete all device +copies before prefill resumes, so disk serialization does not introduce a +background K/V transfer during inference. + +**Admission is advisory, never fatal.** A refused reservation or a failed +capture is a skipped optimisation. The request must still complete. + +**Eviction cannot skip a victim.** If removing an entry fails, the eviction +loop stops rather than trying the next candidate, in both tiers **(source)**. + +## Limits + +Independent limits can each bind first. Payload memory is allocated only when +captured; RAM-retained snapshots and their captures in progress share the RAM budget. + +| Limit | Default | Set by | +| --- | --- | --- | +| Retained snapshot bytes, RAM | smaller of 32 GiB and half the available host RAM; an explicit value up to the available host RAM minus 4 GiB; 27B also checks HIP free memory | `--cache-ram-bytes` | +| RAM checkpoint records | 128, independent of `--sessions` | internal safety limit | +| Disk bytes | 8 GiB | `--cache-disk-bytes` | + +`--cache-ram-bytes off` turns the RAM cache off. The server then keeps no +checkpoint in RAM, commits no cache backing, and computes no budget. Without +`--cache-disk` it also grows no backing before prefill. Each session still reuses its own live state, `--cache-disk` +still works, and the per-response `gufo.component_cache` block stays present +with zero captures. Off drops every RAM checkpoint, so there is no restore from +RAM, no shared-prefix or branch checkpoint, and no retained history. With +`--cache-disk`, Qwen and Flash-Next still copy each disk capture through a +bounded 512 MiB backing, so `backing_prepared` appears in that case only. The +startup line reports `ram_cache=off capacity_bytes=0`. Disk-only serving also +needs metadata for its retained disk index and in-flight publications. Its +metadata remains accounted without an aggregate RAM admission limit; allocation +can still fail if host memory is exhausted. This does not enable RAM checkpoints +or enlarge the fixed capture backing and disk staging buffer. Persistence pins +remain capped at the 512 MiB disk-capture backing capacity. + +When the sessions leave no RAM for the cache above the 4 GiB host reserve, +the server refuses to load with that reason and the remedies: fewer +`--sessions`, a smaller `--context`, or `--cache-ram-bytes off`. `off` loads +even when the host is already below its reserve before the sessions allocate. +When an explicit value is only partly available, the server loads with what +the host allows and logs `event=ram_cache_trimmed` with the requested and the +granted bytes; the same remedies restore the full budget. + +`--cache-ram-bytes 0` selects automatic sizing. Zero does not disable reuse. +A positive value replaces the automatic budget and may exceed it: it trades the +free half of host RAM for retention, but always leaves 4 GiB to the OS and other +processes. For an 8 GiB cap, use `--cache-ram-bytes 8589934592`. The startup +line reports the selected `capacity_bytes`, the `automatic_bytes` budget and +the `max_bytes` an explicit value may claim. With a DFlash2 draft, each +Qwen3.8-27B session also pins about 400 MiB of prompt capture at startup, +reported as `slot_pinned_bytes`. It is charged on top of `capacity_bytes`: an +explicit value may claim at most `max_bytes` minus `slot_pinned_bytes`, or the +startup ceiling minus `slot_pinned_bytes` when that ceiling binds. +`automatic_bytes` is half the available RAM measured before the pins. The +`global_ram_bytes` gauge and the metadata category include the pins, so live +usage can exceed `capacity_bytes`. + +Both are sampled after weights and execution states are allocated, then fixed +for the server run. Flash-Next and Qwen3.8-27B use half the available +host RAM, respecting container/cgroup limits. Inactive page cache, such as +recently read model files, counts as available because the kernel reclaims it +before failing an allocation. Dirty and writeback pages do not. 27B also clamps this to HIP's free +device memory. CPU and GPU allocations compete for the same physical RAM on +Strix Halo, so HIP's free-memory estimate alone is not enough. +For example, 44 GiB available at load gives a 22 GiB automatic RAM cache and +allows an explicit limit of up to 40 GiB, even when HIP reports more free +memory. +Memory that another process claims after startup is not subtracted. When +other GPU servers share the machine, such as an image or speech server, set an +explicit `--cache-ram-bytes` that leaves room for their peak use; starting +them first only accounts for what they hold at that moment. +The RAM payload budget excludes weights, execution states, token metadata, +disk staging and Qwen's separate CPU image-preprocessing cache (up to 128 MiB +of retained encoded/RGB vectors plus bounded metadata). It also excludes temporary +host buffers used to save checkpoints to disk; this is not a limit on total +server memory. + +The 32 GiB automatic cap limits default growth on a lightly loaded machine. +It leaves room for several 27B histories: two 3.7 GB checkpoints per history +would consume about 30 GB for four conversations, before optional copies. +The 128-record safety limit bounds metadata and lookup work without requiring +more execution sessions. Neither guarantees a conversation count: roughly, +divide the byte budget by the retained checkpoint bytes per conversation. +For example, 8 GiB holds at most eight sets of two 512 MiB checkpoints, or +two sets of two 2 GiB checkpoints, before extra copies and in-flight captures. + +Increasing context or sessions reduces the memory left after loading, and +with it both budgets, exactly when snapshots grow. On Flash-Next with +`--sessions 2` at 262144 context, 14.8 GB remained after loading: a 7.76 GB +automatic budget against 5.70 GB snapshots at 200k tokens, so only one deep +conversation stays retained **(measured)**. A newer conversation's stable +boundary then replaces the older one's checkpoint; only optional intermediate +and retry copies are refused. This is a hardware ratio, not a cache policy: +weights, execution states and the OS leave no more memory. To keep more deep +conversations: + +- Raise `--cache-ram-bytes` towards the reported `max_bytes` (less + `slot_pinned_bytes` on Qwen3.8-27B): about 10.5 GB + here, enough for a 200k-token checkpoint plus a 50k one instead of only the + first. +- Run fewer `--sessions`: each Flash-Next session at 262144 context holds about + 6.3 GB of state that the cache can use instead. +- Add `--cache-disk` so checkpoints that leave RAM can still be restored from + disk. Checkpoints of any size stream through the internal buffer. + +Snapshot size scales with retained tokens and differs sharply between models: +roughly 0.5 GB at 5k tokens on Flash-Next, and 3.7 GB at 24k tokens on +Qwen3.8-27B **(measured)**. + +RAM eviction follows the checkpoint priorities above. Disk eviction remains +global least-recently-used, without conversation or rebuild-cost awareness. + +### Component-cache budgets + +Qwen27B and Flash-Next use the same options with these meanings: + +| Option | Meaning | +| --- | --- | +| `--cache-ram-bytes` | The automatic and explicit sizing above, as a cap. Pinned 64 KiB pages for up to about 89% of it are committed as captures need them, in equal steps of about 1 GiB, and stay committed; the rest is reserved for cache metadata, which grows with use. The pages hold checkpoint state, KV rows, partial tails and idle-session spill. There is no separate spill budget. | +| `--cache-disk-bytes` | Counts referenced, temporary and orphaned files. A lower budget at startup removes temporaries and orphans, then the oldest checkpoints by creation order: use history does not survive a restart. | +| `--cache-disk-staging-bytes` | Ignored, with an `event=option_ignored` warning. Disk transfers use an internal 1 MiB pinned buffer; checkpoints of any size stream through it. Its size did not change restore or write speed, and a larger value only took pinned RAM and device heap. | +| `--cache-disk DIR` | Owned by one server. A second one fails at startup, before committing its RAM budget, with an ownership error naming the directory. model's server sharing it. | + +The 128-record limit stays internal. The following measured sizes and timings +are Flash-Next evidence; Qwen27B qualification is recorded in its model card. +Each Flash-Next checkpoint holds about 132 MB of +private state, so below a budget of about 19 GB that state caps the checkpoint +count under 128; only larger explicit budgets can reach the record limit. The startup line +`schema=component-cache-v1 event=configured` reports `capacity_bytes`, +`automatic_bytes`, `max_bytes`, `staging_capacity_bytes`, +`disk_capacity_bytes` and `slot_pinned_bytes` (host memory the sessions pinned +at startup, charged on top of `capacity_bytes`). + +Flash-Next prepares a bounded two-segment reserve before readiness and can +prepare the next segment before a prefill with at least 512 tokens remaining +or when assigning backing to completed append rows. Private-state and partial-tail copies do not request speculative +growth; a capture still commits any backing it needs. + +Backing excludes transparent huge pages before population and attempts a Linux +long-term page pin before GPU registration. GPU registration alone leaves +anonymous pages movable: ordinary memory compaction can invalidate their GPU +mappings and pause the process's queues. Registered `io_uring` buffers supply +the extra pin without submitting I/O or running polling threads. Their +lifetime follows the backing, including blocks that outlive the pool facade; +cleanup unregisters the GPU mapping and releases the pin before unmapping. +If `io_uring` or the process's memory-lock limit refuses the pin, the existing +registered base-page path remains available with the same cache capacity. +`event=backing_prepared` and `event=backing_grown` report +`long_term_pinned_bytes` alongside committed bytes, making that fallback visible. + +Container seccomp profiles may block `io_uring_setup` and `io_uring_register`. +An unlimited `memlock` setting alone does not enable them. Check the pin-byte +counter inside the running container: zero means the extra migration protection +is unavailable. Enabling it requires allowing these two calls in the +operator-managed syscall policy; `io_uring_enter` is not used. The registered +base-page fallback remains compatible with restrictive container policies. + +A step of about 1 GiB took 56–58 ms on the capturing thread while the host had +free pages **(measured)**. Captures run on the scheduler thread, so concurrent +requests pause for that long too; an 8 GiB budget fills in eight steps. When the +kernel must first reclaim page cache, such as the model files read at load, a +step takes longer: a 157K-token turn that retained 4.8 GB right after a restart +spent about 3.5 s growing in 256 MiB steps. Committing pages on demand keeps +that reclaim out of model load: committing a 17 GiB budget up front took +29–39 s at load, against 16 s without it **(measured)**. Segments +cannot be joined, so a payload stays within one, and each edge strands space +that a ~140 MB private state cannot use; equal segments of about 1 GiB keep that +small. A step is skipped while the host would keep less than 4 GiB available +(`schema=component-cache-v1 event=backing_limited`); the cache then works within +what it has committed, evicting as at a full budget, and tries again a second +later. Until the cache fills, the host keeps the remaining memory, including the +page cache that holds recent disk checkpoints, so a restore soon after a +restart reads them from memory. A cache that has filled keeps its footprint; the advice above on explicit budgets for co-resident servers +still applies. + +## The disk tier + +`--cache-disk DIR` adds a second tier that survives restarts. A checkpoint +written before a restart restored a 24,866-token prompt in 1.8 s against about +50 s for a cold prefill **(measured)**. + +A Flash-Next checkpoint is thousands of files: 157K tokens are 4.45 GB in +18,672 files, mostly 256 KiB. Four helper threads hint the files ahead of the +restore, which still reads, checks and copies them in order. That restore took +1.3–1.4 s with the files on disk and 0.85 s from the page cache, against +8.7–9.9 s when one thread hinted each file in turn **(measured, NVMe under +dm-crypt)**. + +Learned divergence points (see above) are ordinary checkpoints, so they reach +disk like any other and survive restarts. + +**Disk checkpoints are spaced at least 2048 tokens apart.** A conversation +advances a few hundred tokens per turn, so writing every turn serialises, fsyncs +and retains a nearly identical snapshot. A checkpoint less than 2048 tokens past +the longest stored entry that is still a prefix of it is skipped and logged as +`min_step`; the RAM tier still retains it. When RAM does not retain it either, +the device state is not copied at all, so a skipped checkpoint costs no capture +time on the request path. Learned shared-prefix boundaries are +exempt, because they sit close to a deeper entry by construction. On a +Qwen3.8-27B functional run this cut disk writes from 31 to 5 and written bytes +from 6.97 GiB to 1.37 GiB **(measured)**. + +The trade-off is what a disk-only restore resumes from. After a restart, or +once RAM evicted the conversation, a request restores the nearest stored entry +and re-prefills up to 2048 tokens plus its own turn, instead of resuming +exactly at the previous frontier. Greedy output is unchanged. Sampled output can +differ from the pre-restart response, because the re-prefilled gap follows +different chunk shapes, as with any partial hit. Plain continuation from RAM is +unaffected. + +Disk entries are evicted by global LRU on last access, so one active run whose +checkpoints are all recent will displace every other conversation in age order +**(measured)**. + +## What invalidates reuse + +Anything that changes the token prefix. In practice: + +- **Tool definitions** — adding, removing or reordering changes the prompt head + and invalidates everything after it. +- **System prompt** — including anything volatile inside it, such as a + timestamp or a working directory. +- **Response schema** — `response_format` is rendered into the prompt. +- **Images** — changing, removing or moving an earlier image invalidates + checkpoints after it. Appending a new one does not. +- **Reasoning the client cannot replay** — thinking is on by default for Qwen + and `reasoning_content` is not part of the OpenAI schema, so an ordinary + client omits it when sending the conversation back. Gufo retains each turn's + boundary before the assistant opening, so the next turn can reuse the prior + history and process the rewritten assistant plus new input. That boundary + must be saved on warm hits too; retaining only the old resume point caused + cache reuse to stop advancing for the rest of the session. + +These do **not** invalidate reuse **(measured)**: changing `temperature`, +`top_p`, `seed`, `max_tokens`, penalties or `stop` between turns; streaming +versus not, which reuse identically and interoperate within one conversation. + +`cache_prompt: false` on `/v1/chat/completions`, `/v1/responses`, +`/v1/completions` or `/completion` bypasses lookup for a single request. The +result can still populate the cache. `null` keeps the default, `true`. + +`cache_persist: false` on the same endpoints keeps one request's checkpoints +in RAM only: nothing it captures is written or staged for the disk tier, so +they are lost on eviction or restart. It still reads disk checkpoints, and it +does not stop a later request without the flag from persisting the same +prefix. `null` keeps the default, `true`. Responses echo the applied value as +a top-level `cache_persist`; see [the server guide](../server.md). + +## Observing it + +| Log line | Meaning | +| --- | --- | +| `schema=component-cache-v1 event=configured` | Flash-Next: RAM, staging and disk budgets at startup, with the automatic budget and the most an explicit `--cache-ram-bytes` may claim; `ram_cache=on` or `ram_cache=off` at the end of the line, and `disk_backing_bytes` for the backing an off cache keeps for disk captures | +| `schema=component-cache-v1 event=backing_grown` | Flash-Next: a capture committed another segment of cache pages (about 1 GiB); reports `committed_bytes`, `segments` and the capture's `acquire_ms` | +| `schema=component-cache-v1 event=ram_cache_trimmed` | Qwen3.8-27B, Flash-Next and DeepSeek V4: an explicit `--cache-ram-bytes` exceeds what the host keeps above its 4 GiB reserve after the sessions allocated; reports `requested_bytes` and the granted `capacity_bytes` | +| `schema=component-cache-v1 event=backing_limited reason=host_reserve` | Flash-Next: the cache stopped growing below its budget because the host would keep less than 4 GiB available | +| `schema=component-cache-v1 event=backing_limited reason=device_heap_reserve` | Flash-Next: the cache stopped growing because registering a segment's pages took the device heap below its 4 GiB dispatch reserve, which would push session and scratch allocations onto managed memory. Hosts that do not charge registered pages to the heap log it only when other allocations shrink the heap during the registration | +| `schema=component-cache-v1 event=option_ignored option=--cache-disk-staging-bytes` | Flash-Next: the staging option is ignored; disk transfers use the internal buffer | +| `schema=component-cache-v1 event=disk_evicted reason=budget` | Flash-Next: startup removed the oldest checkpoints (creation order) to fit a lowered `--cache-disk-bytes` | +| `schema=component-cache-v1 event=disk_over_budget` | Flash-Next: the directory still exceeds `--cache-disk-bytes` after startup reclamation and eviction; publication is refused until it fits | +| `schema=component-cache-v1 event=published` | A checkpoint finished disk publication; `checkpoint_id` identifies the capture and `tokens` its boundary | +| `schema=component-cache-v1 event=persistence_refused reason=min_step` | A captured checkpoint is too close to an existing publication; includes `checkpoint_id` and `tokens` | +| `event=snapshot action=removed reason=entry_capacity` | a retained prefix was evicted because every entry was taken | +| `event=snapshot action=skipped reason=entry_capacity` | no checkpoint record could be replaced safely for this capture | +| `event=snapshot action=skipped reason=byte_capacity` | a checkpoint did not fit the RAM budget | +| `event=disk_cache action=removed reason=lru` | a disk entry was evicted to stay inside `--cache-disk-bytes` | +| `event=disk_cache action=skipped reason=staging_capacity` | a checkpoint exceeded `--cache-disk-staging-bytes` and was never written | +| `event=disk_cache action=skipped reason=min_step` | a checkpoint was less than 2048 tokens past a stored prefix; RAM still retains it | + +Per-request outcomes appear in the completion log and in `usage.gufo`: +`cache_hit`, `cache_miss_reason`, `cache_common_prefix_tokens`, +`cache_checkpoint_tokens`, `cache_restore_bytes`, `cache_restore_ms` (bytes and +milliseconds restored on a hit), `cache_disk_hit` (the restored prefix came +from disk), `cache_snapshot_bytes`, `cache_snapshot_ms` (the KV snapshot this +request's retained prefix occupies and the time to snapshot it, also reported +when a stop or cancel path retains the prefix), `cache_disk_queued_bytes`, +`cache_disk_enqueue_ms` (snapshot bytes handed to disk publication and their +enqueue time), +`shared_prefix_wait_ms` (time spent waiting for a concurrent request, part of +`queue_ms`), plus +`prompt_n` (newly processed) and `cache_n` (reused) in the llama.cpp-compatible +`timings` object. Miss reasons are `no_checkpoint`, `prefix_changed`, +`input_changed`, `no_compatible_boundary` and `disabled`. Flash-Next reports +`no_checkpoint` when no +stored prompt shares a token with the request and `no_compatible_boundary` +when one does but no restorable boundary covers it; +`cache_common_prefix_tokens` is then the longest agreement and +`cache_checkpoint_tokens` the deepest compatible boundary. + +Flash-Next also reports `usage.gufo.component_cache.captured_checkpoint_ids`. +Match these request-local IDs to `checkpoint_id` in publication/refusal logs: +an earlier request's asynchronous write may finish after the current response. +IDs belong to one server lifetime; correlate each restart separately. + +Reading them: + +- `cache_n` growing turn over turn while `prompt_n` stays flat is healthy + reuse. +- Concurrent requests with a shared prefix: one has `shared_prefix_wait_ms` + zero and prefills the prefix; the others wait, then report the prefix in + `cache_n` and only their own tail in `prompt_n`. With `--log-level debug`, + `event=shared_prefix_wait` and `event=shared_prefix_ready` name the leader + and position. +- `cache_n` **pinned** at the same value while `prompt_n` grows every turn is a + checkpoint that stopped advancing. +- A large `cache_common_prefix_tokens` on a miss means a long prefix agreed and + could not be resumed from: a mid-history edit, or an evicted checkpoint. + +## Verifying changes + +- `tests/functional/` covers rotation through independent conversations, a long + history interrupted by tiny side requests, edits/rewind, advancing boundaries, + cancellation and disk restart. Uncached controls check the answers; CPU tests + exercise byte and record pressure without loading models. +- `tests/functional/continuation.py` covers cancellation, reasoning replay, + images and restart persistence against a live server. After a restart, + greedy and exact restores must reproduce their output; sampled restores may + re-prefill less than one disk step. +- `tests/functional/cache_disk_spacing.py`, part of the `cache` suite, checks + disk checkpoint spacing for a growing conversation, the restore after + restart, and that a learned branch boundary is still written. +- `tests/functional/cache_concurrency.py` (`cache-concurrency`) sends + identical prompts, shared-system fan-out with short and long tasks, short or + no shared prefixes, a retained conversation beside a newcomer and a + cancelled leader at once, checking waits, prefill work and uncached answers. + `tests/cli/text_generation_scheduler_test.cpp` covers the same cases, plus + runners without snapshots, without loading a model. +- `tests/cli/component_text_cache_test.cpp` and `tests/cache/` cover + retention, admission, eviction and persistence without loading a model. diff --git a/docs/internal/ci.md b/docs/internal/ci.md new file mode 100644 index 0000000000..631c9e10dc --- /dev/null +++ b/docs/internal/ci.md @@ -0,0 +1,58 @@ +# CI workflows + +What runs on a pull request, on `main` and at release, and which checks gate a +merge. All workflow files live in `.github/workflows/`. Job and step names start +with a verb; a reusable workflow's jobs appear as `caller / called job`. + +| File | Display name | Job | Runner | When | +| --- | --- | --- | --- | --- | +| `checks.yml` | Repository checks | Run CPU and repository checks | GitHub Ubuntu | PRs to main, pushes to main, manual. Bounded CPU, repository and functional-harness tests. | +| `checks.yml` | Repository checks | Warm Linux package cache | GitHub Ubuntu, via `linux-build.yml` | Main and manual only. Builds the production package to fill the shared cache. | +| `linux-build.yml` | Linux build | Linux package | GitHub Ubuntu | Reusable. Main cache warming, and candidate and baseline packages for comparisons. | +| `windows-build.yml` | Windows build | Windows package | GitHub Windows | Reusable. Builds the native application, runs CPU contracts and verifies the bundle. Called by Windows validation and by Toolboxes releases. | +| `devlab-windows.yml` | Windows validation | Build, then Run Windows model checks | GitHub Windows, then Devlab Windows Strix Halo | PRs to main, pushes to main, manual. GPU diagnostics and model smoke checks on the same run's bundle. | +| `devlab-linux.yml` | Linux validation | Authorize and select checks | GitHub Ubuntu | Non-draft PR updates and manual runs. Pins revisions and plans the affected checks. | +| `devlab-linux.yml` | Linux validation | Build | GitHub Ubuntu, via `linux-build.yml` | When the plan selects work. Builds the candidate and `main` packages. | +| `devlab-linux.yml` | Linux validation | Run Linux model checks | Devlab Linux Strix Halo | Prepares while the hosted build runs, then tests once the packages arrive. | +| `devlab-linux.yml` | Linux validation | Publish results | GitHub Ubuntu | After testing, failures included. Publishes the report and the `devlab/functional` status. | +| `devlab-comment.yml` | Functional reporting | Update PR comment | GitHub Ubuntu | When Linux validation starts or ends. Keeps the PR comment current, also for forks, without running PR code. | +| `pr-title.yml` | PR title | Validate PR title | GitHub Ubuntu | PR opened, edited, reopened or updated. | +| `docs-website.yml` | Website docs | Request website development docs | GitHub Ubuntu | Pushes to main that change public docs, manual. Sends `gufo-docs` so gufo.blog refreshes its `development` docs. | +| `release-please.yml` | Release automation | Prepare, merge and publish release | GitHub Ubuntu | Manual. Waits for the required checks, publishes the release and sends the tag to Toolboxes and the website. | + +## Required checks + +The **Required CI** ruleset requires these contexts on `main`: + +| Context | From | +| --- | --- | +| Run CPU and repository checks | `checks.yml` | +| Validate PR title | `pr-title.yml` | +| Build / Windows package | `devlab-windows.yml` calling `windows-build.yml` | +| Run Windows model checks | `devlab-windows.yml` | +| `devlab/functional` | Commit status from `devlab-linux.yml` | + +A required context is the caller and leaf job name, not the workflow display +name, so renaming a job means updating the ruleset, `release-please.yml`'s check +names and `devlab-comment.yml`'s `workflow_run` subscription in the same change. +Toolboxes calls `windows-build.yml@main` by path. + +`devlab/functional` fails on correctness failures and on checked phases that +are consistently slower than `main`. Missing or incomparable evidence is an +error. Noisy but complete comparisons pass with a visible warning, on ordinary +and release PRs alike. See [testing](testing.md#text-api-functional-tests) for +how checks are selected. + +## Caches + +- **Repository checks** use the compiler cache, Cachix and the Magic Nix Cache. + Each run saves under a fresh key, so the Actions cache stays current. +- **Linux package builds** use the package compiler cache and Cachix. Main's + warming job exists because PR builds don't push to Cachix. +- **Windows builds** cache the SDK archive, the compiler cache and the vcpkg + binary cache. +- **Devlab runners** download the verified bundles that the hosted builds + produce; Windows uses the bundle from the same workflow run. + +Native Windows `check-pr` runs every Windows test from the platform-only build +with assertions enabled. A MinGW Nix package remains for local use only. diff --git a/docs/internal/design/cache-redesign/RFC.md b/docs/internal/design/cache-redesign/RFC.md new file mode 100644 index 0000000000..22926d726b --- /dev/null +++ b/docs/internal/design/cache-redesign/RFC.md @@ -0,0 +1,2233 @@ +# RFC: continuation cache redesign + +Status: implementation in progress. Updated 2026-10-11. Flash-Next serving +integration is under qualification in [PR #543](https://github.com/gufo-org/gufo/pull/543). +The all-model cutover and measured acceptance gates remain open; predictions +below are not qualified implementation results. + +This is the single, self-contained review document for the cache redesign. +The original research documents, scripts and measurement inputs are preserved +in pinned archives; retrieval and replay instructions are included below. Measurements of the existing cache, simulations +of proposed behavior and estimates are distinguished throughout. + +Contents: + +- [Context](#context) and [problem statement](#problem-statement). +- [Goals](#goals-and-non-goals) and [glossary](#glossary). +- [Current system](#how-the-system-is-designed-now). +- [Evaluated solutions](#evaluated-solutions), including the detailed hybrid + proposal, conversation examples and comparison table. +- [Success criteria](#success-criteria-and-evaluation) and [risks](#risks). +- [Delivery roadmap](#delivery-roadmap), followed by the detailed + [implementation plan](#implementation-plan). +- [Instrumentation](#instrumentation). +- [Rollout](#compatibility-and-rollout) and [decisions](#open-questions). +- [Evidence appendix](#evidence-appendix) and [references](#references). +- [Archived evidence and replay instructions](#archived-evidence-and-reproducibility). + +## Context + +Gufo serves models locally on a Linux AMD Strix Halo machine. Conversations +often grow over many turns: a coding agent reads files, calls tools and starts +subagents; other users may continue unrelated conversations at the same time. +Reprocessing the full history on every turn can dominate response time. + +The continuation cache retains model state so a later request can resume work +already performed. Useful history may belong to a live conversation, an earlier +edit point, a parent agent, or a conversation resumed after a server restart. +The intended workload includes up to eight concurrent requests and more logical +conversations than execution slots. + +This RFC evaluates how to retain and reuse that work across all Gufo model +families. The priority order is response latency, RAM usage, then disk capacity +and write volume. The implementation should arrive through independently +testable PRs that deliver useful behavior while keeping reviews manageable. + +## Problem statement + +The system needs to reuse compatible computation reliably as conversations +grow, branch, change execution slots and survive restarts. Retention must stay +within explicit resource limits without causing incorrect model state or +unbounded interference with other requests. + +The existing system encounters several difficulties: + +- Retaining many positions in a long history can consume substantial memory + and disk capacity. Different models incur different capture costs. +- Useful state can be overlooked when available prefixes differ between RAM + and disk. That causes avoidable prefill work and delayed responses. +- Transfer-buffer limits can prevent deep checkpoints from being persisted or + restored, even when the configured disk capacity is sufficient. +- Branches, subagents and independent conversations compete for retention. + A busy workload must preserve useful long histories while allowing peers + to progress. +- Model state is more than attention KV. Recurrent, speculative and multimodal + state introduce correctness requirements at specific positions. +- Existing measurements do not establish that a proposed replacement meets + latency and resource requirements at eight concurrent requests. + +These problems require an explicit correctness contract, measurable acceptance +criteria and a design whose costs can be inspected. They do not by themselves +determine a particular storage representation. + +## Goals and non-goals + +Goals: + +- Minimize request latency, including contention and queueing at concurrency + greater than one, while preserving efficient long-horizon continuation. +- Cover every existing model family through explicit capabilities and model + modules. All continuation-capable models are in the delivery scope. +- Preserve exact saved-state restoration and existing numerical-quality + requirements, including speculative execution. +- Support edits, branches, slot rotation, bounded eviction and restart reuse. +- Bound retained RAM, transfer staging, persistence queues and disk usage. +- Make cache decisions and their costs observable and regression-testable. + +Non-goals for the initial implementation: + +- Distributed caching or multiple server processes sharing one cache directory. +- Reading or migrating files from the old cache format. +- Replacing inference scheduling, sampling or model kernels as part of building + the new cache package. +- Guaranteeing identical sampled output between a fresh computation and a + restored prefix computed with a different floating-point execution shape. +- Forcing image/video denoising into an autoregressive continuation interface. + +Paged live KV and disk compaction remain separately evaluated extensions. + +## Glossary + +| Term | Meaning | +| --- | --- | +| Prefill | Execute the prompt tokens needed before generation can continue. | +| KV | Attention key/value rows retained from prior tokens. | +| Conversation | A logical history; it can outlive or move between execution slots. | +| Execution slot | A leased mutable model state in which a request executes. | +| Live frontier | The exact state currently reached in a slot, including executed generated tokens. | +| Checkpoint | A coherent, immutable saved boundary that can be restored. | +| Fixed/private state | State copied for a checkpoint rather than shared as append-only rows; its size depends on the model and configuration. | +| Chunk | An immutable range of shareable rows, initially targeting 2,048 tokens where the model layout permits. | +| Tail | A checkpoint's partial range that does not fill a chunk. | +| Lineage/provenance | The computation that produced particular state bytes and the inheritance of those bytes through restores. | +| Spill | Preserve borrowed rows before their live storage is overwritten. | +| Reservation | Budget capacity committed before a future allocation or transfer needs it. | +| Pin | A lifetime guarantee that prevents storage from being reclaimed while an operation uses it. | +| Compatibility identity | Model, state layout and execution configuration required for safe reuse. | +| Input identity | Tokens and relevant non-token inputs, such as images, for the reused boundary. | +| Manifest | A disk record describing a checkpoint and its required component files. | +| TTFT | Time to first token, including queueing, cache work and remaining prefill. | +| C | Concurrent requests; qualification includes C=1, 2, 4 and 8. | + +## How the system is designed now + +The research baseline is main `b39c530e`. The central lookup limitation also +remains in the inspected main revision `dea22cee`. Existing measurements belong +to their recorded baseline and settings; implementation qualification must +record a fresh matched baseline. See [Current design](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/current-design.md) for +the original source inventory and [Experiments](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/experiments.md) for evidence. + +### Serving, slots and opaque snapshots + +Serving schedules inference. `ContinuationCache` leases execution state, +matches compatible token prefixes and retains checkpoint records. +`TextModelRunner` supplies model-specific capture, restore and persistence. +The disk store currently depends on that runner interface. + +A checkpoint is opaque to common policy and restores as a whole. A recurrent +model cannot restore a checkpoint at position 10,000 and simply truncate its +state to position 6,000. A saved coherent boundary at or before the desired +position is required, followed by any remaining prefill. + +Live state and retained snapshots are distinct. The live frontier can include +generated tokens beyond the prompt checkpoint. Preserving that frontier avoids +recomputing generated history when a parent conversation branches. + +### RAM retention + +The cache has a record limit of 128 and a byte budget. Capture candidates +include stable boundaries, complete prompts, selected 2,048-token grid points +and learned shared-prefix boundaries. Eviction uses priority ranks, then LRU +within a rank; admission may refuse a checkpoint under byte pressure. + +In the research baseline, the stable boundary excludes the generation suffix; +up to four intermediate grid captures are selected. Learned divergence points +require at least a 512-token improvement over already reusable history. Removal +ranks are retry 0, history 1, covered continuation 2, and branch point/last +copy 3. The record limit does not grant permission to exceed the byte budget. + +Physical behavior differs by model: + +- Qwen 27B snapshots own copies of their state, including attention KV and + recurrent buffers. Deep captures therefore copy large payloads. +- Flash-Next already copies private mutable state while borrowing append-only + rows from a live slot. Before overwrite, needed rows are preserved into + backing blocks shared by affected checkpoints. Admission nevertheless + charges the full logical payload per checkpoint. +- Other model families have their own layouts and capabilities. Their complete + inventories must be checked against the implementation base. + +### Disk retention and lookup + +The disk tier stores one complete, checksummed payload per checkpoint, with +tokens and compatibility metadata. Files are published atomically and evicted +individually. The current design allows several processes to share a directory. + +Disk is consulted only when there is no RAM hit. A short RAM hit can therefore +hide a much longer usable disk checkpoint. Writes and restores also encounter +whole-payload staging limits. Streaming writes alone would not solve the +corresponding restore limit. + +The user-facing disk options are `--cache-disk DIR`, `--cache-disk-bytes` and +`--cache-disk-staging-bytes`; RAM has `--cache-ram-bytes`. Disk uses a prefix +tree per persistence identity. Ordinary writes less than 2,048 tokens past a +stored boundary are skipped, with exceptions for learned shared prefixes. +Restoring beyond a stable boundary requires an eligible fallback at or before +that boundary under the current contract. The redesign must preserve that +correctness requirement rather than simply maximizing token count. + +At the recorded baseline, disk eviction was global LRU. PR #409 proposed +removing covered intermediates first while protecting learned shared-prefix +entries. That policy proposal is distinct from chunk ownership and was not +part of the measured baseline. + +Historical issues also recorded repeated 4.1 GB Flash-Next files around 145k +tokens, retry captures refused under pressure causing 5–7 tokens of repeated +prefill, and disk-write/capture overlap raising 27B capture latency from about +20 ms to 57–230 ms. These configuration-specific observations motivated the +later experiments; they are not universal latency constants. + +### Evidence of the current limitations + +| Observation | Evidence and scope | +| --- | --- | +| A short RAM hit hid a longer disk checkpoint, causing 22,558 tokens of repeated prefill | Measured E2 W2 workflow; see E3 in [Experiments](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/experiments.md). | +| Qwen 27B captured approximately 10 GB at 149k tokens, taking 235–265 ms per checkpoint in the recorded run | Measured; configuration-specific. | +| Automatic staging prevented deep checkpoints from reaching disk | Measured in long-agent traces; the approximate 75k boundary depends on model, configuration and queued work. | +| Flash-Next already shares some physical RAM despite full-payload admission charges | Existing implementation and measurements; a full-copy comparison overstates its additional physical RAM savings. | +| Proposed designs improve several retention and persistence outcomes | Simulated E8 revision 2; proposed implementation performance remains unmeasured. | + +## Evaluated solutions + +### Hybrid approach — recommended + +The proposal separates mutable execution state, shared immutable rows and +private state at saved boundaries. One common package owns policy and storage; +model modules supply coherent state and device operations. + +#### Three kinds of state + +| Object | Contents | Lifetime and ownership | +| --- | --- | --- | +| Execution slot | Mutable live KV, recurrent state, positions and other model execution state | Leased to one executing request; allocations belong to the model adapter. | +| Immutable chunk | A shareable range of append-only rows from one computation | Shared by checkpoints that actually inherited those bytes; retained in RAM, disk, or both. | +| Checkpoint | Exact boundary, compatibility/input identity, private state, chunk references and partial tails | Immutable after capture completes; eligible for lookup only while all required components can be supplied. | + +A conversation does not own a slot permanently. Eight execution slots can +serve many more logical conversations over time, within the model's feasible slot count. Conversely, adding more +checkpoint records does not create more execution capacity. The initial +checkpoint limit remains bounded; slot count and retention limits are separate. + +For an attention-only layout, most retained payload consists of append-only +rows. For a hybrid recurrent model, a checkpoint also owns the complete +recurrent state at its boundary. Mutable rings, convolution history, kept +hidden rows and speculative state must be handled according to their actual +semantics, rather than assumed to be ordinary KV. + +```mermaid +flowchart TD + Request[Request and complete input identity] --> Lookup[Common cache: candidates and slot lease] + Lookup --> Live[Compatible live frontier] + Lookup --> Checkpoint[Coherent retained checkpoint] + Checkpoint --> Private[Private state at exact boundary] + Checkpoint --> Chunks[Inherited immutable chunks and private tails] + Chunks --> RAM[Protected live rows or retained RAM] + Chunks --> Disk[Durable disk dependencies] + Private --> Adapter[Model adapter: coherent bounded restore] + RAM --> Adapter + Disk --> Adapter + Adapter --> Slot[Mutable execution slot] + Live --> Slot + Slot --> Suffix[Execute remaining suffix and generation] +``` + +#### Why recurrent state needs exact checkpoints + +Consider a model that alternates attention and recurrent layers. Each recurrent +layer updates its state from hidden activations produced by all preceding +layers for the current token. Attention KV records only selected key/value +projections; it does not preserve all those hidden activations. + +Therefore, attention KV through position 12,000 does not let the cache derive +the recurrent state at position 6,000 or reconstruct it at position 12,000. +The cache needs a saved recurrent boundary and must execute any gap after it. +Saving every layer's missing activations would introduce a different, much +larger representation and is outside this proposal. + +Example: an edit first changes token 6,000. If coherent checkpoints exist at +4,096 and 8,192, only the earlier one can serve this edit. The request restores +4,096 tokens and executes the unchanged gap followed by the changed suffix. +It cannot use the recurrent state from 8,192 merely because some earlier KV +rows still match. + +#### Component descriptors and model modules + +Each adapter describes every required component of a coherent checkpoint: + +- Stable component ID, layout version, element representation and byte size. +- Kind: append-only shareable rows, window rows, or checkpoint-private mutable + state. A window-rows component is append rows of which a continuation reads + only the last `window_rows` (sliding-window attention): a checkpoint at row n + keeps the chunks from the one containing row n - `window_rows`, and shares + them with neighbouring checkpoints, so older chunks become unreferenced and + evictable instead of being copied whole into every checkpoint as private + state. +- Valid logical range, physical range and exact component position. +- Opaque storage handle and bounded transfer operations. +- Completion and lifetime requirements, including device synchronization. +- Model compatibility and boundary-specific non-token input identity. + +The common package must not infer every component length from the prompt +length. Target KV and draft KV can end at different positions. Pooled indexer +rows advance in blocks; a raw indexer ring can overwrite earlier entries. +Each has its own valid range and preservation rules. + +An illustrative Flash-Next inventory is: + +| Component | Proposed treatment | Position rule | +| --- | --- | --- | +| Target attention KV | Share append-only committed ranges | Target execution position. | +| MTP draft KV | Share only ranges the adapter certifies immutable | Draft position, independently validated. | +| Pooled indexer rows | Share completed immutable blocks | Number of completed pooled blocks. | +| Raw indexer ring | Save private chronological contents and metadata | Current ring window and cursor. | +| GDN state and convolution history | Save private state | Exact checkpoint boundary. | +| Kept hidden rows, residuals and execution metadata | Save whatever the numerical contract requires | Component-specific boundary. | +| Sampling or speculative bookkeeping | Preserve model-owned continuation state; initialize request-owned policy through serving | Explicit ownership and position contract. | + +This table is a starting inventory, not a substitute for auditing each mode. +Qwen's adapter must include DeltaNet, convolution and actual MTP/DFlash state +where present. DeepSeek's adapter must inventory compressed pools, windows, +indexers and mutable compressor state. Audio and multimodal modes require +their own complete identity and state inventories. + +Every existing model family must be accounted for. A family with a supported +continuation operation receives the appropriate module and qualification. +A family whose computation has no reusable autoregressive continuation state +declares that capability explicitly and retains its normal execution behavior. +The common package must not pretend that a diffusion denoising trajectory is a +token-prefix continuation. Additional reusable state for such models would +need an appropriate separately specified contract. + +#### Capture and borrowing + +At a coherent boundary, capture copies checkpoint-private state. Shareable +rows may remain borrowed from protected live storage instead of being copied +immediately. Already retained chunks are referenced directly. + +Borrowing is an ownership contract, not an unchecked pointer. The source slot +must preserve every referenced range before any operation overwrites it. +That includes rewind, reset, slot reassignment, destruction and speculative +rollback. A checkpoint becomes visible to readers only after its private state +and all component descriptions are coherent and ready. + +Partial tails are private to the checkpoint's lineage and boundary. They may +also borrow protected rows initially. Their eventual backing storage counts +against reservations. The design does not charge only recurrent state and +then forget the tail or outstanding spill obligation. + +Capture failure skips retention and allows inference to continue when the +live state remains valid. A device failure that invalidates execution follows +the normal request failure path; it cannot be hidden as a harmless cache miss. + +#### Sharing and provenance + +Two checkpoints can share rows if they descend from the same computation of +those rows. This occurs when they are captured from one live execution or when +one request restores an existing checkpoint and continues from it. + +Equal tokens alone are insufficient. Independent prefills can differ in +floating-point execution shape, producing different state bytes. Pairing a +recurrent checkpoint from one computation with KV from another could create +a state that never existed. + +The initial design therefore shares inherited bytes, rather than merging +independent cold computations by token hash. Optional byte deduplication would +require verified byte identity plus compatible component metadata; hashing +large device payloads has a cost and is not needed for the first version. + +Model/weights identity, state ABI, precision, tokenizer/template, context +policy and relevant adapters or speculative configuration constrain reuse. +Images and other non-token inputs must participate in identity at the affected +boundary. Two prompts containing the same image placeholder tokens but +different images must not falsely hit after those inputs enter the computation. + +#### Budget accounting and preservation before mutation + +The retained RAM charge is the sum of unique retained chunks, checkpoint-private +state and tails, metadata, and reserved backing for still-borrowed rows. +Transfer staging and queued jobs are separately bounded and included in the +overall resource ledger. An allocation must have one physical charge even if +many checkpoints reference it. + +Borrowed rows cannot count as free. If a slot lends 6 GiB of rows to several +checkpoints, resetting it may require 6 GiB of preservation. A spill reservation +must have physical backing with pages already committed, rather than only a +promise to allocate later. Reserve that backing before accepting the retention +obligation. The ledger distinguishes free committed backing, assigned spill +reservations and materialized chunks, while charging each physical allocation +once. Assigning a reservation to its chunk does not allocate or double-charge it. + +The review's ROCm 7.2 allocation measurements report about 25 GB/s of page +commit throughput, around 4.5 ms per 111 MB, while the allocation blocks other +HIP calls. Committing 6 GiB on reassignment could therefore cost approximately +258 ms before copying any rows. This estimate exposes a latency hazard; it is +not a measured reassignment result. The copy adds its own cost. + +Create and commit backing within the feasible memory envelope during model +initialization or an explicit inference-quiescent period. Reuse released backing. +Do not refill a pool opportunistically while peers execute: [PR #445](https://github.com/gufo-org/gufo/pull/445) +records an approximately 8 ms decode stall from background spare-block refill. +If committed capacity is insufficient, retire eligible retention or decline the +capture rather than silently introducing a request-path page-commit allocation. + +#### Idle spill and independent transfer streams + +While a slot is idle, background preservation materializes referenced borrowed +rows into the committed backing. Prefer a slot whose outstanding preservation +has completed when assigning an unrelated request. Record the residual spill +wait when reassignment arrives earlier; idle time cannot be assumed available. + +An idle-spill worker pins the source ranges and their slot generation, transfers +bounded pieces and publishes completed backing under the same mutation guard. +The scheduler and cache coordinate that guard before a slot becomes executable +again. Cancellation or a request arriving mid-spill must not overwrite a pinned +source or publish a partially copied chunk. Already preserved ranges remain +usable; required remaining ranges are completed or their eligible retention is +retired before mutation. A slot becoming idle must not force an unbounded eager +copy of every possible checkpoint. + +Every in-flight transfer leases its own pooled stream and completion event; +concurrent transfers must not queue behind an unrelated bulk copy on one shared +stream. PR #445 records a 1,656-token prefill delayed about 24% by that pattern. +Streams return to the pool only after completion. This prevents avoidable FIFO +serialization, but does not eliminate device bandwidth contention. + +Qualify idle spill, zero-idle reassignment and reassignment during a copy. The +replacement conversation B's end-to-end TTFT and already decoding peers' +per-token latency must pass the existing per-request/phase 5% and 3 ms gates +against matched baseline controls. Report page-commit, residual-spill and stream +wait separately; an average throughput improvement cannot hide those regressions. + +Before mutation: + +1. The adapter identifies the ranges that will become invalid. +2. The cache determines which readers and retained checkpoints still need them. +3. Required backing is reserved and the rows are preserved, or eligible + checkpoints are retired before mutation proceeds. +4. Outstanding transfers and reader pins complete before protected storage + can be overwritten or released. + +This sequence must be transactional with respect to mutation. An allocation +failure cannot leave published checkpoints pointing into overwritten storage. +If a pin prevents reclamation, the affected operation waits or chooses another +safe destination; it must not silently violate the pin to stay within budget. + +Live slot allocations remain a separate resource claim. On Strix Halo, host +and device allocations consume the same physical memory capacity, so the +server must report the combined total without double-counting borrowed views. + +#### Lookup, slot selection and restore + +One prefix index represents compatible checkpoints across RAM and disk. +Availability belongs to each component: its bytes may be resident, durable, +or both. A partial manifest with missing required state is not a usable hit. + +Lookup identifies the deepest coherent compatible boundary. It also exposes +the available live frontier, shorter resident candidates and transfer costs. +An exact compatible live continuation should preserve its cheap path. A short +RAM hit must no longer hide a much deeper disk candidate. + +Latency is the first priority. A longer disk prefix is valuable when the +avoided prefill exceeds its restore cost. Initial behavior should be explicit +and deterministic, with the longest usable prefix as the default retained +candidate; any policy that chooses a shorter boundary for lower estimated +latency must be measured, tested and logged with its reason. It must not rely +on the old blanket rule that every RAM hit wins. + +Restore pins the chosen state, leases a destination and preserves that +destination's outstanding borrowed rows before overwrite. The adapter loads +all required components and validates their positions. The slot becomes +executable only after completion. Cancellation or partial failure invalidates +the destination before reuse; an earlier valid checkpoint or cold prefill can +then be attempted. + +In the initial implementation, restoring into a different slot still copies +the full required prefix into contiguous live storage. Shared retained chunks +save retention and capture work; they do not make cross-slot restore zero-copy. + +#### Checkpoint selection and eviction + +Start with bounded records, existing priority ranks and a 2,048-token grid +where compatible with the layout. Candidate boundaries include stable prompt +boundaries, learned shared prefixes, useful message/edit boundaries and recent +grid points. Persisting every possible boundary is unnecessary and can itself +increase response latency, fixed-state memory and writes. + +A recurrent checkpoint requires stopping execution at its exact boundary. +Message boundaries, learned prefixes and grid points can split a prefill pass, +shrink kernel batches and add capture/transfer synchronization. The density +cost includes those effects alongside private bytes and expected reuse. +Prefer candidates aligned with planned prefill passes; coalesce nearby optional +boundaries. Do not change an exact required boundary by rounding its tokens. + +The current baseline skips grid points within 128 tokens of the prompt end +because they split the final pass beside an already planned complete-prompt +checkpoint. The new policy must retain the measured benefit of avoiding such +redundant splits, with adapter-specific pass alignment rather than assuming +that a 2,048-token storage chunk is always an efficient compute boundary. + +For the 6,000-token subagent example, capturing exact private state can require +a pass ending at 6,000. It is worthwhile only if predicted/observed follower +reuse pays for the extra split and synchronization. Otherwise the subagent +continues from the earlier coherent checkpoint and the optional learned capture +is skipped. Instrument pass count, pass sizes, synchronization and marginal +capture cost, and test both aligned and unaligned candidates. + +Retention value depends on future saved work and actual resource cost. A useful +initial policy favors shared branch points and last useful continuations, +while dropping retries and covered history according to existing ranks. +Any change to admission ceilings or eviction priority is reviewed separately +from the storage representation so its effect can be measured. + +Evicting a checkpoint releases its private state and references. A shared chunk +is freed only after its last checkpoint reference, reader pin and persistence +pin disappear. Evicting one child must not destroy its parent's reusable rows. +RAM eviction may leave a durable disk checkpoint; disk eviction updates the +index and removes bytes only when safe. + +#### Disk representation and bounded transfers + +A checkpoint manifest records tokens, identities, component positions, +checksums, chunk references and private-state/tail locations. Full chunks are +written once while referenced in the disk tier. Each new boundary writes its +private state, tails and any new chunks; it does not rewrite every earlier row. + +Both writes and restores stream in bounded buffers. Queue admission reserves +metadata, immutable-source lifetimes and transfer capacity. A checkpoint larger +than staging must still be transferable. No serialization fallback may build +the entire payload in a host buffer. + +The persistence worker is bounded. Under pressure, redundant or low-value +jobs may be skipped or coalesced safely; queue depth and pinned bytes must not +grow without limit. Optional writes yield to latency-sensitive model work. +Device-copy and storage interference must be measured under concurrency, +including peers already decoding. + +#### Publication, crash recovery and format upgrades + +The initial version gives one server process exclusive ownership of a cache +directory. A process lock enforces that rule; eight concurrent requests within +that process follow the feasible model/mode capacity matrix. A second process receives a clear directory +ownership error or uses another directory. + +Publication order is: + +1. Write missing chunks and private payloads to temporary files. +2. Verify checksums and make dependency files durable, including their directory + entries, before publishing anything that references them. +3. Write and fsync the manifest, atomically rename it into the published + namespace, and make that rename durable. +4. Mark the checkpoint durable in the index and release writer reservations. + +A queued or in-flight write is not durable. Graceful shutdown can drain the +bounded queue; abrupt termination preserves only published checkpoints. +Startup reads and validates bounded manifests, identities and declared lengths, +then checks referenced file existence and sizes. It does not scan/checksum the +complete payload of every chunk. The current `IndexExistingFiles` path reads +and verifies entire images; carrying that behavior into the new store could +spend tens of seconds scanning tens of GB before accepting a request. + +Index entries discovered this way are structurally available but have unverified +payloads. During bounded streaming restore, verify each dependency's checksum +and private-state/tail payload. Bytes may be copied into an invalid destination +incrementally, but that slot becomes executable only after every required +checksum and component-position check passes. A failed check invalidates the +destination and affected dependency references before any fallback executes. +Once-verified immutable dependencies may cache verification for their protected +file identity; replacement or mutation invalidates that result. + +Corrupt/incomplete entries are excluded when detected. Orphan reclamation follows +complete manifest-reference discovery and runs outside the serving-critical +startup path. Readers pin dependencies so concurrent eviction cannot remove a +file in use. Gate time to readiness separately from first restored-request TTFT, +and assert that startup payload reads stay bounded by metadata, not total cache +payload size; a restart benefit cannot be claimed by ignoring index-build time. + +Old-format compatibility is not required. The store recognizes its format +version and rebuilds incompatible legacy cache entries as requests arrive. +Cleanup is confined to files recognized as Gufo-managed cache files in the +configured directory; it does not recursively delete unrelated contents. +Unknown future formats are not interpreted as the current format. + +Use a versioned namespace so rollback can cold-start safely. No offline +migration is required. The temporary capacity needed for writes and cleanup +must still fit the disk budget; rebuilding must not leave an unbounded legacy +archive beside the new store. + +#### Correctness contract + +Capture/restore must reproduce the exact coherent model-owned state saved at +the boundary: required bytes, positions, valid ranges and execution metadata. +Derived transient buffers may be reconstructed only under an explicit model +contract that preserves the required numerical behavior. + +This is distinct from requiring a fresh prefill with different batch shapes to +produce identical bytes or sampled strings. Existing quality requirements +remain strict. Tests cover restored state, next-step numerical behavior and +actual speculative rollback; token-prefix equality cannot replace those checks. + +#### Worked examples: a conversation through time + +The following sequence uses logical conversations A, B and C. Token counts +are illustrative; intervals use `[start, end)`. Each checkpoint denotes a +coherent boundary, not just a token count. Chunk size is 2,048 in these examples. + +**1. A starts and grows in the same slot.** + +| Time | Conversation event | Slot and cache effect | +| --- | --- | --- | +| t0 | A: “Inspect this repository and explain its architecture.” The formatted prompt ends at 10,240 tokens. | Slot 1 prefills the prompt. Capture A10 saves private state and describes five full chunks. Those rows can stay borrowed with reserved spill capacity. | +| t1 | The assistant executes tools and generates another 512 tokens. | Slot 1 reaches a live frontier of 10,752. A10 remains a distinct frozen prompt checkpoint. | +| t2 | A appends tool results and asks for an implementation. The next prompt extends the exact executed history. | Reuse the compatible live frontier. Execute only the new suffix; do not restore A10 unnecessarily. | +| t3 | A reaches a prompt boundary of 12,288. | A12 references the same first five chunks and a sixth chunk. Its private state is a new full copy at 12,288. | + +The logical distinction at t1 matters: the retained prompt checkpoint does +not automatically include every generated token. If another request needs +that executed frontier, freeze a coherent checkpoint before it is mutated. +Feeding those generated tokens through a new prefill is not necessarily the +same numerical history as continuing the actual execution. + +**2. B replaces A; A later resumes in another slot.** + +B is unrelated and needs slot 1 while A is idle. Before B overwrites the +borrowed ranges, the cache preserves A's needed rows into backing chunks. +A10 and A12 both reference the common first five chunks. Preservation does +not create five separate copies for each checkpoint. + +A later returns while slot 1 is busy. Slot 2 restores A12: six chunks plus +private state, followed by prefill of A's new suffix. The retained prefix exists +once in the pool, but slot 2 receives its own live copy. This improves retained +capacity without removing the transfer cost or slot 2's live allocation. + +**3. C is a subagent with a shorter shared prefix.** + +C receives A's system prompt and tool definitions through token 6,000, then +asks: “Check the error handling independently.” Assume the nearest compatible +earlier checkpoint is at 4,096. + +1. C restores the first two chunks and private state at 4,096 into slot 3. +2. C prefills the unchanged gap of 1,904 tokens to reach 6,000. +3. The cache captures C6, with inherited chunks `[0, 4096)`, a private tail + `[4096, 6000)`, and private state at exactly 6,000. +4. C then executes its task-specific suffix. +5. A later subagent with the same compatible 6,000-token prefix restores C6 + directly and executes only its own suffix. + +A's third full chunk covers `[4096, 6144)`, extending past the divergence. +The initial design does not treat that entire chunk as reusable by C. The +partial tail stays private. Model-specific components may have additional +alignment constraints; their descriptors, rather than this simple token +arithmetic, govern what can actually be shared. + +**4. Several subagents start simultaneously.** + +Suppose seven subagents arrive before C6 has been captured. They cannot all hit +a checkpoint that does not yet exist. Some may reuse 4,096 and independently +compute the gap; independent new rows retain distinct provenance. + +The cache may coordinate access to an already pending shared-prefix capture, +but waiting for it must not impose a long global stall. Whether bounded waiting +beats duplicate prefill is a measured latency decision. The first release must +be correct for both outcomes and report duplicate work. It does not promise +perfect deduplication of simultaneous cold starts. + +**5. The parent returns after its children.** + +A reaches 24,576 tokens and launches children that inherit this boundary. +Their retained prefix chunks are shared; each child adds private state and +its own suffix. When A takes another turn, its own live frontier or A24 remains +eligible independently of the children. + +Under tight RAM, A24 might survive only on disk. A shorter resident checkpoint +at 4,096 must not hide it. The index exposes both candidates, and restore can +recover A's deeper compatible state. Whether that wins latency depends on disk +read cost versus executing the avoided 20,480-token gap. + +In the recorded current-system W2 failure, a short RAM hit hid a deeper disk +entry and caused 22,558 tokens of repeated prefill. The proposed lookup fixes +that blind spot; shared retention additionally reduces pressure on the parent +checkpoint. These are distinct improvements and should have distinct tests. + +**6. A user edits an earlier message.** + +A's history is now 30,000 tokens, but the user edits a message beginning at +18,500. A checkpoint at 24,576 is too late. A retained coherent checkpoint at +18,432 can restore the unchanged prefix, leaving a 68-token gap before the edit. + +After the edit, new suffix rows have new provenance. Older checkpoints can +remain useful for the old branch, subject to budget. There is no permission +to splice the old recurrent state into the edited branch merely because some +later text happens to be identical. + +**7. Eight slots are active within a feasible model/context envelope.** + +| Slot | Workload | Cache requirement | +| --- | --- | --- | +| 1 | A: long coding-agent continuation | Preserve its cheap live path and useful deep checkpoints. | +| 2 | B: unrelated chat | Bound admission and lookup overhead on a short request. | +| 3–5 | C, D, E: children of A | Share inherited retained rows and preserve independent mutable state. | +| 6 | F: another long independent conversation | Allow useful retention without assuming overlap with A. | +| 7 | G: conversation resumed after restart | Stream restore without monopolizing cache metadata locks. | +| 8 | H: short request while peers decode | Measure its TTFT and effects on peers' inter-token latency. | + +If another subagent arrives, the serving scheduler queues it until a compatible +slot is available. The cache retains history; it does not create a ninth slot. +Slow disk I/O for G must not hold a global metadata lock across the transfer. +Shared device-copy bandwidth can still affect peers, so bounded transfer size +alone is insufficient evidence of good concurrency latency. + +For admitted C=8 configurations, qualification includes this mixed workload +alongside homogeneous chats +and long-agent runs. Aggregate throughput must not conceal one starving user +or a parent that loses all useful continuation points. + +**8. Independent histories have little overlap.** + +Eight unrelated long conversations cannot share their different prefixes. +The design still avoids storing every earlier row again for each checkpoint +within each conversation, and it bounds transfers. However, the sum of eight +distinct live histories remains large. Benefits depend on checkpoint count and +actual shared computation, not the number of users alone. + +For the measured 27B layout, 100,000 tokens at 65,536 bytes/token consume about +6.10 GiB of attention KV. Eight live copies require about 48.83 GiB for that +component alone, before weights, recurrent/draft state, scratch space and +retained-cache obligations. This is an estimate from the measured size model, +not proof that eight such requests fit the target machine. + +**9. Budget pressure evicts a child checkpoint.** + +A24, C24 and D24 reference the same inherited chunks. Evicting C24 frees its +private state and C-only suffix storage. The common prefix stays because A24 +and D24 still reference it. If D is restoring, its pins also keep required +storage alive even if its cache record is concurrently retired. + +If a new capture cannot reserve its private state and eventual spill, it is +skipped. The live request can continue safely. The event includes the requested +bytes, admission reason and protected resources so refusals can be diagnosed. + +**10. The server restarts at long context.** + +A reaches a durable checkpoint at 100,352. A later capture at 102,400 is still +queued when the process terminates abruptly. On restart, the index discovers +100,352 and restores its complete state. It cannot claim 102,400 as a hit. +Remaining history is prefilled from the last valid durable boundary. + +Unlike a whole-file staging requirement, bounded streaming permits restoration +even when the checkpoint's total payload exceeds the transfer-buffer budget. +Actual restart benefit depends on which checkpoints completed publication, +not merely which capture calls succeeded. + +**11. A shared chunk is missing or corrupt.** + +Several manifests reference chunk X. If X fails validation, each checkpoint +requiring X is unavailable unless another verified copy can provide it. An +earlier complete checkpoint or a cold prefill remains a correctness fallback. +The index must not restore valid private state alongside an incomplete prefix. +This larger corruption blast radius is a cost of sharing compared with fully +self-contained files. + +**12. An image changes while the text looks identical.** + +Two requests both ask “Describe this image,” but attach different images. The +prefix before image computation may be reusable. The boundary after the image +requires its supplemental input identity to match. Token placeholders alone +do not establish compatibility. This rule belongs in functional tests as well +as adapter identity construction. + +#### Expected resource savings and their limits + +For one linear history, let `F` be private bytes per checkpoint, `R` shareable +bytes per token, and `p_i` the saved positions. A full-copy representation costs +approximately: + +```text +full snapshots = sum(F + R * p_i) +shared storage = checkpoint_count * F + R * max(p_i) + private_tails +``` + +The shared estimate excludes metadata, transfer scratch, live allocations, +alignment and temporary publication space. Branches add their genuinely new +rows and private partial tails. Independent lineages must be counted separately. + +Using the measured 27B DFlash2 constants (`F = 243,700,000 bytes`, +`R = 65,536 bytes/token`), retain eight aligned checkpoints at 86,016, +88,064, 90,112, 92,160, 94,208, 96,256, 98,304 and 100,352: + +| Representation | Estimated retained payload | +| --- | ---: | +| Eight complete copies | 47.32 GiB | +| One shared prefix plus eight private-state copies | 7.94 GiB | +| Payload reduction for these same retained boundaries | 83.2% | + +This is an arithmetic estimate, applicable to retained RAM for a full-copy +model and to deduplicated disk payload. It is not an end-to-end memory +measurement. Flash-Next already shares some physical RAM, so this comparison +does not establish an equivalent additional RAM saving for that model. + +Private state remains substantial: the recorded Flash-Next MTP layout has +about 113.8 MiB of fixed state, and 27B DFlash2 about 232.4 MiB. Many dense +checkpoints can still consume GiB even with perfect row sharing. Chunk size +and density must be chosen together rather than declaring checkpoints cheap +without a bound. + +The recorded chunk-file microbenchmark added roughly 13% read/write overhead +relative to a large file. Optional disk compaction could reduce file overhead, +but introduces extra writes and temporary capacity. It remains disabled until +measured restore latency justifies it. Published simulation write volumes +exclude compaction. + +### llama.cpp-like approach + +The relevant pattern combines reuse within a live slot, small context +checkpoints for state that cannot simply be truncated, and a host prompt cache +for displaced slot state. The inspected source at `41abbfd59` maintains +checkpoint spacing and a bounded checkpoint list. Its host cache allocates +complete target/draft state plus context checkpoints, removes contained older +prompts and evicts oldest entries when capacity is needed. +See [slot/checkpoint implementation](https://github.com/ggml-org/llama.cpp/blob/41abbfd59/tools/server/server-context.cpp) +and [host prompt cache](https://github.com/ggml-org/llama.cpp/blob/41abbfd59/tools/server/server-task.cpp). + +Applied to Gufo, this would keep efficient same-slot continuation and cheap +recurrent rollback points while retaining whole state when a conversation +leaves its slot. Automatic persistent shared storage would be additional work. + +Advantages: + +- Fits a local serving model and preserves a simple live-slot fast path. +- Avoids repeatedly copying full attention history for every in-slot rollback + boundary. +- Can be delivered with less allocator/kernel change than paged serving. + +Disadvantages for the intended workload: + +- Moving conversations between slots still requires complete retained state + and transfers; multiple displaced histories can consume substantial RAM. +- Host-cache supersession needs care for Gufo's useful older branch points. +- Automatic restart persistence and cross-checkpoint disk sharing remain to + be designed. + +This is a strong source of ideas for live-state handling, but alone does not +address all retention and persistence requirements of the eight-request workload. + +### SGLang-like approach + +SGLang organizes prefix KV in a radix tree. Hybrid-model checkpointing treats +recurrent state as saved boundaries rather than reconstructible token rows. +Its component-based unified tree validates a candidate boundary against all +required components. HiCache extends reuse through device, host and configured +storage tiers. See [hybrid-model caching](https://pytorch.org/blog/hybrid-models-meet-sglang-more-than-full-attention/), +[unified radix cache](https://www.lmsys.org/blog/2026-08-11-unified-radix-cache) +and [HiCache design](https://docs.sglang.io/docs/advanced_features/hicache_design). + +A Gufo adaptation would make shared tree storage more directly responsible +for request KV, with coherent recurrent checkpoints and tier transfers attached +to the tree. This is more ambitious than initially restoring shared retained +chunks into today's contiguous slots. + +Advantages: + +- Shared-prefix structure naturally represents parents, children and many + request histories. +- Component validation makes the difference between traversal depth and a + genuinely reusable hybrid-model boundary explicit. +- The architecture provides useful precedents for tiered storage and + independently reclaimable recurrent checkpoints. + +Disadvantages for Gufo: + +- Directly adopting paged/shared live state requires allocator and execution + integration across model families, beyond retaining immutable checkpoints. +- Multi-tier policies and component relationships add implementation and + review complexity. +- Published upstream throughput or latency results do not qualify Gufo's + kernels, unified-memory hardware or eight-request workloads. + +The recommended design adopts shared-prefix and component-validation ideas, +with a narrower initial execution integration. SGLang's full architecture is +a useful longer-term comparison if live-slot duplication becomes the main limit. + +### vLLM-like approach + +vLLM automatic prefix caching uses reusable blocks keyed by prefix-related +hashes, with reference counts for requests using those blocks. Its hybrid +manager coordinates different state groups and requires a boundary supported +by the required groups. The versioned cache configuration distinguishes Mamba +`all` and `align` strategies with model-dependent support. +See [prefix caching, v0.22.1](https://docs.vllm.ai/en/v0.22.1/design/prefix_caching/), +[cache configuration, v0.22.1](https://docs.vllm.ai/en/v0.22.1/api/vllm/config/cache/) +and [hybrid manager design](https://docs.vllm.ai/en/stable/design/hybrid_kv_cache_manager/). + +Applied to Gufo, this would introduce block-managed live KV and corresponding +attention access, plus a checkpoint policy for hybrid state. Persistence would +need its own store or integration; block prefix caching alone does not define +Gufo's restart semantics. + +Advantages: + +- Direct sharing of live prefix blocks can reduce duplication among active + requests, the main memory limitation left by the initial hybrid proposal. +- Block allocation and reference counting are well suited to concurrent + request lifecycles. +- Multiple required state groups are handled explicitly. + +Disadvantages for Gufo: + +- Requires significant integration with model allocators and attention kernels. +- Recurrent state sizes and block alignment can constrain reuse granularity + or introduce padding; the best policy depends on the actual layout. +- Supported combinations of recurrent caching, speculative modes and storage + must be verified per model/version. + +Upstream documentation evolves. The research's specific model/block-size +examples are not universal constraints. This RFC evaluates the architectural +pattern rather than promising compatibility with a particular upstream backend. + +### Keep the current design + +Keep the existing opaque snapshots and independent disk files unchanged. +This alternative requires no redesign implementation and preserves today's +model-specific capture/restore paths and per-file corruption isolation. + +Its costs and defects remain: full-copy layouts retain/copy large prefixes +per boundary, disk payloads repeat shared history, whole-payload staging limits +deep persistence/restores, and shorter RAM hits can hide deeper disk entries. +Useful dense boundaries remain expensive and separate live-slot allocations +still limit concurrency. This option provides the comparison baseline; work to +improve the current cache is outside this RFC's implementation scope. + +### Other approaches considered in the research + +**KV-only diffs.** Persist only new rows after each boundary. This omits required +recurrent/private state for Gufo's hybrid models and cannot restore a coherent +checkpoint. Adding exact private state and safe shared ownership turns it into +the recommended hybrid representation. + +**A chain of complete deltas and periodic keyframes.** Each delta carries new +rows and complete end-state. It can work, but eviction and recovery become +coupled to chains. Immutable chunk references make dependencies explicit and +allow branches to share a common prefix. Disk compaction may later create +larger extents without introducing GPU-generated full-copy keyframes. + +**Chunked KV with paged live execution.** This is the more ambitious direction +represented by the SGLang/vLLM-like options. It addresses live duplication as +well as retained storage. It remains a separately qualified extension rather +than a prerequisite for building the new common package. + +**External stores such as LMCache, and local engines such as ds4.** They are +additional integration references, rather than a sixth complete Gufo design. +An external store still needs coherent recurrent state, complete compatibility +identity and safe ownership. Importing a backend does not remove those adapter +requirements. See [LMCache hybrid-model support](https://docs.lmcache.ai/mp/hybrid_models.html) +and [ds4](https://github.com/antirez/ds4). This RFC makes no unverified claim +about their measured performance on Gufo. + +### Comparison table + +The columns describe architectural adaptations to Gufo, not a benchmark ranking +of upstream products. Green means a good architectural fit for the row; yellow +means conditional support, additional work or a tradeoff; red means the scoped +approach leaves a material requirement unresolved. Colors express design +assessment, not implementation qualification. Short reasons accompany each. + +| Feature / decision point | Hybrid, recommended | llama.cpp-like | SGLang-like | vLLM-like | Current | +| --- | --- | --- | --- | --- | --- | +| Same-slot long continuation | 🟢 Preserve live frontier | 🟢 Natural slot reuse | 🟢 Reuse live path | 🟢 Reuse live blocks | 🟢 Existing fast path | +| Cheap additional retained boundaries | 🟢 Copy private state, share rows | 🟢 Cheap in-slot checkpoints | 🟢 Shared rows + checkpoints | 🟡 Hybrid state policy/alignment matters | 🟡 Flash shares; 27B still copies | +| Shared retained prefixes across branches | 🟢 Inherited chunks | 🟡 Whole displaced slot states | 🟢 Shared radix paths | 🟢 Shared blocks | 🟡 Model-specific RAM sharing; full disk copies | +| Independent long histories | 🟡 Distinct rows still cost memory | 🟡 Whole histories still retained | 🟡 Distinct rows still cost memory | 🟡 Distinct rows still cost memory | 🔴 Many complete retained copies | +| Live memory across eight related requests | 🟡 Separate live slot copies initially | 🟡 Depends on live allocator adaptation | 🟢 Shared live prefix design | 🟢 Shared live block design | 🟡 Separate slot allocations | +| Cross-slot restore without full-prefix copying | 🔴 Initial contiguous restore copies rows | 🟡 Depends on live allocator adaptation | 🟢 With shared paged execution | 🟢 With block-managed execution | 🔴 Full restore path | +| Automatic restart retention with shared disk payload | 🟢 Specified manifest store | 🔴 Additional automatic disk design needed | 🟡 Storage backend and state support required | 🟡 Additional persistence integration required | 🔴 Persistence exists, but payload duplicated | +| Bounded deep writes and restores | 🟢 Required in both directions | 🟡 Must add bounded persistence | 🟡 Depends on tier/backend integration | 🟡 Depends on storage integration | 🔴 Current whole-payload staging limit | +| Exact recurrent boundary restoration | 🟢 Explicit component contract | 🟢 Exact saved checkpoints | 🟢 Required component boundary | 🟡 Model/mode capability verified | 🟢 Existing coherent snapshots | +| Incremental delivery through Gufo PRs | 🟢 Package, backing, RAM, disk, adapters | 🟢 Smaller execution changes | 🟡 Wider allocator/execution changes | 🟡 Wider allocator/kernel changes | 🟢 Existing implementation | +| Disk corruption isolation | 🟡 Shared dependency affects many entries | 🟡 Depends on added disk design | 🟡 Shared-tier dependency handling | 🟡 Shared-store dependency handling | 🟢 Independent complete files | +| Evidence for admitted per-model concurrency workloads | 🟡 Qualification required | 🟡 Qualification required | 🟡 Qualification required | 🟡 Qualification required | 🟡 Capacity matrix and matched controls required | + +The hybrid is recommended because it addresses repeated retained payload and +deep persistence while preserving current execution paths for incremental +delivery. Its largest unresolved resource limitation is separate live-slot +memory. If measurements show that this prevents the intended workload, paged +live state must be prioritized rather than declaring the first release sufficient. + +## Success criteria and evaluation + +Correctness is a requirement, not a weighted optimization. After correctness, +evaluate tradeoffs in the agreed order: latency, RAM, disk space and write volume. +Lower write volume is not sufficient justification for a request-latency +regression. Similarly, adding dense checkpoints should demonstrate useful +latency improvement against the RAM they retain. + +### Acceptance contract + +| Area | Required evidence | +| --- | --- | +| Correctness | Exact coherent restored state; compatible inputs only; correct target/draft positions; existing numerical-quality checks pass. | +| Reuse | Expected prefill and restored-token work is asserted per request, including edits, forks, rotation and restart. | +| Latency | Matched request/phase timings, including TTFT, capture, restore and affected decoding; preserve repository gates of 5% and 3 ms. | +| Reassignment / peer progress | Replacement B's TTFT and decoding peers' per-token latency pass matched 5% and 3 ms gates for idle, zero-idle and mid-spill reassignment; allocation and copy waits are attributed separately. | +| RAM | Peak total physical allocation and retained unique bytes/reservations stay bounded; distinguish live state, weights and scratch. | +| Disk / restart | Referenced, temporary and orphan bytes are accounted for; readiness time and first-restored-request TTFT are gated separately; startup reads metadata only and restore validates payloads before execution. | +| Failure handling | Cancellation, allocation/transfer failure, corrupted data and crashes release resources and prevent partial-state execution. | +| Model coverage | Every family/mode has capabilities, a frozen feasible capacity row and a qualification record; infeasible C/context combinations are excluded explicitly. | + +Use C=1, 2, 4 and 8 only where the per-model capacity matrix admits that +configuration. Cover one long coding agent, parent/subagent forks, independent +chats, mixed short/long arrivals, more histories than slots, edits, tight budgets +and deep restarts. Include histories around 100k–150k where feasible and shorter +contexts at higher concurrency. Model support does not imply eight simultaneous +long histories fit that model on this machine. + +### Per-model capacity matrix — required before implementation + +During preparation, freeze the planning matrix for each model artifact, +precision, draft mode, configured context, active request depth and concurrency +before implementation. Measure or +validate weights/sidecars, live-state allocation, scratch, committed backing, +private checkpoints, staging and headroom together. Admission must stay inside +the resulting envelope. An unknown row is an unmet planning prerequisite, +rather than an implicit promise to run every C/context combination. + +The current evidence supplies starting points, not new-cache qualification: + +| Model / mode | Observed starting envelope | C=8 / long-context constraint | Required planning result before implementation | +| --- | --- | --- | --- | +| Flash-Next UD-Q4_K_XL + Q8_0 MTP | Historical C=2 server configured at 260k context; one history reached about 149k. C=4 traces used a 131,072-token configured context. | Approximately 114 GB of weights on 125 GiB visible memory leaves a narrow working margin. Eight long live histories are excluded; retained sharing cannot make them fit. | Freeze C=1/2 long-horizon and feasible higher-C short/mixed depths with committed spill backing included. Configured context alone does not prove all slots can reach it together. | +| Flash-Next AR | Payload probes exist; speculative state differs from MTP. | MTP's concurrency envelope cannot be copied unchanged; long C=8 remains unqualified. | Measure a separate AR live/scratch/backing envelope and state the admitted C/depth combinations. | +| Qwen 27B UD-Q8_K_XL + Q8_0 DFlash2 | Historical C=2 server configured at 256k; one history reached about 149k. C=4 traces used 131,072 configured context. | Eight 100k histories need about 48.83 GiB of attention KV alone; weights, draft state, committed backing and scratch are additional. | Freeze feasible C/depth/budget combinations; C=8 is admitted only after the full memory sum and matched workload fit. | +| Qwen 27B Q8 AR and Q4 AR/DFlash2 | AR size probes exist; Q4 and draft combinations are separate functional profiles. | Precision/mode changes weights and resource claims; no universal C=8 allowance. | Establish artifact-specific envelopes; do not infer qualification from the Q8 DFlash trace. | +| DeepSeek V4 Flash AR/DSpark | No matched continuation-capacity campaign in this research. | Unqualified; compressed KV alone does not prove feasibility. | Inventory and measure each supported mode; freeze its supported C/context matrix. | +| Qwen ASR and TTS | Separate execution/capability contracts; no continuation-capacity result here. | Do not apply the text C=8 gate blindly. | Declare applicable continuation operations, concurrent capacity and workload-specific input/history limits. | +| Qwen Image and MiniMax H3 | Image/video generation uses different execution state. | Autoregressive continuation gates apply only to capabilities actually exposed. | Record supported/unsupported continuation capabilities and their own feasible execution envelopes. | + +An unqualified capacity row cannot be admitted until its planning result exists. +Long-horizon and concurrent personas get separate admitted rows; a short C=8 +result cannot replace the long-agent requirement, and infeasible long C=8 is +documented rather than treated as a failing cache optimization. Changes to model +artifacts, allocation policy or committed capacity require revalidating the row. + +### Client history transformations + +Qualification includes thinking-on conversations whose clients omit +`reasoning_content` from later history, beside clients such as Pi that replay +reasoning. It also includes a bridge that rewrites the last user message when +copying it into history, with unrelated short requests filling RAM between turns. +These shapes exercise stable-boundary checkpoints and frozen generated +frontiers, not merely append-only exact prompt growth. + +Use `cache-growth` for omitted/replayed reasoning and select `cache-bridge` +explicitly: it is not included in `all`. Reproduce the shapes from +[#336](https://github.com/gufo-org/gufo/issues/336) and +[#462](https://github.com/gufo-org/gufo/issues/462), asserting compatible restored +boundaries, suffix work, uncached-control correctness and per-request latency. +Run them with new-cache slot rotation, memory pressure, branches and restart. +No fixes to the current cache are proposed as part of those scenarios. + +Compare equivalent retained boundaries and workload histories for resource +claims. Also run fixed-budget comparisons to measure how improved capacity +changes useful reuse. These answer different questions and should be reported +separately. Count private tails and fixed state, not just deduplicated KV. + +Correctness runs on the candidate. Main supplies matched timing controls for +affected histories and suspected regressions, with the same toolchain, model +artifacts, harness, settings and cache history. Do not average regressions away +across requests. Investigate noisy cases with affected alternating controls; +keep inconclusive evidence visibly unqualified and do not widen tolerances. + +### What the research establishes + +- Measured checkpoint size constants, capture/restore costs and repeated work + demonstrate concrete problems in the current system. +- E8 revision 2 models actual request timing, capture/admission sequences, + durable publication and computation lineage. Simulated current reuse matched + recorded reuse within approximately 0.4% in 11 of 12 runs; one 27B workload + differed by about 1.3%. +- Simulations at C=2/C=4 attribute some reuse gains to deeper candidate lookup + and bounded persistence. Other hybrid gains concern capture cost, retained + capacity, write volume and denser useful boundaries. No legacy-cache repair + work is included in the delivery plan. +- Simulator admission/removal behavior is imperfect, and elapsed-time estimates + are not performance qualification. One recorded 1.67 GB disk write stalled + for 782 seconds; its cause remains unexplained. +- There is no implemented-hybrid or matched C=8 qualification result yet. + +These limits belong in the final standalone RFC. Predicted savings should +be replaced or complemented by retained implementation measurements as deliveries +complete, without changing the meaning of historical evidence. + +## Risks + +| Risk | Consequence | Mitigation and required check | +| --- | --- | --- | +| Borrowed rows mutate through an unaudited executor path | Silent corruption of previously captured state | Enforce mutation guards; audit rewind/reset/fork/destruction/speculative rollback; test each path. | +| Sharing based on equal tokens instead of inherited bytes | Incoherent recurrent/KV combinations | Provenance ownership in the common package; independent-prefill negative tests. | +| Reservation or unique-byte accounting errors | OOM during slot reuse, budget overshoot or leaked capacity | A deterministic resource ledger and transactional fault-injection tests. | +| Incomplete model inventory | Missing draft, ring, compressor or recurrent state | Model-owned component inventory and numerical restore tests for each mode. | +| A global lock spans I/O or device work | One slow request stalls all slots | Pin under short metadata locks; execute work outside them; peer-progress tests and lock-wait metrics. | +| Background copies contend with inference | Higher TTFT or inter-token latency at C>1 | Bound/coalesce optional work; measure active-request interference; prioritize latency. | +| Dense checkpoints retain large private state | RAM growth erases sharing gains | Bound density and records; measure marginal latency value against private bytes. | +| Too few checkpoints survive | Earlier edits and subagents re-prefill large gaps | Protect useful shared boundaries; test fixed-budget histories and report checkpoint gaps. | +| Separate live KV prevents a requested C/context combination fitting | OOM or an impossible qualification gate | Freeze per-model envelopes before implementation; qualify admitted rows and exclude infeasible rows; separately evaluate live paging if needed. | +| Shared disk dependency is corrupt | Multiple checkpoints become unusable | Checksums, dependency validation, reverse dependency invalidation and earlier-boundary fallback. | +| Manifest publication is incorrectly ordered | Crash exposes entries with missing dependencies | Dependency durability before manifest publication; crash injection at every stage. | +| Version upgrade or rollback mishandles cache files | Startup failure or stale-state reuse | Explicit versions, managed-file cleanup, cold rebuild and rollback tests. | +| Model-specific exceptions creep into common policy | Review complexity and fragile ownership | Dependency boundary checks; opaque descriptors and model-local transfer/layout code. | +| New eviction policy is bundled with storage changes | Unclear cause of latency/reuse differences | Separate policy PRs and retained per-request evidence. | +| Simulated benefits are treated as measured gains | Premature release or misleading claims | Label evidence; gate each delivery on actual candidate qualification. | + +Cached state may contain information derived from prompts. Retain the current +owner-only file permissions, avoid logging prompt contents, and respect any +existing input isolation identity. Broader tenant isolation is a separately +specified requirement if Gufo's deployment model changes. + +The initial directory-ownership restriction changes today's multi-process +behavior. Document it clearly. It simplifies crash/GC correctness but does not +limit concurrent requests within the owning server. + +## Instrumentation + +Instrumentation is part of the design from the first implementation PR. It +should explain why a request performed work, what resources remained pinned, and which +background operation interfered with a peer. It must not require logging +prompt text or turning on expensive payload inspection. + +| Area | Events / measurements | +| --- | --- | +| Lookup | Live/RAM/disk candidates, deepest compatible boundary, selected boundary, identity rejection and selection reason. | +| Request work | Prompt tokens, restored tokens, executed prefill tokens, checkpoint gap, source/destination slot and actual model/speculative mode. | +| Capture / density | Boundary type, component bytes, committed backing/reservation, pass sizes/count, forced splits, synchronization and admission/skip reason. | +| Spill | Idle versus foreground work, source generation, affected rows, committed backing, residual reassignment wait, unique bytes and copy time. | +| Restore | Pin/lease wait, disk bytes read, device bytes copied, component loading time, failure/cancellation and cold fallback. | +| Memory / allocation | Free/in-use committed pool pages, assigned reservations, private state/tails, staging, queued pins, live allocations, commit/HIP-call blocking time and peak physical total. | +| Persistence | Jobs admitted/coalesced/skipped, queue age/depth, physical bytes written, fsync/publication time and time from capture to durability. | +| Eviction / GC | Checkpoint ID, rank/reason, references removed, unique bytes actually freed, protected pins and orphan cleanup. | +| Concurrency | Slot/lock/stream wait, independent stream leases, transfer interference, B's reassignment TTFT and each peer's token latency during spill/copy work. | +| Recovery | Metadata-only index bytes/time to readiness, unverified/verified dependencies, streaming checksum time, corruption, first-restore TTFT and fallback. | + +Assign bounded internal identifiers to checkpoints, chunks, slots and lineages +for trace correlation. Use bounded aggregate metric labels; arbitrary lineage +or request IDs belong in traces/events rather than unbounded metric dimensions. + +Record every removal and admission outcome needed to reproduce retention +decisions. Existing research could not fully calibrate eviction because some +removals were not logged. A replay should be able to distinguish physical +sharing, accounting changes and a policy that simply retained different state. + +Instrumentation overhead itself is qualified. Expensive detailed traces can +be diagnostic, while normal counters and phase timings remain affordable. + +## Implementation plan + +### Delivery roadmap + +We are implementing the cache shown on the website: conversations use execution +slots, related checkpoints share immutable prefix chunks, each checkpoint keeps +its own model-specific state, and reusable history can live in RAM or on disk. +The delivery plan builds that behavior in three usable increments, after +preparation. It does not include improvements to the current cache. + +The sequence is: **agree on tests and capacity → reuse conversations in RAM → +reuse them after restart → complete and qualify all models**. These are delivery +milestones, not four PRs. Each milestone can contain several small PRs; the +checklists below describe their technical work. + +#### Preparation: agree on what we will test and what fits + +**What we produce:** functional tests describing the expected cache behavior, +a reproducible baseline, and a table of supported model/concurrency/context +combinations. There is no new user-facing cache behavior in this step. + +For example, specify a test in which conversation A grows, a subagent branches +from A, and conversation B takes A's execution slot. The test says which tokens +must be reused when A returns, what memory can be shared, and how much work the +other requests may wait for. Write these expectations before implementing them. +Also specify restart, cancellation, edited-history and corrupted-file outcomes; +those tests become executable as the corresponding components arrive. + +Measure today's cache as a comparison baseline, without changing it. Record +the model artifacts, toolchain, settings and workload history so later latency +and resource comparisons are meaningful. Freeze feasible capacity rows before +implementation: eight requests with shorter histories may fit where eight long +histories do not. Preserve a separate long-agent workload. + +Use isolated allocator, transfer and persistence probes to investigate known +stall risks, including the historical 782-second write. Record unresolved causes +and the checks the new path must pass; remeasure the implemented path before +qualifying it. This investigation is not a prerequisite to designing every +storage detail, nor a project to repair the existing cache. + +**Ready to proceed when:** expected reuse and failure outcomes are specified, +the capacity matrix and comparison environment are recorded, and the latency, +memory and disk checks are explicit. A missing implementation is an expected +reason for a new behavioral test to fail; it is not a passing qualification. + +#### RAM delivery: resume conversations across execution slots + +**What users gain:** A can leave its execution slot, B can use that slot, and A +can later resume from retained RAM state. A parent and its subagents can reuse +their inherited prefix without storing a complete copy for every checkpoint. +This is the first usable increment of the proposed cache. + +Build the common package and plug in a real model adapter. The common package +owns slots, shared chunks, checkpoint lookup, memory budgets and transfer +lifetimes; the adapter knows the model's exact state. Include precommitted spill +backing, preservation while a slot is idle, independent transfer streams and +safe handling of requests arriving during a copy. Choose checkpoint boundaries +using measured reuse benefit, private-state cost and prefill pass overhead. + +Start with one representative model/mode and integrate it into serving within +this delivery, so success is demonstrated by real requests. Other adapters can +progress independently once the contracts stabilize. Convert each mode only +after its tests pass; models awaiting conversion retain their existing behavior. +Persistence through the new disk format arrives in the next delivery. Within +converted modes, retained reuse in this increment is limited to RAM and the +current server lifetime. + +**Ready to ship for a converted mode when:** continuation, edits, forks, +more-conversations-than-slots, cancellation and tight-budget tests pass through +the real server; restored state passes numerical checks; shared memory stays +bounded; and replacing A with B passes B's response-start and other sessions' +token-latency checks. A fake-adapter unit test alone cannot satisfy this gate. + +#### Disk delivery: resume retained conversations after restart + +**What users gain:** useful checkpoints can survive RAM eviction and server +restart. If A has a short checkpoint in RAM and a longer usable one on disk, +lookup considers both. Shared prefixes are also stored once on disk. + +Add the versioned disk store to the same package and lookup index. Write missing +shared chunks plus private state, publish a checkpoint only after its dependencies +are durable, and restore through bounded buffers. At startup, read manifests and +file sizes; verify payload checksums during restore before the slot can execute. +Rebuild incompatible old cache files rather than migrating them. + +**Ready to ship when:** real restart and deeper-disk-reuse scenarios pass, a +100k+ checkpoint larger than the transfer buffer round-trips where capacity +permits, and crash/corruption/cancellation tests never expose partial state. +Measure startup readiness, the first restored request, disk bytes, write volume +and interference with active sessions separately. + +#### Full rollout: deliver every supported model and workload + +**What users gain:** the redesign is available for every supported continuation +mode, with explicit limits for each model. Both long coding-agent sessions and +concurrent independent or mixed sessions are qualified. Eight concurrent requests +are supported in the model/context combinations that fit. + +Finish the remaining model adapters and run the complete affected qualification +matrix. Include clients that omit reasoning from later history, clients that +replay it, bridges that rewrite the final user message, and actual agent/tool +workflows. Publish measured latency and resource results and document cold cache +rebuilds after upgrade. Each model can roll out once its own checks pass; this +milestone closes the all-model scope rather than delaying all integration until +the end. + +**Complete when:** every model/mode has a capability record, a justified capacity +envelope and the required correctness, reuse, latency and resource evidence. +Unsupported operations and infeasible capacity combinations are explicit. The +qualified replacement becomes the default; no permanent alternate cache policy +is required. + +Live-KV paging and disk compaction remain separate follow-up decisions. Bring +paging forward if measurements show it is necessary for an agreed workload; +neither feature is required merely to reproduce the website's retained-cache +design. + +### TDD and behavioral contracts first + +For every behavior change, first write a functional scenario specifying the +observable result. Show that it fails for the missing behavior, implement the +smallest coherent change, then retain the scenario as regression coverage. +Tests assert correctness, expected reused/prefilled work, bounded resources +and safe failure outcomes. They do not merely mirror private implementation +details or assert that a particular helper was called. + +Use a small deterministic fake adapter for common-package tests. It exposes +append-only rows, mutable recurrent state, distinct draft positions and explicit +completion signals. This allows controlled slot churn, transfer ordering, +allocation failures and crash points without model weights or GPU timing noise. + +Model-local tests then establish that real descriptors and transfers preserve +the actual state. Functional HTTP tests in `tests/functional/` exercise user +histories on affected models/modes. A fake adapter cannot qualify numerical +fidelity or contention on Strix Halo. + +Required functional scenarios include: + +| Scenario written before implementation | Required outcome | +| --- | --- | +| Continue one conversation and retry unchanged input | Reuse the correct live/saved boundary and expected suffix work. | +| Freeze a generated frontier before a branch | Children inherit actual executed state rather than an unrelated prefill reconstruction. | +| Drop reasoning or rewrite the final user message in history | Stable-boundary and frozen-frontier reuse stays correct under rotation, pressure and restart; compare suffix work and uncached controls. | +| Edit/shorten history before a recurrent checkpoint | Restore an earlier coherent boundary; never truncate private recurrent state. | +| Rotate more histories than slots | Preserve borrowed rows before overwrite and restore into another slot correctly. | +| Share inherited prefixes; cold-prefill identical tokens separately | Share inherited chunks; preserve distinct independent provenance. | +| Short RAM prefix beside longer disk prefix | Expose and select the deeper usable candidate under the defined policy. | +| Checkpoint larger than staging | Persist and restore through bounded buffers. | +| Tight byte and record budgets | Refuse/evict safely; keep ledger bounded and release last-reference storage. | +| Restore while another request evicts | Pins protect dependencies until completion. | +| Cancel during slot wait, spill, capture, write or restore | Release reservations/leases/pins and invalidate partial execution state. | +| Fail allocation or transfer before mutation | Published checkpoints stay valid; no overwrite before preservation. | +| Reassign a slot before/during/after idle spill | Use precommitted backing, guard source generation and give each transfer an independent stream; gate B's TTFT and each decoding peer's token latency. | +| Add an unaligned optional checkpoint near the prefill tail | Measure extra passes/synchronization; skip capture when its reuse benefit does not justify the pass split. | +| Crash before/after dependency and manifest durability | Restart exposes only complete durable checkpoints. | +| Missing/corrupt shared file | Reject affected checkpoints and use a valid fallback. | +| Restart with a large payload corpus | Startup reads bounded metadata and sizes; readiness and first-restore TTFT are measured separately; checksum failure prevents execution. | +| Old-format cache directory | Rebuild safely without migration or deleting unrelated files. | +| Changed image or other supplemental input | Reuse only boundaries whose complete input identity matches. | +| Mixed workload at each admitted concurrency | Keep peers progressing and preserve separate long-horizon cases; run eight requests only where the frozen model/mode envelope admits them. | + +### Two-layer code structure + +The common package is a CMake library under `src/cache/`. The model loader or +runner constructs its matching adapter and passes it to the package. “Plug in” +means an explicit interface and registration; dynamic library loading is not +required. + +```text +src/cache/ + public contracts: descriptors, capabilities, leases, completions + prefix lookup and checkpoint policy + shared storage, provenance, pins and resource accounting + bounded transfer queue and versioned disk store + events, counters and recovery + +src/models//cache_adapter.* + component inventories and compatibility identity + execution-state creation/reset/destruction + coherent capture/restore and model/device transfers + model-specific numerical and position validation + +tests/functional/ + request-level continuation, branch, rotation and restart scenarios + +model-local tests/ + component layout, exact state and numerical contracts +``` + +| Common package owns | Model module owns | Serving owns | +| --- | --- | --- | +| Slot leases and retention policy | Concrete model allocations and valid state boundaries | Request scheduling, batching and inference progression | +| Prefix index and compatible candidate selection | Complete compatibility/input descriptor | Prompt construction and request configuration | +| Chunk ownership, provenance and reservations | State layout and bounded device operations | Sampling policy and response delivery | +| Disk manifests, checksums, publication and recovery | Private-state encoding/decoding and validation | API cancellation and error propagation | +| Cache events and resource ledger | Model-specific numerical tests | End-to-end latency and functional integration | + +Common code must not depend on HTTP, `TextModelRunner`, model names or model +headers. Reusable device transfer primitives can stay in `src/core/hip/`. +Model-specific tensors and mutation rules stay with the model. Use explicit serving/adapter seams for the new package; keep the current +cache unchanged as a baseline until the qualified replacement is integrated. +The delivered product has one active continuation cache, not competing policies. + +### Reviewable PR boundaries + +Separate the common package, model adapters, serving integration and disk store +into small, testable PRs. Within the RAM delivery, build the independent package +first, add preservation and shared state, then integrate a qualified adapter into +serving. Avoid combining a new storage format, kernel paging and an eviction +policy in one review. Model adapters can progress in parallel once their common +contracts stabilize. + +Every PR names the behavior it adds and the models/modes it affects. Tests arrive +with that behavior or in an immediately preceding contract PR. A package that +passes fake-adapter tests is useful engineering progress; a delivery is ready +only when its real-request checks pass. The existing cache remains a comparison +baseline and the implementation for modes awaiting conversion; this plan does +not change its policy. + +### Baseline, checks and completion records + +Before implementation, pin the base revision, toolchain, weights and sidecars, +model/mode, harness revision, context/resource settings and prior cache history. +Audit every supported component and mutation path against that base. Historical +research revision numbers do not substitute for a current baseline. + +The following engineering checklists support the delivery roadmap above. They +retain the detailed tasks for implementers; readers can assess the plan from +the roadmap without following every allocation or storage detail. All items +are planned; none represents completed cache implementation. + +#### Preparation checklist + +- [ ] Freeze the per-model feasible capacity matrix before implementation; + include committed backing and separately admitted long/concurrent personas. +- [ ] Record a reproducible implementation base and matched benchmark environment. +- [ ] Inventory every current family/mode and its supported continuation, + snapshot, fork and persistence capabilities. +- [ ] Specify slot-lease, completion, checkpoint, reservation and pin lifetimes, + including cancellation, shutdown and allocation/transfer failure. +- [ ] Write functional contracts and fake-adapter failure scenarios first. +- [ ] Establish instrumentation sufficient to replay every admission/removal. +- [ ] Characterize page commits, independent-stream copies and proposed-store + persistence using isolated probes under the admitted concurrent workloads. + Investigate whether the + historical 782 s write-stall mechanism can recur in the proposed allocation, + transfer or writer paths. Record allocator/global-HIP wait, stream wait, + serialization, metadata-lock wait, filesystem and fsync time separately. + Resolve reproducible candidate stalls or keep the affected qualification + blocked; an unexplained baseline outlier is not evidence that the new path + provides bounded peer progress. This task does not patch the current cache. + +#### RAM delivery checklist + +**Common package:** + +- [ ] Build the independent CMake package with the agreed public contracts. +- [ ] Implement fake-adapter scenarios before lifecycle/policy behavior. +- [ ] Enforce no HTTP, serving-runner or model-header dependencies. +- [ ] Define serving/adapter integration seams without changing current-cache policy. +- [ ] Qualify cancellation, completion, failure and resource-ledger contracts. + +**Preserving state before a slot is reused:** + +- [ ] Back admitted spill obligations with pages committed during initialization + or verified inference-quiescent periods; reuse released allocations. +- [ ] Implement bounded idle-slot spill, source-generation guards and safe + handling of a new request arriving mid-copy. +- [ ] Lease one independent pooled stream per in-flight transfer. +- [ ] Gate B's TTFT and peers' per-token latency for idle, zero-idle and mid-spill + reassignment; record allocation/page-commit, copy and synchronization waits. +- [ ] Decline retention or retire eligible references safely when committed + capacity is unavailable; never allocate bulk spill backing secretly on admission. + +**Shared checkpoints and model adapters:** + +- [ ] Inventory shape/precision, valid ranges, backing owners and every mutation + path for each family/mode before adapting it. +- [ ] Implement explicit component positions, immutable chunk ownership, + inherited provenance, private tails and reader pins. +- [ ] Make admission and preservation transactional; convert reserved bytes + into owned backing without double charging. +- [ ] Guard ordinary execution and speculative rollback as well as cache-triggered + reset/rewind/restore/reassignment/destruction. +- [ ] Publish only coherent captures; restore all required components together + and invalidate partial destinations before reuse. +- [ ] Implement density with measured pass-split/synchronization costs; prefer + aligned candidates, skip redundant near-tail grid splits and preserve exact + boundaries where their reuse benefit justifies the additional pass. +- [ ] Qualify numerical/component round trips and measured savings for equivalent + retained histories on each migrated mode. +- [ ] Integrate at least one qualified real model/mode into serving and run + continuation, edited-history, fork, rotation, pressure and cancellation + scenarios through HTTP before declaring the RAM delivery usable. +- [ ] State the RAM-only lifetime limit and the active converted model/mode set; + preserve existing behavior for modes awaiting conversion. + +#### Disk delivery checklist + +- [ ] Version manifests, component layouts and format namespaces; rebuild + recognized incompatible legacy contents without parsing them as new state. +- [ ] Track component availability through one compatible-prefix index. +- [ ] Build the startup index from bounded manifests and dependency sizes; + verify payload checksums lazily during streaming restore before execution. + Gate readiness time and the first restored request separately. +- [ ] Persist missing chunks, private state and tails with dependency durability + before manifest publication, including directory durability. +- [ ] Protect writers/readers with pins; bound queues, staging and cleanup. +- [ ] Enforce exclusive directory ownership and implement reference-based + retirement, corruption rejection, orphan recovery and budget eviction. +- [ ] Inject crashes at publication stages and test concurrent restore/eviction, + missing dependencies, write failure, shutdown and cancellation. +- [ ] Qualify a 100k+ checkpoint round trip exceeding staging; report peak + staging, durable frontier, physical bytes, writes and restore latency. +- [ ] Keep compaction off pending a separately measured proposal. + +#### Full rollout checklist + +- [ ] Deliver every supported continuation layout through the applicable + contract; explain explicitly any unsupported capability. +- [ ] Qualify all admitted model-specific C/depth rows; use C=8 where feasible + and retain separate long-agent and concurrent/mixed acceptance cases. +- [ ] Run thinking-on reasoning-dropping/replaying clients and `cache-bridge` + explicitly with pressure, rotation and restart on affected profiles. +- [ ] Replay affected agent sessions, inspecting actual tool results and drafts. +- [ ] Retain numerical-quality and standard speed results plus matched affected + per-request/phase timing controls; fix confirmed regressions. +- [ ] Publish observed resource/latency results and residual limits; update + user-facing options, events and upgrade behavior to match implemented code. + +Existing suite mappings make these outcomes concrete: + +| Workflow | Existing suites / necessary extensions | +| --- | --- | +| Live continuation / retry | `cache-growth`, `cache-depth`, `long-context`. | +| Dropped reasoning / rewritten history | `cache-growth`, explicitly selected `cache-bridge` (outside `all`), frozen-frontier/stable-boundary scenarios. | +| Edits / shortened histories | `cache-edits`, `cache-depth`. | +| Shared-prefix children / independent provenance | `cache-shared-prefix`, `cache-concurrency`, component ownership tests. | +| More histories than slots / pressure | `cache-rotation`, `cache-depth`, reservation/failure tests. | +| Speculative positions / numerical behavior | `state-edges`, model-local snapshot and quality tests. | +| Supplemental image identity | `cache` and affected multimodal suites where supported. | +| Deep RAM/disk selection and restart | `cache`, disk-spacing coverage, bounded-transfer and crash-injection extensions. | +| Cancellation / peer progress | CPU runner/store tests, `cache-concurrency`, fault-injection extensions. | + +During iteration, use the smallest affected CPU/model targets. Continuation +changes require the affected `cache` and `long-context` functional coverage. +Shared behavior changes require all relevant text profiles; model-specific +changes require the affected modes, including actual draft execution. Missing +models or skipped suites are not quality passes. + +Retain numerical-quality checks and the standard speed benchmark. For reported +coding-agent workflows, replay the affected histories with +`tests/functional/pi_agent.py`, retain sessions and inspect actual tool results. +Follow repository formatting and build checks before C++ commits. Documentation +drafting itself does not require GPU model runs. + +Each PR records the concrete behavior change, invariants affected, commands, +environment, artifact locations, per-request outcomes and known limitations. +A delivery completes only when its real-request acceptance checks pass. +Simulations and partial suites do not mark implementation complete. Fix confirmed +regressions before release; keep noisy evidence visibly inconclusive until resolved. + +## Compatibility and rollout + +Build and qualify the new common package independently first. Introduce each model +adapter only after its state and functional contracts pass. Preserve the live +fast path throughout rollout. Cache admission failures are recoverable misses +when execution remains valid; partially restored state never executes. + +At the new disk-store transition, communicate that existing cache contents +will be rebuilt and directories become single-process-owned. Requests remain +supported, but the first post-upgrade requests may pay cold prefill. This is an +accepted consequence of dropping old-format compatibility. + +Record format and adapter ABI versions independently of model display names. +Rollback either uses its own compatible namespace or starts cold; it must never +read incompatible new payloads. There is no permanent alternate implementation +switch required for normal inference; migration stages are implementation +steps whose final behavior becomes the default after qualification. + +## Open questions + +### Agreed decisions + +| Decision | Agreed direction | +| --- | --- | +| Model scope | All model families accounted for; all supported continuation modes delivered. | +| Delivery | Small, testable PRs delivering RAM reuse, disk/restart reuse and full model coverage. | +| Workloads | Long-horizon coding/agent histories and C>1 independent/mixed workloads; up to eight requests within per-model feasible capacity envelopes. | +| Optimization order | Latency first, RAM second, disk capacity and write volume third. | +| Correctness | Exact coherent saved-state restoration plus existing numerical-quality requirements. | +| Old disk files | No migration or backward compatibility required; safe managed-file rebuild. | +| Directory ownership | One server process per directory initially; concurrent requests within it supported. | +| Documentation | This RFC is the only retained cache-redesign file; research tools and inputs are archived. | + +### Engineering decisions to resolve before dependent implementation + +- Complete component inventories and valid positions for every supported mode. + Resolve before its adapter implementation; do not block unrelated common-package work. +- Concrete adapter API, completion signals and mutation guards. Resolve before + common ownership behavior is implemented. +- Chunk geometry for nonstandard/pool-compressed layouts, and tail accounting. + Start from 2,048-token examples, then validate each descriptor. +- Initial density and admission policy within each feasible matrix row. Include + prefill pass efficiency, synchronization and committed backing in the marginal + cost while preserving long-horizon cases. +- Whether a cost-aware shorter restore should override the deepest available + checkpoint. Define measured thresholds and observable fallback behavior + before enabling such a policy. +- Freeze the per-model capacity matrix during preparation, before + implementation begins. Resolve unqualified rows before starting dependent work; + revise frozen envelopes only with recorded resource evidence. +- Whether measured live-memory/cross-slot copying costs make paged KV necessary + to achieve the intended product workload. +- Whether chunk-file overhead warrants compaction, including its extra writes, + temporary space and crash recovery contract. + +These are explicit review points. They do not reopen the agreed scope or require +choosing every engineering detail before writing the first functional tests. + +## Evidence appendix + +This appendix retains the measurement context, detailed cost model and reference +results inside the RFC. Executable research tools and original inputs remain +retrievable from pinned archives rather than being maintained in this branch. + +### Measurement environment and size model + +The October 7 research used main `b39c530e`, AMD Strix Halo `gfx1151` with +125 GiB visible unified memory, and a 931 GB NVMe behind dm-crypt. Its recorded +release-preset build used the pinned Nix HIP toolchain and GCC wrapper 15.3.0. +The agent harness was `pi` 0.99.2. These details constrain reproducibility; +they are not specifications of every supported deployment. + +Recorded model configurations were Flash-Next UD-Q4_K_XL with a shared Q8_0 +MTP sidecar, and Qwen 27B UD-Q8_K_XL with a Q8_0 DFlash2 sidecar. Size probes +also covered non-speculative modes. Rounded fitted constants were: + +| Recorded configuration | Fixed payload | Marginal payload per token | +| --- | ---: | ---: | +| Flash-Next AR | 113.5 MiB | 25.35 decimal KB | +| Flash-Next MTP | 113.8 MiB | 27.46 decimal KB | +| Qwen 27B AR | Approximately 152 MiB | 64 KiB | +| Qwen 27B DFlash2 | Approximately 232 MiB | 64 KiB | + +These describe the tested snapshot payloads, not all live memory. Layout, +precision, context settings and sidecars can change them. Component-aware +accounting must measure actual bytes rather than hard-code this table. + +### Workloads and simulation interpretation + +The research workloads were a long coding-agent conversation (W1), parent and +subagent branches (W2), multiple independent chats (W3), and reuse surrounding +restart/shared-prefix behavior (W4). Additional W2/W3 runs used C=4. Restart +simulations distinguished graceful queue drain from abrupt loss of unpublished +writes. + +The following representative E8 revision 2 values are total prefill time across +each trace. The existing-system measurement is separate from every simulated +column. They are neither measured hybrid timings nor complete request latency. + +| Trace | Measured existing prefill | Simulated existing | Simulated hybrid | Simulated hybrid + dense boundaries | +| --- | ---: | ---: | ---: | ---: | +| Flash-Next W1 | 130 s | 137 s | 137 s | 137 s | +| Flash-Next W2 | 85 s | 88 s | 72 s | 71 s | +| Flash-Next W3 C=4 | 159 s | 157 s | 157 s | 157 s | +| 27B W1 | 589 s | 596 s | 596 s | 596 s | +| 27B W2 | 293 s | 293 s | 236 s | 233 s | +| 27B W4 | 403 s | 430 s | 394 s | 376 s | +| 27B W3 C=4 | 478 s | 497 s | 497 s | 497 s | + +These values show that candidate selection contributes much of the predicted +W2 benefit: the new index exposes a deeper usable disk checkpoint. +Shared storage can still reduce capture/write costs when prefill totals do +not change. W1's efficient live continuation already reuses most history; +its expected benefit is not a promise to eliminate more prefill. + +For the long 27B trace, simulated graceful restarts at about 104.5k and 148.5k +tokens restored roughly 75k tokens with current staging behavior, versus +104.4k and 133.8k with the hybrid policy. The deeper surviving position reflects +publication, budgets and checkpoint policy; it is not automatically the latest +executed token. The corresponding extra prefill in the current simulation was +about 29k and 59k tokens. + +### Reference stability and archive provenance + +Upstream alternatives were checked against official documentation and the +referenced llama.cpp source revision on October 8. Versioned vLLM links are +pinned where available; the stable design and SGLang documentation are mutable +references, so future implementation decisions must re-check their relevant +contracts. Architectural inference about adapting them to Gufo is identified +as such in the alternatives, rather than presented as an upstream guarantee. + +The last supporting-document/script snapshot is +`b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33`. The complete original results, +including large token arrays and logs, are preserved at +`a32fc43bcb9ec66264f166b5162d93a9223557d5`. Both snapshots are retrievable +through the replay procedure below. They preserve historical discussions and +superseded analyses without requiring duplicate files in this branch. + +### Detailed recorded measurements and reference simulation + +The following tables preserve the measured E1–E4 results, microbenchmarks and +C=4 measurements. E8 revision 2 is the reference simulation. Earlier E5/E7 +outputs remain archived for historical comparison and are superseded for +current design evaluation. The labels and original configurations matter: +these are historical results, not qualification of an implemented hybrid. + +The original E3 ideal-prefix estimates rescale re-tokenized trace positions; +they are not the same metric as the later exact server-work accounting. +Differences between those columns and particular source/log examples must +not be silently treated as conflicting measurements of the same quantity. + +#### E1. Snapshot size model (2026-10-07) + +Disk `payload_bytes` against checkpoint tokens, main-equivalent build, +`--sessions 1`. Every configuration fits fixed + per-token exactly (largest +residual under 0.01%) **(measured)**: + +| Configuration | Fixed | Per token | At 100k tokens | +| --- | ---: | ---: | ---: | +| Flash-Next, AR, `--context 260000` | 113.5 MiB | 25.35 KB | 2.65 GB | +| Flash-Next, AR, `--context 32768` | 113.5 MiB | 25.35 KB | 2.65 GB | +| Flash-Next, MTP, `--context 260000` | 113.8 MiB | 27.46 KB | 2.87 GB | +| 27B, AR, `--context 256000` | 152.4 MiB | 65.54 KB (64 KiB) | 6.71 GB | +| 27B, AR, `--context 32768` | 152.4 MiB | 65.54 KB | 6.71 GB | +| 27B, DFlash2, `--context 256000` | 232.4 MiB | 65.54 KB | 6.80 GB | + +- **Context size doesn't matter.** Checkpoint size depends only on the token + position, not on `--context`. +- **Speculative drafting adds state.** MTP adds 2.1 KB per token; DFlash2 adds + 80 MiB of fixed state. +- **27B is hybrid too.** It has a 152 MiB fixed part, but its per-token cost + is 2.6× Flash-Next's, so sharing KV would save proportionally more on 27B. +- **Automatic RAM budgets are small.** With one session loaded they were + 12.9–17.5 GB for Flash-Next and 33–34 GB for 27B. At 100k tokens that is + about 4–6 Flash-Next checkpoints or 5 for 27B. +- **Deep checkpoints don't reach disk.** The automatic staging limit (3.4 GiB + with Flash-Next loaded) is below one Flash-Next checkpoint at 131k tokens, + and two 27B checkpoints at 64k exceed even 6 GiB. Today's defaults skip + persisting those deep checkpoints (`reason=staging_capacity`). +- **The RAM cache can refuse the newest checkpoint.** At 127k tokens it + refused the prompt checkpoint (`reason=byte_capacity`, 3.34 GB against a + 14.6 GB budget), because the request's own earlier checkpoints already + filled the budget. + +Scripts: `e1_snapshot_size.py`, `run_e1.sh`, `fit_e1.py`. + +#### E2. Workload traces (2026-10-07) + +Production-like servers (the llama-swap command lines plus the disk tier): +- Flash-Next: MTP, `--sessions 2`, `--context 260000`. +- 27B: Q8_K_XL, DFlash2, `--sessions 2`, `--context 256000`. + +Common settings: automatic RAM and staging budgets, a 16 GiB disk budget, and +`--trace`. W1 is a real Pi session grown through tool results by +`tests/functional/agent_long.py` (thinking `low`). W2–W4 are synthetic +(`workloads.py`, thinking off, real model replies). + +Automatic budgets the servers chose **(measured)**: + +| Model | RAM cache budget | Staging budget | Fits at 100k tokens | +| --- | ---: | ---: | --- | +| Flash-Next (2 sessions) | 8.9–9.2 GB | 2.23–2.31 GB | 3 checkpoints in RAM; nothing past ~75k tokens reaches disk | +| 27B (2 sessions) | 23.0–23.3 GB | 5.74–5.84 GB | 3 checkpoints in RAM; nothing past ~75k tokens reaches disk | + +#### E3. Missed reuse + +"Ideal" is the longest prefix each prompt shares with any earlier prompt plus +its output. Prompts were re-tokenized from the trace with the model's own +vocabulary. Re-tokenized text is a few tokens shorter than the server's count, +so positions are rescaled per request. Gaps under 256 tokens are ignored: they +are the re-rendered assistant reply, not a capacity issue. + +| Workload | Requests | Ideal reuse | Actual reuse | Largest misses | +| --- | ---: | ---: | ---: | --- | +| fn W1 agent to 149k | 36 | 95.4% | 95.4% | none | +| fn W2 subagents | 36 | 89.1% | 85.7% | parent after forks: 20.6k tokens, ~17 s | +| fn W3 multi-user | 60 | 87.9% | 87.6% | 1 request, 991 tokens | +| fn W4 restart | 33 | 89.7% | 88.5% | subagent after restart, 6.6k tokens; agent restore 3.7k short | +| 27B W1 agent to 149k | 36 | 95.4% | 95.4% | none | +| 27B W2 subagents | 36 | 89.0% | 85.6% | parent after forks: 20.4k tokens, ~60 s | +| 27B W3 multi-user | 60 | 89.3% | 88.8% | 2 small requests | +| 27B W4 restart | 33 | 89.7% | 87.7% | agent after restart: 13.1k tokens, ~37 s; subagent 6.6k tokens, ~22 s | + +Causes found **(measured, from logs and source)**: + +1. **Disk is ignored after any RAM hit.** It is consulted only when RAM has no + hit at all (`src/cli/serve/text_model_runner.cpp:1877`). In W2 the + parent's turn after its forks matched only the 4,661-token system prompt in + RAM while disk held its 24,599-token checkpoint, so 22,558 tokens were + re-prefilled. +2. **The RAM cache refuses new checkpoints when full.** An incoming checkpoint + may only evict entries of equal or lower rank (`MaxRemovalPriority`, + `src/cli/serve/continuation_cache.cpp:32`, used at `:759`). Refusals + (`event=snapshot action=skipped reason=byte_capacity`) per run: 19–42. +3. **Deep checkpoints never reach disk.** A full file larger than the + automatic staging budget is skipped (`reason=staging_capacity`): 71 skips + in fn W1 and 85 in 27B W1. The deepest persisted checkpoint stops at about + 75k tokens for both models. +4. **No checkpoint at a shared boundary after a restart.** Disk holds prompt + boundaries but not grid checkpoints, so a new subagent sharing a 6.6k-token + system prompt reused nothing. + +#### E4. Overhead of the current design + +From the server logs (`analyze_e4.py`) **(measured)**: + +| Run | Live captures | Capture time, total / max | Disk writes | Written | Staging skips | RAM refusals | +| --- | ---: | --- | ---: | ---: | ---: | ---: | +| fn W1 | 35 | 1.1 s / 158 ms | 6 | 7.1 GB | 71 | 39 | +| fn W2 | 13 | 0.5 s / 110 ms | 25 | 16.3 GB | 8 | 22 | +| fn W3 | 18 | 0.9 s / 246 ms | 24 | 13.7 GB | 9 | 41 | +| fn W4 | 23 | 0.8 s / 117 ms | 26 | 23.2 GB | 29 | 27 | +| 27B W1 | 35 | 5.9 s / 399 ms | 6 | 16.5 GB | 85 | 39 | +| 27B W2 | 8 | 2.6 s / 611 ms | 25 | 37.9 GB | 3 | 19 | +| 27B W3 | 24 | 5.8 s / 634 ms | 25 | 31.7 GB | 7 | 42 | +| 27B W4 | 25 | 7.3 s / 635 ms | 31 | 70.9 GB | 16 | 31 | + +- **27B copies its whole state per capture.** At 149k tokens a 10.0 GB + capture took 235–265 ms, every turn. +- **Flash-Next captures are cheaper** because KV is borrowed (#445). + + +#### Micro-benchmarks (2026-10-07) + +These back the [cost model](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/cost-model.md) **(measured)**: + +- **GPU copies** ([copybench.hip](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/copybench.hip), 56 MiB–10 GiB): + device to device 104–110 GB/s; pinned host either way about 85 GB/s; + pageable 61–83 GB/s. A 10 GiB device copy takes 103 ms. The real 27B capture + of the same 10 GB took 235 ms. +- **Disk** ([diskbench.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/diskbench.py), NVMe under dm-crypt): + - write + fsync 0.58–0.60 GB/s at every size from 56 MiB to 4 GiB; + - cold read 0.97–1.15 GB/s; + - 72 files of 56 MiB versus one 4.2 GB file: write 8.0 s vs 7.1 s, cold + read 4.18 s vs 3.69 s (+13% each). +- **Fixed-state captures already exist.** Flash-Next captures 2.2–5.4 ms at + 1.8k–149k tokens, because its KV is borrowed (#445). 27B captures 13.7 ms at + 1.8k tokens, where its snapshot (0.36 GB) is mostly fixed state. +- **Prefill model** ([fit_prefill.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/fit_prefill.py)), fitted on 150 + requests per model. Median error 9.8% (Flash-Next) and 3.9% (27B). +- **Restoring from chunks** ([chunkcopy.hip](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/chunkcopy.hip)): 8 GiB + moved as many device copies on one stream, in scattered order. + + | Piece size | GB/s | + | ---: | ---: | + | One 8 GiB copy | 103 | + | 64 MiB | 109 | + | 4 MiB | 106 | + | 1 MiB | 88 | + | 256 KiB | 56 | + | 64 KiB | 23 | + + A 2,048-token chunk split per attention layer and K/V is estimated at about + 1–4 MiB per piece for these models, so assembling a session from chunks + keeps device-copy bandwidth. +- **Physical vs accounted RAM** (W1 logs): + - Flash-Next accounted 7.1–8.9 GB of retained checkpoints, while available + memory fell only 4–6 GB including the live session. Borrowed KV is + physically shared, which supports unique-bytes accounting. + - 27B accounted 16.5–22.3 GB for a 14–20 GB fall, consistent with real full + copies. + + +#### E6. Today's system at concurrency 4 + +The production-like servers were rerun with `--sessions 4`, a 131,072-token +context and four parallel clients ([run_e6.sh](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/run_e6.sh)). Workloads: +W3 with 10 users and 100 requests, and W2 with four workers. + +| Run | RAM budget | Staging | Ideal reuse | Actual reuse | RAM refusals | Disk written | Disk write time | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 27B W3, concurrency 4 | 20.2 GB | 5.05 GB | 86.7% | 86.1% | 92 | 33.7 GB | 903 s | +| 27B W2, concurrency 4 | 20.1 GB | 5.03 GB | 89.2% | 89.0% | 22 | 36.1 GB | 97 s | +| Flash-Next W3, concurrency 4 | 8.5 GB | 2.12 GB | 87.5% | 87.1% | 77 | 16.2 GB | 31 s | +| Flash-Next W2, concurrency 4 | 9.0 GB | 2.25 GB | 89.0% | 88.9% | 27 | 14.5 GB | 29 s | + + +#### E8. Simulator replaying production behaviour (simulated, revision 2) + +Two reviews pointed out where E5/E7 departed from production. +[simulate_e8.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/simulate_e8.py) revision 2 models: + +- **Concurrency:** requests replay as events at their real times. Each starts + when its generation started (trace timestamp), captures when its prefill + ends (received + time to first token) and finishes at received + duration. + Live frontiers belong to sessions and are lost when another conversation + takes the session. +- **The capture sequence of `text_model_runner.cpp`:** + - on a cache hit, a frozen copy of the reused frontier (continuation); + - the stable boundary (continuation); + - the complete prompt as a retry copy; + - grid points as history, learned divergence points as branch points. + + Only these prompt-path snapshots are committed. Prompt plus output stays as + the live frontier, not as a retained snapshot (revision 1 got this wrong). +- **Admission:** a new checkpoint may evict only entries at or below its rank + ceiling (`MaxRemovalPriority`: retry 0, history 1, continuation and branch + point 3), lowest rank first. The entry being restored from is protected, and + RemovalPriority's retry, history, covered-continuation and branch-point + ranks apply. +- **Disk:** one serial writer at 0.44 GB/s. Spacing and staging are checked + when the writer reaches a job, and an entry becomes restorable only when its + write completes. A restart is graceful (the queue drains, as on SIGTERM) or, + with `--abrupt`, drops queued and in-flight writes. Revision 1 published + entries when their write started. +- **Lineage-aware chunks:** a request inherits its restore source's chunks + only for the rows it restored; rows it computed form new chunks. + Independent computations of equal tokens are never deduplicated. + +[summarize_e8.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/summarize_e8.py) produces the source tables. The RFC retains current-versus-hybrid +columns; the archived legacy-improvement variant is outside the new design's +implementation scope and is omitted here. + +| Run | Measured prefill | Today | Hybrid | Hybrid + dense | Reuse, simulated today vs actual | Requests within 64 tokens | Refusals: server / simulated | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Flash-Next W1 | 130 s | 137 s | 137 s | 137 s | +0.0% | 36/36 | 39 / 64 | +| Flash-Next W2 | 85 s | 88 s | 72 s | 71 s | -0.1% | 35/36 | 22 / 26 | +| Flash-Next W3 | 108 s | 108 s | 107 s | 107 s | -0.1% | 58/60 | 41 / 47 | +| Flash-Next W4 | 108 s | 100 s | 100 s | 95 s | +0.4% | 28/33 | 27 / 26 | +| Flash-Next W2-C4 | 72 s | 72 s | 72 s | 70 s | -0.2% | 34/36 | 27 / 24 | +| Flash-Next W3-C4 | 159 s | 157 s | 157 s | 157 s | -0.1% | 99/100 | 77 / 81 | +| 27B W1 | 589 s | 596 s | 596 s | 596 s | +0.0% | 36/36 | 39 / 64 | +| 27B W2 | 293 s | 293 s | 236 s | 233 s | -0.0% | 32/36 | 19 / 21 | +| 27B W3 | 352 s | 347 s | 347 s | 347 s | +0.1% | 56/60 | 42 / 48 | +| 27B W4 | 403 s | 430 s | 394 s | 376 s | -1.3% | 27/33 | 31 / 26 | +| 27B W2-C4 | 230 s | 231 s | 231 s | 227 s | -0.2% | 28/36 | 22 / 25 | +| 27B W3-C4 | 478 s | 497 s | 497 s | 497 s | -0.1% | 97/100 | 92 / 97 | + +| Model | Restart before request | Shutdown | Today | Hybrid | Restored after restart: today / hybrid | +| --- | ---: | --- | ---: | ---: | --- | +| Flash-Next | 12 | graceful | 137 s | 137 s | 60,560 / 60,560 | +| Flash-Next | 12 | abrupt | 137 s | 137 s | 60,560 / 60,560 | +| Flash-Next | 20 | graceful | 161 s | 137 s | 75,275 / 104,810 | +| Flash-Next | 20 | abrupt | 161 s | 137 s | 75,275 / 104,810 | +| Flash-Next | 28 | graceful | 185 s | 137 s | 75,275 / 134,388 | +| Flash-Next | 28 | abrupt | 185 s | 137 s | 75,275 / 134,388 | +| 27B | 12 | graceful | 597 s | 597 s | 60,396 / 60,396 | +| 27B | 12 | abrupt | 649 s | 597 s | 45,676 / 60,396 | +| 27B | 20 | graceful | 718 s | 597 s | 75,026 / 104,386 | +| 27B | 20 | abrupt | 718 s | 597 s | 75,026 / 104,386 | +| 27B | 28 | graceful | 855 s | 597 s | 75,026 / 133,842 | +| 27B | 28 | abrupt | 855 s | 597 s | 75,026 / 133,842 | + +| Run | Disk written: server | Today (sim) | Hybrid | Hybrid + dense | +| --- | ---: | ---: | ---: | ---: | +| Flash-Next W1 | 7.1 GB | 7.0 GB | 5.7 GB | 5.7 GB | +| Flash-Next W2 | 16.3 GB | 16.6 GB | 5.3 GB | 5.7 GB | +| Flash-Next W3 | 13.7 GB | 13.5 GB | 6.3 GB | 6.3 GB | +| Flash-Next W4 | 23.2 GB | 26.7 GB | 7.1 GB | 6.8 GB | +| Flash-Next W2-C4 | 14.5 GB | 15.6 GB | 5.4 GB | 5.8 GB | +| Flash-Next W3-C4 | 16.2 GB | 15.9 GB | 8.7 GB | 8.7 GB | +| 27B W1 | 16.5 GB | 16.5 GB | 13.2 GB | 13.2 GB | +| 27B W2 | 37.9 GB | 38.4 GB | 12.0 GB | 13.0 GB | +| 27B W3 | 31.7 GB | 31.5 GB | 13.5 GB | 13.4 GB | +| 27B W4 | 70.9 GB | 71.4 GB | 17.2 GB | 16.0 GB | +| 27B W2-C4 | 36.1 GB | 36.6 GB | 11.6 GB | 12.6 GB | +| 27B W3-C4 | 33.7 GB | 33.6 GB | 20.1 GB | 20.0 GB | + +Reading E8: + +- **Fidelity.** + - Actual reuse is reproduced within 0.4% on 11 of 12 runs (27B W4 −1.3%), + with 28–36 of 36 and 97–99 of 100 requests within 64 tokens. + - Prefill time within 0–7%, disk writes within about 15%. + - RAM refusals match on 10 of 12 runs; the W1 runs over-count (64 vs 39). + - The set of retained checkpoints cannot be verified, because the server + logs removals only when the entry limit forces them. +- **The new design's modeled benefit** includes the deeper W2 restore, + durable checkpoints at depth, more retained branch points and reduced writes. + Dense boundaries also improved modeled W4 prefill to 376 s on 27B and 95 s + on Flash-Next. These estimates omit the newly explicit allocation/idle-spill, + prefill-pass-split and startup contracts, which require implementation evidence. +- **Disk writes:** the hybrid simulation writes approximately 1.7–4.2 times less + than the existing cache in multi-conversation traces. Existing W1 writes are + already low because deep writes were skipped, so write totals must be read + together with the durable frontier and retained boundaries. + +### Detailed historical cost model + +The following model is derived from measured constants on the research host. +Every proposed-hybrid timing, retained-capacity count, compaction estimate and +endurance illustration is a prediction, not an implementation measurement. +Counts assume one linear lineage and the original modeled checkpoint policy; +actual private tails, alignment, reader pins and temporary storage must be +included in candidate accounting. This is retained for comparison and replay, +not a source of hard-coded production defaults. + +### Measured constants + +| Constant | Value | Source | Plausibility check | +| --- | --- | --- | --- | +| Checkpoint size, Flash-Next (MTP) | 113.8 MiB + 27.46 KB/token | E1 disk payloads, exact fit | #275's production logs give the same slope | +| Checkpoint size, 27B (DFlash2) | 232.4 MiB + 64 KiB/token | E1 disk payloads, exact fit | — | +| Device copy (device to device) | 104–110 GB/s | [copybench.hip](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/copybench.hip) | Real RAM restores: 27B 33k tokens (2.4 GB) in 25 ms, 96 GB/s | +| Host copy (pinned, either way) | ~85 GB/s; pageable 61–83 GB/s | copybench.hip | — | +| Capture of fixed state only | Flash-Next 2–5 ms at any depth | E2 W1 `live_checkpoint` | Flash-Next already captures only fixed state today (#445): 2.2–5.4 ms from 1.8k to 149k tokens | +| Capture, 27B full copy | 14 ms at 0.36 GB, 235 ms at 10 GB (≈ 67 ms + 17 ms/GB, r² 0.51) | E2 W1 `live_checkpoint`, one agent, no concurrency | Its fixed state is 0.24 GB, so a fixed-state-only 27B capture is ~10–15 ms, matching the 1.8k-token captures | +| RAM held by checkpoints | Flash-Next: physical well below accounted; 27B: physical ≈ accounted | E2 W1 logs: `retained_bytes` vs `host_available_mib` | Flash-Next accounted 7.1–8.9 GB while available memory fell only 4–6 GB including the live session; 27B accounted 16.5–22.3 GB for a 14–20 GB fall. Counting unique bytes matches what the hardware holds | +| Disk write + fsync, raw | 0.58–0.60 GB/s at every size | [diskbench.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/diskbench.py) | — | +| Disk write in gufo | 0.44 GB/s (serialize + checksum + write + fsync) | E2 `write_ms` against `file_bytes`, about 170 writes | Per-write medians 0.36 GB/s (27B) and 0.52 GB/s (Flash-Next). One unexplained outlier at concurrency 4: 1.67 GB in 782 s | +| Disk cold read | 1.1 GB/s; 1.4–1.5 GB/s when partly cached | diskbench.py; E2 disk restores | Real restores: 55.5k-token 27B file in 2.5 s | +| Assembling a session from chunks in memory | 106 GB/s for 4 MiB pieces, 88 GB/s for 1 MiB, vs 103 GB/s for one copy | [chunkcopy.hip](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/chunkcopy.hip), 8 GiB as many device copies | Per-layer pieces of a 2,048-token chunk are an estimated 1–4 MiB | +| Chunk files instead of one file | +13% write time, +13% cold-read time (72 × 56 MiB vs 4 GiB) | diskbench.py | Compaction may reduce it; qualification required | +| Prefill N tokens on D cached | Flash-Next 0.36 s + 0.79 ms/token + small depth term; 27B 0.52 s + 2.66 ms/token + 16.5 ns × N × (D + N/2) | [fit_prefill.py](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/scripts/fit_prefill.py), 150 requests each; median error 9.8% and 3.9% | Simulated prefill time matches measured within 3–8% (E7) | + +`cache_snapshot_ms` in `usage.gufo` is not used as a capture cost. It is +measured from capture start to when the capture is joined +(`src/cli/serve/text_model_runner.cpp:913`), so it includes overlapped wall +time. Its medians (0.3–0.5 s per request on Flash-Next, about 1 s on 27B) are +an upper bound, not time on the critical path. + +### Per-operation costs + +RAM and staging budgets are the automatic values chosen with two sessions: +9.2 GB and 2.3 GB for Flash-Next, 23 GB and 5.75 GB for 27B. "Persist" for the +hybrid means one 2,048-token step: fixed state plus 2,048 tokens of KV. + +#### Flash-Next (MTP) + +| Operation | Depth | Today | Hybrid | +| --- | ---: | ---: | ---: | +| Checkpoint bytes | 32k | 1.00 GB | 119 MB + shared KV | +| Capture (on the request path) | 32k | 3 ms | ~3 ms | +| Persist one checkpoint | 32k | 2.3 s | 399 ms | +| Restore from RAM | 32k | 10 ms | 10 ms | +| Restore from disk (cold) | 32k | 907 ms | 1.0 s | +| Prefill instead (cold) | 32k | 25.8 s | 25.8 s | +| Checkpoints of this conversation in the RAM budget | 32k | 9 | 56 | +| Checkpoint bytes | 100k | 2.87 GB | 119 MB + shared KV | +| Capture (on the request path) | 100k | 3 ms | ~3 ms | +| Persist one checkpoint | 100k | 6.5 s (skipped: > staging) | 399 ms | +| Restore from RAM | 100k | 29 ms | 29 ms | +| Restore from disk (cold) | 100k | 2.6 s | 2.9 s | +| Prefill instead (cold) | 100k | 80.4 s | 80.4 s | +| Checkpoints of this conversation in the RAM budget | 100k | 3 | 43 | +| Checkpoint bytes | 149k | 4.21 GB | 119 MB + shared KV | +| Capture (on the request path) | 149k | 3 ms | ~3 ms | +| Persist one checkpoint | 149k | 9.6 s (skipped: > staging) | 399 ms | +| Restore from RAM | 149k | 42 ms | 42 ms | +| Restore from disk (cold) | 149k | 3.8 s | 4.3 s | +| Prefill instead (cold) | 149k | 2.0 min | 2.0 min | +| Checkpoints of this conversation in the RAM budget | 149k | 2 | 34 | + +#### 27B (DFlash2) + +| Operation | Depth | Today | Hybrid | +| --- | ---: | ---: | ---: | +| Checkpoint bytes | 32k | 2.34 GB | 244 MB + shared KV | +| Capture (on the request path) | 32k | 106 ms | ~14 ms | +| Persist one checkpoint | 32k | 5.3 s | 859 ms | +| Restore from RAM | 32k | 23 ms | 23 ms | +| Restore from disk (cold) | 32k | 2.1 s | 2.4 s | +| Prefill instead (cold) | 32k | 94.0 s | 94.0 s | +| Checkpoints of this conversation in the RAM budget | 32k | 9 | 67 | +| Checkpoint bytes | 100k | 6.80 GB | 244 MB + shared KV | +| Capture (on the request path) | 100k | 181 ms | ~14 ms | +| Persist one checkpoint | 100k | 15.4 s (skipped: > staging) | 859 ms | +| Restore from RAM | 100k | 68 ms | 68 ms | +| Restore from disk (cold) | 100k | 6.2 s | 7.0 s | +| Prefill instead (cold) | 100k | 5.8 min | 5.8 min | +| Checkpoints of this conversation in the RAM budget | 100k | 3 | 52 | +| Checkpoint bytes | 149k | 10.01 GB | 244 MB + shared KV | +| Capture (on the request path) | 149k | 236 ms | ~14 ms | +| Persist one checkpoint | 149k | 22.7 s (skipped: > staging) | 859 ms | +| Restore from RAM | 149k | 100 ms | 100 ms | +| Restore from disk (cold) | 149k | 9.1 s | 10.3 s | +| Prefill instead (cold) | 149k | 9.7 min | 9.7 min | +| Checkpoints of this conversation in the RAM budget | 149k | 2 | 42 | + +"Prefill instead (cold)" extrapolates the fitted model to a cold prompt. The +earlier measurements in [KV-CACHE.md](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/KV-CACHE.md) were 280 s for 101,545 +27B tokens (a different configuration) and 184 s for 203,047 Flash-Next tokens, +so these numbers are within about 25% and directionally right. + +### Background costs + +**Compaction** (hybrid only) rewrites a lineage's chunk files into one file. +It reads and writes the KV bytes once, at 1.1 GB/s and 0.59 GB/s: + +| Conversation | KV bytes | Compaction I/O | +| --- | ---: | ---: | +| Flash-Next at 149k tokens | 4.1 GB | ~11 s, in the background | +| 27B at 149k tokens | 9.8 GB | ~25 s, in the background | + +**Disk writes per long agent session** (the W1 runs to 149k tokens, from E8 revision 2; compaction not included): + +| Model | Today | Hybrid | +| --- | ---: | ---: | +| Flash-Next | 7.0 GB, with deep writes skipped | 5.7 GB | +| 27B | 16.5 GB, with deep writes skipped | 13.2 GB | + +### Reading the tables + +1. **Restore costs the same in both designs.** It is bound by bytes, and the + hybrid reads the same bytes, approximately 13% slower in the recorded chunk-file microbenchmark; + compaction benefits remain unqualified. Restoring from disk is 28–64× cheaper than prefilling. +2. **In these two measured layouts, capture savings primarily concern 27B.** Flash-Next already borrows KV, so the + hybrid changes nothing there. On 27B it saves about 90–220 ms per + checkpoint at 32–149k tokens, on the request path. +3. **Persisting is where today's design breaks.** A deep full checkpoint takes + 6–23 s to write and does not fit the automatic staging budget, so it is + skipped. The hybrid writes 0.4–0.9 s per 2,048-token step. +4. **RAM capacity:** + - today the budget holds 2–3 checkpoints of one long conversation; + - the hybrid holds 34–52, which is what makes dense checkpoints + (message boundaries, a shared system prompt) affordable. + + +## Archived evidence and reproducibility + +The active cache-redesign directory contains this RFC only. Research code and +data are preserved together through two pinned snapshots: + +| Snapshot | Contents | Retrieval | +| --- | --- | --- | +| `b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33` | Last supporting documents, 24 script/document files, 14 small measurement/fit inputs, run metadata and the original-data checksum manifest | [Browse](https://github.com/gufo-org/gufo/tree/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign), [download](https://github.com/gufo-org/gufo/archive/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33.tar.gz). | +| `a32fc43bcb9ec66264f166b5162d93a9223557d5` | All 133 original result files: token arrays, per-request metadata, server logs, measured fits and generated outputs | [Browse results](https://github.com/gufo-org/gufo/tree/a32fc43bcb9ec66264f166b5162d93a9223557d5/docs/cache-redesign/results), [download](https://github.com/gufo-org/gufo/archive/a32fc43bcb9ec66264f166b5162d93a9223557d5.tar.gz). | + +Keeping scripts/data out of the active tree does not rewrite these published +commits. Both commits are retained by the published non-release tag +[`research/cache-redesign-2026-10-08`](https://github.com/gufo-org/gufo/tree/research/cache-redesign-2026-10-08), +which points to `b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33`; +`a32fc43bcb9ec66264f166b5162d93a9223557d5` is its ancestor. This reachable +ref keeps the SHA-pinned browse/download/API links independent of squash +merging or deleting `fedeizzo/cache-redesign`. Preserve this research tag; do +not move or delete it without migrating the evidence and updating this RFC. +The archives provide provenance for historical measurements; they are not +matching performance controls for later cache implementations. + +### Recover and verify the research outside the checkout + +The commands below use authenticated `gh`, GNU tar and `sha256sum`. They extract +only the research scripts and results into a fresh temporary directory. Run +them from a Gufo checkout; the application source is not modified. + +```sh +export GUFO_REPO=$(git rev-parse --show-toplevel) +export CACHE_EXP_DIR=$(mktemp -d) + +gh auth status +gh api repos/gufo-org/gufo/git/ref/tags/research/cache-redesign-2026-10-08 \ + --jq .object.sha +gh api repos/gufo-org/gufo/tarball/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33 \ + > "$CACHE_EXP_DIR/research-tools.tar.gz" +gh api repos/gufo-org/gufo/tarball/a32fc43bcb9ec66264f166b5162d93a9223557d5 \ + > "$CACHE_EXP_DIR/research-results.tar.gz" + +tar -xzf "$CACHE_EXP_DIR/research-tools.tar.gz" -C "$CACHE_EXP_DIR" \ + --strip-components=3 --wildcards \ + '*/docs/cache-redesign/scripts/*' '*/docs/cache-redesign/results/*' +tar -xzf "$CACHE_EXP_DIR/research-results.tar.gz" -C "$CACHE_EXP_DIR" \ + --strip-components=3 --wildcards '*/docs/cache-redesign/results/*' + +cd "$CACHE_EXP_DIR" +sha256sum --quiet --check results/archive.sha256 +``` + +The check covers all 133 original result files before any analysis regenerates +outputs. The last scripts and retained inputs were compared byte for byte with +the recovered archive during RFC consolidation. Recovered datasets and new +outputs stay outside the checkout. + +### Replay existing summaries and regenerate simulations + +The cost model, overhead analysis and E8 summary use Python's standard library. +They can read existing archived outputs without GPU access or model weights: + +```sh +python3 scripts/cost_model.py +python3 scripts/analyze_e4.py +python3 scripts/summarize_e8.py +``` + +These three commands were successfully replayed during consolidation. The E8 +summary exactly matched archived `results/e8_summary.md`. This verifies archival +retrieval and summary reproduction, not a new hybrid implementation or a fresh +simulation of every trace. + +The archived summary includes an older legacy-improvement variant. Its values +remain available as history; this RFC's tables project the existing/hybrid +columns and the implementation plan does not propose that legacy work. + +Re-running token analysis, fitting and simulation requires the recorded Python +3.13 environment with NumPy (the research used 2.4.4). W1's functional driver +also needs `jsonschema`. With those dependencies available: + +```sh +python3 scripts/analyze_e3.py fn w2 +python3 scripts/simulate_e8.py fn w2 +python3 scripts/simulate_e8.py q27 w1 --restart-at 20 --abrupt +python3 scripts/fit_prefill.py +PYTHON=python3 scripts/run_e8.sh +python3 scripts/summarize_e8.py +python3 scripts/cost_model.py +``` + +Use models `fn` and `q27`; workloads are `w1`–`w4`, `w2-c4` and `w3-c4`. +Pass `--sessions 4` when replaying C=4 workloads individually. E8 revision 2 +is the reference. Archived E5/E7 code/results remain useful for understanding +how the simulator changed, but do not override the later reference results. + +### Rerun measurements against an explicitly selected binary + +Actual measurements require Strix Halo, the model/sidecar files and a Gufo +production binary. They start servers and reset their own experimental cache +directories. Keep the experiment directory separate from a serving cache and +stop conflicting model servers before invoking measurement drivers. + +| Variable | Meaning | +| --- | --- | +| `CACHE_EXP_DIR` | External root containing `scripts/`, `results/` and experimental `cache/`. | +| `GUFO_REPO` | Explicit source checkout used for corpora and functional drivers. | +| `GUFO_BIN` | Explicit candidate or baseline production binary; default is `$CACHE_EXP_DIR/bin/gufo`. | +| `LLAMA_TOKENIZE` | Explicit compatible llama.cpp tokenizer executable. | +| `FN_MODEL`, `FN_MTP`, `Q27_MODEL`, `Q27_DFLASH` | Actual model and speculative sidecar files. | +| `PYTHON` | Interpreter used by shell drivers; default `python3`. | + +The archived defaults contain paths from the original host. Override them +explicitly when measuring elsewhere. For a historical rerun, match the recorded +source/toolchain/harness and artifact identities; for implementation qualification, +record new matched controls instead of calling old results a current baseline. + +| Measurement / analysis | Archived tool | Notes | +| --- | --- | --- | +| E1 payload sizes | `run_e1.sh`, `e1_snapshot_size.py`, `fit_e1.py` | Raises disk staging to 6 GiB so deeper samples can be written. | +| E2 workload traces | `run_e2.sh`, `w1_agent.py`, `workloads.py`, `serverctl.py` | W1 uses `tests/functional/agent_long.py`; W2–W4 use synthetic histories with real replies. | +| Trace tokenization and E3 misses | `tokenize_traces.py`, `analyze_e3.py` | Builds `requests.npz` from rendered trace records and model vocabulary. | +| E4 measured overhead | `analyze_e4.py` | Reads server logs and records totals used in summary comparisons. | +| E6 concurrency | `run_e6.sh` | Four sessions/clients and a 131,072-token context. | +| E8 reference | `simulate_e8.py`, `run_e8.sh`, `summarize_e8.py` | Concurrent events, real capture/admission sequence, durable publication and provenance. | +| GPU copy microbenchmarks | `copybench.hip`, `chunkcopy.hip` | Build through `nix develop -c tools/bench/build.sh `. | +| Disk microbenchmark | `diskbench.py` | Can write up to 8.4 GB in the experiment cache directory. | +| Prefill/cost fitting | `fit_prefill.py`, `cost_model.py` | Fits are inputs to predictions, not production defaults. | + +Drivers check free disk space before GPU runs, with a 30 GB minimum in the +recorded tools. An experimental cache can reach its 16 GiB configured budget. +Do not run GPU sweeps merely to edit or review this document. + +The archived run metadata records source `b39c530e` (tree-identical to +`7f6ea6e1`), binary SHA-256 +`152383473e166d13271e61a38125925f3a8ce2b385b3c4ec82658e452cff7e73`, tokenizer +build 11382 and Qwen model snapshot +`4ca720788d1e01f1bff70c033e0d0028fd02e502`. Use the complete archived +[metadata](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/results/metadata.json) +and actual artifact fingerprints for matching controls. + +### Consolidation record and historical decisions + +| Former file / directory | Information retained here or in the pinned archive | +| --- | --- | +| `current-design.md` | Current-system mechanics, limitations and source baseline are in the RFC; precise historical source locations remain archived. | +| `hybrid-design.md` | Ownership, components, transfers, publication and worked examples are incorporated; earlier approximate examples remain archived. | +| `cache-package.md` | Common/model boundary, lifecycle contracts, capabilities and migration are incorporated. | +| `implementation-PLAN.MD` | Detailed delivery tasks, acceptance gates and existing suite mappings are incorporated with the expanded all-model scope. | +| `experiments.md` | Recorded E1–E4 and C=4 measurements, microbenchmarks and full E8 reference tables are incorporated; superseded E5/E7 tables remain archived. | +| `cost-model.md` | Full constants, per-operation estimates and background costs are incorporated with prediction caveats. | +| `options.md`, `external-engines.md` | All architectural alternatives and central tradeoffs are incorporated; version-specific historical tuning/defaults remain archived. | +| `decision-brief.md` | Findings and hybrid recommendation are incorporated; earlier legacy-fix proposals remain archived and are excluded from implementation scope. | +| `README.md` | Important discussion history is summarized below; the complete dated log remains archived. | +| `scripts/`, `results/` | Exact archived tools, inputs, outputs, checksums and recovery/replay instructions remain available through the two snapshots above. | + +Research began on October 7 with Flash-Next and 27B as the measurement scope; +DeepSeek was not measured in that round. The implementation scope subsequently +expanded to all model families. Earlier suggestions that paging/component +infrastructure was unnecessary merely because Gufo has few slots are superseded +by this RFC's explicit C=8 capacity qualification and adapter architecture. + +Issue [#275](https://github.com/gufo-org/gufo/issues/275) motivated investigating +one long conversation consuming disk capacity. PR +[#409](https://github.com/gufo-org/gufo/pull/409) proposed covered-intermediate +eviction; at the October 8 review its merge was on hold. The historical plan +also declined eager K=2 supersession, per-conversation byte caps and a checkpoint +interval flag. Those are discussion records, not requirements preventing +separately justified policy changes under this RFC. + +The October 8 reviews added provenance-safe sharing, spill reservations, +streaming in both directions, complete component positions, crash ordering, +pins, exclusive directory ownership and the two-layer package. Compaction was +deferred and E8 revised to model actual concurrency and durable publication. +Old scope, acceptance proposals and external-engine defaults are preserved +as history rather than silently presented as current decisions. + +## References + +- [Current design](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/current-design.md). +- [Hybrid design research](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/hybrid-design.md). +- [Cache package and model adapters](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/cache-package.md). +- [Implementation checklist](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/implementation-PLAN.MD). +- [Experiments and evidence](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/experiments.md), especially E8 revision 2. +- [Cost model](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/cost-model.md). +- [Evaluated options](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/options.md). +- [Other engines](https://github.com/gufo-org/gufo/blob/b9ca6b4e18abe50d4d446f5460823b7bcb4cdb33/docs/cache-redesign/external-engines.md). diff --git a/docs/internal/design/model-extensions/RFC.md b/docs/internal/design/model-extensions/RFC.md new file mode 100644 index 0000000000..7291a28661 --- /dev/null +++ b/docs/internal/design/model-extensions/RFC.md @@ -0,0 +1,1398 @@ +# RFC: model extensions + +Status: draft for maintainer review. Written 2026-10-30 against main +`5d66de8c`; revised after nine reviews the same day. Nothing in this document +is implemented. Inventories describe the inspected revision; counts are +reproducible with the commands in the [evidence appendix](#evidence-appendix), +and estimates are labelled as such. + +This is the single review document for turning Gufo models into build-time +extensions. It records the current coupling, the alternatives considered, +the recommended design, its stability policy and a delivery plan made of +small, testable PRs. + +Contents: + +- [Context](#context) and [problem statement](#problem-statement). +- [Goals](#goals-and-non-goals) and [glossary](#glossary). +- [Current system](#how-the-system-is-designed-now), with a coupling inventory. +- [Evaluated solutions](#evaluated-solutions), including prior art and a + comparison table. +- [Recommended design](#recommended-design-build-time-source-extensions). +- [Interface stability policy](#interface-stability-policy). +- [Distribution](#distribution) and [quality tiers](#quality-tiers-and-conformance). +- [Success criteria](#success-criteria-and-evaluation) and [risks](#risks). +- [Implementation plan](#implementation-plan) and [rollout](#compatibility-and-rollout). +- [Decisions](#open-questions), [evidence](#evidence-appendix) and + [references](#references). + +## Context + +Gufo serves a growing set of models on AMD Strix Halo (`gfx1151`): text +generation (DeepSeek V4 Flash, Qwen3.8 27B, Qwen3.8 Flash-Next), embeddings +(EmbeddingGemma 2), speech recognition (Qwen3-ASR), speech synthesis +(Qwen3-TTS), image generation (Qwen-Image-2.1) and audiovisual generation +(MiniMax H3). Each model ships hand-optimized kernels, its own numerical +contracts and, for text models, speculative decoding and continuation-cache +integration. + +Every model and quantization added today raises the maintenance load of the +whole project: a new model edits the CLI, the server, core enums, the build, +CI and the test registries, and every later change to those shared layers +must be checked against every model. Maintainers want a new model to arrive +as a self-contained unit that registers itself, so that integrating it +requires the minimum number of PRs to the core, ideally none beyond a +registration. + +Each Gufo process serves one model, together with its own draft, MTP head or +vision sidecar when those are enabled. Official artifacts are Nix outputs, +OCI images built by the Toolboxes repository and a Windows ZIP +([release process](../../releasing.md)). + +## Problem statement + +Model-specific knowledge is spread across shared layers. The consequences: + +- Adding a model requires edits to `src/cli/` (serve, prompt, bench, + kernel-bench, transcribe, video), core enums in `src/core/`, the root + `CMakeLists.txt`, `cmake/Checks.cmake`, `CMakePresets.json`, GitHub + workflows, Nix files and the functional-test registries. Reviews of a new + model therefore also review the core. +- Shared files grow with every model. `inference_backend.cpp` (4,070 lines) + contains every text model's runner; `openai_chat.cpp` (4,191 lines) scans + per-model tool-call markers. +- The model/core boundary is implicit and moves often. Core serving features + change the per-model runner interface regularly. +- Out-of-tree experimentation, such as a contributor's fork carrying a new + architecture, cannot be combined with upstream without merge conflicts in + the same shared files. +- Nothing prevents a model from depending on another model's internals or + on the CLI: four models include Qwen sources, DeepSeek includes server + logging, and nine model test files include `src/cli/` headers. + +A plugin mechanism alone does not reduce kernel-tuning work per model and +quantization. That cost is addressed separately (see +[non-goals](#goals-and-non-goals) and [host services](#host-services)); this +RFC removes the integration and coupling cost and creates the seam that lets +shared kernels be reused. + +## Goals and non-goals + +Goals: + +- A model is an extension: one directory with its sources, kernels, tests, + documentation and manifests. Building and testing an in-tree model + **within an existing capability** touches no file outside its own + directories: no CLI, core, CMake, preset, workflow, Nix or registry edits, + except new flake inputs, new modules in the shared `tools/gufo/` Python + package and new Windows dependencies in `vcpkg.json`. A new extension + absent from `extensions.lock` counts as unshipped by default. + Shipping it in official artifacts additionally takes a one-line edit to + the pinned extension list. Committed generated files (the models index, + third-party notices, the merged functional registries) are regenerated + for both testing and shipping; model-specific functional + suites that + [AGENTS.md](../../../../AGENTS.md) keeps in `tests/functional/` remain there. +- An out-of-tree extension builds into Gufo with zero changes to the Gufo + repository, through CMake and Nix. +- Registration is explicit, generated by the build, and debuggable. No + reliance on static-initialization side effects. +- The boundary is at step level: one call performs a whole prefill pass, + decode step, decode batch, embedding batch or synthesis chunk. There are no + per-layer or per-kernel calls in the serving interfaces, so the boundary + costs no measurable performance. +- A versioned interface whose evolution is mostly additive, with a written + stability policy and measurable criteria for declaring it stable. +- Official artifacts keep working as today. Third parties can publish their + own images with a documented recipe. +- The core keeps owning HTTP/OpenAI semantics, cross-request scheduling for + text, the + continuation cache policy and budgets, diagnostics and the functional + harness. + +Non-goals for the initial implementation: + +- Runtime loading of binary plugins (`.so`/`.dll`). Kept as a later, + separately evaluated layer on the same interface. +- A stable ABI. Only source (API) compatibility is promised. +- New capability kinds without core changes. Capabilities are core-owned; + adding one (for example realtime speech-to-speech) is a core change. +- A generic graph or IR model format that removes model code. +- Reducing per-model kernel tuning. The design must not block a shared + kernel library, but building one is separate work. +- Hosting several unrelated models in one process. +- Changing any model's numerical behavior or cache identity. Migration is a + refactor and must be byte-identical where the lossless-precision gate + applies. + +## Glossary + +| Term | Meaning | +| --- | --- | +| Extension | A unit of model code, with manifests, built into Gufo and registered through the generated registry. | +| In-tree extension | An extension under `src/models//` in the Gufo repository. | +| Out-of-tree extension | An extension in another repository, added with `GUFO_EXTENSION_DIRS` or the Nix `extensions` argument. | +| Metadata manifest | `extension.json`: declarative facts (name, versions, capabilities, keys, options, conditions, packages, tests) readable by CMake, Nix and Python without building. | +| Build manifest | `extension.cmake`: the build logic (targets, sources, HIP options) for the extension. | +| Registry | The build-generated table that maps artifact keys to extension providers. | +| Provider | One loadable model kind registered by an extension, for one capability. | +| Capability | A core-owned family of behavior with its own interface: text generation, embeddings, speech recognition, speech synthesis, image generation, video generation. | +| Artifact key | A matchable identity of a primary artifact, such as `gguf:qwen4exp` or a safetensors `architectures[0]`. | +| Probe | A provider's pure, HIP-free check that confirms it can load an artifact matched by key. | +| Artifact set | The files a provider loads: primary file, shards, sidecars (such as `--mmproj`) and draft artifacts. | +| Family library | A shared library of code used by several extensions of one model family, such as Qwen control tokens. | +| Host services | Core facilities an extension may call: allocation, staging, snapshot backing, transfers, cache contracts, sampling and constraint state, logging, tracing, kernel plans. | +| Extension API | The versioned C++ headers under `include/gufo/ext/`, the CMake functions and the metadata schema extensions use. | +| Conformance suite | Capability-level functional tests every extension must pass. | +| Tier | The support level of an extension: core or community. | + +## How the system is designed now + +### Build and registration + +Models are built in three different ways: + +- **Separate static libraries:** DeepSeek V4 Flash (only under + `ENGINE_ENABLE_HIP`), Qwen3.8 Flash-Next, Qwen3-TTS, Qwen3-ASR, + EmbeddingGemma 2 and Qwen-Image-2.1 build their own `gufo_` targets. + Flash-Next builds its library and CPU tests without HIP too; the hosted + CPU `check-pr` runs some of them. +- **Compiled into `gufo_core`:** the whole Qwen 27B model (tokenizer, chat + template, forward pass, HIP kernels, vision encoder, continuation adapter) + is added with `target_sources(gufo_core PRIVATE ...)` from + `src/models/qwen/CMakeLists.txt`. MiniMax H3's sources are listed in the + root `CMakeLists.txt` and also compiled into `gufo_core`, as are + `src/eval/{dataset,extract,regrade}.cpp`, `src/testing/compare` and, under + HIP, + `src/core/speculative/speculative_verifier.cpp`, whose header includes the + Qwen executor, generator, DFlash policy and tokenizer. +- **Inside the HTTP library:** `src/models/deepseek_v4_flash/tool_calls.cpp` + is compiled into `gufo_http`. + +`gufo_core` therefore compiles and exposes Qwen 27B and H3 to every +consumer. The repository root is a public include directory of almost +every target (`gufo_core`, `gufo_platform`, `gufo_cache`, `gufo_hip_host`, +`gufo_logging`, `gufo_diagnostics`, `gufo_kernel_bench_support` and the +model libraries); every source includes by root-relative +path (`#include "src/models//..."`), so nothing restricts which headers +a model includes. CMake cannot remove a public include directory for only +some consumers. + +There is no registry. The CLI selects a model either by subcommand +(`gufo serve llm|embedding|tts|asr|image|video`) or, within `llm`, by reading +`general.architecture` from the GGUF and branching: `deepseek4`, `qwen4exp`, +otherwise Qwen 27B as the fallback for any other architecture. Within Qwen, +vision support and sampling presets are chosen by tensor shape +(`qwen35.embedding_length == 5120`; 64 layers, hidden size 5120 and vocabulary +248,320). `prompt` and `bench` repeat their own architecture checks and load +models directly, without the server's runner layer. `kernel-bench` calls +individual Qwen kernels. `eval` is an HTTP client and loads no model; its +only model coupling is the DeepSeek fixture path compiled in through +`GUFO_EVAL_SOURCE_DATA`. + +### The text-generation boundary today + +The real per-model boundary for text is `TextModelRunner` +(`src/cli/serve/text_model_runner.hpp`), not `TextGenerationBackend`. +`TextGenerationBackend` is the request-level interface the HTTP layer uses, +and it has one implementation, `InferenceBackend`. Below it, +`TextGenerationScheduler`, `TextRunnerPool` and `ComponentTextCache` drive +per-model runners through `TextModelRunner`'s 46 virtual methods: + +- Prefill: `Prefill`, `PrefillThrough` with in-pass checkpoint callbacks. +- Decode: `SelectNext`, `Advance`, `DecodeStep`, `DecodeBatch`, + `AdvanceBatch`, which take core-owned `SamplerState` (grammar constraint, + reasoning budget, stop handling, logprobs). +- State: `Snapshot`, `RestoreOrFork`, persistent-snapshot serialization, + streaming and restore. +- Resources and planning: `ResourceClaim`, `SupportedPlans`, `PollDevice`, + `BuildConstraintVocabulary`. +- `TextRunnerCapabilities`, which tells the scheduler whether incremental + prefill, snapshots, forks, batched multi-token decode (with a width + limit), in-pass checkpoints, partial prefill retention and prefill + rollback are available. + +The implementations `QwenTextRunner`, `DeepSeekTextRunner` and +`QwenFlashNextTextRunner` all live in `inference_backend.cpp`, on top of a +shared `HipTextModelRunner`, which only does device probing (`PollDevice`, +`DeviceUsable`). Next to it, the template `CreateHipComponentCacheResources` +holds the component cache's pinned-host backing (segment sizing, commit +growth, host-reserve pressure retries, a 2 GiB pre-readiness reserve) for +Qwen 27B and Flash-Next. It calls a method that is not part of +`cache::Adapter`, `BackingPlan(budget)`, which each model's adapter +implements with its own `ContinuationBackingClass` struct: an unlisted +model/core contract. DeepSeek's native snapshots and all three runners' +`ResourceClaim` use the same host budget functions +(`HostSnapshotBudgetBytes`, `HostSnapshotCeilingBytes`). + +Each model also builds its cache compatibility identity there, as one +model-specific serialization in which core-owned lines (schema, artifact and +draft fingerprints, context tokens, decode concurrency, draft limits) are +interleaved with model lines. A second, process-local identity +(`model_instance=`) keys RAM reuse within one process. + +The header is not only the runner contract. It also holds RAM and disk cache +options, memory-budget functions and `TextRunnerPool`, and it depends on +`ChatRequest`, `TextGenerationBackend::InitialOutputState`, +`ContinuationState`, `cache::ResourceLedger` and `ComponentCacheResources`. + +The runner contract also depends on serve-layer types: +`TextRunnerState` and `TextRunnerSnapshot` derive from `ContinuationState` +and `ContinuationSnapshot` (`src/cli/serve/continuation_cache.hpp`), and the +header includes `text_publication_wait.hpp`, `TextGenerationBackend` and +`sampling::JsonConstraint::ToolFormat`. Its out-of-line defaults +(`text_model_runner.cpp`), the continuation cache, the scheduler and +`inference_backend.cpp` are compiled directly into the `gufo` executable, +and model tests compile those sources into their own binaries; there is no +serving library. + +The contract moves often. In the 30 days before 2026-10-30, the +`TextModelRunner` class body changed in 12 commits, 11 of them substantive +(the whole header in 28, including cache options and pool changes that did +not affect runners), and `text_generation_backend.hpp` in 22. Commits that +changed the runner's virtual methods include #524, #573, #445, #821 and +#683. + +### Continuation state per model + +Prompt reuse reaches models through two paths: + +- **Component cache adapter:** Qwen 27B and Flash-Next implement + `cache::Adapter` (`src/cache/adapter.hpp`): components, compatibility + identity, slots, capture/restore and prefill planning. +- **Native runner snapshots:** DeepSeek V4 Flash has no `cache::Adapter`. It + provides `snapshot`, `fork` and `prefix_reuse` through + `DeepSeekTextRunnerSnapshot` and a persistence descriptor in its runner. + +The [continuation cache RFC](../cache-redesign/RFC.md)'s all-model cutover is +still open, so both paths are current product behavior. + +### Coupling inventory + +References to each model outside `src/models/`, under `src/cli`, `src/core`, +`src/cache`, `src/eval` and `src/testing` (matching lines from the +[inventory command](#inventory-commands); the count includes comments and +depends on the pattern, so it indicates where coupling lives rather than +exact effort). The root `CMakeLists.txt` mentions models on 225 of its 1,366 +lines. + +| Model | Files outside its directory that reference it | +| --- | --- | +| DeepSeek V4 Flash | `serve/inference_backend.cpp` (34), `bench/bench.cpp` (18), `serve/openai_chat.cpp` (15), `prompt/prompt.cpp` (14), `serve/inference_backend.hpp` (2), `eval/eval.cpp` (1) | +| Qwen (27B and shared) | `serve/inference_backend.cpp` (27), `prompt/prompt.cpp` (13), `bench/kernel_bench_main.cpp` (6), `core/speculative/speculative_verifier.hpp` (4), `bench/bench.cpp` (3), `core/quant/ggml_dequant.hpp` (2, comments), `serve/text_generation_backend.hpp` (2), `serve/inference_backend.hpp` (1), `core/speculative/draft_backend.hpp` (1), `serve/http_server.cpp` (1), `serve/openai_chat.cpp` (1), `core/quant/ggml_gemm.hpp` (1, comment) | +| Qwen3.8 Flash-Next | `serve/inference_backend.cpp` (16), `prompt/prompt.cpp` (8), `bench/bench.cpp` (4), `bench/bench.hpp` (2), `serve/inference_backend.hpp` (2) | +| Qwen3-TTS | `serve/tts_service.cpp` (23), `serve/tts_service.hpp` (13), `serve/audio_tts_api.cpp` (12), `serve/tts_websocket.cpp` (5), `serve/serve.cpp` (2) | +| Qwen3-ASR | `serve/asr_service.cpp` (13), `transcribe/transcribe.cpp` (9), `serve/asr_service.hpp` (7), `serve/audio_asr_api.cpp` (5), `serve/asr_websocket.cpp` (5) | +| EmbeddingGemma 2 | `serve/embedding_service.cpp` (16), `serve/embedding_service.hpp` (6), `serve/embeddings_api.cpp` (2), `serve/serve.cpp` (1) | +| MiniMax H3 | `serve/video_jobs.cpp` (12), `video/video.cpp` (11), `serve/video_jobs.hpp` (6), `serve/video_api.cpp` (3), `video/video.hpp` (2) | +| Qwen-Image-2.1 | `serve/image_api.hpp` (5), `serve/image_api.cpp` (1), `serve/serve.cpp` (1) | + +Paths are under `src/cli/` unless they start with `core/`. + +Model knowledge that is not a model-name reference but must still move: + +| Location | What it encodes | +| --- | --- | +| `src/core/json_constraint.hpp` / `.cpp` | `ToolFormat { kJson, kQwen, kDeepSeek }`; the Qwen XML and DeepSeek DSML tool grammars are interleaved with schema-driven value grammars through the schema compiler. | +| `src/cli/serve/openai_chat.cpp` | Streaming tool-call marker scanning per dialect, a JSON fallback that recognizes every dialect's markers plus client envelope closers, per-dialect reasoning-separator rules, and parsers using core helpers (`SchemaAccepts`, `PythonLiteralsToJson`, `QuoteTracker`). | +| `src/core/text_sampling_defaults.hpp` | `TextModelPreset { kQwen38, kDeepSeekV4Flash }`, selected by architecture string and layer shape. | +| `src/core/model_config.hpp`, `src/core/gguf_reader.cpp` | `ModelConfig` and `GgufReader::ExtractModelConfig` are shaped for Qwen hybrids (`ssm.*`, `full_attention_interval`, `nextn_predict_layers`, fallback architecture `"qwen"`); `architecture` defaults to `"qwen35"`. | +| `src/cli/serve/inference_backend.hpp` | `TextSpeculativeBackend { kDisabled, kDFlash, kDSpark, kMtp }`: valid `--speculative` values and their validation are model-specific. | +| `src/cli/serve/text_generation_backend.hpp`, `src/core/speculative/` | Server and speculative types come from `src/models/qwen/` (`ChatMessage`, `ChatTool`, tokenizer, Qwen executor and DFlash policy). | +| `src/cli/serve/serve.cpp`, `bench/bench.cpp` | Per-command option definitions (`--speculative`, `--enable-yarn`, draft paths), help text, `--mmproj` sidecar discovery, GPU queue profiles chosen per subcommand before any HIP call. | +| `src/cli/serve/http_server.cpp` | `/v1/models` listing: `owned_by` strings (text models report `gufo`) and H3's five preset model IDs with `root` and `capability`. | +| `tools/ci/` | `kernel-resources.json` scratch allowances keyed by model kernel symbols, vendored model paths in `check-format.py`, a model list in `check-docs.py`, DS4 in `check-dependencies.py`. | +| `src/cli/main.cpp` | Help text naming models. | +| `cmake/Checks.cmake`, `CMakePresets.json` | Hand-maintained `check-pr` test lists (including Windows) and per-model test presets. | +| `.github/workflows/` | Explicit Windows build target lists and devlab workflows. | +| `.devops/nix/package.nix`, `mk-serve.nix`, `flake.nix` | Evaluation-time source-filter exceptions for model fixtures, per-model module arguments (`dflashModel`, `dsparkModel`, `mtpModel`), and per-model references. `package.nix` passes its own CMake flags rather than using presets. | +| `tests/functional/devlab.json`, `impact.json` | Two schemas with different profile sets: model profiles, shared assets (also across models, such as the ASR asset in the TTS round trip), representatives, disabled entries, core-path impact rules that enumerate every model's profiles, and rules mapping model-owned core paths (such as `src/cli/serve/embedding*`, `asr*`) to models. | +| `tests/functional/*.py` | 21 of 87 files contain model-specific logic; AGENTS.md keeps them in `tests/functional/`. | +| `tools/` | Per-model tools (`tools/qwen27b`, `tools/qwen-flash`, `tools/ds4`, `tools/h3`, `tools/models/*`), model Python tests in `tests/tools/`, per-model flake checks, devshell Python dependencies and reference packages in `flake.nix` and profiler knowledge. | +| Root `CMakeLists.txt` install rules, `THIRD_PARTY_NOTICES.md`, `licenses/`, `docs/models/README.md` | H3 manifest, DeepSeek eval fixture, `LICENSE.ds4`, notices and the model index. | + +Cross-model and model-to-CLI dependencies: + +| Extension-to-be | Depends on | +| --- | --- | +| Flash-Next | Qwen tokenizer and chat template (its cache identity hashes `QwenChatTemplate::OfficialTemplateSha256()`), Qwen kernels (`prefill_quant_gemm.hpp`) and the Qwen vision stack. | +| Qwen3-TTS | `qwen/control_tokens.hpp` and Qwen HIP ops (`qwen/hip/ops.hpp`). | +| Qwen-Image-2.1 | Qwen tokenizer and control tokens. | +| MiniMax H3 | `qwen/control_tokens.hpp` only. | +| DeepSeek V4 Flash | `src/cli/serve/logging.hpp` (three files): the only production `src/cli/` include in a model directory. | +| Model tests | Nine test files across eight test directories include `src/cli/` headers (for example `qwen3_asr/tests/audio_api_test.cpp`, `tests/models/embedding_gemma2/embeddings_api_test.cpp`). | + +Core headers used by model directories (by include count, from the +[inventory command](#inventory-commands)): + +| Model | Core headers | +| --- | --- | +| Qwen 27B | `gguf_reader` (26), `hip/detail/*` dispatch telemetry and GEMV dispatcher (20), `hip/hip_utils` (17), `quant/ggml_dequant` (7), `model_config` (5), `sampling` (4), `image` (3), `speculative/draft_backend`, `hip/snapshot_transfer`, `hip/managed_alloc`, `hip/host_allocations`, `crypto/sha256`, `speculative/prompt_lookup`, `reasoning`, `quant/ggml_gemm`, `platform/prefault`, `platform/pages`, `mapped_prefetch`, `hip/weight_upload`, `hip/transfer_pool`, `hip/snapshot_copy`, `hip/heap_placement` | +| Flash-Next | `hip/managed_alloc` (5), `gguf_reader` (5), `sampling` (3), `session_mode` (2), `quant/ggml_dequant` (2), `speculative/prompt_lookup`, `platform/pages`, `platform/mapped_file`, `platform/fs`, `hip/weight_upload`, `hip/transfer_pool`, `hip/snapshot_transfer`, `hip/snapshot_copy`, `hip/host_allocations` | +| DeepSeek V4 Flash | `platform/mapped_file` (3), `sampling` (2), `session_mode`, `reasoning`, `platform/publish`, `platform/os_info`, `platform/fs`, `mapped_prefetch`, `json`, `hip/weight_upload`, `hip/snapshot_transfer`, `hip/managed_alloc`, `gguf_reader`, `crypto/sha256` | +| EmbeddingGemma 2 | `json` (6), `hip/hip_utils` (2), `platform/mapped_file`, `platform/library`, `image` | +| Qwen3-ASR | `json` (3), `hip/weight_upload` (2), `utf8`, `platform/prefault`, `platform/mapped_file`, `mapped_prefetch`, `gguf_reader`, `cancellable_gate` | +| Qwen3-TTS | `json` (3), `mapped_prefetch` (2), `hip/weight_upload` (2), `platform/prefault`, `platform/mapped_file`, `gguf_reader` | +| Qwen-Image-2.1 | `platform/mapped_file`, `mapped_prefetch`, `json`, `image`, `hip/weight_upload`, `gguf_reader`, `crypto/sha256` | +| MiniMax H3 | `platform/mapped_file` (6), `platform/os_info` (4), `mapped_prefetch` | + +### Existing seams to build on + +- **`TextModelRunner`** already separates the scheduler and cache from + per-model execution. Its runner contract is the starting point for the + text extension interface, after the header is split and the + implementations move out of `inference_backend.cpp`. +- **`cache::Adapter`** is a model-provided interface owned by a common + package. The cache RFC already states that "plug in means an explicit + interface and registration; dynamic library loading is not required". This + RFC applies that principle to the whole model. +- **Service classes** (`EmbeddingService`, `TtsService`, `AsrService`, + `ImageService`, `VideoJobService`) isolate the HTTP surface from the model + for non-text capabilities, although each is written against one concrete + model's types (for example `EmbeddingService` options use + `embedding_gemma2::VideoOptions`). EmbeddingGemma 2's batch scheduler lives + in its model directory. +- **`devlab.json` and `impact.json`** already describe models, assets and + impact rules as data, consumed by the harness and by + `.github/workflows/devlab-*.yml` and `windows-build.yml`. + +## Evaluated solutions + +### Build-time source extensions — recommended + +An extension is source code with manifests. CMake discovers in-tree +extensions under `src/models/*/` and out-of-tree ones from +`GUFO_EXTENSION_DIRS`, builds them against the extension API, and generates a +registry translation unit that calls each extension's entry point. Nix +exposes the same thing as `gufo.override { extensions = [ ... ]; }`, reading +the same declarative metadata. + +Compatibility is a source (API) promise: an extension is always compiled with +the same compiler, ROCm and flags as the host, and is statically linked with +one copy of `gufo_core`. There is no ABI to freeze, no duplicated singletons, +no DLL/CRT problems on Windows, and the boundary costs nothing compared with +today. The cost is that combining an official artifact with an arbitrary +third-party extension requires a rebuild. + +The detailed design follows in +[Recommended design](#recommended-design-build-time-source-extensions). + +### Runtime binary plugins + +Extensions as shared libraries loaded with `dlopen`/`LoadLibrary` from a +plugin directory. This is the only option where an official artifact accepts +a third-party model without a rebuild. + +Requirements this would add: + +- A C ABI, or an exactly pinned toolchain checked at load time, because the + C++ ABI (layouts, `std::` types, exceptions) is not stable across compilers + and standard libraries. Prior art that succeeds (ONNX Runtime's versioned + `OrtApi` function table, Triton's `TRITONBACKEND_*` API with major/minor + version checks, ggml's dynamically loaded backends) uses a C interface. +- `gufo_core` as a shared library. If the executable and a plugin both + linked it statically, one process would contain two transfer pools, two + staging budgets and two pinned-memory accountings; serve and the cache + would use one copy while the model used the other, and neither copy would + see the other's allocations. +- Load-time verification of ROCm and HIP runtime versions, and Windows + handling of CRT heaps across DLL boundaries. + +Performance would not change if the boundary stays at step level: one +indirect call costs nanoseconds against millisecond decode steps, and Gufo +does not use LTO today, so no cross-module inlining is lost. The cost is +engineering and stability, not speed. Freezing an ABI before the API has been +exercised by eight models, while the runner contract still changes weekly, +would freeze its mistakes. + +Recommendation: defer. Add it later as a C shim over the same C++ interface +when there is concrete demand (see [rollout](#compatibility-and-rollout)). + +### Separate worker process + +The core process owns HTTP, scheduling and cache; each model runs in a worker +process speaking a Gufo IPC protocol, sharing device memory through +`hipIpcGetMemHandle`. Ollama's runner subprocesses are an example of this +split. + +It gives language independence and crash isolation. It also moves the +continuation cache, which manipulates model device memory under strict +ownership rules, across a process boundary; turns step-level scheduler calls +such as `DecodeBatch` into IPC round trips; doubles process lifecycle and +failure handling; and depends on HIP IPC support on Windows. The cost exceeds +the benefit for a one-model-per-process server. + +### Data-only extensions + +An extension as configuration (architecture parameters, tensor naming, op +graph) interpreted by shared kernels, as in ggml-style engines. This removes +code per model only for architectures that are combinations of existing +operations; every model Gufo ships today has bespoke kernels or state +(DeltaNet, compressed attention pools, MTP heads, diffusion schedulers). +It is not a replacement. A future "configurable decoder" extension could be +built on top of the source-extension mechanism for families that fit. + +### Keep the current design + +No migration cost. All current costs remain and grow with each model; the +implicit boundary keeps making shared changes risky. This is the baseline. + +### Prior art + +| Project | Mechanism | Lesson for Gufo | +| --- | --- | --- | +| vLLM | Out-of-tree models register through the `vllm.general_plugins` Python entry point calling `ModelRegistry.register_model`; plugin functions must be re-entrant; `VLLM_PLUGINS` filters which load. The documented registration call is guaranteed stable. | Registration by architecture name is enough as the integration point. Keep the registration surface tiny and promise its stability explicitly. | +| SGLang | `SGLANG_EXTERNAL_MODEL_PACKAGE` names a package whose modules expose `EntryClass`; also in-code `ModelRegistry` registration. | A single, discoverable entry symbol per extension. | +| Modular MAX | `max serve --custom-architectures path:package` imports a package exposing `ARCHITECTURES`, matched against the checkpoint's `architectures[0]`; a custom architecture overrides a built-in one of the same name. | Match on artifact identity, and make override behavior explicit. Gufo chooses an explicit error and selection over implicit precedence. | +| Triton Inference Server | Backends are shared libraries behind the `TRITONBACKEND_*` C API; minor versions add optional functions, majors must match. | If binary plugins come later: C API, major/minor negotiation, a coarse model-instance/execute boundary. | +| ONNX Runtime | `OrtApiBase::GetApi(version)` returns a versioned function table; structures carry a version field. | The reference shape for a future ABI layer: append-only, version-requested tables. | +| llama.cpp / ggml | Backends can be built as dynamically loaded libraries (`GGML_BACKEND_DL`, `ggml_backend_load_all`); models remain in-tree. Embedders hit "no backends are loaded" when they forget the loader. | Dynamic loading adds integration failure modes; explicit, generated registration avoids them. | +| Godot | C++ modules are compiled into the engine (requiring rebuilt export templates); GDExtension later added runtime-loaded native libraries, forward-compatible only (4.2 extensions work on 4.3, not the reverse). | The recommended path: build-time modules first, a binary interface once the API has matured. | +| Zephyr RTOS | Out-of-tree modules are discovered by a `zephyr/module.yml` or `zephyr/CMakeLists.txt` marker and passed with `EXTRA_ZEPHYR_MODULES`. | A declarative metadata file plus CMake build logic per module is proven at scale. | +| Linux kernel | `stable-api-nonsense.rst`: no stable in-kernel API; whoever changes an interface fixes all in-tree users. | Core-tier models stay in-tree so interface changes are fixed with them; out-of-tree extensions get an explicitly versioned surface. | + +### Comparison table + +Green means a good fit for the row; yellow means conditional or extra work; +red means the option leaves the requirement unresolved. + +| Requirement | Source extensions, recommended | Binary plugins | Worker process | Data-only | Current | +| --- | --- | --- | --- | --- | --- | +| New in-tree model without core edits | 🟢 Directory plus manifests | 🟢 Same | 🟢 Same | 🟡 Only for fitting architectures | 🔴 Edits CLI, core, CMake, CI | +| Out-of-tree model with no Gufo PR | 🟢 `GUFO_EXTENSION_DIRS` / Nix | 🟢 Drop-in library | 🟢 Separate binary | 🟡 Config only | 🔴 Fork required | +| Official artifact plus third-party model, no rebuild | 🔴 Rebuild required | 🟢 Drop-in | 🟢 Drop-in | 🟢 Drop-in | 🔴 Fork required | +| Performance | 🟢 Identical to today | 🟢 With step-level boundary | 🟡 IPC per scheduler step, cross-process cache | 🔴 Loses bespoke kernels | 🟢 Baseline | +| Compatibility promise | 🟢 API only | 🔴 ABI, C shim, toolchain checks | 🟡 Wire protocol | 🟡 Schema | 🟢 None needed | +| Single `gufo_core` state | 🟢 One static link | 🟡 Requires shared core | 🟡 Split across processes | 🟢 One process | 🟢 One process | +| Continuation cache integration | 🟢 In-process adapter or snapshots | 🟢 In-process | 🔴 Cross-process device memory | 🟡 Generic only | 🟢 Existing | +| Windows | 🟢 Same build | 🟡 DLL/CRT boundary | 🟡 HIP IPC support | 🟢 Same build | 🟢 Same build | +| Incremental delivery | 🟢 Model by model | 🟡 After ABI design | 🟡 After protocol design | 🔴 Rewrite | 🟢 Nothing to deliver | + +## Recommended design: build-time source extensions + +### Layout + +```text +include/gufo/ext/ public extension API (versioned headers) + version.hpp GUFO_EXTENSION_API_VERSION_{MAJOR,MINOR,REVISION} + registry.hpp Registry, ProviderInfo + artifact.hpp ArtifactKey, ArtifactSet (primary, shards, sidecars, drafts) + options.hpp OptionSpec, ParsedOptions + host.hpp Host services handle + text_generation.hpp capability interfaces, one header each + embeddings.hpp + speech_recognition.hpp + speech_synthesis.hpp + image_generation.hpp + video_generation.hpp + platform/ re-exported platform leaves (mapped files, pages, fs, ...) + experimental/ no stability guarantee (initially: tool syntax and + grammar builder, kernels and HIP utilities, + transfer primitives, most runner extensions) + +cmake/GufoExtension.cmake gufo_extension(), gufo_extension_hip_sources() +schemas/extension.schema.json + +src/models// an in-tree extension + extension.json metadata manifest + extension.cmake build manifest + extension.cpp entry point: registers providers + ... model sources, kernels, cache integration + tests/ unit/operator tests, registered by the manifest + functional/ devlab and impact registry fragments + tools/ model-specific tools (optional) + +src/families// family libraries, each with its own manifests + qwen/control_tokens/ ... + +/generated/extension_registry.cpp one per executable +/generated/_constants.hpp per-extension constants from metadata +``` + +Documentation can stay under `docs/models//` and tests under +`tests/models//` during migration, provided they are registered by the +manifests; physical moves are an +[open question](#to-resolve-before-dependent-implementation). + +### Include scheme + +- Extensions include the extension API as `` and their own + files relative to their extension root, which the build adds as a private + include directory. In-tree extensions keep root-relative includes of their + own files during migration. +- Core headers that models use today (see the + [inventory](#coupling-inventory)) are classified one by one: re-exported + under `include/gufo/ext/` (stable, `platform/` or `experimental/`), wrapped + by a host service, or made private to the core. Publishing these headers + is its own plan step, before the pilot. +- The root `CMakeLists.txt` also adds the repository root tree-wide + (`include_directories`), force-includes `libstdcxx_noinline.hpp` and sets + Windows compile definitions per directory; out-of-tree directories added + with `add_subdirectory` inherit these, so `gufo_extension()` and the step + 11 allowlist check account for inherited directory properties. The + `GUFO_PLATFORM_ONLY` early return skips discovery and registry + generation. +- Re-exporting means **forwarding headers**: `include/gufo/ext/...` headers + include the real `src/...` headers, which stay where they are (the + platform leaves stay in `src/core/platform/`, as AGENTS.md requires). The + repository root therefore remains a public include directory, and the + isolation check is the permanent enforcement mechanism: extension code may + include only `gufo/ext/...`, its own files and its declared `depends`. + `gufo_extension()` adds no further public include directories. +- Because forwarded headers stay in `src/`, the API surface is defined by a + generated list (`include/gufo/ext/SURFACE`): the transitive include + closure of the forwarding headers, such as `json_constraint.hpp` reached + through `sampling.hpp`. The API-change check, version bumps and the 1.0 + churn measurement watch those paths, including `src/cache/adapter.hpp`. + +### Target graph + +Extensions need libraries to link against, and the registry must not create +a cycle. The targets are: + +```text +gufo_platform, gufo_logging, gufo_hip_host platform leaves, logging, HIP host + ^ +gufo_cache, gufo_cache_hip cache contracts, staging, transfers, + ^ component cache backing +gufo_core HIP utilities, GGUF, JSON, sampling, + ^ constraints +gufo_ext_runtime extension API types, registry, defaults, + ^ ^ neutral continuation bases, host services, + | | host memory-budget queries + | | + | extensions gufo_, family libraries + | ^ +gufo_serving, gufo_http, gufo_llm_cli scheduler, pool, component text cache, +gufo_diagnostics InferenceBackend, HTTP, prompt/bench, + ^ diagnose +gufo_test_support HTTP and serving fixtures for model API + ^ tests (test executables only) +gufo, gufo-kernel-bench, test executables each compiles its own generated registry +``` + +`gufo_logging` keeps its name and position; logging code only moves out of +`src/cli/serve/`. + +Extensions depend on `gufo_ext_runtime` and the libraries below it, never on +`gufo_serving` or `gufo_http`. Serving, HTTP, CLI and diagnostics libraries +depend on `gufo_ext_runtime` and see extensions only through the registry +interface. The generated registry is compiled into each executable, +including `gufo-kernel-bench`, so no library depends on extensions; test +executables get a registry for only the extensions they test. +`gufo_diagnostics` receives the `Registry&` as an argument instead of +referencing an executable-defined symbol. + +Interim edges during migration: until steps 8 and 10 finish, `gufo_http` +links the non-text model libraries, `gufo_serving` contains the text +runners, and `gufo_llm_cli` and `gufo-kernel-bench` link model libraries +directly. Between steps 5 and 6, `gufo_serving` does not exist yet: the +`gufo` executable, `gufo_http`, `gufo_llm_cli` and the three test binaries +that compile `inference_backend.cpp` link `qwen_text` and the Qwen 27B +library directly, because server types still come from them. These edges are listed in the isolation report and removed model by +model; the final graph holds only after step 10. + +### Metadata and build manifests + +The **metadata manifest** carries everything CI, Nix, Python and the +registry generator need without compiling or configuring: + +```json +{ + "schema": 1, + "name": "qwen38_flash_next", + "api_version": "0.1", + "version": "0.4.0", + "entry": "gufo_ext_qwen38_flash_next_register", + "depends": ["qwen_text", "qwen_kernels", "qwen_vision"], + "providers": [{ + "id": "qwen38-flash-next", + "capability": "text_generation", + "keys": ["gguf:qwen4exp"], + "speculative": ["mtp"] + }], + "options": [ + {"name": "--mtp-model", "type": "path", "commands": ["serve llm", "bench", "prompt"]} + ], + "targets": { + "gufo_qwen38_flash_next": {"requires": []}, + "gufo_qwen38_flash_next_hip": {"requires": ["hip"]} + }, + "platforms": ["linux", "windows"], + "packages": [{"pkg_config": "libavformat", "nix": "ffmpeg", "windows": "ffmpeg[avformat]"}], + "compile_definitions": {"GUFO_EXAMPLE_DATA": "install_data:example.json"}, + "runtime_libraries": ["gufo-video-libraries.txt"], + "install_data": [], + "licenses": [], + "production_paths": {"include": ["**/*.cpp", "**/*.h", "**/*.hpp", "**/*.hip", "extension.*"], + "exclude": ["tests/", "functional/", "tools/", "fixtures/"]}, + "vendored_paths": [], + "kernel_resources": "kernel-resources.json", + "docs": {"title": "Qwen3.8 Flash-Next", "inputs": "Sharded Q4 GGUF; text/images", + "guide": "docs/models/qwen3.8-flash-next.md"}, + "tests": [ + {"target": "qwen38_flash_next_config_test", "ctest": "qwen38_flash_next\\.config", + "check_pr": true, "exclude_os": []}, + {"target": "qwen38_flash_next_ngram_test", "ctest": "qwen38_flash_next\\.ngram", + "check_pr": false, "windows_build": true} + ], + "test_labels": ["qwen38_flash_next"], + "fixtures": "tests/fixtures/", + "bundled_tests": [], + "functional": "functional/", + "tools": "tools/", + "python_checks": [{"name": "example-quality", "tests": "tests/tools/", "sources": ["tools/"]}] +} +``` + +`packages` maps each external dependency per ecosystem (pkg-config module, +Nix attribute, vcpkg port and features), and the `pkg_check_modules` calls +for model dependencies (libav, sndfile, soxr) move from the root build into +the extensions that need them; CMake cache variables with Nix store paths +come from `extension.nix`, and `runtime_libraries` replace today's core-owned settings such as H3's ffmpeg +paths, EmbeddingGemma's libav paths and the library list the Windows +workflow bundles. `compile_definitions` replaces model data paths passed on +the `gufo` executable today (`GUFO_H3_SOURCE_MANIFEST`, +`GUFO_H3_INSTALLED_SOURCE_MANIFEST`); eval's paths stay core-owned. +`licenses` and `install_data` drive the Nix install check. +The example shows the shape, not Flash-Next's actual dependencies. A +dependency that needs provisioning not expressible this way is a core +change. Family libraries use the same schema with `"kind": "library"` and no +`entry` or providers; the entry point lives in a target with no build +conditions, and providers whose HIP target is not built register as +excluded. Test targets are created only under `BUILD_TESTING`. +`production_paths` uses recursive globs relative to the extension root, with excludes; `install_data`, `licenses` and `runtime_libraries` paths are included implicitly. +Configure-time validation tolerates `fixtures`, `functional` and `tools` +being absent, because production sources filter them out. Test registration +lives in the manifests, so editing a test source does not change the +production derivation, but adding or renaming a test does. +`python_checks` and `extension.nix` replace the per-model flake checks +(`h3-manifest`, `h3-quality`, `h3-ml-quality`), the per-model devshell +Python dependencies (librosa, LPIPS, torchvision) and reference packages +(`ds4-reference`, `llama-cpp-mtp-reference`); model +Python tests such as `tests/tools/h3_*` move with their extension. Flake +check names are public flake outputs, so generated checks keep today's +names. + +`production_paths` limits what enters production Nix sources, so editing an +extension's test sources, functional fragments or tools does not change the +production derivation. `vendored_paths`, `kernel_resources` and `docs` +replace the model knowledge in `tools/ci/` and the models index. +`test_labels` replace per-model test presets (`ctest --preset gpu-full -L +