use std::{cell::Cell, rc::Rc};
use crate::{DType, Error, Matrix, Result, Runtime, matrix};
use super::super::{Module, ModuleRegistry, matrix::gelu};
use super::{AttentionMode, LayerNorm, Linear, MultiHeadAttention, TransformerBlock};
pub struct EncoderDecoderBlock {
model_width: usize,
hidden_width: usize,
sequence_length: Cell<usize>,
num_heads: usize,
norm_self_attention: Rc<LayerNorm>,
self_attention: Rc<MultiHeadAttention>,
norm_cross_attention: Rc<LayerNorm>,
cross_attention: Rc<MultiHeadAttention>,
norm_feed_forward: Rc<LayerNorm>,
feed_forward_input: Rc<Linear>,
feed_forward_output: Rc<Linear>,
registry: ModuleRegistry,
}
impl EncoderDecoderBlock {
pub fn new_with_seed(
model_width: usize,
hidden_width: usize,
sequence_length: usize,
num_heads: usize,
epsilon: f32,
seed: u64,
) -> Result<Self> {
Self::new_with_seed_on(
&Runtime::current()?,
model_width,
hidden_width,
sequence_length,
num_heads,
epsilon,
seed,
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_seed_on(
runtime: &Runtime,
model_width: usize,
hidden_width: usize,
sequence_length: usize,
num_heads: usize,
epsilon: f32,
seed: u64,
) -> Result<Self> {
if model_width == 0
|| hidden_width == 0
|| sequence_length == 0
|| num_heads == 0
|| !model_width.is_multiple_of(num_heads)
{
return Err(Error::invalid_argument(
"EncoderDecoderBlock requires positive D/FFN/S/H and D divisible by H",
));
}
let norm_self_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
let self_attention = Rc::new(MultiHeadAttention::new_with_seed_on(
runtime,
model_width,
num_heads,
sequence_length,
seed,
)?);
let norm_cross_attention = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
let cross_attention = Rc::new(MultiHeadAttention::new_with_seed_on(
runtime,
model_width,
num_heads,
sequence_length,
seed.wrapping_add(6),
)?);
let norm_feed_forward = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
let feed_forward_input = Rc::new(Linear::new_with_seed_on(
runtime,
model_width,
hidden_width,
seed.wrapping_add(12),
)?);
let feed_forward_output = Rc::new(Linear::new_with_seed_on(
runtime,
hidden_width,
model_width,
seed.wrapping_add(13),
)?);
let mut registry = ModuleRegistry::new();
registry.register_module("ln_self", norm_self_attention.clone())?;
registry.register_module("self_attn", self_attention.clone())?;
registry.register_module("ln_cross", norm_cross_attention.clone())?;
registry.register_module("cross_attn", cross_attention.clone())?;
registry.register_module("ln_ffn", norm_feed_forward.clone())?;
registry.register_module("ffn1", feed_forward_input.clone())?;
registry.register_module("ffn2", feed_forward_output.clone())?;
Ok(Self {
model_width,
hidden_width,
sequence_length: Cell::new(sequence_length),
num_heads,
norm_self_attention,
self_attention,
norm_cross_attention,
cross_attention,
norm_feed_forward,
feed_forward_input,
feed_forward_output,
registry,
})
}
pub fn forward(&self, input: &Matrix, encoder_output: &Matrix) -> Result<Matrix> {
let normalized = self.norm_self_attention.forward(input)?;
let attended = self.self_attention.forward(&normalized)?;
let residual = matrix::add(input, &attended)?;
let normalized = self.norm_cross_attention.forward(&residual)?;
let attended = self
.cross_attention
.forward_kv(&normalized, encoder_output)?;
let residual = matrix::add(&residual, &attended)?;
let normalized = self.norm_feed_forward.forward(&residual)?;
let hidden = gelu(&self.feed_forward_input.forward(&normalized)?)?;
let projected = self.feed_forward_output.forward(&hidden)?;
matrix::add(&residual, &projected)
}
pub const fn model_width(&self) -> usize {
self.model_width
}
pub const fn hidden_width(&self) -> usize {
self.hidden_width
}
pub fn sequence_length(&self) -> usize {
self.sequence_length.get()
}
pub const fn num_heads(&self) -> usize {
self.num_heads
}
pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
self.self_attention.set_sequence_length(sequence_length)?;
self.cross_attention.set_sequence_length(sequence_length)?;
self.sequence_length.set(sequence_length);
Ok(())
}
}
impl Module for EncoderDecoderBlock {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
let _ = input;
Err(Error::invalid_argument(
"EncoderDecoderBlock requires encoder output; call EncoderDecoderBlock::forward(input, encoder_output)",
))
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}
pub struct EncoderDecoder {
source_vocab_size: usize,
target_vocab_size: usize,
source_context_length: usize,
target_context_length: usize,
model_width: usize,
hidden_width: usize,
num_heads: usize,
source_token_embedding: Rc<super::Embedding>,
source_position_embedding: Rc<super::Embedding>,
target_token_embedding: Rc<super::Embedding>,
target_position_embedding: Rc<super::Embedding>,
encoder_blocks: Vec<Rc<TransformerBlock>>,
decoder_blocks: Vec<Rc<EncoderDecoderBlock>>,
encoder_norm: Rc<LayerNorm>,
decoder_norm: Rc<LayerNorm>,
head: Rc<Linear>,
registry: ModuleRegistry,
}
impl EncoderDecoder {
#[allow(clippy::too_many_arguments)]
pub fn new_with_seed(
source_vocab_size: usize,
target_vocab_size: usize,
source_context_length: usize,
target_context_length: usize,
model_width: usize,
hidden_width: usize,
num_layers: usize,
num_heads: usize,
epsilon: f32,
seed: u64,
) -> Result<Self> {
Self::new_with_seed_on(
&Runtime::current()?,
source_vocab_size,
target_vocab_size,
source_context_length,
target_context_length,
model_width,
hidden_width,
num_layers,
num_heads,
epsilon,
seed,
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_seed_on(
runtime: &Runtime,
source_vocab_size: usize,
target_vocab_size: usize,
source_context_length: usize,
target_context_length: usize,
model_width: usize,
hidden_width: usize,
num_layers: usize,
num_heads: usize,
epsilon: f32,
seed: u64,
) -> Result<Self> {
if source_vocab_size == 0
|| target_vocab_size == 0
|| source_context_length == 0
|| target_context_length == 0
|| model_width == 0
|| hidden_width == 0
|| num_layers == 0
|| num_heads == 0
|| !model_width.is_multiple_of(num_heads)
|| u32::try_from(source_context_length - 1).is_err()
|| u32::try_from(target_context_length - 1).is_err()
{
return Err(Error::invalid_argument(
"EncoderDecoder requires positive dimensions, D divisible by H, and U32 positions",
));
}
let source_token_embedding = Rc::new(super::Embedding::new_with_seed_on(
runtime,
source_vocab_size,
model_width,
seed,
)?);
let source_position_embedding = Rc::new(super::Embedding::new_with_seed_on(
runtime,
source_context_length,
model_width,
seed.wrapping_add(1),
)?);
let target_token_embedding = Rc::new(super::Embedding::new_with_seed_on(
runtime,
target_vocab_size,
model_width,
seed.wrapping_add(2),
)?);
let target_position_embedding = Rc::new(super::Embedding::new_with_seed_on(
runtime,
target_context_length,
model_width,
seed.wrapping_add(3),
)?);
let mut registry = ModuleRegistry::new();
registry.register_module("src_token_embedding", source_token_embedding.clone())?;
registry.register_module("src_position_embedding", source_position_embedding.clone())?;
registry.register_module("tgt_token_embedding", target_token_embedding.clone())?;
registry.register_module("tgt_position_embedding", target_position_embedding.clone())?;
let encoder_stride = 6_u64;
let mut encoder_blocks = Vec::with_capacity(num_layers);
for index in 0..num_layers {
let block = Rc::new(TransformerBlock::new_with_seed_on(
runtime,
model_width,
hidden_width,
source_context_length,
num_heads,
epsilon,
seed.wrapping_add(4 + (index as u64) * encoder_stride),
)?);
block.set_attention_mode(AttentionMode::Bidirectional);
registry.register_module(format!("encoder_{index}"), block.clone())?;
encoder_blocks.push(block);
}
let decoder_stride = 16_u64;
let decoder_base = 4 + (num_layers as u64) * encoder_stride;
let mut decoder_blocks = Vec::with_capacity(num_layers);
for index in 0..num_layers {
let block = Rc::new(EncoderDecoderBlock::new_with_seed_on(
runtime,
model_width,
hidden_width,
target_context_length,
num_heads,
epsilon,
seed.wrapping_add(decoder_base + (index as u64) * decoder_stride),
)?);
registry.register_module(format!("decoder_{index}"), block.clone())?;
decoder_blocks.push(block);
}
let encoder_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
let decoder_norm = Rc::new(LayerNorm::new_on(runtime, model_width, epsilon)?);
let head_seed = seed.wrapping_add(decoder_base + (num_layers as u64) * decoder_stride);
let head = Rc::new(Linear::new_with_seed_on(
runtime,
model_width,
target_vocab_size,
head_seed,
)?);
registry.register_module("encoder_norm", encoder_norm.clone())?;
registry.register_module("decoder_norm", decoder_norm.clone())?;
registry.register_module("head", head.clone())?;
Ok(Self {
source_vocab_size,
target_vocab_size,
source_context_length,
target_context_length,
model_width,
hidden_width,
num_heads,
source_token_embedding,
source_position_embedding,
target_token_embedding,
target_position_embedding,
encoder_blocks,
decoder_blocks,
encoder_norm,
decoder_norm,
head,
registry,
})
}
pub fn encode(&self, tokens: &Matrix) -> Result<Matrix> {
let (batch, sequence) = Self::token_geometry(tokens, self.source_context_length)?;
let rows = batch
.checked_mul(sequence)
.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
let mut value = self.embed(
tokens,
&self.source_token_embedding,
&self.source_position_embedding,
rows,
self.source_context_length,
)?;
for block in &self.encoder_blocks {
value = block.forward(&value)?;
}
self.encoder_norm.forward(&value)
}
pub fn decode(&self, tokens: &Matrix, encoder_output: &Matrix) -> Result<Matrix> {
let (batch, sequence) = Self::token_geometry(tokens, self.target_context_length)?;
let [encoder_rows, encoder_width] = encoder_output.shape() else {
return Err(Error::invalid_argument(
"EncoderDecoder encoder output must have shape [batch*source_context, D]",
));
};
if encoder_output.dtype() != DType::F32
|| *encoder_width != self.model_width
|| *encoder_rows != batch * self.source_context_length
|| !tokens.runtime().same_as(encoder_output.runtime())
{
return Err(Error::invalid_argument(format!(
"EncoderDecoder requires same-runtime F32 encoder output [{}, {}]; found {:?} {}",
batch * self.source_context_length,
self.model_width,
encoder_output.shape(),
encoder_output.dtype().token(),
)));
}
let rows = batch
.checked_mul(sequence)
.ok_or_else(|| Error::invalid_argument("EncoderDecoder row count overflows usize"))?;
let mut value = self.embed(
tokens,
&self.target_token_embedding,
&self.target_position_embedding,
rows,
self.target_context_length,
)?;
for block in &self.decoder_blocks {
value = block.forward(&value, encoder_output)?;
}
self.head.forward(&self.decoder_norm.forward(&value)?)
}
pub fn forward(&self, source: &Matrix, target: &Matrix) -> Result<Matrix> {
self.decode(target, &self.encode(source)?)
}
fn token_geometry(tokens: &Matrix, context_length: usize) -> Result<(usize, usize)> {
let [batch, sequence] = tokens.shape() else {
return Err(Error::invalid_argument(
"EncoderDecoder tokens must have shape [batch, context_length]",
));
};
if *batch == 0
|| *sequence != context_length
|| !matches!(tokens.dtype(), DType::U8 | DType::U32)
{
return Err(Error::invalid_argument(format!(
"EncoderDecoder tokens must be nonempty U8 or U32 [batch, {context_length}]"
)));
}
Ok((*batch, *sequence))
}
fn embed(
&self,
tokens: &Matrix,
token_embedding: &super::Embedding,
position_embedding: &super::Embedding,
rows: usize,
context_length: usize,
) -> Result<Matrix> {
let position_values = (0..rows)
.map(|index| (index % context_length) as u32)
.collect::<Vec<_>>();
let position_ids =
Matrix::new_from_slice_handle(tokens.runtime(), vec![rows], &position_values)?;
let token_values = token_embedding
.forward(tokens)?
.reshape([rows, self.model_width])?;
let position_values = position_embedding.forward(&position_ids)?;
matrix::add(&token_values, &position_values)
}
pub const fn source_vocab_size(&self) -> usize {
self.source_vocab_size
}
pub const fn target_vocab_size(&self) -> usize {
self.target_vocab_size
}
pub const fn source_context_length(&self) -> usize {
self.source_context_length
}
pub const fn target_context_length(&self) -> usize {
self.target_context_length
}
pub const fn model_width(&self) -> usize {
self.model_width
}
pub const fn hidden_width(&self) -> usize {
self.hidden_width
}
pub fn num_layers(&self) -> usize {
self.encoder_blocks.len()
}
pub const fn num_heads(&self) -> usize {
self.num_heads
}
pub fn encoder_block(&self, index: usize) -> Option<&TransformerBlock> {
self.encoder_blocks.get(index).map(Rc::as_ref)
}
pub fn decoder_block(&self, index: usize) -> Option<&EncoderDecoderBlock> {
self.decoder_blocks.get(index).map(Rc::as_ref)
}
}
impl Module for EncoderDecoder {
fn forward(&self, input: &Matrix) -> Result<Matrix> {
let _ = input;
Err(Error::invalid_argument(
"EncoderDecoder requires source and target tokens; call EncoderDecoder::forward(source, target)",
))
}
fn registry(&self) -> &ModuleRegistry {
&self.registry
}
}