diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs index 6e78b70a..94b3d9ce 100644 --- a/control-plane/src/kar.rs +++ b/control-plane/src/kar.rs @@ -191,6 +191,45 @@ pub fn decode_tensor_range( decode_tensor_inner(path, name, level, start, Some(count)) } +/// CPU parity oracle for one CUDA row-gather request. The entire archive is +/// verified before the bounded row is decoded. +pub fn decode_tensor_row( + path: &Path, + name: &str, + level: u8, + row_id: u32, +) -> Result, String> { + let (_, records) = inspect_with_sources(path)?; + let record = records + .iter() + .find(|record| record.name == name) + .ok_or_else(|| format!("KAR tensor not found: {name}"))?; + let row_len = usize::try_from( + *record + .dimensions + .first() + .ok_or("KAR tensor has no dimensions")?, + ) + .map_err(|_| "KAR row length is too large")?; + if record.storage_class != 0 + || row_len == 0 + || !row_len.is_multiple_of(32) + || row_len > 1_000_000 + { + return Err("CUDA row gather requires a compressed record with a row length divisible by 32 and at most one million values".into()); + } + let start = (row_id as usize) + .checked_mul(row_len) + .ok_or("KAR row offset overflow")?; + if start + .checked_add(row_len) + .is_none_or(|end| end as u64 > record.n_elements) + { + return Err("KAR row ID exceeds tensor bounds".into()); + } + decode_tensor_range(path, name, level, start, row_len) +} + fn decode_tensor_inner( path: &Path, name: &str, diff --git a/control-plane/src/kar_fixture.rs b/control-plane/src/kar_fixture.rs index 60447a35..1890e87f 100644 --- a/control-plane/src/kar_fixture.rs +++ b/control-plane/src/kar_fixture.rs @@ -79,6 +79,11 @@ mod tests { let decoded = kar::decode_preview_tensor(&path, "smoke.expert", 2).unwrap(); assert_eq!(&decoded[..4], &[-0.75, -0.25, 0.25, 0.75]); assert_eq!(created.decoded_fnv1a64, kar::f32_fnv1a64(&decoded)); + assert_eq!( + kar::decode_tensor_row(&path, "smoke.expert", 2, 0).unwrap(), + decoded + ); + assert!(kar::decode_tensor_row(&path, "smoke.expert", 2, 1).is_err()); assert!(write(&path).is_err()); std::fs::remove_file(path).unwrap(); } diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 42d88f91..efe8f5f4 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -364,6 +364,16 @@ async fn main() -> Result<(), Box> { println!("first={} last={}", values[0], values[values.len() - 1]); Ok(()) } + [model, action, path, tensor, level, row_flag, row_id] + if model == "model" && action == "checksum-kar-row" && row_flag == "--row" => + { + let row_id: u32 = row_id.parse()?; + let values = kar::decode_tensor_row(Path::new(path), tensor, level.parse()?, row_id)?; + println!("tensor={tensor} row_id={row_id} elements={} level={level}", values.len()); + println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values)); + println!("first={} last={}", values[0], values[values.len() - 1]); + Ok(()) + } [model, action, path] if model == "model" && action == "inspect-kar" => { let summary = kar::inspect(Path::new(path))?; println!("KAR-2: {path}"); @@ -643,7 +653,7 @@ async fn main() -> Result<(), Box> { print!("{}", include_str!("../third_party/ggml/LICENSE")); Ok(()) } - _ => Err("usage: strata-next [serve|doctor|--ggml-license|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + _ => Err("usage: strata-next [serve|doctor|--ggml-license|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), } } diff --git a/docs/build-validation.md b/docs/build-validation.md index 346da012..20a1091a 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -172,3 +172,9 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Overlay preparation and paired comparison now resolve a selected PLE partition to its exact GGUF byte range and base KAR virtual source record. A synthetic v5 fixture encoded both an unsplit dense record and one of four PLE parts at level 3, verified the two replacement mappings, and compared both full records against the GGUF values. Altering the part's source byte offset caused comparison to fail. This validates record mapping and reconstruction for small synthetic data; no full v5 archive or model-level quality result exists yet. - All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The local build directory was cleaned after validation; preserved GGUF shards and v4 KAR artifacts were not changed. + +## 2026-10-03 — one-row CUDA smoke path + +- The isolated CUDA smoke target now accepts `--row ROW_ID` for a compressed record, including a selected PLE part from an overlay. It checks the local row bound, stages the record's compressed prefix, calls `kar_decode_rows` on a CUDA stream, and hashes only the one-row output. This reduces the output allocation for the smoke path; it does not reduce the initial compressed prefix transfer or integrate decoding into Strata's multiply path. +- Local Clang C++20 syntax checking with a temporary CUDA API declaration stub passed. No CUDA toolkit or GPU execution was available on the Mac. A read-only check of the Linux RTX 5090 at this step found 31,867/32,607 MiB VRAM in use by existing processes under driver 595.91.07, so neither the kernel result nor CPU/GPU row parity is claimed yet. +- The Rust `model checksum-kar-row` oracle verifies the complete KAR archive and decodes a bounded row for checksum comparison. On the synthetic 32-value fixture its row-0 values match the existing full-tensor CPU decoder exactly: both CLI paths returned FNV-1a `ff9fd7a827b333a5`; an out-of-range row is rejected. The temporary fixture was removed. All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md index 28936202..8afc02f3 100644 --- a/docs/compressed-runtime.md +++ b/docs/compressed-runtime.md @@ -46,7 +46,7 @@ An experimental KAR overlay now carries higher-precision replacement records for `model resolve-kar-overlay --base BASE.kar --overlay OVERLAY.kar` now emits a verified tensor-to-archive mapping for a future loader. It recomputes both archive SHA-256 values, validates every payload CRC, checks the shared virtual-F32 source identity, and rejects a replacement with a different source digest, offset, or dimensions. The command does not load weights or enable overlay serving. Keep both archives immutable after resolution; a GPU loader must validate their identities again before using this mapping. -The isolated Linux CUDA smoke target accepts an optional overlay path and routes a requested tensor to the selected archive after payload, common source identity, name, shape, dtype, per-record source digest, and source-offset checks. Run the full Rust resolver first for complete archive hashes and provenance. This exercises compressed VRAM residency and CUDA decoding for one selected record when the GPU is available; it does not integrate with Strata's matrix multiplication, schedule a model, or pass the quality gate. +The isolated Linux CUDA smoke target accepts an optional overlay path and routes a requested tensor to the selected archive after payload, common source identity, name, shape, dtype, per-record source digest, and source-offset checks. `--row ROW_ID` selects one local row of a compressed record and decodes it into a one-row GPU output buffer after staging that record's complete compressed level prefix. Run the full Rust resolver first for complete archive hashes and provenance. This exercises compressed VRAM residency and CUDA decoding for one selected record when the GPU is available; it does not integrate with Strata's matrix multiplication, schedule a model, or pass the quality gate. The CPU quality oracle can decode up to one million values from an arbitrary nested tensor offset with bounded memory, reading only the needed scales and plane words after archive verification. `cargo run --release --example compare-kar-range -- FILE.gguf FILE.kar LEVEL START COUNT` compares this archived output against pinned ggml dequantization of a one-tensor GGUF sample. On source-verified real slices, independent level-2 archive reconstruction gave relative L2 around 0.33–0.34 for sampled IQ3_S and IQ4_NL ranges; level 3 reduced one IQ4_NL range to 0.165. This is a numerical roundtrip check on selected ranges, not an agent-quality gate. diff --git a/gpu/kar/README.md b/gpu/kar/README.md index 81bf11db..17b566b9 100644 --- a/gpu/kar/README.md +++ b/gpu/kar/README.md @@ -10,6 +10,8 @@ cmake -S gpu/kar -B artifacts/kar-gpu-build -G Ninja -DCMAKE_CUDA_ARCHITECTURES= cmake --build artifacts/kar-gpu-build --target strata-kar-gpu-smoke artifacts/kar-gpu-build/strata-kar-gpu-smoke /tmp/strata-smoke.kar smoke.expert 2 30 strata-next model checksum-kar-preview /tmp/strata-smoke.kar smoke.expert 2 +artifacts/kar-gpu-build/strata-kar-gpu-smoke /tmp/strata-smoke.kar smoke.expert 2 30 --row 0 +strata-next model checksum-kar-row /tmp/strata-smoke.kar smoke.expert 2 --row 0 ``` An optional fifth argument is an overlay archive. The smoke target opens both @@ -25,3 +27,5 @@ The smoke target alone does not authenticate the archive files against provenance and is not a serving loader. The smoke program validates the KAR container and payload CRCs, reserves a chosen tensor's compressed level prefix in VRAM, decodes it on a CUDA stream, and reports a warm kernel median over the requested iterations. Compare `output_fnv1a64` with the native CPU command above using the selected archive, tensor, and level. This is a **kernel smoke measurement**, not an end-to-end inference comparison or a model quality result. It does not yet link the decoder into Strata's serving path. Use the original model digest, archive digest, driver/CUDA versions, GPU, tensor, cache state, and iteration count when recording results. + +`--row ROW_ID` selects the CUDA row-gather decoder for one row of a compressed record. The row ID is local to the selected KAR part, so `--row 0` on a split PLE part addresses that part's first row. This mode stages the same complete compressed level prefix with `kar_reserve`, then allocates and writes only one F32 row. It reports `mode=row` and the one-row output checksum. Compare a real-model result with `model checksum-kar-row` on the selected archive and part name; that CPU command verifies the complete archive before bounded range decoding. The one-row synthetic fixture above has the same checksum as its full-tensor decode. Row mode does not reduce the initial PCIe transfer of that part and does not make the full model fit in VRAM. diff --git a/gpu/kar/src/kar_gpu_smoke.cpp b/gpu/kar/src/kar_gpu_smoke.cpp index e2f2c5c6..0e6caf33 100644 --- a/gpu/kar/src/kar_gpu_smoke.cpp +++ b/gpu/kar/src/kar_gpu_smoke.cpp @@ -103,8 +103,13 @@ bool overlay_matches_base(const kar_archive* base, const kar_archive* overlay, } // namespace int main(int argc, char** argv) { - if (argc != 5 && argc != 6) { - std::cerr << "usage: strata-kar-gpu-smoke BASE.kar TENSOR LEVEL ITERATIONS [OVERLAY.kar]\n"; + uint32_t row_id = 0; + const bool row_mode = argc >= 7 && std::strcmp(argv[argc - 2], "--row") == 0; + const int positional_end = row_mode ? argc - 2 : argc; + if ((positional_end != 5 && positional_end != 6) || + (row_mode && !parse_uint(argv[argc - 1], &row_id))) { + std::cerr << "usage: strata-kar-gpu-smoke BASE.kar TENSOR LEVEL ITERATIONS " + "[OVERLAY.kar] [--row ROW_ID]\n"; return 2; } uint32_t level = 0, iterations = 0; @@ -117,7 +122,7 @@ int main(int argc, char** argv) { if (!kar_ok(kar_open(argv[1], KAR_OPEN_VERIFY_PAYLOAD, &raw_base), "kar_open base")) return 1; std::unique_ptr base(raw_base, kar_close); kar_archive* raw_overlay = nullptr; - if (argc == 6 && !kar_ok(kar_open(argv[5], KAR_OPEN_VERIFY_PAYLOAD, &raw_overlay), + if (positional_end == 6 && !kar_ok(kar_open(argv[5], KAR_OPEN_VERIFY_PAYLOAD, &raw_overlay), "kar_open overlay")) return 1; std::unique_ptr overlay(raw_overlay, kar_close); SourceDirectory base_source, overlay_source; @@ -138,6 +143,11 @@ int main(int argc, char** argv) { std::cerr << "smoke tensor must contain 1..100 million elements\n"; return 1; } + if (row_mode && (tensor->storage_class == KAR_RAW || !tensor->row_words || + row_id >= tensor->row_count)) { + std::cerr << "row mode requires a compressed record with an addressable row ID\n"; + return 1; + } cudaDeviceProp device{}; int driver = 0, runtime = 0; if (!cuda_ok(cudaGetDeviceProperties(&device, 0), "cudaGetDeviceProperties") || @@ -148,29 +158,42 @@ int main(int argc, char** argv) { cudaStream_t stream = nullptr; cudaEvent_t start = nullptr, stop = nullptr; float* output = nullptr; + uint32_t* device_row_id = nullptr; int result = 1; do { if (!cuda_ok(cudaStreamCreate(&stream), "cudaStreamCreate") || !cuda_ok(cudaEventCreate(&start), "cudaEventCreate") || !cuda_ok(cudaEventCreate(&stop), "cudaEventCreate")) break; - const size_t output_bytes = static_cast(tensor->n_elements) * sizeof(float); + const size_t output_elements = + row_mode ? tensor->row_len : static_cast(tensor->n_elements); + const size_t output_bytes = output_elements * sizeof(float); if (!cuda_ok(cudaMalloc(&output, output_bytes), "cudaMalloc")) break; + if (row_mode && + (!cuda_ok(cudaMalloc(&device_row_id, sizeof(row_id)), "cudaMalloc row ID") || + !cuda_ok(cudaMemcpyAsync(device_row_id, &row_id, sizeof(row_id), + cudaMemcpyHostToDevice, stream), "cudaMemcpyAsync row ID"))) { + break; + } + const kar_row_request row_request{ + static_cast(index), level, 1, device_row_id, output}; + const auto decode = [&]() { + return row_mode ? kar_decode_rows(archive, &row_request, stream) + : kar_decode(archive, static_cast(index), level, output, stream); + }; if (!cuda_ok(cudaEventRecord(start, stream), "reserve start") || !kar_ok(kar_reserve(archive, static_cast(index), level, stream), "kar_reserve") || !cuda_ok(cudaEventRecord(stop, stream), "reserve stop") || !cuda_ok(cudaEventSynchronize(stop), "reserve synchronize")) break; float reserve_ms = 0.0f; if (!cuda_ok(cudaEventElapsedTime(&reserve_ms, start, stop), "reserve elapsed")) break; - if (!kar_ok(kar_decode(archive, static_cast(index), level, output, stream), - "kar_decode warmup") || + if (!kar_ok(decode(), "kar_decode warmup") || !cuda_ok(cudaStreamSynchronize(stream), "decode warmup synchronize")) break; std::vector samples; samples.reserve(iterations); bool failed = false; for (uint32_t run = 0; run < iterations; ++run) { if (!cuda_ok(cudaEventRecord(start, stream), "decode start") || - !kar_ok(kar_decode(archive, static_cast(index), level, output, stream), - "kar_decode") || + !kar_ok(decode(), "kar_decode") || !cuda_ok(cudaEventRecord(stop, stream), "decode stop") || !cuda_ok(cudaEventSynchronize(stop), "decode synchronize")) { failed = true; @@ -184,7 +207,7 @@ int main(int argc, char** argv) { samples.push_back(milliseconds); } if (failed) break; - std::vector host(tensor->n_elements); + std::vector host(output_elements); if (!cuda_ok(cudaMemcpy(host.data(), output, output_bytes, cudaMemcpyDeviceToHost), "cudaMemcpy output")) break; uint64_t checksum = 14695981039346656037ull; @@ -198,13 +221,16 @@ int main(int argc, char** argv) { << "device=" << device.name << " driver_api=" << driver << " cuda_runtime=" << runtime << '\n' << "tensor=" << tensor->name << " source=" << selected_source - << " elements=" << tensor->n_elements + << " elements=" << output_elements + << " mode=" << (row_mode ? "row" : "full") + << (row_mode ? " row_id=" + std::to_string(row_id) : "") << " level=" << level << " resident_bytes=" << kar_resident_bytes(archive) << "\nreserve_ms=" << reserve_ms << " decode_median_ms=" << median_ms << " iterations=" << iterations << "\noutput_fnv1a64=" << std::hex << checksum << std::dec << " first=" << host.front() << " last=" << host.back() << '\n'; result = 0; } while (false); + if (device_row_id) cudaFree(device_row_id); if (output) cudaFree(output); if (start) cudaEventDestroy(start); if (stop) cudaEventDestroy(stop);