From 80f66707bdaff356579c8deaadfa1f5296577dfc Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 3 Oct 2026 10:58:14 +0200 Subject: [PATCH] Add experimental KAR PLE model quality arm --- control-plane/src/kar_fixture.rs | 93 +++++++++ control-plane/src/main.rs | 11 ++ docs/build-validation.md | 13 ++ docs/compressed-runtime.md | 30 +++ engine/strata/CMakeLists.txt | 18 ++ .../strata/include/strata/kernels/ngram.hpp | 6 + engine/strata/src/kernels/ngram.cpp | 187 +++++++++++++++++- engine/strata/src/program/generate.cpp | 33 +++- gpu/kar/README.md | 10 + gpu/kar/src/kar_ple_cpu_probe.cpp | 64 ++++++ 10 files changed, 460 insertions(+), 5 deletions(-) create mode 100644 gpu/kar/src/kar_ple_cpu_probe.cpp diff --git a/control-plane/src/kar_fixture.rs b/control-plane/src/kar_fixture.rs index 1890e87f..cf096c3e 100644 --- a/control-plane/src/kar_fixture.rs +++ b/control-plane/src/kar_fixture.rs @@ -12,6 +12,89 @@ pub struct FixtureSummary { pub decoded_fnv1a64: u64, } +pub struct PleFixtureSummary { + pub archive_digest: [u8; 32], + pub row_fnv1a64: [u64; 4], +} + +/// Four PLE-shaped rows in two KAR parts, for the optional Strata PLE reader. +pub fn write_ple(destination: &Path) -> Result { + let mut weights = Vec::with_capacity(4 * 160); + for row in 0..4 { + for column in 0..160 { + let value = [-1.0f32, -0.25, 0.25, 1.0][(row + column) % 4]; + weights.push(value); + } + } + let mut raw = Vec::with_capacity(weights.len() * 4); + for weight in &weights { + raw.extend_from_slice(&weight.to_le_bytes()); + } + let source = kar_writer::SourceIdentity { + name: "strata-next-ple-smoke-f32", + architecture: "synthetic", + builder: "strata-next/ple-smoke-topdown-g32-l2-v1", + digest: Sha256::digest(&raw).into(), + total_elements: weights.len() as u64, + bytes: raw.len() as u64, + }; + let first = kar_codec::encode_with_boundaries(&weights[..320], 32, &[-0.5, 0.0, 0.5], 2)?; + let second = kar_codec::encode_with_boundaries(&weights[320..], 32, &[-0.5, 0.0, 0.5], 2)?; + let book1 = [0xb800u16, 0x3800]; + let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let first_planes = first.planes.iter().map(Vec::as_slice).collect::>(); + let second_planes = second.planes.iter().map(Vec::as_slice).collect::>(); + let first_digest: [u8; 32] = Sha256::digest(&raw[..1280]).into(); + let second_digest: [u8; 32] = Sha256::digest(&raw[1280..]).into(); + let tensors = [ + kar_writer::Tensor { + name: "per_layer_token_embd.weight#strata-part-001-of-002", + dims: &[160, 2], + source_dtype: 0, + source_digest: first_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &first.scales, + books: &books, + planes: &first_planes, + }, + }, + kar_writer::Tensor { + name: "per_layer_token_embd.weight#strata-part-002-of-002", + dims: &[160, 2], + source_dtype: 0, + source_digest: second_digest, + source_offset: 1280, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &second.scales, + books: &books, + planes: &second_planes, + }, + }, + ]; + kar_writer::write_archive(destination, &source, &tensors)?; + let mut row_fnv1a64 = [0; 4]; + for (row, checksum) in row_fnv1a64.iter_mut().enumerate() { + let name = tensors[row / 2].name; + let values = kar::decode_tensor_row(destination, name, 2, (row % 2) as u32)?; + *checksum = kar::f32_fnv1a64(&values); + } + Ok(PleFixtureSummary { + archive_digest: Sha256::digest(std::fs::read(destination).map_err(|e| e.to_string())?) + .into(), + row_fnv1a64, + }) +} + pub fn write(destination: &Path) -> Result { let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(8); let encoded = kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2)?; @@ -87,4 +170,14 @@ mod tests { assert!(write(&path).is_err()); std::fs::remove_file(path).unwrap(); } + + #[test] + fn ple_fixture_has_two_ordered_parts_and_four_rows() { + let path = + std::env::temp_dir().join(format!("strata-ple-fixture-{}.kar", std::process::id())); + let created = write_ple(&path).unwrap(); + assert_eq!(kar::verify(&path).unwrap().tensor_count, 2); + assert_ne!(created.row_fnv1a64[0], created.row_fnv1a64[1]); + std::fs::remove_file(path).unwrap(); + } } diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 44d86d7a..388fe250 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -28,6 +28,17 @@ async fn main() -> Result<(), Box> { println!("output_fnv1a64={:x}", result.decoded_fnv1a64); Ok(()) } + [model, action, flag, output] + if model == "model" && action == "ple-smoke-fixture" && flag == "--output" => + { + let result = kar_fixture::write_ple(Path::new(output))?; + println!("KAR-2 PLE smoke fixture: {output}"); + println!("archive_sha256={}", hex::encode(result.archive_digest)); + for (row, checksum) in result.row_fnv1a64.iter().enumerate() { + println!("row={row} fnv1a64={checksum:016x}"); + } + Ok(()) + } [model, action, manifest, flag, output] if model == "model" && flag == "--output" && action == "fetch" => { diff --git a/docs/build-validation.md b/docs/build-validation.md index 447dc019..d119cd1a 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -1,5 +1,18 @@ # Build validation +## 2026-10-03 — experimental PLE quality arm + +The imported engine builds on Linux CUDA 13.2/sm_120 with the optional +`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` flag. The ordinary build still succeeds +with the flag off. A synthetic KAR-2 archive with four 160-value PLE rows in +two parts was generated by the Rust CLI. The independent Rust decoder and the +new Strata `PleTable` probe matched FNV-1a checksums for all four rows, including +the boundary between parts: `20c844888ce711a5`, `6a219cbf159362a5`, +`62bed3d23ae584a5`, and `68137da89d55afa5`. The fixture was deleted from +both hosts after the check. This verifies row layout, bit order, scale/book +reconstruction, and part indexing on a synthetic archive; real-model output +and paired throughput remain unmeasured. + ## 2026-10-02 — source-only build - Strata upstream commit: `d9ab8435f654c368c586340d490915f6addf56a3`. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 97d22a44..0a00bfe4 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -1,5 +1,35 @@ # Compressed model runtime contract +## Experimental model quality arm + +The imported Strata engine has an optional Linux CUDA build flag, +`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, with `STRATA_NEXT_KAR_DIR` pointing at +`gpu/kar`. It adds `--ple-kar ARCHIVE --ple-kar-level 2` to `strata generate`. +With those flags, the PLE lookup table is decoded from KAR on the CPU, while +the native pack and GGUF shards still supply every other weight. The archive +is checked by `libkar` including all payload CRCs, and its PLE parts must have +the expected F32 geometry and complete row count. Check the known archive +SHA-256 and sidecar before a run. The feature is off in ordinary builds. +`strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for +comparison with `strata-next model checksum-kar-row` on the matching part. + +This arm measures whether PLE transcoding changes whole-model output and task +quality. It does not load the full compressed model, stage sparse PLE packets +to CUDA, or establish a model throughput gain. Use the same engine source, +model pack, sampling, workload, and server wrapper for control and candidate; +load the arms sequentially on a 32 GB GPU. The private +`scripts/compare-chat-reports.py` pairs two single-arm benchmark reports by +case and repetition and records quality and HTTP wall-time ratios. The times +remain descriptive until run order, disk/cache state, and interference are +controlled. + +`scripts/bench-chat-sequential-server.py` can run those arms one after the +other against the same private Strata server configuration. It verifies the +expected KAR SHA-256 first, writes temporary config files in tmpfs with mode +0600, starts only its own server process, unloads each model after the arm, +and keeps response reports outside Git. The candidate adds the experimental +PLE flags only; the original server configuration is never edited. + ## Artifact pipeline `strata-next model fetch` downloads the pinned source shards to an external volume. `model verify` checks their size and SHA-256 before any conversion. The current experimental `model prepare-sharded-streamed` builds a KAR-2 archive and a provenance sidecar with source and archive digests, codec policy, and tensor mapping; it writes to a staging path and publishes the finished archive without replacing an existing file. A production `model prepare --format kar2` still needs a per-class rate policy, tokenizer identity, and full-model quality approval. The final one-command `serve` flow should run missing fetch/verify/prepare stages automatically, reuse a verified prepared archive on subsequent starts, and never treat an incomplete stage as usable. Neither source shards nor the archive belong in Git or CI artifacts. diff --git a/engine/strata/CMakeLists.txt b/engine/strata/CMakeLists.txt index 4efc2976..f7dfadb7 100644 --- a/engine/strata/CMakeLists.txt +++ b/engine/strata/CMakeLists.txt @@ -267,6 +267,24 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/ngram/ple_reader.cpp src/platform/direct_file.cpp) target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) + option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build the optional KAR PLE CPU quality arm" OFF) + set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") + if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") + endif() + if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") + message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") + endif() + add_library(strata_next_kar STATIC "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") + target_include_directories(strata_next_kar PUBLIC "${STRATA_NEXT_KAR_DIR}/vendor") + target_link_libraries(strata_next_kar PUBLIC CUDA::cudart) + set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) + target_link_libraries(strata_kernels PUBLIC strata_next_kar) + target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) + add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") + target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) + endif() # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) diff --git a/engine/strata/include/strata/kernels/ngram.hpp b/engine/strata/include/strata/kernels/ngram.hpp index 3c6f8fab..6d06f0d3 100644 --- a/engine/strata/include/strata/kernels/ngram.hpp +++ b/engine/strata/include/strata/kernels/ngram.hpp @@ -139,6 +139,12 @@ public: /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + /// Experimental CPU quality arm: read rows from a verified KAR-2 archive + /// while the rest of the engine continues to use its normal model pack. + /// The CUDA selective-row path is measured separately and is not used here. + bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, + uint64_t expected_rows = PLE_TABLE_ROWS); + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. bool issue(const uint32_t* rows16); diff --git a/engine/strata/src/kernels/ngram.cpp b/engine/strata/src/kernels/ngram.cpp index 1a1552bf..15c2658b 100644 --- a/engine/strata/src/kernels/ngram.cpp +++ b/engine/strata/src/kernels/ngram.cpp @@ -11,12 +11,21 @@ #include #include #include +#include +#include #if !defined(_WIN32) #include #endif #include #include +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) +#include "libkar.h" +#include +#include +#include +#endif + #if defined(_WIN32) // `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. #define WIN32_LEAN_AND_MEAN @@ -153,6 +162,50 @@ struct PleTable::Impl { bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL float scale = 1.0f; // the FP8 table's one scale uint32_t rb = PLE_ROW_BYTES; // bytes per row +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + struct KarPart { + uint32_t number = 0; + uint64_t row_base = 0; + const kar_tensor_info* tensor = nullptr; + }; + kar_archive* kar = nullptr; + int kar_fd = -1; + const uint8_t* kar_map = nullptr; + size_t kar_bytes = 0; + uint32_t kar_level = 0; + std::string kar_format; + std::vector kar_parts; + void decode_kar_row(uint32_t row, float* out160) const { + const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, + [](const KarPart& item, uint32_t wanted) { + return item.row_base + item.tensor->row_count <= wanted; + }); + const kar_tensor_info* t = part->tensor; + const uint64_t local_row = uint64_t(row) - part->row_base; + const uint64_t first_word = local_row * t->row_words; + const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; + for (uint32_t word = 0; word < t->row_words; ++word) { + const uint64_t source_word = first_word + word; + const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); + const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); + uint32_t bits[8] = {}; + for (uint32_t level = 0; level < kar_level; ++level) { + const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes + + source_word * 4; + bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | + (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); + } + for (uint32_t bit = 0; bit < 32; ++bit) { + uint32_t code = 0; + for (uint32_t level = 0; level < kar_level; ++level) + code = (code << 1) | ((bits[level] >> bit) & 1u); + const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); + out160[word * 32 + bit] = book * scale; + } + } + bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); + } +#endif void decode(const uint8_t* row, float* out160) const { if (fp8) fp8_e4m3_dequant_row(row, scale, out160); else if (q5_0) @@ -164,6 +217,107 @@ struct PleTable::Impl { PleTable::PleTable() : impl_(new Impl) {} PleTable::~PleTable() { close(); delete impl_; } +bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, + uint64_t expected_rows) { +#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + (void) kar_path; (void) level; (void) expected_rows; + err = "experimental KAR PLE support is not compiled into this engine"; + return false; +#else + close(); + if (level < 1 || level > 8 || expected_rows == 0) { + err = "KAR PLE level or expected row count is invalid"; + return false; + } + kar_archive* archive = nullptr; + const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); + if (status != KAR_OK) { + err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); + return false; + } + impl_->kar = archive; + impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); + struct stat file_info {}; + if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || + uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { + err = "KAR PLE cannot reopen the verified archive at its expected length"; + close(); + return false; + } + impl_->kar_bytes = size_t(file_info.st_size); + void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); + if (map == MAP_FAILED) { + err = "KAR PLE cannot map the verified archive"; + close(); + return false; + } + impl_->kar_map = static_cast(map); + const std::string parent = "per_layer_token_embd.weight"; + const std::string prefix = parent + "#strata-part-"; + uint32_t declared_parts = 0; + for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { + const kar_tensor_info* t = kar_tensor(impl_->kar, i); + const std::string name = t->name; + uint32_t number = 0, total = 0; + if (name == parent) { + number = total = 1; + } else if (name.rfind(prefix, 0) == 0) { + char extra = 0; + if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { + err = "KAR PLE part name is malformed"; + close(); + return false; + } + } else { + continue; + } + if (!number || !total || number > total || (declared_parts && declared_parts != total) || + t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || + t->nesting != KAR_TOPDOWN || t->n_dims != 2 || + t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || + t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || + level < t->planes_min || level > t->planes_max) { + err = "KAR PLE part geometry or precision level differs from the model"; + close(); + return false; + } + declared_parts = total; + impl_->kar_parts.push_back({number, 0, t}); + } + std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), + [](const Impl::KarPart& left, const Impl::KarPart& right) { + return left.number < right.number; + }); + if (!declared_parts || impl_->kar_parts.size() != declared_parts) { + err = "KAR PLE parts are absent or incomplete"; + close(); + return false; + } + uint64_t rows = 0; + for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { + auto& part = impl_->kar_parts[i]; + if (part.number != i + 1 || part.tensor->row_count == 0 || + part.tensor->row_count > expected_rows - rows) { + err = "KAR PLE parts are out of order or exceed expected rows"; + close(); + return false; + } + part.row_base = rows; + rows += part.tensor->row_count; + } + if (rows != expected_rows) { + err = "KAR PLE row count differs from the model"; + close(); + return false; + } + impl_->n_rows = rows; + impl_->kar_level = level; + impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; + impl_->mode = PleIo::Mmap; + return true; +#endif +} + bool PleTable::open(const std::string& gguf_path, std::string& err) { return open(gguf_path, err, PleIoOptions{}); } @@ -280,6 +434,18 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO } void PleTable::close() { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); + impl_->kar_map = nullptr; + impl_->kar_bytes = 0; + if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); + impl_->kar_fd = -1; + if (impl_->kar) kar_close(impl_->kar); + impl_->kar = nullptr; + impl_->kar_parts.clear(); + impl_->kar_level = 0; + impl_->kar_format.clear(); +#endif impl_->reader.close(); impl_->pending = false; impl_->locked = false; // the unmap below releases the lock @@ -293,14 +459,31 @@ void PleTable::close() { impl_->fp8 = false; } -bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } +bool PleTable::is_open() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) return true; +#endif + return impl_->data != nullptr || impl_->reader.is_open(); +} bool PleTable::locked() const { return impl_->locked; } -const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } +const char* PleTable::format() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) return impl_->kar_format.c_str(); +#endif + return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; +} PleIo PleTable::mode() const { return impl_->mode; } uint64_t PleTable::rows() const { return impl_->n_rows; } uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } void PleTable::read_row(uint32_t row, float* out160) const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) { + if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); + else impl_->decode_kar_row(row, out160); + return; + } +#endif if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { uint8_t raw[PLE_ROW_BYTES_MAX]; std::string err; diff --git a/engine/strata/src/program/generate.cpp b/engine/strata/src/program/generate.cpp index 53c38a00..68d712f1 100644 --- a/engine/strata/src/program/generate.cpp +++ b/engine/strata/src/program/generate.cpp @@ -220,6 +220,8 @@ struct Options { std::string embd_gguf; /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. std::string ple_io = "direct"; + std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native + uint32_t ple_kar_level = 2; int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables int ple_inflight = 64; double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this @@ -423,6 +425,8 @@ void usage() { " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" " shard that holds per_layer_token_embd.weight when not given\n" + " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" + " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" " --no-ple explicit diagnostic ablation of the PLE layer\n" " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" @@ -1053,6 +1057,18 @@ int main(int argc, char** argv) { else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); + else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); + else if (a == "--ple-kar-level") { + const std::string value = next("--ple-kar-level"); + unsigned level = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || + level < 1 || level > 8) { + std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); + return 2; + } + o.ple_kar_level = level; + } else if (a == "--no-ple") o.no_ple = true; else if (a == "--ple-io") o.ple_io = next("--ple-io"); else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); @@ -1547,6 +1563,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); return 2; } + if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || + (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { + std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); + return 2; + } if (o.native_ple_postops && o.no_ple) { std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); return 2; @@ -2041,7 +2062,9 @@ int main(int argc, char** argv) { pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; } - if (!ple_table.open(o.ple_gguf, err, pio)) { + const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) + : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); + if (!ple_open) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } @@ -2049,7 +2072,10 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", ple_table.locked() ? "locked in RAM" : "loaded (not locked)", std::chrono::duration(Clock::now() - tpl).count()); - if (pio.keepalive_ms > 0) + if (!o.ple_kar.empty()) + std::fprintf(stderr, "strata generate: experimental PLE KAR CPU quality arm at level %u\n", + o.ple_kar_level); + else if (pio.keepalive_ms > 0) std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " "%.0f ms without a read, until %.0f s after the last request " "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); @@ -2468,7 +2494,8 @@ int main(int argc, char** argv) { return 1; } std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", - (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); + (unsigned long long) ple_table.rows(), + o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); } } for (size_t i = 0; i < stages.size(); ++i) { diff --git a/gpu/kar/README.md b/gpu/kar/README.md index 9d3d5e51..dc750beb 100644 --- a/gpu/kar/README.md +++ b/gpu/kar/README.md @@ -1,5 +1,15 @@ # KAR CUDA smoke target +The optional `strata_next_kar_ple_probe` target belongs to the imported +Strata engine build when `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`. It exercises +the separate CPU PLE quality arm on real KAR rows. A successful checksum does +not imply the sparse CUDA packet path is wired into serving. + +For a model-free reader check, run `strata-next model ple-smoke-fixture --output +/tmp/ple-smoke.kar`, then `strata_next_kar_ple_probe /tmp/ple-smoke.kar 2 +--expected-rows 4 0 1 2 3`. The four checksums must match those printed by +the Rust fixture command. Remove the temporary archive afterward. + `vendor/libkar.h` and `vendor/libkar.cu` are copied unchanged from local `koference` commit `806d2398ae1daaceb2917242911e5680cbfb3608`, paths `r08/code/libkar.h` and `r08/code/libkar.cu`. Their SHA-256 values are `1d725069fd2c275423f5db70fb4190e7d51760e0c48a2a5ebe8c91993936ca92` and `331babd2a2f260abb7de602d414edd97399542ec1bccb23ffcdfad69dc0ade28` respectively. Keep these bytes and upstream provenance traceable when making local changes. On Linux with CUDA 13 and a supported NVIDIA GPU, create a model-free fixture and compare its CPU and GPU decode checksums: diff --git a/gpu/kar/src/kar_ple_cpu_probe.cpp b/gpu/kar/src/kar_ple_cpu_probe.cpp new file mode 100644 index 00000000..c70e3e86 --- /dev/null +++ b/gpu/kar/src/kar_ple_cpu_probe.cpp @@ -0,0 +1,64 @@ +// Checks the experimental Strata PLE reader against the independent Rust KAR oracle. +// The archive is validated by PleTable::open_kar before any row is decoded. +#include "strata/kernels/ngram.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +bool parse_u32(const char* input, uint32_t& value) { + const std::string text(input); + const auto result = std::from_chars(text.data(), text.data() + text.size(), value); + return result.ec == std::errc{} && result.ptr == text.data() + text.size(); +} + +uint64_t fnv_f32(const float* values, size_t count) { + uint64_t hash = 0xcbf29ce484222325ULL; + for (size_t i = 0; i < count; ++i) { + const auto* bytes = reinterpret_cast(&values[i]); + for (size_t byte = 0; byte < sizeof(float); ++byte) { + hash ^= bytes[byte]; + hash *= 0x100000001b3ULL; + } + } + return hash; +} +} // namespace + +int main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: strata_next_kar_ple_probe ARCHIVE LEVEL [--expected-rows N] ROW [ROW...]\n"); + return 2; + } + uint32_t level = 0; + if (!parse_u32(argv[2], level) || level < 1 || level > 8) return 2; + uint32_t expected_rows = strata::kernels::PLE_TABLE_ROWS; + int first_row = 3; + if (argc >= 6 && std::string(argv[3]) == "--expected-rows") { + if (!parse_u32(argv[4], expected_rows) || expected_rows == 0) return 2; + first_row = 5; + } + strata::kernels::PleTable table; + std::string err; + if (!table.open_kar(argv[1], level, err, expected_rows)) { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + std::vector rows; + for (int i = first_row; i < argc; ++i) { + uint32_t row = 0; + if (!parse_u32(argv[i], row) || row >= table.rows()) return 2; + rows.push_back(row); + } + std::array decoded{}; + for (uint32_t row : rows) { + table.read_row(row, decoded.data()); + std::printf("row=%u fnv1a64=%016llx\n", row, + static_cast(fnv_f32(decoded.data(), decoded.size()))); + } + return 0; +}