oarust 0.14.1

GPU-first semantic computing engine written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// @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
	}
}