8.1 Interface migration: KV format v1 to v2
Most engineering time is spent changing systems that already work, and the hardest changes are to interfaces other components depend on. The KV cache is one. Its export envelope is read by the C block pool and carried between engines by the Rust transfer path, and format v2 changes its representation: blocks become fp8 E4M3 values with one f32 scale per (layer, K or V, head) instead of f16. A coordinated migration is necessary, because with mixed versions in flight a peer can otherwise corrupt blocks or reject valid transfers.
Concepts from other sections (7)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- KV cache: the stored keys and values of earlier tokens, bytes per token. Read more: 11.1 Counting: parameters, FLOPs, KV bytes, and memory plans in Mathematics
- Block pool: one slab of fixed-size KV blocks handed out by id. Read more: 21.8 A paged KV block pool in C in AI Engineering
- E4M3: an 8-bit float with 4 exponent bits (bias 7) and 3 fraction bits, no infinity, largest finite value 448. Read more: 15.4 FP8 and microscaling formats in Mathematics
- Readers before writers: the rollout order in which every consumer accepts the new format before any producer emits it. Read more: 12.5 The KV format v2 migration in Systems Engineering
- CRC-32C: a 32-bit Castagnoli checksum over a payload, used to detect corruption. Read more: 1.10 Protocol Buffers and gRPC: schema evolution, unary and streaming RPCs, stubs in Programming and Algorithms
- Pure function: a function whose output depends only on its inputs and which mutates nothing. Read more: Chapter 4: Coding and Design Patterns
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even in Mathematics
This section builds the pieces that make the migration safe: a reader that accepts both versions, a writer that can emit either, and a one-way offline converter from v1 files to v2. Along the way it works one block through the conversion by hand, so you can see exactly what fp8 costs. The solution is the tl-kv-format crate: lib.rs provides decode, encode, upgrade_v1, Envelope, Block, Shape, and Error; main.rs is the offline converter kv-migrate; and Cargo.toml is the manifest. The byte layout is fixed by the contract course/contracts/formats/kv-block.md, in its sections “Export envelope”, “Payload, format v2”, and “Reader rules”.
The migration follows the Deprecation policy from the previous chapter, which sets the rollback window during which v1 must stay readable, and it is rehearsed in The KV format v2 migration in Systems Engineering. Try to predict each step of the solution before you read it.
Learning objectives
- Explain why a format migration ships readers before writers and keeps the old format readable through the rollback window.
- Convert a block from f16 to fp8 E4M3 by hand, including the per-slab scale and round-to-nearest-even ties.
- Validate an untrusted binary envelope completely, with checked size arithmetic, before returning any data.
- Build a one-way, atomic offline converter that refuses to quantize twice.
Readers first, then writers
Section titled “Readers first, then writers”The principles come before the code. Document the wire envelope and the negotiation rules first. Make readers compatible before any writer emits v2. Keep v1 readable through the rollback window. And reject unsupported versions before allocating or mutating any state.
Put together, the rollout looks like this. Ship a reader that accepts v1 and v2, then deploy writers that emit v2 only after every reader advertises support. Test mixed pairs, fp8 scales, the content hash, malformed lengths, and the downgrade path. Track the format version by peer, so you know when the last v1 consumer is gone.
Converting one block by hand
Section titled “Converting one block by hand”Take the contract’s worked v1 envelope: B=2, L=1, Hkv=1, D=2, one full block with hash 0xA91AB0C1027B9366, K = [[1, 2], [3, 4]] and V = [[0.5, -1], [0, 0.25]]. Its v1 payload is 1 × 2 × 1 × 2 × 2 × 2 = 16 bytes of f16. The v2 payload is 1 × 2 × 1 × (2 × 2 + 4) = 16 bytes: eight fp8 values plus two f32 scales. The two sizes happen to match for this tiny shape; the interpretation differs.
Now convert. The K slab is 1 2 3 4, so amax = 4 and scale = 4/448. Dividing gives 112 224 336 448. In e4m3 (bias 7, three mantissa bits), 112 = 1.75 × 2^6 is code 0x6e, 224 = 1.75 × 2^7 is 0x76, and 448 = 1.75 × 2^8 is 0x7e, the largest finite value. 336 falls exactly between the neighbours 320 = 1.25 × 2^8 (0x7a) and 352 = 1.375 × 2^8 (0x7b); the tie goes to the even code 0x7a, so the third K value decodes to 320 × 4/448 ≈ 2.857, not 3. The V slab has amax = 1 and scale = 1/448: 0.5 → 224 → 0x76, -1 → -448 → 0xfe, 0 → 0x00, 0.25 → 112 → 0x6e. The converted 60-byte envelope, as the solution produces it, is:
54 4c 4b 56 02 00 03 00 01 00 00 00 02 00 00 00 magic, version 2, dtype 3 (e4m3), n_blocks 1, block_tokens 201 00 00 00 01 00 00 00 02 00 00 00 n_layers 1, n_kv_heads 1, head_dim 266 93 7b 02 c1 b0 1a a9 02 00 00 00 block_hash (unchanged), n_tokens 26e 76 7a 7e 76 fe 00 6e K codes, V codes25 49 12 3c 25 49 12 3b f32 scales 4/448, 1/448dd 13 89 2e crc32c of everything before itThe hash and fill are copied untouched. They identify the block’s tokens, not its numbers, so prefix-cache routing still works after the migration. The decoded values are 1, 2, 2.857, 4, 0.5, -1, 0, 0.25, and the difference from the original is the loss fp8 costs.
The interface
Section titled “The interface”The layout is the contract’s. An envelope is a 28-byte header ("TLKV", u16 version, u16 dtype, u32 n_blocks, then B, L, Hkv, D), followed by n records of u64 hash, u32 n_tokens, payload, and a trailing CRC-32C. The v2 envelope keeps the same header and block records; dtype 3 means fp8 e4m3. v1 payloads are f16 [L][2][Hkv][B][D]; v2 payloads are e4m3 [L][2][Hkv][B][D] followed by f32 [L][2][Hkv] scales.
pub fn decode(bytes: &[u8], expected: Shape) -> Result<Envelope, Error>; // reads v1 and v2pub fn encode(env: &Envelope, version: u16) -> Result<Vec<u8>, Error>; // writes v1 or v2pub fn upgrade_v1(bytes: &[u8], shape: Shape) -> Result<Vec<u8>, Error>; // v1 in, v2 out, never v2 inThe binary is kv-migrate <input> <output> <block_tokens> <layers> <kv_heads> <head_dim>. It exits 2 with a message on any error.
Building it step by step
Section titled “Building it step by step”Seven observations shape the solution, and the code comments refer back to them by number.
- A reader that trusts any byte before checking the whole envelope can hand a corrupt block to decode. So
decodechecks magic, version, dtype, shape, exact length, and CRC, in that order, and only then builds a single block. - Lengths come from untrusted header fields multiplied together.
L × 2 × Hkv × B × Dcan overflowusizeon a hostile header, and a wrapped product could match a short buffer. So every size is computed with checked arithmetic, and an overflow is its own error. - The version decides the dtype: v1 must say 1 (f16), v2 must say 3 (e4m3). A mismatched pair is ambiguous, so it is rejected rather than guessed.
- fp8 e4m3 has a largest finite value of 448 and about two significant decimal digits. Values must be scaled into range, and one scale per slab (layer, K or V, head) is the granularity at which magnitudes differ in attention. Choosing
scale = amax / 448maps the largest value onto 448 exactly, so nothing saturates. An all-zero slab would give scale 0, which cannot be divided by and which the reader rejects, so it gets 1.0. - Positions past
n_tokenscarry no data. Writing them as zero makes the bytes a pure function of the block’s real contents, which is what golden comparisons and content hashing need. A non-zero hash promises a full block, son_tokens == Bis enforced when the hash is set. - Quantization loses information. Converting v2 again would re-quantize already rounded values without any warning, so the upgrader accepts v1 only.
- A converter that crashes halfway must not leave a truncated file under the output name, where a later reader might pick it up. Write to
<output>.tmpand rename: a rename on one filesystem is atomic, so readers see the old file or the complete new one.
The code, annotated
Section titled “The code, annotated”The solution file packs each function onto a few long lines. The quotes below are reformatted one statement per line, with comments added; the logic is unchanged.
Sizes, with overflow as an error.
fn product(s: Shape) -> Result<usize, Error> { // elements per block: L * 2 (K and V) * Hkv * B * D, every multiply checked [s.layers as usize, 2, s.kv_heads as usize, s.block_tokens as usize, s.head_dim as usize] .into_iter() .try_fold(1usize, |a, b| a.checked_mul(b).ok_or(Error::Overflow))}fn slab_count(s: Shape) -> Result<usize, Error> { // one scale per (layer, K or V, head) (s.layers as usize).checked_mul(2) .and_then(|x| x.checked_mul(s.kv_heads as usize)) .ok_or(Error::Overflow)}CRC-32C, bit by bit with the reflected Castagnoli polynomial. It is slow per byte but needs no table or dependency, and the converter is offline.
fn crc32c(bytes: &[u8]) -> u32 { let mut c = !0u32; // initial value 0xFFFFFFFF for &b in bytes { c ^= b as u32; for _ in 0..8 { c = if c & 1 != 0 { (c >> 1) ^ 0x82f63b78 } else { c >> 1 }; } } !c // final XOR 0xFFFFFFFF}e4m3. Decoding follows the format directly: 1 sign bit, 4 exponent bits with bias 7, 3 mantissa bits, subnormals at exponent 0, and only S.1111.111 as NaN (there is no infinity). Encoding does not do bit tricks; it searches all 127 non-negative finite codes for the nearest, breaking ties toward an even code.
fn e4_decode(b: u8) -> f32 { let sign = if b & 0x80 == 0 { 1.0 } else { -1.0 }; let e = (b >> 3) & 15; let m = b & 7; if e == 15 && m == 7 { return f32::NAN } if e == 0 { sign * (m as f32 / 8.0) * 2f32.powi(-6) } // subnormal else { sign * (1.0 + m as f32 / 8.0) * 2f32.powi(e as i32 - 7) }}fn e4_encode(x: f32) -> Result<u8, Error> { if !x.is_finite() { return Err(Error::NonFinite) } let sign = if x.is_sign_negative() { 0x80 } else { 0 }; let a = x.abs().min(448.0); // clamp: the scale already keeps |x| <= 448 let mut best = 0u8; let mut err = f32::INFINITY; for b in 0..=0x7e { // 0x7f is NaN, never a candidate let v = e4_decode(b); let d = (v - a).abs(); if d < err || (d == err && b & 1 == 0) { // round to nearest, ties to even best = b; err = d; } } Ok(sign | best)}Because the codes are visited in increasing order and a tie only replaces best with an even code, 336 becomes 0x7a (even), as in the hand-worked example. The f16 helpers read_f16 and write_f16 play the same role for v1 and reject non-finite values and overflow past f16’s range.
Decode: validate everything, then build.
pub fn decode(bytes: &[u8], expected: Shape) -> Result<Envelope, Error> { if bytes.len() < HEADER + 4 { return Err(Error::Truncated) } // header plus CRC if &bytes[..4] != b"TLKV" { return Err(Error::Magic) } let version = u16at(bytes, 4); let dtype = u16at(bytes, 6); if version != V1 && version != V2 { return Err(Error::Version) } if dtype != if version == V1 { 1 } else { 3 } { return Err(Error::Dtype) } // step 3 let n = u32at(bytes, 8) as usize; let shape = Shape { block_tokens: u32at(bytes, 12), layers: u32at(bytes, 16), kv_heads: u32at(bytes, 20), head_dim: u32at(bytes, 24) }; if shape != expected { return Err(Error::Shape) } // the receiving pool's shape let elems = product(shape)?; let slabs = slab_count(shape)?; let payload = if version == V1 { elems.checked_mul(2).ok_or(Error::Overflow)? // two bytes per f16 } else { elems.checked_add(slabs.checked_mul(4).ok_or(Error::Overflow)?).ok_or(Error::Overflow)? }; let rec = 12usize.checked_add(payload).ok_or(Error::Overflow)?; // hash + fill + payload let len = HEADER.checked_add(n.checked_mul(rec).ok_or(Error::Overflow)?) .and_then(|x| x.checked_add(4)).ok_or(Error::Overflow)?; if len != bytes.len() { return Err(Error::Length) } // exact, not "at least" if crc32c(&bytes[..len - 4]) != u32at(bytes, len - 4) { return Err(Error::Checksum) } // ... only now walk the recordsThe length check comes before the CRC so the CRC never reads out of bounds, and both come before any block is built, so a corrupt envelope returns an error and nothing else.
let slab_elems = elems / slabs; // B * D values share one scale let mut blocks = Vec::with_capacity(n); let mut at = HEADER; for _ in 0..n { let hash = u64at(bytes, at); let fill = u32at(bytes, at + 8); // fill in 1..=B, and a registered (hashed) block must be full: step 5 if fill == 0 || fill > shape.block_tokens || (hash != 0 && fill != shape.block_tokens) { return Err(Error::Tokens) } let p = &bytes[at + 12..at + 12 + payload]; let mut values = Vec::with_capacity(elems); if version == V1 { for x in p.chunks_exact(2) { values.push(read_f16(u16::from_le_bytes([x[0], x[1]]))) } } else { for (i, &b) in p[..elems].iter().enumerate() { // the scales follow all the codes; element i belongs to slab i / slab_elems let s = elems + (i / slab_elems) * 4; let scale = f32::from_le_bytes(p[s..s + 4].try_into().unwrap()); if !scale.is_finite() || scale <= 0.0 { return Err(Error::Length) } values.push(e4_decode(b) * scale) } } blocks.push(Block { hash, n_tokens: fill, values }); at += rec; } Ok(Envelope { version, shape, blocks })}Encode: the scale rule and zero padding.
pub fn encode(env: &Envelope, version: u16) -> Result<Vec<u8>, Error> { // ... version check, sizes as in decode, header written little-endian with the version's dtype for block in &env.blocks { // the same token rules as the reader, so the writer cannot emit what a reader rejects if block.values.len() != elems || block.n_tokens == 0 || block.n_tokens > s.block_tokens || (block.hash != 0 && block.n_tokens != s.block_tokens) { return Err(Error::Tokens) } out.extend_from_slice(&block.hash.to_le_bytes()); out.extend_from_slice(&block.n_tokens.to_le_bytes()); if version == V1 { for (i, &x) in block.values.iter().enumerate() { let pos = (i % se) / (s.head_dim as usize); // token position inside the slab let v = if pos >= block.n_tokens as usize { 0.0 } else { x }; // zero the tail out.extend_from_slice(&write_f16(v)?.to_le_bytes()) } } else { let mut scales = Vec::with_capacity(slabs); for slab in 0..slabs { let x = &block.values[slab * se..(slab + 1) * se]; let max = x.iter().map(|v| v.abs()).fold(0.0f32, f32::max); scales.push(if max == 0.0 { 1.0 } else { max / 448.0 }); // step 4 } for (i, &x) in block.values.iter().enumerate() { let pos = (i % se) / (s.head_dim as usize); let v = if pos >= block.n_tokens as usize { 0.0 } else { x }; out.push(e4_encode(v / scales[i / se])?) } for scale in scales { out.extend_from_slice(&scale.to_le_bytes()) } // after all codes } } let crc = crc32c(&out); out.extend_from_slice(&crc.to_le_bytes()); Ok(out)}Here se is the slab size B × D. Inside a slab the layout is [B][D], so (i % se) / D is the token position, which is how the tail is found without a nested loop. The scale is taken over the whole slab; in the converter path the slab comes from a decoded v1 block whose tail is already zero, so this equals the contract’s “amax over filled positions”.
The upgrade and the process boundary.
pub fn upgrade_v1(bytes: &[u8], shape: Shape) -> Result<Vec<u8>, Error> { let env = decode(bytes, shape)?; // full validation, including CRC if env.version != V1 { return Err(Error::Version) } // step 6: never quantize twice encode(&env, V2)}fn run() -> Result<(), Box<dyn std::error::Error>> { let args: Vec<String> = env::args().collect(); if args.len() != 7 { return Err("usage: kv-migrate <input> <output> <block_tokens> <layers> <kv_heads> <head_dim>".into()); } let n = |i: usize| args[i].parse::<u32>().map_err(|e| format!("invalid dimension {}: {e}", args[i])); let shape = Shape { block_tokens: n(3)?, layers: n(4)?, kv_heads: n(5)?, head_dim: n(6)? }; let input = fs::read(&args[1])?; let output = upgrade_v1(&input, shape)?; // all work in memory first let tmp = args[2].to_owned() + ".tmp"; fs::write(&tmp, output)?; fs::rename(tmp, &args[2])?; // step 7: atomic replace Ok(())}The expected shape is a command-line argument, not read from the input, so the operator states the receiving pool’s dimensions and a file for another model is refused with Shape.
Full solution: lib.rs, main.rs.
Why this design
Section titled “Why this design”Decoding and encoding are linear in the envelope size. The brute-force e4m3 encoder does 127 comparisons per element, which is fine for an offline converter and easy to check against the format definition; the contract’s reference for e4m3 conversion in the C pool is tinyllm/numerics.h.
The reader validates, then builds, rather than streaming blocks out as they are parsed. A streaming reader would have handed earlier blocks to the caller before discovering a bad CRC at the end.
The format uses per-slab scales rather than one scale per block or per element. A single block scale lets one large head crush every other head into a few codes; per-element scales cost 4 bytes per byte of data and defeat the purpose of fp8.
The conversion is a separate offline binary rather than an in-process migration. Python and the engine meet at a documented file boundary, the conversion can be rerun on the original inputs, and a rollback is just keeping the v1 files.
One tradeoff is accepted knowingly: v2 is lossy. In the hand-worked example the value 3 becomes 2.857. The migration is safe only because readers learn v2 before writers emit it, and v1 stays readable through the rollback window.
What can go wrong
Section titled “What can go wrong”A correct solution handles each of the following cases:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand example converts to the golden bytes | unit | Converts the hand-worked envelope and compares the exact bytes, then checks hash, fill, and values within 0.2. | Establishes the migration result by hand before broader cases. |
| both formats round-trip with their own dtype | unit | Reads and writes v1 and v2 with the correct dtype for each. | Lets readers roll forward while retaining rollback support. |
| corruption is rejected before any block is returned | boundary | Rejects bad CRC before exposing payload data. | Prevents corrupted KV blocks from reaching decode. |
| shape mismatch and unknown version are rejected | boundary | Rejects incompatible dimensions and unsupported format versions. | Keeps peers from misreading valid-looking bytes. |
| a partial tail is zero-filled and never claims a full hash | boundary | Makes padding deterministic and avoids a false full-block hash. | Prevents dedupe from treating incomplete blocks as complete. |
| an all-zero slab uses unit scale | boundary | Gives an all-zero slab finite unit scale. | Avoids invalid quantization metadata. |
| the upgrader refuses a v2 input | boundary | Refuses a second conversion. | Prevents silent repeated quantization. |
| the process converter writes its output atomically | integration | Exercises the subprocess converter and atomic output path. | Keeps Python and Rust separated by the documented file boundary. |
Warning: Emitting v2 before all readers advertise support means a mixed-version peer rejects or misreads a block.
decodereads both versions, so readers can be upgraded first, andencodewrites either version for the rollback window.
Returning data before validating the envelope CRC lets corrupt blocks reach the scheduler as plausible KV data. decode checks the exact length and the CRC before the record loop builds any Block, as the annotated decoder shows.
Re-converting an already quantized v2 block adds loss without an explicit error. upgrade_v1 returns Error::Version for any input that is not v1.
Warning: Unchecked size arithmetic on header fields lets a crafted header wrap the size and pass the length check.
product,slab_count, and every size computation usechecked_mulandchecked_addand fail withError::Overflow.
Where this leads
Section titled “Where this leads”This migration rests on several earlier pieces. The Deprecation policy sets the rollback window during which v1 must stay readable. An architecture decision record, as described in Software Engineering, records why the format changes and the rollout order (readers first). The contract course/contracts/formats/kv-block.md fixes the byte layout, the scale rule, and the reader rules this converter implements. And Disaggregated prefill and decode in AI Engineering is the KV transfer path that carries these envelopes between engines.
Next comes the drill. In The KV format v2 migration, a v1-only reader meets a v2 writer, and the rollout order decides whether that is a clean refusal or an outage.
Further reading
Section titled “Further reading”- The worked v1 example in
kv-block.md: decode the v1 bytes by hand, then compare them with the v2 bytes worked above. - FP8 and microscaling formats in Mathematics: why e4m3 tops out at 448 and how block scaling generalises the per-slab scale.
- Kleppmann, Designing Data-Intensive Applications, ch. 4, on encoding and evolution.
Key terms
Section titled “Key terms”- Export envelope: the KV file and wire format: a 28-byte header, block records of hash, fill, and payload, and a trailing CRC-32C.
- fp8 E4M3: an 8-bit float with 1 sign, 4 exponent (bias 7), and 3 mantissa bits; largest finite value 448, no infinity.
- Slab: the
B × Dvalues of one (layer, K or V, head) in a block, which share one f32 scale. - Per-slab scale:
amax / 448for the slab, or 1.0 when the slab is all zero. - Readers first: the rollout order in which every reader accepts the new format before any writer emits it.
- Atomic rename: writing to a temporary file and renaming it over the target, so readers see either the old file or the complete new one.
Summary
Section titled “Summary”- The v2 envelope keeps the 28-byte header and block records; dtype 3 means fp8 e4m3.
- Each (layer, K or V, head) slab carries one f32 scale, the maximum absolute value divided by 448, or 1.0 for all-zero data.
- The reader validates magic, version, dtype, shape, exact length, and CRC, with checked arithmetic, before returning any block.
- Readers learn v2 before writers emit it, and v1 stays readable through the rollback window, because v2 is lossy.
- The offline converter validates the v1 CRC and dimensions, refuses v2 input, and writes its v2 output atomically.
Review questions
Section titled “Review questions”- Why is the length compared with
!=and not<?Answer
Trailing or missing bytes mean the header's `n_blocks` or shape does not describe the buffer. If extra bytes were tolerated, the CRC would sit at `len - 4` computed from the header while the buffer ended elsewhere, and two readers could disagree about which bytes are covered. An exact length makes the CRC's position, and therefore what it protects, unambiguous. - Why does an all-zero slab get scale 1.0 instead of 0?
Answer
Encoding divides by the scale, so 0 would give NaN codes, and the reader rejects a scale that is not finite and positive. Any positive scale decodes zero codes to zero; 1.0 is the simplest finite choice. - What goes wrong if
upgrade_v1accepted a v2 input?Answer
It would decode the fp8 values, compute new scales, and quantize again. Each pass can move values to different codes, so data degrades silently with every rerun of the migration. Refusing with `Version` makes the operation idempotent in effect: rerunning on the original v1 files gives the same output. - Why write to
<output>.tmpand rename instead of writing<output>directly?Answer
A crash or full disk during `fs::write` would leave a truncated file under the real name, and a reader might load it. A rename within one filesystem is atomic, so the output name always holds either nothing (or the previous file) or a complete, CRC-valid envelope. - Why does a block with a non-zero hash have to be full?
Answer
The hash is the prefix-cache identity of exactly `B` tokens. A partial block has no stable identity yet; if it claimed one, the prefix cache could match a later request against a block missing some of its tokens. - In the hand-worked example, why does the K value 3 decode to about 2.857?
Answer
With `scale = 4/448`, 3 maps to 336, which lies exactly halfway between the e4m3 values 320 (`0x7a`) and 352 (`0x7b`). Round-to-nearest-even picks `0x7a`, and `320 × 4/448 ≈ 2.857`.