cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
Documentation
// SPDX-License-Identifier: MIT OR Apache-2.0

// NOTE: This module implements the main MoeRouter. High LOC is due to the
// full public API, loading logic, multiple routing modes, and extensive tests.
// Further modularization planned.

//! Public MoE router API. Checkpoint bytes come from `engram-parser` 0.3.0.
//!
//! Private helpers live in:
//! - `moe/checkpoint.rs` for normalized tensor binding (migration shim)
//! - `moe/adapter.rs` for checkpoint adapter resolution and tensor selection
//! - `moe/routing.rs` for routing math and embedding resampling
//!
//! GGUF and Safetensors parsing, inventory, and packed dequantization are
//! owned by `engram-parser` (`features = ["safetensors"]`, validated on
//! 0.3.0). This crate binds those tensors into reference-backend `f32`
//! routing. It does not know the container format in the scoring loop.
//! `MappedCheckpoint` is a temporary shim; see that module for the removal
//! condition. Token rows call engram's Q8_0, Q5_K, and Q6_K decoders.
//! IQ3_S / IQ3_XXS stay errors: engram 0.3.0 does not decode those wire
//! types. Do not reimplement packed dequant here.

mod adapter;
mod checkpoint;
mod routing;

#[cfg(test)]
pub(crate) mod test_fixtures;

use self::adapter::{ModelAdapter, resolve_adapter};
use self::checkpoint::{BoundGate, MappedCheckpoint, open_mapped_checkpoint};
use self::routing::{
    apply_extract_token_options, checkpoint_gate_scores, normalize_l2, resample_embedding,
    synthetic_gate_scores,
};
use crate::error::{HybridError, Result};
pub use crate::types::RoutingMode;
pub use crate::types::{EMBEDDING_DIM, ExtractTokenOptions, MAX_STUB_EXPERTS, MAX_TARGET_DIM};

pub(crate) use self::routing::{reject_nan_routing_scores, route_top_k};

pub struct MoeRouter {
    model_path: String,
    num_experts: usize,
    top_k: usize,
    loaded: bool,
    metadata: RouterMetadata,
    adapter: Option<ModelAdapter>,
    routing_mode: RoutingMode,
    checkpoint: Option<MappedCheckpoint>,
    /// Decoded once at load. `None` for the synthetic stub router.
    bound_gate: Option<BoundGate>,
}

#[derive(Debug, Clone, Default)]
pub struct RouterMetadata {
    pub architecture: String,
    pub hidden_size: usize,
    pub num_layers: usize,
    pub num_experts: usize,
    pub expert_used_count: usize,
    pub quantization: String,
    pub routing_tensor_name: String,
}

#[derive(Debug, Clone)]
pub struct MoeOutput {
    pub expert_weights: Vec<f32>,
    pub selected_experts: Vec<usize>,
    pub hidden: Vec<f32>,
}

/// Rejects `num_experts` beyond the checkpoint before running `bind`, which
/// decodes the gate and copies the whole token-embedding payload.
fn bind_after_expert_count_check<T>(
    effective_num_experts: usize,
    checkpoint_experts: usize,
    bind: impl FnOnce() -> Result<T>,
) -> Result<T> {
    if effective_num_experts > checkpoint_experts {
        return Err(HybridError::InvalidConfig(format!(
            "num_experts ({effective_num_experts}) exceeds checkpoint expert_count ({checkpoint_experts})"
        )));
    }
    bind()
}

impl MoeRouter {
    /// Load a checkpoint and route through its gate weights.
    ///
    /// Uses [`RoutingMode::default()`] (`DenseSim`), so `forward` scores the
    /// bound routing tensor. Pass [`RoutingMode::StubUniform`] to
    /// [`Self::load_with_mode`] explicitly when uniform stub output is wanted;
    /// `load` never selects the stub for a loaded checkpoint.
    pub fn load(model_path: &str, num_experts: usize, top_k: usize) -> Result<Self> {
        Self::load_with_mode(model_path, num_experts, top_k, RoutingMode::default())
    }

