Skip to main content

oa/ml/nn/
transformer.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_transformer.json
3// generator_version=8; schema_sha256=ab47d3b9cb45a138760c3807677ef78b03e4c5ccce65acf1d387e59608ab8c95
4
5use std::{cell::Cell, rc::Rc};
6
7use crate::{DType, Error, Matrix, Result, Runtime, matrix};
8
9use super::super::{Module, ModuleRegistry, matrix::gelu};
10
11use super::{AttentionCache, AttentionMode, LayerNorm, Linear, Moe, MultiHeadAttention};
12
13// OA donor: oacpp/source/cpp/lib/oa/ml/nn/transformer/transformer.cpp
14// Adaptation: Complete donor composition with constructor-owned adaptive child registration; shared typed dense/MoE recipes preserve parameter names, seed strides and MoE-owned RMSNorm/residual; Rust retains separate Linear/GELU dispatch and extends the donor MoE block recipe to a stacked language model
15#[derive(Clone, Copy)]
16enum FeedForwardConfig {
17	Dense,
18	Moe {
19		num_experts: usize,
20		experts_per_token: usize,
21	},
22}
23
24enum FeedForward {
25	Dense {
26		norm: Rc<LayerNorm>,
27		input: Rc<Linear>,
28		output: Rc<Linear>,
29	},
30	Moe(Rc<Moe>),
31}
32
33/// One pre-normalized causal Transformer block.
34pub struct TransformerBlock {
35	model_width: usize,
36	hidden_width: usize,
37	sequence_length: Cell<usize>,
38	num_heads: usize,
39	norm_attention: Rc<LayerNorm>,
40	attention: Rc<MultiHeadAttention>,
41	feed_forward: FeedForward,
42	adaptive_modulation: Option<Rc<Linear>>,
43	condition_dim: Option<usize>,
44	registry: ModuleRegistry,
45}
46
47impl TransformerBlock {
48	pub fn new_with_seed(
49		model_width: usize,
50		hidden_width: usize,
51		sequence_length: usize,
52		num_heads: usize,
53		epsilon: f32,
54		seed: u64,
55	) -> Result<Self> {
56		Self::new_with_seed_on(
57			&Runtime::current()?,
58			model_width,
59			hidden_width,
60			sequence_length,
61			num_heads,
62			epsilon,
63			seed,
64		)
65	}
66
67	/// Construct the canonical pre-norm attention and GELU feed-forward block.
68	///
69	/// # Errors
70	///
71	/// Returns an error for invalid dimensions or failed child construction.
72	#[allow(clippy::too_many_arguments)]
73	pub fn new_with_seed_on(
74		runtime: &Runtime,
75		model_width: usize,
76		hidden_width: usize,
77		sequence_length: usize,
78		num_heads: usize,
79		epsilon: f32,
80		seed: u64,
81	) -> Result<Self> {
82		Self::new_with_seed_config(
83			runtime,
84			model_width,
85			hidden_width,
86			sequence_length,
87			num_heads,
88			num_heads,
89			epsilon,
90			seed,
91			FeedForwardConfig::Dense,
92		)
93	}
94
95	/// Construct a dense block with zero-initialized adaptive conditioning.
96	///
97	/// The complete child tree is registered before the block is returned. This
98	/// is the Rust replacement for donor `enableAdaptiveConditioning`, whose
99	/// post-construction registry mutation would violate [`ModuleRegistry`]'s
100	/// fixed structural-ownership contract.
101	///
102	/// # Errors
103	///
104	/// Returns an error for invalid block dimensions, a zero condition width,
105	/// shape overflow, allocation failure, or child registration failure.
106	#[allow(
107		clippy::too_many_arguments,
108		reason = "the constructor preserves the donor block and conditioning dimensions"
109	)]
110	pub fn new_with_seed_conditioned(
111		model_width: usize,
112		hidden_width: usize,
113		sequence_length: usize,
114		num_heads: usize,
115		condition_dim: usize,
116		epsilon: f32,
117		seed: u64,
118	) -> Result<Self> {
119		Self::new_with_seed_conditioned_on(
120			&Runtime::current()?,
121			model_width,
122			hidden_width,
123			sequence_length,
124			num_heads,
125			condition_dim,
126			epsilon,
127			seed,
128		)
129	}
130
131	#[allow(clippy::too_many_arguments)]
132	pub fn new_with_seed_conditioned_on(
133		runtime: &Runtime,
134		model_width: usize,
135		hidden_width: usize,
136		sequence_length: usize,
137		num_heads: usize,
138		condition_dim: usize,
139		epsilon: f32,
140		seed: u64,
141	) -> Result<Self> {
142		Self::new_with_seed_on(
143			runtime,
144			model_width,
145			hidden_width,
146			sequence_length,
147			num_heads,
148			epsilon,
149			seed,
150		)?
151		.with_adaptive_conditioning(runtime, condition_dim)
152	}
153
154	/// Construct the donor pre-norm attention block with a sparse MoE residual.
155	///
156	/// The MoE owns its RMSNorm and residual connection, so this block does not
157	/// add a second feed-forward normalization or residual around it.
158	///
159	/// # Errors
160	///
161	/// Returns an error for invalid attention or MoE dimensions, failed child
162	/// construction, or registration failure.
163	#[allow(
164		clippy::too_many_arguments,
165		reason = "the constructor preserves the donor attention and MoE dimensions"
166	)]
167	pub fn new_with_seed_moe(
168		model_width: usize,
169		expert_hidden_width: usize,
170		sequence_length: usize,
171		num_heads: usize,
172		num_experts: usize,
173		experts_per_token: usize,
174		epsilon: f32,
175		seed: u64,
176	) -> Result<Self> {
177		Self::new_with_seed_moe_on(
178			&Runtime::current()?,
179			model_width,
180			expert_hidden_width,
181			sequence_length,
182			num_heads,
183			num_experts,
184			experts_per_token,
185			epsilon,
186			seed,
187		)
188	}
189
190	#[allow(clippy::too_many_arguments)]
191	pub fn new_with_seed_moe_on(
192		runtime: &Runtime,
193		model_width: usize,
194		expert_hidden_width: usize,
195		sequence_length: usize,
196		num_heads: usize,
197		num_experts: usize,
198		experts_per_token: usize,
199		epsilon: f32,
200		seed: u64,
201	) -> Result<Self> {
202		Self::new_with_seed_config(
203			runtime,
204			model_width,
205			expert_hidden_width,
206			sequence_length,
207			num_heads,
208			num_heads,
209			epsilon,
210			seed,
211			FeedForwardConfig::Moe {
212				num_experts,
213				experts_per_token,
214			},
215		)
216	}
217
218	/// Construct a sparse-MoE block with zero-initialized adaptive conditioning.
219	///
220	/// # Errors
221	///
222	/// Returns an error for invalid attention, expert, or conditioning geometry,
223	/// allocation failure, or child registration failure.
224	#[allow(
225		clippy::too_many_arguments,
226		reason = "the constructor preserves the donor attention, MoE, and conditioning dimensions"
227	)]
228	pub fn new_with_seed_moe_conditioned(
229		model_width: usize,
230		expert_hidden_width: usize,
231		sequence_length: usize,
232		num_heads: usize,
233		num_experts: usize,
234		experts_per_token: usize,
235		condition_dim: usize,
236		epsilon: f32,
237		seed: u64,
238	) -> Result<Self> {
239		Self::new_with_seed_moe_conditioned_on(
240			&Runtime::current()?,
241			model_width,
242			expert_hidden_width,
243			sequence_length,
244			num_heads,
245			num_experts,
246			experts_per_token,
247			condition_dim,
248			epsilon,
249			seed,
250		)
251	}
252
253	#[allow(clippy::too_many_arguments)]
254	pub fn new_with_seed_moe_conditioned_on(
255		runtime: &Runtime,
256		model_width: usize,
257		expert_hidden_width: usize,
258		sequence_length: usize,
259		num_heads: usize,
260		num_experts: usize,
261		experts_per_token: usize,
262		condition_dim: usize,
263		epsilon: f32,
264		seed: u64,
265	) -> Result<Self> {
266		Self::new_with_seed_moe_on(
267			runtime,
268			model_width,
269			expert_hidden_width,
270			sequence_length,
271			num_heads,
272			num_experts,
273			experts_per_token,
274			epsilon,
275			seed,
276		)?
277		.with_adaptive_conditioning(runtime, condition_dim)
278	}
279
280	/// Construct a dense block with grouped-query attention.
281	///
282	/// `num_kv_heads` must divide `num_heads` and selects the shared
283	/// key/value head count; `1` is multi-query attention.
284	///
285	/// # Errors
286	///
287	/// Returns an error for invalid block or grouping dimensions, or failed
288	/// child construction.
289	#[allow(clippy::too_many_arguments)]
290	pub fn new_with_seed_gqa_on(
291		runtime: &Runtime,
292		model_width: usize,
293		hidden_width: usize,
294		sequence_length: usize,
295		num_heads: usize,
296		num_kv_heads: usize,
297		epsilon: f32,
298		seed: u64,
299	) -> Result<Self> {
300		Self::new_with_seed_config(
301			runtime,
302			model_width,
303			hidden_width,
304			sequence_length,
305			num_heads,
306			num_kv_heads,
307			epsilon,
308			seed,
309			FeedForwardConfig::Dense,
310		)
311	}
312
313	// Both public recipes construct one attention tree and one feed-forward owner.
314	#[allow(
315		clippy::too_many_arguments,
316		reason = "shared constructor preserves public block recipes"
317	)]
318	fn new_with_seed_config(
319		runtime: &Runtime,
320		model_width: usize,
321		hidden_width: usize,
322		sequence_length: usize,
323		num_heads: usize,
324		num_kv_heads: usize,
325		epsilon: f32,
326		seed: u64,
327		config: FeedForwardConfig,
328	) -> Result<Self> {
329		if matches!(config, FeedForwardConfig::Dense) && hidden_width == 0 {
330			return Err(Error::invalid_argument(
331				"Transformer FFN width must be nonzero",
332			));
333		}
334		if num_kv_heads == 0 || !num_heads.is_multiple_of(num_kv_heads) {
335			return Err(Error::invalid_argument(
336				"Transformer requires a nonzero key/value head count dividing num_heads",
337			));
338		}
339		let norm_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
340		let attention = if num_kv_heads == num_heads {
341			Rc::new(MultiHeadAttention::new_with_seed_on(
342				runtime,
343				model_width,
344				num_heads,
345				sequence_length,
346				seed,
347			)?)
348		} else {
349			Rc::new(MultiHeadAttention::new_with_seed_and_options_grouped_on(
350				runtime,
351				model_width,
352				num_heads,
353				num_kv_heads,
354				sequence_length,
355				0.0,
356				true,
357				seed,
358			)?)
359		};
360		let mut registry = ModuleRegistry::new();
361		registry.register_module("ln_attn", norm_attention.clone())?;
362		registry.register_module("attention", attention.clone())?;
363		let feed_forward = match config {
364			FeedForwardConfig::Dense => {
365				let norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
366				let input = Rc::new(Linear::new_with_seed_on(
367					runtime,
368					model_width,
369					hidden_width,
370					seed.wrapping_add(4),
371				)?);
372				let output = Rc::new(Linear::new_with_seed_on(
373					runtime,
374					hidden_width,
375					model_width,
376					seed.wrapping_add(5),
377				)?);
378				registry.register_module("ln_ffn", norm.clone())?;
379				registry.register_module("ffn1", input.clone())?;
380				registry.register_module("ffn2", output.clone())?;
381				FeedForward::Dense {
382					norm,
383					input,
384					output,
385				}
386			}
387			FeedForwardConfig::Moe {
388				num_experts,
389				experts_per_token,
390			} => {
391				let moe = Rc::new(Moe::new_with_seed_on(
392					runtime,
393					model_width,
394					hidden_width,
395					num_experts,
396					experts_per_token,
397					epsilon,
398					seed.wrapping_add(4),
399				)?);
400				registry.register_module("moe", moe.clone())?;
401				FeedForward::Moe(moe)
402			}
403		};
404		Ok(Self {
405			model_width,
406			hidden_width,
407			sequence_length: Cell::new(sequence_length),
408			num_heads,
409			norm_attention,
410			attention,
411			feed_forward,
412			adaptive_modulation: None,
413			condition_dim: None,
414			registry,
415		})
416	}
417
418	fn with_adaptive_conditioning(mut self, runtime: &Runtime, condition_dim: usize) -> Result<Self> {
419		if condition_dim == 0 {
420			return Err(Error::invalid_argument(
421				"Transformer adaptive condition width must be nonzero",
422			));
423		}
424		let modulation_width = self
425			.model_width
426			.checked_mul(6)
427			.ok_or_else(|| Error::invalid_argument("Transformer modulation width overflows usize"))?;
428		let weight_count = condition_dim
429			.checked_mul(modulation_width)
430			.ok_or_else(|| Error::invalid_argument("Transformer modulation size overflows usize"))?;
431		let weight = Matrix::new_from_f32_on(
432			runtime,
433			[modulation_width, condition_dim],
434			&vec![0.0; weight_count],
435		)?;
436		let bias = Matrix::new_from_f32_on(runtime, [modulation_width], &vec![0.0; modulation_width])?;
437		let adaptive_modulation = Rc::new(Linear::new_from_matrices(weight, bias)?);
438		self
439			.registry
440			.register_module("adaptive_modulation", adaptive_modulation.clone())?;
441		self.adaptive_modulation = Some(adaptive_modulation);
442		self.condition_dim = Some(condition_dim);
443		Ok(self)
444	}
445
446	/// Apply pre-norm attention/residual followed by pre-norm GELU FFN/residual.
447	///
448	/// # Errors
449	///
450	/// Returns an error unless input is F32 `[B*S, D]` or child recording fails.
451	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
452		self.forward_impl(input, None)
453	}
454
455	/// Apply this block with an explicit bidirectional additive attention mask.
456	///
457	/// # Errors
458	///
459	/// Returns an error unless the mask is F32 `[B*H*S, S]` for the current
460	/// sequence geometry, or a child operation fails.
461	pub fn forward_masked(&self, input: &Matrix, additive_mask: &Matrix) -> Result<Matrix> {
462		self.forward_impl(input, Some(additive_mask))
463	}
464
465	/// Apply donor AdaLN-Zero conditioning without an explicit attention mask.
466	///
467	/// # Errors
468	///
469	/// Returns an error unless this block was constructed with adaptive
470	/// conditioning, input is F32 `[B*S, D]`, condition is same-runtime F32
471	/// `[B, C]`, or a child operation fails.
472	pub fn forward_conditioned(&self, input: &Matrix, condition: &Matrix) -> Result<Matrix> {
473		self.forward_conditioned_impl(input, condition, None)
474	}
475
476	/// Apply donor AdaLN-Zero conditioning with an additive attention mask.
477	///
478	/// # Errors
479	///
480	/// Returns an error unless the conditioned input contract and the attention
481	/// mask contract are both satisfied, or a child operation fails.
482	pub fn forward_conditioned_masked(
483		&self,
484		input: &Matrix,
485		condition: &Matrix,
486		additive_mask: &Matrix,
487	) -> Result<Matrix> {
488		self.forward_conditioned_impl(input, condition, Some(additive_mask))
489	}
490
491	fn forward_conditioned_impl(
492		&self,
493		input: &Matrix,
494		condition: &Matrix,
495		additive_mask: Option<&Matrix>,
496	) -> Result<Matrix> {
497		let Some(adaptive_modulation) = &self.adaptive_modulation else {
498			return Err(Error::failed_precondition(
499				"Transformer block was not constructed with adaptive conditioning",
500			));
501		};
502		let condition_dim = self
503			.condition_dim
504			.expect("adaptive modulation and condition width are constructed together");
505		let [rows, features] = input.shape() else {
506			return Err(Error::invalid_argument(
507				"conditioned Transformer input must have shape [B*S, D]",
508			));
509		};
510		let [condition_batch, condition_features] = condition.shape() else {
511			return Err(Error::invalid_argument(
512				"Transformer condition must have shape [B, C]",
513			));
514		};
515		if input.dtype() != DType::F32
516			|| condition.dtype() != DType::F32
517			|| *features != self.model_width
518			|| *rows == 0
519			|| !rows.is_multiple_of(self.sequence_length.get())
520			|| *condition_batch != rows / self.sequence_length.get()
521			|| *condition_features != condition_dim
522			|| !input.runtime().same_as(condition.runtime())
523		{
524			return Err(Error::invalid_argument(
525				"conditioned Transformer requires same-runtime F32 [B*S, D] input and [B, C] condition",
526			));
527		}
528
529		let modulation = adaptive_modulation.forward(condition)?;
530		let modulation = matrix::repeat_interleave(&modulation, self.sequence_length.get(), 0)?;
531		let mut parts = Vec::with_capacity(6);
532		for index in 0..6 {
533			let start = index * self.model_width;
534			parts.push(matrix::slice(
535				&modulation,
536				1,
537				start as i64,
538				(start + self.model_width) as i64,
539			)?);
540		}
541
542		let attention_scale = matrix::add_scalar(&parts[1], 1.0)?;
543		let attention_normalized = self.norm_attention.forward(input)?;
544		let attention_normalized = matrix::mul(&attention_normalized, &attention_scale)?;
545		let attention_normalized = matrix::add(&attention_normalized, &parts[0])?;
546		let attention_delta = match additive_mask {
547			Some(mask) => self.attention.forward_masked(&attention_normalized, mask)?,
548			None => self.attention.forward(&attention_normalized)?,
549		};
550		let attention_delta = matrix::mul(&attention_delta, &parts[2])?;
551		let residual = matrix::add(input, &attention_delta)?;
552
553		let feed_forward_normalized = match &self.feed_forward {
554			FeedForward::Dense { norm, .. } => norm.forward(&residual)?,
555			FeedForward::Moe(_) => residual.clone(),
556		};
557		let feed_forward_scale = matrix::add_scalar(&parts[4], 1.0)?;
558		let feed_forward_normalized = matrix::mul(&feed_forward_normalized, &feed_forward_scale)?;
559		let feed_forward_normalized = matrix::add(&feed_forward_normalized, &parts[3])?;
560		let feed_forward_delta = match &self.feed_forward {
561			FeedForward::Dense { input, output, .. } => {
562				let hidden = gelu(&input.forward(&feed_forward_normalized)?)?;
563				output.forward(&hidden)?
564			}
565			FeedForward::Moe(moe) => moe.forward(&feed_forward_normalized)?,
566		};
567		let feed_forward_delta = matrix::mul(&feed_forward_delta, &parts[5])?;
568		matrix::add(&residual, &feed_forward_delta)
569	}
570
571	/// Advance one autoregressive position through the block against `cache`.
572	///
573	/// `input` must be F32 `[batch, model_width]` for the cache's batch size.
574	/// Runs the same pre-norm → attention → residual → FFN → residual
575	/// sequence as `forward_impl` for one position, with
576	/// [`MultiHeadAttention::step`] supplying the cached key/value state.
577	/// Inference-only per [`MultiHeadAttention::step`]: an active
578	/// `GradientTape` is rejected there, and conditioned blocks are not
579	/// admitted for incremental decode.
580	///
581	/// # Errors
582	///
583	/// Returns an error for a conditioned block, an active tape, a foreign
584	/// or mismatched cache, or a failed child operation.
585	pub fn step(&self, input: &Matrix, cache: &mut AttentionCache) -> Result<Matrix> {
586		if self.is_adaptively_conditioned() {
587			return Err(Error::failed_precondition(
588				"TransformerBlock incremental decode does not admit adaptive conditioning",
589			));
590		}
591		let normalized = self.norm_attention.forward(input)?;
592		let attended = self.attention.step(&normalized, cache)?;
593		let residual = matrix::add(input, &attended)?;
594		match &self.feed_forward {
595			FeedForward::Dense {
596				norm,
597				input,
598				output,
599			} => {
600				let normalized = norm.forward(&residual)?;
601				let hidden = gelu(&input.forward(&normalized)?)?;
602				let projected = output.forward(&hidden)?;
603				matrix::add(&residual, &projected)
604			}
605			FeedForward::Moe(moe) => moe.forward(&residual),
606		}
607	}
608
609	fn forward_impl(&self, input: &Matrix, additive_mask: Option<&Matrix>) -> Result<Matrix> {
610		let normalized = self.norm_attention.forward(input)?;
611		let attended = match additive_mask {
612			Some(mask) => self.attention.forward_masked(&normalized, mask)?,
613			None => self.attention.forward(&normalized)?,
614		};
615		let residual = matrix::add(input, &attended)?;
616		match &self.feed_forward {
617			FeedForward::Dense {
618				norm,
619				input,
620				output,
621			} => {
622				let normalized = norm.forward(&residual)?;
623				let hidden = gelu(&input.forward(&normalized)?)?;
624				let projected = output.forward(&hidden)?;
625				matrix::add(&residual, &projected)
626			}
627			FeedForward::Moe(moe) => moe.forward(&residual),
628		}
629	}
630
631	pub const fn model_width(&self) -> usize {
632		self.model_width
633	}
634	pub const fn hidden_width(&self) -> usize {
635		self.hidden_width
636	}
637	pub fn sequence_length(&self) -> usize {
638		self.sequence_length.get()
639	}
640	pub const fn num_heads(&self) -> usize {
641		self.num_heads
642	}
643
644	/// Return whether this block uses routed experts instead of a dense FFN.
645	pub fn is_moe(&self) -> bool {
646		matches!(&self.feed_forward, FeedForward::Moe(_))
647	}
648
649	/// Return the routed expert module when this is an MoE block.
650	pub fn moe(&self) -> Option<&Moe> {
651		match &self.feed_forward {
652			FeedForward::Moe(moe) => Some(moe),
653			FeedForward::Dense { .. } => None,
654		}
655	}
656
657	/// Return whether this block owns a registered AdaLN-Zero projection.
658	pub fn is_adaptively_conditioned(&self) -> bool {
659		self.adaptive_modulation.is_some()
660	}
661
662	/// Return the accepted condition width for an adaptive block.
663	pub const fn condition_dim(&self) -> Option<usize> {
664		self.condition_dim
665	}
666
667	/// Select causal or bidirectional attention for this block.
668	pub fn set_attention_mode(&self, mode: AttentionMode) {
669		self.attention.set_mode(mode);
670	}
671
672	/// Return this block's attention visibility contract.
673	pub fn attention_mode(&self) -> AttentionMode {
674		self.attention.mode()
675	}
676
677	/// Change runtime sequence geometry without rebuilding block parameters.
678	///
679	/// # Errors
680	///
681	/// Returns an error when `sequence_length` is zero.
682	pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
683		self.attention.set_sequence_length(sequence_length)?;
684		self.sequence_length.set(sequence_length);
685		Ok(())
686	}
687}
688
689impl Module for TransformerBlock {
690	fn forward(&self, input: &Matrix) -> Result<Matrix> {
691		TransformerBlock::forward(self, input)
692	}
693	fn registry(&self) -> &ModuleRegistry {
694		&self.registry
695	}
696}
697
698/// Ready-to-train causal Transformer language model.
699///
700/// This is the idiomatic Rust spelling of donor `oa::NnTransformer`: token and
701/// position embeddings, registered Transformer blocks, final normalization,
702/// and a vocabulary projection.
703pub struct Transformer {
704	vocab_size: usize,
705	context_length: usize,
706	model_width: usize,
707	hidden_width: usize,
708	num_heads: usize,
709	num_kv_heads: usize,
710	token_embedding: Rc<super::Embedding>,
711	position_embedding: Rc<super::Embedding>,
712	blocks: Vec<Rc<TransformerBlock>>,
713	final_norm: Rc<LayerNorm>,
714	head: Rc<Linear>,
715	registry: ModuleRegistry,
716}
717
718impl Transformer {
719	/// Construct a deterministic causal language model.
720	///
721	/// # Errors
722	///
723	/// Returns an error unless all dimensions are positive, the model width is
724	/// divisible by the head count, positions fit U32, and every child can be
725	/// constructed and registered.
726	#[allow(clippy::too_many_arguments)]
727	pub fn new_with_seed(
728		vocab_size: usize,
729		context_length: usize,
730		model_width: usize,
731		hidden_width: usize,
732		num_layers: usize,
733		num_heads: usize,
734		epsilon: f32,
735		seed: u64,
736	) -> Result<Self> {
737		Self::new_with_seed_on(
738			&Runtime::current()?,
739			vocab_size,
740			context_length,
741			model_width,
742			hidden_width,
743			num_layers,
744			num_heads,
745			epsilon,
746			seed,
747		)
748	}
749
750	#[allow(clippy::too_many_arguments)]
751	pub fn new_with_seed_on(
752		runtime: &Runtime,
753		vocab_size: usize,
754		context_length: usize,
755		model_width: usize,
756		hidden_width: usize,
757		num_layers: usize,
758		num_heads: usize,
759		epsilon: f32,
760		seed: u64,
761	) -> Result<Self> {
762		Self::new_with_seed_config(
763			runtime,
764			vocab_size,
765			context_length,
766			model_width,
767			hidden_width,
768			num_layers,
769			num_heads,
770			num_heads,
771			epsilon,
772			seed,
773			FeedForwardConfig::Dense,
774		)
775	}
776
777	/// Construct a deterministic causal language model with MoE Transformer blocks.
778	///
779	/// Every block preserves the donor topology: pre-norm attention and residual,
780	/// followed by one MoE module that owns its own RMSNorm and residual.
781	///
782	/// # Errors
783	///
784	/// Returns an error unless all dimensions are valid or when child allocation
785	/// and registration fail.
786	#[allow(
787		clippy::too_many_arguments,
788		reason = "the constructor preserves the complete Transformer and MoE recipe"
789	)]
790	pub fn new_with_seed_moe(
791		vocab_size: usize,
792		context_length: usize,
793		model_width: usize,
794		expert_hidden_width: usize,
795		num_layers: usize,
796		num_heads: usize,
797		num_experts: usize,
798		experts_per_token: usize,
799		epsilon: f32,
800		seed: u64,
801	) -> Result<Self> {
802		Self::new_with_seed_moe_on(
803			&Runtime::current()?,
804			vocab_size,
805			context_length,
806			model_width,
807			expert_hidden_width,
808			num_layers,
809			num_heads,
810			num_experts,
811			experts_per_token,
812			epsilon,
813			seed,
814		)
815	}
816
817	#[allow(clippy::too_many_arguments)]
818	pub fn new_with_seed_moe_on(
819		runtime: &Runtime,
820		vocab_size: usize,
821		context_length: usize,
822		model_width: usize,
823		expert_hidden_width: usize,
824		num_layers: usize,
825		num_heads: usize,
826		num_experts: usize,
827		experts_per_token: usize,
828		epsilon: f32,
829		seed: u64,
830	) -> Result<Self> {
831		Self::new_with_seed_config(
832			runtime,
833			vocab_size,
834			context_length,
835			model_width,
836			expert_hidden_width,
837			num_layers,
838			num_heads,
839			num_heads,
840			epsilon,
841			seed,
842			FeedForwardConfig::Moe {
843				num_experts,
844				experts_per_token,
845			},
846		)
847	}
848
849	/// Construct a deterministic causal language model with grouped-query
850	/// attention in every block.
851	///
852	/// `num_kv_heads` must divide `num_heads` and selects the shared
853	/// key/value head count; `1` is multi-query attention.
854	///
855	/// # Errors
856	///
857	/// Returns an error under the [`Self::new_with_seed`] dimension contract,
858	/// or when `num_kv_heads` is zero or does not divide `num_heads`.
859	#[allow(clippy::too_many_arguments)]
860	pub fn new_with_seed_gqa(
861		vocab_size: usize,
862		context_length: usize,
863		model_width: usize,
864		hidden_width: usize,
865		num_layers: usize,
866		num_heads: usize,
867		num_kv_heads: usize,
868		epsilon: f32,
869		seed: u64,
870	) -> Result<Self> {
871		Self::new_with_seed_gqa_on(
872			&Runtime::current()?,
873			vocab_size,
874			context_length,
875			model_width,
876			hidden_width,
877			num_layers,
878			num_heads,
879			num_kv_heads,
880			epsilon,
881			seed,
882		)
883	}
884
885	#[allow(clippy::too_many_arguments)]
886	pub fn new_with_seed_gqa_on(
887		runtime: &Runtime,
888		vocab_size: usize,
889		context_length: usize,
890		model_width: usize,
891		hidden_width: usize,
892		num_layers: usize,
893		num_heads: usize,
894		num_kv_heads: usize,
895		epsilon: f32,
896		seed: u64,
897	) -> Result<Self> {
898		Self::new_with_seed_config(
899			runtime,
900			vocab_size,
901			context_length,
902			model_width,
903			hidden_width,
904			num_layers,
905			num_heads,
906			num_kv_heads,
907			epsilon,
908			seed,
909			FeedForwardConfig::Dense,
910		)
911	}
912
913	// A single model builder retains each recipe's checkpoint names and seed stride.
914	#[allow(
915		clippy::too_many_arguments,
916		reason = "shared constructor preserves public model recipes"
917	)]
918	fn new_with_seed_config(
919		runtime: &Runtime,
920		vocab_size: usize,
921		context_length: usize,
922		model_width: usize,
923		hidden_width: usize,
924		num_layers: usize,
925		num_heads: usize,
926		num_kv_heads: usize,
927		epsilon: f32,
928		seed: u64,
929		config: FeedForwardConfig,
930	) -> Result<Self> {
931		let (seed_stride, valid_experts, dimension_error) = match config {
932			FeedForwardConfig::Dense => (
933				6,
934				true,
935				"Transformer requires positive dimensions, D divisible by H, and U32 positions",
936			),
937			FeedForwardConfig::Moe { num_experts, .. } => (
938				8,
939				num_experts != 0,
940				"MoE Transformer requires positive dimensions, D divisible by H, and U32 positions",
941			),
942		};
943		if vocab_size == 0
944			|| context_length == 0
945			|| model_width == 0
946			|| hidden_width == 0
947			|| num_layers == 0
948			|| num_heads == 0
949			|| num_kv_heads == 0
950			|| !valid_experts
951			|| !model_width.is_multiple_of(num_heads)
952			|| !num_heads.is_multiple_of(num_kv_heads)
953			|| u32::try_from(context_length - 1).is_err()
954		{
955			return Err(Error::invalid_argument(dimension_error));
956		}
957		let token_embedding = Rc::new(super::Embedding::new_with_seed_on(
958			runtime,
959			vocab_size,
960			model_width,
961			seed,
962		)?);
963		let position_embedding = Rc::new(super::Embedding::new_with_seed_on(
964			runtime,
965			context_length,
966			model_width,
967			seed.wrapping_add(1),
968		)?);
969		let mut registry = ModuleRegistry::new();
970		registry.register_module("token_embedding", token_embedding.clone())?;
971		registry.register_module("position_embedding", position_embedding.clone())?;
972		let mut blocks = Vec::with_capacity(num_layers);
973		for index in 0..num_layers {
974			let seed_offset = (index as u64).wrapping_mul(seed_stride).wrapping_add(2);
975			let block = Rc::new(TransformerBlock::new_with_seed_config(
976				runtime,
977				model_width,
978				hidden_width,
979				context_length,
980				num_heads,
981				num_kv_heads,
982				epsilon,
983				seed.wrapping_add(seed_offset),
984				config,
985			)?);
986			registry.register_module(format!("block_{index}"), block.clone())?;
987			blocks.push(block);
988		}
989		let final_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
990		let head_seed = seed.wrapping_add(
991			(num_layers as u64)
992				.wrapping_mul(seed_stride)
993				.wrapping_add(2),
994		);
995		let head = Rc::new(Linear::new_with_seed_on(
996			runtime,
997			model_width,
998			vocab_size,
999			head_seed,
1000		)?);
1001		registry.register_module("final_norm", final_norm.clone())?;
1002		registry.register_module("head", head.clone())?;
1003		Ok(Self {
1004			vocab_size,
1005			context_length,
1006			model_width,
1007			hidden_width,
1008			num_heads,
1009			num_kv_heads,
1010			token_embedding,
1011			position_embedding,
1012			blocks,
1013			final_norm,
1014			head,
1015			registry,
1016		})
1017	}
1018
1019	/// Evaluate all-position vocabulary logits for U8 or U32 tokens `[B, S]`.
1020	///
1021	/// # Errors
1022	///
1023	/// Returns an error unless `S` equals the configured context length and the
1024	/// input is nonempty U8/U32, or a child operation fails.
1025	pub fn forward(&self, tokens: &Matrix) -> Result<Matrix> {
1026		let [batch, sequence] = tokens.shape() else {
1027			return Err(Error::invalid_argument(
1028				"Transformer tokens must have shape [batch, context_length]",
1029			));
1030		};
1031		if *batch == 0
1032			|| *sequence != self.context_length
1033			|| !matches!(tokens.dtype(), DType::U8 | DType::U32)
1034		{
1035			return Err(Error::invalid_argument(
1036				"Transformer tokens must be nonempty U8 or U32 [batch, context_length]",
1037			));
1038		}
1039		let rows = batch
1040			.checked_mul(*sequence)
1041			.ok_or_else(|| Error::invalid_argument("Transformer row count overflows usize"))?;
1042		let position_values = (0..rows)
1043			.map(|index| (index % self.context_length) as u32)
1044			.collect::<Vec<_>>();
1045		let position_ids =
1046			Matrix::new_from_slice_handle(tokens.runtime(), vec![rows], &position_values)?;
1047		let token_values = self
1048			.token_embedding
1049			.forward(tokens)?
1050			.reshape([rows, self.model_width])?;
1051		let position_values = self.position_embedding.forward(&position_ids)?;
1052		let mut value = matrix::add(&token_values, &position_values)?;
1053		for block in &self.blocks {
1054			value = block.forward(&value)?;
1055		}
1056		self.head.forward(&self.final_norm.forward(&value)?)
1057	}
1058
1059	pub const fn vocab_size(&self) -> usize {
1060		self.vocab_size
1061	}
1062
1063	pub const fn context_length(&self) -> usize {
1064		self.context_length
1065	}
1066
1067	pub const fn model_width(&self) -> usize {
1068		self.model_width
1069	}
1070
1071	pub const fn hidden_width(&self) -> usize {
1072		self.hidden_width
1073	}
1074
1075	pub fn num_layers(&self) -> usize {
1076		self.blocks.len()
1077	}
1078
1079	pub const fn num_heads(&self) -> usize {
1080		self.num_heads
1081	}
1082
1083	/// Return the key/value head count each query-head group shares.
1084	pub const fn num_kv_heads(&self) -> usize {
1085		self.num_kv_heads
1086	}
1087
1088	/// Return whether every block uses routed experts.
1089	pub fn is_moe(&self) -> bool {
1090		self.blocks.iter().all(|block| block.is_moe())
1091	}
1092
1093	/// Return one Transformer block by layer index.
1094	pub fn block(&self, index: usize) -> Option<&TransformerBlock> {
1095		self.blocks.get(index).map(Rc::as_ref)
1096	}
1097
1098	/// Allocate per-layer attention caches for one autoregressive decode
1099	/// session.
1100	///
1101	/// # Errors
1102	///
1103	/// Returns an error when `batch_size` is zero.
1104	pub fn new_cache(&self, batch_size: usize) -> Result<TransformerCache> {
1105		let mut caches = Vec::with_capacity(self.blocks.len());
1106		for block in &self.blocks {
1107			caches.push(block.attention.new_cache(batch_size)?);
1108		}
1109		Ok(TransformerCache {
1110			caches,
1111			position: 0,
1112		})
1113	}
1114
1115	/// Advance one autoregressive position against `cache`.
1116	///
1117	/// `token` must be a `[batch]` U8 or U32 matrix for the cache's batch
1118	/// size. The step embeds the token and `cache.position`, runs every
1119	/// block's incremental [`TransformerBlock::step`], and returns `[batch,
1120	/// vocab_size]` logits — the incremental equivalent of taking the last
1121	/// position of `forward`. Decode is bounded by `context_length` and is
1122	/// inference-only per [`MultiHeadAttention::step`].
1123	///
1124	/// # Errors
1125	///
1126	/// Returns an error for an exhausted context window, mismatched
1127	/// token shape or dtype, a foreign cache count, or a failed child
1128	/// operation.
1129	pub fn step(&self, token: &Matrix, cache: &mut TransformerCache) -> Result<Matrix> {
1130		if cache.caches.len() != self.blocks.len() {
1131			return Err(Error::invalid_argument(
1132				"Transformer decode cache does not match the layer count",
1133			));
1134		}
1135		let batch_size = cache
1136			.caches
1137			.first()
1138			.map(|entry| entry.batch_size())
1139			.unwrap_or(0);
1140		if token.shape() != [batch_size] || !matches!(token.dtype(), DType::U8 | DType::U32) {
1141			return Err(Error::invalid_argument(format!(
1142				"Transformer step requires a nonempty U8 or U32 token [{batch_size}]"
1143			)));
1144		}
1145		if cache.position >= self.context_length {
1146			return Err(Error::failed_precondition(
1147				"Transformer decode cache exhausted the context length",
1148			));
1149		}
1150		let token_values = self.token_embedding.forward(token)?;
1151		let position_ids = Matrix::new_from_slice_handle(
1152			token.runtime(),
1153			vec![batch_size],
1154			&vec![cache.position as u32; batch_size],
1155		)?;
1156		let position_values = self.position_embedding.forward(&position_ids)?;
1157		let mut value = matrix::add(&token_values, &position_values)?;
1158		for (block, entry) in self.blocks.iter().zip(cache.caches.iter_mut()) {
1159			value = block.step(&value, entry)?;
1160		}
1161		cache.position += 1;
1162		self.head.forward(&self.final_norm.forward(&value)?)
1163	}
1164}
1165
1166/// Per-layer key/value cache set for one autoregressive decode session.
1167///
1168/// Each entry pairs with the same-index Transformer block; every
1169/// [`Transformer::step`] appends one position per layer and advances the
1170/// decode position used for positional embedding and the context-length
1171/// bound.
1172pub struct TransformerCache {
1173	caches: Vec<AttentionCache>,
1174	position: usize,
1175}
1176
1177impl TransformerCache {
1178	/// Return the number of decoded positions.
1179	pub const fn len(&self) -> usize {
1180		self.position
1181	}
1182
1183	/// Return whether no positions are cached.
1184	pub const fn is_empty(&self) -> bool {
1185		self.position == 0
1186	}
1187}
1188
1189impl Module for Transformer {
1190	fn forward(&self, input: &Matrix) -> Result<Matrix> {
1191		Transformer::forward(self, input)
1192	}
1193
1194	fn registry(&self) -> &ModuleRegistry {
1195		&self.registry
1196	}
1197}