[LD] Inkling ModelImporter foundation: typed config + total tensor classification + validated IR assembly
- ld::inkling: parse_config(config.json) -> InklingConfig (TextConfig,
LoopConfig, MtpConfig), checked extraction + consistency guards
(top_k <= n_experts, n_head % n_kv == 0, core_start < core_end).
full_attention_layers() = complement of local_layer_ids ({5,11,17,23}).
- ld::inkling_ir: classify(name) -> TensorRole, the total tensor-name ->
typed-role mapping (trunk, per-layer attn projections/sconv/controllers/
norms, NVFP4 router+experts, attention-residual/cross-pass queries, vision).
Unknown names -> None (explicit rejection). Verified TOTAL on the live
archive: 1244/1244 classified, 24 layers.
- ld::inkling_ir: assemble()/assemble_archive() -> InklingIr (trunk + 24
LayerIr + vision), structural validation vs config (layer count, embed
shape = vocab x hidden, required per-layer components, expert first dim =
n_experts). Attention-norm validation is type-aware: SWA layers use
attn_norm, full-attention layers use q/k/v_input_norm (discovered + fixed
via the live test, verified on the inventory).
- Opt-in #[ignore] live tests against /mnt/models/Inkling/safetensors
(config, classification completeness, IR assembly) — all pass; default
suite stays host-independent.
Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 87/87 PASS;
3 ignored live tests pass; lean proofs (4 files, 42 theorems) green.
This commit is contained in:
1 parent
4de272beb1
commit
465315ae94
3 files changed
+847
No files matched your search
@@ -0,0 +1,297 @@
|
||||
//! Inkling-2-Mini `ModelImporter` — config parsing (docs/ARCHITECTURE.md §3).
|
||||
//!
|
||||
//! First slice of the dual-step loader: `config.json` → typed `InklingConfig`.
|
||||
//! Ground truth: the live `/mnt/models/Inkling/safetensors/config.json` and
|
||||
//! `../strata-safetensors/engine/src/inkling2/ink_safetensors_loader.h`.
|
||||
//! Pure checked parsing (no IO here); the tensor-name → canonical-IR mapping
|
||||
//! and the `BackendPacker` build on top of this.
|
||||
|
||||
use vetta_infer_abi::json::{parse_json, JsonVal};
|
||||
|
||||
type Obj<'a> = &'a std::collections::HashMap<String, JsonVal>;
|
||||
|
||||
fn obj<'a>(v: &'a JsonVal) -> Result<Obj<'a>, String> {
|
||||
v.as_obj().ok_or_else(|| "expected JSON object".to_string())
|
||||
}
|
||||
|
||||
fn field<'a>(m: Obj<'a>, k: &str) -> Result<&'a JsonVal, String> {
|
||||
m.get(k).ok_or_else(|| format!("missing field '{k}'"))
|
||||
}
|
||||
|
||||
fn uint(m: Obj, k: &str) -> Result<u64, String> {
|
||||
field(m, k)?.as_u64().ok_or_else(|| format!("field '{k}' not a non-negative integer"))
|
||||
}
|
||||
|
||||
fn usize_of(m: Obj, k: &str) -> Result<usize, String> {
|
||||
let n = uint(m, k)?;
|
||||
usize::try_from(n).map_err(|_| format!("field '{k}' too large"))
|
||||
}
|
||||
|
||||
fn float(m: Obj, k: &str) -> Result<f64, String> {
|
||||
match field(m, k)? {
|
||||
JsonVal::Num(f) => Ok(*f),
|
||||
JsonVal::Int(n) => Ok(*n as f64),
|
||||
_ => Err(format!("field '{k}' not a number")),
|
||||
}
|
||||
}
|
||||
|
||||
fn bool_of(m: Obj, k: &str) -> Result<bool, String> {
|
||||
match field(m, k)? {
|
||||
JsonVal::Bool(b) => Ok(*b),
|
||||
_ => Err(format!("field '{k}' not a bool")),
|
||||
}
|
||||
}
|
||||
|
||||
fn id_list(m: Obj, k: &str) -> Result<Vec<usize>, String> {
|
||||
let arr = field(m, k)?.as_arr().ok_or_else(|| format!("field '{k}' not an array"))?;
|
||||
arr.iter()
|
||||
.map(|v| {
|
||||
let n = v.as_u64().ok_or_else(|| format!("'{k}' element not an integer"))?;
|
||||
usize::try_from(n).map_err(|_| format!("'{k}' element too large"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The looped core: layers `[core_start, core_end)` run `num_passes` times.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LoopConfig {
|
||||
pub core_start: usize,
|
||||
pub core_end: usize,
|
||||
pub num_passes: usize,
|
||||
pub gate_rank: usize,
|
||||
pub is_varloop: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TextConfig {
|
||||
pub hidden: usize,
|
||||
pub n_layers: usize,
|
||||
pub vocab: usize,
|
||||
pub unpadded_vocab: usize,
|
||||
pub n_head: usize,
|
||||
pub n_kv: usize,
|
||||
pub head_dim: usize,
|
||||
pub d_rel: usize,
|
||||
pub rel_extent: usize,
|
||||
pub swa_win: usize,
|
||||
pub sconv_k: usize,
|
||||
pub rms_eps: f64,
|
||||
pub n_experts: usize,
|
||||
pub top_k: usize,
|
||||
pub n_shared: usize,
|
||||
pub inter: usize,
|
||||
pub route_scale: f64,
|
||||
pub final_logit_softcapping: f64,
|
||||
pub local_layer_ids: Vec<usize>,
|
||||
pub loop_cfg: LoopConfig,
|
||||
}
|
||||
|
||||
impl TextConfig {
|
||||
/// Layers NOT in `local_layer_ids` use full (relative) attention instead
|
||||
/// of sliding-window. For Inkling-2-Mini: {5, 11, 17, 23}.
|
||||
pub fn full_attention_layers(&self) -> Vec<usize> {
|
||||
(0..self.n_layers).filter(|i| !self.local_layer_ids.contains(i)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MtpConfig {
|
||||
pub hidden: usize,
|
||||
pub n_layers: usize,
|
||||
pub n_head: usize,
|
||||
pub n_kv: usize,
|
||||
pub head_dim: usize,
|
||||
pub inter: usize,
|
||||
pub block_size: usize,
|
||||
pub markov_rank: usize,
|
||||
pub rope_theta: f64,
|
||||
pub rms_eps: f64,
|
||||
pub swa_win: usize,
|
||||
pub local_layer_ids: Vec<usize>,
|
||||
pub target_layer_ids: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct InklingConfig {
|
||||
pub eos_token_id: u64,
|
||||
pub quant_algo: String,
|
||||
pub text: TextConfig,
|
||||
pub mtp: Option<MtpConfig>,
|
||||
}
|
||||
|
||||
/// Parse the official HF `config.json` (text_config + loop_config + mtp_config
|
||||
/// + quantization_config). Vision is parsed by the Vision importer (M1 later).
|
||||
pub fn parse_config(text: &str) -> Result<InklingConfig, String> {
|
||||
let root = parse_json(text)?;
|
||||
let m = obj(&root)?;
|
||||
let eos_token_id = uint(m, "eos_token_id")?;
|
||||
|
||||
let quant_algo = match m.get("quantization_config") {
|
||||
Some(q) => {
|
||||
let qm = obj(q)?;
|
||||
match qm.get("quant_algo").and_then(|v| v.as_str()) {
|
||||
Some(s) => s.to_string(),
|
||||
None => return Err("quantization_config.quant_algo missing".into()),
|
||||
}
|
||||
}
|
||||
None => "none".to_string(),
|
||||
};
|
||||
|
||||
let tc = obj(field(m, "text_config")?)?;
|
||||
let lc = obj(field(tc, "loop_config")?)?;
|
||||
let loop_cfg = LoopConfig {
|
||||
core_start: usize_of(lc, "core_start")?,
|
||||
core_end: usize_of(lc, "core_end")?,
|
||||
num_passes: usize_of(lc, "num_passes")?,
|
||||
gate_rank: usize_of(lc, "gate_rank")?,
|
||||
is_varloop: bool_of(lc, "is_varloop")?,
|
||||
};
|
||||
if loop_cfg.core_start >= loop_cfg.core_end {
|
||||
return Err("loop_config: core_start >= core_end".into());
|
||||
}
|
||||
let text_cfg = TextConfig {
|
||||
hidden: usize_of(tc, "hidden_size")?,
|
||||
n_layers: usize_of(tc, "num_hidden_layers")?,
|
||||
vocab: usize_of(tc, "vocab_size")?,
|
||||
unpadded_vocab: usize_of(tc, "unpadded_vocab_size")?,
|
||||
n_head: usize_of(tc, "num_attention_heads")?,
|
||||
n_kv: usize_of(tc, "num_key_value_heads")?,
|
||||
head_dim: usize_of(tc, "head_dim")?,
|
||||
d_rel: usize_of(tc, "d_rel")?,
|
||||
rel_extent: usize_of(tc, "rel_extent")?,
|
||||
swa_win: usize_of(tc, "sliding_window_size")?,
|
||||
sconv_k: usize_of(tc, "sconv_kernel_size")?,
|
||||
rms_eps: float(tc, "rms_norm_eps")?,
|
||||
n_experts: usize_of(tc, "n_routed_experts")?,
|
||||
top_k: usize_of(tc, "num_experts_per_tok")?,
|
||||
n_shared: usize_of(tc, "n_shared_experts")?,
|
||||
inter: usize_of(tc, "intermediate_size")?,
|
||||
route_scale: float(tc, "route_scale")?,
|
||||
final_logit_softcapping: float(tc, "final_logit_softcapping")?,
|
||||
local_layer_ids: id_list(tc, "local_layer_ids")?,
|
||||
loop_cfg,
|
||||
};
|
||||
if text_cfg.top_k > text_cfg.n_experts {
|
||||
return Err("num_experts_per_tok > n_routed_experts".into());
|
||||
}
|
||||
if text_cfg.n_head % text_cfg.n_kv != 0 {
|
||||
return Err("num_attention_heads not divisible by num_key_value_heads".into());
|
||||
}
|
||||
|
||||
let mtp = match m.get("mtp_config") {
|
||||
Some(v) => {
|
||||
let mc = obj(v)?;
|
||||
Some(MtpConfig {
|
||||
hidden: usize_of(mc, "hidden_size")?,
|
||||
n_layers: usize_of(mc, "num_hidden_layers")?,
|
||||
n_head: usize_of(mc, "num_attention_heads")?,
|
||||
n_kv: usize_of(mc, "num_key_value_heads")?,
|
||||
head_dim: usize_of(mc, "head_dim")?,
|
||||
inter: usize_of(mc, "intermediate_size")?,
|
||||
block_size: usize_of(mc, "block_size")?,
|
||||
markov_rank: usize_of(mc, "markov_rank")?,
|
||||
rope_theta: float(mc, "rope_theta")?,
|
||||
rms_eps: float(mc, "rms_norm_eps")?,
|
||||
swa_win: usize_of(mc, "sliding_window_size")?,
|
||||
local_layer_ids: id_list(mc, "local_layer_ids")?,
|
||||
target_layer_ids: id_list(mc, "target_layer_ids")?,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(InklingConfig { eos_token_id, quant_algo, text: text_cfg, mtp })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Trimmed but faithful extract of the live Inkling-2-Mini config.json.
|
||||
const CFG: &str = r#"{
|
||||
"eos_token_id": 200006,
|
||||
"text_config": {
|
||||
"hidden_size": 2304, "num_hidden_layers": 24, "vocab_size": 201024,
|
||||
"unpadded_vocab_size": 200058, "num_attention_heads": 24,
|
||||
"num_key_value_heads": 8, "head_dim": 128, "d_rel": 16, "rel_extent": 1024,
|
||||
"sliding_window_size": 1024, "sconv_kernel_size": 4, "rms_norm_eps": 1e-06,
|
||||
"n_routed_experts": 128, "num_experts_per_tok": 8, "n_shared_experts": 0,
|
||||
"intermediate_size": 1152, "route_scale": 8.0, "final_logit_softcapping": 30.0,
|
||||
"local_layer_ids": [0,1,2,3,4,6,7,8,9,10,12,13,14,15,16,18,19,20,21,22],
|
||||
"loop_config": {"core_start":6,"core_end":18,"num_passes":3,"gate_rank":64,"is_varloop":false}
|
||||
},
|
||||
"mtp_config": {
|
||||
"hidden_size": 2304, "num_hidden_layers": 3, "num_attention_heads": 24,
|
||||
"num_key_value_heads": 8, "head_dim": 128, "intermediate_size": 9216,
|
||||
"block_size": 8, "markov_rank": 256, "rope_theta": 1000000.0, "rms_norm_eps": 1e-06,
|
||||
"sliding_window_size": 1024, "local_layer_ids": [0,2], "target_layer_ids": [5,23,41,48]
|
||||
},
|
||||
"quantization_config": {"quant_method":"modelopt","quant_algo":"NVFP4"}
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn parse_live_config() {
|
||||
let c = parse_config(CFG).unwrap();
|
||||
assert_eq!(c.eos_token_id, 200006);
|
||||
assert_eq!(c.quant_algo, "NVFP4");
|
||||
assert_eq!(c.text.hidden, 2304);
|
||||
assert_eq!(c.text.n_layers, 24);
|
||||
assert_eq!(c.text.n_experts, 128);
|
||||
assert_eq!(c.text.top_k, 8);
|
||||
assert_eq!(c.text.inter, 1152);
|
||||
assert_eq!(c.text.local_layer_ids.len(), 20);
|
||||
assert_eq!(c.text.loop_cfg.core_start, 6);
|
||||
assert_eq!(c.text.loop_cfg.core_end, 18);
|
||||
assert_eq!(c.text.loop_cfg.num_passes, 3);
|
||||
let mtp = c.mtp.unwrap();
|
||||
assert_eq!(mtp.block_size, 8);
|
||||
assert_eq!(mtp.markov_rank, 256);
|
||||
assert_eq!(mtp.target_layer_ids, vec![5, 23, 41, 48]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_attention_layers_are_complement_of_local() {
|
||||
let c = parse_config(CFG).unwrap();
|
||||
assert_eq!(c.text.full_attention_layers(), vec![5, 11, 17, 23]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_inconsistent_config() {
|
||||
let bad = CFG.replace("\"num_experts_per_tok\": 8", "\"num_experts_per_tok\": 256");
|
||||
assert!(parse_config(&bad).is_err());
|
||||
let bad2 = CFG.replace("\"core_start\":6", "\"core_start\":18");
|
||||
assert!(parse_config(&bad2).is_err());
|
||||
let bad3 = CFG.replace("\"num_key_value_heads\": 8", "\"num_key_value_heads\": 7");
|
||||
assert!(parse_config(&bad3).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_mtp_is_optional() {
|
||||
// A config without mtp_config still parses (mtp = None).
|
||||
let no_mtp = CFG.replace(
|
||||
r#""mtp_config": {
|
||||
"hidden_size": 2304, "num_hidden_layers": 3, "num_attention_heads": 24,
|
||||
"num_key_value_heads": 8, "head_dim": 128, "intermediate_size": 9216,
|
||||
"block_size": 8, "markov_rank": 256, "rope_theta": 1000000.0, "rms_norm_eps": 1e-06,
|
||||
"sliding_window_size": 1024, "local_layer_ids": [0,2], "target_layer_ids": [5,23,41,48]
|
||||
},"#,
|
||||
"",
|
||||
);
|
||||
assert!(parse_config(&no_mtp).unwrap().mtp.is_none());
|
||||
}
|
||||
|
||||
/// Opt-in live check against the real artifact (host-dependent):
|
||||
/// `cargo test -p vetta-infer-ld -- --ignored inkling_live`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn inkling_live_config() {
|
||||
let raw = std::fs::read_to_string("/mnt/models/Inkling/safetensors/config.json").unwrap();
|
||||
let c = parse_config(&raw).unwrap();
|
||||
assert_eq!(c.text.hidden, 2304);
|
||||
assert_eq!(c.text.n_layers, 24);
|
||||
assert_eq!(c.text.n_experts, 128);
|
||||
assert_eq!(c.text.full_attention_layers(), vec![5, 11, 17, 23]);
|
||||
assert_eq!(c.quant_algo, "NVFP4");
|
||||
assert_eq!(c.mtp.unwrap().target_layer_ids, vec![5, 23, 41, 48]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
//! 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, 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());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@
|
||||
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
|
||||
|
||||
pub mod bundle;
|
||||
pub mod inkling;
|
||||
pub mod inkling_ir;
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
|
||||
Reference in new issue
Block a user