Skip to main content

oa/ml/nn/
empyrealm.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_empyrealm.json
3// generator_version=8; schema_sha256=0c4389a30952cfe058829bfcdfd4aba526712700ca878f8fce810dbc18fd8afc
4
5use std::rc::Rc;
6
7use crate::{DType, Error, Matrix, Result, Runtime};
8
9use super::{
10	AttentionCache, Embedding, Ffn, Mamba3, Mamba3Config, Mamba3State, Moe, MultiHeadAttention,
11	RmsNorm,
12};
13
14use crate::ml::{Module, ModuleRegistry, autograd};
15
16// OA donor: oacpp/source/cpp/lib/oa/ml/nn/empyrealm/empyrealmCore.cpp
17// 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
18/// Layer schedule and widths for the hybrid `Empyrealm` stack.
19///
20/// `attention_every` interleaves one causal self-attention block after every
21/// `attention_every - 1` Mamba-3 blocks, at positions
22/// `k * attention_every - 1`; zero produces a pure Mamba-3 stack. Every block
23/// owns a pre-normalized residual mixer plus a dense or routed-expert feed-
24/// forward tail, and the stack ends in a final RMSNorm.
25#[derive(Clone, Debug, PartialEq)]
26pub struct EmpyrealmConfig {
27	/// Mixer block count.
28	pub layers: usize,
29	/// Attention block period; `0` disables attention entirely.
30	pub attention_every: usize,
31	/// Head count for attention blocks; must divide `mamba.model_width`.
32	pub attention_heads: usize,
33	/// Packed sequence length attention blocks are built and required to run.
34	pub sequence_length: usize,
35	/// Hidden width of each block's feed-forward tail.
36	pub ffn_hidden: usize,
37	/// Routed expert count; `0` selects the dense SwiGLU feed-forward.
38	pub moe_experts: usize,
39	/// Experts activated per token when `moe_experts` is nonzero.
40	pub moe_experts_per_token: usize,
41	/// Normalization epsilon shared by RMSNorm and the feed-forward tails.
42	pub epsilon: f32,
43	/// Mamba-3 block configuration; `model_width` owns the stack width.
44	pub mamba: Mamba3Config,
45}
46
47impl EmpyrealmConfig {
48	/// Construct the OA hybrid defaults for one model width.
49	pub fn new(model_width: usize, sequence_length: usize) -> Self {
50		Self {
51			layers: 4,
52			attention_every: 4,
53			attention_heads: 4,
54			sequence_length,
55			ffn_hidden: model_width * 2,
56			moe_experts: 0,
57			moe_experts_per_token: 0,
58			epsilon: 1e-5,
59			mamba: Mamba3Config::new(model_width),
60		}
61	}
62}
63
64/// Per-block decode state kind, matching the block's mixer.
65enum EmpyrealmLayerState {
66	Mamba(Mamba3State),
67	Attention(AttentionCache),
68}
69
70/// Caller-owned per-block decode state for `Empyrealm`.
71///
72/// Entries mirror the block schedule one to one: Mamba-3 blocks own a
73/// [`Mamba3State`] and attention blocks own an [`AttentionCache`]. Obtaining
74/// it through [`Empyrealm::new_state`] binds it to that module instance and
75/// keeps every child owner check intact.
76pub struct EmpyrealmState {
77	owner_id: u64,
78	batch_size: usize,
79	layers: Vec<EmpyrealmLayerState>,
80}
81
82impl EmpyrealmState {
83	/// Return the fixed batch size accepted by this state.
84	pub const fn batch_size(&self) -> usize {
85		self.batch_size
86	}
87
88	/// Return the number of per-block decode slots.
89	pub fn layer_count(&self) -> usize {
90		self.layers.len()
91	}
92}
93
94/// Block mixer kind for the `Empyrealm` hybrid stack.
95enum EmpyrealmMixer {
96	Mamba(Rc<Mamba3>),
97	Attention(Rc<MultiHeadAttention>),
98}
99
100/// Block feed-forward kind for the `Empyrealm` hybrid stack.
101enum EmpyrealmFfn {
102	Dense(Rc<Ffn>),
103	Routed(Rc<Moe>),
104}
105
106/// One pre-normalized residual block of the `Empyrealm` hybrid stack.
107struct EmpyrealmBlock {
108	model_width: usize,
109	norm: Rc<RmsNorm>,
110	mixer: EmpyrealmMixer,
111	ffn: EmpyrealmFfn,
112	registry: ModuleRegistry,
113}
114
115impl EmpyrealmBlock {
116	fn forward(&self, input: &Matrix) -> Result<Matrix> {
117		let normed = self.norm.forward(input)?;
118		let mixed = match &self.mixer {
119			EmpyrealmMixer::Mamba(mixer) => mixer.forward(&normed)?,
120			EmpyrealmMixer::Attention(attention) => {
121				let [batch, sequence, _] = input.shape() else {
122					return Err(Error::invalid_argument(
123						"Empyrealm block input must have shape [B, S, D]",
124					));
125				};
126				let rows = batch
127					.checked_mul(*sequence)
128					.ok_or_else(|| Error::invalid_argument("Empyrealm packed row count overflows usize"))?;
129				attention
130					.forward(&normed.reshape([rows, self.model_width])?)?
131					.reshape(input.shape().to_vec())?
132			}
133		};
134		let residual = crate::matrix::add(&mixed, input)?;
135		self.tail(&residual)
136	}
137
138	fn tail(&self, residual: &Matrix) -> Result<Matrix> {
139		match &self.ffn {
140			EmpyrealmFfn::Dense(ffn) => ffn.forward(residual),
141			EmpyrealmFfn::Routed(moe) => {
142				let rows = residual
143					.element_count()
144					.checked_div(self.model_width)
145					.ok_or_else(|| {
146						Error::invalid_argument("Empyrealm feed-forward width does not divide the residual")
147					})?;
148				moe
149					.forward(&residual.reshape([rows, self.model_width])?)?
150					.reshape(residual.shape().to_vec())
151			}
152		}
153	}
154
155	fn new_state(&self, batch_size: usize) -> Result<EmpyrealmLayerState> {
156		match &self.mixer {
157			EmpyrealmMixer::Mamba(mixer) => mixer.new_state(batch_size).map(EmpyrealmLayerState::Mamba),
158			EmpyrealmMixer::Attention(attention) => attention
159				.new_cache(batch_size)
160				.map(EmpyrealmLayerState::Attention),
161		}
162	}
163
164	fn step(&self, input: &Matrix, state: &mut EmpyrealmLayerState) -> Result<Matrix> {
165		let normed = self.norm.forward(input)?;
166		let mixed = match (&self.mixer, state) {
167			(EmpyrealmMixer::Mamba(mixer), EmpyrealmLayerState::Mamba(state)) => {
168				mixer.step(&normed, state)?
169			}
170			(EmpyrealmMixer::Attention(attention), EmpyrealmLayerState::Attention(cache)) => {
171				let batch = cache.batch_size();
172				attention
173					.step(&normed.reshape([batch, self.model_width])?, cache)?
174					.reshape([batch, 1, self.model_width])?
175			}
176			_ => {
177				return Err(Error::invalid_argument(
178					"Empyrealm decode state does not match the block schedule",
179				));
180			}
181		};
182		let residual = crate::matrix::add(&mixed, input)?;
183		self.tail(&residual)
184	}
185}
186
187impl Module for EmpyrealmBlock {
188	fn forward(&self, input: &Matrix) -> Result<Matrix> {
189		EmpyrealmBlock::forward(self, input)
190	}
191
192	fn registry(&self) -> &ModuleRegistry {
193		&self.registry
194	}
195}
196
197/// OA's embedding-plus-hybrid-Mamba core with one canonical Rust execution path.
198///
199/// The stack interleaves Mamba-3 blocks with evenly spaced causal
200/// self-attention blocks (Nemotron-style), each followed by a dense or
201/// routed-expert feed-forward tail. Whole-sequence forward runs through the
202/// module graph; single-token decode threads caller-owned
203/// [`EmpyrealmState`] through `step`/`step_embedded`.
204pub struct Empyrealm {
205	registry: ModuleRegistry,
206	embedding: Rc<Embedding>,
207	blocks: Vec<Rc<EmpyrealmBlock>>,
208	norm: Rc<RmsNorm>,
209	model_width: usize,
210	sequence_length: usize,
211	has_attention: bool,
212}
213
214impl Empyrealm {
215	#[allow(clippy::too_many_arguments)]
216	pub fn new_with_seed(vocab_size: usize, config: EmpyrealmConfig, seed: u64) -> Result<Self> {
217		Self::new_with_seed_on(&Runtime::current()?, vocab_size, config, seed)
218	}
219
220	/// Construct a deterministic token embedding and hybrid mixer stack.
221	///
222	/// # Errors
223	///
224	/// Returns an error for invalid schedule/width/routing configuration or
225	/// when a child module cannot be constructed or registered.
226	pub fn new_with_seed_on(
227		runtime: &Runtime,
228		vocab_size: usize,
229		config: EmpyrealmConfig,
230		seed: u64,
231	) -> Result<Self> {
232		if config.layers == 0
233			|| config.ffn_hidden == 0
234			|| config.sequence_length == 0
235			|| config.mamba.model_width == 0
236		{
237			return Err(Error::invalid_argument(
238				"Empyrealm requires positive layers, ffn_hidden, sequence_length, and model_width",
239			));
240		}
241		if !config.epsilon.is_finite() || config.epsilon <= 0.0 {
242			return Err(Error::invalid_argument(
243				"Empyrealm epsilon must be finite and positive",
244			));
245		}
246		if config.attention_every > 0
247			&& (config.attention_heads == 0
248				|| !config
249					.mamba
250					.model_width
251					.is_multiple_of(config.attention_heads))
252		{
253			return Err(Error::invalid_argument(
254				"Empyrealm attention_heads must be positive and divide model_width",
255			));
256		}
257		if config.moe_experts > 0
258			&& (config.moe_experts_per_token == 0 || config.moe_experts_per_token > config.moe_experts)
259		{
260			return Err(Error::invalid_argument(
261				"Empyrealm requires 1 <= moe_experts_per_token <= moe_experts",
262			));
263		}
264		let model_width = config.mamba.model_width;
265		let embedding = Rc::new(Embedding::new_with_seed_on(
266			runtime,
267			vocab_size,
268			model_width,
269			seed,
270		)?);
271		let mut registry = ModuleRegistry::new();
272		registry.register_module("embed", embedding.clone())?;
273		let mut blocks = Vec::with_capacity(config.layers);
274		let mut attention_indices = Vec::new();
275		for index in 0..config.layers {
276			let block_seed = seed
277				.wrapping_add(1)
278				.wrapping_add((index as u64).wrapping_mul(64));
279			let is_attention =
280				config.attention_every > 0 && index % config.attention_every == config.attention_every - 1;
281			let norm = Rc::new(RmsNorm::new_on(runtime, model_width, config.epsilon)?);
282			let mixer = if is_attention {
283				attention_indices.push(index);
284				EmpyrealmMixer::Attention(Rc::new(MultiHeadAttention::new_with_seed_on(
285					runtime,
286					model_width,
287					config.attention_heads,
288					config.sequence_length,
289					block_seed,
290				)?))
291			} else {
292				EmpyrealmMixer::Mamba(Rc::new(Mamba3::new_with_seed_on(
293					runtime,
294					config.mamba,
295					block_seed,
296				)?))
297			};
298			let ffn = if config.moe_experts > 0 {
299				EmpyrealmFfn::Routed(Rc::new(Moe::new_with_seed_on(
300					runtime,
301					model_width,
302					config.ffn_hidden,
303					config.moe_experts,
304					config.moe_experts_per_token,
305					config.epsilon,
306					block_seed.wrapping_add(32),
307				)?))
308			} else {
309				EmpyrealmFfn::Dense(Rc::new(Ffn::new_with_seed_on(
310					runtime,
311					model_width,
312					config.ffn_hidden,
313					config.epsilon,
314					block_seed.wrapping_add(32),
315				)?))
316			};
317			let mut block_registry = ModuleRegistry::new();
318			block_registry.register_module("norm", norm.clone())?;
319			match &mixer {
320				EmpyrealmMixer::Mamba(module) => {
321					block_registry.register_module("mixer", module.clone())?;
322				}
323				EmpyrealmMixer::Attention(module) => {
324					block_registry.register_module("mixer", module.clone())?;
325				}
326			}
327			match &ffn {
328				EmpyrealmFfn::Dense(module) => {
329					block_registry.register_module("ffn", module.clone())?;
330				}
331				EmpyrealmFfn::Routed(module) => {
332					block_registry.register_module("ffn", module.clone())?;
333				}
334			}
335			let block = Rc::new(EmpyrealmBlock {
336				model_width,
337				norm,
338				mixer,
339				ffn,
340				registry: block_registry,
341			});
342			registry.register_module(format!("block_{index}"), block.clone())?;
343			blocks.push(block);
344		}
345		let norm = Rc::new(RmsNorm::new_on(runtime, model_width, config.epsilon)?);
346		registry.register_module("tail_norm", norm.clone())?;
347		Ok(Self {
348			registry,
349			embedding,
350			blocks,
351			norm,
352			model_width,
353			sequence_length: config.sequence_length,
354			has_attention: !attention_indices.is_empty(),
355		})
356	}
357
358	/// Embed a nonempty rank-two token grid and evaluate the hybrid stack.
359	///
360	/// # Errors
361	///
362	/// Returns an error unless `tokens` is U8/U32 `[batch, sequence]` matching
363	/// the configured sequence length, or a child operation cannot be recorded.
364	pub fn forward(&self, tokens: &Matrix) -> Result<Matrix> {
365		let [batch, sequence] = tokens.shape() else {
366			return Err(Error::invalid_argument(
367				"Empyrealm tokens must have shape [batch, sequence]",
368			));
369		};
370		if !matches!(tokens.dtype(), DType::U8 | DType::U32) || *batch == 0 || *sequence == 0 {
371			return Err(Error::invalid_argument(
372				"Empyrealm tokens must be a nonempty U8/U32 Matrix",
373			));
374		}
375		let embedded = self.embedding.forward(tokens)?;
376		self.forward_embedded(&embedded)
377	}
378
379	/// Evaluate the hybrid stack over pre-embedded `[B, S, D]` features.
380	///
381	/// When the stack contains attention blocks, `S` must equal the configured
382	/// `sequence_length`. Output is `[B, S, D]` after the final RMSNorm.
383	///
384	/// # Errors
385	///
386	/// Returns an error unless the input is nonempty FP32
387	/// `[B, S, model_width]`, the sequence length matches an attention-bearing
388	/// configuration, or a child operation cannot be recorded.
389	pub fn forward_embedded(&self, embedded: &Matrix) -> Result<Matrix> {
390		let [batch, sequence, width] = embedded.shape() else {
391			return Err(Error::invalid_argument(
392				"Empyrealm embedded input must have shape [B, S, D]",
393			));
394		};
395		if embedded.dtype() != DType::F32 || *batch == 0 || *sequence == 0 || *width != self.model_width
396		{
397			return Err(Error::invalid_argument(format!(
398				"Empyrealm requires nonempty F32 [B, S, {}]; found {:?} {}",
399				self.model_width,
400				embedded.shape(),
401				embedded.dtype().token()
402			)));
403		}
404		if self.has_attention && *sequence != self.sequence_length {
405			return Err(Error::invalid_argument(format!(
406				"Empyrealm attention blocks require S = {}; found {}",
407				self.sequence_length, sequence,
408			)));
409		}
410		let mut output = embedded.clone();
411		for block in &self.blocks {
412			output = block.forward(&output)?;
413		}
414		self.norm.forward(&output)
415	}
416
417	/// Allocate a per-block decode state owned by this module.
418	///
419	/// # Errors
420	///
421	/// Returns an error when `batch_size` is zero or a child state or cache
422	/// cannot be allocated.
423	pub fn new_state(&self, batch_size: usize) -> Result<EmpyrealmState> {
424		if batch_size == 0 {
425			return Err(Error::invalid_argument(
426				"Empyrealm decode state requires a positive batch size",
427			));
428		}
429		let mut layers = Vec::with_capacity(self.blocks.len());
430		for block in &self.blocks {
431			layers.push(block.new_state(batch_size)?);
432		}
433		Ok(EmpyrealmState {
434			owner_id: self.embedding.weight().data().value_id(),
435			batch_size,
436			layers,
437		})
438	}
439
440	/// Embed one token column and advance every block's decode state.
441	///
442	/// `tokens` must be U8/U32 `[batch, 1]`. This is an inference-only path.
443	///
444	/// # Errors
445	///
446	/// Returns an error for invalid tokens, an active gradient tape, or a
447	/// failed embedding or step recording.
448	pub fn step(&self, tokens: &Matrix, state: &mut EmpyrealmState) -> Result<Matrix> {
449		let [batch, sequence] = tokens.shape() else {
450			return Err(Error::invalid_argument(
451				"Empyrealm step tokens must have shape [batch, 1]",
452			));
453		};
454		if !matches!(tokens.dtype(), DType::U8 | DType::U32) || *sequence != 1 {
455			return Err(Error::invalid_argument(
456				"Empyrealm step tokens must be U8/U32 [batch, 1]",
457			));
458		}
459		if *batch != state.batch_size {
460			return Err(Error::invalid_argument(format!(
461				"Empyrealm step batch {} does not match state batch {}",
462				batch, state.batch_size,
463			)));
464		}
465		let embedded = self.embedding.forward(tokens)?;
466		self.step_embedded(&embedded, state)
467	}
468
469	/// Advance one pre-embedded `[B, 1, D]` position through the stack.
470	///
471	/// This is an inference-only operation: recurrent-state differentiation is
472	/// not admitted, and calling it while a [`crate::ml::GradientTape`] is
473	/// active returns an error.
474	///
475	/// # Errors
476	///
477	/// Returns an error for an active gradient tape, a state owned by another
478	/// module, mismatched batch/shape/dtype, or failed recording.
479	pub fn step_embedded(&self, embedded: &Matrix, state: &mut EmpyrealmState) -> Result<Matrix> {
480		if autograd::recording_active() {
481			return Err(Error::failed_precondition(
482				"Empyrealm decode is inference-only and cannot run inside a GradientTape",
483			));
484		}
485		let owner = self.embedding.weight().data();
486		if state.owner_id != owner.value_id() {
487			return Err(Error::invalid_argument(
488				"Empyrealm decode state belongs to another module instance",
489			));
490		}
491		if embedded.shape() != [state.batch_size, 1, self.model_width] || embedded.dtype() != DType::F32
492		{
493			return Err(Error::invalid_argument(format!(
494				"Empyrealm step requires F32 input [{}, 1, {}]; found {:?} {}",
495				state.batch_size,
496				self.model_width,
497				embedded.shape(),
498				embedded.dtype().token()
499			)));
500		}
501		if state.layers.len() != self.blocks.len() {
502			return Err(Error::invalid_argument(
503				"Empyrealm decode state does not match the block schedule",
504			));
505		}
506		let mut output = embedded.clone();
507		for (block, layer) in self.blocks.iter().zip(state.layers.iter_mut()) {
508			output = block.step(&output, layer)?;
509		}
510		self.norm.forward(&output)
511	}
512
513	/// Return the number of blocks in the hybrid stack.
514	pub fn layer_count(&self) -> usize {
515		self.blocks.len()
516	}
517
518	/// Return the block positions holding self-attention mixers.
519	pub fn attention_indices(&self) -> Vec<usize> {
520		self
521			.blocks
522			.iter()
523			.enumerate()
524			.filter_map(|(index, block)| match &block.mixer {
525				EmpyrealmMixer::Attention(_) => Some(index),
526				EmpyrealmMixer::Mamba(_) => None,
527			})
528			.collect()
529	}
530}
531
532impl Module for Empyrealm {
533	fn forward(&self, input: &Matrix) -> Result<Matrix> {
534		Empyrealm::forward(self, input)
535	}
536
537	fn registry(&self) -> &ModuleRegistry {
538		&self.registry
539	}
540}