Skip to main content

oa/ml/nn/
encoder_decoder.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_encoder_decoder.json
3// generator_version=8; schema_sha256=665d485ab19631028a10f518bfffa6864f1d312848b7f2c0e5ff43a8c5a5fc8b
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::{AttentionMode, LayerNorm, Linear, MultiHeadAttention, TransformerBlock};
12
13// OA donor: oacpp/source/cpp/lib/oa/ml/nn/transformer/transformer.cpp
14// Adaptation: Rust-only composition reusing the Transformer block recipe: encoder blocks run bidirectional MultiHeadAttention, decoder blocks add a cross-attention stage whose keys and values are projected from the encoder output through the new MultiHeadAttention::forward_kv composed path; separate source/target vocabularies and context lengths, deterministic seed strides, fixed structural registration
15/// One pre-normalized decoder block of an encoder-decoder EncoderDecoder.
16///
17/// Applies causal self-attention, bidirectional cross-attention over the
18/// encoder output, and a dense GELU feed-forward stage, each behind a
19/// pre-norm residual. The cross-attention stage projects its keys and
20/// values from the encoder output on every call, so the same block also
21/// serves training and uncached evaluation.
22pub struct EncoderDecoderBlock {
23	model_width: usize,
24	hidden_width: usize,
25	sequence_length: Cell<usize>,
26	num_heads: usize,
27	norm_self_attention: Rc<LayerNorm>,
28	self_attention: Rc<MultiHeadAttention>,
29	norm_cross_attention: Rc<LayerNorm>,
30	cross_attention: Rc<MultiHeadAttention>,
31	norm_feed_forward: Rc<LayerNorm>,
32	feed_forward_input: Rc<Linear>,
33	feed_forward_output: Rc<Linear>,
34	registry: ModuleRegistry,
35}
36
37impl EncoderDecoderBlock {
38	/// Construct the canonical decoder block with causal self-attention and
39	/// bidirectional cross-attention.
40	///
41	/// # Errors
42	///
43	/// Returns an error for invalid dimensions or failed child construction.
44	pub fn new_with_seed(
45		model_width: usize,
46		hidden_width: usize,
47		sequence_length: usize,
48		num_heads: usize,
49		epsilon: f32,
50		seed: u64,
51	) -> Result<Self> {
52		Self::new_with_seed_on(
53			&Runtime::current()?,
54			model_width,
55			hidden_width,
56			sequence_length,
57			num_heads,
58			epsilon,
59			seed,
60		)
61	}
62
63	#[allow(clippy::too_many_arguments)]
64	pub fn new_with_seed_on(
65		runtime: &Runtime,
66		model_width: usize,
67		hidden_width: usize,
68		sequence_length: usize,
69		num_heads: usize,
70		epsilon: f32,
71		seed: u64,
72	) -> Result<Self> {
73		if model_width == 0
74			|| hidden_width == 0
75			|| sequence_length == 0
76			|| num_heads == 0
77			|| !model_width.is_multiple_of(num_heads)
78		{
79			return Err(Error::invalid_argument(
80				"EncoderDecoderBlock requires positive D/FFN/S/H and D divisible by H",
81			));
82		}
83		let norm_self_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
84		let self_attention = Rc::new(MultiHeadAttention::new_with_seed_on(
85			runtime,
86			model_width,
87			num_heads,
88			sequence_length,
89			seed,
90		)?);
91		let norm_cross_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
92		let cross_attention = Rc::new(MultiHeadAttention::new_with_seed_on(
93			runtime,
94			model_width,
95			num_heads,
96			sequence_length,
97			seed.wrapping_add(6),
98		)?);
99		let norm_feed_forward = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
100		let feed_forward_input = Rc::new(Linear::new_with_seed_on(
101			runtime,
102			model_width,
103			hidden_width,
104			seed.wrapping_add(12),
105		)?);
106		let feed_forward_output = Rc::new(Linear::new_with_seed_on(
107			runtime,
108			hidden_width,
109			model_width,
110			seed.wrapping_add(13),
111		)?);
112		let mut registry = ModuleRegistry::new();
113		registry.register_module("ln_self", norm_self_attention.clone())?;
114		registry.register_module("self_attn", self_attention.clone())?;
115		registry.register_module("ln_cross", norm_cross_attention.clone())?;
116		registry.register_module("cross_attn", cross_attention.clone())?;
117		registry.register_module("ln_ffn", norm_feed_forward.clone())?;
118		registry.register_module("ffn1", feed_forward_input.clone())?;
119		registry.register_module("ffn2", feed_forward_output.clone())?;
120		Ok(Self {
121			model_width,
122			hidden_width,
123			sequence_length: Cell::new(sequence_length),
124			num_heads,
125			norm_self_attention,
126			self_attention,
127			norm_cross_attention,
128			cross_attention,
129			norm_feed_forward,
130			feed_forward_input,
131			feed_forward_output,
132			registry,
133		})
134	}
135
136	/// Apply pre-norm self-attention, cross-attention over `encoder_output`,
137	/// and GELU feed-forward stages behind residuals.
138	///
139	/// `input` is F32 `[B*S_tgt, D]`; `encoder_output` is F32 `[B*S_src, D]`
140	/// on the same runtime for the same batch.
141	///
142	/// # Errors
143	///
144	/// Returns an error unless both matrices satisfy their geometry and
145	/// dtype contracts, or a child operation fails.
146	pub fn forward(&self, input: &Matrix, encoder_output: &Matrix) -> Result<Matrix> {
147		let normalized = self.norm_self_attention.forward(input)?;
148		let attended = self.self_attention.forward(&normalized)?;
149		let residual = matrix::add(input, &attended)?;
150		let normalized = self.norm_cross_attention.forward(&residual)?;
151		let attended = self
152			.cross_attention
153			.forward_kv(&normalized, encoder_output)?;
154		let residual = matrix::add(&residual, &attended)?;
155		let normalized = self.norm_feed_forward.forward(&residual)?;
156		let hidden = gelu(&self.feed_forward_input.forward(&normalized)?)?;
157		let projected = self.feed_forward_output.forward(&hidden)?;
158		matrix::add(&residual, &projected)
159	}
160
161	/// Evaluate the block with an additive cross-attention key-padding mask.
162	///
163	/// `cross_mask` is the additive `[B*H*S_target, S_source]` mask broadcast
164	/// into the cross-attention scores, built with 0 at visible source
165	/// positions and a large negative value at padding. Decoder self-attention
166	/// stays causal-only: under the right-padding contract padding positions
167	/// follow valid ones, so causal visibility already excludes them.
168	///
169	/// # Errors
170	///
171	/// Returns an error under the [`Self::forward`] contract or when the mask
172	/// does not match the cross-attention score geometry.
173	pub fn forward_masked(
174		&self,
175		input: &Matrix,
176		encoder_output: &Matrix,
177		cross_mask: &Matrix,
178	) -> Result<Matrix> {
179		let normalized = self.norm_self_attention.forward(input)?;
180		let attended = self.self_attention.forward(&normalized)?;
181		let residual = matrix::add(input, &attended)?;
182		let normalized = self.norm_cross_attention.forward(&residual)?;
183		let attended =
184			self
185				.cross_attention
186				.forward_kv_masked(&normalized, encoder_output, cross_mask)?;
187		let residual = matrix::add(&residual, &attended)?;
188		let normalized = self.norm_feed_forward.forward(&residual)?;
189		let hidden = gelu(&self.feed_forward_input.forward(&normalized)?)?;
190		let projected = self.feed_forward_output.forward(&hidden)?;
191		matrix::add(&residual, &projected)
192	}
193
194	pub const fn model_width(&self) -> usize {
195		self.model_width
196	}
197	pub const fn hidden_width(&self) -> usize {
198		self.hidden_width
199	}
200	pub fn sequence_length(&self) -> usize {
201		self.sequence_length.get()
202	}
203	pub const fn num_heads(&self) -> usize {
204		self.num_heads
205	}
206
207	/// Change runtime target sequence geometry without rebuilding parameters.
208	///
209	/// # Errors
210	///
211	/// Returns an error when `sequence_length` is zero.
212	pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
213		self.self_attention.set_sequence_length(sequence_length)?;
214		self.cross_attention.set_sequence_length(sequence_length)?;
215		self.sequence_length.set(sequence_length);
216		Ok(())
217	}
218}
219
220impl Module for EncoderDecoderBlock {
221	fn forward(&self, input: &Matrix) -> Result<Matrix> {
222		let _ = input;
223		Err(Error::invalid_argument(
224			"EncoderDecoderBlock requires encoder output; call EncoderDecoderBlock::forward(input, encoder_output)",
225		))
226	}
227	fn registry(&self) -> &ModuleRegistry {
228		&self.registry
229	}
230}
231
232/// Ready-to-train encoder-decoder Transformer for sequence-to-sequence tasks.
233///
234/// Source and target token/position embeddings feed separate block stacks:
235/// encoder blocks run bidirectional self-attention, decoder blocks run
236/// causal self-attention and bidirectional cross-attention over the encoder
237/// output. `forward(source, target)` returns all-position target logits.
238pub struct EncoderDecoder {
239	source_vocab_size: usize,
240	target_vocab_size: usize,
241	source_context_length: usize,
242	target_context_length: usize,
243	model_width: usize,
244	hidden_width: usize,
245	num_heads: usize,
246	source_token_embedding: Rc<super::Embedding>,
247	source_position_embedding: Rc<super::Embedding>,
248	target_token_embedding: Rc<super::Embedding>,
249	target_position_embedding: Rc<super::Embedding>,
250	encoder_blocks: Vec<Rc<TransformerBlock>>,
251	decoder_blocks: Vec<Rc<EncoderDecoderBlock>>,
252	encoder_norm: Rc<LayerNorm>,
253	decoder_norm: Rc<LayerNorm>,
254	head: Rc<Linear>,
255	registry: ModuleRegistry,
256}
257
258impl EncoderDecoder {
259	/// Construct a deterministic encoder-decoder Transformer.
260	///
261	/// Both stacks use `num_layers` blocks of the same width recipe.
262	///
263	/// # Errors
264	///
265	/// Returns an error unless all dimensions are positive, the model width
266	/// is divisible by the head count, positions fit U32, and every child
267	/// can be constructed and registered.
268	#[allow(clippy::too_many_arguments)]
269	pub fn new_with_seed(
270		source_vocab_size: usize,
271		target_vocab_size: usize,
272		source_context_length: usize,
273		target_context_length: usize,
274		model_width: usize,
275		hidden_width: usize,
276		num_layers: usize,
277		num_heads: usize,
278		epsilon: f32,
279		seed: u64,
280	) -> Result<Self> {
281		Self::new_with_seed_on(
282			&Runtime::current()?,
283			source_vocab_size,
284			target_vocab_size,
285			source_context_length,
286			target_context_length,
287			model_width,
288			hidden_width,
289			num_layers,
290			num_heads,
291			epsilon,
292			seed,
293		)
294	}
295
296	#[allow(clippy::too_many_arguments)]
297	pub fn new_with_seed_on(
298		runtime: &Runtime,
299		source_vocab_size: usize,
300		target_vocab_size: usize,
301		source_context_length: usize,
302		target_context_length: usize,
303		model_width: usize,
304		hidden_width: usize,
305		num_layers: usize,
306		num_heads: usize,
307		epsilon: f32,
308		seed: u64,
309	) -> Result<Self> {
310		if source_vocab_size == 0
311			|| target_vocab_size == 0
312			|| source_context_length == 0
313			|| target_context_length == 0
314			|| model_width == 0
315			|| hidden_width == 0
316			|| num_layers == 0
317			|| num_heads == 0
318			|| !model_width.is_multiple_of(num_heads)
319			|| u32::try_from(source_context_length - 1).is_err()
320			|| u32::try_from(target_context_length - 1).is_err()
321		{
322			return Err(Error::invalid_argument(
323				"EncoderDecoder requires positive dimensions, D divisible by H, and U32 positions",
324			));
325		}
326		let source_token_embedding = Rc::new(super::Embedding::new_with_seed_on(
327			runtime,
328			source_vocab_size,
329			model_width,
330			seed,
331		)?);
332		let source_position_embedding = Rc::new(super::Embedding::new_with_seed_on(
333			runtime,
334			source_context_length,
335			model_width,
336			seed.wrapping_add(1),
337		)?);
338		let target_token_embedding = Rc::new(super::Embedding::new_with_seed_on(
339			runtime,
340			target_vocab_size,
341			model_width,
342			seed.wrapping_add(2),
343		)?);
344		let target_position_embedding = Rc::new(super::Embedding::new_with_seed_on(
345			runtime,
346			target_context_length,
347			model_width,
348			seed.wrapping_add(3),
349		)?);
350		let mut registry = ModuleRegistry::new();
351		registry.register_module("src_token_embedding", source_token_embedding.clone())?;
352		registry.register_module("src_position_embedding", source_position_embedding.clone())?;
353		registry.register_module("tgt_token_embedding", target_token_embedding.clone())?;
354		registry.register_module("tgt_position_embedding", target_position_embedding.clone())?;
355		let encoder_stride = 6_u64;
356		let mut encoder_blocks = Vec::with_capacity(num_layers);
357		for index in 0..num_layers {
358			let block = Rc::new(TransformerBlock::new_with_seed_on(
359				runtime,
360				model_width,
361				hidden_width,
362				source_context_length,
363				num_heads,
364				epsilon,
365				seed.wrapping_add(4 + (index as u64) * encoder_stride),
366			)?);
367			block.set_attention_mode(AttentionMode::Bidirectional);
368			registry.register_module(format!("encoder_{index}"), block.clone())?;
369			encoder_blocks.push(block);
370		}
371		let decoder_stride = 16_u64;
372		let decoder_base = 4 + (num_layers as u64) * encoder_stride;
373		let mut decoder_blocks = Vec::with_capacity(num_layers);
374		for index in 0..num_layers {
375			let block = Rc::new(EncoderDecoderBlock::new_with_seed_on(
376				runtime,
377				model_width,
378				hidden_width,
379				target_context_length,
380				num_heads,
381				epsilon,
382				seed.wrapping_add(decoder_base + (index as u64) * decoder_stride),
383			)?);
384			registry.register_module(format!("decoder_{index}"), block.clone())?;
385			decoder_blocks.push(block);
386		}
387		let encoder_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
388		let decoder_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
389		let head_seed = seed.wrapping_add(decoder_base + (num_layers as u64) * decoder_stride);
390		let head = Rc::new(Linear::new_with_seed_on(
391			runtime,
392			model_width,
393			target_vocab_size,
394			head_seed,
395		)?);
396		registry.register_module("encoder_norm", encoder_norm.clone())?;
397		registry.register_module("decoder_norm", decoder_norm.clone())?;
398		registry.register_module("head", head.clone())?;
399		Ok(Self {
400			source_vocab_size,
401			target_vocab_size,
402			source_context_length,
403			target_context_length,
404			model_width,
405			hidden_width,
406			num_heads,
407			source_token_embedding,
408			source_position_embedding,
409			target_token_embedding,
410			target_position_embedding,
411			encoder_blocks,
412			decoder_blocks,
413			encoder_norm,
414			decoder_norm,
415			head,
416			registry,
417		})
418	}
419
420	/// Embed source tokens `tokens`, a U8/U32 `[batch, source_context]`
421	/// matrix, through the encoder stack.
422	///
423	/// # Errors
424	///
425	/// Returns an error unless `tokens` is nonempty U8 or U32 `[batch,
426	/// source_context_length]`, or a child operation fails.
427	pub fn encode(&self, tokens: &Matrix) -> Result<Matrix> {
428		let (batch, sequence) = Self::token_geometry(tokens, self.source_context_length)?;
429		let rows = batch
430			.checked_mul(sequence)
431			.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
432		let mut value = self.embed(
433			tokens,
434			&self.source_token_embedding,
435			&self.source_position_embedding,
436			rows,
437			self.source_context_length,
438		)?;
439		for block in &self.encoder_blocks {
440			value = block.forward(&value)?;
441		}
442		self.encoder_norm.forward(&value)
443	}
444
445	/// Evaluate all-position target logits for `tokens`, a U8/U32 `[batch,
446	/// target_context]` matrix, against a computed `encoder_output`.
447	///
448	/// `encoder_output` must be F32 `[batch*source_context_length,
449	/// model_width]` on the same runtime — normally the result of
450	/// [`Self::encode`].
451	///
452	/// # Errors
453	///
454	/// Returns an error unless `tokens` and `encoder_output` satisfy their
455	/// geometry, dtype, and runtime contracts, or a child operation fails.
456	pub fn decode(&self, tokens: &Matrix, encoder_output: &Matrix) -> Result<Matrix> {
457		let (batch, sequence) = Self::token_geometry(tokens, self.target_context_length)?;
458		let [encoder_rows, encoder_width] = encoder_output.shape() else {
459			return Err(Error::invalid_argument(
460				"EncoderDecoder encoder output must have shape [batch*source_context, D]",
461			));
462		};
463		if encoder_output.dtype() != DType::F32
464			|| *encoder_width != self.model_width
465			|| *encoder_rows != batch * self.source_context_length
466			|| !tokens.runtime().same_as(encoder_output.runtime())
467		{
468			return Err(Error::invalid_argument(format!(
469				"EncoderDecoder requires same-runtime F32 encoder output [{}, {}]; found {:?} {}",
470				batch * self.source_context_length,
471				self.model_width,
472				encoder_output.shape(),
473				encoder_output.dtype().token(),
474			)));
475		}
476		let rows = batch
477			.checked_mul(sequence)
478			.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
479		let mut value = self.embed(
480			tokens,
481			&self.target_token_embedding,
482			&self.target_position_embedding,
483			rows,
484			self.target_context_length,
485		)?;
486		for block in &self.decoder_blocks {
487			value = block.forward(&value, encoder_output)?;
488		}
489		self.head.forward(&self.decoder_norm.forward(&value)?)
490	}
491
492	/// Encode `source` and decode `target`, returning `[batch*target_context,
493	/// target_vocab]` logits.
494	///
495	/// # Errors
496	///
497	/// Returns an error under the [`Self::encode`] and [`Self::decode`]
498	/// contracts.
499	pub fn forward(&self, source: &Matrix, target: &Matrix) -> Result<Matrix> {
500		self.decode(target, &self.encode(source)?)
501	}
502
503	/// Encode `source` with an additive encoder self-attention key-padding
504	/// mask.
505	///
506	/// `source_mask` is the additive `[B*H*S_source, S_source]` mask with 0 at
507	/// visible positions and a large negative value at padding, preventing
508	/// bidirectional encoder attention from reading padding keys.
509	///
510	/// # Errors
511	///
512	/// Returns an error under the [`Self::encode`] contract or when the mask
513	/// does not match the encoder score geometry.
514	pub fn encode_masked(&self, tokens: &Matrix, source_mask: &Matrix) -> Result<Matrix> {
515		let (batch, sequence) = Self::token_geometry(tokens, self.source_context_length)?;
516		let rows = batch
517			.checked_mul(sequence)
518			.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
519		let mut value = self.embed(
520			tokens,
521			&self.source_token_embedding,
522			&self.source_position_embedding,
523			rows,
524			self.source_context_length,
525		)?;
526		for block in &self.encoder_blocks {
527			value = block.forward_masked(&value, source_mask)?;
528		}
529		self.encoder_norm.forward(&value)
530	}
531
532	/// Decode `target` against a masked-encoding output with an additive
533	/// cross-attention key-padding mask.
534	///
535	/// `cross_mask` is the additive `[B*H*S_target, S_source]` mask over
536	/// source keys. Under the right-padding contract decoder self-attention
537	/// needs no padding mask because causal visibility already excludes
538	/// trailing padding.
539	///
540	/// # Errors
541	///
542	/// Returns an error under the [`Self::decode`] contract or when the mask
543	/// does not match the cross-attention score geometry.
544	pub fn decode_masked(
545		&self,
546		tokens: &Matrix,
547		encoder_output: &Matrix,
548		cross_mask: &Matrix,
549	) -> Result<Matrix> {
550		let (batch, sequence) = Self::token_geometry(tokens, self.target_context_length)?;
551		let [encoder_rows, encoder_width] = encoder_output.shape() else {
552			return Err(Error::invalid_argument(
553				"EncoderDecoder encoder output must have shape [batch*source_context, D]",
554			));
555		};
556		if encoder_output.dtype() != DType::F32
557			|| *encoder_width != self.model_width
558			|| *encoder_rows != batch * self.source_context_length
559			|| !tokens.runtime().same_as(encoder_output.runtime())
560		{
561			return Err(Error::invalid_argument(format!(
562				"EncoderDecoder requires same-runtime F32 encoder output [{}, {}]; found {:?} {}",
563				batch * self.source_context_length,
564				self.model_width,
565				encoder_output.shape(),
566				encoder_output.dtype().token(),
567			)));
568		}
569		let rows = batch
570			.checked_mul(sequence)
571			.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
572		let mut value = self.embed(
573			tokens,
574			&self.target_token_embedding,
575			&self.target_position_embedding,
576			rows,
577			self.target_context_length,
578		)?;
579		for block in &self.decoder_blocks {
580			value = block.forward_masked(&value, encoder_output, cross_mask)?;
581		}
582		self.head.forward(&self.decoder_norm.forward(&value)?)
583	}
584
585	/// Encode and decode with key-padding masks on both source visibility
586	/// routes, returning `[batch*target_context, target_vocab]` logits.
587	///
588	/// # Errors
589	///
590	/// Returns an error under the [`Self::encode_masked`] and
591	/// [`Self::decode_masked`] contracts.
592	pub fn forward_masked(
593		&self,
594		source: &Matrix,
595		target: &Matrix,
596		source_mask: &Matrix,
597		cross_mask: &Matrix,
598	) -> Result<Matrix> {
599		self.decode_masked(
600			target,
601			&self.encode_masked(source, source_mask)?,
602			cross_mask,
603		)
604	}
605
606	fn token_geometry(tokens: &Matrix, context_length: usize) -> Result<(usize, usize)> {
607		let [batch, sequence] = tokens.shape() else {
608			return Err(Error::invalid_argument(
609				"EncoderDecoder tokens must have shape [batch, context_length]",
610			));
611		};
612		if *batch == 0
613			|| *sequence != context_length
614			|| !matches!(tokens.dtype(), DType::U8 | DType::U32)
615		{
616			return Err(Error::invalid_argument(format!(
617				"EncoderDecoder tokens must be nonempty U8 or U32 [batch, {context_length}]"
618			)));
619		}
620		Ok((*batch, *sequence))
621	}
622
623	fn embed(
624		&self,
625		tokens: &Matrix,
626		token_embedding: &super::Embedding,
627		position_embedding: &super::Embedding,
628		rows: usize,
629		context_length: usize,
630	) -> Result<Matrix> {
631		let position_values = (0..rows)
632			.map(|index| (index % context_length) as u32)
633			.collect::<Vec<_>>();
634		let position_ids =
635			Matrix::new_from_slice_handle(tokens.runtime(), vec![rows], &position_values)?;
636		let token_values = token_embedding
637			.forward(tokens)?
638			.reshape([rows, self.model_width])?;
639		let position_values = position_embedding.forward(&position_ids)?;
640		matrix::add(&token_values, &position_values)
641	}
642
643	pub const fn source_vocab_size(&self) -> usize {
644		self.source_vocab_size
645	}
646	pub const fn target_vocab_size(&self) -> usize {
647		self.target_vocab_size
648	}
649	pub const fn source_context_length(&self) -> usize {
650		self.source_context_length
651	}
652	pub const fn target_context_length(&self) -> usize {
653		self.target_context_length
654	}
655	pub const fn model_width(&self) -> usize {
656		self.model_width
657	}
658	pub const fn hidden_width(&self) -> usize {
659		self.hidden_width
660	}
661	pub fn num_layers(&self) -> usize {
662		self.encoder_blocks.len()
663	}
664	pub const fn num_heads(&self) -> usize {
665		self.num_heads
666	}
667
668	/// Return one encoder block by layer index.
669	pub fn encoder_block(&self, index: usize) -> Option<&TransformerBlock> {
670		self.encoder_blocks.get(index).map(Rc::as_ref)
671	}
672
673	/// Return one decoder block by layer index.
674	pub fn decoder_block(&self, index: usize) -> Option<&EncoderDecoderBlock> {
675		self.decoder_blocks.get(index).map(Rc::as_ref)
676	}
677}
678
679impl Module for EncoderDecoder {
680	fn forward(&self, input: &Matrix) -> Result<Matrix> {
681		let _ = input;
682		Err(Error::invalid_argument(
683			"EncoderDecoder requires source and target tokens; call EncoderDecoder::forward(source, target)",
684		))
685	}
686	fn registry(&self) -> &ModuleRegistry {
687		&self.registry
688	}
689}