83 lines
22 KiB
Markdown
83 lines
22 KiB
Markdown
# Compressed model runtime contract
|
||
|
||
## 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.
|
||
|
||
The first source profile is Qwen3.8-Flash-Next IQ3_S, which is already quantized. KAR transcoding of it is a **lossy experiment** until full-model quality is measured. A higher-fidelity source may be needed if the IQ3_S → KAR path exceeds the error budget. Keep the verified native IQ3_S pack as the control arm and recovery path; never infer model quality from archive size or isolated tensor error alone.
|
||
|
||
The tokenizer vocabulary, merge rules, and token-ID-to-text decoder belong in host RAM and run in Rust; they need no VRAM residency. Model embedding and output matrices are weights, even when their dimensions include the vocabulary size. Their placement and precision must be planned separately from tokenizer metadata. CPU placement of those matrices is possible but adds transfer or compute cost that must be measured on the target workload.
|
||
|
||
KAR-2, as specified by the local koference project at commit `806d2398ae1daaceb2917242911e5680cbfb3608` (`r08/docs/format-kar-v2.md`, `r08/code/libkar.h`), is one archive per model with a source digest, directory digest, payload checks, and per-tensor precision levels. The Rust command should call a validated native encoder or a stable `libkar` API; Python may be used for offline research, calibration, and differential tests, but not by production serving. The decoder must reject an archive whose identity, bounds, checksums, or tensor layout do not match the expected model.
|
||
|
||
The current `model inspect-kar` command performs bounded structural checks, header CRC-32, directory SHA-256, source identity reporting, and tensor section checks. `model verify-kar` additionally scans every tensor section and checks its payload CRC-32 with bounded memory. With `--manifest SPEC --source-dir DIR`, it verifies each source shard's size and SHA-256, then hashes the shards in filename order and compares the concatenated digest and byte count with the archive header. The sharded derived-F32 archives below require their dedicated verifier because the physical GGUF shard digest differs from the virtual F32 source digest. These checks do not constitute a model-quality or GPU execution result.
|
||
|
||
The Rust `kar_writer` module emits a KAR-2 container from already coded RAW/NESTED tensor slices. A synthetic two-tensor output matches the pinned koference reference writer byte for byte, including header, directory, aligned payload, CRCs, and digest. The writer verifies its temporary file before atomic no-replace publication and rejects non-finite f16 scales/books. It does not choose a compression rate or approve a serving configuration.
|
||
|
||
`strata-next model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. The KAR writer can stream both RAW tensor bytes and pre-encoded NESTED sections from files through a 1 MiB buffer. It checks the RAW source digest or NESTED section digest; the latter also checks finite f16 scales/books and zero alignment padding. The experimental native encoder supplies these sections for all GGUF types found in the target model.
|
||
|
||
An experimental native `kar_codec::encode_with_boundaries` converts one in-memory f32 tensor to group scales and MSB-first bit planes using nested boundaries. `kar_codec::fit_topdown` fits those boundaries and f16 books to an already selected normalized sample; pinned synthetic fixtures match koference's Python reference. It rounds scales to IEEE f16 before assigning cells and uses the same bit-within-u32 order as koference's CUDA decoder. `kar_codec::decode_range` reconstructs a selected prefix into a caller-sized CPU buffer, giving a small numerical oracle for later CUDA checks. The streamed pipeline separately handles source decoding, bounded calibration and encoding, while model rate selection and lossy serving approval remain open.
|
||
|
||
`strata-next model prepare-f32-preview FILE.gguf --output FILE.kar --levels N` connects the GGUF index, native calibration, encoder, CPU reconstruction check, and verified KAR writer. It accepts only a single F32 GGUF no larger than 64 MiB, at most 1000 tensors, with at most 1 million elements per tensor. Each encoded tensor is written to a private staging section and released from memory before the next tensor; the archive writer reads those sections with a 1 MiB buffer. Staging is cleaned after success or failure. It fits each tensor from all normalized values, records the rate in the KAR builder identity, and prints source/archive SHA-256 plus the maximum tensor relative L2. This command is an explicitly lossy integration preview. IQ3_S input is rejected, and no output from this command is eligible for serving until the full-model quality gate passes.
|
||
|
||
The Rust `iq3_s` module now decodes one GGUF IQ3_S block (110 bytes, 256 F32 outputs) or a caller-sized sequence of complete blocks. Its 512-entry grid is copied from the pinned Strata/ggml tree, checked by SHA-256, and carries the ggml MIT notice in the binary through `--ggml-license`. Synthetic block output matches an independent Python calculation. A real-data slice of 262,144 IQ3_S blocks also produced 67,108,864 bit-identical F32 values against the pinned ggml CPU decoder. Both complete source shards have since passed their manifest SHA-256 checks.
|
||
|
||
KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be identified directly as a KAR-2 tensor source without violating that field. `model derive-iq3-identity FILE.gguf` computes a versioned **virtual F32 source identity** for a single GGUF whose tensors are all IQ3_S. It streams dequantized little-endian F32 values in GGUF tensor-directory order, reports the derived stream and per-tensor digests/offsets alongside the original GGUF and IQ3 tensor digests, and does not materialize the expanded data. The original GGUF digest belongs in a separate provenance manifest; the existing `verify-kar --manifest` checks physical source files and must not be used as proof of this virtual stream.
|
||
|
||
`model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N` uses that identity to create a small, explicitly experimental KAR archive with F32 source dtype, virtual F32 tensor offsets/digests, and the derived stream digest. The original GGUF and IQ3 digests go into `FILE.kar.provenance.json`, published after the archive and bound to its SHA-256. If provenance publication fails, the new archive is removed. `model verify-iq3-preview FILE.kar --source FILE.gguf` recomputes the virtual source, checks every KAR tensor's F32 source record, scans payload CRCs, and compares the sidecar to the source and archive. It shares the F32 preview's 64 MiB source, 1000 tensor, and 1 million elements per tensor limits; source types must all be IQ3_S. Mixed-type shards, multi-shard identity, real tensor parity, and the full-model quality gate remain open. Neither preview archive is eligible for serving.
|
||
|
||
`model derive-mixed-identity FILE.gguf` extends the virtual F32 identity to a single GGUF containing IQ3_S plus other supported types. It preserves F32 bit patterns, expands F16 and BF16 to F32, and uses the pinned Rust IQ3_S decoder or statically linked ggml C CPU dequantizers for other quantized types. The virtual stream digest covers values in tensor-directory order and excludes GGUF headers and padding. The command reports original type and source digest per tensor. `model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N` encodes a small bounded source and verifies its sidecar; that preview still uses the original four source kinds and is not eligible for serving.
|
||
|
||
`model derive-sharded-identity MANIFEST --source-dir DIR` computes a virtual F32 identity across two or more GGUF shards. It sorts shards by byte-wise filename, checks each shard size and SHA-256 against the pinned manifest, rejects symlinks and duplicate tensor names, then concatenates decoded tensor values in each shard's directory order. The output includes per-shard identities and global derived tensor offsets. `model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` uses that identity to assemble a small experimental KAR from file-backed encoded sections, with a sidecar that binds every shard, tensor, and the archive digest. `model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR` recomputes and checks those links and the KAR payload CRCs. The 64 MiB preview cap, real-model quality gate, other tensor formats, and GPU path remain open.
|
||
|
||
The native `gguf_f32_stream` visitor yields source bytes and derived little-endian F32 bytes in bounded chunks. Besides F32, F16, BF16 and the independent Rust IQ3_S path, it uses the pinned ggml CPU dequantizers for actual target kinds Q8_0, Q4_K, Q5_K, Q6_K, IQ2_S, IQ4_NL, IQ3_XXS, IQ4_XS and Q2_0. The ggml C source at llama.cpp commit `3cf03257f219afbe7334045ff7c6a06ac68c627d` is vendored with hashes and linked statically into the Rust executable. A pinned synthetic IQ3_S block matches the independent Rust decoder exactly; one block of each real target quant type passes the bounded visitor. Both source shards are SHA-256 verified; real-model quality remains open.
|
||
|
||
The C bridge dispatches by named ggml type constants and checks its native block size against the Rust GGUF index before reading. This corrected an early kind-18/kind-22 swap (`IQ3_XXS` versus `IQ2_S`). Streamed archives now use v4 builder/provenance/derivation identifiers because giant GGUF tensors require multiple KAR-2 records; earlier streamed archives are rejected by the current verifier. Both target shards are SHA-256 verified, and one real block of every type in the first shard decoded to finite F32 values. The complete model-quality gate remains open.
|
||
|
||
The experimental `kar_sample` primitive normalizes these streamed values in reusable groups of 32 with the same rounded f16 scale logic as the existing codec. It takes at most 65,536 values from deterministic, digest-seeded positions spread across the padded tensor. For tensors over 1,048,576 elements it seeks directly to the selected GGUF blocks; F32 and IQ3_S sparse samples matched full-stream samples in tests. This sample is not a validated rate policy; per-class policy and the real-model quality gate remain open.
|
||
|
||
The `kar_stream_encode` primitive writes one canonical nested section directly from bounded GGUF chunks using the supplied calibration. It keeps only a group, source chunk, and buffered file writers in memory, hashes both physical and virtual sources, and computes tensor relative L2. A synthetic section matches the existing in-memory writer byte for byte and passes KAR-2 archive verification; an IQ3_S stream crossing a chunk boundary preserves source and derived digests.
|
||
|
||
`model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` now connects the bounded visitor, deterministic 65,536-value calibration sample, file-backed section encoder, and KAR-2 archive writer across manifest-pinned GGUF shards. It has no 64 MiB preview cap or per-tensor allocation. If a tensor cannot supply a valid nested calibration, it is copied as virtual F32 into a RAW section instead of being discarded. Every streamed tensor's physical and virtual digest is checked against an independently derived identity, every shard is hashed again after preparation, and the archive and separate preparation-policy provenance are published without replacing existing files. Oversized tensors are split into adjacent records with checked source and virtual offsets and part hashes. `model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N` independently verifies the shards, virtual tensor source records, archive payload CRCs, and sidecar binding. A small forced-split test reconstructs both records on CPU. Both real target shards and selected KAR slices are verified; full-model rate choice, quality, and Linux GPU loader still need validation. This command is experimental and its output is not eligible for serving.
|
||
|
||
The streamed preparer tracks relative L2 and encoded bytes per KAR record and prints the twenty records with the largest relative L2 on a newly created archive. The existing 51.50 GiB archive predates that recording and has only its full-record maximum of 0.68008092. `model analyze-sharded-kar` can now compare small source/archive windows for every record in that existing archive; its `--assume-verified` mode uses the earlier full source/archive verification and marks that assumption in the report. This ranks candidates for more precision but is not a full-record error bound or a model-quality score; a split parent tensor appears as multiple records. A selective precision policy can encode sensitive records at more KAR levels, retain an exact representation, or add independently addressable residual blocks. Residuals need archive integrity checks and must be included in transfer, VRAM, and CUDA decode budgets. Choose the policy after per-class distortion measurements and the separate model-quality gate; a lossless outer codec cannot repair KAR quantization error.
|
||
|
||
An experimental KAR overlay now carries higher-precision replacement records for a selected subset without rebuilding the full archive. Its provenance binds the base archive and candidate policy digests; selected physical and virtual source digests are checked during encoding. The overlay is independently verified, and the CPU comparison command measures paired full-record error against both archives. A serving loader must still select overlay records by name, verify both artifacts together, and account for their VRAM residency and transfer before this can affect inference. An overlay is not an additive residual: it replaces the selected base record when enabled.
|
||
|
||
`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. `--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.
|
||
|
||
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation.
|
||
|
||
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally.
|
||
|
||
The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape.
|
||
|
||
## GPU path
|
||
|
||
`strata-next model plan-kar-memory FILE.kar --level 2 --budget-mib 24576` reads validated KAR metadata and reports compressed-prefix residency, full F32 decode scratch, the largest single-record peak, and records whose full decode exceeds the supplied VRAM slice. The budget must be the memory left after the engine, KV cache, and other allocations; it is not the card's advertised capacity. `one_row_peak_bytes` is only a geometric lower bound for records that `kar_decode_rows()` can address. It does not mean the model can compute from one row of an arbitrary expert or projection. This command does not scan payload CRCs or approve the archive for serving.
|
||
|
||
`strata-next model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level 2 --overlay-level 3 --budget-mib 24576` first verifies both complete archive hashes, payload CRCs, provenance, and every replacement mapping. It then counts exactly one selected record per tensor at its chosen precision level, separating base and overlay compressed residency and reporting the largest F32 scratch and one-row lower bound. Keep both archives immutable after this check. This is still a memory calculation, not GPU admission or permission to serve a lossy model.
|
||
|
||
On the verified Qwen3.8-Flash-Next IQ3_S level-2 archive, the metadata plan at a hypothetical 24,576 MiB slice reports 55,294,991,056 bytes if all compressed records were resident, so residency must be selective. Two split `per_layer_token_embd.weight` records exceed that slice for full F32 decode: their compressed-prefix-plus-output peaks are 138,000,000,016 and 82,801,059,856 bytes. Their one-row lower bounds are 10,000,000,656 and 6,000,077,456 bytes. `kar_decode_rows()` avoids the huge F32 output but `kar_reserve()` still stages the complete 10.0 GB or 6.0 GB compressed record. Efficient cold row lookup therefore needs smaller addressable PLE parts or a sparse staging kernel. The engine must not allocate the full decoded table on the target card. These are metadata arithmetic, not GPU measurements or quality results.
|
||
|
||
For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim.
|
||
|
||
The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test.
|
||
|
||
## Cache profiles
|
||
|
||
| Profile | Attention state | Status |
|
||
| --- | --- | --- |
|
||
| `with-key` | K and V cache, using the selected baseline KV format | Control profile for quality and performance |
|
||
| `without-key` | Value-Only cache with a validated `Wq_keyless` transform; separate QSA indexer keys remain | Experimental until the Keyless quality gate passes |
|
||
|
||
Record the model digest, archive digest, cache profile, KV format, context length, slot count, and hardware with every comparison. Test `without-key` on held-out activation traces and full 256K/512K agent workloads; report memory savings, quality, and throughput separately. A cache profile cannot silently change when an archive is selected.
|
||
|
||
## Test-runtime switch
|
||
|
||
The testing runtime can first receive shadow traffic after a real Linux GPU smoke test proves model loading and a complete text response. Replacing the current test endpoint requires live Responses streaming, cancellation and tool-call integrity, sanitized Codex replay, a verified compressed GPU path, both cache profiles labeled accurately, and a one-step rollback to the current runtime. `without-key` can be tested separately before it is eligible as a default.
|