aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-kv-store / src / identity.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | // Prefix-chained chunk keys adapt the rolling-hash idea of LMCache's |
| 17 | // `TokenHasher` (lmcache/v1/multiprocess/token_hasher.py, lines 30-52, 60-70, |
| 18 | // 183-190 at 4d69cdc4). LMCache is Apache-2.0, Copyright LMCache contributors. |
| 19 | // No LMCache code is copied. This file hashes with SHA-256 over a different |
| 20 | // byte layout (ADR 0003 section 1) so host and native share one derivation. |
| 21 | |
| 22 | //! Versioned chunk identity: namespace id and prefix-chained chunk keys |
| 23 | //! (ADR 0003 section 1). Pure functions, no I/O, no heap use while hashing. |
| 24 | |
| 25 | use crate::error::KvError; |
| 26 | use crate::record::{segment_count, ChunkHeader, FLAG_PARTIAL_TAIL, FORMAT_VERSION, MAX_SEGMENTS}; |
| 27 | use aien_platform::ObjectId; |
| 28 | use alloc::vec::Vec; |
| 29 | use sha2::{Digest, Sha256}; |
| 30 | |
| 31 | /// Fingerprint of everything that must be equal for stored bytes to be reusable. |
| 32 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 33 | pub struct NamespaceId(pub [u8; 32]); |
| 34 | |
| 35 | /// Key of one chunk; carries the prefix chain. Wraps the platform `ObjectId`. |
| 36 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 37 | pub struct ChunkKey(pub ObjectId); |
| 38 | |
| 39 | impl ChunkKey { |
| 40 | pub fn as_bytes(&self) -> &[u8; 32] { |
| 41 | &self.0 .0 |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl PartialOrd for ChunkKey { |
| 46 | fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { |
| 47 | Some(self.cmp(other)) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl Ord for ChunkKey { |
| 52 | fn cmp(&self, other: &Self) -> core::cmp::Ordering { |
| 53 | self.as_bytes().cmp(other.as_bytes()) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// KV element type codes (ADR 1.2 field 9). |
| 58 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 59 | #[repr(u8)] |
| 60 | pub enum KvDtype { |
| 61 | Fp4 = 1, |
| 62 | Fp8 = 2, |
| 63 | Bf16 = 3, |
| 64 | Fp16 = 4, |
| 65 | Fp32 = 5, |
| 66 | } |
| 67 | |
| 68 | impl KvDtype { |
| 69 | pub fn from_u8(v: u8) -> Option<Self> { |
| 70 | match v { |
| 71 | 1 => Some(Self::Fp4), |
| 72 | 2 => Some(Self::Fp8), |
| 73 | 3 => Some(Self::Bf16), |
| 74 | 4 => Some(Self::Fp16), |
| 75 | 5 => Some(Self::Fp32), |
| 76 | _ => None, |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Payload byte format (ADR 1.2 field 11). |
| 82 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 83 | #[repr(u8)] |
| 84 | pub enum BackendFormat { |
| 85 | /// Host paged pool v1: bf16 blocks in the pool's own layout (ADR 2.2). |
| 86 | HostPagedPoolV1 = 1, |
| 87 | /// Native f32 decode state v1: strided per layer (ADR 2.3). |
| 88 | NativeF32DecodeStateV1 = 2, |
| 89 | } |
| 90 | |
| 91 | impl BackendFormat { |
| 92 | pub fn from_u8(v: u8) -> Option<Self> { |
| 93 | match v { |
| 94 | 1 => Some(Self::HostPagedPoolV1), |
| 95 | 2 => Some(Self::NativeF32DecodeStateV1), |
| 96 | _ => None, |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Llama-3 RoPE scaling (ADR 1.2 field 7). |
| 102 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 103 | pub struct RopeScaling { |
| 104 | pub factor: f64, |
| 105 | pub low_freq_factor: f64, |
| 106 | pub high_freq_factor: f64, |
| 107 | pub original_max_position_embeddings: u64, |
| 108 | } |
| 109 | |
| 110 | /// Byte strides of the pool layout (ADR 1.2 field 10; `KvLayout` in aien-kv-cache). |
| 111 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 112 | pub struct LayoutStrides { |
| 113 | pub head_stride: u64, |
| 114 | pub token_stride: u64, |
| 115 | pub kv_plane_stride: u64, |
| 116 | pub layer_stride: u64, |
| 117 | pub block_stride: u64, |
| 118 | pub element_bytes: u64, |
| 119 | } |
| 120 | |
| 121 | /// Every input of the namespace id, in ADR 1.2 order. Strings are borrowed so a |
| 122 | /// caller builds this without copying model metadata. |
| 123 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 124 | pub struct NamespaceFields<'a> { |
| 125 | pub model_sha256: [u8; 32], |
| 126 | /// At most 255 bytes (u8 length prefix). |
| 127 | pub model_digest_kind: &'a str, |
| 128 | /// At most 65535 bytes (u16 length prefix). |
| 129 | pub model_id: &'a str, |
| 130 | pub num_layers: u32, |
| 131 | pub num_kv_heads: u32, |
| 132 | pub head_dim: u32, |
| 133 | pub block_size: u32, |
| 134 | pub rope_theta: f32, |
| 135 | pub rope_scaling: Option<RopeScaling>, |
| 136 | pub qk_norm: bool, |
| 137 | pub dtype: KvDtype, |
| 138 | pub layout: LayoutStrides, |
| 139 | pub backend_format: BackendFormat, |
| 140 | pub chunk_tokens: u32, |
| 141 | /// At most 64 bytes (METRICS_AND_SETTINGS `AIEN_KV_STORE_NAMESPACE`). |
| 142 | pub sharing_namespace: &'a str, |
| 143 | /// `ComputeConfig::digest_with_engine()` (ADR 1.2 field 14, sections 1.2.1 |
| 144 | /// and 1.2.2): every other number that changes what the forward pass |
| 145 | /// computes, and the engine that computed it. |
| 146 | pub compute_config_digest: [u8; 32], |
| 147 | } |
| 148 | |
| 149 | pub const MAX_SHARING_NAMESPACE_BYTES: usize = 64; |
| 150 | /// At most 255 bytes (u8 length prefix). |
| 151 | pub const MAX_ARITH_ID_BYTES: usize = 255; |
| 152 | |
| 153 | /// Activation function code (ADR 1.2.1 field 7). The loader refuses everything |
| 154 | /// but silu today; the byte exists so a future activation cannot alias. |
| 155 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 156 | #[repr(u8)] |
| 157 | pub enum HiddenAct { |
| 158 | Silu = 1, |
| 159 | } |
| 160 | |
| 161 | /// Computation-affecting settings not already in the namespace fields (ADR |
| 162 | /// 1.2.1). Built from the resolved `ModelConfig` by `aien-runtime` (cut C6a), |
| 163 | /// never from raw `config.json`. |
| 164 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 165 | pub struct ComputeConfig<'a> { |
| 166 | pub num_heads: u32, |
| 167 | pub hidden_dim: u64, |
| 168 | pub intermediate_dim: u64, |
| 169 | pub vocab_size: u64, |
| 170 | pub rms_norm_eps: f32, |
| 171 | pub tie_word_embeddings: bool, |
| 172 | pub hidden_act: HiddenAct, |
| 173 | /// `TensorBackend::name()`; at most 255 bytes. |
| 174 | pub arith_id: &'a str, |
| 175 | /// `KV_ARITH_EPOCH`: bumped by any change that alters forward-pass numbers. |
| 176 | pub arith_epoch: u32, |
| 177 | } |
| 178 | |
| 179 | impl ComputeConfig<'_> { |
| 180 | /// Compute-only digest of ADR 1.2.1: `SHA-256("AIEN-PKV-CFG-V1\0" || |
| 181 | /// num_heads u32le || hidden_dim u64le || intermediate_dim u64le || |
| 182 | /// vocab_size u64le || rms_norm_eps bits u32le || tie u8 || hidden_act u8 || |
| 183 | /// arith_id u8-len + bytes || arith_epoch u32le)`. Since sc#504 this is |
| 184 | /// **not** namespace field 14: field 14 is |
| 185 | /// [`ComputeConfig::digest_with_engine`], which also binds the engine. |
| 186 | pub fn digest(&self) -> Result<[u8; 32], KvError> { |
| 187 | let mut h = Sha256::new(); |
| 188 | h.update(CFG_DOMAIN); |
| 189 | self.put_fields(&mut h)?; |
| 190 | Ok(h.finalize().into()) |
| 191 | } |
| 192 | |
| 193 | /// Namespace field 14 (ADR 1.2.2): `SHA-256("AIEN-PKV-CFG-V2\0" || fields 1 |
| 194 | /// to 9 exactly as in [`ComputeConfig::digest`] || weight_format u8 || |
| 195 | /// engine_build_id u8-len + bytes || rounding_class u8-len + bytes || |
| 196 | /// engine_config_digest)`. Refused when the build id or the rounding class |
| 197 | /// is empty (`FieldEmpty`) or longer than 255 bytes (`FieldTooLong`). |
| 198 | pub fn digest_with_engine(&self, engine: &EngineIdentity<'_>) -> Result<[u8; 32], KvError> { |
| 199 | let mut h = Sha256::new(); |
| 200 | h.update(CFG_ENGINE_DOMAIN); |
| 201 | self.put_fields(&mut h)?; |
| 202 | h.update([engine.weight_format as u8]); // 10 |
| 203 | put_required_u8_len_str(&mut h, "engine_build_id", engine.engine_build_id)?; // 11 |
| 204 | put_required_u8_len_str(&mut h, "rounding_class", engine.rounding_class)?; // 12 |
| 205 | h.update(engine.engine_config_digest); // 13 |
| 206 | Ok(h.finalize().into()) |
| 207 | } |
| 208 | |
| 209 | fn put_fields(&self, h: &mut Sha256) -> Result<(), KvError> { |
| 210 | h.update(self.num_heads.to_le_bytes()); // 1 |
| 211 | h.update(self.hidden_dim.to_le_bytes()); // 2 |
| 212 | h.update(self.intermediate_dim.to_le_bytes()); // 3 |
| 213 | h.update(self.vocab_size.to_le_bytes()); // 4 |
| 214 | h.update(self.rms_norm_eps.to_bits().to_le_bytes()); // 5 |
| 215 | h.update([u8::from(self.tie_word_embeddings)]); // 6 |
| 216 | h.update([self.hidden_act as u8]); // 7 |
| 217 | if self.arith_id.len() > MAX_ARITH_ID_BYTES { |
| 218 | return Err(KvError::FieldTooLong("arith_id")); |
| 219 | } |
| 220 | put_u8_len_str(h, "arith_id", self.arith_id)?; // 8 |
| 221 | h.update(self.arith_epoch.to_le_bytes()); // 9 |
| 222 | Ok(()) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /// How the engine holds the weights it computes with (ADR 1.2.2). One |
| 227 | /// checkpoint directory (one file digest) can be loaded several ways, and each |
| 228 | /// gives different K/V bytes. |
| 229 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 230 | #[repr(u8)] |
| 231 | pub enum WeightFormat { |
| 232 | /// The weights are used in the element type the file stores them in. |
| 233 | AsFile = 1, |
| 234 | /// Converted to bf16 at load. |
| 235 | Bf16 = 2, |
| 236 | /// Expert (MoE) weights quantized to fp8 at load, the rest as loaded. |
| 237 | Fp8Experts = 3, |
| 238 | /// Every linear weight quantized to fp8 at load. |
| 239 | Fp8All = 4, |
| 240 | } |
| 241 | |
| 242 | impl WeightFormat { |
| 243 | pub fn from_u8(v: u8) -> Option<Self> { |
| 244 | match v { |
| 245 | 1 => Some(Self::AsFile), |
| 246 | 2 => Some(Self::Bf16), |
| 247 | 3 => Some(Self::Fp8Experts), |
| 248 | 4 => Some(Self::Fp8All), |
| 249 | _ => None, |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// Stable name for logs and settings. |
| 254 | pub fn as_str(self) -> &'static str { |
| 255 | match self { |
| 256 | Self::AsFile => "as-file", |
| 257 | Self::Bf16 => "bf16", |
| 258 | Self::Fp8Experts => "fp8-experts", |
| 259 | Self::Fp8All => "fp8-all", |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// MoE shape and run-time numeric switches of the engine (ADR 1.2.2), built by |
| 265 | /// the engine caller. A dense model has zero experts. Whole-prompt prefill |
| 266 | /// changes activation rounding, so it changes the K/V bytes. |
| 267 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 268 | pub struct EngineConfig<'a> { |
| 269 | pub num_experts: u32, |
| 270 | pub experts_per_token: u32, |
| 271 | pub expert_intermediate_dim: u64, |
| 272 | pub whole_prompt_prefill: bool, |
| 273 | pub device_router: bool, |
| 274 | /// Matrix-multiply path label (for example `gemm`, `gemv`); 1 to 255 bytes. |
| 275 | pub matmul_path: &'a str, |
| 276 | } |
| 277 | |
| 278 | impl EngineConfig<'_> { |
| 279 | /// `SHA-256("AIEN-PKV-ENG-V1\0" || num_experts u32le || experts_per_token |
| 280 | /// u32le || expert_intermediate_dim u64le || whole_prompt_prefill u8 || |
| 281 | /// device_router u8 || matmul_path u8-len + bytes)`. |
| 282 | pub fn digest(&self) -> Result<[u8; 32], KvError> { |
| 283 | let mut h = Sha256::new(); |
| 284 | h.update(ENG_DOMAIN); |
| 285 | h.update(self.num_experts.to_le_bytes()); |
| 286 | h.update(self.experts_per_token.to_le_bytes()); |
| 287 | h.update(self.expert_intermediate_dim.to_le_bytes()); |
| 288 | h.update([u8::from(self.whole_prompt_prefill)]); |
| 289 | h.update([u8::from(self.device_router)]); |
| 290 | put_required_u8_len_str(&mut h, "matmul_path", self.matmul_path)?; |
| 291 | Ok(h.finalize().into()) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | /// The engine that computes the K/V (ADR 1.2.2, sc#504). Required by |
| 296 | /// [`ComputeConfig::digest_with_engine`] and by the runtime's persistence |
| 297 | /// wiring: there is no default, so every caller states each value. |
| 298 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 299 | pub struct EngineIdentity<'a> { |
| 300 | /// Weights as loaded, not as stored: one file digest can be loaded as |
| 301 | /// bf16 or fp8. |
| 302 | pub weight_format: WeightFormat, |
| 303 | /// Engine and kernel build (for example engine commit plus the linked |
| 304 | /// kernel archive digest); 1 to 255 bytes. |
| 305 | pub engine_build_id: &'a str, |
| 306 | /// Numeric rounding class of the arithmetic (for example backend name plus |
| 307 | /// `KV_ARITH_EPOCH`); 1 to 255 bytes. |
| 308 | pub rounding_class: &'a str, |
| 309 | /// [`EngineConfig::digest`], or the engine's own 32-byte digest over its |
| 310 | /// MoE shape and numeric run switches. |
| 311 | pub engine_config_digest: [u8; 32], |
| 312 | } |
| 313 | |
| 314 | /// V2 since sc#504 (field 14 binds the engine), so no V1 namespace can match. |
| 315 | const NS_DOMAIN: &[u8] = b"AIEN-PKV-NS-V2\0"; |
| 316 | const CHUNK_DOMAIN: &[u8] = b"AIEN-PKV-CHUNK-V1\0"; |
| 317 | const CFG_DOMAIN: &[u8] = b"AIEN-PKV-CFG-V1\0"; |
| 318 | const CFG_ENGINE_DOMAIN: &[u8] = b"AIEN-PKV-CFG-V2\0"; |
| 319 | const ENG_DOMAIN: &[u8] = b"AIEN-PKV-ENG-V1\0"; |
| 320 | |
| 321 | /// A required string: empty is refused, so an unknown value cannot alias. |
| 322 | fn put_required_u8_len_str(h: &mut Sha256, name: &'static str, s: &str) -> Result<(), KvError> { |
| 323 | if s.is_empty() { |
| 324 | return Err(KvError::FieldEmpty(name)); |
| 325 | } |
| 326 | put_u8_len_str(h, name, s) |
| 327 | } |
| 328 | |
| 329 | fn put_u8_len_str(h: &mut Sha256, name: &'static str, s: &str) -> Result<(), KvError> { |
| 330 | let len = u8::try_from(s.len()).map_err(|_| KvError::FieldTooLong(name))?; |
| 331 | h.update([len]); |
| 332 | h.update(s.as_bytes()); |
| 333 | Ok(()) |
| 334 | } |
| 335 | |
| 336 | fn put_u16_len_str(h: &mut Sha256, name: &'static str, s: &str) -> Result<(), KvError> { |
| 337 | let len = u16::try_from(s.len()).map_err(|_| KvError::FieldTooLong(name))?; |
| 338 | h.update(len.to_le_bytes()); |
| 339 | h.update(s.as_bytes()); |
| 340 | Ok(()) |
| 341 | } |
| 342 | |
| 343 | impl NamespaceFields<'_> { |
| 344 | fn check_geometry(&self) -> Result<(), KvError> { |
| 345 | if self.block_size == 0 |
| 346 | || self.chunk_tokens == 0 |
| 347 | || self.num_layers == 0 |
| 348 | || self.num_kv_heads == 0 |
| 349 | || self.head_dim == 0 |
| 350 | || !self.chunk_tokens.is_multiple_of(self.block_size) |
| 351 | { |
| 352 | return Err(KvError::InvalidGeometry); |
| 353 | } |
| 354 | // A zero byte factor makes every payload zero bytes long. |
| 355 | let zero_bytes = match self.backend_format { |
| 356 | BackendFormat::HostPagedPoolV1 => self.layout.block_stride == 0, |
| 357 | BackendFormat::NativeF32DecodeStateV1 => self.layout.element_bytes == 0, |
| 358 | }; |
| 359 | if zero_bytes { |
| 360 | return Err(KvError::InvalidGeometry); |
| 361 | } |
| 362 | // A host chunk is one segment per pool block and the digest table holds |
| 363 | // at most `MAX_SEGMENTS` = 119 (ADR 2.1 item 3, amended by section 20): |
| 364 | // `chunk_blocks` is capped at 119 there. |
| 365 | if self.backend_format == BackendFormat::HostPagedPoolV1 |
| 366 | && self.chunk_tokens / self.block_size > MAX_SEGMENTS as u32 |
| 367 | { |
| 368 | return Err(KvError::TooManySegments); |
| 369 | } |
| 370 | Ok(()) |
| 371 | } |
| 372 | |
| 373 | /// `SHA-256("AIEN-PKV-NS-V2\0" || fields)` (ADR 1.2). |
| 374 | pub fn namespace_id(&self) -> Result<NamespaceId, KvError> { |
| 375 | self.check_geometry()?; |
| 376 | if self.sharing_namespace.len() > MAX_SHARING_NAMESPACE_BYTES { |
| 377 | return Err(KvError::FieldTooLong("sharing_namespace")); |
| 378 | } |
| 379 | let mut h = Sha256::new(); |
| 380 | h.update(NS_DOMAIN); |
| 381 | h.update(FORMAT_VERSION.to_le_bytes()); // 1 |
| 382 | h.update(self.model_sha256); // 2 |
| 383 | put_u8_len_str(&mut h, "model_digest_kind", self.model_digest_kind)?; // 3 |
| 384 | put_u16_len_str(&mut h, "model_id", self.model_id)?; // 4 |
| 385 | for v in [ |
| 386 | self.num_layers, |
| 387 | self.num_kv_heads, |
| 388 | self.head_dim, |
| 389 | self.block_size, |
| 390 | ] { |
| 391 | h.update(v.to_le_bytes()); // 5 |
| 392 | } |
| 393 | h.update(self.rope_theta.to_bits().to_le_bytes()); // 6 |
| 394 | match &self.rope_scaling { |
| 395 | // 7 |
| 396 | None => h.update([0u8]), |
| 397 | Some(r) => { |
| 398 | h.update([1u8]); |
| 399 | h.update(r.factor.to_bits().to_le_bytes()); |
| 400 | h.update(r.low_freq_factor.to_bits().to_le_bytes()); |
| 401 | h.update(r.high_freq_factor.to_bits().to_le_bytes()); |
| 402 | h.update(r.original_max_position_embeddings.to_le_bytes()); |
| 403 | } |
| 404 | } |
| 405 | h.update([u8::from(self.qk_norm)]); // 8 |
| 406 | h.update([self.dtype as u8]); // 9 |
| 407 | let l = &self.layout; // 10 |
| 408 | for v in [ |
| 409 | l.head_stride, |
| 410 | l.token_stride, |
| 411 | l.kv_plane_stride, |
| 412 | l.layer_stride, |
| 413 | l.block_stride, |
| 414 | l.element_bytes, |
| 415 | ] { |
| 416 | h.update(v.to_le_bytes()); |
| 417 | } |
| 418 | h.update([self.backend_format as u8]); // 11 |
| 419 | h.update(self.chunk_tokens.to_le_bytes()); // 12 |
| 420 | put_u16_len_str(&mut h, "sharing_namespace", self.sharing_namespace)?; // 13 |
| 421 | h.update(self.compute_config_digest); // 14 |
| 422 | Ok(NamespaceId(h.finalize().into())) |
| 423 | } |
| 424 | |
| 425 | /// Payload size the writer must produce for `token_count` positions |
| 426 | /// (ADR 2.2 and 2.3). Checked arithmetic, no allocation. |
| 427 | /// |
| 428 | /// Host: `ceil(token_count / block_size) * block_stride`. Native: per layer, |
| 429 | /// K rows then V rows of `token_count * kv_dim` elements. |
| 430 | pub fn expected_payload_len(&self, token_count: u32) -> Result<u64, KvError> { |
| 431 | self.check_geometry()?; |
| 432 | if token_count == 0 || token_count > self.chunk_tokens { |
| 433 | return Err(KvError::TokenCountOutOfRange); |
| 434 | } |
| 435 | match self.backend_format { |
| 436 | BackendFormat::HostPagedPoolV1 => { |
| 437 | let blocks = u64::from(token_count.div_ceil(self.block_size)); |
| 438 | blocks |
| 439 | .checked_mul(self.layout.block_stride) |
| 440 | .ok_or(KvError::Overflow) |
| 441 | } |
| 442 | BackendFormat::NativeF32DecodeStateV1 => { |
| 443 | let kv_dim = u64::from(self.num_kv_heads) |
| 444 | .checked_mul(u64::from(self.head_dim)) |
| 445 | .ok_or(KvError::Overflow)?; |
| 446 | u64::from(self.num_layers) |
| 447 | .checked_mul(2) |
| 448 | .and_then(|v| v.checked_mul(u64::from(token_count))) |
| 449 | .and_then(|v| v.checked_mul(kv_dim)) |
| 450 | .and_then(|v| v.checked_mul(self.layout.element_bytes)) |
| 451 | .ok_or(KvError::Overflow) |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | /// Bytes per payload segment for a chunk of `token_count` positions (ADR |
| 457 | /// 12 H8): host = `layout.block_stride` (one pool block); native = the whole |
| 458 | /// payload (one segment). |
| 459 | pub fn segment_bytes(&self, token_count: u32) -> Result<u64, KvError> { |
| 460 | match self.backend_format { |
| 461 | BackendFormat::HostPagedPoolV1 => { |
| 462 | self.check_geometry()?; |
| 463 | if token_count == 0 || token_count > self.chunk_tokens { |
| 464 | return Err(KvError::TokenCountOutOfRange); |
| 465 | } |
| 466 | Ok(self.layout.block_stride) |
| 467 | } |
| 468 | BackendFormat::NativeF32DecodeStateV1 => self.expected_payload_len(token_count), |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /// Number of payload segments for `token_count` positions; at most |
| 473 | /// `MAX_SEGMENTS`. |
| 474 | pub fn segment_count(&self, token_count: u32) -> Result<u32, KvError> { |
| 475 | let payload_len = self.expected_payload_len(token_count)?; |
| 476 | segment_count(payload_len, self.segment_bytes(token_count)?) |
| 477 | } |
| 478 | |
| 479 | /// Build the header a writer would emit (or a reader would expect) for one |
| 480 | /// chunk. Sets `partial_tail` when `token_count < chunk_tokens`; fills |
| 481 | /// `payload_len` from `expected_payload_len`. |
| 482 | pub fn chunk_header( |
| 483 | &self, |
| 484 | namespace_id: &NamespaceId, |
| 485 | chunk_key: ChunkKey, |
| 486 | parent: Option<&ChunkKey>, |
| 487 | first_position: u32, |
| 488 | token_count: u32, |
| 489 | written_unix_ns: u64, |
| 490 | ) -> Result<ChunkHeader, KvError> { |
| 491 | let payload_len = self.expected_payload_len(token_count)?; |
| 492 | if !first_position.is_multiple_of(self.chunk_tokens) { |
| 493 | return Err(KvError::PositionMismatch); |
| 494 | } |
| 495 | Ok(ChunkHeader { |
| 496 | namespace_id: *namespace_id, |
| 497 | chunk_key, |
| 498 | parent_key: parent.map_or([0u8; 32], |p| *p.as_bytes()), |
| 499 | model_sha256: self.model_sha256, |
| 500 | first_position, |
| 501 | token_count, |
| 502 | chunk_tokens: self.chunk_tokens, |
| 503 | block_size: self.block_size, |
| 504 | num_layers: self.num_layers, |
| 505 | num_kv_heads: self.num_kv_heads, |
| 506 | head_dim: self.head_dim, |
| 507 | dtype: self.dtype as u8, |
| 508 | backend_format: self.backend_format as u8, |
| 509 | flags: if token_count < self.chunk_tokens { |
| 510 | FLAG_PARTIAL_TAIL |
| 511 | } else { |
| 512 | 0 |
| 513 | }, |
| 514 | payload_len, |
| 515 | written_unix_ns, |
| 516 | }) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | /// One link of the chain (ADR 1.3). `parent` is `None` for the first chunk |
| 521 | /// (hashed as 32 zero bytes). `first_position` is the absolute position of |
| 522 | /// `tokens[0]`. |
| 523 | pub fn chunk_key( |
| 524 | namespace: &NamespaceId, |
| 525 | parent: Option<&ChunkKey>, |
| 526 | first_position: u32, |
| 527 | tokens: &[u32], |
| 528 | ) -> Result<ChunkKey, KvError> { |
| 529 | let token_count = u32::try_from(tokens.len()).map_err(|_| KvError::Overflow)?; |
| 530 | if token_count == 0 { |
| 531 | return Err(KvError::TokenCountOutOfRange); |
| 532 | } |
| 533 | first_position |
| 534 | .checked_add(token_count) |
| 535 | .ok_or(KvError::Overflow)?; |
| 536 | let mut h = Sha256::new(); |
| 537 | h.update(CHUNK_DOMAIN); |
| 538 | h.update(namespace.0); |
| 539 | h.update(parent.map_or([0u8; 32], |p| *p.as_bytes())); |
| 540 | h.update(first_position.to_le_bytes()); |
| 541 | h.update(token_count.to_le_bytes()); |
| 542 | for t in tokens { |
| 543 | h.update(t.to_le_bytes()); |
| 544 | } |
| 545 | Ok(ChunkKey(ObjectId(h.finalize().into()))) |
| 546 | } |
| 547 | |
| 548 | /// Keys for every chunk of `tokens`: full chunks of `chunk_tokens`, then an |
| 549 | /// optional partial tail keyed with its exact token count. |
| 550 | pub fn chunk_chain( |
| 551 | namespace: &NamespaceId, |
| 552 | chunk_tokens: u32, |
| 553 | tokens: &[u32], |
| 554 | ) -> Result<Vec<ChunkKey>, KvError> { |
| 555 | if chunk_tokens == 0 { |
| 556 | return Err(KvError::InvalidGeometry); |
| 557 | } |
| 558 | let per = chunk_tokens as usize; |
| 559 | let mut keys: Vec<ChunkKey> = Vec::with_capacity(tokens.len().div_ceil(per)); |
| 560 | for (i, chunk) in tokens.chunks(per).enumerate() { |
| 561 | let first_position = u32::try_from(i) |
| 562 | .ok() |
| 563 | .and_then(|i| i.checked_mul(chunk_tokens)) |
| 564 | .ok_or(KvError::Overflow)?; |
| 565 | let key = chunk_key(namespace, keys.last(), first_position, chunk)?; |
| 566 | keys.push(key); |
| 567 | } |
| 568 | Ok(keys) |
| 569 | } |