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"; +}