WIP: STRA-10: bounded compressed KAR expert cache #2

Closed
admin wants to merge 13 commits from codex/stra10-bounded-kar-cache-gitea into main
28 changed files with 1335 additions and 85 deletions
+115
View File
@@ -0,0 +1,115 @@
name: KAR CUDA compile (GPU hidden)
on:
workflow_dispatch:
pull_request:
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'
- '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'
- '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
container:
image: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
env:
NVIDIA_VISIBLE_DEVICES: void
CUDA_VISIBLE_DEVICES: ''
steps:
- 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~24.04.1 \
git=1:2.43.0-1ubuntu7.3
- 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 and native engine in pinned GPU-hidden container
shell: bash
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
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~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
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
export CC=gcc-13 CXX=g++-13
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$"
# 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
+19
View File
@@ -0,0 +1,19 @@
{
"schema_version": 1,
"platform": "linux/amd64",
"builder_image": "ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b",
"builder_glibc": "2.39",
"apt_packages": {
"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",
"cuda_architecture": "120",
"compile_jobs": 1
}
+68 -1
View File
@@ -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,65 @@ 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.
## 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.
@@ -0,0 +1,120 @@
#pragma once
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
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<int32_t, 128> kind;
kind.fill(-1);
std::fill(output, output + entries * hidden, std::numeric_limits<float>::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<class Dispatch>
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
@@ -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
@@ -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)
@@ -0,0 +1,85 @@
#pragma once
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
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<class Read, class Write>
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<int32_t>::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<float> input((size_t) (batch_limit * hidden));
std::vector<float> output(input.size());
std::array<int32_t, batch_limit> 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<float>::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
@@ -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,17 @@ 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;
}
/// 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.
@@ -78,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.
@@ -114,6 +128,9 @@ 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)
+11
View File
@@ -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<double, std::milli>(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";
+38 -14
View File
@@ -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<float>(T * (uint64_t) attn_scratch_floats_);
tail_snap_ = b.take<float>(nQ * TS);
logits_ = b.take<float>(T * (uint64_t) g.n_expert); w_ = b.take<float>(T * K); ids_ = b.take<int32_t>(T * K);
shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N); hit_out_ = b.take<float>(T * K * N);
hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N);
if (!hits.experimental_all_routed) {
hit_out_ = b.take<float>(T * K * N);
hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
}
plan_ = b.take<int32_t>(2 * ((uint64_t) plan_i32_ + 16));
staging_ = b.take<uint8_t>((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob);
hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
nat_xq_ = b.take<uint8_t>(T * (N / 32) * 36);
hit_scratch_ = b.take<uint8_t>(std::max<uint64_t>(
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<uint8_t>((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob);
hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
nat_xq_ = b.take<uint8_t>(T * (N / 32) * 36);
hit_scratch_ = b.take<uint8_t>(std::max<uint64_t>(
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<float>(T * N); head_inj_ = b.take<float>(HC);
sh_bf16_ = b.take<uint16_t>(T * N); sh_gate_ = b.take<float>(T * (uint64_t) g.n_ff);
sh_up_ = b.take<float>(T * (uint64_t) g.n_ff); sh_g_ = b.take<float>(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(&copy_, 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.
+97 -26
View File
@@ -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<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
a.take<int32_t>(T * K, ok);
if (mp.fallback) a.take<uint16_t>(T * K * N, ok);
a.take<float>(T * K * 1280, ok);
if (mp.fallback) a.take<uint16_t>(T * K * 640, ok);
if (native_routed && mp.fallback) a.take<uint16_t>(T * K * N, ok);
if (native_routed) a.take<float>(T * K * 1280, ok);
if (native_routed && mp.fallback) a.take<uint16_t>(T * K * 640, ok);
a.take<float>(T * K * N, ok); a.take<float>(T * 640, ok);
a.take<float>(T * 640, ok); a.take<uint16_t>(T * 640, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
if (mp.any) {
if (native_routed && mp.any) {
a.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), N), ok);
a.take<float>(T * K * 640, ok);
a.take<uint8_t>(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<Stager>();
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<uint8_t>((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<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
const MmqPlan& mp = mmq_plan();
m.Xs = mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
m.GU = c.take<float>(T * K * 1280, ok);
m.Hh = mp.fallback ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
m.Xs = !m.experimental_all_routed && mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
m.GU = !m.experimental_all_routed ? c.take<float>(T * K * 1280, ok) : nullptr;
m.Hh = !m.experimental_all_routed && mp.fallback ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
m.Dm = c.take<float>(T * K * N, ok);
m.sgate = c.take<float>(T * 640, ok); m.sup = c.take<float>(T * 640, ok); m.sh_h = c.take<uint16_t>(T * 640, ok);
m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
if (mp.any) {
if (!m.experimental_all_routed && mp.any) {
m.Xq = c.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), N), ok);
m.H = c.take<float>(T * K * 640, ok);
m.Hq = c.take<uint8_t>(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<uint16_t>(1280 * 2560, ok); m.dq_d[i] = o.take<uint16_t>(2560 * 640, ok); }
if (mmq_plan().any) {
for (int i = 0; !m.experimental_all_routed && i < DQ; ++i) { m.dq_gu[i] = o.take<uint16_t>(1280 * 2560, ok); m.dq_d[i] = o.take<uint16_t>(2560 * 640, ok); }
if (!m.experimental_all_routed && mmq_plan().any) {
const MmqPlan& mp = mmq_plan();
m.ids_identity = o.take<int32_t>(T * K, ok);
m.bounds_dev = o.take<int32_t>((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<mmq::Context>();
}
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<uint8_t>((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<uint8_t>((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<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(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<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(2560 * 640, ok); }
if (!experimental_all_routed && mmq_plan().any) {
const MmqPlan& mp = mmq_plan();
o.take<int32_t>(T * K, ok);
o.take<int32_t>((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok);
o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
}
for (int i = 0; i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
for (int i = 0; !experimental_all_routed && i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
f(T * N);
f((size_t) strata::kernels::NG_HC_DIM);
strata::kernels::KvHostPools stage;
@@ -997,11 +1019,19 @@ 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_;
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;
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 +1198,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<StreamEntry> seq;
std::vector<size_t> seq_start;
@@ -1655,13 +1687,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<int32_t> 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 +1914,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 +1927,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 +2047,12 @@ 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 (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) {
pt.fold();
double total = 0.0;
+82 -11
View File
@@ -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,7 +1931,14 @@ 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");
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 +1962,11 @@ 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_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
if (kar_expert_archive != nullptr) {
@@ -2351,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);
}
@@ -2673,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
@@ -3124,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)
@@ -3824,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`
@@ -3947,6 +4002,13 @@ int main(int argc, char** argv) {
return 2;
}
strata::prefill::Prefill sp;
#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS)
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;
int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk)
@@ -3972,7 +4034,7 @@ int main(int argc, char** argv) {
std::vector<std::pair<int32_t, int32_t>> 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;
@@ -4100,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,
@@ -4169,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;
};
@@ -4187,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;
@@ -4303,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;
@@ -5828,6 +5891,13 @@ 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_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");
std::vector<float> final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0);
@@ -6152,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<int64_t> oracle;
if (!o.spec_oracle.empty()) {
std::ifstream in(o.spec_oracle);
@@ -6163,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;
@@ -6171,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;
@@ -6602,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());
+5
View File
@@ -56,6 +56,11 @@ 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)
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)
target_compile_features(strata-kar-expert-test PRIVATE cxx_std_20)
target_link_libraries(strata-kar-expert-test PRIVATE strata_kar_expert)
+54
View File
@@ -200,3 +200,57 @@ 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 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.
+7 -3
View File
@@ -1,6 +1,7 @@
#pragma once
#include "libkar.h"
#include "kar_expert_cache.hpp"
#include <cstddef>
#include <cstdint>
#include <memory>
@@ -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> impl_;
+114
View File
@@ -0,0 +1,114 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <vector>
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<ExpertTensorSlice,3> 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;i<entries_.size();++i) if (entries_[i].valid && entries_[i].key==key) {
entries_[i].last_used=next_tick(); ++stats_.hits; slot=i; return true;
}
++stats_.misses; return false;
}
bool begin_upload(size_t& slot) {
if (failed_ || pending_ || uploading_ || entries_.empty()) return false;
slot=0;
for (size_t i=0;i<entries_.size();++i) {
if (!entries_[i].valid) { slot=i; break; }
if (entries_[i].last_used < entries_[slot].last_used) slot=i;
}
replacing_=entries_[slot].valid;
entries_[slot].valid=false; // overwritten bytes can no longer name the old key
uploading_=true; uploading_slot_=slot; return true;
}
bool publish_upload(size_t slot, const ExpertCacheKey& key) {
if (!uploading_ || slot!=uploading_slot_ || failed_) return false;
entries_[slot].key=key; entries_[slot].valid=true;
entries_[slot].last_used=next_tick(); ++stats_.uploads;
if (replacing_) ++stats_.evictions;
uploading_=false; replacing_=false; return true;
}
void fail_upload() { if (uploading_) entries_[uploading_slot_].valid=false; uploading_=false; replacing_=false; failed_=true; }
bool begin_run() { if (failed_ || pending_ || uploading_) return false; pending_=true; return true; }
bool finish_run() { if (!pending_ || failed_) return false; pending_=false; return true; }
void fail() { failed_=true; pending_=false; uploading_=false; replacing_=false; }
private:
struct Entry { ExpertCacheKey key{}; uint64_t last_used=0; bool valid=false; };
uint64_t next_tick() {
// Renormalize before wrap; relative ordering remains unchanged.
if (clock_==UINT64_MAX) {
uint64_t min=UINT64_MAX;
for (const auto& e:entries_) if (e.valid && e.last_used<min) min=e.last_used;
if (min!=UINT64_MAX) for (auto& e:entries_) if (e.valid) e.last_used-=min;
clock_=0;
for (const auto& e:entries_) if (e.valid && e.last_used>clock_) clock_=e.last_used;
}
return ++clock_;
}
std::vector<Entry> entries_;
ExpertCacheStats stats_{};
uint64_t clock_=0;
size_t uploading_slot_=0;
bool pending_=false, uploading_=false, replacing_=false, failed_=false;
};
} // namespace strata::kar
+4 -3
View File
@@ -6,15 +6,16 @@
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();
~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);
+59 -19
View File
@@ -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<uint8_t*> 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<void*>(compressed), static_cast<void*>(weights),
static_cast<void*>(x), static_cast<void*>(gate),
for (auto* p : compressed_slots) if (p) cudaFree(p);
for (void* p : {static_cast<void*>(weights), static_cast<void*>(x), static_cast<void*>(gate),
static_cast<void*>(up), static_cast<void*>(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<<level)*2;
p->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<size_t>(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<uint64_t>(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<size_t>(slot_count));
for (uint64_t i=0;i<slot_count;++i) {
uint8_t* slot=nullptr;
if (!check(cudaMalloc(&slot,p->slot_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<uintptr_t>(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<uint64_t(tokens)*p.hidden;++i)
if (!std::isfinite(input[i])) { error="expert input contains nonfinite values"; return false; }
std::memcpy(p.host_x,input,uint64_t(tokens)*p.hidden*4); p.tokens=tokens;
if (!p.cache.begin_run()) { error="expert cache is not available for run"; return false; }
p.pending=true;
if (!check(cudaMemcpyAsync(p.x,p.host_x,uint64_t(tokens)*p.hidden*4,cudaMemcpyHostToDevice,p.stream),"expert input upload",error)) {
p.failed=true; return false;
p.cache.fail(); p.failed=true; return false;
}
for (uint32_t role=0;role<3;++role) {
decode<<<(p.hidden*p.ff+255)/256,256,0,p.stream>>>(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<<<dim3(rows,tokens),256,0,p.stream>>>(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<uint64_t(p.tokens)*p.hidden;++i)
if (!std::isfinite(p.host_out[i])) { p.failed=true; error="expert produced nonfinite output"; return false; }
if (!std::isfinite(p.host_out[i])) { p.cache.fail(); p.failed=true; error="expert produced nonfinite output"; return false; }
std::memcpy(output,p.host_out,uint64_t(p.tokens)*p.hidden*4); return true;
}
bool ResidentExpert::inspect_matrix(uint32_t role, float* output, std::string& error) {
@@ -202,12 +242,12 @@ bool ResidentExpert::inspect_matrix(uint32_t role, float* output, std::string& e
error="expert matrix inspection requires idle resident state"; return false;
}
auto& p=*impl_;
decode<<<(p.hidden*p.ff+255)/256,256,0,p.stream>>>(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;
}
+82
View File
@@ -0,0 +1,82 @@
#include "kar_expert_cache.hpp"
#include <array>
#include <cstdio>
#include <stdexcept>
#include <vector>
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<ReferenceEntry,slots> reference{};
uint64_t clock=0, hits=0, misses=0, uploads=0, evictions=0;
uint32_t random=0x5eed1234u;
for(size_t n=0;n<operations;++n) {
random=random*1664525u+1013904223u;
const uint32_t expert=(random>>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<slots;++i) if(reference[i].valid && reference[i].key==request) { expected=i; break; }
size_t got=slots;
if(expected<slots) {
require(actual.lookup(request,got) && got==expected,"LRU hit differs from independent reference");
reference[expected].age=++clock; ++hits;
} else {
require(!actual.lookup(request,got),"LRU unexpected hit against independent reference"); ++misses;
size_t victim=slots;
for(size_t i=0;i<slots;++i) if(!reference[i].valid) { victim=i; break; }
if(victim==slots) {
victim=0;
for(size_t i=1;i<slots;++i) if(reference[i].age<reference[victim].age) victim=i;
++evictions;
}
require(actual.begin_upload(got) && got==victim,"LRU victim differs from independent reference");
reference[victim].valid=false;
require(actual.publish_upload(got,request),"LRU upload publication failed");
reference[victim]={request,++clock,true}; ++uploads;
}
require(actual.stats().hits==hits && actual.stats().misses==misses &&
actual.stats().uploads==uploads && actual.stats().evictions==evictions,
"LRU counters differ from independent reference");
}
std::puts("PASS: 10,000-operation LRU reference, exact slice identity, counters, serial ownership and fail-closed upload");
return 0;
} catch(const std::exception& e) { std::fprintf(stderr,"KAR LRU index test: %s\n",e.what()); return 1; }
+27 -5
View File
@@ -2,6 +2,8 @@
#include "kar_expert.hpp"
#include <algorithm>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <fcntl.h>
@@ -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<Impl>();
// Keep a descriptor to the exact inode used by both mappings. Replacing the
// configured path during validation cannot select a different payload.
@@ -69,9 +91,9 @@ 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",
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;
}
+8 -2
View File
@@ -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<float> matrix(H*F),input(8*H),output(8*H);
for(size_t i=0;i<input.size();++i)input[i]=float(int(i%17)-8)/16;
@@ -79,9 +82,12 @@ int main() try {
}
}
}
const auto stats=expert.cache_stats();
require(stats.uploads==2 && stats.hits==1 && stats.evictions==0,
"persistent expert cache did not reuse the repeated expert");
auto bad=tensors[0];bad.books_offset=UINT64_MAX-1;
require(!expert.stage(archive.data(),archive.size(),bad,tensors[1],tensors[2],0,error),"wrapped offset accepted");
require(!expert.run(input.data(),1,error),"run after failed stage accepted");
std::puts("PASS: exact matrix bytes, FP64 multiply tolerance1e-6, 1/8 tokens, expert0->1->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;}
+2
View File
@@ -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
+14
View File
@@ -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
+35
View File
@@ -0,0 +1,35 @@
#!/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 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
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','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()
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
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():
assert f'{name}={version}' in workflow
print('PASS: pinned CUDA 13.0.1 GPU-hidden Gitea container and direct packages')
+14
View File
@@ -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
+14
View File
@@ -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
+148
View File
@@ -0,0 +1,148 @@
#include "strata/core/experimental_routed.hpp"
#include <cassert>
#include <iostream>
#include <vector>
using namespace strata::core;
constexpr int tokens = 8, routes = 16, hidden = 2;
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<float> usage = std::vector<float>(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<Backend*>(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<float>::infinity();
if (b.mode == 6) y[1] = std::numeric_limits<float>::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; });
std::array<float, tokens * hidden> input{};
std::array<int32_t, tokens * routes> ids{};
std::array<float, tokens * routes * hidden> output{};
for (int t = 0; t < tokens; ++t) {
input[2 * t] = t + 0.5f; input[2 * t + 1] = t - 0.25f;
for (int k = 0; k < routes; ++k) ids[t * routes + k] = (k + t) % 16;
}
Backend b;
int64_t bad_expert = -1;
auto run = [&](int64_t n = tokens, int64_t k = routes, int64_t layer = 2,
ExperimentalRoutedBackend fn = backend, void* owner = nullptr) {
return dispatch_experimental_all_routed(layer, 4, hidden, 16, input.data(), ids.data(), n, k,
fn, owner ? owner : &b, output.data(), bad_expert, error);
};
assert(run() && b.calls == 1);
// Verify routing order and exactly one router-weight multiplication. No
// baseline cache/source/pool exists in this test: all 128 rows are owned.
for (int t = 0; t < tokens; ++t) {
float actual0 = 0, actual1 = 0, weight_sum = 0, weighted_expert = 0;
for (int k = 0; k < routes; ++k) {
const float weight = (k + 1) / 256.0f;
const auto i = t * routes + k;
actual0 += weight * output[2 * i]; actual1 += weight * output[2 * i + 1];
weight_sum += weight; weighted_expert += weight * ids[i];
}
const float oracle0 = 2 * input[2 * t] * weight_sum + weighted_expert;
const float oracle1 = 3 * input[2 * t + 1] * weight_sum - weighted_expert;
assert(std::abs(actual0 - oracle0) <= 1e-5f && std::abs(actual1 - oracle1) <= 1e-5f);
}
for (int mode = 1; mode <= 6; ++mode) {
b = Backend{}; b.mode = mode;
assert(!run() && b.calls == 1 && !error.empty());
}
// Invalid admission must leave outputs untouched and never enter backend.
b = Backend{}; output.fill(19);
auto untouched = [&] { assert(b.calls == 0); for (float x : output) assert(x == 19); };
for (int n : {0, 9}) { assert(!run(n)); untouched(); }
for (int k : {0, 17, 1024}) { assert(!run(tokens, k)); untouched(); }
for (int layer : {-1, 4}) { assert(!run(tokens, routes, layer)); untouched(); }
ids.back() = 16;
assert(!run() && bad_expert == 16); untouched();
ids.back() = -1;
assert(!run() && bad_expert == -1); untouched();
ids.back() = 6;
ids[1] = ids[0];
assert(!run() && bad_expert == ids[0]); untouched();
ids[1] = 1;
input[0] = std::numeric_limits<float>::quiet_NaN();
assert(!run()); untouched(); input[0] = 0.5f;
assert(!run(tokens, routes, 2, nullptr)); untouched();
assert(!dispatch_experimental_all_routed(2, 4, hidden, 16, input.data(), ids.data(), tokens, routes,
backend, nullptr, output.data(), bad_expert, error)); untouched();
Dispatch d;
d.experimental_miss = backend; d.experimental_miss_user = &b;
assert(dispatch_experimental_routed_window(d, hidden, input.data(), ids.data(), tokens, routes, output.data()));
assert(d.layers == 3 && d.experts == 138 && d.cache_refused == 133 && d.cache_hits == 7);
assert(d.multi_entries == 0 && d.multi_misses == 0 && !d.failed);
for (int i = 0; i < 64; ++i) assert(d.usage[i] == (i / 16 == 2 ? 8 : 0));
b = Backend{}; b.mode = 1;
d = Dispatch{}; d.experimental_miss = backend; d.experimental_miss_user = &b;
assert(!dispatch_experimental_routed_window(d, hidden, input.data(), ids.data(), tokens, routes, output.data()));
assert(d.failed && d.fail_layer == 2 && d.layers == 2 && d.experts == 10 && d.cache_refused == 5);
assert(std::string(d.fail) == "synthetic stage/run/finish fault");
assert(!dispatch_experimental_routed_window(d, hidden, input.data(), ids.data(), tokens, routes, output.data()));
assert(b.calls == 1); // a previous failure stays failed
b = Backend{};
d = Dispatch{}; d.experimental_miss = backend; d.experimental_miss_user = &b;
d.usage.resize(16);
assert(!dispatch_experimental_routed_window(d, hidden, input.data(), ids.data(), tokens, routes, output.data()));
assert(b.calls == 0 && d.failed && d.fail_layer == 2 && d.layers == 2);
std::cout << "PASS: strict all-routed admission, 128-row weighted CPU oracle (absolute tolerance 1e-5), "
"ownership, counters/usage, null native handles, bounds, duplicate/nonfinite input and backend fault rejection\n";
}
+92
View File
@@ -0,0 +1,92 @@
#include "strata/prefill/experimental_experts.hpp"
#include <cassert>
#include <iostream>
#include <numeric>
using namespace strata::prefill;
struct Backend {
int calls = 0, mode = 0;
std::vector<int64_t> 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<Backend*>(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<float>::infinity();
if (b.mode == 4) y[1] = std::numeric_limits<float>::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<int32_t, 4> offsets{0, 19, 19, 38};
std::array<int32_t, 38> source{};
for (int t = 0; t < 19; ++t) { source[t] = t; source[19 + t] = 18 - t; }
std::array<float, 38 * 3> 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<int64_t>{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";
}