    pub fn load_with_mode(
        model_path: &str,
        num_experts: usize,
        top_k: usize,
        routing_mode: RoutingMode,
    ) -> Result<Self> {
        if model_path.is_empty() {
            return Self::build_stub_router(num_experts, top_k, routing_mode);
        }

        let (metadata, mut checkpoint, adapter) = Self::probe_and_map(model_path)?;
        let effective_num_experts = if num_experts == 0 {
            metadata.num_experts
        } else {
            num_experts
        };
        let bound_gate =
            bind_after_expert_count_check(effective_num_experts, metadata.num_experts, || {
                checkpoint.bind_router_weights(
                    &adapter.token_embedding_tensor,
                    &adapter.routing_tensor,
                    model_path,
                )
            })?;

        let effective_top_k = if top_k == 0 {
            metadata.expert_used_count.max(1).min(effective_num_experts)
        } else {
            top_k.max(1).min(effective_num_experts)
        };
        Ok(Self {
            model_path: model_path.to_owned(),
            num_experts: effective_num_experts,
            top_k: effective_top_k,
            loaded: true,
            metadata,
            adapter: Some(adapter),
            routing_mode,
            checkpoint: Some(checkpoint),
            bound_gate: Some(bound_gate),
        })
    }

    fn build_stub_router(
        num_experts: usize,
        top_k: usize,
        routing_mode: RoutingMode,
    ) -> Result<Self> {
        // The stub sizes `expert_weights` and the synthetic gate scores from
        // this value, so it is bounded here rather than at first `forward`.
        // `usize::MAX` would otherwise reach `Vec::with_capacity` as a
        // capacity-overflow panic and a merely huge value as an
        // `handle_alloc_error` abort.
        if num_experts > MAX_STUB_EXPERTS {
            return Err(HybridError::InvalidConfig(format!(
                "stub router num_experts ({num_experts}) exceeds MAX_STUB_EXPERTS ({MAX_STUB_EXPERTS})"
            )));
        }
        let inferred_experts = num_experts.max(1);
        let inferred_top_k = top_k.max(1).min(inferred_experts);
        Ok(Self {
            model_path: String::new(),
            num_experts: inferred_experts,
            top_k: inferred_top_k,
            loaded: false,
            metadata: RouterMetadata {
                architecture: "stub".into(),
                hidden_size: EMBEDDING_DIM,
                num_layers: 0,
                num_experts: inferred_experts,
                expert_used_count: inferred_top_k,
                quantization: "stub".into(),
                routing_tensor_name: "synthetic".into(),
            },
            adapter: None,
            routing_mode,
            checkpoint: None,
            bound_gate: None,
        })
    }

    pub fn probe_model(path: &str) -> Result<RouterMetadata> {
        let (metadata, _checkpoint, _adapter) = Self::probe_and_map(path)?;
        Ok(metadata)
    }

    pub fn forward(&self, embedding: &[f32]) -> Result<MoeOutput> {
        if embedding.len() != EMBEDDING_DIM {
            return Err(HybridError::InputLengthMismatch {
                expected: EMBEDDING_DIM,
                got: embedding.len(),
            });
        }

        match self.routing_mode {
            RoutingMode::StubUniform => Ok(self.stub_output()),
            RoutingMode::DenseSim => self.simulate_moe_routing(embedding),
        }
    }

    /// Dequantize the checkpoint token row at native `hidden_size` (no resample, no L2).
    pub fn extract_token_embedding(&self, token_id: usize) -> Result<Vec<f32>> {
        self.extract_token_embedding_with_options(token_id, ExtractTokenOptions::default())
    }

    /// Dequantize a token row, optionally resampling and/or L2-normalizing.
    ///
    /// Returns [`HybridError::InvalidConfig`] when
    /// [`ExtractTokenOptions::target_dim`] is `Some(0)` (an empty row that only
    /// fails later as [`HybridError::InputLengthMismatch`]) or greater than
    /// [`MAX_TARGET_DIM`]. Resampling allocates the requested length, so the
    /// bound keeps a caller-supplied `usize` from reaching
    /// `Vec::with_capacity` as a capacity-overflow panic.
    pub fn extract_token_embedding_with_options(
        &self,
        token_id: usize,
        options: ExtractTokenOptions,
    ) -> Result<Vec<f32>> {
        if let Some(target_dim) = options.target_dim {
            if target_dim == 0 {
                return Err(HybridError::InvalidConfig(
                    "ExtractTokenOptions.target_dim must be greater than 0".into(),
                ));
            }
            if target_dim > MAX_TARGET_DIM {
                return Err(HybridError::InvalidConfig(format!(
                    "ExtractTokenOptions.target_dim ({target_dim}) exceeds MAX_TARGET_DIM ({MAX_TARGET_DIM})"
                )));
            }
        }
        let adapter = self
            .adapter
            .as_ref()
            .ok_or_else(|| HybridError::ModelLoad {
                path: self.model_path.clone(),
                reason: "checkpoint not loaded".into(),
            })?;
        let checkpoint = self
            .checkpoint
            .as_ref()
            .ok_or_else(|| HybridError::ModelLoad {
                path: self.model_path.clone(),
                reason: "checkpoint not loaded".into(),
            })?;
        let embedding = checkpoint.extract_token_embedding(
            &adapter.token_embedding_tensor,
            &self.model_path,
            token_id,
        )?;
        Ok(apply_extract_token_options(&embedding, options))
    }

