- ld::inkling_graph: emit_decode_base() generates the complete base decode forward from the IR over the unrolled physical schedule: embed -> [per-layer: norm -> QKV -> flash -> O-proj -> residual-add -> MLP norm -> router -> experts w13/w2 -> reduce -> residual-add] -> final norm -> unembed. Live-verified on Inkling: 675 ops, 236 arena decls, validated by abi::arena (no overlap / checked bounds / no use-before-write). This is the structurally-complete base; Inkling parity refinements (learned AttnRes block-mix, loop controllers, ShortConv4, relpos, SWA window, paged KV) layer on top next. - abi::vplan: add the Inkling stage opcodes AttnResMix, ShortConv4, LoopCtrl, L2Clip, KvStore, RelPosBias, MoeRouterTopk, VecAdd (30 total, roundtrip). - ld::inkling_ir: LlmComp derives Copy (used by value in the emitter). - docs/inkling-forward-design.md: full per-layer sequence extracted from forward_batch_chunk (k1 AttnRes block-mix + controllers, k2 projections + shortconv + relpos + KV store, k3 flash, O-proj block-boundary rule, k4 sigmoid router + SiTU experts), real scratch buffer set, deep-residual block mechanism (block_size=6 snapshots + learned queries). Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; 5 ignored live tests pass (base graph 675 ops); lean proofs (4 files, 42 theorems) green.
548 lines
21 KiB
Rust
548 lines
21 KiB
Rust
//! Inkling tensor-name → canonical IR roles (docs/ARCHITECTURE.md §3).
|
|
//!
|
|
//! The heart of the `ModelImporter`: every official HF tensor name is
|
|
//! classified into a typed role (domain + layer + component). Ground truth:
|
|
//! `docs/inkling-tensor-inventory.txt` (1244 live tensors) and
|
|
//! `../strata-safetensors/engine/src/inkling2/ink_safetensors_loader.h`.
|
|
//! Pure string parsing; the live completeness test asserts NO tensor is
|
|
//! left unclassified (a silent `Unknown` would be a loader bug).
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum Domain {
|
|
Llm,
|
|
Vision,
|
|
}
|
|
|
|
/// Attention projection / auxiliary tensors (per layer, under `attn.`).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum AttnPart {
|
|
WqDu,
|
|
WkDv,
|
|
WvDv,
|
|
WoUd,
|
|
WrDu,
|
|
GateAttn,
|
|
SinkProj,
|
|
RelLogitsProj,
|
|
QL2Clip,
|
|
RelL2Clip,
|
|
}
|
|
|
|
/// Short-convolution targets and parts (`sconv_kernel_size = 4`).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum SconvTarget {
|
|
Attn,
|
|
K,
|
|
V,
|
|
Mlp,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum SconvPart {
|
|
Weight,
|
|
Static,
|
|
Proj,
|
|
}
|
|
|
|
/// Loop controllers (gain/forget/down gates across passes).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum CtrlTarget {
|
|
Attn,
|
|
K,
|
|
V,
|
|
Mlp,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum CtrlKind {
|
|
Down,
|
|
Forget,
|
|
Gain,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum RouterPart {
|
|
Weight,
|
|
Bias,
|
|
}
|
|
|
|
/// NVFP4 expert tensors: packed `[n_experts, ...]` weight + per-block scale
|
|
/// (F8_E4M3) + amax (F32) + outer scale denominator.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum ExpertMat {
|
|
W13,
|
|
W2,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum ExpertPart {
|
|
Weight,
|
|
Scale,
|
|
Amax,
|
|
OuterScale,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum LlmComp {
|
|
Embed,
|
|
EmbedNorm,
|
|
FinalNorm,
|
|
Unembed,
|
|
AttnNorm,
|
|
MlpNorm,
|
|
QInputNorm,
|
|
KInputNorm,
|
|
VInputNorm,
|
|
Attn(AttnPart),
|
|
Sconv(SconvTarget, SconvPart),
|
|
Controller(CtrlTarget, CtrlKind),
|
|
Router(RouterPart),
|
|
Expert(ExpertMat, ExpertPart),
|
|
AttnResQuery(usize),
|
|
MlpResQuery(usize),
|
|
OutputQuery,
|
|
CrossPassQuery,
|
|
CrossPassKvQuery,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
pub enum TensorRole {
|
|
Llm { layer: Option<usize>, comp: LlmComp },
|
|
/// Vision backbone keeps its raw sub-path; the Vision importer (M1) types it.
|
|
Vision { layer: Option<usize>, part: String },
|
|
}
|
|
|
|
fn parse_idx(s: &str) -> Option<usize> {
|
|
s.parse::<usize>().ok()
|
|
}
|
|
|
|
/// Classify an official tensor name. `None` = unrecognized (loader must reject).
|
|
pub fn classify(name: &str) -> Option<TensorRole> {
|
|
let rest = name.strip_prefix("model.")?;
|
|
let (domain, rest) = if let Some(r) = rest.strip_prefix("llm.") {
|
|
(Domain::Llm, r)
|
|
} else if let Some(r) = rest.strip_prefix("visual.") {
|
|
(Domain::Vision, r)
|
|
} else {
|
|
return None;
|
|
};
|
|
|
|
// Extract optional layer index: `layers.N.<remainder>`.
|
|
let (layer, comp_path) = if let Some(r) = rest.strip_prefix("layers.") {
|
|
let (idx, r) = r.split_once('.')?;
|
|
(Some(parse_idx(idx)?), r)
|
|
} else {
|
|
(None, rest)
|
|
};
|
|
|
|
match domain {
|
|
Domain::Vision => {
|
|
// visual.backbone.layers.N.<...> already stripped `layers.N` above
|
|
// only when present at top level; vision nests under `backbone.`.
|
|
let (vlayer, part) = if let Some(r) = comp_path.strip_prefix("backbone.layers.") {
|
|
let (idx, r) = r.split_once('.')?;
|
|
(Some(parse_idx(idx)?), r.to_string())
|
|
} else {
|
|
(layer, comp_path.to_string())
|
|
};
|
|
Some(TensorRole::Vision { layer: vlayer, part })
|
|
}
|
|
Domain::Llm => {
|
|
let comp = classify_llm(comp_path)?;
|
|
Some(TensorRole::Llm { layer, comp })
|
|
}
|
|
}
|
|
}
|
|
|
|
fn classify_llm(p: &str) -> Option<LlmComp> {
|
|
Some(match p {
|
|
"embed.weight" => LlmComp::Embed,
|
|
"embed_norm.weight" => LlmComp::EmbedNorm,
|
|
"norm.weight" => LlmComp::FinalNorm,
|
|
"unembed.weight" => LlmComp::Unembed,
|
|
"attn_norm.weight" => LlmComp::AttnNorm,
|
|
"mlp_norm.weight" => LlmComp::MlpNorm,
|
|
"q_input_norm.weight" => LlmComp::QInputNorm,
|
|
"k_input_norm.weight" => LlmComp::KInputNorm,
|
|
"v_input_norm.weight" => LlmComp::VInputNorm,
|
|
"attn.wq_du.weight" => LlmComp::Attn(AttnPart::WqDu),
|
|
"attn.wk_dv.weight" => LlmComp::Attn(AttnPart::WkDv),
|
|
"attn.wv_dv.weight" => LlmComp::Attn(AttnPart::WvDv),
|
|
"attn.wo_ud.weight" => LlmComp::Attn(AttnPart::WoUd),
|
|
"attn.wr_du.weight" => LlmComp::Attn(AttnPart::WrDu),
|
|
"attn.gate_attn.weight" => LlmComp::Attn(AttnPart::GateAttn),
|
|
"attn.attn_sink_proj.weight" => LlmComp::Attn(AttnPart::SinkProj),
|
|
"attn.rel_logits_proj.proj" => LlmComp::Attn(AttnPart::RelLogitsProj),
|
|
"attn.q_l2_clip.scale" => LlmComp::Attn(AttnPart::QL2Clip),
|
|
"attn.rel_l2_clip.scale" => LlmComp::Attn(AttnPart::RelL2Clip),
|
|
"attn.k_sconv.weight" => LlmComp::Sconv(SconvTarget::K, SconvPart::Weight),
|
|
"attn.k_sconv.static_w" => LlmComp::Sconv(SconvTarget::K, SconvPart::Static),
|
|
"attn.k_sconv.weight_proj" => LlmComp::Sconv(SconvTarget::K, SconvPart::Proj),
|
|
"attn.v_sconv.weight" => LlmComp::Sconv(SconvTarget::V, SconvPart::Weight),
|
|
"attn.v_sconv.static_w" => LlmComp::Sconv(SconvTarget::V, SconvPart::Static),
|
|
"attn.v_sconv.weight_proj" => LlmComp::Sconv(SconvTarget::V, SconvPart::Proj),
|
|
"attn_sconv.weight" => LlmComp::Sconv(SconvTarget::Attn, SconvPart::Weight),
|
|
"mlp_sconv.weight" => LlmComp::Sconv(SconvTarget::Mlp, SconvPart::Weight),
|
|
"controllers.attn.down_weight" => LlmComp::Controller(CtrlTarget::Attn, CtrlKind::Down),
|
|
"controllers.attn.forget_weight" => LlmComp::Controller(CtrlTarget::Attn, CtrlKind::Forget),
|
|
"controllers.attn.gain_weight" => LlmComp::Controller(CtrlTarget::Attn, CtrlKind::Gain),
|
|
"controllers.k.down_weight" => LlmComp::Controller(CtrlTarget::K, CtrlKind::Down),
|
|
"controllers.k.forget_weight" => LlmComp::Controller(CtrlTarget::K, CtrlKind::Forget),
|
|
"controllers.k.gain_weight" => LlmComp::Controller(CtrlTarget::K, CtrlKind::Gain),
|
|
"controllers.v.down_weight" => LlmComp::Controller(CtrlTarget::V, CtrlKind::Down),
|
|
"controllers.v.forget_weight" => LlmComp::Controller(CtrlTarget::V, CtrlKind::Forget),
|
|
"controllers.v.gain_weight" => LlmComp::Controller(CtrlTarget::V, CtrlKind::Gain),
|
|
"controllers.mlp.down_weight" => LlmComp::Controller(CtrlTarget::Mlp, CtrlKind::Down),
|
|
"controllers.mlp.forget_weight" => LlmComp::Controller(CtrlTarget::Mlp, CtrlKind::Forget),
|
|
"controllers.mlp.gain_weight" => LlmComp::Controller(CtrlTarget::Mlp, CtrlKind::Gain),
|
|
"mlp.gate.weight" => LlmComp::Router(RouterPart::Weight),
|
|
"mlp.gate.bias" => LlmComp::Router(RouterPart::Bias),
|
|
"mlp.experts.w13_weight" => LlmComp::Expert(ExpertMat::W13, ExpertPart::Weight),
|
|
"mlp.experts.w13_weight_scale" => LlmComp::Expert(ExpertMat::W13, ExpertPart::Scale),
|
|
"mlp.experts.w13_weight_amax" => LlmComp::Expert(ExpertMat::W13, ExpertPart::Amax),
|
|
"mlp.experts.w13_weight_outer_scale_denominator" => LlmComp::Expert(ExpertMat::W13, ExpertPart::OuterScale),
|
|
"mlp.experts.w2_weight" => LlmComp::Expert(ExpertMat::W2, ExpertPart::Weight),
|
|
"mlp.experts.w2_weight_scale" => LlmComp::Expert(ExpertMat::W2, ExpertPart::Scale),
|
|
"mlp.experts.w2_weight_amax" => LlmComp::Expert(ExpertMat::W2, ExpertPart::Amax),
|
|
"mlp.experts.w2_weight_outer_scale_denominator" => LlmComp::Expert(ExpertMat::W2, ExpertPart::OuterScale),
|
|
"attn_res.output_query" => LlmComp::OutputQuery,
|
|
"middle_cycle_cross_pass_queries" => LlmComp::CrossPassQuery,
|
|
"middle_cycle_cross_pass_kv_queries" => LlmComp::CrossPassKvQuery,
|
|
_ => {
|
|
if let Some(i) = p.strip_prefix("attn_res.attn_queries.") {
|
|
LlmComp::AttnResQuery(parse_idx(i)?)
|
|
} else if let Some(i) = p.strip_prefix("attn_res.mlp_queries.") {
|
|
LlmComp::MlpResQuery(parse_idx(i)?)
|
|
} else {
|
|
return None;
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
// ============================================================================
|
|
// Canonical IR assembly: group classified tensors per layer, validate structure
|
|
// against the config. This is the in-memory IR the BackendPacker consumes.
|
|
// ============================================================================
|
|
|
|
use crate::inkling::InklingConfig;
|
|
use crate::TensorInfo;
|
|
use std::collections::HashMap;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct TensorMeta {
|
|
pub name: String,
|
|
pub dtype: String,
|
|
pub shape: Vec<u64>,
|
|
pub bytes: u64,
|
|
}
|
|
|
|
impl TensorMeta {
|
|
fn from_info(name: &str, t: &TensorInfo) -> Self {
|
|
Self {
|
|
name: name.to_string(),
|
|
dtype: t.dtype.clone(),
|
|
shape: t.shape.clone(),
|
|
bytes: t.byte_len(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct LayerIr {
|
|
pub index: usize,
|
|
pub is_full_attn: bool,
|
|
pub comps: HashMap<LlmComp, TensorMeta>,
|
|
}
|
|
|
|
impl LayerIr {
|
|
pub fn get(&self, comp: LlmComp) -> Option<&TensorMeta> {
|
|
self.comps.get(&comp)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct InklingIr {
|
|
pub config: InklingConfig,
|
|
pub trunk: HashMap<LlmComp, TensorMeta>,
|
|
pub layers: Vec<LayerIr>,
|
|
pub vision: Vec<TensorMeta>,
|
|
}
|
|
|
|
impl InklingIr {
|
|
pub fn layer(&self, i: usize) -> Option<&LayerIr> {
|
|
self.layers.get(i)
|
|
}
|
|
}
|
|
|
|
/// Components every decoder layer must carry (the decode critical path).
|
|
const REQUIRED_LAYER_COMPS: &[LlmComp] = &[
|
|
LlmComp::Attn(AttnPart::WqDu),
|
|
LlmComp::Attn(AttnPart::WkDv),
|
|
LlmComp::Attn(AttnPart::WvDv),
|
|
LlmComp::Attn(AttnPart::WoUd),
|
|
LlmComp::MlpNorm,
|
|
LlmComp::Router(RouterPart::Weight),
|
|
LlmComp::Expert(ExpertMat::W13, ExpertPart::Weight),
|
|
LlmComp::Expert(ExpertMat::W2, ExpertPart::Weight),
|
|
];
|
|
|
|
/// Assemble the canonical IR from classified tensors, validating structure
|
|
/// against `config`. Unrecognized names and missing required components are
|
|
/// explicit errors (never a silently partial model).
|
|
pub fn assemble<'a>(
|
|
config: &InklingConfig,
|
|
tensors: impl Iterator<Item = (&'a str, &'a TensorInfo)>,
|
|
) -> Result<InklingIr, String> {
|
|
let n_layers = config.text.n_layers;
|
|
let full = config.text.full_attention_layers();
|
|
let mut layers: Vec<LayerIr> = (0..n_layers)
|
|
.map(|i| LayerIr { index: i, is_full_attn: full.contains(&i), comps: HashMap::new() })
|
|
.collect();
|
|
let mut trunk = HashMap::new();
|
|
let mut vision = Vec::new();
|
|
|
|
for (name, info) in tensors {
|
|
let meta = TensorMeta::from_info(name, info);
|
|
match classify(name) {
|
|
Some(TensorRole::Llm { layer: None, comp }) => {
|
|
trunk.insert(comp, meta);
|
|
}
|
|
Some(TensorRole::Llm { layer: Some(i), comp }) => {
|
|
let layer = layers.get_mut(i).ok_or_else(|| format!("layer {i} out of range (n_layers={n_layers}): {name}"))?;
|
|
layer.comps.insert(comp, meta);
|
|
}
|
|
Some(TensorRole::Vision { .. }) => vision.push(meta),
|
|
None => return Err(format!("unclassified tensor: {name}")),
|
|
}
|
|
}
|
|
|
|
// Trunk invariants.
|
|
for comp in [LlmComp::Embed, LlmComp::EmbedNorm, LlmComp::FinalNorm, LlmComp::Unembed] {
|
|
if !trunk.contains_key(&comp) {
|
|
return Err(format!("missing trunk component {comp:?}"));
|
|
}
|
|
}
|
|
let embed = &trunk[&LlmComp::Embed];
|
|
if embed.shape != vec![config.text.vocab as u64, config.text.hidden as u64] {
|
|
return Err(format!("embed shape {:?} != [vocab {}, hidden {}]", embed.shape, config.text.vocab, config.text.hidden));
|
|
}
|
|
|
|
// Per-layer invariants.
|
|
for layer in &layers {
|
|
for comp in REQUIRED_LAYER_COMPS {
|
|
if !layer.comps.contains_key(comp) {
|
|
return Err(format!("layer {} missing required component {comp:?}", layer.index));
|
|
}
|
|
}
|
|
// Attention norms differ by type: SWA layers use a single attn_norm;
|
|
// full (relative) attention layers use q/k/v_input_norm (verified live).
|
|
let norm_comps: &[LlmComp] = if layer.is_full_attn {
|
|
&[LlmComp::QInputNorm, LlmComp::KInputNorm, LlmComp::VInputNorm]
|
|
} else {
|
|
&[LlmComp::AttnNorm]
|
|
};
|
|
for comp in norm_comps {
|
|
if !layer.comps.contains_key(comp) {
|
|
return Err(format!("layer {} missing attention norm {comp:?}", layer.index));
|
|
}
|
|
}
|
|
for mat in [ExpertMat::W13, ExpertMat::W2] {
|
|
let w = &layer.comps[&LlmComp::Expert(mat, ExpertPart::Weight)];
|
|
if w.shape.first() != Some(&(config.text.n_experts as u64)) {
|
|
return Err(format!("layer {} expert {mat:?} first dim {:?} != n_experts {}", layer.index, w.shape.first(), config.text.n_experts));
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(InklingIr { config: config.clone(), trunk, layers, vision })
|
|
}
|
|
|
|
/// Convenience: assemble directly from an opened archive.
|
|
pub fn assemble_archive(config: &InklingConfig, ar: &crate::SafetensorsArchive) -> Result<InklingIr, String> {
|
|
assemble(config, ar.tensors.iter().map(|(n, t)| (n.as_str(), t)))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn trunk_roles() {
|
|
assert_eq!(classify("model.llm.embed.weight"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::Embed }));
|
|
assert_eq!(classify("model.llm.unembed.weight"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::Unembed }));
|
|
assert_eq!(classify("model.llm.norm.weight"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::FinalNorm }));
|
|
}
|
|
|
|
#[test]
|
|
fn per_layer_roles() {
|
|
assert_eq!(classify("model.llm.layers.0.attn.wq_du.weight"),
|
|
Some(TensorRole::Llm { layer: Some(0), comp: LlmComp::Attn(AttnPart::WqDu) }));
|
|
assert_eq!(classify("model.llm.layers.11.k_input_norm.weight"),
|
|
Some(TensorRole::Llm { layer: Some(11), comp: LlmComp::KInputNorm }));
|
|
assert_eq!(classify("model.llm.layers.5.mlp.experts.w13_weight_scale"),
|
|
Some(TensorRole::Llm { layer: Some(5), comp: LlmComp::Expert(ExpertMat::W13, ExpertPart::Scale) }));
|
|
assert_eq!(classify("model.llm.layers.7.controllers.mlp.gain_weight"),
|
|
Some(TensorRole::Llm { layer: Some(7), comp: LlmComp::Controller(CtrlTarget::Mlp, CtrlKind::Gain) }));
|
|
assert_eq!(classify("model.llm.layers.3.attn.k_sconv.weight_proj"),
|
|
Some(TensorRole::Llm { layer: Some(3), comp: LlmComp::Sconv(SconvTarget::K, SconvPart::Proj) }));
|
|
}
|
|
|
|
#[test]
|
|
fn query_roles() {
|
|
assert_eq!(classify("model.llm.attn_res.attn_queries.22"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::AttnResQuery(22) }));
|
|
assert_eq!(classify("model.llm.attn_res.mlp_queries.23"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::MlpResQuery(23) }));
|
|
assert_eq!(classify("model.llm.middle_cycle_cross_pass_kv_queries"),
|
|
Some(TensorRole::Llm { layer: None, comp: LlmComp::CrossPassKvQuery }));
|
|
}
|
|
|
|
#[test]
|
|
fn vision_roles() {
|
|
assert_eq!(classify("model.visual.backbone.layers.4.self_attn.q_proj.weight"),
|
|
Some(TensorRole::Vision { layer: Some(4), part: "self_attn.q_proj.weight".into() }));
|
|
assert_eq!(classify("model.visual.proj_in.weight"),
|
|
Some(TensorRole::Vision { layer: None, part: "proj_in.weight".into() }));
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_rejected() {
|
|
assert_eq!(classify("model.llm.layers.0.attn.bogus.weight"), None);
|
|
assert_eq!(classify("model.bogus.weight"), None);
|
|
assert_eq!(classify("embed.weight"), None);
|
|
}
|
|
|
|
/// Opt-in live completeness: EVERY tensor in the real archive classifies.
|
|
/// `cargo test -p vetta-infer-ld -- --ignored inkling_ir_live`.
|
|
#[test]
|
|
#[ignore]
|
|
fn inkling_ir_live_complete() {
|
|
let ar = crate::SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
|
let mut llm = 0usize;
|
|
let mut vision = 0usize;
|
|
let mut layers = std::collections::BTreeSet::new();
|
|
for name in ar.tensors.keys() {
|
|
match classify(name) {
|
|
Some(TensorRole::Llm { layer, .. }) => {
|
|
llm += 1;
|
|
if let Some(l) = layer {
|
|
layers.insert(l);
|
|
}
|
|
}
|
|
Some(TensorRole::Vision { .. }) => vision += 1,
|
|
None => panic!("unclassified tensor: {name}"),
|
|
}
|
|
}
|
|
assert_eq!(ar.tensors.len(), 1244);
|
|
assert!(vision > 0);
|
|
assert_eq!(layers.len(), 24); // 0..23
|
|
assert_eq!(*layers.iter().next().unwrap(), 0);
|
|
assert_eq!(*layers.iter().next_back().unwrap(), 23);
|
|
eprintln!("classified {llm} LLM + {vision} vision tensors, 24 layers");
|
|
}
|
|
|
|
// --- IR assembly tests ---
|
|
|
|
const MINI_CFG: &str = r#"{
|
|
"eos_token_id": 0,
|
|
"text_config": {
|
|
"hidden_size": 8, "num_hidden_layers": 2, "vocab_size": 16,
|
|
"unpadded_vocab_size": 16, "num_attention_heads": 2, "num_key_value_heads": 1,
|
|
"head_dim": 4, "d_rel": 2, "rel_extent": 4, "sliding_window_size": 4,
|
|
"sconv_kernel_size": 4, "rms_norm_eps": 1e-06, "n_routed_experts": 4,
|
|
"num_experts_per_tok": 2, "n_shared_experts": 0, "intermediate_size": 8,
|
|
"route_scale": 1.0, "final_logit_softcapping": 30.0, "local_layer_ids": [0],
|
|
"loop_config": {"core_start":0,"core_end":1,"num_passes":1,"gate_rank":2,"is_varloop":false}
|
|
},
|
|
"quantization_config": {"quant_algo":"NVFP4"}
|
|
}"#;
|
|
|
|
fn mk(name: &str, shape: Vec<u64>) -> (String, TensorInfo) {
|
|
(name.to_string(), TensorInfo { shard_idx: 0, dtype: "BF16".into(), shape, begin: 0, end: 1 })
|
|
}
|
|
|
|
fn mini_tensors() -> Vec<(String, TensorInfo)> {
|
|
let mut v = vec![
|
|
mk("model.llm.embed.weight", vec![16, 8]),
|
|
mk("model.llm.embed_norm.weight", vec![8]),
|
|
mk("model.llm.norm.weight", vec![8]),
|
|
mk("model.llm.unembed.weight", vec![16, 8]),
|
|
];
|
|
for l in 0..2 {
|
|
for (suffix, shape) in [
|
|
("attn.wq_du.weight", vec![8, 8]),
|
|
("attn.wk_dv.weight", vec![4, 8]),
|
|
("attn.wv_dv.weight", vec![4, 8]),
|
|
("attn.wo_ud.weight", vec![8, 8]),
|
|
("attn_norm.weight", vec![8]),
|
|
("mlp_norm.weight", vec![8]),
|
|
("q_input_norm.weight", vec![8]),
|
|
("k_input_norm.weight", vec![8]),
|
|
("v_input_norm.weight", vec![8]),
|
|
("mlp.gate.weight", vec![4, 8]),
|
|
("mlp.experts.w13_weight", vec![4, 8, 8]),
|
|
("mlp.experts.w2_weight", vec![4, 8, 8]),
|
|
] {
|
|
v.push(mk(&format!("model.llm.layers.{l}.{suffix}"), shape));
|
|
}
|
|
}
|
|
v
|
|
}
|
|
|
|
#[test]
|
|
fn assemble_minimal_ok() {
|
|
let cfg = crate::inkling::parse_config(MINI_CFG).unwrap();
|
|
let ts = mini_tensors();
|
|
let ir = assemble(&cfg, ts.iter().map(|(n, t)| (n.as_str(), t))).unwrap();
|
|
assert_eq!(ir.layers.len(), 2);
|
|
assert!(!ir.layer(0).unwrap().is_full_attn);
|
|
assert!(ir.layer(1).unwrap().is_full_attn);
|
|
assert!(ir.layer(0).unwrap().get(LlmComp::Attn(AttnPart::WqDu)).is_some());
|
|
assert_eq!(ir.trunk[&LlmComp::Embed].shape, vec![16, 8]);
|
|
}
|
|
|
|
#[test]
|
|
fn assemble_missing_component_rejected() {
|
|
let cfg = crate::inkling::parse_config(MINI_CFG).unwrap();
|
|
let mut ts = mini_tensors();
|
|
ts.retain(|(n, _)| n != "model.llm.layers.1.attn.wq_du.weight");
|
|
let err = assemble(&cfg, ts.iter().map(|(n, t)| (n.as_str(), t))).unwrap_err();
|
|
assert!(err.contains("layer 1 missing"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn assemble_bad_expert_dim_rejected() {
|
|
let cfg = crate::inkling::parse_config(MINI_CFG).unwrap();
|
|
let mut ts = mini_tensors();
|
|
for (n, t) in ts.iter_mut() {
|
|
if n == "model.llm.layers.0.mlp.experts.w13_weight" {
|
|
t.shape = vec![3, 8, 8];
|
|
}
|
|
}
|
|
let err = assemble(&cfg, ts.iter().map(|(n, t)| (n.as_str(), t))).unwrap_err();
|
|
assert!(err.contains("n_experts"), "{err}");
|
|
}
|
|
|
|
/// Opt-in live IR assembly against the real artifact.
|
|
/// `cargo test -p vetta-infer-ld -- --ignored inkling_assemble_live`.
|
|
#[test]
|
|
#[ignore]
|
|
fn inkling_assemble_live() {
|
|
let raw = std::fs::read_to_string("/mnt/models/Inkling/safetensors/config.json").unwrap();
|
|
let cfg = crate::inkling::parse_config(&raw).unwrap();
|
|
let ar = crate::SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap();
|
|
let ir = assemble_archive(&cfg, &ar).unwrap();
|
|
assert_eq!(ir.layers.len(), 24);
|
|
assert_eq!(ir.trunk[&LlmComp::Embed].shape, vec![201024, 2304]);
|
|
assert!(ir.layer(11).unwrap().get(LlmComp::QInputNorm).is_some());
|
|
assert!(ir.layer(0).unwrap().get(LlmComp::QInputNorm).is_none());
|
|
for l in &ir.layers {
|
|
assert_eq!(l.get(LlmComp::Expert(ExpertMat::W13, ExpertPart::Weight)).unwrap().shape[0], 128);
|
|
}
|
|
eprintln!("assembled IR: {} layers, {} vision tensors", ir.layers.len(), ir.vision.len());
|
|
}
|
|
} |