Prototype selective CUDA staging for KAR rows

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 10:21:06 +02:00
parent a0c4e7c311
commit fc36acdba5
4 changed files with 284 additions and 0 deletions
+4
View File
@@ -229,3 +229,7 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- `scripts/check-kar-cuda-records.py` compared Rust CPU and CUDA reconstruction checksums for all 22 records in the private level-3 precision overlay. The checksum matched for **22/22** real records: full output for records up to one million values and row 0 for larger records. Thirty warm CUDA iterations per record gave isolated median decode times from 0.002496 to 0.003200 ms; recorded compressed residency ranged from 53,792 to 13,762,592 bytes. Transfer/setup time, matrix multiplication, and model-level quality are outside this measurement. The independent paired full-record L2 report for those same 22 records has median relative L2 0.50735 at base level 2 and 0.22608 at overlay level 3; this improvement is numerical, not a passed model-quality gate. The model-free temporary GPU fixture was removed after validation.
- A local release CLI independently verified the complete 55,295,529,472-byte v4 archive and decoded row 0 of `per_layer_token_embd.weight#strata-part-001-of-002` at level 2. Its 160 F32 values have FNV-1a `c6f74b955ce5a5ae`. This is the CPU oracle for a later GPU check after the remote v4 transfer finishes and its SHA-256 is verified. The temporary local Cargo build directory was removed after this run.
- The local CI entry point now checks Python syntax for both new offline measurement scripts and runs a mock HTTP A/B test. That test delays readiness until `max_context` becomes nonzero, requires bearer authentication, checks three case results per arm and paired output equality, and confirms the private report has mode 0600 without the token. It passed locally with Python 3; hosted GitHub Actions still cannot run until a repository is created.
## 2026-10-03 — selective KAR row transfer prototype
- Added an isolated CUDA prototype that verifies a KAR archive, gathers only the requested rows' scales and plane words into one compact packet, and decodes that packet on GPU. On RTX 5090 (driver 595.91.07, CUDA 13.2), level-3 `blk.0.ffn_gate_inp.weight` rows 0 and 1 each reconstructed to the same FNV-1a values as the independently verified Rust CPU decoder: `1a84ea920505914` and `b9359351c81dc9fb`. One row used a 1,136-byte H2D packet versus a 573,472-byte complete record prefix; two rows used 2,256 bytes versus the same prefix. The one-row test's 30 warm iterations had median H2D event time 0.003008 ms and decode event time 0.007328 ms. The existing full-prefix smoke on the same record reported `reserve_ms=0.044608` and warm decode median 0.003200 ms, but its reserve includes allocation/synchronization and the two programs have different setup paths, so these timing numbers are not a paired speedup claim. Packet construction and storage page faults are not timed. The prototype binary SHA-256 is `b05f037d68f3f4ca5d24f5a56029762d889babc8954f68050f187fe7bca9c44c`; it was built with the server's CUDA 13.2 `nvcc`. The server lacks CMake, so the new CMake target itself has not run there; the direct `nvcc` build and real CUDA execution passed.
+4
View File
@@ -24,3 +24,7 @@ set_target_properties(strata_kar_cuda PROPERTIES
add_executable(strata-kar-gpu-smoke src/kar_gpu_smoke.cpp)
target_compile_features(strata-kar-gpu-smoke PRIVATE cxx_std_20)
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)
+11
View File
@@ -35,3 +35,14 @@ Before any CUDA allocation, the smoke program checks the selected prefix, F32 ou
The smoke program caps the decoded F32 output at 100 million elements. A large PLE part can therefore be used with `--row` if its selected compressed prefix fits the available VRAM; its complete tensor need not fit the full-output cap.
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.
## 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.
```sh
cmake --build artifacts/kar-gpu-build --target strata-kar-sparse-row-smoke
artifacts/kar-gpu-build/strata-kar-sparse-row-smoke OVERLAY.kar blk.0.ffn_gate_inp.weight 3 30 0 1
```
The smoke reports packet bytes, the full-record prefix bytes, warm H2D event time, warm CUDA decode event time, and per-row byte checksums. Packet construction, archive verification, page faults, output transfer, matrix multiplication, and runtime scheduling are not included in those event times. 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.
+265
View File
@@ -0,0 +1,265 @@
#include "libkar.h"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace {
bool cuda_ok(cudaError_t status, const char* where) {
if (status == cudaSuccess) return true;
std::fprintf(stderr, "%s: %s\n", where, cudaGetErrorString(status));
return false;
}
bool kar_ok(kar_status status, const char* where) {
if (status == KAR_OK) return true;
std::fprintf(stderr, "%s: %s: %s\n", where, kar_strerror(status), kar_last_error());
return false;
}
bool parse_u32(const char* text, uint32_t& value) {
if (!text || !*text || *text == '-') return false;
char* end = nullptr;
errno = 0;
const auto parsed = std::strtoul(text, &end, 10);
if (errno || *end || parsed > std::numeric_limits<uint32_t>::max()) return false;
value = static_cast<uint32_t>(parsed);
return true;
}
bool within(uint64_t offset, uint64_t size, uint64_t file_size) {
return offset <= file_size && size <= file_size - offset;
}
uint64_t align4(uint64_t n) { return (n + 3u) & ~uint64_t{3}; }
uint64_t fnv1a64(const float* values, size_t count) {
auto hash = uint64_t{0xcbf29ce484222325};
const auto* bytes = reinterpret_cast<const unsigned char*>(values);
for (size_t i = 0; i < count * sizeof(float); ++i)
hash = (hash ^ bytes[i]) * uint64_t{0x100000001b3};
return hash;
}
float median(std::vector<float>& values) {
std::sort(values.begin(), values.end());
return values[values.size() / 2];
}
// One output word comes from one compact scale and one word from each plane.
// The source tensor's distant row addresses were resolved on the host.
__global__ void sparse_decode(const uint8_t* packet, float* output,
uint32_t words, uint32_t level,
uint32_t scale_offset, uint32_t plane_offset) {
const uint32_t word = blockIdx.x * blockDim.x + threadIdx.x;
if (word >= words) return;
const auto* book = reinterpret_cast<const __half*>(packet);
const auto* scales = reinterpret_cast<const __half*>(packet + scale_offset);
const auto* planes = reinterpret_cast<const uint32_t*>(packet + plane_offset);
const float scale = __half2float(scales[word]);
uint32_t bits[8];
for (uint32_t p = 0; p < level; ++p) bits[p] = planes[p * words + word];
for (uint32_t bit = 0; bit < 32; ++bit) {
uint32_t index = 0;
for (uint32_t p = 0; p < level; ++p)
index = (index << 1) | ((bits[p] >> bit) & 1u);
output[uint64_t(word) * 32 + bit] = __half2float(book[index]) * scale;
}
}
struct MappedFile {
int fd = -1;
const uint8_t* data = nullptr;
size_t size = 0;
~MappedFile() {
if (data) munmap(const_cast<uint8_t*>(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) return false;
size = static_cast<size_t>(info.st_size);
void* mapped = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) return false;
data = static_cast<const uint8_t*>(mapped);
return true;
}
};
} // namespace
int main(int argc, char** argv) {
if (argc < 6) {
std::fprintf(stderr, "usage: strata-kar-sparse-row-smoke ARCHIVE.kar TENSOR LEVEL ITERATIONS ROW_ID [ROW_ID ...]\n");
return 2;
}
uint32_t level = 0, iterations = 0;
if (!parse_u32(argv[3], level) || !parse_u32(argv[4], iterations) ||
level < 1 || level > 8 || iterations < 1 || iterations > 1000 || argc - 5 > 128) {
std::fprintf(stderr, "level must be 1..8, iterations 1..1000, rows 1..128\n");
return 2;
}
std::vector<uint32_t> row_ids;
for (int i = 5; i < argc; ++i) {
uint32_t row = 0;
if (!parse_u32(argv[i], row)) return 2;
row_ids.push_back(row);
}
kar_archive* raw = nullptr;
if (!kar_ok(kar_open(argv[1], KAR_OPEN_VERIFY_PAYLOAD, &raw), "kar_open")) return 1;
std::unique_ptr<kar_archive, decltype(&kar_close)> archive(raw, kar_close);
const int index = kar_find(archive.get(), argv[2]);
if (index < 0) {
std::fprintf(stderr, "tensor not found\n");
return 1;
}
const kar_tensor_info* tensor = kar_tensor(archive.get(), static_cast<uint32_t>(index));
if (tensor->storage_class != KAR_NESTED || tensor->row_words == 0 ||
tensor->group < 32 || tensor->group % 32 ||
level < tensor->planes_min || level > tensor->planes_max) {
std::fprintf(stderr, "record is not a supported compressed row tensor at this level\n");
return 1;
}
for (uint32_t row : row_ids)
if (uint64_t(row) >= tensor->row_count) {
std::fprintf(stderr, "row ID exceeds record bounds\n");
return 1;
}
const uint64_t word_count64 = uint64_t(row_ids.size()) * tensor->row_words;
const uint64_t value_count64 = word_count64 * 32;
if (word_count64 == 0 || word_count64 > 1'000'000 || value_count64 > 100'000'000) return 1;
const auto words = static_cast<uint32_t>(word_count64);
const auto values = static_cast<size_t>(value_count64);
const uint64_t book_bytes = uint64_t{1} << level;
const uint64_t book_size = book_bytes * 2;
const uint64_t scale_offset64 = book_size;
const uint64_t plane_offset64 = align4(scale_offset64 + word_count64 * 2);
const uint64_t packet_bytes64 = plane_offset64 + word_count64 * level * 4;
if (packet_bytes64 > std::numeric_limits<uint32_t>::max()) return 1;
const auto packet_bytes = static_cast<size_t>(packet_bytes64);
const auto scale_offset = static_cast<uint32_t>(scale_offset64);
const auto plane_offset = static_cast<uint32_t>(plane_offset64);
MappedFile file;
if (!file.open_read(argv[1]) || file.size != kar_info(archive.get())->archive_bytes) {
std::fprintf(stderr, "cannot map verified archive at its expected length\n");
return 1;
}
const uint64_t book_source = tensor->books_offset + ((uint64_t{1} << level) - 2u) * 2u;
if (!within(book_source, book_size, file.size)) return 1;
std::vector<uint8_t> packet(packet_bytes, 0);
std::memcpy(packet.data(), file.data + book_source, book_size);
for (size_t row_position = 0; row_position < row_ids.size(); ++row_position) {
const uint64_t first_word = uint64_t(row_ids[row_position]) * tensor->row_words;
for (uint32_t col = 0; col < tensor->row_words; ++col) {
const uint64_t source_word = first_word + col;
const uint64_t packed_word = uint64_t(row_position) * tensor->row_words + col;
const uint64_t scale_source = tensor->scales_offset +
(source_word / (tensor->group / 32)) * 2;
if (!within(scale_source, 2, file.size)) return 1;
std::memcpy(packet.data() + scale_offset + packed_word * 2,
file.data + scale_source, 2);
for (uint32_t plane = 0; plane < level; ++plane) {
const uint64_t word_source = tensor->planes_offset +
uint64_t(plane) * tensor->plane_stride_bytes + source_word * 4;
if (!within(word_source, 4, file.size)) return 1;
const uint64_t packed_offset = plane_offset +
(uint64_t(plane) * word_count64 + packed_word) * 4;
std::memcpy(packet.data() + packed_offset, file.data + word_source, 4);
}
}
}
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<uint64_t>(512ull << 20, total_bytes / 16);
const uint64_t needed = packet_bytes64 + value_count64 * sizeof(float);
if (free_bytes <= headroom || needed > free_bytes - headroom) {
std::fprintf(stderr, "insufficient GPU memory for sparse row smoke\n");
return 1;
}
uint8_t* pinned = nullptr;
uint8_t* device_packet = nullptr;
float* device_output = nullptr;
cudaStream_t stream = nullptr;
cudaEvent_t start = nullptr, middle = nullptr, stop = nullptr;
int result = 1;
do {
if (!cuda_ok(cudaHostAlloc(&pinned, packet_bytes, cudaHostAllocDefault), "cudaHostAlloc") ||
!cuda_ok(cudaMalloc(&device_packet, packet_bytes), "cudaMalloc packet") ||
!cuda_ok(cudaMalloc(&device_output, values * sizeof(float)), "cudaMalloc output") ||
!cuda_ok(cudaStreamCreate(&stream), "cudaStreamCreate") ||
!cuda_ok(cudaEventCreate(&start), "cudaEventCreate start") ||
!cuda_ok(cudaEventCreate(&middle), "cudaEventCreate middle") ||
!cuda_ok(cudaEventCreate(&stop), "cudaEventCreate stop")) break;
std::memcpy(pinned, packet.data(), packet_bytes);
std::vector<float> transfers, decodes;
transfers.reserve(iterations);
decodes.reserve(iterations);
bool failed = false;
for (uint32_t repeat = 0; repeat <= iterations; ++repeat) {
if (!cuda_ok(cudaEventRecord(start, stream), "event start") ||
!cuda_ok(cudaMemcpyAsync(device_packet, pinned, packet_bytes,
cudaMemcpyHostToDevice, stream), "row packet transfer") ||
!cuda_ok(cudaEventRecord(middle, stream), "event middle")) { failed = true; break; }
sparse_decode<<<(words + 255) / 256, 256, 0, stream>>>(
device_packet, device_output, words, level, scale_offset, plane_offset);
if (!cuda_ok(cudaGetLastError(), "sparse decode launch") ||
!cuda_ok(cudaEventRecord(stop, stream), "event stop") ||
!cuda_ok(cudaEventSynchronize(stop), "event synchronize")) { failed = true; break; }
if (repeat) {
float transfer = 0, decode = 0;
if (!cuda_ok(cudaEventElapsedTime(&transfer, start, middle), "transfer elapsed") ||
!cuda_ok(cudaEventElapsedTime(&decode, middle, stop), "decode elapsed")) {
failed = true; break;
}
transfers.push_back(transfer);
decodes.push_back(decode);
}
}
if (failed) break;
std::vector<float> host(values);
if (!cuda_ok(cudaMemcpy(host.data(), device_output, values * sizeof(float),
cudaMemcpyDeviceToHost), "copy output")) break;
const auto full_prefix = kar_decode_rows_cost(archive.get(), static_cast<uint32_t>(index),
level, row_ids.size()).resident_bytes;
std::printf("tensor=%s level=%u rows=%zu row_len=%u output_values=%zu\n",
argv[2], level, row_ids.size(), tensor->row_len, values);
std::printf("sparse_packet_bytes=%zu full_prefix_bytes=%llu iterations=%u\n",
packet_bytes, static_cast<unsigned long long>(full_prefix), iterations);
std::printf("transfer_median_ms=%.9g decode_median_ms=%.9g\n",
median(transfers), median(decodes));
std::printf("output_fnv1a64=%llx first=%.9g last=%.9g\n",
static_cast<unsigned long long>(fnv1a64(host.data(), host.size())),
host.front(), host.back());
for (size_t row = 0; row < row_ids.size(); ++row)
std::printf("row_id=%u row_fnv1a64=%llx\n", row_ids[row],
static_cast<unsigned long long>(fnv1a64(
host.data() + row * tensor->row_len, tensor->row_len)));
result = 0;
} while (false);
if (stop) cudaEventDestroy(stop);
if (middle) cudaEventDestroy(middle);
if (start) cudaEventDestroy(start);
if (stream) cudaStreamDestroy(stream);
if (device_output) cudaFree(device_output);
if (device_packet) cudaFree(device_packet);
if (pinned) cudaFreeHost(pinned);
return result;
}