From 139efbd1f56e9087963cf27264d95213b8d85aed Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 3 Oct 2026 17:05:27 +0200 Subject: [PATCH] Prototype bounded compressed PLE row cache on CUDA --- .../2026-10-03-bounded-ple-cache-smoke.md | 66 +++ gpu/kar/CMakeLists.txt | 4 + gpu/kar/README.md | 21 + gpu/kar/src/kar_row_cache_smoke.cu | 386 ++++++++++++++++++ 4 files changed, 477 insertions(+) create mode 100644 docs/experiments/2026-10-03-bounded-ple-cache-smoke.md create mode 100644 gpu/kar/src/kar_row_cache_smoke.cu diff --git a/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md b/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md new file mode 100644 index 00000000..ad57e4cf --- /dev/null +++ b/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md @@ -0,0 +1,66 @@ +# Bounded compressed PLE row cache smoke, 2026-10-03 + +## Setup + +This is the first **functional** GPU cache probe following the +[offline row-locality screen](2026-10-03-ple-cache-reuse.md). The program +`gpu/kar/src/kar_row_cache_smoke.cu` was compiled on Linux for `sm_120` with +CUDA 13.2.86 and the repository's pinned `libkar` object. The new CMake target +also configured and built successfully with CUDA 13.2.86 and Ninja on that +host. Hardware was an +RTX 5090 (32,607 MiB reported VRAM), NVIDIA driver 595.91.07, 600 W reported +power limit. The private Qwen3.8-Flash-Next IQ3_S KAR v4 archive and its +provenance are described in the [paired KAR report](2026-10-03-kar-ple-ab.md). +The selected record was `per_layer_token_embd.weight#strata-part-001-of-002` +at level 2. Payload CRCs were verified before any row access; no full-archive +SHA-256 pass was added. The two pinned GGUF source-shard SHA-256 values are +`4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` +and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +The archive's source-side SHA-256 was +`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; +the remote file was not independently SHA-checked, as recorded in the paired +report. The repository base before this probe was `49b091c`. + +The probe reserves only a bounded compressed-row cache, an update buffer, +slot IDs, a four-entry codebook, and the current F32 output. The CPU maps +row IDs to slots with LRU replacement. Each missed PLE row admits 50 +compressed bytes from the verified archive into a 64-byte VRAM slot. It +uploads a 56-byte update record per miss and four-byte slot ID per access; +the update record includes its slot number and two padding bytes. A CUDA +scatter kernel writes the row to its assigned slot, then another kernel +decodes the selected rows in VRAM. Every batch is compared byte for byte with +a fresh, independently gathered CPU decode of the encoded archive rows. + +## Correctness checks + +Both private traces used 16 row IDs per batch and a 1 MiB cache with 16,384 +slots. The five-batch trace requested rows 0–15, reversed them, repeated +them, requested 100–115, then revisited 0–15. The eviction trace filled the +cache with rows 0–16,399, repeated the last 16, then revisited the first 16. +The observed counts matched the expected LRU behavior exactly. + +| Trace | Batches | Accesses | Hits | Misses | Row bytes admitted | Actual H2D argument bytes | CPU parity | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | +| Reuse | 5 | 80 | 48 | 32 | 1,600 | 2,112 | Exact for all batches | +| Eviction | 1,027 | 16,432 | 16 | 16,416 | 820,800 | 985,024 | Exact for all batches | + +The eviction run's archive CRC verification took 80,131 ms. The first run +preceded the verification-time field and did not record that duration. The +sum of CUDA-event stages was 0.105 ms for five reuse batches and 7.047 ms +for 1,027 eviction batches. Those event sums include update and slot-ID +copies plus the scatter and decode kernels. The source arrays were ordinary +host memory, so the event sums may omit some host-side copy or staging time. +They exclude archive verification, CPU LRU lookup, output readback, CPU +reference decoding, and the rest of model inference. No throughput or +speedup claim follows. The output hash chains were `64284b0dfd5bfad9` +and `210c15ebb02c4a16`, respectively; exact per-batch CPU parity is the +stronger correctness check. + +This smoke keeps 1 MiB of cache payload allocated; it does not hold a 10 GB +PLE record in VRAM. It proves compressed row admission, hits, eviction, and +CUDA decoding work together on the real archive under the tested traces. +It does **not** yet use actual model request row IDs or connect decoded rows +to Strata's PLE consumer. It does not establish model quality, expert/KV +pressure, or end-to-end agent speed. The next step is a captured prefill and +decode row trace, then serving-path integration with a quality gate and +paired throughput measurement against the native baseline. diff --git a/gpu/kar/CMakeLists.txt b/gpu/kar/CMakeLists.txt index 0b58166d..900c4e62 100644 --- a/gpu/kar/CMakeLists.txt +++ b/gpu/kar/CMakeLists.txt @@ -28,3 +28,7 @@ target_link_libraries(strata-kar-gpu-smoke PRIVATE strata_kar_cuda) add_executable(strata-kar-sparse-row-smoke src/kar_sparse_row_smoke.cu) set_target_properties(strata-kar-sparse-row-smoke PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) target_link_libraries(strata-kar-sparse-row-smoke PRIVATE strata_kar_cuda) + +add_executable(strata-kar-row-cache-smoke src/kar_row_cache_smoke.cu) +set_target_properties(strata-kar-row-cache-smoke PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) +target_link_libraries(strata-kar-row-cache-smoke PRIVATE strata_kar_cuda) diff --git a/gpu/kar/README.md b/gpu/kar/README.md index fd3ebea1..d0f80418 100644 --- a/gpu/kar/README.md +++ b/gpu/kar/README.md @@ -81,6 +81,27 @@ The smoke program caps the decoded F32 output at 100 million elements. A large P For a private real-model overlay, `scripts/check-kar-cuda-records.py` accepts a JSON list of `{name, elements}` records (or a report with a `records` array), an archive, the Rust CLI, and the CUDA smoke binary. It checks byte-level CPU/CUDA output parity for each record, using the full tensor up to one million values and row 0 above that limit. It writes the complete result outside Git with mode 0600. Its event timings cover warm CUDA decoding only; it does not time PCIe transfer or multiply, and parity with the CPU KAR decoder is separate from quality against GGUF or end-to-end inference. +## Bounded compressed-row GPU cache probe + +`strata-kar-row-cache-smoke` exercises an experimental 1–1024 MiB VRAM cache +for the level-2, group-32, 160-value PLE geometry. Each GPU slot uses 64 +bytes for a 50-byte compressed row. A CPU LRU map assigns slots; the program +uploads only missed rows and the batch's slot IDs, scatters misses into VRAM, +and decodes the selected rows with CUDA. Every batch is checked byte for byte +against a fresh CPU decode from the verified archive. This probe is not wired +into serving and its event time does not include archive verification, CPU +planning, output readback, or the parity check. + +Build with `cmake --build artifacts/kar-gpu-build --target +strata-kar-row-cache-smoke`. Invoke as `strata-kar-row-cache-smoke ARCHIVE.kar +'per_layer_token_embd.weight#strata-part-001-of-002' 2 64 TRACE.txt`. The +private trace contains one batch per line with up to 128 space-separated, +part-local decimal row IDs. The cache refuses to run if its allocation would +leave less than 512 MiB or one sixteenth of total VRAM free, whichever is +greater. Keep traces and models outside Git. See +`docs/experiments/2026-10-03-bounded-ple-cache-smoke.md` for the first real +archive checks. + ## Selective row transfer prototype `strata-kar-sparse-row-smoke` tests a different staging geometry. The upstream `kar_decode_rows` computes only requested rows but `kar_reserve` first transfers the record's complete level prefix. The prototype verifies the KAR archive, gathers only the selected rows' codebook, group scales, and bit-plane words from the mapped file into a compact host packet, transfers that packet once, and decodes the rows on CUDA. It does not modify the pinned `libkar` source. Its output is compared with `model checksum-kar-row` for each selected row. diff --git a/gpu/kar/src/kar_row_cache_smoke.cu b/gpu/kar/src/kar_row_cache_smoke.cu new file mode 100644 index 00000000..79193750 --- /dev/null +++ b/gpu/kar/src/kar_row_cache_smoke.cu @@ -0,0 +1,386 @@ +#include "libkar.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +// This first cache prototype supports the target PLE geometry only. Keeping +// these constants explicit prevents accidental use with another KAR record. +constexpr uint32_t kRowValues = 160; +constexpr uint32_t kWords = 5; +constexpr uint32_t kLevel = 2; +constexpr uint32_t kRowBytes = kWords * (2 + kLevel * 4); +constexpr uint32_t kSlotBytes = 64; +constexpr uint32_t kMaxBatch = 128; + +struct Update { + uint32_t slot; + uint8_t bytes[kRowBytes]; +}; +static_assert(sizeof(Update) == 56); + +bool cuda_ok(cudaError_t code, const char* where) { + if (code == cudaSuccess) return true; + std::fprintf(stderr, "%s: %s\n", where, cudaGetErrorString(code)); + return false; +} + +bool inside(uint64_t offset, uint64_t size, uint64_t total) { + return offset <= total && size <= total - offset; +} + +bool parse_u32(const char* text, uint32_t& value) { + if (!text || !*text || *text == '-') return false; + errno = 0; + char* end = nullptr; + const unsigned long parsed = std::strtoul(text, &end, 10); + if (errno || *end || parsed > std::numeric_limits::max()) return false; + value = static_cast(parsed); + return true; +} + +struct MappedFile { + int fd = -1; + const uint8_t* data = nullptr; + size_t size = 0; + ~MappedFile() { + if (data) munmap(const_cast(data), size); + if (fd >= 0) close(fd); + } + bool open_read(const char* path) { + fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + struct stat info {}; + if (fstat(fd, &info) || info.st_size <= 0 || + uint64_t(info.st_size) > std::numeric_limits::max()) return false; + size = static_cast(info.st_size); + void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0); + if (mapped == MAP_FAILED) return false; + data = static_cast(mapped); + return true; + } +}; + +struct Entry { + uint32_t slot; + std::list::iterator age; +}; + +struct Lru { + explicit Lru(uint32_t slots) : slots(slots) {} + uint32_t slots; + uint32_t next_slot = 0; + std::list recent; + std::unordered_map entries; + + bool lookup(uint32_t row, uint32_t& slot) { + const auto found = entries.find(row); + if (found == entries.end()) return false; + slot = found->second.slot; + recent.splice(recent.begin(), recent, found->second.age); + return true; + } + + uint32_t admit(uint32_t row) { + uint32_t slot = 0; + if (next_slot < slots) { + slot = next_slot++; + } else { + const uint32_t victim = recent.back(); + slot = entries.at(victim).slot; + entries.erase(victim); + recent.pop_back(); + } + recent.push_front(row); + entries.emplace(row, Entry{slot, recent.begin()}); + return slot; + } +}; + +__global__ void scatter_updates(uint8_t* cache, const Update* updates, uint32_t count) { + const uint32_t i = blockIdx.x; + const uint32_t byte = threadIdx.x; + if (i < count && byte < kRowBytes) + cache[uint64_t(updates[i].slot) * kSlotBytes + byte] = updates[i].bytes[byte]; +} + +__global__ void decode_rows(const uint8_t* cache, const uint32_t* slots, + const __half* book, float* output, uint32_t count) { + const uint32_t row = blockIdx.x; + const uint32_t value = threadIdx.x; + if (row >= count || value >= kRowValues) return; + const uint8_t* source = cache + uint64_t(slots[row]) * kSlotBytes; + const uint32_t word = value / 32; + const uint32_t bit = value % 32; + const uint16_t scale_bits = uint16_t(source[word * 2]) | + (uint16_t(source[word * 2 + 1]) << 8); + uint32_t p0 = 0, p1 = 0; + memcpy(&p0, source + 10 + word * 4, 4); + memcpy(&p1, source + 30 + word * 4, 4); + const uint32_t index = (((p0 >> bit) & 1u) << 1) | ((p1 >> bit) & 1u); + output[uint64_t(row) * kRowValues + value] = + __half2float(book[index]) * __half2float(__ushort_as_half(scale_bits)); +} + +uint64_t fnv1a(const float* values, size_t count) { + uint64_t hash = 0xcbf29ce484222325ull; + const auto* bytes = reinterpret_cast(values); + for (size_t i = 0; i < count * sizeof(float); ++i) + hash = (hash ^ bytes[i]) * 0x100000001b3ull; + return hash; +} + +bool load_row(Update& update, uint32_t row, const kar_tensor_info& tensor, + const MappedFile& file) { + const uint64_t scale = tensor.scales_offset + uint64_t(row) * 10; + if (!inside(scale, 10, file.size)) return false; + std::memcpy(update.bytes, file.data + scale, 10); + for (uint32_t plane = 0; plane < kLevel; ++plane) { + const uint64_t start = tensor.planes_offset + uint64_t(plane) * + tensor.plane_stride_bytes + uint64_t(row) * 20; + if (!inside(start, 20, file.size)) return false; + std::memcpy(update.bytes + 10 + plane * 20, file.data + start, 20); + } + return true; +} + +void decode_cpu(const Update& update, const uint8_t* book_bytes, float* output) { + for (uint32_t value = 0; value < kRowValues; ++value) { + const uint32_t word = value / 32, bit = value % 32; + uint16_t scale_bits = 0, book_bits = 0; + uint32_t p0 = 0, p1 = 0; + std::memcpy(&scale_bits, update.bytes + word * 2, 2); + std::memcpy(&p0, update.bytes + 10 + word * 4, 4); + std::memcpy(&p1, update.bytes + 30 + word * 4, 4); + const uint32_t index = (((p0 >> bit) & 1u) << 1) | ((p1 >> bit) & 1u); + std::memcpy(&book_bits, book_bytes + index * 2, 2); + output[value] = __half2float(__ushort_as_half(book_bits)) * + __half2float(__ushort_as_half(scale_bits)); + } +} + +bool read_trace(const char* path, uint64_t rows, std::vector>& batches) { + std::ifstream input(path); + if (!input) return false; + std::string line; + while (std::getline(input, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream fields(line); + std::vector batch; + std::string field; + while (fields >> field) { + uint32_t row = 0; + if (!parse_u32(field.c_str(), row) || uint64_t(row) >= rows || + batch.size() == kMaxBatch) return false; + batch.push_back(row); + } + if (!batch.empty()) batches.push_back(std::move(batch)); + if (batches.size() > 1'000'000) return false; + } + return !batches.empty() && !input.bad(); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 6) { + std::fprintf(stderr, "usage: strata-kar-row-cache-smoke ARCHIVE.kar TENSOR LEVEL CACHE_MIB TRACE.txt\n"); + return 2; + } + uint32_t level = 0, budget_mib = 0; + if (!parse_u32(argv[3], level) || level != kLevel || + !parse_u32(argv[4], budget_mib) || budget_mib < 1 || budget_mib > 1024) { + std::fprintf(stderr, "this prototype requires level=2 and cache_mib=1..1024\n"); + return 2; + } + kar_archive* raw = nullptr; + const auto verify_begin = std::chrono::steady_clock::now(); + if (kar_open(argv[1], KAR_OPEN_VERIFY_PAYLOAD, &raw) != KAR_OK) { + std::fprintf(stderr, "kar_open: %s\n", kar_last_error()); + return 1; + } + const double archive_verify_ms = std::chrono::duration( + std::chrono::steady_clock::now() - verify_begin).count(); + std::unique_ptr archive(raw, kar_close); + const int index = kar_find(archive.get(), argv[2]); + if (index < 0) return 1; + const kar_tensor_info* tensor = kar_tensor(archive.get(), static_cast(index)); + if (tensor->storage_class != KAR_NESTED || tensor->group != 32 || + tensor->row_words != kWords || tensor->row_len != kRowValues || + tensor->planes_min > kLevel || tensor->planes_max < kLevel || + tensor->row_count > std::numeric_limits::max()) { + std::fprintf(stderr, "record is not the target group-32, 160-value PLE geometry\n"); + return 1; + } + MappedFile file; + if (!file.open_read(argv[1]) || file.size != kar_info(archive.get())->archive_bytes) + return 1; + const uint64_t book_offset = tensor->books_offset + 4; + if (!inside(book_offset, 8, file.size)) return 1; + std::vector> batches; + if (!read_trace(argv[5], tensor->row_count, batches)) { + std::fprintf(stderr, "invalid row trace; expected one batch of up to 128 IDs per line\n"); + return 1; + } + const uint32_t slots = std::min((uint64_t(budget_mib) << 20) / kSlotBytes, + tensor->row_count); + size_t max_batch = 0; + for (const auto& batch : batches) max_batch = std::max(max_batch, batch.size()); + if (slots < max_batch) return 1; + size_t free_bytes = 0, total_bytes = 0; + if (!cuda_ok(cudaMemGetInfo(&free_bytes, &total_bytes), "cudaMemGetInfo")) return 1; + const uint64_t headroom = std::max(512ull << 20, total_bytes / 16); + const uint64_t needed = uint64_t(slots) * kSlotBytes + + kMaxBatch * (sizeof(Update) + sizeof(uint32_t) + + kRowValues * sizeof(float)) + 8; + if (free_bytes <= headroom || needed > free_bytes - headroom) { + std::fprintf(stderr, "insufficient free VRAM with required headroom\n"); + return 1; + } + uint8_t* device_cache = nullptr; + Update* device_updates = nullptr; + uint32_t* device_slots = nullptr; + __half* device_book = nullptr; + float* device_output = nullptr; + cudaStream_t stream = nullptr; + cudaEvent_t start = nullptr, stop = nullptr; + int result = 1; + do { + if (!cuda_ok(cudaMalloc(&device_cache, uint64_t(slots) * kSlotBytes), "cache allocation") || + !cuda_ok(cudaMalloc(&device_updates, kMaxBatch * sizeof(Update)), "update allocation") || + !cuda_ok(cudaMalloc(&device_slots, kMaxBatch * sizeof(uint32_t)), "slot allocation") || + !cuda_ok(cudaMalloc(&device_book, 8), "book allocation") || + !cuda_ok(cudaMalloc(&device_output, kMaxBatch * kRowValues * sizeof(float)), + "output allocation") || + !cuda_ok(cudaStreamCreate(&stream), "stream create") || + !cuda_ok(cudaEventCreate(&start), "start event") || + !cuda_ok(cudaEventCreate(&stop), "stop event") || + !cuda_ok(cudaMemcpyAsync(device_book, file.data + book_offset, 8, + cudaMemcpyHostToDevice, stream), "book upload") || + !cuda_ok(cudaStreamSynchronize(stream), "book synchronize")) break; + Lru lru(slots); + std::array updates{}; + std::array slot_ids{}; + std::vector output(kMaxBatch * kRowValues); + std::vector expected(kMaxBatch * kRowValues); + uint64_t hits = 0, misses = 0, compressed_upload = 0, actual_upload = 0; + double host_prepare_ms = 0, gpu_stage_ms = 0; + uint64_t output_hash = 0xcbf29ce484222325ull; + bool failed = false; + for (const auto& batch : batches) { + const auto host_begin = std::chrono::steady_clock::now(); + uint32_t update_count = 0; + for (size_t i = 0; i < batch.size(); ++i) { + uint32_t slot = 0; + if (lru.lookup(batch[i], slot)) { + ++hits; + } else { + ++misses; + slot = lru.admit(batch[i]); + updates[update_count].slot = slot; + if (!load_row(updates[update_count], batch[i], *tensor, file)) { + failed = true; break; + } + ++update_count; + } + slot_ids[i] = slot; + } + if (failed) break; + host_prepare_ms += std::chrono::duration( + std::chrono::steady_clock::now() - host_begin).count(); + compressed_upload += uint64_t(update_count) * kRowBytes; + actual_upload += uint64_t(update_count) * sizeof(Update) + + batch.size() * sizeof(uint32_t); + if (!cuda_ok(cudaEventRecord(start, stream), "start record") || + (update_count && !cuda_ok(cudaMemcpyAsync(device_updates, updates.data(), + update_count * sizeof(Update), cudaMemcpyHostToDevice, stream), "update upload")) || + !cuda_ok(cudaMemcpyAsync(device_slots, slot_ids.data(), + batch.size() * sizeof(uint32_t), cudaMemcpyHostToDevice, stream), "slot upload")) { + failed = true; break; + } + if (update_count) { + scatter_updates<<>>(device_cache, device_updates, + update_count); + if (!cuda_ok(cudaGetLastError(), "scatter launch")) { failed = true; break; } + } + decode_rows<<(batch.size()), 256, 0, stream>>>( + device_cache, device_slots, device_book, device_output, + static_cast(batch.size())); + if (!cuda_ok(cudaGetLastError(), "decode launch") || + !cuda_ok(cudaEventRecord(stop, stream), "stop record") || + !cuda_ok(cudaEventSynchronize(stop), "stop synchronize")) { + failed = true; break; + } + float elapsed = 0; + if (!cuda_ok(cudaEventElapsedTime(&elapsed, start, stop), "event elapsed")) { + failed = true; break; + } + gpu_stage_ms += elapsed; + const size_t value_count = batch.size() * kRowValues; + if (!cuda_ok(cudaMemcpy(output.data(), device_output, value_count * sizeof(float), + cudaMemcpyDeviceToHost), "output copy")) { + failed = true; break; + } + Update reference{}; + for (size_t i = 0; i < batch.size(); ++i) { + if (!load_row(reference, batch[i], *tensor, file)) { + failed = true; break; + } + decode_cpu(reference, file.data + book_offset, + expected.data() + i * kRowValues); + } + if (failed) break; + if (std::memcmp(output.data(), expected.data(), value_count * sizeof(float)) != 0) { + std::fprintf(stderr, "cached CUDA rows differ from independent CPU row decode\n"); + failed = true; break; + } + const uint64_t batch_hash = fnv1a(output.data(), value_count); + output_hash = (output_hash ^ batch_hash) * 0x100000001b3ull; + } + if (failed) break; + std::printf("batches=%zu row_accesses=%llu cache_slots=%u cache_allocated_bytes=%llu archive_verify_ms=%.3f\n", + batches.size(), static_cast(hits + misses), slots, + static_cast(uint64_t(slots) * kSlotBytes), + archive_verify_ms); + std::printf("hits=%llu misses=%llu hit_rate=%.6f compressed_row_bytes=%llu actual_upload_bytes=%llu\n", + static_cast(hits), static_cast(misses), + double(hits) / double(hits + misses), + static_cast(compressed_upload), + static_cast(actual_upload)); + std::printf("host_prepare_total_ms=%.6f gpu_stage_total_ms=%.6f cpu_parity=exact batch_hash_chain=%llx\n", + host_prepare_ms, gpu_stage_ms, static_cast(output_hash)); + result = 0; + } while (false); + if (stop) cudaEventDestroy(stop); + if (start) cudaEventDestroy(start); + if (stream) cudaStreamDestroy(stream); + if (device_output) cudaFree(device_output); + if (device_book) cudaFree(device_book); + if (device_slots) cudaFree(device_slots); + if (device_updates) cudaFree(device_updates); + if (device_cache) cudaFree(device_cache); + return result; +}