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

/// The JSON format is scoped to this crate's deterministic reference backend.
/// Each public transformer value carries its own version and rejects drift.
macro_rules! reference_serde {
    ($name:ident, $wire:ident { $($field:ident : $ty:ty),+ $(,)? }) => {
        #[derive(serde::Deserialize)]
        #[serde(deny_unknown_fields)]
        struct $wire {
            schema_version: u32,
            $($field: $ty,)+
        }

        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
            where S: serde::Serializer {
                use serde::ser::{Error, SerializeStruct};
                self.validate_wire().map_err(S::Error::custom)?;
                let mut wire = serializer.serialize_struct(stringify!($name), 1 + [$(stringify!($field)),+].len())?;
                wire.serialize_field("schema_version", &1u32)?;
                $(wire.serialize_field(stringify!($field), &self.$field)?;)+
                wire.end()
            }
        }

        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
            where D: serde::Deserializer<'de> {
                let wire: $wire = crate::reference_json::deserialize_object(deserializer)?;
                if wire.schema_version != 1 {
                    return Err(serde::de::Error::custom(format!("unsupported {} schema_version {}", stringify!($name), wire.schema_version)));
                }
                let value = Self { $($field: wire.$field,)+ };
                value.validate_wire().map_err(serde::de::Error::custom)?;
                Ok(value)
            }
        }
    };
}

/// Epsilon used by every LayerNorm in the reference transformer.
///
/// Shared by [`block::TransformerBlock::try_forward`], the final layer norm in
/// [`model::TransformerLM::try_hidden_states`], and the stage executor
/// ([`crate::stage::ReferenceExecutor`]) so a composed topology normalizes with
/// exactly the same constant as the monolithic forward pass.
pub(crate) const LAYER_NORM_EPS: f32 = 1e-5;

fn expect_shape(tensor: &crate::tensor::Tensor, expected: &[usize]) -> crate::error::Result<()> {
    if tensor.shape() != expected {
        return Err(crate::error::CortexError::ShapeMismatch {
            expected: expected.to_vec(),
            got: tensor.shape().to_vec(),
        });
    }
    Ok(())
}

/// Adds the `[1, cols]` (or `[cols]`) `bias` to every row of the 2-D `out`
/// in place. Replaces tiling the bias into a `[rows, cols]` tensor plus a third
/// buffer for `try_add`; each element still gets the same single `a + b`.
pub(crate) fn add_row_bias(
    out: &mut crate::tensor::Tensor,
    bias: &crate::tensor::Tensor,
) -> crate::error::Result<()> {
    let cols = match out.shape() {
        [_, cols] if *cols == bias.numel() => *cols,
        shape => {
            return Err(crate::error::CortexError::ShapeMismatch {
                expected: vec![shape.first().copied().unwrap_or(0), bias.numel()],
                got: shape.to_vec(),
            });
        }
    };
    if cols == 0 {
        return Ok(());
    }
    let b = bias.data();
    for row in out.data_mut().chunks_exact_mut(cols) {
        for (x, &bv) in row.iter_mut().zip(b) {
            *x += bv;
        }
    }
    Ok(())
}

/// Single head-configuration predicate shared by every constructor and wire
/// validator, so one bad input yields one error variant and one message.
///
/// A zero `dim` or `num_heads` is [`CortexError::ZeroWidth`] (`axis` is the
/// argument/field position the caller passes in); a non-dividing
/// `num_heads` is [`CortexError::InvalidConfig`].
pub(crate) fn check_head_config(
    op: &'static str,
    dim: usize,
    num_heads: usize,
    dim_axis: usize,
    heads_axis: usize,
) -> crate::error::Result<()> {
    use crate::error::CortexError;
    if dim == 0 {
        return Err(CortexError::ZeroWidth { op, axis: dim_axis });
    }
    if num_heads == 0 {
        return Err(CortexError::ZeroWidth {
            op,
            axis: heads_axis,
        });
    }
    if !dim.is_multiple_of(num_heads) {
        return Err(CortexError::InvalidConfig(format!(
            "num_heads ({num_heads}) must divide dim ({dim})"
        )));
    }
    Ok(())
}

/// Sum of tensor element counts. Saturates instead of overflowing, so a
/// parameter count over `pub` fields can never panic or wrap.
pub(crate) fn sum_numel<'a>(tensors: impl IntoIterator<Item = &'a crate::tensor::Tensor>) -> usize {
    tensors
        .into_iter()
        .fold(0usize, |acc, t| acc.saturating_add(t.numel()))
}

pub mod attention;
pub mod block;
pub mod model;

pub use attention::MultiHeadAttention;
pub use block::TransformerBlock;
pub use model::{TransformerConfig, TransformerLM};