feat(kar): add bounded compressed expert LRU
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
name: KAR CUDA compile (GPU hidden)
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'gpu/kar/**'
|
||||
- 'engine/strata/CMakeLists.txt'
|
||||
- 'scripts/bootstrap-cuda-toolkit.py'
|
||||
- 'scripts/build-static-cuda.sh'
|
||||
- 'scripts/test-kar-expert-cache.sh'
|
||||
- 'scripts/test-kar-cuda-build-lock.py'
|
||||
- 'deploy/cuda-toolkit.lock.json'
|
||||
- 'deploy/kar-cuda-build.lock.json'
|
||||
- '.gitea/workflows/kar-cuda-compile.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'gpu/kar/**'
|
||||
- 'engine/strata/CMakeLists.txt'
|
||||
- 'scripts/bootstrap-cuda-toolkit.py'
|
||||
- 'scripts/build-static-cuda.sh'
|
||||
- 'scripts/test-kar-expert-cache.sh'
|
||||
- 'scripts/test-kar-cuda-build-lock.py'
|
||||
- 'deploy/cuda-toolkit.lock.json'
|
||||
- 'deploy/kar-cuda-build.lock.json'
|
||||
- '.gitea/workflows/kar-cuda-compile.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
kar-cuda-compile:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 150
|
||||
steps:
|
||||
- uses: https://git.vezha.io/actions/checkout@v4
|
||||
|
||||
- name: Build lock check
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 scripts/test-kar-cuda-build-lock.py
|
||||
|
||||
- name: Compile CUDA component in GPU-hidden Docker
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import json; print(json.load(open("deploy/kar-cuda-build.lock.json"))["builder_image"])')"
|
||||
packages="$(python3 -c 'import json; p=json.load(open("deploy/kar-cuda-build.lock.json"))["apt_packages"]; print(" ".join(f"{k}={v}" for k,v in p.items()))')"
|
||||
docker run --rm --platform linux/amd64 --network bridge \
|
||||
-e NVIDIA_VISIBLE_DEVICES=void -e CUDA_VISIBLE_DEVICES= \
|
||||
-e LOCKED_PACKAGES="$packages" \
|
||||
-v "$GITHUB_WORKSPACE:/work" -w /work "$base" \
|
||||
bash -euxo pipefail -c '
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends $LOCKED_PACKAGES
|
||||
dpkg-query -W -f="${Package}=${Version}\n" ca-certificates cmake gcc-13 g++-13 make python3
|
||||
python3 scripts/test-kar-cuda-build-lock.py
|
||||
CXX=g++-13 scripts/test-kar-expert-cache.sh
|
||||
python3 scripts/bootstrap-cuda-toolkit.py --output /tmp/cuda-toolkit
|
||||
export CUDACXX=/tmp/cuda-toolkit/bin/nvcc
|
||||
export CUDAToolkit_ROOT=/tmp/cuda-toolkit
|
||||
export CC=gcc-13 CXX=g++-13
|
||||
cmake -S gpu/kar -B /tmp/kar-build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=120
|
||||
cmake --build /tmp/kar-build --parallel 1 --target strata-kar-expert-cache-test strata-kar-expert-test strata-kar-expert-miss-test strata-kar-expert-probe
|
||||
ctest --test-dir /tmp/kar-build --output-on-failure -R "^kar_expert_cache_index$"
|
||||
test -z "$(nvidia-smi 2>/dev/null || true)" || { echo "unexpected GPU visible in compile container" >&2; exit 1; }
|
||||
'
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"platform": "linux/amd64",
|
||||
"builder_image": "ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794",
|
||||
"apt_packages": {
|
||||
"ca-certificates": "20260601~26.04.1",
|
||||
"cmake": "4.2.3-2ubuntu2",
|
||||
"gcc-13": "13.4.0-10ubuntu1",
|
||||
"g++-13": "13.4.0-10ubuntu1",
|
||||
"make": "4.4.1-3",
|
||||
"python3": "3.14.3-0ubuntu2"
|
||||
},
|
||||
"cuda_toolkit_lock": "cuda-toolkit.lock.json",
|
||||
"cuda_toolkit_release": "13.0.1",
|
||||
"cuda_architecture": "120",
|
||||
"compile_jobs": 1
|
||||
}
|
||||
@@ -56,6 +56,10 @@ target_compile_features(strata-kar-expert-probe PRIVATE cxx_std_20)
|
||||
target_link_libraries(strata-kar-expert-probe PRIVATE strata_kar_cuda strata_kar_expert)
|
||||
|
||||
enable_testing()
|
||||
add_executable(strata-kar-expert-cache-test src/kar_expert_cache_test.cpp)
|
||||
target_compile_features(strata-kar-expert-cache-test PRIVATE cxx_std_17)
|
||||
add_test(NAME kar_expert_cache_index COMMAND strata-kar-expert-cache-test)
|
||||
set_tests_properties(kar_expert_cache_index PROPERTIES TIMEOUT 60)
|
||||
add_executable(strata-kar-expert-test src/kar_expert_test.cpp)
|
||||
target_compile_features(strata-kar-expert-test PRIVATE cxx_std_20)
|
||||
target_link_libraries(strata-kar-expert-test PRIVATE strata_kar_expert)
|
||||
|
||||
@@ -200,3 +200,27 @@ bounded GPU cache and does not measure cold random storage access.
|
||||
The smoke reports packet bytes, the full-record prefix bytes, warm H2D event time, warm CUDA decode event time, and per-row byte checksums. It reports archive verification and one packet build separately as host wall time; those are not included in the GPU event times. Page faults, output transfer, matrix multiplication, and runtime scheduling need separate accounting. Random rows may trigger storage reads and CPU work, so fewer PCIe bytes do not by themselves establish lower request latency. A production path needs a bounded packet cache, coalescing across requests, provenance binding, backpressure, and integration with the PLE consumer before it can be evaluated as inference.
|
||||
|
||||
The `--range START COUNT` form generates consecutive local row IDs, up to 200,000 rows and the same 100-million-value output cap. `--random COUNT SEED` generates deterministic pseudorandom local IDs within the selected tensor record. Both omit individual row checksums for more than 128 rows but still report the whole output checksum. The contiguous selection is useful for GPU transfer scaling; random selection probes host packet assembly with scattered rows. Neither selection is a representative storage page-fault benchmark because archive payload verification reads the complete file first and can warm the page cache. The smoke times both first packet assembly and a median of five repeated assemblies on the same rows. It also times an upload of the same number of F32 rows from pinned host memory into the output buffer. That upload is the GPU stage of Strata's current PLE prefill path. The comparison excludes its CPU row decoding; compare it with the separate CPU gather probe. Compare the measured stages at the same row count rather than inferring latency from byte counts alone.
|
||||
# Experimental compressed expert cache
|
||||
|
||||
`ResidentExpert` can keep a bounded set of three-matrix expert packets compressed
|
||||
in device memory. `STRATA_NEXT_KAR_EXPERTS_CACHE_MIB` is an opt-in budget used by
|
||||
the experimental native-miss adapter; it must be an integer from 1 to 4096 and
|
||||
large enough for one complete expert slot. An unset variable retains the legacy
|
||||
single-slot footprint. Slots are allocated up front after the free-VRAM/headroom
|
||||
check. A hit reuses the compressed packet and one shared F32 decode scratch;
|
||||
eviction can happen only while no run is pending. A slot's exact mapping and
|
||||
tensor-slice key is published only after its upload synchronizes successfully.
|
||||
Upload or kernel errors poison the component closed. Cache hit counts, uploads,
|
||||
evictions, compressed bytes and scratch bytes are diagnostics, not a speed claim.
|
||||
|
||||
The CUDA-independent index tests run with `scripts/test-kar-expert-cache.sh`.
|
||||
CUDA component tests also check exact reconstructed matrices and FP64 multiply
|
||||
parity on a GPU; CI only compiles those targets with GPU devices hidden and does
|
||||
not claim runtime correctness or model quality.
|
||||
|
||||
The Gitea build lock is `deploy/kar-cuda-build.lock.json`: Ubuntu 26.04 amd64
|
||||
base image digest `88a381d5…d3794`, GCC/G++ 13.4.0, CMake 4.2.3, GNU make
|
||||
4.4.1 and Python 3.14.3. The CUDA compiler and redistributable components are
|
||||
separately checksum-locked in `deploy/cuda-toolkit.lock.json` to NVIDIA CUDA
|
||||
13.0.1. The lock records the direct apt package versions; Ubuntu's transitive
|
||||
packages are resolved from that image's configured archive during CI.
|
||||
|
||||
@@ -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_;
|
||||
|
||||
@@ -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
|
||||
@@ -14,7 +14,7 @@ public:
|
||||
~ExpertMiss();
|
||||
bool open(const char* archive, uint32_t layers, uint32_t experts,
|
||||
uint32_t hidden, uint32_t intermediate, uint32_t level,
|
||||
std::string& error);
|
||||
std::string& error, uint64_t compressed_cache_budget_bytes=0);
|
||||
bool compute(int64_t layer, const float* input, const int32_t* ids,
|
||||
int64_t tokens, int64_t k, int32_t* kind, float* output,
|
||||
std::string& error);
|
||||
|
||||
+59
-19
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
@@ -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,7 +91,7 @@ bool ExpertMiss::open(const char* path,uint32_t layers,uint32_t experts,uint32_t
|
||||
}
|
||||
p->records.push_back(t);
|
||||
}
|
||||
if(!p->resident.open(hidden,ff,level,8,error))return false;
|
||||
if(!p->resident.open(hidden,ff,level,8,error,compressed_cache_budget_bytes))return false;
|
||||
p->input.resize(size_t(hidden)*8);p->output.resize(size_t(hidden)*8);
|
||||
std::fprintf(stderr,"strata KAR experimental: native verifier misses (short prompt and decode), level=%u, compressed=%llu scratch=%llu; quality not qualified\n",
|
||||
level,(unsigned long long)p->resident.resident_bytes(),(unsigned long long)p->resident.scratch_bytes());
|
||||
|
||||
@@ -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;}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
lock=json.loads((ROOT/'deploy/kar-cuda-build.lock.json').read_text())
|
||||
assert lock['schema_version']==1
|
||||
assert lock['platform']=='linux/amd64'
|
||||
assert re.fullmatch(r'ubuntu@sha256:[0-9a-f]{64}',lock['builder_image'])
|
||||
assert lock['cuda_toolkit_release']=='13.0.1'
|
||||
assert lock['cuda_architecture']=='120' and lock['compile_jobs']==1
|
||||
assert lock['cuda_toolkit_lock']=='cuda-toolkit.lock.json'
|
||||
toolkit=json.loads((ROOT/'deploy'/lock['cuda_toolkit_lock']).read_text())
|
||||
assert toolkit['release']==lock['cuda_toolkit_release']
|
||||
required={'ca-certificates','cmake','gcc-13','g++-13','make','python3'}
|
||||
assert set(lock['apt_packages'])==required
|
||||
assert all(re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*',v) for v in lock['apt_packages'].values())
|
||||
print('PASS: pinned CUDA 13.0.1 Linux build image, compiler, CMake and base packages')
|
||||
Executable
+14
@@ -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
|
||||
Reference in New Issue
Block a user