// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
// Source: tool/gen/nn/schema/ml/ml_nn_empyrealm.json
// generator_version=8; schema_sha256=6f3ad0f41900bbedc6182f7d23c110987a9b3dfc5cdd38708dd9240916e73c8e
use std::rc::Rc;
use crate::{DType, Engine, Error, Matrix, Result};
use super::{
AttentionCache, Embedding, Ffn, Mamba3, Mamba3Config, Mamba3State, Moe, MultiHeadAttention,
RmsNorm,
};
use crate::ml::{Module, ModuleRegistry, autograd};
// OA donor: oacpp/source/cpp/lib/oa/ml/nn/empyrealm/empyrealmCore.cpp
// Adaptation: Complete Rust hybrid composition diverging from the donor's renamed Mamba-3 copies: embedding plus an interleaved Mamba-3/causal-attention block stack (Nemotron-style), pre-normalized residual mixers, dense or routed-expert SwiGLU feed-forward tails and a final RMSNorm; preserves seeded child construction, the embed/block_*/tail-norm checkpoint tree, checked U8/U32 token and FP32 embedded shapes, and extends the caller-owned decode state across per-block Mamba3State and AttentionCache slots; renames public EmpyrealmCore to Empyrealm
/// Layer schedule and widths for the hybrid `Empyrealm` stack.
///
/// `attention_every` interleaves one causal self-attention block after every
/// `attention_every - 1` Mamba-3 blocks, at positions
/// `k * attention_every - 1`; zero produces a pure Mamba-3 stack. Every block
/// owns a pre-normalized residual mixer plus a dense or routed-expert feed-
/// forward tail, and the stack ends in a final RMSNorm.
#[derive(Clone, Debug, PartialEq)]
pub struct EmpyrealmConfig {
/// Mixer block count.
pub layers: usize,
/// Attention block period; `0` disables attention entirely.
pub attention_every: usize,
/// Head count for attention blocks; must divide `mamba.model_width`.
pub attention_heads: usize,
/// Packed sequence length attention blocks are built and required to run.
pub sequence_length: usize,
/// Hidden width of each block's feed-forward tail.
pub ffn_hidden: usize,
/// Routed expert count; `0` selects the dense SwiGLU feed-forward.
pub moe_experts: usize,
/// Experts activated per token when `moe_experts` is nonzero.
pub moe_experts_per_token: usize,
/// Normalization epsilon shared by RMSNorm and the feed-forward tails.
pub epsilon: f32,
/// Mamba-3 block configuration; `model_width` owns the stack width.
pub mamba: Mamba3Config,
}
impl EmpyrealmConfig {
/// Construct the OA hybrid defaults for one model width.
pub fn new(model_width: usize, sequence_length: usize) -> Self {
Self {
layers: 4,
attention_every: 4,
attention_heads: 4,
sequence_length,
ffn_hidden: model_width * 2,
moe_experts: 0,
moe_experts_per_token: 0,
epsilon: 1e-5,
mamba: Mamba3Config::new(model_width),
}
}
}
/// Per-block decode state kind, matching the block's mixer.
enum EmpyrealmLayerState {
Mamba(Mamba3State),
Attention(AttentionCache),
}
/// Caller-owned per-block decode state for `Empyrealm`.
///
/// Entries mirror the block schedule one to one: Mamba-3 blocks own a
/// [`Mamba3State`] and attention blocks own an [`AttentionCache`]. Obtaining
/// it through [`Empyrealm::new_state`] binds it to that module instance and
/// keeps every child owner check intact.
pub struct EmpyrealmState {
owner_id: u64,
batch_size: usize,
layers: Vec<EmpyrealmLayerState>,
}
impl EmpyrealmState {
/// Return the fixed batch size accepted by this state.
pub const fn batch_size(&self) -> usize {
self.batch_size
}
/// Return the number of per-block decode slots.
pub fn layer_count(&self) -> usize {
self.layers.len()
}
}
/// Block mixer kind for the `Empyrealm` hybrid stack.
enum EmpyrealmMixer {
Mamba(Rc<Mamba3>),
Attention(Rc<MultiHeadAttention>),
}
/// Block feed-forward kind for the `Empyrealm` hybrid stack.
enum EmpyrealmFfn {
Dense(Rc<Ffn>),
Routed(Rc<Moe>),
}
/// One pre-normalized residual block of the `Empyrealm` hybrid stack.
struct EmpyrealmBlock {
model_width: usize,
norm: Rc<RmsNorm>,
mixer: EmpyrealmMixer,
ffn: EmpyrealmFfn,
registry: ModuleRegistry,
}
impl EmpyrealmBlock {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
let normed = self.norm.forward(input)?;
let mixed = match &self.mixer {
EmpyrealmMixer::Mamba(mixer) => mixer.forward(&normed)?,
EmpyrealmMixer::Attention(attention) => {
let [batch, sequence, _] = input.shape() else {
return Err(Error::invalid_argument(
"Empyrealm block input must have shape [B, S, D]",
));
};
let rows = batch
.checked_mul(*sequence)
.ok_or_else(|| Error::invalid_argument("Empyrealm packed row count overflows usize"))?;
attention
.forward(&normed.reshape([rows, self.model_width])?)?
.reshape(input.shape().to_vec())?
}
};
let residual = crate::matrix::add(&mixed, input)?;
self.tail(&residual)
}
fn tail(&self, residual: &Matrix) -> Result<Matrix> {
match &self.ffn {
EmpyrealmFfn::Dense(ffn) => ffn.forward(residual),
EmpyrealmFfn::Routed(moe) => {
let rows = residual
.element_count()
.checked_div(self.model_width)
.ok_or_else(|| {
Error::invalid_argument("Empyrealm feed-forward width does not divide the residual")
})?;
moe
.forward(&residual.reshape([rows, self.model_width])?)?
.reshape(residual.shape().to_vec())
}
}
}
fn new_state(&self, batch_size: usize) -> Result<EmpyrealmLayerState> {
match &self.mixer {
EmpyrealmMixer::Mamba(mixer) => mixer.new_state(batch_size).map(EmpyrealmLayerState::Mamba),
EmpyrealmMixer::Attention(attention) => attention
.new_cache(batch_size)
.map(EmpyrealmLayerState::Attention),
}
}
fn step(&self, input: &Matrix, state: &mut EmpyrealmLayerState) -> Result<Matrix> {
let normed = self.norm.forward(input)?;
let mixed = match (&self.mixer, state) {
(EmpyrealmMixer::Mamba(mixer), EmpyrealmLayerState::Mamba(state)) => {
mixer.step(&normed, state)?
}
(EmpyrealmMixer::Attention(attention), EmpyrealmLayerState::Attention(cache)) => {
let batch = cache.batch_size();
attention
.step(&normed.reshape([batch, self.model_width])?, cache)?
.reshape([batch, 1, self.model_width])?
}
_ => {
return Err(Error::invalid_argument(
"Empyrealm decode state does not match the block schedule",
));
}
};
let residual = crate::matrix::add(&mixed, input)?;
self.tail(&residual)
}
}
impl Module for EmpyrealmBlock {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
EmpyrealmBlock::forward(self, input)
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}
/// OA's embedding-plus-hybrid-Mamba core with one canonical Rust execution path.
///
/// The stack interleaves Mamba-3 blocks with evenly spaced causal
/// self-attention blocks (Nemotron-style), each followed by a dense or
/// routed-expert feed-forward tail. Whole-sequence forward runs through the
/// module graph; single-token decode threads caller-owned
/// [`EmpyrealmState`] through `step`/`step_embedded`.
pub struct Empyrealm {
registry: ModuleRegistry,
embedding: Rc<Embedding>,
blocks: Vec<Rc<EmpyrealmBlock>>,
norm: Rc<RmsNorm>,
model_width: usize,
sequence_length: usize,
has_attention: bool,
}
impl Empyrealm {
#[allow(clippy::too_many_arguments)]
pub fn new_with_seed(vocab_size: usize, config: EmpyrealmConfig, seed: u64) -> Result<Self> {
Self::new_with_seed_on(&Engine::current()?, vocab_size, config, seed)
}
/// Construct a deterministic token embedding and hybrid mixer stack.
///
/// # Errors
///
/// Returns an error for invalid schedule/width/routing configuration or
/// when a child module cannot be constructed or registered.
pub fn new_with_seed_on(
engine: &Engine,
vocab_size: usize,
config: EmpyrealmConfig,
seed: u64,
) -> Result<Self> {
if config.layers == 0
|| config.ffn_hidden == 0
|| config.sequence_length == 0
|| config.mamba.model_width == 0
{
return Err(Error::invalid_argument(
"Empyrealm requires positive layers, ffn_hidden, sequence_length, and model_width",
));
}
if !config.epsilon.is_finite() || config.epsilon <= 0.0 {
return Err(Error::invalid_argument(
"Empyrealm epsilon must be finite and positive",
));
}
if config.attention_every > 0
&& (config.attention_heads == 0
|| !config
.mamba
.model_width
.is_multiple_of(config.attention_heads))
{
return Err(Error::invalid_argument(
"Empyrealm attention_heads must be positive and divide model_width",
));
}
if config.moe_experts > 0
&& (config.moe_experts_per_token == 0 || config.moe_experts_per_token > config.moe_experts)
{
return Err(Error::invalid_argument(
"Empyrealm requires 1 <= moe_experts_per_token <= moe_experts",
));
}
let model_width = config.mamba.model_width;
let embedding = Rc::new(Embedding::new_with_seed_on(
engine,
vocab_size,
model_width,
seed,
)?);
let mut registry = ModuleRegistry::new();
registry.register_module("embed", embedding.clone())?;
let mut blocks = Vec::with_capacity(config.layers);
let mut attention_indices = Vec::new();
for index in 0..config.layers {
let block_seed = seed
.wrapping_add(1)
.wrapping_add((index as u64).wrapping_mul(64));
let is_attention =
config.attention_every > 0 && index % config.attention_every == config.attention_every - 1;
let norm = Rc::new(RmsNorm::new_on(engine, model_width, config.epsilon)?);
let mixer = if is_attention {
attention_indices.push(index);
EmpyrealmMixer::Attention(Rc::new(MultiHeadAttention::new_with_seed_on(
engine,
model_width,
config.attention_heads,
config.sequence_length,
block_seed,
)?))
} else {
EmpyrealmMixer::Mamba(Rc::new(Mamba3::new_with_seed_on(
engine,
config.mamba,
block_seed,
)?))
};
let ffn = if config.moe_experts > 0 {
EmpyrealmFfn::Routed(Rc::new(Moe::new_with_seed_on(
engine,
model_width,
config.ffn_hidden,
config.moe_experts,
config.moe_experts_per_token,
config.epsilon,
block_seed.wrapping_add(32),
)?))
} else {
EmpyrealmFfn::Dense(Rc::new(Ffn::new_with_seed_on(
engine,
model_width,
config.ffn_hidden,
config.epsilon,
block_seed.wrapping_add(32),
)?))
};
let mut block_registry = ModuleRegistry::new();
block_registry.register_module("norm", norm.clone())?;
match &mixer {
EmpyrealmMixer::Mamba(module) => {
block_registry.register_module("mixer", module.clone())?;
}
EmpyrealmMixer::Attention(module) => {
block_registry.register_module("mixer", module.clone())?;
}
}
match &ffn {
EmpyrealmFfn::Dense(module) => {
block_registry.register_module("ffn", module.clone())?;
}
EmpyrealmFfn::Routed(module) => {
block_registry.register_module("ffn", module.clone())?;
}
}
let block = Rc::new(EmpyrealmBlock {
model_width,
norm,
mixer,
ffn,
registry: block_registry,
});
registry.register_module(format!("block_{index}"), block.clone())?;
blocks.push(block);
}
let norm = Rc::new(RmsNorm::new_on(engine, model_width, config.epsilon)?);
registry.register_module("tail_norm", norm.clone())?;
Ok(Self {
registry,
embedding,
blocks,
norm,
model_width,
sequence_length: config.sequence_length,
has_attention: !attention_indices.is_empty(),
})
}
/// Embed a nonempty rank-two token grid and evaluate the hybrid stack.
///
/// # Errors
///
/// Returns an error unless `tokens` is U8/U32 `[batch, sequence]` matching
/// the configured sequence length, or a child operation cannot be recorded.
pub fn forward(&self, tokens: &Matrix) -> Result<Matrix> {
let [batch, sequence] = tokens.shape() else {
return Err(Error::invalid_argument(
"Empyrealm tokens must have shape [batch, sequence]",
));
};
if !matches!(tokens.dtype(), DType::U8 | DType::U32) || *batch == 0 || *sequence == 0 {
return Err(Error::invalid_argument(
"Empyrealm tokens must be a nonempty U8/U32 Matrix",
));
}
let embedded = self.embedding.forward(tokens)?;
self.forward_embedded(&embedded)
}
/// Evaluate the hybrid stack over pre-embedded `[B, S, D]` features.
///
/// When the stack contains attention blocks, `S` must equal the configured
/// `sequence_length`. Output is `[B, S, D]` after the final RMSNorm.
///
/// # Errors
///
/// Returns an error unless the input is nonempty FP32
/// `[B, S, model_width]`, the sequence length matches an attention-bearing
/// configuration, or a child operation cannot be recorded.
pub fn forward_embedded(&self, embedded: &Matrix) -> Result<Matrix> {
let [batch, sequence, width] = embedded.shape() else {
return Err(Error::invalid_argument(
"Empyrealm embedded input must have shape [B, S, D]",
));
};
if embedded.dtype() != DType::F32 || *batch == 0 || *sequence == 0 || *width != self.model_width
{
return Err(Error::invalid_argument(format!(
"Empyrealm requires nonempty F32 [B, S, {}]; found {:?} {}",
self.model_width,
embedded.shape(),
embedded.dtype().token()
)));
}
if self.has_attention && *sequence != self.sequence_length {
return Err(Error::invalid_argument(format!(
"Empyrealm attention blocks require S = {}; found {}",
self.sequence_length, sequence,
)));
}
let mut output = embedded.clone();
for block in &self.blocks {
output = block.forward(&output)?;
}
self.norm.forward(&output)
}
/// Allocate a per-block decode state owned by this module.
///
/// # Errors
///
/// Returns an error when `batch_size` is zero or a child state or cache
/// cannot be allocated.
pub fn new_state(&self, batch_size: usize) -> Result<EmpyrealmState> {
if batch_size == 0 {
return Err(Error::invalid_argument(
"Empyrealm decode state requires a positive batch size",
));
}
let mut layers = Vec::with_capacity(self.blocks.len());
for block in &self.blocks {
layers.push(block.new_state(batch_size)?);
}
Ok(EmpyrealmState {
owner_id: self.embedding.weight().data().value_id(),
batch_size,
layers,
})
}
/// Embed one token column and advance every block's decode state.
///
/// `tokens` must be U8/U32 `[batch, 1]`. This is an inference-only path.
///
/// # Errors
///
/// Returns an error for invalid tokens, an active gradient tape, or a
/// failed embedding or step recording.
pub fn step(&self, tokens: &Matrix, state: &mut EmpyrealmState) -> Result<Matrix> {
let [batch, sequence] = tokens.shape() else {
return Err(Error::invalid_argument(
"Empyrealm step tokens must have shape [batch, 1]",
));
};
if !matches!(tokens.dtype(), DType::U8 | DType::U32) || *sequence != 1 {
return Err(Error::invalid_argument(
"Empyrealm step tokens must be U8/U32 [batch, 1]",
));
}
if *batch != state.batch_size {
return Err(Error::invalid_argument(format!(
"Empyrealm step batch {} does not match state batch {}",
batch, state.batch_size,
)));
}
let embedded = self.embedding.forward(tokens)?;
self.step_embedded(&embedded, state)
}
/// Advance one pre-embedded `[B, 1, D]` position through the stack.
///
/// This is an inference-only operation: recurrent-state differentiation is
/// not admitted, and calling it while a [`crate::ml::GradientTape`] is
/// active returns an error.
///
/// # Errors
///
/// Returns an error for an active gradient tape, a state owned by another
/// module, mismatched batch/shape/dtype, or failed recording.
pub fn step_embedded(&self, embedded: &Matrix, state: &mut EmpyrealmState) -> Result<Matrix> {
if autograd::recording_active() {
return Err(Error::failed_precondition(
"Empyrealm decode is inference-only and cannot run inside a GradientTape",
));
}
let owner = self.embedding.weight().data();
if state.owner_id != owner.value_id() {
return Err(Error::invalid_argument(
"Empyrealm decode state belongs to another module instance",
));
}
if embedded.shape() != [state.batch_size, 1, self.model_width] || embedded.dtype() != DType::F32
{
return Err(Error::invalid_argument(format!(
"Empyrealm step requires F32 input [{}, 1, {}]; found {:?} {}",
state.batch_size,
self.model_width,
embedded.shape(),
embedded.dtype().token()
)));
}
if state.layers.len() != self.blocks.len() {
return Err(Error::invalid_argument(
"Empyrealm decode state does not match the block schedule",
));
}
let mut output = embedded.clone();
for (block, layer) in self.blocks.iter().zip(state.layers.iter_mut()) {
output = block.step(&output, layer)?;
}
self.norm.forward(&output)
}
/// Return the number of blocks in the hybrid stack.
pub fn layer_count(&self) -> usize {
self.blocks.len()
}
/// Return the block positions holding self-attention mixers.
pub fn attention_indices(&self) -> Vec<usize> {
self
.blocks
.iter()
.enumerate()
.filter_map(|(index, block)| match &block.mixer {
EmpyrealmMixer::Attention(_) => Some(index),
EmpyrealmMixer::Mamba(_) => None,
})
.collect()
}
}
impl Module for Empyrealm {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
Empyrealm::forward(self, input)
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}