diff --git a/crates/vetta-infer-ld/src/dspark.rs b/crates/vetta-infer-ld/src/dspark.rs new file mode 100644 index 0000000..7396aa3 --- /dev/null +++ b/crates/vetta-infer-ld/src/dspark.rs @@ -0,0 +1,268 @@ +//! DSpark drafter (MTP head) weight manifest, layout check and loader. +//! +//! Step 1 of the reviewer's drafter guide (review/2026-12-02-…): load +//! `mtp.safetensors` and validate its layout BEFORE any speculative kernel runs +//! (mirrors the reference `ink_dspark_layout_check`); a missing/mismatched file +//! disables the drafter gracefully instead of corrupting generation. +//! +//! The manifest/layout check is CPU-only (safe Rust, checked shapes); the GPU +//! upload (`load`) is behind the `hip` feature. QKV and gate/up are fused at +//! load time (reviewer tip) so the draft step issues one GEMM each. + +use crate::SafetensorsArchive; + +/// DSpark geometry (config.json `mtp_config`), validated against the manifest. +pub const DS_LAYERS: usize = 3; +pub const DS_HIDDEN: usize = 2304; +pub const DS_HEADS: usize = 24; +pub const DS_KV: usize = 8; +pub const DS_HD: usize = 128; +pub const DS_INTER: usize = 9216; +pub const DS_BLOCK: usize = 8; +pub const DS_MARKOV_RANK: usize = 256; +pub const DS_VOCAB_PAD: usize = 201024; +/// Target-layer taps [5, 23, 41, 48] (48 = post depth-mix + final norm). +pub const DS_TAPS: [usize; 4] = [5, 23, 41, 48]; +/// Which drafter layers are SWA (local_layer_ids); the rest are global. +pub const DS_SWA_LAYERS: [usize; 2] = [0, 2]; + +/// Expected (name, shape) pairs for `mtp.safetensors` (all BF16). +pub fn expected_tensors() -> Vec<(String, Vec)> { + let mut v = vec![ + ("fuse_weight".to_string(), vec![4, 4]), + ("markov_head.dflare_norm.weight".to_string(), vec![DS_HIDDEN as u64]), + ("markov_head.markov_w1.weight".to_string(), vec![DS_VOCAB_PAD as u64, DS_MARKOV_RANK as u64]), + ("markov_head.rnn_proj.weight".to_string(), vec![768, 5120]), + ("markov_head.rnn_proj.bias".to_string(), vec![768]), + ("markov_head.hidden_out.weight".to_string(), vec![DS_HIDDEN as u64, DS_MARKOV_RANK as u64]), + ("markov_head.hidden_out.bias".to_string(), vec![DS_HIDDEN as u64]), + ("mask_embed".to_string(), vec![DS_HIDDEN as u64]), + ("norm.weight".to_string(), vec![DS_HIDDEN as u64]), + ]; + for il in 0..DS_LAYERS { + let p = format!("layers.{il}."); + let q = DS_HEADS * DS_HD; // 3072 + let kv = DS_KV * DS_HD; // 1024 + for (suf, shape) in [ + ("dflare_norm.weight", vec![DS_HIDDEN as u64]), + ("input_layernorm.weight", vec![DS_HIDDEN as u64]), + ("post_attention_layernorm.weight", vec![DS_HIDDEN as u64]), + ("self_attn.q_norm.weight", vec![DS_HD as u64]), + ("self_attn.k_norm.weight", vec![DS_HD as u64]), + ("self_attn.k_norm_ctx.weight", vec![DS_HD as u64]), + ("self_attn.q_proj.weight", vec![q as u64, DS_HIDDEN as u64]), + ("self_attn.k_proj.weight", vec![kv as u64, DS_HIDDEN as u64]), + ("self_attn.v_proj.weight", vec![kv as u64, DS_HIDDEN as u64]), + ("self_attn.k_proj_ctx.weight", vec![kv as u64, DS_HIDDEN as u64]), + ("self_attn.v_proj_ctx.weight", vec![kv as u64, DS_HIDDEN as u64]), + ("self_attn.o_proj.weight", vec![DS_HIDDEN as u64, q as u64]), + ("mlp.gate_proj.weight", vec![DS_INTER as u64, DS_HIDDEN as u64]), + ("mlp.up_proj.weight", vec![DS_INTER as u64, DS_HIDDEN as u64]), + ("mlp.down_proj.weight", vec![DS_HIDDEN as u64, DS_INTER as u64]), + ] { + v.push((format!("{p}{suf}"), shape)); + } + } + v +} + +/// Validate that `ar` (opened on mtp.safetensors) carries exactly the expected +/// BF16 tensors with the expected shapes. Err => disable the drafter. +pub fn layout_check(ar: &SafetensorsArchive) -> Result<(), String> { + for (name, shape) in expected_tensors() { + let info = ar + .tensors + .get(&name) + .ok_or_else(|| format!("dspark layout: missing tensor '{name}'"))?; + if info.dtype != "BF16" { + return Err(format!("dspark layout: '{name}' dtype {} != BF16", info.dtype)); + } + if info.shape != shape { + return Err(format!( + "dspark layout: '{name}' shape {:?} != {:?}", + info.shape, shape + )); + } + } + Ok(()) +} + +#[cfg(feature = "hip")] +mod gpu { + use super::*; + use crate::packer; + use vetta_infer_hip::DeviceBuf; + + pub struct DsparkLayer { + pub dflare_norm: DeviceBuf, + pub input_ln: DeviceBuf, + pub post_ln: DeviceBuf, + pub q_norm: DeviceBuf, + pub k_norm: DeviceBuf, + pub k_norm_ctx: DeviceBuf, + /// fused [q;k;v] = [(24+8+8)*128, 2304] f32 + pub qkv_w: DeviceBuf, + pub o_w: DeviceBuf, + /// fused [gate;up] = [2*9216, 2304] f32 + pub gate_up_w: DeviceBuf, + pub down_w: DeviceBuf, + pub k_ctx: DeviceBuf, + pub v_ctx: DeviceBuf, + } + + pub struct DsparkWeights { + pub fuse_w: DeviceBuf, + pub layers: Vec, + pub markov_dflare_norm: DeviceBuf, + pub markov_w1: DeviceBuf, + pub rnn_proj_w: DeviceBuf, + pub rnn_proj_b: DeviceBuf, + pub hidden_out_w: DeviceBuf, + pub hidden_out_b: DeviceBuf, + pub mask_embed: DeviceBuf, + pub norm: DeviceBuf, + } + + fn bf16_to_f32(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(2) + .map(|c| f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16)) + .collect() + } + + /// Read a BF16 tensor as host f32. + fn host_f32(ar: &SafetensorsArchive, name: &str) -> Result, String> { + let info = ar.tensors.get(name).ok_or_else(|| format!("missing '{name}'"))?; + let mut raw = vec![0u8; info.byte_len() as usize]; + ar.read_slice(name, 0, &mut raw)?; + Ok(bf16_to_f32(&raw)) + } + + /// Concatenate row-major BF16 matrices [rows_i, k] into one f32 DeviceBuf. + fn fuse_rows(ar: &SafetensorsArchive, names: &[&str]) -> Result { + let mut all = Vec::new(); + for n in names { + all.extend_from_slice(&host_f32(ar, n)?); + } + let bytes = all.len() * 4; + let b = DeviceBuf::alloc_unpooled(bytes)?; + let raw: Vec = all.iter().flat_map(|f| f.to_le_bytes()).collect(); + b.h2d_bytes(&raw)?; + Ok(b) + } + + impl DsparkWeights { + /// Load + fuse all drafter weights (resident, unpooled). Caller must + /// have passed `layout_check` first. + pub fn load(ar: &SafetensorsArchive) -> Result { + layout_check(ar)?; + let f = |n: &str| packer::load_bf16_as_f32(ar, n); + let mut layers = Vec::with_capacity(DS_LAYERS); + for il in 0..DS_LAYERS { + let p = format!("layers.{il}."); + let qkv = fuse_rows( + ar, + &[ + &format!("{p}self_attn.q_proj.weight"), + &format!("{p}self_attn.k_proj.weight"), + &format!("{p}self_attn.v_proj.weight"), + ], + )?; + let gate_up = fuse_rows( + ar, + &[ + &format!("{p}mlp.gate_proj.weight"), + &format!("{p}mlp.up_proj.weight"), + ], + )?; + layers.push(DsparkLayer { + dflare_norm: f(&format!("{p}dflare_norm.weight"))?, + input_ln: f(&format!("{p}input_layernorm.weight"))?, + post_ln: f(&format!("{p}post_attention_layernorm.weight"))?, + q_norm: f(&format!("{p}self_attn.q_norm.weight"))?, + k_norm: f(&format!("{p}self_attn.k_norm.weight"))?, + k_norm_ctx: f(&format!("{p}self_attn.k_norm_ctx.weight"))?, + qkv_w: qkv, + o_w: f(&format!("{p}self_attn.o_proj.weight"))?, + gate_up_w: gate_up, + down_w: f(&format!("{p}mlp.down_proj.weight"))?, + k_ctx: f(&format!("{p}self_attn.k_proj_ctx.weight"))?, + v_ctx: f(&format!("{p}self_attn.v_proj_ctx.weight"))?, + }); + } + Ok(Self { + fuse_w: f("fuse_weight")?, + layers, + markov_dflare_norm: f("markov_head.dflare_norm.weight")?, + markov_w1: f("markov_head.markov_w1.weight")?, + rnn_proj_w: f("markov_head.rnn_proj.weight")?, + rnn_proj_b: f("markov_head.rnn_proj.bias")?, + hidden_out_w: f("markov_head.hidden_out.weight")?, + hidden_out_b: f("markov_head.hidden_out.bias")?, + mask_embed: f("mask_embed")?, + norm: f("norm.weight")?, + }) + } + } +} + +#[cfg(feature = "hip")] +pub use gpu::{DsparkLayer, DsparkWeights}; + +#[cfg(test)] +mod tests { + use super::*; + + /// CPU-only: the real mtp.safetensors must pass the layout check. + #[test] + fn mtp_layout_check_real_file() { + let path = "/mnt/models/Inkling/safetensors/mtp.safetensors"; + if !std::path::Path::new(path).exists() { + eprintln!("skip: mtp.safetensors not present"); + return; + } + let ar = SafetensorsArchive::open_file(path).unwrap(); + layout_check(&ar).unwrap(); + assert_eq!(ar.tensors.len(), expected_tensors().len()); + } + + /// A wrong shape must be rejected (drafter disabled), not silently accepted. + #[test] + fn layout_check_rejects_wrong_shape() { + let mut ar = SafetensorsArchive { + dir: std::path::PathBuf::from("."), + shards: vec![], + tensors: std::collections::HashMap::new(), + }; + for (name, mut shape) in expected_tensors() { + if name == "fuse_weight" { + shape = vec![4, 5]; // corrupt + } + ar.tensors.insert( + name, + crate::TensorInfo { shard_idx: 0, dtype: "BF16".into(), shape, begin: 0, end: 0 }, + ); + } + assert!(layout_check(&ar).is_err()); + } + + /// GPU: load + fuse the real drafter weights; check resident buffer sizes. + #[test] + #[cfg(feature = "hip")] + fn dspark_load_real_weights() { + let path = "/mnt/models/Inkling/safetensors/mtp.safetensors"; + if !std::path::Path::new(path).exists() { + eprintln!("skip: mtp.safetensors not present"); + return; + } + let ar = SafetensorsArchive::open_file(path).unwrap(); + let w = DsparkWeights::load(&ar).unwrap(); + assert_eq!(w.layers.len(), DS_LAYERS); + assert_eq!(w.fuse_w.bytes, 4 * 4 * 4); + let qkv_rows = (DS_HEADS + 2 * DS_KV) * DS_HD; // 5120 + assert_eq!(w.layers[0].qkv_w.bytes, qkv_rows * DS_HIDDEN * 4); + assert_eq!(w.layers[0].gate_up_w.bytes, 2 * DS_INTER * DS_HIDDEN * 4); + assert_eq!(w.markov_w1.bytes, DS_VOCAB_PAD * DS_MARKOV_RANK * 4); + assert_eq!(w.rnn_proj_w.bytes, 768 * 5120 * 4); + } +} \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index fc89bbf..b73dd74 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -703,7 +703,7 @@ pub fn final_logits(cache: &WeightCache, cur: &DeviceBuf, blocks: &[DeviceBuf], /// final residual stream + the accumulated depth-block snapshots. (Prelude / /// single-pass; full-attn layers + loop controllers + bank rollback come next.) pub fn forward_swa_layers( - cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, max_seq: usize, pos: i32, + cache: &WeightCache, schedule: &[usize], d: &Dims, token: i32, _max_seq: usize, pos: i32, ) -> Result<(DeviceBuf, Vec), String> { let cur = embed_token(cache, token, d.hidden, /*vocab*/ 201024)?; let mut blocks: Vec = Vec::new(); diff --git a/crates/vetta-infer-ld/src/lib.rs b/crates/vetta-infer-ld/src/lib.rs index 4767468..03f3678 100644 --- a/crates/vetta-infer-ld/src/lib.rs +++ b/crates/vetta-infer-ld/src/lib.rs @@ -9,6 +9,7 @@ //! index.json) and F-05 (PID-isolated atomic commit) by construction. pub mod bundle; +pub mod dspark; pub mod inkling; pub mod inkling_ir; pub mod inkling_plan; @@ -76,102 +77,26 @@ impl SafetensorsArchive { let mut tensors = HashMap::new(); for (shard_idx, path) in shard_paths.into_iter().enumerate() { - let file = OpenOptions::new() - .read(true) - .open(&path) - .map_err(|e| format!("open {}: {e}", path.display()))?; - let file_size = file - .metadata() - .map_err(|e| format!("stat {}: {e}", path.display()))? - .len(); - if file_size < 8 { - return Err(format!("truncated safetensors file {}", path.display())); - } - let mut len_buf = [0u8; 8]; - file.read_exact_at(&mut len_buf, 0) - .map_err(|e| format!("read header len {}: {e}", path.display()))?; - let hlen = u64::from_le_bytes(len_buf); - let data_start = 8u64 - .checked_add(hlen) - .ok_or_else(|| format!("header length overflow in {}", path.display()))?; - if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size { - return Err(format!( - "invalid header length {hlen} (file_size={file_size}) in {}", - path.display() - )); - } - let mut hbytes = vec![0u8; hlen as usize]; - file.read_exact_at(&mut hbytes, 8) - .map_err(|e| format!("read header {}: {e}", path.display()))?; - let hstr = std::str::from_utf8(&hbytes) - .map_err(|_| format!("non-UTF-8 header in {}", path.display()))?; - let root = parse_json(hstr)?; - let obj = root - .as_obj() - .ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?; - let avail = file_size - data_start; - - for (name, val) in obj { - if name == "__metadata__" { - continue; - } - let to = val - .as_obj() - .ok_or_else(|| format!("tensor '{name}' entry is not object"))?; - let dtype = to - .get("dtype") - .and_then(|v| v.as_str()) - .ok_or_else(|| format!("tensor '{name}' missing dtype"))? - .to_string(); - let shape_arr = to - .get("shape") - .and_then(|v| v.as_arr()) - .ok_or_else(|| format!("tensor '{name}' missing shape"))?; - let mut shape = Vec::with_capacity(shape_arr.len()); - for d in shape_arr { - shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?); - } - let offs = to - .get("data_offsets") - .and_then(|v| v.as_arr()) - .ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?; - if offs.len() != 2 { - return Err(format!("tensor '{name}' data_offsets len != 2")); - } - let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?; - let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?; - if end < begin || end > avail { - return Err(format!( - "tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}", - path.display() - )); - } - if tensors.contains_key(name) { - return Err(format!("duplicate tensor '{name}' across shards")); - } - tensors.insert( - name.clone(), - TensorInfo { - shard_idx, - dtype, - shape, - begin, - end, - }, - ); - } - - shards.push(SafetensorsShard { - path, - file, - file_size, - data_start, - }); + let sh = load_shard(&path, shard_idx, &mut tensors)?; + shards.push(sh); } Ok(Self { dir, shards, tensors }) } + /// Open a SINGLE safetensors file (e.g. `mtp.safetensors`, which is not in + /// the trunk index weight_map). Same checked header/bounds validation. + pub fn open_file(path: impl AsRef) -> Result { + let path = path.as_ref().to_path_buf(); + let dir = path + .parent() + .unwrap_or_else(|| Path::new(".")) + .to_path_buf(); + let mut tensors = HashMap::new(); + let sh = load_shard(&path, 0, &mut tensors)?; + Ok(Self { dir, shards: vec![sh], tensors }) + } + pub fn total_tensor_bytes(&self) -> u64 { self.tensors.values().map(|t| t.byte_len()).sum() } @@ -200,6 +125,93 @@ impl SafetensorsArchive { } } +fn load_shard( + path: &Path, + shard_idx: usize, + tensors: &mut HashMap, +) -> Result { + let file = OpenOptions::new() + .read(true) + .open(path) + .map_err(|e| format!("open {}: {e}", path.display()))?; + let file_size = file + .metadata() + .map_err(|e| format!("stat {}: {e}", path.display()))? + .len(); + if file_size < 8 { + return Err(format!("truncated safetensors file {}", path.display())); + } + let mut len_buf = [0u8; 8]; + file.read_exact_at(&mut len_buf, 0) + .map_err(|e| format!("read header len {}: {e}", path.display()))?; + let hlen = u64::from_le_bytes(len_buf); + let data_start = 8u64 + .checked_add(hlen) + .ok_or_else(|| format!("header length overflow in {}", path.display()))?; + if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size { + return Err(format!( + "invalid header length {hlen} (file_size={file_size}) in {}", + path.display() + )); + } + let mut hbytes = vec![0u8; hlen as usize]; + file.read_exact_at(&mut hbytes, 8) + .map_err(|e| format!("read header {}: {e}", path.display()))?; + let hstr = std::str::from_utf8(&hbytes) + .map_err(|_| format!("non-UTF-8 header in {}", path.display()))?; + let root = parse_json(hstr)?; + let obj = root + .as_obj() + .ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?; + let avail = file_size - data_start; + + for (name, val) in obj { + if name == "__metadata__" { + continue; + } + let to = val + .as_obj() + .ok_or_else(|| format!("tensor '{name}' entry is not object"))?; + let dtype = to + .get("dtype") + .and_then(|v| v.as_str()) + .ok_or_else(|| format!("tensor '{name}' missing dtype"))? + .to_string(); + let shape_arr = to + .get("shape") + .and_then(|v| v.as_arr()) + .ok_or_else(|| format!("tensor '{name}' missing shape"))?; + let mut shape = Vec::with_capacity(shape_arr.len()); + for d in shape_arr { + shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?); + } + let offs = to + .get("data_offsets") + .and_then(|v| v.as_arr()) + .ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?; + if offs.len() != 2 { + return Err(format!("tensor '{name}' data_offsets len != 2")); + } + let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?; + let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?; + if end < begin || end > avail { + return Err(format!( + "tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}", + path.display() + )); + } + if tensors.contains_key(name) { + return Err(format!("duplicate tensor '{name}' across shards")); + } + tensors.insert( + name.clone(), + TensorInfo { shard_idx, dtype, shape, begin, end }, + ); + } + + Ok(SafetensorsShard { path: path.to_path_buf(), file, file_size, data_start }) +} + fn discover_shards(dir: &Path) -> Result, String> { let idx_path = dir.join("model.safetensors.index.json"); if idx_path.is_file() {