[Core] DSpark brick 2: mtp.safetensors manifest + layout-check + fused loader
- SafetensorsArchive::open_file (single shard; mtp is not in the trunk index); header/bounds parsing refactored into load_shard shared with open(). - dspark.rs: expected_tensors() manifest (54 BF16 tensors, exact shapes), layout_check() CPU-only (missing/mismatched => drafter disabled, mirrors reference ink_dspark_layout_check), DsparkWeights::load() GPU resident (unpooled) with qkv [5120,2304] and gate_up [18432,2304] fused at load. - Tests: CPU layout_check on the real file + wrong-shape rejection; GPU dspark_load_real_weights verifies fused/resident buffer sizes. CPU -D warnings green; ld GPU 30/30; gw 15/15.
This commit is contained in:
1 parent
afce5cbbfe
commit
3a9533afd0
3 files changed
+372
-92
No files matched your search
@@ -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<u64>)> {
|
||||
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<DsparkLayer>,
|
||||
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<f32> {
|
||||
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<Vec<f32>, 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<DeviceBuf, String> {
|
||||
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<u8> = 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<Self, String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user