oa/ml/nn/
attention_pool.rs1use std::rc::Rc;
4
5use crate::{DType, Error, Matrix, Result, Runtime, matrix};
6
7use super::super::{Module, ModuleRegistry, Parameter, autograd};
8use super::MultiHeadAttention;
9
10pub struct AttentionPool {
18 model_width: usize,
19 query: Parameter,
20 attention: Rc<MultiHeadAttention>,
21 registry: ModuleRegistry,
22}
23
24impl AttentionPool {
25 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 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 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}