From 92e611bad51d675c1e6d48216a1e72379933f967 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 13:38:15 +0200 Subject: [PATCH 01/13] feat(kar): add bounded compressed expert LRU --- .gitea/workflows/kar-cuda-compile.yml | 67 +++++++++++++++ deploy/kar-cuda-build.lock.json | 17 ++++ gpu/kar/CMakeLists.txt | 4 + gpu/kar/README.md | 24 ++++++ gpu/kar/include/kar_expert.hpp | 10 ++- gpu/kar/include/kar_expert_cache.hpp | 114 ++++++++++++++++++++++++++ gpu/kar/include/kar_expert_miss.hpp | 2 +- gpu/kar/src/kar_expert.cu | 78 +++++++++++++----- gpu/kar/src/kar_expert_cache_test.cpp | 82 ++++++++++++++++++ gpu/kar/src/kar_expert_miss.cpp | 30 ++++++- gpu/kar/src/kar_expert_test.cpp | 10 ++- scripts/check-local.sh | 2 + scripts/test-kar-cuda-build-lock.py | 19 +++++ scripts/test-kar-expert-cache.sh | 14 ++++ 14 files changed, 444 insertions(+), 29 deletions(-) create mode 100644 .gitea/workflows/kar-cuda-compile.yml create mode 100644 deploy/kar-cuda-build.lock.json create mode 100644 gpu/kar/include/kar_expert_cache.hpp create mode 100644 gpu/kar/src/kar_expert_cache_test.cpp create mode 100644 scripts/test-kar-cuda-build-lock.py create mode 100755 scripts/test-kar-expert-cache.sh diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml new file mode 100644 index 00000000..8e9720fc --- /dev/null +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -0,0 +1,67 @@ +name: KAR CUDA compile (GPU hidden) + +on: + push: + paths: + - 'gpu/kar/**' + - 'engine/strata/CMakeLists.txt' + - 'scripts/bootstrap-cuda-toolkit.py' + - 'scripts/build-static-cuda.sh' + - 'scripts/test-kar-expert-cache.sh' + - 'scripts/test-kar-cuda-build-lock.py' + - 'deploy/cuda-toolkit.lock.json' + - 'deploy/kar-cuda-build.lock.json' + - '.gitea/workflows/kar-cuda-compile.yml' + pull_request: + paths: + - 'gpu/kar/**' + - 'engine/strata/CMakeLists.txt' + - 'scripts/bootstrap-cuda-toolkit.py' + - 'scripts/build-static-cuda.sh' + - 'scripts/test-kar-expert-cache.sh' + - 'scripts/test-kar-cuda-build-lock.py' + - 'deploy/cuda-toolkit.lock.json' + - 'deploy/kar-cuda-build.lock.json' + - '.gitea/workflows/kar-cuda-compile.yml' + +permissions: + contents: read + +jobs: + kar-cuda-compile: + runs-on: ubuntu-latest + timeout-minutes: 150 + steps: + - uses: https://git.vezha.io/actions/checkout@v4 + + - name: Build lock check + shell: bash + run: | + set -euo pipefail + python3 scripts/test-kar-cuda-build-lock.py + + - name: Compile CUDA component in GPU-hidden Docker + shell: bash + run: | + set -euo pipefail + base="$(python3 -c 'import json; print(json.load(open("deploy/kar-cuda-build.lock.json"))["builder_image"])')" + packages="$(python3 -c 'import json; p=json.load(open("deploy/kar-cuda-build.lock.json"))["apt_packages"]; print(" ".join(f"{k}={v}" for k,v in p.items()))')" + docker run --rm --platform linux/amd64 --network bridge \ + -e NVIDIA_VISIBLE_DEVICES=void -e CUDA_VISIBLE_DEVICES= \ + -e LOCKED_PACKAGES="$packages" \ + -v "$GITHUB_WORKSPACE:/work" -w /work "$base" \ + bash -euxo pipefail -c ' + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $LOCKED_PACKAGES + dpkg-query -W -f="${Package}=${Version}\n" ca-certificates cmake gcc-13 g++-13 make python3 + python3 scripts/test-kar-cuda-build-lock.py + CXX=g++-13 scripts/test-kar-expert-cache.sh + python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit + export CUDACXX=/tmp/cuda-toolkit/bin/nvcc + export CUDAToolkit_ROOT=/tmp/cuda-toolkit + export CC=gcc-13 CXX=g++-13 + cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 + cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe + ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$" + test -z "$(nvidia-smi 2>/dev/null || true)" || { echo "unexpected GPU visible in compile container" >&2; exit 1; } + ' diff --git a/deploy/kar-cuda-build.lock.json b/deploy/kar-cuda-build.lock.json new file mode 100644 index 00000000..ebcc7d8a --- /dev/null +++ b/deploy/kar-cuda-build.lock.json @@ -0,0 +1,17 @@ +{ + "schema_version": 1, + "platform": "linux/amd64", + "builder_image": "ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794", + "apt_packages": { + "ca-certificates": "20260601~26.04.1", + "cmake": "4.2.3-2ubuntu2", + "gcc-13": "13.4.0-10ubuntu1", + "g++-13": "13.4.0-10ubuntu1", + "make": "4.4.1-3", + "python3": "3.14.3-0ubuntu2" + }, + "cuda_toolkit_lock": "cuda-toolkit.lock.json", + "cuda_toolkit_release": "13.0.1", + "cuda_architecture": "120", + "compile_jobs": 1 +} diff --git a/gpu/kar/CMakeLists.txt b/gpu/kar/CMakeLists.txt index 3bb84780..5b67d607 100644 --- a/gpu/kar/CMakeLists.txt +++ b/gpu/kar/CMakeLists.txt @@ -56,6 +56,10 @@ target_compile_features(strata-kar-expert-probe PRIVATE cxx_std_20) target_link_libraries(strata-kar-expert-probe PRIVATE strata_kar_cuda strata_kar_expert) enable_testing() +add_executable(strata-kar-expert-cache-test src/kar_expert_cache_test.cpp) +target_compile_features(strata-kar-expert-cache-test PRIVATE cxx_std_17) +add_test(NAME kar_expert_cache_index COMMAND strata-kar-expert-cache-test) +set_tests_properties(kar_expert_cache_index PROPERTIES TIMEOUT 60) add_executable(strata-kar-expert-test src/kar_expert_test.cpp) target_compile_features(strata-kar-expert-test PRIVATE cxx_std_20) target_link_libraries(strata-kar-expert-test PRIVATE strata_kar_expert) diff --git a/gpu/kar/README.md b/gpu/kar/README.md index 651ba9c3..3216222a 100644 --- a/gpu/kar/README.md +++ b/gpu/kar/README.md @@ -200,3 +200,27 @@ bounded GPU cache and does not measure cold random storage access. The smoke reports packet bytes, the full-record prefix bytes, warm H2D event time, warm CUDA decode event time, and per-row byte checksums. It reports archive verification and one packet build separately as host wall time; those are not included in the GPU event times. Page faults, output transfer, matrix multiplication, and runtime scheduling need separate accounting. Random rows may trigger storage reads and CPU work, so fewer PCIe bytes do not by themselves establish lower request latency. A production path needs a bounded packet cache, coalescing across requests, provenance binding, backpressure, and integration with the PLE consumer before it can be evaluated as inference. The `--range START COUNT` form generates consecutive local row IDs, up to 200,000 rows and the same 100-million-value output cap. `--random COUNT SEED` generates deterministic pseudorandom local IDs within the selected tensor record. Both omit individual row checksums for more than 128 rows but still report the whole output checksum. The contiguous selection is useful for GPU transfer scaling; random selection probes host packet assembly with scattered rows. Neither selection is a representative storage page-fault benchmark because archive payload verification reads the complete file first and can warm the page cache. The smoke times both first packet assembly and a median of five repeated assemblies on the same rows. It also times an upload of the same number of F32 rows from pinned host memory into the output buffer. That upload is the GPU stage of Strata's current PLE prefill path. The comparison excludes its CPU row decoding; compare it with the separate CPU gather probe. Compare the measured stages at the same row count rather than inferring latency from byte counts alone. +# Experimental compressed expert cache + +`ResidentExpert` can keep a bounded set of three-matrix expert packets compressed +in device memory. `STRATA_NEXT_KAR_EXPERTS_CACHE_MIB` is an opt-in budget used by +the experimental native-miss adapter; it must be an integer from 1 to 4096 and +large enough for one complete expert slot. An unset variable retains the legacy +single-slot footprint. Slots are allocated up front after the free-VRAM/headroom +check. A hit reuses the compressed packet and one shared F32 decode scratch; +eviction can happen only while no run is pending. A slot's exact mapping and +tensor-slice key is published only after its upload synchronizes successfully. +Upload or kernel errors poison the component closed. Cache hit counts, uploads, +evictions, compressed bytes and scratch bytes are diagnostics, not a speed claim. + +The CUDA-independent index tests run with `scripts/test-kar-expert-cache.sh`. +CUDA component tests also check exact reconstructed matrices and FP64 multiply +parity on a GPU; CI only compiles those targets with GPU devices hidden and does +not claim runtime correctness or model quality. + +The Gitea build lock is `deploy/kar-cuda-build.lock.json`: Ubuntu 26.04 amd64 +base image digest `88a381d5…d3794`, GCC/G++ 13.4.0, CMake 4.2.3, GNU make +4.4.1 and Python 3.14.3. The CUDA compiler and redistributable components are +separately checksum-locked in `deploy/cuda-toolkit.lock.json` to NVIDIA CUDA +13.0.1. The lock records the direct apt package versions; Ubuntu's transitive +packages are resolved from that image's configured archive during CI. diff --git a/gpu/kar/include/kar_expert.hpp b/gpu/kar/include/kar_expert.hpp index d91a7716..167c14ee 100644 --- a/gpu/kar/include/kar_expert.hpp +++ b/gpu/kar/include/kar_expert.hpp @@ -1,6 +1,7 @@ #pragma once #include "libkar.h" +#include "kar_expert_cache.hpp" #include #include #include @@ -9,8 +10,9 @@ namespace strata::kar { // Experimental component. The caller owns an immutable, verified archive mapping. -// One resident compressed expert; one reusable decoded matrix, never a full bank. -// Not thread safe. stage/run may only follow completion of the previous run. +// A byte-bounded set of compressed experts shares one reusable decoded matrix; +// it never creates a full decoded bank. Not thread safe. stage/run may only +// follow completion of the previous run. class ResidentExpert { public: ResidentExpert(); @@ -18,7 +20,8 @@ public: ResidentExpert(const ResidentExpert&) = delete; ResidentExpert& operator=(const ResidentExpert&) = delete; bool open(uint32_t hidden, uint32_t intermediate, uint32_t level, - uint32_t max_tokens, std::string& error); + uint32_t max_tokens, std::string& error, + uint64_t compressed_cache_budget_bytes=0); bool stage(const uint8_t* archive, size_t bytes, const kar_tensor_info& gate, const kar_tensor_info& up, const kar_tensor_info& down, uint32_t expert, std::string& error); @@ -29,6 +32,7 @@ public: bool inspect_matrix(uint32_t role, float* output, std::string& error); uint64_t resident_bytes() const; uint64_t scratch_bytes() const; + ExpertCacheStats cache_stats() const; private: struct Impl; std::unique_ptr impl_; diff --git a/gpu/kar/include/kar_expert_cache.hpp b/gpu/kar/include/kar_expert_cache.hpp new file mode 100644 index 00000000..607ec026 --- /dev/null +++ b/gpu/kar/include/kar_expert_cache.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata::kar { + +// Identity of the verified immutable mapping and the exact three tensor slices +// used for one expert. The mapping is owned for the cache's whole lifetime. +struct ExpertTensorSlice { + uint64_t books_offset=0, scales_offset=0, planes_offset=0; + uint64_t section_offset=0, section_bytes=0, scales_bytes=0, books_bytes=0; + uint64_t dims[4]={}; + uint64_t n_elements=0, n_padded=0, n_groups=0, words=0; + uint32_t plane_stride_bytes=0, payload_crc32=0, n_dims=0, group=0; + uint32_t planes_stored=0, planes_min=0, planes_max=0; + uint32_t storage_class=0, nesting=0, source_dtype=0, element_order=0; +}; + +struct ExpertCacheKey { + uintptr_t mapping=0; + uint64_t archive_bytes=0; + uint32_t expert=0, level=0; + std::array tensors{}; +}; + +inline bool operator==(const ExpertTensorSlice& a, const ExpertTensorSlice& b) { + for (size_t i=0;i<4;++i) if (a.dims[i]!=b.dims[i]) return false; + return a.books_offset==b.books_offset && a.scales_offset==b.scales_offset && + a.planes_offset==b.planes_offset && a.section_offset==b.section_offset && + a.section_bytes==b.section_bytes && a.scales_bytes==b.scales_bytes && + a.books_bytes==b.books_bytes && a.n_elements==b.n_elements && + a.n_padded==b.n_padded && a.n_groups==b.n_groups && a.words==b.words && + a.plane_stride_bytes==b.plane_stride_bytes && a.payload_crc32==b.payload_crc32 && + a.n_dims==b.n_dims && a.group==b.group && a.planes_stored==b.planes_stored && + a.planes_min==b.planes_min && a.planes_max==b.planes_max && + a.storage_class==b.storage_class && a.nesting==b.nesting && + a.source_dtype==b.source_dtype && a.element_order==b.element_order; +} +inline bool operator==(const ExpertCacheKey& a, const ExpertCacheKey& b) { + return a.mapping==b.mapping && a.archive_bytes==b.archive_bytes && + a.expert==b.expert && a.level==b.level && a.tensors==b.tensors; +} + +struct ExpertCacheStats { + uint64_t hits=0, misses=0, uploads=0, evictions=0; +}; + +// CUDA-independent cache ownership/index. A slot is not published until its +// upload has completed; any upload fault poisons the index closed. +class ExpertLruIndex { +public: + explicit ExpertLruIndex(size_t slots) : entries_(slots) {} + size_t capacity() const { return entries_.size(); } + const ExpertCacheStats& stats() const { return stats_; } + bool failed() const { return failed_; } + bool pending() const { return pending_; } + + bool lookup(const ExpertCacheKey& key, size_t& slot) { + if (failed_ || pending_ || uploading_) return false; + for (size_t i=0;iclock_) clock_=e.last_used; + } + return ++clock_; + } + std::vector entries_; + ExpertCacheStats stats_{}; + uint64_t clock_=0; + size_t uploading_slot_=0; + bool pending_=false, uploading_=false, replacing_=false, failed_=false; +}; + +} // namespace strata::kar diff --git a/gpu/kar/include/kar_expert_miss.hpp b/gpu/kar/include/kar_expert_miss.hpp index 4d6a424f..6e8e9cd2 100644 --- a/gpu/kar/include/kar_expert_miss.hpp +++ b/gpu/kar/include/kar_expert_miss.hpp @@ -14,7 +14,7 @@ public: ~ExpertMiss(); bool open(const char* archive, uint32_t layers, uint32_t experts, uint32_t hidden, uint32_t intermediate, uint32_t level, - std::string& error); + std::string& error, uint64_t compressed_cache_budget_bytes=0); bool compute(int64_t layer, const float* input, const int32_t* ids, int64_t tokens, int64_t k, int32_t* kind, float* output, std::string& error); diff --git a/gpu/kar/src/kar_expert.cu b/gpu/kar/src/kar_expert.cu index 9bde4425..636d301f 100644 --- a/gpu/kar/src/kar_expert.cu +++ b/gpu/kar/src/kar_expert.cu @@ -56,19 +56,21 @@ __global__ void activate(float* gate, const float* up, uint32_t values) { struct ResidentExpert::Impl { uint32_t hidden=0, ff=0, level=0, max_tokens=0, tokens=0, words=0, books=0; - uint64_t packet=0, scratch=0; + uint64_t packet=0, slot_bytes=0, resident=0, scratch=0; + size_t active_slot=0; bool staged=false, pending=false, failed=false; cudaStream_t stream=nullptr; cudaEvent_t done=nullptr; - uint8_t* compressed=nullptr; + std::vector compressed_slots; + ExpertLruIndex cache{0}; uint8_t* host_packet=nullptr; float *weights=nullptr, *x=nullptr, *gate=nullptr, *up=nullptr, *out=nullptr; float *host_x=nullptr, *host_out=nullptr; ~Impl() { if (stream) cudaStreamSynchronize(stream); if (done) cudaEventDestroy(done); - for (void* p : {static_cast(compressed), static_cast(weights), - static_cast(x), static_cast(gate), + for (auto* p : compressed_slots) if (p) cudaFree(p); + for (void* p : {static_cast(weights), static_cast(x), static_cast(gate), static_cast(up), static_cast(out)}) if (p) cudaFree(p); if (host_packet) cudaFreeHost(host_packet); if (host_x) cudaFreeHost(host_x); @@ -78,11 +80,13 @@ struct ResidentExpert::Impl { }; ResidentExpert::ResidentExpert() = default; ResidentExpert::~ResidentExpert() = default; -uint64_t ResidentExpert::resident_bytes() const { return impl_ ? impl_->packet * 3 : 0; } +uint64_t ResidentExpert::resident_bytes() const { return impl_ ? impl_->resident : 0; } uint64_t ResidentExpert::scratch_bytes() const { return impl_ ? impl_->scratch : 0; } +ExpertCacheStats ResidentExpert::cache_stats() const { return impl_ ? impl_->cache.stats() : ExpertCacheStats{}; } bool ResidentExpert::open(uint32_t hidden, uint32_t ff, uint32_t level, - uint32_t max_tokens, std::string& error) { + uint32_t max_tokens, std::string& error, + uint64_t compressed_cache_budget_bytes) { if (impl_) { error="expert is already open"; return false; } if (!hidden || !ff || hidden > 16384 || ff > 16384 || hidden % 32 || ff % 32 || level < 1 || level > 8 || !max_tokens || max_tokens > 8 || @@ -93,24 +97,37 @@ bool ResidentExpert::open(uint32_t hidden, uint32_t ff, uint32_t level, p->hidden=hidden; p->ff=ff; p->level=level; p->max_tokens=max_tokens; p->words=hidden*ff/32; p->books=(1u<packet=align256(p->books + uint64_t(p->words)*(2+4*level)); + p->slot_bytes=p->packet*3; + const uint64_t budget=compressed_cache_budget_bytes ? compressed_cache_budget_bytes : p->slot_bytes; + const uint64_t slot_count=budget/p->slot_bytes; + if (!slot_count || slot_count>4096) { + error="compressed expert cache budget must fit 1..4096 complete expert slots"; return false; + } + p->resident=slot_count*p->slot_bytes; + p->cache=ExpertLruIndex(static_cast(slot_count)); p->scratch=uint64_t(hidden)*ff*4 + uint64_t(max_tokens)*(hidden*2+ff*2)*4; size_t free=0,total=0; if (!check(cudaMemGetInfo(&free,&total),"expert memory query",error)) return false; const uint64_t headroom=std::max(512ull<<20,total/16); - if (free < headroom || p->packet*3+p->scratch > free-headroom) { + if (free < headroom || p->resident+p->scratch > free-headroom) { error="expert budget would cross GPU headroom"; return false; } if (!check(cudaStreamCreateWithFlags(&p->stream,cudaStreamNonBlocking),"expert stream",error) || !check(cudaEventCreateWithFlags(&p->done,cudaEventDisableTiming),"expert event",error) || - !check(cudaMalloc(&p->compressed,p->packet*3),"expert compressed allocation",error) || !check(cudaMalloc(&p->weights,uint64_t(hidden)*ff*4),"expert matrix scratch",error) || !check(cudaMalloc(&p->x,uint64_t(max_tokens)*hidden*4),"expert input",error) || !check(cudaMalloc(&p->out,uint64_t(max_tokens)*hidden*4),"expert output",error) || !check(cudaMalloc(&p->gate,uint64_t(max_tokens)*ff*4),"expert gate",error) || !check(cudaMalloc(&p->up,uint64_t(max_tokens)*ff*4),"expert up",error) || - !check(cudaMallocHost(&p->host_packet,p->packet*3),"expert host staging",error) || !check(cudaMallocHost(&p->host_x,uint64_t(max_tokens)*hidden*4),"expert host input",error) || !check(cudaMallocHost(&p->host_out,uint64_t(max_tokens)*hidden*4),"expert host output",error)) return false; + p->compressed_slots.reserve(static_cast(slot_count)); + for (uint64_t i=0;islot_bytes),"expert compressed slot allocation",error)) return false; + p->compressed_slots.push_back(slot); + } + if (!check(cudaMallocHost(&p->host_packet,p->slot_bytes),"expert host staging",error)) return false; impl_=std::move(p); return true; } @@ -141,7 +158,26 @@ bool ResidentExpert::stage(const uint8_t* archive, size_t bytes, error="KAR expert plane outside archive"; return false; } } - std::memset(p.host_packet,0,p.packet*3); + ExpertCacheKey key{}; + key.mapping=reinterpret_cast(archive); key.archive_bytes=bytes; + key.expert=expert; key.level=p.level; + for (uint32_t role=0;role<3;++role) { + const auto& t=*records[role]; auto& out=key.tensors[role]; + out.books_offset=t.books_offset; out.scales_offset=t.scales_offset; out.planes_offset=t.planes_offset; + out.section_offset=t.section_offset; out.section_bytes=t.section_bytes; + out.scales_bytes=t.scales_bytes; out.books_bytes=t.books_bytes; + for (uint32_t d=0;d<4;++d) out.dims[d]=t.dims[d]; + out.n_elements=t.n_elements; out.n_padded=t.n_padded; out.n_groups=t.n_groups; out.words=t.words; + out.plane_stride_bytes=t.plane_stride_bytes; out.payload_crc32=t.payload_crc32; + out.n_dims=t.n_dims; out.group=t.group; out.planes_stored=t.planes_stored; + out.planes_min=t.planes_min; out.planes_max=t.planes_max; + out.storage_class=t.storage_class; out.nesting=t.nesting; + out.source_dtype=t.source_dtype; out.element_order=t.element_order; + } + size_t slot=0; + if (p.cache.lookup(key,slot)) { p.active_slot=slot; p.staged=true; return true; } + if (!p.cache.begin_upload(slot)) { error="expert cache is not available for upload"; return false; } + std::memset(p.host_packet,0,p.slot_bytes); for (uint32_t role=0;role<3;++role) { const auto& t=*records[role]; auto* dst=p.host_packet+role*p.packet; const uint64_t first_word=uint64_t(expert)*p.words; @@ -153,10 +189,12 @@ bool ResidentExpert::stage(const uint8_t* archive, size_t bytes, uint64_t(p.words)*4); } // Blocking on this stream's copy protects host staging reuse on consecutive stage calls. - if (!check(cudaMemcpyAsync(p.compressed,p.host_packet,p.packet*3,cudaMemcpyHostToDevice,p.stream),"expert upload",error) || + if (!check(cudaMemcpyAsync(p.compressed_slots[slot],p.host_packet,p.slot_bytes,cudaMemcpyHostToDevice,p.stream),"expert upload",error) || !check(cudaStreamSynchronize(p.stream),"expert upload completion",error)) { - p.failed=true; return false; + p.cache.fail_upload(); p.failed=true; return false; } + if (!p.cache.publish_upload(slot,key)) { p.cache.fail(); p.failed=true; error="expert cache publication failed"; return false; } + p.active_slot=slot; p.staged=true; return true; } @@ -167,12 +205,13 @@ bool ResidentExpert::run(const float* input, uint32_t tokens, std::string& error for (uint64_t i=0;i>>(p.compressed+role*p.packet,p.weights, + decode<<<(p.hidden*p.ff+255)/256,256,0,p.stream>>>(p.compressed_slots[p.active_slot]+role*p.packet,p.weights, p.hidden*p.ff,p.level,p.words,p.books); const uint32_t cols=role==2?p.ff:p.hidden, rows=role==2?p.hidden:p.ff; multiply<<>>(p.weights,role==2?p.gate:p.x, @@ -182,7 +221,7 @@ bool ResidentExpert::run(const float* input, uint32_t tokens, std::string& error if (!check(cudaGetLastError(),"expert kernels",error) || !check(cudaMemcpyAsync(p.host_out,p.out,uint64_t(tokens)*p.hidden*4,cudaMemcpyDeviceToHost,p.stream),"expert result",error) || !check(cudaEventRecord(p.done,p.stream),"expert completion",error)) { - p.failed=true; return false; + p.cache.fail(); p.failed=true; return false; } return true; } @@ -191,10 +230,11 @@ bool ResidentExpert::finish(float* output, std::string& error) { error="expert finish without a healthy pending run"; return false; } auto& p=*impl_; - if (!check(cudaEventSynchronize(p.done),"expert wait",error)) { p.failed=true; return false; } + if (!check(cudaEventSynchronize(p.done),"expert wait",error)) { p.cache.fail(); p.failed=true; return false; } p.pending=false; + if (!p.cache.finish_run()) { p.cache.fail(); p.failed=true; error="expert cache run ownership was lost"; return false; } for (uint64_t i=0;i>>(p.compressed+role*p.packet,p.weights, + decode<<<(p.hidden*p.ff+255)/256,256,0,p.stream>>>(p.compressed_slots[p.active_slot]+role*p.packet,p.weights, p.hidden*p.ff,p.level,p.words,p.books); if (!check(cudaGetLastError(),"expert inspection decode",error) || !check(cudaMemcpyAsync(output,p.weights,uint64_t(p.hidden)*p.ff*4,cudaMemcpyDeviceToHost,p.stream),"expert inspection copy",error) || !check(cudaStreamSynchronize(p.stream),"expert inspection wait",error)) { - p.failed=true; return false; + p.cache.fail(); p.failed=true; return false; } return true; } diff --git a/gpu/kar/src/kar_expert_cache_test.cpp b/gpu/kar/src/kar_expert_cache_test.cpp new file mode 100644 index 00000000..91a4ff92 --- /dev/null +++ b/gpu/kar/src/kar_expert_cache_test.cpp @@ -0,0 +1,82 @@ +#include "kar_expert_cache.hpp" +#include +#include +#include +#include + +using namespace strata::kar; +namespace { +void require(bool ok,const char* what) { if(!ok) throw std::runtime_error(what); } +ExpertCacheKey key(uint32_t expert,uint64_t offset) { + ExpertCacheKey k{}; k.mapping=0x1234; k.archive_bytes=4096; k.expert=expert; k.level=2; + for (auto& t:k.tensors) { t.books_offset=offset; t.n_dims=3; t.dims[0]=64; t.dims[1]=32; t.dims[2]=8; } + return k; +} +void upload(ExpertLruIndex& cache,const ExpertCacheKey& k) { + size_t slot=0; require(cache.begin_upload(slot),"begin upload rejected"); + require(cache.publish_upload(slot,k),"publish rejected"); +} +} +int main() try { + const auto a=key(0,100), b=key(1,200), c=key(2,300); + ExpertLruIndex cache(2); + upload(cache,a); upload(cache,b); + size_t slot=99; + require(cache.lookup(a,slot) && slot==0,"repeat hit/mru failed"); + size_t victim=99; require(cache.begin_upload(victim) && victim==1,"LRU victim was not expert B"); + require(cache.publish_upload(victim,c),"replacement publish failed"); + require(!cache.lookup(b,slot),"evicted key still hit"); + require(cache.lookup(a,slot) && slot==0,"resident key lost after eviction"); + require(cache.capacity()==2 && cache.stats().uploads==3 && cache.stats().hits==2 && + cache.stats().misses==1 && cache.stats().evictions==1,"budget or counters wrong"); + require(cache.begin_run(),"run ownership acquire failed"); + require(!cache.begin_upload(victim) && !cache.lookup(a,slot) && !cache.begin_run(), + "pending run allowed cache mutation or overlapping owner"); + require(cache.finish_run() && !cache.finish_run(),"run ownership release invalid"); + require(cache.begin_upload(victim),"upload after run completion rejected"); + cache.fail_upload(); + require(cache.failed() && !cache.begin_run() && !cache.begin_upload(victim) && !cache.lookup(a,slot), + "failed upload did not fail closed"); + + ExpertLruIndex geometry(1); upload(geometry,a); + auto wrong=key(0,101); + require(!geometry.lookup(wrong,slot),"different slice identity hit cached expert"); + + struct ReferenceEntry { ExpertCacheKey key{}; uint64_t age=0; bool valid=false; }; + constexpr size_t slots=5, operations=10000; + ExpertLruIndex actual(slots); + std::array reference{}; + uint64_t clock=0, hits=0, misses=0, uploads=0, evictions=0; + uint32_t random=0x5eed1234u; + for(size_t n=0;n>8)%13; + const uint64_t slice=100+((random>>20)%3)*4096; + const auto request=key(expert,slice); + size_t expected=slots; + for(size_t i=0;i #include +#include +#include #include #include #include @@ -28,16 +30,36 @@ struct ExpertMiss::Impl { }; ExpertMiss::ExpertMiss() = default; ExpertMiss::~ExpertMiss() { - if(impl_)std::fprintf(stderr,"strata KAR experimental misses: %llu entries computed; compressed=%llu scratch=%llu bytes\n", + if(impl_) { + const auto stats=impl_->resident.cache_stats(); + std::fprintf(stderr,"strata KAR experimental misses: %llu entries computed; compressed=%llu scratch=%llu bytes; cache hits=%llu misses=%llu uploads=%llu evictions=%llu\n", (unsigned long long)impl_->computed,(unsigned long long)impl_->resident.resident_bytes(), - (unsigned long long)impl_->resident.scratch_bytes()); + (unsigned long long)impl_->resident.scratch_bytes(),(unsigned long long)stats.hits, + (unsigned long long)stats.misses,(unsigned long long)stats.uploads,(unsigned long long)stats.evictions); + } } uint64_t ExpertMiss::computed() const {return impl_?impl_->computed:0;} bool ExpertMiss::open(const char* path,uint32_t layers,uint32_t experts,uint32_t hidden, - uint32_t ff,uint32_t level,std::string& error) { + uint32_t ff,uint32_t level,std::string& error, + uint64_t compressed_cache_budget_bytes) { if(impl_ || !path || !*path || layers<1 || layers>512 || experts<1 || experts>65536) { error="invalid KAR miss configuration";return false; } + if (compressed_cache_budget_bytes==0) { + const char* text=std::getenv("STRATA_NEXT_KAR_EXPERTS_CACHE_MIB"); + if (text) { + if (!*text) { error="STRATA_NEXT_KAR_EXPERTS_CACHE_MIB must be an integer in 1..4096";return false; } + for (const char* c=text;*c;++c) if (*c<'0' || *c>'9') { + error="STRATA_NEXT_KAR_EXPERTS_CACHE_MIB must be an integer in 1..4096";return false; + } + errno=0; char* end=nullptr; + const unsigned long long mib=std::strtoull(text,&end,10); + if (errno || end==text || *end!='\0' || mib==0 || mib>4096) { + error="STRATA_NEXT_KAR_EXPERTS_CACHE_MIB must be an integer in 1..4096";return false; + } + compressed_cache_budget_bytes=uint64_t(mib)*(1ull<<20); + } + } auto p=std::make_unique(); // Keep a descriptor to the exact inode used by both mappings. Replacing the // configured path during validation cannot select a different payload. @@ -69,7 +91,7 @@ bool ExpertMiss::open(const char* path,uint32_t layers,uint32_t experts,uint32_t } p->records.push_back(t); } - if(!p->resident.open(hidden,ff,level,8,error))return false; + if(!p->resident.open(hidden,ff,level,8,error,compressed_cache_budget_bytes))return false; p->input.resize(size_t(hidden)*8);p->output.resize(size_t(hidden)*8); std::fprintf(stderr,"strata KAR experimental: native verifier misses (short prompt and decode), level=%u, compressed=%llu scratch=%llu; quality not qualified\n", level,(unsigned long long)p->resident.resident_bytes(),(unsigned long long)p->resident.scratch_bytes()); diff --git a/gpu/kar/src/kar_expert_test.cpp b/gpu/kar/src/kar_expert_test.cpp index ef567cac..b9da4f92 100644 --- a/gpu/kar/src/kar_expert_test.cpp +++ b/gpu/kar/src/kar_expert_test.cpp @@ -45,8 +45,11 @@ int main() try { require(!invalid.open(63,F,1,8,error),"unaligned hidden accepted"); require(!invalid.open(H,F,0,8,error),"zero level accepted"); require(!invalid.open(H,F,1,9,error),"oversized batch accepted"); + require(!invalid.open(H,F,1,8,error,1),"undersized compressed cache budget accepted"); strata::kar::ResidentExpert expert; - require(expert.open(H,F,1,8,error),error.c_str()); + // packet=512 bytes, three matrices per expert; two compressed slots are 3072 bytes. + require(expert.open(H,F,1,8,error,3072),error.c_str()); + require(expert.resident_bytes()==3072,"compressed cache byte budget mismatch"); require(!expert.open(H,F,1,8,error),"double open accepted"); std::vector matrix(H*F),input(8*H),output(8*H); for(size_t i=0;i1->0, geometry/state/overflow guards"); + std::puts("PASS: exact matrix bytes, FP64 multiply tolerance1e-6, 1/8 tokens, 2-slot compressed reuse, geometry/state/overflow guards"); return 0; } catch(const std::exception& e) {std::fprintf(stderr,"KAR expert test: %s\n",e.what());return 1;} diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 27af6254..c953c928 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -14,6 +14,8 @@ python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-runtime-image.py" python3 "${repo_root}/scripts/test-keyless-routing.py" +python3 "${repo_root}/scripts/test-kar-cuda-build-lock.py" +"${repo_root}/scripts/test-kar-expert-cache.sh" cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py new file mode 100644 index 00000000..a912decc --- /dev/null +++ b/scripts/test-kar-cuda-build-lock.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +import json +from pathlib import Path +import re + +ROOT=Path(__file__).resolve().parents[1] +lock=json.loads((ROOT/'deploy/kar-cuda-build.lock.json').read_text()) +assert lock['schema_version']==1 +assert lock['platform']=='linux/amd64' +assert re.fullmatch(r'ubuntu@sha256:[0-9a-f]{64}',lock['builder_image']) +assert lock['cuda_toolkit_release']=='13.0.1' +assert lock['cuda_architecture']=='120' and lock['compile_jobs']==1 +assert lock['cuda_toolkit_lock']=='cuda-toolkit.lock.json' +toolkit=json.loads((ROOT/'deploy'/lock['cuda_toolkit_lock']).read_text()) +assert toolkit['release']==lock['cuda_toolkit_release'] +required={'ca-certificates','cmake','gcc-13','g++-13','make','python3'} +assert set(lock['apt_packages'])==required +assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_packages'].values()) +print('PASS: pinned CUDA 13.0.1 Linux build image, compiler, CMake and base packages') diff --git a/scripts/test-kar-expert-cache.sh b/scripts/test-kar-expert-cache.sh new file mode 100755 index 00000000..cd77df6f --- /dev/null +++ b/scripts/test-kar-expert-cache.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +build_dir="$(mktemp -d "${TMPDIR:-/tmp}/kar-expert-cache.XXXXXX")" +trap 'rm -rf "$build_dir"' EXIT +"${CXX:-c++}" -std=c++17 -Wall -Wextra -Werror -pedantic \ + -fsanitize=address,undefined -fno-omit-frame-pointer -I"$repo_root/gpu/kar/include" \ + "$repo_root/gpu/kar/src/kar_expert_cache_test.cpp" -o "$build_dir/kar-expert-cache-test" +if [[ "$(uname -s)" == Darwin ]]; then + # Apple's ASan runtime does not implement LeakSanitizer. + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-expert-cache-test" +else + ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-expert-cache-test" +fi -- 2.54.0 From 8c19d8244718672633a203a79fee5ef1b34ec4be Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 13:59:51 +0200 Subject: [PATCH 02/13] fix(ci): use pinned GPU-hidden job container --- .gitea/workflows/kar-cuda-compile.yml | 68 ++++++++++++--------------- scripts/test-kar-cuda-build-lock.py | 10 +++- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index 8e9720fc..18d00d88 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -1,17 +1,6 @@ name: KAR CUDA compile (GPU hidden) on: - push: - paths: - - 'gpu/kar/**' - - 'engine/strata/CMakeLists.txt' - - 'scripts/bootstrap-cuda-toolkit.py' - - 'scripts/build-static-cuda.sh' - - 'scripts/test-kar-expert-cache.sh' - - 'scripts/test-kar-cuda-build-lock.py' - - 'deploy/cuda-toolkit.lock.json' - - 'deploy/kar-cuda-build.lock.json' - - '.gitea/workflows/kar-cuda-compile.yml' pull_request: paths: - 'gpu/kar/**' @@ -31,37 +20,40 @@ jobs: kar-cuda-compile: runs-on: ubuntu-latest timeout-minutes: 150 + container: + image: ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794 + options: --platform linux/amd64 + env: + NVIDIA_VISIBLE_DEVICES: void + CUDA_VISIBLE_DEVICES: '' steps: - uses: https://git.vezha.io/actions/checkout@v4 - - name: Build lock check + - name: Compile CUDA component in pinned GPU-hidden container shell: bash run: | set -euo pipefail python3 scripts/test-kar-cuda-build-lock.py - - - name: Compile CUDA component in GPU-hidden Docker - shell: bash - run: | - set -euo pipefail - base="$(python3 -c 'import json; print(json.load(open("deploy/kar-cuda-build.lock.json"))["builder_image"])')" - packages="$(python3 -c 'import json; p=json.load(open("deploy/kar-cuda-build.lock.json"))["apt_packages"]; print(" ".join(f"{k}={v}" for k,v in p.items()))')" - docker run --rm --platform linux/amd64 --network bridge \ - -e NVIDIA_VISIBLE_DEVICES=void -e CUDA_VISIBLE_DEVICES= \ - -e LOCKED_PACKAGES="$packages" \ - -v "$GITHUB_WORKSPACE:/work" -w /work "$base" \ - bash -euxo pipefail -c ' - apt-get update -qq - DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $LOCKED_PACKAGES - dpkg-query -W -f="${Package}=${Version}\n" ca-certificates cmake gcc-13 g++-13 make python3 - python3 scripts/test-kar-cuda-build-lock.py - CXX=g++-13 scripts/test-kar-expert-cache.sh - python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit - export CUDACXX=/tmp/cuda-toolkit/bin/nvcc - export CUDAToolkit_ROOT=/tmp/cuda-toolkit - export CC=gcc-13 CXX=g++-13 - cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 - cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe - ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$" - test -z "$(nvidia-smi 2>/dev/null || true)" || { echo "unexpected GPU visible in compile container" >&2; exit 1; } - ' + test "$NVIDIA_VISIBLE_DEVICES" = void + test -z "$CUDA_VISIBLE_DEVICES" + if compgen -G '/dev/nvidia*' >/dev/null; then + echo 'unexpected NVIDIA device mounted in CUDA compile job' >&2 + exit 1 + fi + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + ca-certificates=20260601~26.04.1 \ + cmake=4.2.3-2ubuntu2 \ + gcc-13=13.4.0-10ubuntu1 \ + g++-13=13.4.0-10ubuntu1 \ + make=4.4.1-3 \ + python3=3.14.3-0ubuntu2 + dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 make python3 + CXX=g++-13 scripts/test-kar-expert-cache.sh + python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit + export CUDACXX=/tmp/cuda-toolkit/bin/nvcc + export CUDAToolkit_ROOT=/tmp/cuda-toolkit + export CC=gcc-13 CXX=g++-13 + cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 + cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe + ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$" diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index a912decc..e7479343 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -16,4 +16,12 @@ assert toolkit['release']==lock['cuda_toolkit_release'] required={'ca-certificates','cmake','gcc-13','g++-13','make','python3'} assert set(lock['apt_packages'])==required assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_packages'].values()) -print('PASS: pinned CUDA 13.0.1 Linux build image, compiler, CMake and base packages') +workflow=(ROOT/'.gitea/workflows/kar-cuda-compile.yml').read_text() +assert f"image: {lock['builder_image']}" in workflow +assert 'pull_request:' in workflow and '\n push:' not in workflow +assert 'NVIDIA_VISIBLE_DEVICES: void' in workflow +assert "CUDA_VISIBLE_DEVICES: ''" in workflow +assert 'docker run' not in workflow +for name,version in lock['apt_packages'].items(): + assert f'{name}={version}' in workflow +print('PASS: pinned CUDA 13.0.1 GPU-hidden Gitea container and direct packages') -- 2.54.0 From c1c70859aaeb674f9ab9ca4f06fc33184402a9f6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:13:21 +0200 Subject: [PATCH 03/13] fix(ci): drop unsupported container platform option --- .gitea/workflows/kar-cuda-compile.yml | 2 +- scripts/test-kar-cuda-build-lock.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index 18d00d88..e7014bfe 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -22,7 +22,6 @@ jobs: timeout-minutes: 150 container: image: ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794 - options: --platform linux/amd64 env: NVIDIA_VISIBLE_DEVICES: void CUDA_VISIBLE_DEVICES: '' @@ -34,6 +33,7 @@ jobs: run: | set -euo pipefail python3 scripts/test-kar-cuda-build-lock.py + test "$(dpkg --print-architecture)" = amd64 test "$NVIDIA_VISIBLE_DEVICES" = void test -z "$CUDA_VISIBLE_DEVICES" if compgen -G '/dev/nvidia*' >/dev/null; then diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index e7479343..db573727 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -19,6 +19,7 @@ assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_package workflow=(ROOT/'.gitea/workflows/kar-cuda-compile.yml').read_text() assert f"image: {lock['builder_image']}" in workflow assert 'pull_request:' in workflow and '\n push:' not in workflow +assert 'options: --platform' not in workflow assert 'NVIDIA_VISIBLE_DEVICES: void' in workflow assert "CUDA_VISIBLE_DEVICES: ''" in workflow assert 'docker run' not in workflow -- 2.54.0 From 2d2995f40f76c308e808bbe2fce1ed5731d95117 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:13:48 +0200 Subject: [PATCH 04/13] fix(ci): use Gitea built-in checkout --- .gitea/workflows/kar-cuda-compile.yml | 2 +- scripts/test-kar-cuda-build-lock.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index e7014bfe..6f8f36e0 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -26,7 +26,7 @@ jobs: NVIDIA_VISIBLE_DEVICES: void CUDA_VISIBLE_DEVICES: '' steps: - - uses: https://git.vezha.io/actions/checkout@v4 + - uses: builtin:checkout - name: Compile CUDA component in pinned GPU-hidden container shell: bash diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index db573727..19cb1379 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -23,6 +23,8 @@ assert 'options: --platform' not in workflow assert 'NVIDIA_VISIBLE_DEVICES: void' in workflow assert "CUDA_VISIBLE_DEVICES: ''" in workflow assert 'docker run' not in workflow +assert 'uses: builtin:checkout' in workflow +assert 'actions/checkout@' not in workflow for name,version in lock['apt_packages'].items(): assert f'{name}={version}' in workflow print('PASS: pinned CUDA 13.0.1 GPU-hidden Gitea container and direct packages') -- 2.54.0 From 90d6d2db203769e023bbf8b67d736cb78b0a746d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:16:31 +0200 Subject: [PATCH 05/13] fix(ci): checkout PR head with scoped Gitea token --- .gitea/workflows/kar-cuda-compile.yml | 28 +++++++++++++++++++++++++-- deploy/kar-cuda-build.lock.json | 1 + scripts/test-kar-cuda-build-lock.py | 6 ++++-- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index 6f8f36e0..f19663ae 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -26,7 +26,31 @@ jobs: NVIDIA_VISIBLE_DEVICES: void CUDA_VISIBLE_DEVICES: '' steps: - - uses: builtin:checkout + - name: Install pinned Git for private checkout + shell: bash + run: | + set -euo pipefail + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + ca-certificates=20260601~26.04.1 \ + git=1:2.53.0-1ubuntu1 + + - name: Checkout exact pull-request head + shell: bash + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: | + set -euo pipefail + : "${GITEA_TOKEN:?missing read-only GITEA_TOKEN}" + git init -q + git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + GIT_CONFIG_COUNT=1 \ + GIT_CONFIG_KEY_0=http.extraheader \ + GIT_CONFIG_VALUE_0="Authorization: token ${GITEA_TOKEN}" \ + git fetch --depth=1 origin "$GITHUB_REF" + git checkout --detach FETCH_HEAD + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + unset GITEA_TOKEN - name: Compile CUDA component in pinned GPU-hidden container shell: bash @@ -48,7 +72,7 @@ jobs: g++-13=13.4.0-10ubuntu1 \ make=4.4.1-3 \ python3=3.14.3-0ubuntu2 - dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 make python3 + dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 git make python3 CXX=g++-13 scripts/test-kar-expert-cache.sh python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit export CUDACXX=/tmp/cuda-toolkit/bin/nvcc diff --git a/deploy/kar-cuda-build.lock.json b/deploy/kar-cuda-build.lock.json index ebcc7d8a..1f6e12fb 100644 --- a/deploy/kar-cuda-build.lock.json +++ b/deploy/kar-cuda-build.lock.json @@ -7,6 +7,7 @@ "cmake": "4.2.3-2ubuntu2", "gcc-13": "13.4.0-10ubuntu1", "g++-13": "13.4.0-10ubuntu1", + "git": "1:2.53.0-1ubuntu1", "make": "4.4.1-3", "python3": "3.14.3-0ubuntu2" }, diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index 19cb1379..65b1bb43 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -13,7 +13,7 @@ assert lock['cuda_architecture']=='120' and lock['compile_jobs']==1 assert lock['cuda_toolkit_lock']=='cuda-toolkit.lock.json' toolkit=json.loads((ROOT/'deploy'/lock['cuda_toolkit_lock']).read_text()) assert toolkit['release']==lock['cuda_toolkit_release'] -required={'ca-certificates','cmake','gcc-13','g++-13','make','python3'} +required={'ca-certificates','cmake','gcc-13','g++-13','git','make','python3'} assert set(lock['apt_packages'])==required assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_packages'].values()) workflow=(ROOT/'.gitea/workflows/kar-cuda-compile.yml').read_text() @@ -23,7 +23,9 @@ assert 'options: --platform' not in workflow assert 'NVIDIA_VISIBLE_DEVICES: void' in workflow assert "CUDA_VISIBLE_DEVICES: ''" in workflow assert 'docker run' not in workflow -assert 'uses: builtin:checkout' in workflow +assert 'git fetch --depth=1 origin "$GITHUB_REF"' in workflow +assert 'GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}' in workflow +assert 'uses: builtin:checkout' not in workflow assert 'actions/checkout@' not in workflow for name,version in lock['apt_packages'].items(): assert f'{name}={version}' in workflow -- 2.54.0 From 25d2c07fde524bb983e5d1917993a695194d15e5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:17:24 +0200 Subject: [PATCH 06/13] fix(ci): install Python before CUDA build checks --- .gitea/workflows/kar-cuda-compile.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index f19663ae..0bd0a4e4 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -56,7 +56,6 @@ jobs: shell: bash run: | set -euo pipefail - python3 scripts/test-kar-cuda-build-lock.py test "$(dpkg --print-architecture)" = amd64 test "$NVIDIA_VISIBLE_DEVICES" = void test -z "$CUDA_VISIBLE_DEVICES" @@ -73,6 +72,7 @@ jobs: make=4.4.1-3 \ python3=3.14.3-0ubuntu2 dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 git make python3 + python3 scripts/test-kar-cuda-build-lock.py CXX=g++-13 scripts/test-kar-expert-cache.sh python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit export CUDACXX=/tmp/cuda-toolkit/bin/nvcc -- 2.54.0 From 106f2479012fe99ab362f0cb0c1138df22726c3e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:19:14 +0200 Subject: [PATCH 07/13] fix(ci): select installed CUDA host compiler --- .gitea/workflows/kar-cuda-compile.yml | 4 +++- scripts/test-kar-cuda-build-lock.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index 0bd0a4e4..ef25a937 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -78,6 +78,8 @@ jobs: export CUDACXX=/tmp/cuda-toolkit/bin/nvcc export CUDAToolkit_ROOT=/tmp/cuda-toolkit export CC=gcc-13 CXX=g++-13 - cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 + cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-13 \ + -DCMAKE_CUDA_ARCHITECTURES=120 cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$" diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index 65b1bb43..32574c05 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -25,6 +25,7 @@ assert "CUDA_VISIBLE_DEVICES: ''" in workflow assert 'docker run' not in workflow assert 'git fetch --depth=1 origin "$GITHUB_REF"' in workflow assert 'GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}' in workflow +assert '-DCMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-13' in workflow assert 'uses: builtin:checkout' not in workflow assert 'actions/checkout@' not in workflow for name,version in lock['apt_packages'].items(): -- 2.54.0 From 3f5cbf3d2ee798f2c71741c835aec8deed40e615 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:29:28 +0200 Subject: [PATCH 08/13] fix(ci): use CUDA-supported Ubuntu builder baseline --- .gitea/workflows/kar-cuda-compile.yml | 19 ++++++++++--------- deploy/kar-cuda-build.lock.json | 17 +++++++++-------- scripts/test-kar-cuda-build-lock.py | 2 ++ 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index ef25a937..ba70e4f5 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 150 container: - image: ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794 + image: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b env: NVIDIA_VISIBLE_DEVICES: void CUDA_VISIBLE_DEVICES: '' @@ -32,8 +32,8 @@ jobs: set -euo pipefail apt-get update -qq DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ - ca-certificates=20260601~26.04.1 \ - git=1:2.53.0-1ubuntu1 + ca-certificates=20260601~24.04.1 \ + git=1:2.43.0-1ubuntu7.3 - name: Checkout exact pull-request head shell: bash @@ -57,6 +57,7 @@ jobs: run: | set -euo pipefail test "$(dpkg --print-architecture)" = amd64 + test "$(getconf GNU_LIBC_VERSION)" = 'glibc 2.39' test "$NVIDIA_VISIBLE_DEVICES" = void test -z "$CUDA_VISIBLE_DEVICES" if compgen -G '/dev/nvidia*' >/dev/null; then @@ -65,12 +66,12 @@ jobs: fi apt-get update -qq DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ - ca-certificates=20260601~26.04.1 \ - cmake=4.2.3-2ubuntu2 \ - gcc-13=13.4.0-10ubuntu1 \ - g++-13=13.4.0-10ubuntu1 \ - make=4.4.1-3 \ - python3=3.14.3-0ubuntu2 + ca-certificates=20260601~24.04.1 \ + cmake=3.28.3-1build7 \ + gcc-13=13.3.0-6ubuntu2~24.04.1 \ + g++-13=13.3.0-6ubuntu2~24.04.1 \ + make=4.3-4.1build2 \ + python3=3.12.3-0ubuntu2.1 dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 git make python3 python3 scripts/test-kar-cuda-build-lock.py CXX=g++-13 scripts/test-kar-expert-cache.sh diff --git a/deploy/kar-cuda-build.lock.json b/deploy/kar-cuda-build.lock.json index 1f6e12fb..1a61f295 100644 --- a/deploy/kar-cuda-build.lock.json +++ b/deploy/kar-cuda-build.lock.json @@ -1,15 +1,16 @@ { "schema_version": 1, "platform": "linux/amd64", - "builder_image": "ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794", + "builder_image": "ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b", + "builder_glibc": "2.39", "apt_packages": { - "ca-certificates": "20260601~26.04.1", - "cmake": "4.2.3-2ubuntu2", - "gcc-13": "13.4.0-10ubuntu1", - "g++-13": "13.4.0-10ubuntu1", - "git": "1:2.53.0-1ubuntu1", - "make": "4.4.1-3", - "python3": "3.14.3-0ubuntu2" + "ca-certificates": "20260601~24.04.1", + "cmake": "3.28.3-1build7", + "gcc-13": "13.3.0-6ubuntu2~24.04.1", + "g++-13": "13.3.0-6ubuntu2~24.04.1", + "git": "1:2.43.0-1ubuntu7.3", + "make": "4.3-4.1build2", + "python3": "3.12.3-0ubuntu2.1" }, "cuda_toolkit_lock": "cuda-toolkit.lock.json", "cuda_toolkit_release": "13.0.1", diff --git a/scripts/test-kar-cuda-build-lock.py b/scripts/test-kar-cuda-build-lock.py index 32574c05..d0aac4a7 100644 --- a/scripts/test-kar-cuda-build-lock.py +++ b/scripts/test-kar-cuda-build-lock.py @@ -7,6 +7,7 @@ ROOT=Path(__file__).resolve().parents[1] lock=json.loads((ROOT/'deploy/kar-cuda-build.lock.json').read_text()) assert lock['schema_version']==1 assert lock['platform']=='linux/amd64' +assert lock['builder_glibc']=='2.39' assert re.fullmatch(r'ubuntu@sha256:[0-9a-f]{64}',lock['builder_image']) assert lock['cuda_toolkit_release']=='13.0.1' assert lock['cuda_architecture']=='120' and lock['compile_jobs']==1 @@ -18,6 +19,7 @@ assert set(lock['apt_packages'])==required assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_packages'].values()) workflow=(ROOT/'.gitea/workflows/kar-cuda-compile.yml').read_text() assert f"image: {lock['builder_image']}" in workflow +assert "getconf GNU_LIBC_VERSION)" in workflow and "'glibc 2.39'" in workflow assert 'pull_request:' in workflow and '\n push:' not in workflow assert 'options: --platform' not in workflow assert 'NVIDIA_VISIBLE_DEVICES: void' in workflow -- 2.54.0 From cbe7c7021b1fee0f56905c7709a138ed17b5be50 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 14:58:19 +0200 Subject: [PATCH 09/13] fix(kar): add cache test header include path --- gpu/kar/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/gpu/kar/CMakeLists.txt b/gpu/kar/CMakeLists.txt index 5b67d607..6666c456 100644 --- a/gpu/kar/CMakeLists.txt +++ b/gpu/kar/CMakeLists.txt @@ -58,6 +58,7 @@ target_link_libraries(strata-kar-expert-probe PRIVATE strata_kar_cuda strata_kar enable_testing() add_executable(strata-kar-expert-cache-test src/kar_expert_cache_test.cpp) target_compile_features(strata-kar-expert-cache-test PRIVATE cxx_std_17) +target_include_directories(strata-kar-expert-cache-test PRIVATE include) add_test(NAME kar_expert_cache_index COMMAND strata-kar-expert-cache-test) set_tests_properties(kar_expert_cache_index PROPERTIES TIMEOUT 60) add_executable(strata-kar-expert-test src/kar_expert_test.cpp) -- 2.54.0 From 33f075fb7c9cdee9094df003c247cca2adb807b6 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 18:20:58 +0200 Subject: [PATCH 10/13] feat(kar): add explicit bounded batched prefill backend --- .gitea/workflows/kar-cuda-compile.yml | 25 ++++- docs/upstream.md | 23 ++++- .../strata/prefill/experimental_experts.hpp | 85 +++++++++++++++++ .../strata/include/strata/prefill/prefill.hpp | 11 +++ engine/strata/src/prefill/prefill.cpp | 52 ++++++++++- engine/strata/src/program/generate.cpp | 17 ++++ gpu/kar/README.md | 36 +++++++- gpu/kar/include/kar_expert_miss.hpp | 5 +- gpu/kar/src/kar_expert_miss.cpp | 2 +- scripts/test-kar-prefill-contract.sh | 14 +++ tests/kar-prefill-contract.cpp | 92 +++++++++++++++++++ 11 files changed, 349 insertions(+), 13 deletions(-) create mode 100644 engine/strata/include/strata/prefill/experimental_experts.hpp create mode 100755 scripts/test-kar-prefill-contract.sh create mode 100644 tests/kar-prefill-contract.cpp diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index ba70e4f5..d7b22251 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -5,8 +5,16 @@ on: paths: - 'gpu/kar/**' - 'engine/strata/CMakeLists.txt' + - 'engine/strata/include/strata/prefill/**' + - 'engine/strata/src/prefill/**' + - 'engine/strata/src/program/generate.cpp' + - 'tests/kar-prefill-contract.cpp' + - 'scripts/test-kar-prefill-contract.sh' + - 'docs/upstream.md' + - 'gpu/kar/README.md' - 'scripts/bootstrap-cuda-toolkit.py' - 'scripts/build-static-cuda.sh' + - 'scripts/check-static-cuda-elf.py' - 'scripts/test-kar-expert-cache.sh' - 'scripts/test-kar-cuda-build-lock.py' - 'deploy/cuda-toolkit.lock.json' @@ -52,7 +60,7 @@ jobs: test "$(git rev-parse HEAD)" = "$GITHUB_SHA" unset GITEA_TOKEN - - name: Compile CUDA component in pinned GPU-hidden container + - name: Compile CUDA component and native engine in pinned GPU-hidden container shell: bash run: | set -euo pipefail @@ -75,6 +83,7 @@ jobs: dpkg-query -W -f='${Package}=${Version}\n' ca-certificates cmake gcc-13 g++-13 git make python3 python3 scripts/test-kar-cuda-build-lock.py CXX=g++-13 scripts/test-kar-expert-cache.sh + CXX=g++-13 scripts/test-kar-prefill-contract.sh python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit export CUDACXX=/tmp/cuda-toolkit/bin/nvcc export CUDAToolkit_ROOT=/tmp/cuda-toolkit @@ -84,3 +93,17 @@ jobs: -DCMAKE_CUDA_ARCHITECTURES=120 cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$" + + # Compile the actual native engine, including generate and Prefill: + # the standalone KAR component cannot cover their callback integration. + cmake -S engine/strata -B /tmp/kar-engine-build \ + -DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF \ + -DSTRATA_CUDA_STATIC=ON -DSTRATA_NATIVE_EXPERTS=ON \ + -DSTRATA_PORTABLE=ON -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON \ + -DSTRATA_NEXT_KAR_DIR="$PWD/gpu/kar" \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120 \ + -DCMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-13 + cmake --build /tmp/kar-engine-build --parallel 1 --target strata + python3 scripts/check-static-cuda-elf.py /tmp/kar-engine-build/strata + env -u LD_LIBRARY_PATH /tmp/kar-engine-build/strata --help diff --git a/docs/upstream.md b/docs/upstream.md index 0c42da90..b3642247 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -7,7 +7,8 @@ | Upstream repository URL | https://github.com/Niko1221/Strata.git | | Upstream commit SHA | `d9ab8435f654c368c586340d490915f6addf56a3` | | Local repository path | `engine/strata/` | -| Hosted project repository URL | https://github.com/paveldhq/strata-next (private) | +| Primary hosted project repository URL | https://git.vezha.io/para/leleka (private; push and CI) | +| Historical hosted project repository URL | https://github.com/paveldhq/strata-next (private) | | Import date | 2026-10-02 | | Engine build instructions | `scripts/build-cpu.sh` for source checks; CUDA build still to validate on Linux GPU | | Local patch strategy | Squashed Git subtree; preserve upstream commit IDs in subtree merge messages | @@ -16,6 +17,10 @@ The local Git remote `strata-upstream` points to the URL above. To review an upd The imported upstream tree includes its own small optional experimental control-vector GGUF and reference data. Production model weights, captures, and generated output remain outside this repository. The private project repository was created on 2026-10-04; its initial `main` is `858e7aa050f56b051dac5e3d7b765a05cb958aee`. This preserves the existing subtree history and does not change the pinned upstream identity. +Project pushes and CI now use the private Gitea repository above. The historical +hosting record and the pinned Strata upstream identity remain traceable; this +hosting change does not advance or replace the imported upstream source. + ## Local CUDA validation, 2026-10-04 The upstream identity above is unchanged. The local Keyless opt-in fork compiled @@ -44,3 +49,19 @@ also exercises KAR misses. The runtime requires explicit archive and precision environment settings, validates the archive payload and expert geometry, and rejects unsupported pool/multi-device configurations. This is an experimental quality arm, not full compressed-model residency or a qualified speedup. + +## Experimental KAR batched prefill, 2026-10-07 + +The upstream SHA above is unchanged. A separate local +`STRATA_NEXT_KAR_PREFILL=1` opt-in connects batched prefill to the same KAR expert +backend. It requires the experimental expert build and explicit archive/level; +without the opt-in, prefill retains the upstream native IQ path. The callback +uses bounded groups of at most eight activations, preserves grouped output and +router weighting, and stops on backend or transfer failures. This arm bypasses +native routed-expert staging/GEMM and its streaming producer, while keeping +shared/dense projections and the native cache for verifier hits. + +Host grouping contracts and GPU-hidden native-engine compilation are separate +from real GPU validation. Tensor/logit parity, compressed residency, model +quality and paired end-to-end measurements remain mandatory; this source change +does not establish those results or enable the experimental profile by default. diff --git a/engine/strata/include/strata/prefill/experimental_experts.hpp b/engine/strata/include/strata/prefill/experimental_experts.hpp new file mode 100644 index 00000000..8191d4cf --- /dev/null +++ b/engine/strata/include/strata/prefill/experimental_experts.hpp @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::prefill { + +using ExperimentalExperts = bool (*)(void*, int64_t, const float*, const int32_t*, + int64_t, int64_t, int32_t*, float*, std::string&); + +inline bool parse_experimental_prefill_flag(const char* text, bool& enabled, std::string& error) { + enabled = text && std::strcmp(text, "1") == 0; + if (!text || std::strcmp(text, "0") == 0 || enabled) return true; + error = "STRATA_NEXT_KAR_PREFILL must be exactly 0 or 1"; + return false; +} + +// Host contract for the explicit experimental prefill backend. Read and write +// must complete their transfers before returning: each batch reuses these buffers. +// Each output is an unweighted expert row in grouped order; moe_combine owns weights. +template +bool dispatch_grouped_experts(int64_t layer, int64_t hidden, int64_t experts, + int64_t tokens, int64_t routes, const int32_t* offsets, + const int32_t* source_rows, ExperimentalExperts backend, + void* user, Read read, Write write, uint64_t& completed, + std::string& error) { + if (!backend || !user || hidden < 1 || hidden > 16384 || experts < 1 || experts > 4096 || + tokens < 1 || routes < 1 || routes > 16 || + tokens > std::numeric_limits::max() / routes || + !offsets || !source_rows || offsets[0] != 0 || offsets[experts] != tokens * routes) { + error = "prefill: invalid experimental expert grouping"; + return false; + } + const int64_t rows = tokens * routes; + // Validate the entire grouping before any backend result is written. + for (int64_t e = 0; e < experts; ++e) + if (offsets[e] < 0 || offsets[e + 1] < offsets[e] || offsets[e + 1] > rows) { + error = "prefill: invalid experimental expert offsets"; + return false; + } + for (int64_t row = 0; row < rows; ++row) + if (source_rows[row] < 0 || source_rows[row] >= tokens) { + error = "prefill: invalid experimental expert source row"; + return false; + } + constexpr int64_t batch_limit = 8; + std::vector input((size_t) (batch_limit * hidden)); + std::vector output(input.size()); + std::array ids{}, kind{}; + for (int64_t e = 0; e < experts; ++e) { + ids.fill((int32_t) e); + for (int64_t begin = offsets[e]; begin < offsets[e + 1]; begin += batch_limit) { + const int64_t count = std::min(batch_limit, (int64_t) offsets[e + 1] - begin); + if (!read(source_rows + begin, count, input.data(), error)) return false; + kind.fill(-1); + std::fill(output.begin(), output.end(), std::numeric_limits::quiet_NaN()); + if (!backend(user, layer, input.data(), ids.data(), count, 1, + kind.data(), output.data(), error)) { + if (error.empty()) error = "prefill: experimental expert backend failed"; + return false; + } + for (int64_t i = 0; i < count; ++i) + if (kind[(size_t) i] != 3) { + error = "prefill: experimental expert backend left an unhandled row"; + return false; + } + for (int64_t i = 0; i < count * hidden; ++i) + if (!std::isfinite(output[(size_t) i])) { + error = "prefill: experimental expert backend returned a non-finite row"; + return false; + } + if (!write(begin, count, output.data(), error)) return false; + completed += (uint64_t) count; + } + } + return true; +} + +} // namespace strata::prefill diff --git a/engine/strata/include/strata/prefill/prefill.hpp b/engine/strata/include/strata/prefill/prefill.hpp index da225d3b..55e21542 100644 --- a/engine/strata/include/strata/prefill/prefill.hpp +++ b/engine/strata/include/strata/prefill/prefill.hpp @@ -10,6 +10,7 @@ // Requires the native weights (`--native`): every quantized projection must carry its GGUF blocks. #pragma once +#include "strata/prefill/experimental_experts.hpp" #include "strata/core/expert_cache.hpp" #include "strata/core/expert_source.hpp" #include "strata/core/layer.hpp" @@ -30,6 +31,7 @@ struct PrefillStats { double ms_experts_host = 0; ///< host time staging non-resident experts int64_t experts_streamed = 0; ///< expert blobs copied host -> device int64_t experts_dma = 0; ///< ...of which straight from the pinned arena (no CPU copy) + uint64_t experimental_expert_rows = 0; ///< completed KAR rows; not native cache hits int64_t experts_resident = 0; ///< expert-layer groups served from the VRAM tier double ms_ple = 0; }; @@ -57,6 +59,13 @@ public: /// callbacks stay. The device `init` ran on must be current. void reset(); + /// Explicit lossy experiment, off by default. Handles all routed prefill + /// experts; shared/dense work stays native. The owner must outlive this Prefill. + /// Callback and owner survive reset; backend errors abort, never native fallback. + void set_experimental_experts(ExperimentalExperts backend, void* user) { + experimental_experts_ = backend; experimental_user_ = user; + } + /// `host_res`: the static residency table (n_layers x n_expert, slot or -1) or null; `cache` its slots. /// `borrow`/`borrow_bytes`: device memory to carve every buffer from (the top slots of the expert cache, /// lent for the prompt and refilled after it); null = allocate normally. @@ -114,6 +123,8 @@ public: } private: + ExperimentalExperts experimental_experts_ = nullptr; + void* experimental_user_ = nullptr; int64_t stage_lb_ = 0, stage_le_ = -1; Prefill* next_ = nullptr; const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) diff --git a/engine/strata/src/prefill/prefill.cpp b/engine/strata/src/prefill/prefill.cpp index 37edb9f0..b1a6ba3d 100644 --- a/engine/strata/src/prefill/prefill.cpp +++ b/engine/strata/src/prefill/prefill.cpp @@ -997,11 +997,15 @@ struct PfTimer { bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { err.clear(); + if (experimental_experts_ && !experimental_user_) { + err = "prefill: missing experimental expert backend owner"; return false; + } Impl& m = *impl_; const core::OnDevice on_device(m.device); const core::ModelGeometry& g = *m.g; core::SessionState& ss = *m.ss; const auto t_start = Clock::now(); + const uint64_t experimental_before = stats_.experimental_expert_rows; // Offline teacher capture for fitting only the paper's query-routing parameters. // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. std::ofstream keyless_trace; @@ -1168,7 +1172,9 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's // `used` event recorded), so the copy stream never waits on an event that is not queued yet const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout(); - const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr; + // KAR owns all routed expert rows in this explicit arm. Do not start + // the native streaming producer: no consumer would release its ring slots. + const bool stream_all = !experimental_experts_ && m.ring > STAGE && T >= stream_all_min() && m.src != nullptr; struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; }; std::vector seq; std::vector seq_start; @@ -1655,13 +1661,44 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); } - // the experts, in id order: resident ones from VRAM, the others through the staging ring std::vector order; for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e); const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); - const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; + const bool use_mmq = !experimental_experts_ && mmq_plan().any && mmq_plan().layer[(size_t) l]; const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; + if (experimental_experts_) { + // Existing host grouping ordered the router results. Each + // bounded activation read also waits for mixed/slot writes + // on this Prefill stream; KAR runs on its own stream. + auto read = [&](const int32_t* rows, int64_t count, float* dst, std::string& e) { + for (int64_t i = 0; i < count; ++i) + if (cudaMemcpyAsync(dst + i * N, m.mixed + (int64_t) rows[i] * N, + (size_t) N * sizeof(float), cudaMemcpyDeviceToHost, m.cs) != cudaSuccess) { + cudaStreamSynchronize(m.cs); + e = "prefill: KAR activation read failed"; return false; + } + if (cudaStreamSynchronize(m.cs) != cudaSuccess) { + e = "prefill: KAR activation stream failed"; return false; + } + return true; + }; + auto write = [&](int64_t begin, int64_t count, const float* src, std::string& e) { + const auto copied = cudaMemcpyAsync(m.Dm + begin * N, src, + (size_t) (count * N) * sizeof(float), cudaMemcpyHostToDevice, m.cs); + // Before reusable host output is touched again, only + // this Prefill stream must finish reading it. + const auto done = cudaStreamSynchronize(m.cs); + if (copied != cudaSuccess || done != cudaSuccess) { + e = "prefill: KAR output upload failed"; return false; + } + return true; + }; + if (!dispatch_grouped_experts(l, N, m.g->n_expert, T, K, m.off.data(), src_h, + experimental_experts_, experimental_user_, read, write, + stats_.experimental_expert_rows, err)) return false; + } else { + // Native experts: resident ones from VRAM, others through the staging ring. const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; pt.mark(kPfGather, cs); @@ -1851,6 +1888,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } release_to(m.g->n_expert); } + } // native routed experts; experimental rows are already in Dm pt.mark(kPfCombine, cs); moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs); // debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values @@ -1863,8 +1901,9 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e for (float v : h) c += !std::isfinite(v); return c; }; - const int64_t bgu = bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N), bbo = bad(m.bo, T * N); - const int64_t bh = m.H ? bad(m.H, T * K * 640) : -1; + // KAR validates its returned rows; native GU/H buffers are unused in that arm. + const int64_t bgu = experimental_experts_ ? 0 : bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N), bbo = bad(m.bo, T * N); + const int64_t bh = !experimental_experts_ && m.H ? bad(m.H, T * K * 640) : -1; static int64_t reported = -1; if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) { reported = stats_.chunks; @@ -1982,6 +2021,9 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e return false; } stats_.ms_total += ms_since(t_start); + if (experimental_experts_) + std::fprintf(stderr, "strata prefill: experimental KAR routed rows=%llu; native cache retained; quality not qualified\n", + (unsigned long long) (stats_.experimental_expert_rows - experimental_before)); if (pt.on) { pt.fold(); double total = 0.0; diff --git a/engine/strata/src/program/generate.cpp b/engine/strata/src/program/generate.cpp index 1e8cdfa3..6f3abf00 100644 --- a/engine/strata/src/program/generate.cpp +++ b/engine/strata/src/program/generate.cpp @@ -1895,6 +1895,15 @@ int main(int argc, char** argv) { } } const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); + bool kar_prefill = false; + if (!strata::prefill::parse_experimental_prefill_flag(std::getenv("STRATA_NEXT_KAR_PREFILL"), kar_prefill, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 2; + } + if (kar_prefill && (!kar_expert_archive || !*kar_expert_archive || o.prefill_chunk <= 0)) { + std::fprintf(stderr, "strata generate: KAR prefill requires an explicit KAR expert archive and --prefill CHUNK\n"); + return 2; + } + #if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) strata::kar::ExpertMiss kar_expert_miss; if (kar_expert_archive != nullptr) { @@ -1918,6 +1927,8 @@ int main(int argc, char** argv) { // Native resident hits are the baseline. Route all otherwise CPU/PCIe // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. o.pcie_frac = 0; + if (kar_prefill) + std::fprintf(stderr, "strata generate: experimental KAR prefill ON: all routed experts; native cache retained; quality not qualified\n"); } #else if (kar_expert_archive != nullptr) { @@ -3947,6 +3958,9 @@ int main(int argc, char** argv) { return 2; } strata::prefill::Prefill sp; +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + if (kar_prefill) sp.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); +#endif void* borrow = nullptr; uint64_t borrow_bytes = 0; int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk) @@ -5828,6 +5842,9 @@ int main(int argc, char** argv) { int64_t pos_start = 0; int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used) strata::prefill::Prefill prefill; +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + if (kar_prefill) prefill.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); +#endif double prefill_batched_ms = 0; std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb"); std::vector final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0); diff --git a/gpu/kar/README.md b/gpu/kar/README.md index 3216222a..a78b2908 100644 --- a/gpu/kar/README.md +++ b/gpu/kar/README.md @@ -218,9 +218,39 @@ CUDA component tests also check exact reconstructed matrices and FP64 multiply parity on a GPU; CI only compiles those targets with GPU devices hidden and does not claim runtime correctness or model quality. -The Gitea build lock is `deploy/kar-cuda-build.lock.json`: Ubuntu 26.04 amd64 -base image digest `88a381d5…d3794`, GCC/G++ 13.4.0, CMake 4.2.3, GNU make -4.4.1 and Python 3.14.3. The CUDA compiler and redistributable components are +The Gitea build lock is `deploy/kar-cuda-build.lock.json`: Ubuntu 24.04 amd64 +base image digest `f610ab94…6106b`, glibc 2.39, GCC/G++ 13.3.0, CMake 3.28.3, +GNU make 4.3 and Python 3.12.3. The CUDA compiler and redistributable components are separately checksum-locked in `deploy/cuda-toolkit.lock.json` to NVIDIA CUDA 13.0.1. The lock records the direct apt package versions; Ubuntu's transitive packages are resolved from that image's configured archive during CI. + +## Explicit experimental KAR prefill + +Archive-only mode still routes native verifier misses through KAR and retains +native IQ prefill and verifier hits. `STRATA_NEXT_KAR_PREFILL=1` additionally +routes **all routed prefill experts** through that same verified archive and +bounded compressed cache. This switch accepts exactly `0` or `1`; unset and `0` +keep the prior behavior. It requires the experimental KAR build, archive, +explicit level, supported single-GPU native geometry and `--prefill CHUNK`. + +The prefill host grouping gathers at most eight F32 activation rows per expert, +waits only for its own CUDA stream, invokes KAR, and uploads unweighted output +rows in grouped order for the existing MoE combine. The reusable host buffers +must finish their transfers before reuse. Native expert staging/MMQ is bypassed +for this arm, including the large-prompt stream-all producer whose ring would +otherwise have no consumer. Shared experts, dense projections, router weights, +MTP and the allocated native IQ cache stay unchanged. The callback owner lives +through both serve and CLI prefill, and the callback survives Prefill reset. + +A failed backend, unhandled row, non-finite result or failed transfer aborts +prefill; no partially computed output is replaced by the native path. This is +an explicit lossy experiment, not a performance improvement or full-model +compressed residency claim. Actual GPU/model correctness, paired quality and +residency qualification remain required before promotion. + +`scripts/test-kar-prefill-contract.sh` checks grouped scatter with uneven batches, +strict opt-in values, row bounds and fail-closed ownership/transfer behavior +without CUDA. Gitea additionally compiles the actual native CUDA engine with +the experimental backend enabled and devices hidden, then audits the static +ELF and runs `--help`; those build gates do not exercise inference. diff --git a/gpu/kar/include/kar_expert_miss.hpp b/gpu/kar/include/kar_expert_miss.hpp index 6e8e9cd2..43ef7d9e 100644 --- a/gpu/kar/include/kar_expert_miss.hpp +++ b/gpu/kar/include/kar_expert_miss.hpp @@ -6,8 +6,9 @@ namespace strata::kar { -// Experimental native verifier cache-miss arm. Batched prefill and cache hits retain -// the native IQ weights. Not a full compressed-model serving implementation. +// Experimental native verifier cache-miss backend. A separate explicit prefill +// opt-in uses it for all routed prompt rows; verifier hits retain native IQ. +// Not a full compressed-model serving implementation. class ExpertMiss { public: ExpertMiss(); diff --git a/gpu/kar/src/kar_expert_miss.cpp b/gpu/kar/src/kar_expert_miss.cpp index cbe399fe..cd9ee9e2 100644 --- a/gpu/kar/src/kar_expert_miss.cpp +++ b/gpu/kar/src/kar_expert_miss.cpp @@ -93,7 +93,7 @@ bool ExpertMiss::open(const char* path,uint32_t layers,uint32_t experts,uint32_t } if(!p->resident.open(hidden,ff,level,8,error,compressed_cache_budget_bytes))return false; p->input.resize(size_t(hidden)*8);p->output.resize(size_t(hidden)*8); - std::fprintf(stderr,"strata KAR experimental: native verifier misses (short prompt and decode), level=%u, compressed=%llu scratch=%llu; quality not qualified\n", + std::fprintf(stderr,"strata KAR experimental expert backend: level=%u, compressed=%llu scratch=%llu; verifier misses and explicit prefill opt-in; quality not qualified\n", level,(unsigned long long)p->resident.resident_bytes(),(unsigned long long)p->resident.scratch_bytes()); impl_=std::move(p);return true; } diff --git a/scripts/test-kar-prefill-contract.sh b/scripts/test-kar-prefill-contract.sh new file mode 100755 index 00000000..24d8a697 --- /dev/null +++ b/scripts/test-kar-prefill-contract.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +build_dir="$(mktemp -d "${TMPDIR:-/tmp}/kar-prefill-contract.XXXXXX")" +trap 'rm -rf "$build_dir"' EXIT +"${CXX:-c++}" -std=c++17 -Wall -Wextra -Werror -pedantic \ + -fsanitize=address,undefined -fno-omit-frame-pointer \ + -I"$repo_root/engine/strata/include" \ + "$repo_root/tests/kar-prefill-contract.cpp" -o "$build_dir/kar-prefill-contract" +if [[ "$(uname -s)" == Darwin ]]; then + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-prefill-contract" +else + ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-prefill-contract" +fi diff --git a/tests/kar-prefill-contract.cpp b/tests/kar-prefill-contract.cpp new file mode 100644 index 00000000..e173d48f --- /dev/null +++ b/tests/kar-prefill-contract.cpp @@ -0,0 +1,92 @@ +#include "strata/prefill/experimental_experts.hpp" + +#include +#include +#include + +using namespace strata::prefill; +struct Backend { + int calls = 0, mode = 0; + std::vector batches; +}; +bool backend(void* user, int64_t layer, const float* x, const int32_t* ids, + int64_t tokens, int64_t k, int32_t* kind, float* y, std::string& error) { + auto& b = *static_cast(user); + ++b.calls; + b.batches.push_back(tokens); + assert(layer == 7 && tokens >= 1 && tokens <= 8 && k == 1); + if (b.mode == 1 || (b.mode == 5 && b.calls == 2)) { error = "synthetic backend fault"; return false; } + if (b.mode == 2) return true; // unhandled rows may not fall back + for (int64_t t = 0; t < tokens; ++t) { + assert(kind[t] == -1 && ids[t] == ids[0]); + kind[t] = 3; + for (int h = 0; h < 3; ++h) y[t * 3 + h] = x[t * 3 + h] + (float) ids[t] * 100; + } + if (b.mode == 3) y[0] = std::numeric_limits::infinity(); + if (b.mode == 4) y[1] = std::numeric_limits::quiet_NaN(); + return true; +} +int main() { + std::string error; + bool enabled = true; + assert(parse_experimental_prefill_flag(nullptr, enabled, error) && !enabled); + assert(parse_experimental_prefill_flag("0", enabled, error) && !enabled); + assert(parse_experimental_prefill_flag("1", enabled, error) && enabled); + for (auto bad : {"", "true", "01", "2", " 1", "1 "}) + assert(!parse_experimental_prefill_flag(bad, enabled, error)); + + // 19 tokens, 2 routes: expert 0 is split 8/8/3, expert 1 empty, + // expert 2 split 8/8/3; reversed second group verifies grouped scatter. + std::array offsets{0, 19, 19, 38}; + std::array source{}; + for (int t = 0; t < 19; ++t) { source[t] = t; source[19 + t] = 18 - t; } + std::array output{}; + int reads = 0, writes = 0; + bool read_fail = false, write_fail = false; + auto read = [&](const int32_t* rows, int64_t n, float* x, std::string& e) { + ++reads; + if (read_fail) { e = "synthetic transfer fault"; return false; } + for (int64_t t = 0; t < n; ++t) + for (int h = 0; h < 3; ++h) x[t * 3 + h] = (float) (rows[t] * 10 + h); + return true; + }; + auto write = [&](int64_t begin, int64_t n, const float* y, std::string& e) { + ++writes; + if (write_fail) { e = "synthetic output fault"; return false; } + std::copy(y, y + n * 3, output.begin() + begin * 3); + return true; + }; + Backend b; + uint64_t completed = 0; + auto run = [&](int64_t hidden = 3, void* owner = nullptr) { + return dispatch_grouped_experts(7, hidden, 3, 19, 2, offsets.data(), source.data(), + backend, owner ? owner : &b, read, write, completed, error); + }; + assert(run() && completed == 38 && reads == 6 && writes == 6); + assert((b.batches == std::vector{8, 8, 3, 8, 8, 3})); + for (int row = 0; row < 38; ++row) + for (int h = 0; h < 3; ++h) + assert(output[row * 3 + h] == source[row] * 10 + h + (row < 19 ? 0 : 200)); + for (int mode = 1; mode <= 4; ++mode) { + b = Backend{}; b.mode = mode; completed = 0; reads = writes = 0; + assert(!run() && completed == 0 && b.calls == 1 && writes == 0 && !error.empty()); + } + b = Backend{}; b.mode = 5; completed = 0; reads = writes = 0; + assert(!run() && completed == 8 && b.calls == 2 && writes == 1); + b = Backend{}; completed = 0; reads = writes = 0; + assert(!dispatch_grouped_experts(7, 3, 3, 19, 2, offsets.data(), source.data(), + backend, nullptr, read, write, completed, error) && b.calls == 0 && reads == 0); + source.back() = 19; + assert(!run() && reads == 0 && b.calls == 0 && writes == 0); + source.back() = 0; + offsets[1] = 39; + assert(!run() && reads == 0 && b.calls == 0); + offsets[1] = 19; + assert(!run(0) && reads == 0 && b.calls == 0); + assert(!run(16385) && reads == 0 && b.calls == 0); + read_fail = true; + assert(!run() && b.calls == 0 && writes == 0); + read_fail = false; write_fail = true; + assert(!run() && b.calls == 1 && completed == 0); + std::cout << "PASS: bounded KAR prefill grouping, scatter, strict opt-in and fail-closed ownership/transfer contract\n"; +} -- 2.54.0 From b6563e3937683c722dd700fe64001043744b3bf0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 19:06:39 +0200 Subject: [PATCH 11/13] feat(kar): isolate target native routed storage in explicit mode --- .gitea/workflows/kar-cuda-compile.yml | 5 + docs/upstream.md | 46 ++++++ .../strata/core/experimental_routed.hpp | 120 ++++++++++++++ .../include/strata/core/expert_source.hpp | 2 + engine/strata/include/strata/core/verify.hpp | 1 + .../strata/include/strata/prefill/prefill.hpp | 8 +- engine/strata/src/core/expert_source.cpp | 11 ++ engine/strata/src/core/verify.cpp | 52 ++++-- engine/strata/src/prefill/prefill.cpp | 73 ++++++--- engine/strata/src/program/generate.cpp | 84 ++++++++-- scripts/test-kar-all-routed-contract.sh | 14 ++ tests/kar-all-routed-contract.cpp | 148 ++++++++++++++++++ 12 files changed, 512 insertions(+), 52 deletions(-) create mode 100644 engine/strata/include/strata/core/experimental_routed.hpp create mode 100755 scripts/test-kar-all-routed-contract.sh create mode 100644 tests/kar-all-routed-contract.cpp diff --git a/.gitea/workflows/kar-cuda-compile.yml b/.gitea/workflows/kar-cuda-compile.yml index d7b22251..daf72765 100644 --- a/.gitea/workflows/kar-cuda-compile.yml +++ b/.gitea/workflows/kar-cuda-compile.yml @@ -5,11 +5,15 @@ on: paths: - 'gpu/kar/**' - 'engine/strata/CMakeLists.txt' + - 'engine/strata/include/strata/core/**' + - 'engine/strata/src/core/**' - 'engine/strata/include/strata/prefill/**' - 'engine/strata/src/prefill/**' - 'engine/strata/src/program/generate.cpp' - 'tests/kar-prefill-contract.cpp' - 'scripts/test-kar-prefill-contract.sh' + - 'tests/kar-all-routed-contract.cpp' + - 'scripts/test-kar-all-routed-contract.sh' - 'docs/upstream.md' - 'gpu/kar/README.md' - 'scripts/bootstrap-cuda-toolkit.py' @@ -84,6 +88,7 @@ jobs: python3 scripts/test-kar-cuda-build-lock.py CXX=g++-13 scripts/test-kar-expert-cache.sh CXX=g++-13 scripts/test-kar-prefill-contract.sh + CXX=g++-13 scripts/test-kar-all-routed-contract.sh python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit export CUDACXX=/tmp/cuda-toolkit/bin/nvcc export CUDAToolkit_ROOT=/tmp/cuda-toolkit diff --git a/docs/upstream.md b/docs/upstream.md index b3642247..d7f92e11 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -65,3 +65,49 @@ Host grouping contracts and GPU-hidden native-engine compilation are separate from real GPU validation. Tensor/logit parity, compressed residency, model quality and paired end-to-end measurements remain mandatory; this source change does not establish those results or enable the experimental profile by default. + +## Experimental KAR all-routed target isolation, 2026-10-07 + +The pinned upstream SHA remains unchanged. A separate local default-off +`STRATA_NEXT_KAR_ALL_ROUTED=1` arm requires `STRATA_NEXT_KAR_PREFILL=1`, the +experimental KAR CUDA build, explicit expert archive and level, a native pack, +fixed positive `--prefill CHUNK`, `--spec 2..8`, `--expert-cache 0`, `--pcie-frac 0`, and disabled +adaptive native cache (`--adapt-every 0` or `--adapt-swaps 0`). It rejects native +expert profiles, mmap/resident/shared native banks, nonzero PCIe share, native +cache policy/order switches, disabled callbacks, GPU-floor/no-capture modes, +multi-device configurations, automatic chunks and a native device expert plan. +Admission precedes opening the KAR backend or mutating its runtime options. + +For the target layers, this arm omits opening `ArenaExpertSource` or +`FileExpertSource`, native `ExpertCache` slots and native hit buffers. The early +multi-token callback validates the whole window before any native lookahead, +source begin/prefetch, quantization, plan or CPU expert job. Every routed row +starts unowned and must return as a finite unweighted `kind=3` row in routing +order; malformed input, duplicate experts within a token, missing owners, +unhandled rows or backend faults fail the layer. Completed KAR rows count as +native cache refusals, never native hits; native CPU job/miss counts remain zero. +The verifier accepts an absent native tier only in this explicit mode, requires +the host callback, copies all completed host rows to its existing combine and +omits native routed activation/hit/PCIe staging buffers and kernels. Its normal +empty-plan completion publishes the A/B flags after the callback returns. + +Prefill selects this allocation mode before initialization and keeps it across +reset and relayout. Counting and carving use the same mode; routed GU, fallback +activation/intermediate, MMQ, dequantized expert and staging rings, native +stager workers and ring events are omitted. Router/grouping, routed output rows, +shared experts, dense/embedding/head/PLE, attention, KV/indexer and session +state remain. Attention and MoE scratch share a region sized by their maximum, +so omitted MoE buffers cannot be added together as a claimed VRAM saving. The +CPU expert-pool object remains for existing callback plumbing but runs no native +routed jobs. The MTP drafter still uploads its separate native draft experts +when configured: this is **not** a zero-copy full compressed-model claim. + +`scripts/test-kar-all-routed-contract.sh` uses synthetic expert matrices and +non-unit router weights to check 128 rows against an independent CPU combine +oracle (absolute tolerance `1e-5`), strict admission, successful counters/usage, +null native handles, bounds, ownership, nonfinite/duplicate input and injected +backend faults under address/undefined-behavior sanitizers. The existing +prefill contract test also passes. These CPU results establish host contracts; +CUDA compilation, real tensor/logit parity, model quality, allocation telemetry +and paired end-to-end performance measurements are separate gates. No quality, +measured memory saving or performance qualification is established by this patch. diff --git a/engine/strata/include/strata/core/experimental_routed.hpp b/engine/strata/include/strata/core/experimental_routed.hpp new file mode 100644 index 00000000..06d87eb4 --- /dev/null +++ b/engine/strata/include/strata/core/experimental_routed.hpp @@ -0,0 +1,120 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +// Separate from KAR misses and KAR_PREFILL: this arm removes the target's +// native routed bank. Every selected row must therefore have a KAR owner. +inline bool parse_experimental_all_routed_flag(const char* text, bool& enabled, std::string& error) { + enabled = text && std::strcmp(text, "1") == 0; + if (!text || std::strcmp(text, "0") == 0 || enabled) return true; + error = "STRATA_NEXT_KAR_ALL_ROUTED must be exactly 0 or 1"; + return false; +} + +struct ExperimentalRoutedProfile { + bool built = false, native_pack = false, prefill = false; + bool no_pool = false, no_capture = false, multi_device = false; + bool native_bank_option = false, adaptive_cache = false, device_plan = false; + const char* archive = nullptr; + const char* level = nullptr; + int64_t chunk = 0, window = 0; + bool automatic_chunk = false; + int native_cache = 0; + bool native_profile = false; +}; + +// Admission must precede archive GPU allocations and changes to options. +inline bool validate_experimental_routed_profile(const ExperimentalRoutedProfile& p, std::string& error) { + if (!p.built || !p.native_pack || !p.prefill || !p.archive || !*p.archive || + !p.level || std::strlen(p.level) != 1 || p.level[0] < '1' || p.level[0] > '8' || + p.chunk <= 0 || p.automatic_chunk || p.window < 2 || p.window > 8 || + p.no_pool || p.no_capture || p.multi_device || p.native_bank_option || + p.adaptive_cache || p.device_plan || p.native_cache != 0 || p.native_profile) { + error = "KAR all-routed requires the experimental CUDA build, native pack, explicit archive/level, " + "KAR_PREFILL=1, fixed --prefill CHUNK, --spec 2..8, enabled callback, --expert-cache 0, --pcie-frac 0, " + "--adapt-every 0 (or --adapt-swaps 0), one GPU, and no native expert profile/bank or device plan"; + return false; + } + return true; +} + +using ExperimentalRoutedBackend = bool (*)(void*, int64_t, const float*, const int32_t*, + int64_t, int64_t, int32_t*, float*, std::string&); + +// Unweighted rows in routing order: the caller's existing combine applies weights. +// No source, native pool, residency table, activation quantizer or plan is needed. +inline bool dispatch_experimental_all_routed(int64_t layer, int64_t layers, int64_t hidden, int64_t experts, + const float* input, const int32_t* ids, int64_t tokens, int64_t routes, + ExperimentalRoutedBackend backend, void* user, float* output, + int64_t& bad_expert, std::string& error) { + bad_expert = -1; + error.clear(); + if (layers < 1 || layers > 512 || layer < 0 || layer >= layers || hidden < 1 || hidden > 16384 || experts < 1 || + experts > 65536 || tokens < 1 || tokens > 8 || routes < 1 || routes > 16 || + !input || !ids || !output || !backend || !user) { + error = "invalid KAR all-routed dispatch"; return false; + } + const int64_t entries = tokens * routes; + for (int64_t i = 0; i < tokens * hidden; ++i) + if (!std::isfinite(input[i])) { error = "non-finite KAR routed activation"; return false; } + for (int64_t i = 0; i < entries; ++i) { + if (ids[i] < 0 || ids[i] >= experts) { + bad_expert = ids[i]; error = "a routed expert id is out of range"; return false; + } + // Top-k never duplicates an expert within a token. Refuse an invalid + // group before the backend can partially stage or write its results. + for (int64_t j = i / routes * routes; j < i; ++j) + if (ids[j] == ids[i]) { + bad_expert = ids[i]; error = "duplicate KAR routed expert within a token"; return false; + } + } + std::array kind; + kind.fill(-1); + std::fill(output, output + entries * hidden, std::numeric_limits::quiet_NaN()); + if (!backend(user, layer, input, ids, tokens, routes, kind.data(), output, error)) { + if (error.empty()) error = "KAR all-routed backend failed"; + return false; + } + for (int64_t i = 0; i < entries; ++i) + if (kind[(size_t) i] != 3) { error = "KAR all-routed backend left an unhandled row"; return false; } + for (int64_t i = 0; i < entries * hidden; ++i) + if (!std::isfinite(output[i])) { error = "KAR all-routed backend returned a non-finite row"; return false; } + return true; +} + +// The actual early dispatcher is CPU-testable without CUDA or a native source. +// A failure preserves the failing layer and completed counters; later calls +// stay failed. Keep the error storage alive for ExpertDispatch::fail. +template +bool dispatch_experimental_routed_window(Dispatch& d, int64_t hidden, const float* input, + const int32_t* ids, int64_t tokens, int64_t routes, float* output) { + if (d.failed) return false; + static thread_local std::string error; + int64_t bad_expert = -1; + error.clear(); + const bool usage_ok = d.usage.empty() || (d.layers >= 0 && d.n_expert > 0 && + (uint64_t) d.layers < (uint64_t) d.usage.size() / (uint64_t) d.n_expert); + if (!usage_ok) error = "KAR all-routed usage table is too small"; + if (!usage_ok || !dispatch_experimental_all_routed(d.layers, d.experimental_layers, hidden, d.n_expert, + input, ids, tokens, routes, d.experimental_miss, d.experimental_miss_user, output, bad_expert, error)) { + d.failed = true; d.fail = error.c_str(); d.fail_layer = d.layers; d.fail_expert = bad_expert; + return false; + } + if (!d.usage.empty()) + for (int64_t i = 0; i < tokens * routes; ++i) + d.usage[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] += 1.0f; + d.cache_refused += tokens * routes; // completed KAR rows, never native hits + d.experts += tokens * routes; + ++d.layers; + return true; +} + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/expert_source.hpp b/engine/strata/include/strata/core/expert_source.hpp index e2669ebe..f7d73a21 100644 --- a/engine/strata/include/strata/core/expert_source.hpp +++ b/engine/strata/include/strata/core/expert_source.hpp @@ -217,6 +217,8 @@ struct ExpertDispatch { int64_t, int64_t, int32_t*, float*, std::string&); ExperimentalMiss experimental_miss = nullptr; void* experimental_miss_user = nullptr; + bool experimental_all_routed = false; ///< strict separate arm; no native source or cache fallback + int64_t experimental_layers = 0; ///< target archive layer bound, not the MTP draft layer strata::kernels::cpu::ExpertPool* pool = nullptr; ExpertSource* src = nullptr; RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts diff --git a/engine/strata/include/strata/core/verify.hpp b/engine/strata/include/strata/core/verify.hpp index 29b064fb..726c0293 100644 --- a/engine/strata/include/strata/core/verify.hpp +++ b/engine/strata/include/strata/core/verify.hpp @@ -44,6 +44,7 @@ using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, i int64_t layer); struct VerifyHits { + bool experimental_all_routed = false; ///< no native routed tier; mandatory host KAR callback const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1 const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena const uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob) diff --git a/engine/strata/include/strata/prefill/prefill.hpp b/engine/strata/include/strata/prefill/prefill.hpp index 55e21542..3c8543cb 100644 --- a/engine/strata/include/strata/prefill/prefill.hpp +++ b/engine/strata/include/strata/prefill/prefill.hpp @@ -66,6 +66,10 @@ public: experimental_experts_ = backend; experimental_user_ = user; } + /// Separate strict all-routed arm: omit native routed scratch/staging. + /// Configure before init; immutable across relayout and survives reset. + bool set_experimental_all_routed(ExperimentalExperts backend, void* user, std::string& err); + /// `host_res`: the static residency table (n_layers x n_expert, slot or -1) or null; `cache` its slots. /// `borrow`/`borrow_bytes`: device memory to carve every buffer from (the top slots of the expert cache, /// lent for the prompt and refilled after it); null = allocate normally. @@ -87,7 +91,8 @@ public: static void set_ring_override(int slots); /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). - static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); + static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool experimental_all_routed = false); /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest /// first, -1 for none) and is advanced to the last two of these. @@ -125,6 +130,7 @@ public: private: ExperimentalExperts experimental_experts_ = nullptr; void* experimental_user_ = nullptr; + bool experimental_all_routed_ = false; int64_t stage_lb_ = 0, stage_le_ = -1; Prefill* next_ = nullptr; const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) diff --git a/engine/strata/src/core/expert_source.cpp b/engine/strata/src/core/expert_source.cpp index 4d3cb759..b6e649e8 100644 --- a/engine/strata/src/core/expert_source.cpp +++ b/engine/strata/src/core/expert_source.cpp @@ -1,5 +1,6 @@ // src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. #include "strata/core/expert_source.hpp" +#include "strata/core/experimental_routed.hpp" #include "strata/core/remote_experts.hpp" #include "strata/kernels/cpu/expert_layout.hpp" #include "strata/artifact/gguf_reader.hpp" @@ -1615,6 +1616,16 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 float* out) { using namespace strata::kernels::cpu; if (d.failed) return; + // Must precede lookahead, source begin/prefetch, native planning and pool + // activation/job allocations. The all-routed arm has no native expert bank. + if (d.experimental_all_routed) { + const auto start = std::chrono::steady_clock::now(); + if (!dispatch_experimental_routed_window(d, H, x_f, ids, n_tok, k, out)) return; + d.ms_run += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + // Verifier::run publishes an empty native plan after this callback; + // all host rows cross to its existing combine, with router weights once. + return; + } if (n_tok < 1 || n_tok > MAXT) { d.failed = true; d.fail = "a verify window has more tokens than the multi-token expert kernel takes"; diff --git a/engine/strata/src/core/verify.cpp b/engine/strata/src/core/verify.cpp index 58f7594b..69a42d74 100644 --- a/engine/strata/src/core/verify.cpp +++ b/engine/strata/src/core/verify.cpp @@ -190,6 +190,11 @@ Verifier::~Verifier() { bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, const NativeHead* head, int max_t, std::string& err) { + if (hits.experimental_all_routed && (hits.d_res || hits.cache_base || hits.slot_off || hits.n_slots || hits.blob || + lb_ != 0 || (le_ >= 0 && le_ != g.n_layers) || hand_in_ || hand_out_)) { + err = "verify: all-routed mode requires one complete target stage and no native expert tier"; + return false; + } g_diag_verifier.store(this); diag_verify_fn().store(&diag_active_verifier); for (auto& slot : g_live) { @@ -226,7 +231,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens"; return false; } - if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) { + if (!hits.experimental_all_routed && (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0)) { err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " "--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU"; return false; @@ -324,15 +329,20 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& attn_scratch_ = b.take(T * (uint64_t) attn_scratch_floats_); tail_snap_ = b.take(nQ * TS); logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); - shared_ = b.take(T * N); parts_ = b.take(T * K * N); hit_out_ = b.take(T * K * N); - hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); + shared_ = b.take(T * N); parts_ = b.take(T * K * N); + if (!hits.experimental_all_routed) { + hit_out_ = b.take(T * K * N); + hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); + } plan_ = b.take(2 * ((uint64_t) plan_i32_ + 16)); - staging_ = b.take((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob); - hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); - nat_xq_ = b.take(T * (N / 32) * 36); - hit_scratch_ = b.take(std::max( - strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff), - strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff))); + if (!hits.experimental_all_routed) { + staging_ = b.take((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob); + hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); + nat_xq_ = b.take(T * (N / 32) * 36); + hit_scratch_ = b.take(std::max( + strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff), + strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff))); + } head_mixed_ = b.take(T * N); head_inj_ = b.take(HC); sh_bf16_ = b.take(T * N); sh_gate_ = b.take(T * (uint64_t) g.n_ff); sh_up_ = b.take(T * (uint64_t) g.n_ff); sh_g_ = b.take(T + 4); @@ -356,7 +366,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& real.base = (uint8_t*) arena_; carve(real); sink_.staging = (unsigned long long) staging_; - sink_.staging_cap = kStagingBlobs; + sink_.staging_cap = hits.experimental_all_routed ? 0 : kStagingBlobs; (void) TS; if (cudaStreamCreateWithFlags(©_, cudaStreamNonBlocking) != cudaSuccess) { err = "verify: copy stream create failed"; @@ -374,7 +384,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& // exact, but neutral on RIBPC 1-2 GPUs: off by default) { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); - device_plan_ = v != nullptr && std::atoi(v) != 0; + device_plan_ = !hits.experimental_all_routed && v != nullptr && std::atoi(v) != 0; } if (device_plan_) { bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess; @@ -751,7 +761,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { return false; } } - if (strata::kernels::cpu::expert_layout().native) + if (hits_.experimental_all_routed) { + // KAR consumes the original normed FP32 rows, not native routed activations. + } else if (strata::kernels::cpu::expert_layout().native) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); else quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); @@ -764,6 +776,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { const int tb = tb_[grp], te = te_[grp], n = te - tb; const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; + if (hits_.experimental_all_routed) { + // Every row belongs to the strict host backend. Waiting for the + // normal completion flag preserves failure/release behavior. + wait_flag_ge(m_flag_, ring, cs); + copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, + (int64_t) n * K * N, cs); + } else { int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs); @@ -823,6 +842,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs); } moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs); + } if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows try { native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); @@ -1054,6 +1074,9 @@ bool Verifier::capture_commit(std::string& err) { bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err) { using namespace strata::kernels; + if (hits_.experimental_all_routed && (!pool || !user)) { + err = "verify: all-routed mode requires its host expert callback"; return false; + } const OnDevice on_device(device_); if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } @@ -1279,8 +1302,9 @@ void Verifier::set_plan_slot(int grp) { sink_.start2 = base + ptr_off + 4 * cap; const int G = groups_[last_t_] > 0 ? groups_[last_t_] : 1; const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; - sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob); - sink_.staging_cap = per; + sink_.staging = hits_.experimental_all_routed ? 0 : + (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob); + sink_.staging_cap = hits_.experimental_all_routed ? 0 : per; } // Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. diff --git a/engine/strata/src/prefill/prefill.cpp b/engine/strata/src/prefill/prefill.cpp index b1a6ba3d..749e2c59 100644 --- a/engine/strata/src/prefill/prefill.cpp +++ b/engine/strata/src/prefill/prefill.cpp @@ -290,6 +290,9 @@ struct Stager { }; struct Prefill::Impl { + bool experimental_all_routed = false; + ExperimentalExperts routed_backend = nullptr; + void* routed_user = nullptr; const core::WeightTable* wt = nullptr; const core::ModelGeometry* g = nullptr; core::SessionState* ss = nullptr; @@ -411,6 +414,17 @@ strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, co Prefill::Prefill() : impl_(new Impl) {} Prefill::~Prefill() { release(); } +bool Prefill::set_experimental_all_routed(ExperimentalExperts backend, void* user, std::string& err) { + if (impl_->g != nullptr || !backend || !user) { + err = "prefill: all-routed backend must be configured before init with an owner"; + return false; + } + experimental_all_routed_ = true; + experimental_experts_ = backend; + experimental_user_ = user; + return true; +} + void Prefill::reset() { release(); impl_.reset(new Impl); @@ -495,17 +509,17 @@ const MmqPlan& mmq_plan() { }(); return plan; } -uint64_t moe_set_bytes(size_t T, int64_t n_expert) { +uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool native_routed = true) { const MmqPlan& mp = mmq_plan(); Alloc a; a.count_only = true; bool ok = true; a.take(T * n_expert, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); - if (mp.fallback) a.take(T * K * N, ok); - a.take(T * K * 1280, ok); - if (mp.fallback) a.take(T * K * 640, ok); + if (native_routed && mp.fallback) a.take(T * K * N, ok); + if (native_routed) a.take(T * K * 1280, ok); + if (native_routed && mp.fallback) a.take(T * K * 640, ok); a.take(T * K * N, ok); a.take(T * 640, ok); a.take(T * 640, ok); a.take(T * 640, ok); a.take(T * N, ok); a.take(T, ok); - if (mp.any) { + if (native_routed && mp.any) { a.take(mmq::q8_bytes((int64_t) (T * K), N), ok); a.take(T * K * 640, ok); a.take(mmq::q8_bytes((int64_t) (T * K), 640), ok); @@ -518,6 +532,12 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, void* stream, std::string& err, void* borrow, uint64_t borrow_bytes) { Impl& m = *impl_; + if (experimental_all_routed_ && (!experimental_experts_ || !experimental_user_ || src || host_res || + (cache && cache->slots() > 0) || borrow || borrow_bytes)) { + err = "prefill: all-routed mode requires its backend and no native source/cache/borrow"; return false; + } + m.experimental_all_routed = experimental_all_routed_; + m.routed_backend = experimental_experts_; m.routed_user = experimental_user_; m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) { @@ -548,11 +568,11 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.borrowed = borrow != nullptr; bool ok = true; // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table - for (int i = 0; i < RING_MAX; ++i) { + for (int i = 0; !m.experimental_all_routed && i < RING_MAX; ++i) { if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false; if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false; } - if (!m.stager) { + if (!m.experimental_all_routed && !m.stager) { m.stager = std::make_unique(); const int hw = (int) std::thread::hardware_concurrency(); const char* stv = std::getenv("STRATA_STAGER_THREADS"); // D-5: the host copy threads of unpinned blobs @@ -569,7 +589,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co m.steps_host.resize(T * strata::kernels::kStepCount); m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); { - const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); + const size_t need = 3 * T * K + (m.experimental_all_routed ? 0 : + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2))); const char* gc = std::getenv("STRATA_GROUP_COPY"); if (m.grp_n < need && !(gc && gc[0] == '1')) { if (m.grp_host) cudaFreeHost(m.grp_host); @@ -653,7 +674,7 @@ bool Prefill::carve(size_t T, void* alloc) { { // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch, - m.attn_batch, s), moe_set_bytes(T, m.g->n_expert)}); + m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, !m.experimental_all_routed)}); uint8_t* base = o.take((size_t) region, ok); m.region = base; m.region_bytes = region; @@ -675,21 +696,21 @@ bool Prefill::carve(size_t T, void* alloc) { m.logits = c.take(T * m.g->n_expert, ok); m.w = c.take(T * K, ok); m.ids = c.take(T * K, ok); m.slot_dev = c.take(T * K, ok); m.src_dev = c.take(T * K, ok); const MmqPlan& mp = mmq_plan(); - m.Xs = mp.fallback ? c.take(T * K * N, ok) : nullptr; - m.GU = c.take(T * K * 1280, ok); - m.Hh = mp.fallback ? c.take(T * K * 640, ok) : nullptr; + m.Xs = !m.experimental_all_routed && mp.fallback ? c.take(T * K * N, ok) : nullptr; + m.GU = !m.experimental_all_routed ? c.take(T * K * 1280, ok) : nullptr; + m.Hh = !m.experimental_all_routed && mp.fallback ? c.take(T * K * 640, ok) : nullptr; m.Dm = c.take(T * K * N, ok); m.sgate = c.take(T * 640, ok); m.sup = c.take(T * 640, ok); m.sh_h = c.take(T * 640, ok); m.shared = c.take(T * N, ok); m.sg = c.take(T, ok); - if (mp.any) { + if (!m.experimental_all_routed && mp.any) { m.Xq = c.take(mmq::q8_bytes((int64_t) (T * K), N), ok); m.H = c.take(T * K * 640, ok); m.Hq = c.take(mmq::q8_bytes((int64_t) (T * K), 640), ok); } if (base == nullptr) ok = false; } - for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take(1280 * 2560, ok); m.dq_d[i] = o.take(2560 * 640, ok); } - if (mmq_plan().any) { + for (int i = 0; !m.experimental_all_routed && i < DQ; ++i) { m.dq_gu[i] = o.take(1280 * 2560, ok); m.dq_d[i] = o.take(2560 * 640, ok); } + if (!m.experimental_all_routed && mmq_plan().any) { const MmqPlan& mp = mmq_plan(); m.ids_identity = o.take(T * K, ok); m.bounds_dev = o.take((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok); @@ -699,7 +720,7 @@ bool Prefill::carve(size_t T, void* alloc) { // lends them - a write now would corrupt a resident expert) if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); } - m.ring = ring_slots(T); + m.ring = m.experimental_all_routed ? 0 : ring_slots(T); for (int i = 0; i < m.ring; ++i) { m.stage_dev[i] = o.take((size_t) MAXBLOB(), ok); m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for @@ -888,7 +909,8 @@ void Prefill::set_pinned_share(double share) { g_pinned_share = share; } void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; } double Prefill::pinned_share() { return g_pinned_share; } -uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { +uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, + bool experimental_all_routed) { // the same allocation sequence as `init`, counted const size_t T = (size_t) chunk; bool ok = true; @@ -908,16 +930,16 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), - moe_set_bytes(T, g.n_expert)}), ok); - for (int i = 0; i < DQ; ++i) { o.take(1280 * 2560, ok); o.take(2560 * 640, ok); } - if (mmq_plan().any) { + moe_set_bytes(T, g.n_expert, !experimental_all_routed)}), ok); + for (int i = 0; !experimental_all_routed && i < DQ; ++i) { o.take(1280 * 2560, ok); o.take(2560 * 640, ok); } + if (!experimental_all_routed && mmq_plan().any) { const MmqPlan& mp = mmq_plan(); o.take(T * K, ok); o.take((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok); o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); } - for (int i = 0; i < ring_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); + for (int i = 0; !experimental_all_routed && i < ring_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); f(T * N); f((size_t) strata::kernels::NG_HC_DIM); strata::kernels::KvHostPools stage; @@ -1001,6 +1023,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e err = "prefill: missing experimental expert backend owner"; return false; } Impl& m = *impl_; + if (m.experimental_all_routed != experimental_all_routed_ || + (m.experimental_all_routed && (m.routed_backend != experimental_experts_ || m.routed_user != experimental_user_))) { + err = "prefill: all-routed allocation mode/backend changed after init"; return false; + } const core::OnDevice on_device(m.device); const core::ModelGeometry& g = *m.g; core::SessionState& ss = *m.ss; @@ -2021,7 +2047,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e return false; } stats_.ms_total += ms_since(t_start); - if (experimental_experts_) + if (m.experimental_all_routed) + std::fprintf(stderr, "strata prefill: experimental KAR routed rows=%llu; target native routed storage omitted; quality not qualified\n", + (unsigned long long) (stats_.experimental_expert_rows - experimental_before)); + else if (experimental_experts_) std::fprintf(stderr, "strata prefill: experimental KAR routed rows=%llu; native cache retained; quality not qualified\n", (unsigned long long) (stats_.experimental_expert_rows - experimental_before)); if (pt.on) { diff --git a/engine/strata/src/program/generate.cpp b/engine/strata/src/program/generate.cpp index 6f3abf00..596e5bc5 100644 --- a/engine/strata/src/program/generate.cpp +++ b/engine/strata/src/program/generate.cpp @@ -20,6 +20,7 @@ #include "strata/core/conversation_memory.hpp" #include "strata/core/coupled_draft.hpp" #include "strata/core/expert_source.hpp" +#include "strata/core/experimental_routed.hpp" #if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) #include "kar_expert_miss.hpp" #endif @@ -1286,6 +1287,39 @@ int main(int argc, char** argv) { } } } + // Strict all-routed admission before device probing, contexts or native + // resource setup. Native layout/geometry is confirmed after metadata load. + const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); + bool kar_all_routed = false, kar_prefill = false; + std::string kar_option_error; + if (!strata::core::parse_experimental_all_routed_flag(std::getenv("STRATA_NEXT_KAR_ALL_ROUTED"), kar_all_routed, kar_option_error)) { + std::fprintf(stderr, "strata generate: %s\n", kar_option_error.c_str()); return 2; + } + if (kar_all_routed && !strata::prefill::parse_experimental_prefill_flag(std::getenv("STRATA_NEXT_KAR_PREFILL"), kar_prefill, kar_option_error)) { + std::fprintf(stderr, "strata generate: %s\n", kar_option_error.c_str()); return 2; + } + if (kar_all_routed) { + strata::core::ExperimentalRoutedProfile p; +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + p.built = true; +#endif + p.native_pack = !o.native_preset.empty(); p.prefill = kar_prefill; p.archive = kar_expert_archive; + p.level = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); + p.chunk = o.prefill_chunk; p.automatic_chunk = o.prefill_auto; p.window = o.spec; + p.no_pool = o.no_pool; p.no_capture = o.no_capture || o.graph_only || o.gpu_only_full || o.gpu_stages; + p.multi_device = !o.layer_split.empty() || !o.split_device.empty() || + std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), [](int n) { return n != 0; }); + p.native_bank_option = o.mmap_experts || o.resident_cpu_experts || !o.shared_expert_arena.empty() || + o.pcie_frac != 0 || o.expert_cache_per_layer || o.expert_cache_cpu_order; + p.native_cache = o.expert_cache; p.native_profile = !o.expert_profile.empty(); + p.adaptive_cache = o.adapt_every > 0 && o.adapt_swaps > 0; + const char* device_plan = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); + p.device_plan = device_plan && std::strcmp(device_plan, "0") != 0; + if (!strata::core::validate_experimental_routed_profile(p, kar_option_error)) { + std::fprintf(stderr, "strata generate: %s\n", kar_option_error.c_str()); return 2; + } + } + strata::core::set_coupled_draft(o.coupled_draft); if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); @@ -1748,6 +1782,9 @@ int main(int argc, char** argv) { } } const bool native_pack = strata::kernels::cpu::expert_layout().native; + if (kar_all_routed && !native_pack) { + std::fprintf(stderr, "strata generate: KAR all-routed requires a native expert layout\n"); return 2; + } // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). @@ -1894,8 +1931,6 @@ int main(int argc, char** argv) { rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); } } - const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); - bool kar_prefill = false; if (!strata::prefill::parse_experimental_prefill_flag(std::getenv("STRATA_NEXT_KAR_PREFILL"), kar_prefill, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 2; } @@ -1927,7 +1962,10 @@ int main(int argc, char** argv) { // Native resident hits are the baseline. Route all otherwise CPU/PCIe // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. o.pcie_frac = 0; - if (kar_prefill) + if (kar_all_routed) + std::fprintf(stderr, "strata generate: experimental KAR all-routed ON: target native routed RAM/VRAM bank omitted; " + "MTP/shared/dense/KV retained; quality not qualified\n"); + else if (kar_prefill) std::fprintf(stderr, "strata generate: experimental KAR prefill ON: all routed experts; native cache retained; quality not qualified\n"); } #else @@ -2362,7 +2400,7 @@ int main(int argc, char** argv) { // An explicit number truncates the ranked list ("what would 2,000 slots give" without rebuilding the // file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks // every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto. - if (o.expert_cache == 0) o.expert_cache = -1; + if (o.expert_cache == 0 && !kar_all_routed) o.expert_cache = -1; std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n", o.expert_profile.c_str(), profile.size(), (long long) pslots); } @@ -2684,7 +2722,11 @@ int main(int argc, char** argv) { } strata::core::ArenaExpertSource arena_src; strata::core::ExpertSource* srcp = nullptr; - if (o.mmap_experts) { + if (kar_all_routed) { + // No target routed IQ bank or mmap fallback. Null is intentional: the + // strict callbacks must bypass every native source consumer. + std::fprintf(stderr, "strata generate: target native routed expert source omitted (KAR all-routed)\n"); + } else if (o.mmap_experts) { // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose @@ -3135,6 +3177,8 @@ int main(int argc, char** argv) { if (kar_expert_archive != nullptr) { drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; drive.d.experimental_miss_user = &kar_expert_miss; + drive.d.experimental_all_routed = kar_all_routed; + drive.d.experimental_layers = g.n_layers; } #endif for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) @@ -3835,7 +3879,7 @@ int main(int argc, char** argv) { strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0); } auto lend_slots = [&](int64_t c) -> int64_t { - const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, c); + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, c, kar_all_routed); const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need` @@ -3959,7 +4003,11 @@ int main(int argc, char** argv) { } strata::prefill::Prefill sp; #if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) - if (kar_prefill) sp.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); + if (kar_all_routed) { + if (!sp.set_experimental_all_routed(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 2; + } + } else if (kar_prefill) sp.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); #endif void* borrow = nullptr; uint64_t borrow_bytes = 0; @@ -3986,7 +4034,7 @@ int main(int argc, char** argv) { std::vector> lent; }; auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t { - const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, c); + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, c, kar_all_routed); strata::core::ExpertCache& xc = *p.cache; if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need` int64_t k = 0; @@ -4114,7 +4162,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(p.dev); size_t fb = 0, tb = 0; if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } - const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk); + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk, kar_all_routed); if ((uint64_t) fb >= need + (3ull << 29)) { std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, @@ -4183,7 +4231,7 @@ int main(int argc, char** argv) { } } if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); - if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + if (!sp.init(wt, g, ss, srcp, &xcache, host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) return err.find("do not fit") != std::string::npos ? 2 : 1; return 0; }; @@ -4201,7 +4249,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(dev); size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); - const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c); + const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c, kar_all_routed); if (need + kHeadroom > (int64_t) fb) { dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb; return false; @@ -4317,6 +4365,7 @@ int main(int argc, char** argv) { } strata::core::Verifier ver; strata::core::VerifyHits vh; + vh.experimental_all_routed = kar_all_routed; vh.d_res = thits.d_res; vh.cache_base = thits.cache_base; vh.blob = thits.blob; @@ -5843,7 +5892,11 @@ int main(int argc, char** argv) { int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used) strata::prefill::Prefill prefill; #if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) - if (kar_prefill) prefill.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); + if (kar_all_routed) { + if (!prefill.set_experimental_all_routed(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 2; + } + } else if (kar_prefill) prefill.set_experimental_experts(&strata::kar::ExpertMiss::dispatch, &kar_expert_miss); #endif double prefill_batched_ms = 0; std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb"); @@ -6169,7 +6222,7 @@ int main(int argc, char** argv) { // round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted. const bool ended = o.stop_eos && !produced.empty() && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end(); - if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) { + if ((spec_pos > 0 || kar_all_routed) && (int64_t) produced.size() < o.max_new && !ended) { std::vector oracle; if (!o.spec_oracle.empty()) { std::ifstream in(o.spec_oracle); @@ -6180,7 +6233,7 @@ int main(int argc, char** argv) { return 2; } } - if (thits.d_res == nullptr) { + if (thits.d_res == nullptr && !kar_all_routed) { std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, " "--expert-cache and the token graph)\n"); return 2; @@ -6188,6 +6241,7 @@ int main(int argc, char** argv) { mem_mark("the head and the prompt path"); strata::core::Verifier ver; strata::core::VerifyHits vh; + vh.experimental_all_routed = kar_all_routed; vh.d_res = thits.d_res; vh.cache_base = thits.cache_base; vh.blob = thits.blob; @@ -6619,7 +6673,7 @@ int main(int argc, char** argv) { std::printf("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n", " pool phases", wp / per, dr / per, rp / per); } - std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads()); + std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) (srcp ? srcp->reads() : 0)); for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) std::printf(" CUDA%d experts %lld routed entries computed\n", r + 1, (long long) remote_experts[(size_t) r].computed()); diff --git a/scripts/test-kar-all-routed-contract.sh b/scripts/test-kar-all-routed-contract.sh new file mode 100755 index 00000000..5bb9b9db --- /dev/null +++ b/scripts/test-kar-all-routed-contract.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +build_dir="$(mktemp -d "${TMPDIR:-/tmp}/kar-all-routed-contract.XXXXXX")" +trap 'rm -rf "$build_dir"' EXIT +"${CXX:-c++}" -std=c++17 -Wall -Wextra -Werror -pedantic \ + -fsanitize=address,undefined -fno-omit-frame-pointer \ + -I"$repo_root/engine/strata/include" \ + "$repo_root/tests/kar-all-routed-contract.cpp" -o "$build_dir/kar-all-routed-contract" +if [[ "$(uname -s)" == Darwin ]]; then + ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-all-routed-contract" +else + ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=halt_on_error=1 "$build_dir/kar-all-routed-contract" +fi diff --git a/tests/kar-all-routed-contract.cpp b/tests/kar-all-routed-contract.cpp new file mode 100644 index 00000000..31f4d2d1 --- /dev/null +++ b/tests/kar-all-routed-contract.cpp @@ -0,0 +1,148 @@ +#include "strata/core/experimental_routed.hpp" +#include +#include +#include + +using namespace strata::core; +struct Backend { int calls = 0, mode = 0; }; +struct Dispatch { + bool failed = false; + const char* fail = nullptr; + int64_t layers = 2, experimental_layers = 4, n_expert = 16; + int64_t fail_layer = -1, fail_expert = -1, cache_refused = 5, experts = 10; + int64_t cache_hits = 7, multi_entries = 0, multi_misses = 0; + // Null native handles are intentional, matching the strict runtime arm. + void *src = nullptr, *pool = nullptr, *plan = nullptr; + ExperimentalRoutedBackend experimental_miss = nullptr; + void* experimental_miss_user = nullptr; + std::vector usage = std::vector(4 * 16, 0); +}; +// Synthetic two-coordinate experts: [2*x0+e, 3*x1-e]. The oracle below +// independently combines these linear expert matrices with non-unit weights. +bool backend(void* user, int64_t layer, const float* x, const int32_t* ids, + int64_t tokens, int64_t routes, int32_t* kind, float* y, std::string& error) { + auto& b = *static_cast(user); + ++b.calls; + assert(layer == 2); + if (b.mode == 1) { error = "synthetic stage/run/finish fault"; return false; } + if (b.mode == 2) return false; // empty errors still become actionable + for (int64_t t = 0; t < tokens; ++t) + for (int64_t k = 0; k < routes; ++k) { + const auto i = t * routes + k; + assert(kind[i] == -1); // Native cache hits must never be pre-owned. + kind[i] = 3; + y[2 * i] = 2 * x[2 * t] + ids[i]; + y[2 * i + 1] = 3 * x[2 * t + 1] - ids[i]; + } + if (b.mode == 3) kind[tokens * routes - 1] = 0; // Native hit is forbidden. + if (b.mode == 4) kind[0] = -1; + if (b.mode == 5) y[0] = std::numeric_limits::infinity(); + if (b.mode == 6) y[1] = std::numeric_limits::quiet_NaN(); + return true; +} +int main() { + bool enabled = true; + std::string error; + assert(parse_experimental_all_routed_flag(nullptr, enabled, error) && !enabled); + assert(parse_experimental_all_routed_flag("0", enabled, error) && !enabled); + assert(parse_experimental_all_routed_flag("1", enabled, error) && enabled); + for (const auto* bad : {"", "01", "true", "2", " 1", "1 "}) + assert(!parse_experimental_all_routed_flag(bad, enabled, error)); + ExperimentalRoutedProfile valid; + valid.built = valid.native_pack = valid.prefill = true; + valid.archive = "synthetic-unused.kar"; valid.level = "2"; valid.chunk = 32; valid.window = 4; + assert(validate_experimental_routed_profile(valid, error)); + auto reject = [&](auto edit) { + auto p = valid; edit(p); + assert(!validate_experimental_routed_profile(p, error) && !error.empty()); + }; + for (auto member : {&ExperimentalRoutedProfile::built, &ExperimentalRoutedProfile::native_pack, + &ExperimentalRoutedProfile::prefill}) reject([&](auto& p) { p.*member = false; }); + for (auto member : {&ExperimentalRoutedProfile::no_pool, &ExperimentalRoutedProfile::no_capture, + &ExperimentalRoutedProfile::multi_device, &ExperimentalRoutedProfile::native_bank_option, + &ExperimentalRoutedProfile::adaptive_cache, &ExperimentalRoutedProfile::device_plan, + &ExperimentalRoutedProfile::automatic_chunk, &ExperimentalRoutedProfile::native_profile}) + reject([&](auto& p) { p.*member = true; }); + reject([](auto& p) { p.archive = nullptr; }); + reject([](auto& p) { p.archive = ""; }); + reject([](auto& p) { p.level = nullptr; }); + for (const char* level : {"", "0", "9", "02", " 2", "2 "}) + reject([&](auto& p) { p.level = level; }); + reject([](auto& p) { p.chunk = 0; }); + for (int window : {0, 1, 9}) reject([&](auto& p) { p.window = window; }); + for (int cache : {-1, 1, 8000}) reject([&](auto& p) { p.native_cache = cache; }); + + constexpr int tokens = 8, routes = 16, hidden = 2; + std::array