Skip to main content

engram_parser/analysis/moe/
expert.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Per-expert raw weight bundle.
4//!
5//! Each expert has up to three projections (`gate`, `up`, `down`),
6//! stored as opaque byte buffers plus shape/dtype metadata. The parser
7//! never assembles a functional neural layer — callers receive raw
8//! bytes and are responsible for any downstream compute.
9
10use crate::gguf::DType;
11
12/// Owned raw tensor buffer: bytes + shape + dtype, no references into
13/// the source [`GgufLayout`](crate::gguf::GgufLayout).
14///
15/// This is an *analysis result type*, not a tensor abstraction:
16/// expert extraction may slice a stacked GGUF tensor, so the result
17/// holds expert-local `dims` plus owned `bytes`. It does not replace
18/// [`TensorInfo`](crate::checkpoint::TensorInfo) /
19/// [`Checkpoint::tensor_bytes`](crate::checkpoint::Checkpoint::tensor_bytes),
20/// which remain the core checkpoint contract. Its `dtype`/`ggml_type`
21/// fields make this extraction path GGUF-specific; any normalized
22/// cross-format expert tensor type is planned v0.4 work.
23#[derive(Debug, Clone)]
24pub struct RawTensor {
25    /// Source tensor name (e.g. `"blk.0.ffn_gate_exps.weight"`).
26    pub source_name: String,
27    /// Dimensions of this expert's slice (expert dimension stripped).
28    pub dims: Vec<usize>,
29    /// Dtype preserved from the GGUF directory.
30    pub dtype: DType,
31    /// Raw `ggml_type` code (useful for round-tripping unknown quants).
32    pub ggml_type: u32,
33    /// Raw byte payload — length equals the byte size of one expert's
34    /// chunk within a stacked tensor, or the whole tensor if the
35    /// checkpoint stores one tensor per expert.
36    pub bytes: Vec<u8>,
37    /// True if this buffer was sliced from a stacked `[n_experts, ...]`
38    /// tensor; false if the checkpoint stored a dedicated per-expert
39    /// tensor.
40    pub stacked_slice: bool,
41}
42
43/// Raw weights for a single MoE expert.
44///
45/// Fields are `Option<_>` because GGUF checkpoints differ on which
46/// expert projections they store. OLMoE exposes `gate / up / down`;
47/// other MoE families may omit or rename a subset.
48#[derive(Debug, Clone)]
49pub struct MoeExpertWeights {
50    /// Transformer block this expert belongs to.
51    pub block: usize,
52    /// Expert index within the block.
53    pub expert: usize,
54    /// `ffn_gate` projection, if present in the checkpoint.
55    pub gate: Option<RawTensor>,
56    /// `ffn_up` projection, if present.
57    pub up: Option<RawTensor>,
58    /// `ffn_down` projection, if present.
59    pub down: Option<RawTensor>,
60}
61
62impl MoeExpertWeights {
63    /// Convenience: `true` if all three projections were located.
64    pub fn is_complete(&self) -> bool {
65        self.gate.is_some() && self.up.is_some() && self.down.is_some()
66    }
67}