use std::f32::consts::FRAC_1_SQRT_2;
use frink_gguf::TensorSource;
use crate::LoadError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DensePresence {
Required,
Optional,
}
#[derive(Debug, Clone, Copy)]
pub struct ParallelDenseFfn {
pub arch: &'static str,
pub presence: DensePresence,
pub sum_scale: Option<f32>,
pub lines: &'static str,
}
pub const PARALLEL_DENSE_FFN_ARCHITECTURES: &[ParallelDenseFfn] = &[
ParallelDenseFfn {
arch: "grok",
presence: DensePresence::Optional,
sum_scale: Some(FRAC_1_SQRT_2),
lines: "src/models/grok.cpp:66-68,171-184",
},
ParallelDenseFfn {
arch: "arctic",
presence: DensePresence::Required,
sum_scale: None,
lines: "src/models/arctic.cpp:38-42,118-154",
},
];
pub const SHARED_EXPERT_SUM_SCALE: &[(&str, f32, &str)] =
&[("cohere2moe", 0.5, "src/models/cohere2moe.cpp:248-260")];
pub fn shared_expert_sum_scale(arch: &str, has_shared_expert: bool) -> Option<f32> {
if !has_shared_expert {
return None;
}
SHARED_EXPERT_SUM_SCALE
.iter()
.find(|(a, _, _)| *a == arch)
.map(|(_, scale, _)| *scale)
}
pub fn parallel_dense_ffn(arch: &str) -> Option<&'static ParallelDenseFfn> {
PARALLEL_DENSE_FFN_ARCHITECTURES
.iter()
.find(|row| row.arch == arch)
}
pub fn parallel_dense_for_layer(
arch: &str,
file: &impl TensorSource,
l: usize,
) -> Result<Option<&'static ParallelDenseFfn>, LoadError> {
let Some(row) = parallel_dense_ffn(arch) else {
return Ok(None);
};
let names = ["ffn_gate", "ffn_up", "ffn_down"].map(|t| format!("blk.{l}.{t}.weight"));
let present = names
.iter()
.filter(|n| file.find_tensor(n).is_some())
.count();
match (present, row.presence) {
(3, _) => Ok(Some(row)),
(0, DensePresence::Optional) => Ok(None),
(0, DensePresence::Required) => Err(LoadError::Gguf(
frink_gguf::GgufError::TensorNotFound(format!(
"{} (the dense half of `{arch}`'s parallel dense + MoE layer, REQUIRED by {})",
names[1], row.lines
)),
)),
_ => Err(LoadError::UnsupportedFeature(
arch.to_string(),
format!(
"layer {l} carries {present} of the dense `ffn_gate` / `ffn_up` / `ffn_down` \
triple; {} reads all three or none",
row.lines
),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_source::StubSource;
const TRIPLE: [&str; 3] = [
"blk.0.ffn_gate.weight",
"blk.0.ffn_up.weight",
"blk.0.ffn_down.weight",
];
#[test]
fn presence_follows_each_rows_rule() {
let grok2 = parallel_dense_for_layer("grok", &StubSource::with_tensors(&TRIPLE), 0)
.unwrap()
.expect("Grok-2 has the branch");
assert_eq!(grok2.sum_scale, Some(FRAC_1_SQRT_2));
assert!(
parallel_dense_for_layer("grok", &StubSource::with_tensors(&[]), 0)
.unwrap()
.is_none()
);
let arctic = parallel_dense_for_layer("arctic", &StubSource::with_tensors(&TRIPLE), 0)
.unwrap()
.expect("Arctic always has the branch");
assert_eq!(arctic.sum_scale, None);
let err = parallel_dense_for_layer("arctic", &StubSource::with_tensors(&[]), 0)
.expect_err("REQUIRED");
assert!(err.to_string().contains("arctic.cpp:38-42"), "{err}");
for arch in ["grok", "arctic"] {
let err = parallel_dense_for_layer(arch, &StubSource::with_tensors(&TRIPLE[..2]), 0)
.err()
.unwrap_or_else(|| panic!("{arch}: 2 of 3 refused"));
assert!(err.to_string().contains("2 of the dense"), "{err}");
}
}
#[test]
fn a_dense_ffn_on_any_other_architecture_is_not_this_tables_business() {
for arch in ["llama", "deepseek", "dbrx", "qwen3moe", "smallthinker"] {
assert!(
parallel_dense_for_layer(arch, &StubSource::with_tensors(&TRIPLE), 0)
.unwrap()
.is_none(),
"{arch}"
);
}
}
#[test]
fn every_row_is_an_audited_generic_row() {
for row in PARALLEL_DENSE_FFN_ARCHITECTURES {
let profile = crate::capability::resolve_profile(row.arch).unwrap_or_else(|| {
panic!(
"`{}` ({}) is not a registered architecture",
row.arch, row.lines
)
});
assert!(matches!(
profile.path,
crate::capability::ArchPath::GenericGqa { .. }
));
assert!(
crate::capability::AUDITED_GENERIC_GQA.contains(&row.arch),
"{}",
row.arch
);
}
}
}