Skip to main content

oa/ml/nn/
attention_pool.rs

1//! Attention pooling: a learned query attending over a sequence.
2
3use std::rc::Rc;
4
5use crate::{DType, Error, Matrix, Result, Runtime, matrix};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd};
8use super::MultiHeadAttention;
9
10/// Pool a `[B*S, D]` sequence to `[B, D]` through a single learned query.
11///
12/// The query is a trainable `[1, D]` parameter broadcast to one query row
13/// per batch element, then routed through [`MultiHeadAttention::forward_kv`]
14/// — the same cross-attention path encoder-decoder uses, with the sequence
15/// as key/value source. Equivalent to `nn.MultiheadAttention` pooling blocks
16/// used by ViT-style attention poolers.
17pub struct AttentionPool {
18	model_width: usize,
19	query: Parameter,
20	attention: Rc<MultiHeadAttention>,
21	registry: ModuleRegistry,
22}
23
24impl AttentionPool {
25	/// Construct with a seeded single-query attention block and a
26	/// zero-initialized query.
27	///
28	/// The internal attention uses query sequence length one; the key/value
29	/// extent is taken from the input at each forward.
30	///
31	/// # Errors
32	///
33	/// Returns an error under the attention constructor contract or when
34	/// allocation/registration fails.
35	pub fn new_with_seed_on(
36		runtime: &Runtime,
37		model_width: usize,
38		num_heads: usize,
39		seed: u64,
40	) -> Result<Self> {
41		if model_width == 0 {
42			return Err(Error::invalid_argument(
43				"attention pool requires a nonzero model width",
44			));
45		}
46		let attention = Rc::new(MultiHeadAttention::new_with_seed_on(
47			runtime,
48			model_width,
49			num_heads,
50			1,
51			seed,
52		)?);
53		let query = Parameter::new(
54			"query",
55			Matrix::new_from_f32_on(runtime, [1, model_width], &vec![0.0_f32; model_width])?,
56		)?;
57		let mut registry = ModuleRegistry::new();
58		registry.register_parameter("query", query.clone())?;
59		registry.register_module("attention", Rc::clone(&attention) as Rc<dyn Module>)?;
60		Ok(Self {
61			model_width,
62			query,
63			attention,
64			registry,
65		})
66	}
67
68	/// Construct on the current runtime.
69	///
70	/// # Errors
71	///
72	/// Returns an error under the same contract as [`Self::new_with_seed_on`].
73	pub fn new_with_seed(model_width: usize, num_heads: usize, seed: u64) -> Result<Self> {
74		Self::new_with_seed_on(&Runtime::current()?, model_width, num_heads, seed)
75	}
76
77	/// Pool `input` shaped `[B*S, D]` to `[B, D]` for `batch` sequences.
78	///
79	/// # Errors
80	///
81	/// Returns an error unless `input` is F32 `[B*S, D]` with `B == batch`,
82	/// or the attention forward fails.
83	pub fn forward(&self, input: &Matrix, batch: usize) -> Result<Matrix> {
84		let [rows, width] = input.shape() else {
85			return Err(Error::invalid_argument(format!(
86				"attention pool requires [B*S, D]; found {:?}",
87				input.shape(),
88			)));
89		};
90		if input.dtype() != DType::F32 || *width != self.model_width {
91			return Err(Error::invalid_argument(format!(
92				"attention pool requires F32 width {}; found {:?} {}",
93				self.model_width,
94				input.shape(),
95				input.dtype().token(),
96			)));
97		}
98		if batch == 0 || !rows.is_multiple_of(batch) {
99			return Err(Error::invalid_argument(format!(
100				"attention pool rows {rows} must be a multiple of batch {batch}"
101			)));
102		}
103		autograd::record_parameter_leaf(&self.query)?;
104		let query = matrix::repeat_interleave(&self.query.data(), batch, 0)?;
105		self.attention.forward_kv(&query, input)
106	}
107}
108
109impl Module for AttentionPool {
110	fn forward(&self, input: &Matrix) -> Result<Matrix> {
111		let _ = input;
112		Err(Error::invalid_argument(
113			"AttentionPool requires the batch count; call AttentionPool::forward(input, batch)",
114		))
115	}
116
117	fn registry(&self) -> &ModuleRegistry {
118		&self.registry
119	}
120}