    fn probe_and_map(path: &str) -> Result<(RouterMetadata, MappedCheckpoint, ModelAdapter)> {
        let checkpoint = open_mapped_checkpoint(path)?;
        let adapter = resolve_adapter(&checkpoint, path)?;
        let metadata = RouterMetadata {
            architecture: adapter.architecture.clone(),
            hidden_size: adapter.hidden_size,
            num_layers: adapter.num_layers,
            num_experts: adapter.num_experts,
            expert_used_count: adapter.expert_used_count,
            quantization: adapter.quantization.clone(),
            routing_tensor_name: adapter.routing_tensor.clone(),
        };
        Ok((metadata, checkpoint, adapter))
    }

    fn simulate_moe_routing(&self, embedding: &[f32]) -> Result<MoeOutput> {
        let gate_scores = self.gate_scores(embedding)?;
        let (expert_weights, selected_experts) = route_top_k(&gate_scores, self.top_k)?;
        let selected_mass: f32 = selected_experts
            .iter()
            .map(|&idx| expert_weights[idx])
            .sum();
        let hidden: Vec<f32> = embedding.iter().map(|&v| v * selected_mass).collect();

        Ok(MoeOutput {
            expert_weights,
            selected_experts,
            hidden,
        })
    }

    /// Gate scores for `embedding` under this router's checkpoint or synthetic
    /// policy. Exposed crate-wide so `snn::SpikingMoeRouter` can compose
    /// routing with an external [`crate::snn::SnnBackend`].
    pub(crate) fn gate_scores(&self, embedding: &[f32]) -> Result<Vec<f32>> {
        if let (Some(gate), Some(adapter)) = (&self.bound_gate, &self.adapter) {
            let mut routed_embedding = resample_embedding(embedding, adapter.hidden_size);
            normalize_l2(&mut routed_embedding);
            return checkpoint_gate_scores(
                &gate.dims,
                &gate.weights,
                &self.model_path,
                &adapter.routing_tensor,
                self.num_experts,
                &routed_embedding,
            );
        }

        Ok(synthetic_gate_scores(self.num_experts, embedding))
    }

    fn stub_output(&self) -> MoeOutput {
        let n = self.num_experts.max(1);
        MoeOutput {
            expert_weights: vec![1.0 / n as f32; n],
            selected_experts: (0..self.top_k.min(n)).collect(),
            hidden: vec![0.0; EMBEDDING_DIM],
        }
    }

    pub fn is_loaded(&self) -> bool {
        self.loaded
    }

    pub fn model_path(&self) -> &str {
        &self.model_path
    }

    pub fn architecture(&self) -> &str {
        &self.metadata.architecture
    }

    pub fn quantization(&self) -> &str {
        &self.metadata.quantization
    }

    pub fn hidden_size(&self) -> usize {
        self.metadata.hidden_size
    }

    pub fn num_layers(&self) -> usize {
        self.metadata.num_layers
    }

    pub fn checkpoint_num_experts(&self) -> usize {
        self.metadata.num_experts
    }

    pub fn checkpoint_expert_used_count(&self) -> usize {
        self.metadata.expert_used_count
    }

    pub fn routing_tensor_name(&self) -> &str {
        &self.metadata.routing_tensor_name
    }

    pub fn num_experts(&self) -> usize {
        self.num_experts
    }

    pub fn top_k(&self) -> usize {
        self.top_k
    }

    pub fn routing_mode(&self) -> RoutingMode {
        self.routing_mode
    }
}

#[cfg(test)]
mod tests;