1use std::{
6 cell::{Cell, RefCell},
7 rc::Rc,
8};
9
10use crate::{DType, Error, Matrix, Result, Runtime, matrix as core_matrix};
11
12use super::super::{
13 Module, ModuleRegistry, NamedRngState, autograd,
14 matrix::{
15 bmm, bmm_nt, bmm_tn, flash_attention_causal, merge_heads, scaled_dot_product_attention,
16 softmax_scaled_masked, split_heads,
17 },
18};
19
20use super::Linear;
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum AttentionBackend {
31 #[default]
33 Auto,
34 Standard,
36 Flash,
38 Linear,
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub enum AttentionMode {
47 #[default]
49 Causal,
50 Bidirectional,
52}
53
54pub struct MultiHeadAttention {
56 model_width: usize,
57 num_heads: usize,
58 num_kv_heads: usize,
59 sequence_length: Cell<usize>,
60 query_projection: Rc<Linear>,
61 key_projection: Rc<Linear>,
62 value_projection: Rc<Linear>,
63 output_projection: Rc<Linear>,
64 dropout_probability: f32,
65 dropout_seed: u64,
66 dropout_draw: Option<NamedRngState>,
67 backend: Cell<AttentionBackend>,
68 mode: Cell<AttentionMode>,
69 last_backend: Cell<AttentionBackend>,
70 mask_cache: RefCell<Vec<AttentionMask>>,
71 registry: ModuleRegistry,
72}
73
74struct AttentionMask {
75 batch: usize,
76 sequence_length: usize,
77 key_length: usize,
78 causal: bool,
79 value: Matrix,
80}
81
82pub struct AttentionCache {
88 owner_id: u64,
89 batch_size: usize,
90 keys: Option<Matrix>,
91 values: Option<Matrix>,
92 position: usize,
93}
94
95impl AttentionCache {
96 pub const fn batch_size(&self) -> usize {
98 self.batch_size
99 }
100
101 pub const fn len(&self) -> usize {
103 self.position
104 }
105
106 pub const fn is_empty(&self) -> bool {
108 self.position == 0
109 }
110}
111
112impl MultiHeadAttention {
113 #[allow(clippy::too_many_arguments)]
114 pub fn new_with_seed(
115 model_width: usize,
116 num_heads: usize,
117 sequence_length: usize,
118 seed: u64,
119 ) -> Result<Self> {
120 Self::new_with_seed_on(
121 &Runtime::current()?,
122 model_width,
123 num_heads,
124 sequence_length,
125 seed,
126 )
127 }
128
129 pub fn new_with_seed_on(
137 runtime: &Runtime,
138 model_width: usize,
139 num_heads: usize,
140 sequence_length: usize,
141 seed: u64,
142 ) -> Result<Self> {
143 Self::new_with_seed_and_options_on(
144 runtime,
145 model_width,
146 num_heads,
147 sequence_length,
148 0.0,
149 true,
150 seed,
151 )
152 }
153
154 #[allow(clippy::too_many_arguments)]
155 pub fn new_with_seed_and_bias(
156 model_width: usize,
157 num_heads: usize,
158 sequence_length: usize,
159 bias: bool,
160 seed: u64,
161 ) -> Result<Self> {
162 Self::new_with_seed_and_bias_on(
163 &Runtime::current()?,
164 model_width,
165 num_heads,
166 sequence_length,
167 bias,
168 seed,
169 )
170 }
171
172 pub fn new_with_seed_and_bias_on(
179 runtime: &Runtime,
180 model_width: usize,
181 num_heads: usize,
182 sequence_length: usize,
183 bias: bool,
184 seed: u64,
185 ) -> Result<Self> {
186 Self::new_with_seed_and_options_on(
187 runtime,
188 model_width,
189 num_heads,
190 sequence_length,
191 0.0,
192 bias,
193 seed,
194 )
195 }
196
197 #[allow(clippy::too_many_arguments)]
208 pub fn new_with_seed_and_options(
209 model_width: usize,
210 num_heads: usize,
211 sequence_length: usize,
212 dropout_probability: f32,
213 bias: bool,
214 seed: u64,
215 ) -> Result<Self> {
216 Self::new_with_seed_and_options_on(
217 &Runtime::current()?,
218 model_width,
219 num_heads,
220 sequence_length,
221 dropout_probability,
222 bias,
223 seed,
224 )
225 }
226
227 #[allow(clippy::too_many_arguments)]
228 pub fn new_with_seed_and_options_on(
229 runtime: &Runtime,
230 model_width: usize,
231 num_heads: usize,
232 sequence_length: usize,
233 dropout_probability: f32,
234 bias: bool,
235 seed: u64,
236 ) -> Result<Self> {
237 Self::new_with_seed_and_options_grouped_on(
238 runtime,
239 model_width,
240 num_heads,
241 num_heads,
242 sequence_length,
243 dropout_probability,
244 bias,
245 seed,
246 )
247 }
248
249 #[allow(clippy::too_many_arguments)]
264 pub fn new_with_seed_and_options_grouped_on(
265 runtime: &Runtime,
266 model_width: usize,
267 num_heads: usize,
268 num_kv_heads: usize,
269 sequence_length: usize,
270 dropout_probability: f32,
271 bias: bool,
272 seed: u64,
273 ) -> Result<Self> {
274 if model_width == 0
275 || num_heads == 0
276 || num_kv_heads == 0
277 || sequence_length == 0
278 || !model_width.is_multiple_of(num_heads)
279 || !num_heads.is_multiple_of(num_kv_heads)
280 {
281 return Err(Error::invalid_argument(
282 "attention requires positive D/H/KV/S, D divisible by H, and H divisible by KV",
283 ));
284 }
285 if !dropout_probability.is_finite() || !(0.0..1.0).contains(&dropout_probability) {
286 return Err(Error::invalid_argument(
287 "attention dropout probability must be finite and in [0, 1)",
288 ));
289 }
290 let kv_width = (model_width / num_heads)
291 .checked_mul(num_kv_heads)
292 .ok_or_else(|| Error::invalid_argument("attention key/value width overflows usize"))?;
293 let query_projection = Rc::new(Linear::new_with_seed_and_bias_on(
294 runtime,
295 model_width,
296 model_width,
297 bias,
298 seed,
299 )?);
300 let key_projection = Rc::new(Linear::new_with_seed_and_bias_on(
301 runtime,
302 model_width,
303 kv_width,
304 bias,
305 seed.wrapping_add(1),
306 )?);
307 let value_projection = Rc::new(Linear::new_with_seed_and_bias_on(
308 runtime,
309 model_width,
310 kv_width,
311 bias,
312 seed.wrapping_add(2),
313 )?);
314 let output_projection = Rc::new(Linear::new_with_seed_and_bias_on(
315 runtime,
316 model_width,
317 model_width,
318 bias,
319 seed.wrapping_add(3),
320 )?);
321 let mut registry = ModuleRegistry::new();
322 registry.register_module("q_proj", query_projection.clone())?;
323 registry.register_module("k_proj", key_projection.clone())?;
324 registry.register_module("v_proj", value_projection.clone())?;
325 registry.register_module("out_proj", output_projection.clone())?;
326 let dropout_draw = if dropout_probability > 0.0 {
327 Some(registry.register_rng_state("dropout_draw", 0)?)
328 } else {
329 None
330 };
331 Ok(Self {
332 model_width,
333 num_heads,
334 num_kv_heads,
335 sequence_length: Cell::new(sequence_length),
336 query_projection,
337 key_projection,
338 value_projection,
339 output_projection,
340 dropout_probability,
341 dropout_seed: seed.wrapping_add(4),
342 dropout_draw,
343 backend: Cell::new(AttentionBackend::Auto),
344 mode: Cell::new(AttentionMode::Causal),
345 last_backend: Cell::new(AttentionBackend::Standard),
346 mask_cache: RefCell::new(Vec::new()),
347 registry,
348 })
349 }
350
351 fn geometry(&self, input: &Matrix) -> Result<usize> {
352 let sequence_length = self.sequence_length.get();
353 let [rows, width] = input.shape() else {
354 return Err(Error::invalid_argument(
355 "MultiHeadAttention expects F32 [B*S, D] input",
356 ));
357 };
358 if input.dtype() != DType::F32
359 || *width != self.model_width
360 || *rows == 0
361 || !rows.is_multiple_of(sequence_length)
362 {
363 return Err(Error::invalid_argument(format!(
364 "MultiHeadAttention expects nonempty F32 [B*S, {}] with S={}; found {:?} {}",
365 self.model_width,
366 sequence_length,
367 input.shape(),
368 input.dtype().token(),
369 )));
370 }
371 Ok(rows / sequence_length)
372 }
373
374 fn project(&self, input: &Matrix) -> Result<(Matrix, Matrix, Matrix)> {
375 Ok((
376 self.query_projection.forward(input)?,
377 self.key_projection.forward(input)?,
378 self.value_projection.forward(input)?,
379 ))
380 }
381
382 fn grouped_heads(&self, tensor: &Matrix, batch: usize, sequence_length: usize) -> Result<Matrix> {
385 let heads = split_heads(tensor, batch, sequence_length, self.num_kv_heads)?;
386 if self.num_kv_heads == self.num_heads {
387 return Ok(heads);
388 }
389 core_matrix::repeat_interleave(&heads, self.num_heads / self.num_kv_heads, 0)
390 }
391
392 fn expand_cached_heads(&self, tensor: &Matrix) -> Result<Matrix> {
394 if self.num_kv_heads == self.num_heads {
395 return Ok(tensor.clone());
396 }
397 core_matrix::repeat_interleave(tensor, self.num_heads / self.num_kv_heads, 0)
398 }
399
400 fn forward_standard(
401 &self,
402 input: &Matrix,
403 additive_mask: Option<&Matrix>,
404 causal: bool,
405 ) -> Result<Matrix> {
406 let batch = self.geometry(input)?;
407 let sequence_length = self.sequence_length.get();
408 let (query, key, value) = self.project(input)?;
409 let query = split_heads(&query, batch, sequence_length, self.num_heads)?;
410 let key = self.grouped_heads(&key, batch, sequence_length)?;
411 let value = self.grouped_heads(&value, batch, sequence_length)?;
412 let scale = 1.0 / ((self.model_width / self.num_heads) as f32).sqrt();
413 let context = if self.is_training() && self.dropout_probability > 0.0 {
414 let batch_heads = batch
415 .checked_mul(self.num_heads)
416 .ok_or_else(|| Error::invalid_argument("attention batch by head count overflows usize"))?;
417 let score_rows = batch_heads
418 .checked_mul(sequence_length)
419 .ok_or_else(|| Error::invalid_argument("attention score rows overflow usize"))?;
420 let scores = bmm_nt(&query, &key)?.reshape([score_rows, sequence_length])?;
421 let owned_mask;
422 let mask = if let Some(mask) = additive_mask {
423 mask
424 } else {
425 owned_mask = self.cached_mask(input, batch, causal)?;
426 &owned_mask
427 };
428 let probability = softmax_scaled_masked(&scores, mask, scale)?;
429 let Some(stream) = self.dropout_draw.as_ref() else {
430 return Err(Error::internal("attention dropout stream is unregistered"));
431 };
432 let probability = core_matrix::dropout_streamed(
433 &probability,
434 self.dropout_probability,
435 self.dropout_seed,
436 stream,
437 )?;
438 bmm(
439 &probability.reshape([batch_heads, sequence_length, sequence_length])?,
440 &value,
441 )?
442 } else {
443 scaled_dot_product_attention(&query, &key, &value, additive_mask, scale, causal)?
444 };
445 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
446 let output = self.output_projection.forward(&context)?;
447 self.last_backend.set(AttentionBackend::Standard);
448 Ok(output)
449 }
450
451 fn cached_mask(&self, input: &Matrix, batch: usize, causal: bool) -> Result<Matrix> {
452 let sequence_length = self.sequence_length.get();
453 self.cached_mask_impl(input, batch, sequence_length, sequence_length, causal)
454 }
455
456 fn cached_mask_impl(
457 &self,
458 input: &Matrix,
459 batch: usize,
460 sequence_length: usize,
461 key_length: usize,
462 causal: bool,
463 ) -> Result<Matrix> {
464 if let Some(mask) = self.mask_cache.borrow().iter().find(|mask| {
465 mask.batch == batch
466 && mask.sequence_length == sequence_length
467 && mask.key_length == key_length
468 && mask.causal == causal
469 }) {
470 return Ok(mask.value.clone());
471 }
472 let batch_heads = batch
473 .checked_mul(self.num_heads)
474 .ok_or_else(|| Error::invalid_argument("attention batch by head count overflows usize"))?;
475 let score_rows = batch_heads
476 .checked_mul(sequence_length)
477 .ok_or_else(|| Error::invalid_argument("attention score rows overflow usize"))?;
478 let count = score_rows
479 .checked_mul(key_length)
480 .ok_or_else(|| Error::invalid_argument("attention score size overflows usize"))?;
481 let mut values = vec![0.0_f32; count];
482 if causal {
483 for row in 0..score_rows {
484 let query = row % sequence_length;
485 for key in query + 1..key_length {
486 values[row * key_length + key] = -1.0e9;
487 }
488 }
489 }
490 let mask = Matrix::allocate(
491 input.runtime(),
492 vec![score_rows, key_length],
493 count,
494 DType::F32,
495 )?;
496 mask.write_values(&values)?;
497 self.mask_cache.borrow_mut().push(AttentionMask {
498 batch,
499 sequence_length,
500 key_length,
501 causal,
502 value: mask.clone(),
503 });
504 Ok(mask)
505 }
506
507 fn forward_flash(&self, input: &Matrix) -> Result<Matrix> {
508 let batch = self.geometry(input)?;
509 let sequence_length = self.sequence_length.get();
510 let (query, key, value) = self.project(input)?;
511 let query = split_heads(&query, batch, sequence_length, self.num_heads)?;
512 let key = self.grouped_heads(&key, batch, sequence_length)?;
513 let value = self.grouped_heads(&value, batch, sequence_length)?;
514 let scale = 1.0 / ((self.model_width / self.num_heads) as f32).sqrt();
515 let context = flash_attention_causal(&query, &key, &value, scale)?;
516 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
517 let output = self.output_projection.forward(&context)?;
518 self.last_backend.set(AttentionBackend::Flash);
519 Ok(output)
520 }
521
522 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
533 let mode = self.mode.get();
534 match self.backend.get() {
535 AttentionBackend::Flash => {
536 if mode != AttentionMode::Causal
537 || input.dtype() != DType::F32
538 || self.dropout_probability != 0.0
539 || self.sequence_length.get() > 1024
540 {
541 return Err(Error::invalid_argument(
542 "FlashAttention requires causal F32 input, dropout=0, and sequence length <= 1024",
543 ));
544 }
545 self.forward_flash(input)
546 }
547 AttentionBackend::Linear => Err(Error::invalid_argument(
548 "AttentionBackend::Linear is not supported by MultiHeadAttention; use CausalLinearAttention instead",
549 )),
550 AttentionBackend::Auto | AttentionBackend::Standard => {
551 self.forward_standard(input, None, mode == AttentionMode::Causal)
552 }
553 }
554 }
555
556 pub fn forward_masked(&self, input: &Matrix, additive_mask: &Matrix) -> Result<Matrix> {
565 if self.backend.get() == AttentionBackend::Flash {
566 return Err(Error::invalid_argument(
567 "FlashAttention does not accept an arbitrary additive mask",
568 ));
569 }
570 self.forward_standard(input, Some(additive_mask), false)
571 }
572
573 pub fn forward_kv(&self, input: &Matrix, key_value_source: &Matrix) -> Result<Matrix> {
590 self.forward_kv_impl(input, key_value_source, None)
591 }
592
593 pub fn forward_kv_masked(
601 &self,
602 input: &Matrix,
603 key_value_source: &Matrix,
604 additive_mask: &Matrix,
605 ) -> Result<Matrix> {
606 self.forward_kv_impl(input, key_value_source, Some(additive_mask))
607 }
608
609 fn forward_kv_impl(
610 &self,
611 input: &Matrix,
612 key_value_source: &Matrix,
613 additive_mask: Option<&Matrix>,
614 ) -> Result<Matrix> {
615 if self.backend.get() == AttentionBackend::Flash {
616 return Err(Error::invalid_argument(
617 "FlashAttention does not admit a separate key/value source",
618 ));
619 }
620 let batch = self.geometry(input)?;
621 let sequence_length = self.sequence_length.get();
622 let [key_rows, key_width] = key_value_source.shape() else {
623 return Err(Error::invalid_argument(
624 "MultiHeadAttention cross-attention expects F32 [B*S_kv, D] key/value source",
625 ));
626 };
627 if key_value_source.dtype() != DType::F32
628 || *key_width != self.model_width
629 || *key_rows == 0
630 || !key_rows.is_multiple_of(batch)
631 || !input.runtime().same_as(key_value_source.runtime())
632 {
633 return Err(Error::invalid_argument(format!(
634 "MultiHeadAttention cross-attention requires same-runtime F32 [B*S_kv, {}] source with batch {batch}; found {:?} {}",
635 self.model_width,
636 key_value_source.shape(),
637 key_value_source.dtype().token(),
638 )));
639 }
640 let key_length = key_rows / batch;
641 let query = self.query_projection.forward(input)?;
642 let key = self.key_projection.forward(key_value_source)?;
643 let value = self.value_projection.forward(key_value_source)?;
644 let query = split_heads(&query, batch, sequence_length, self.num_heads)?;
645 let key = self.grouped_heads(&key, batch, key_length)?;
646 let value = self.grouped_heads(&value, batch, key_length)?;
647 let scale = 1.0 / ((self.model_width / self.num_heads) as f32).sqrt();
648 let batch_heads = batch
649 .checked_mul(self.num_heads)
650 .ok_or_else(|| Error::invalid_argument("attention batch by head count overflows usize"))?;
651 let score_rows = batch_heads
652 .checked_mul(sequence_length)
653 .ok_or_else(|| Error::invalid_argument("attention score rows overflow usize"))?;
654 let scores = bmm_nt(&query, &key)?.reshape([score_rows, key_length])?;
655 let owned_mask;
656 let mask = if let Some(mask) = additive_mask {
657 mask
658 } else {
659 owned_mask = self.cached_mask_impl(input, batch, sequence_length, key_length, false)?;
660 &owned_mask
661 };
662 let mut probability = softmax_scaled_masked(&scores, mask, scale)?;
663 if self.is_training() && self.dropout_probability > 0.0 {
664 let Some(stream) = self.dropout_draw.as_ref() else {
665 return Err(Error::internal("attention dropout stream is unregistered"));
666 };
667 probability = core_matrix::dropout_streamed(
668 &probability,
669 self.dropout_probability,
670 self.dropout_seed,
671 stream,
672 )?;
673 }
674 let context = bmm(
675 &probability.reshape([batch_heads, sequence_length, key_length])?,
676 &value,
677 )?;
678 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
679 let output = self.output_projection.forward(&context)?;
680 self.last_backend.set(AttentionBackend::Standard);
681 Ok(output)
682 }
683
684 pub fn new_cache(&self, batch_size: usize) -> Result<AttentionCache> {
693 if batch_size == 0 {
694 return Err(Error::invalid_argument(
695 "MultiHeadAttention attention cache requires a positive batch size",
696 ));
697 }
698 Ok(AttentionCache {
699 owner_id: self.query_projection.weight().data().value_id(),
700 batch_size,
701 keys: None,
702 values: None,
703 position: 0,
704 })
705 }
706
707 pub fn step(&self, input: &Matrix, cache: &mut AttentionCache) -> Result<Matrix> {
721 if autograd::recording_active() {
722 return Err(Error::failed_precondition(
723 "MultiHeadAttention incremental attention is inference-only and cannot run inside a GradientTape",
724 ));
725 }
726 let owner = self.query_projection.weight().data();
727 if cache.owner_id != owner.value_id() {
728 return Err(Error::invalid_argument(
729 "MultiHeadAttention attention cache belongs to another module instance",
730 ));
731 }
732 if input.shape() != [cache.batch_size, self.model_width] || input.dtype() != DType::F32 {
733 return Err(Error::invalid_argument(format!(
734 "MultiHeadAttention step requires F32 input [{}, {}]; found {:?} {}",
735 cache.batch_size,
736 self.model_width,
737 input.shape(),
738 input.dtype().token(),
739 )));
740 }
741 let (query, key, value) = self.project(input)?;
742 let query = split_heads(&query, cache.batch_size, 1, self.num_heads)?;
743 let key = split_heads(&key, cache.batch_size, 1, self.num_kv_heads)?;
744 let value = split_heads(&value, cache.batch_size, 1, self.num_kv_heads)?;
745 let (keys, values) = match (cache.keys.take(), cache.values.take()) {
746 (Some(keys), Some(values)) => (
747 core_matrix::concat(&[keys, key], 1)?,
748 core_matrix::concat(&[values, value], 1)?,
749 ),
750 (None, None) => (key, value),
751 _ => {
752 return Err(Error::failed_precondition(
753 "MultiHeadAttention attention cache holds a partial key/value pair",
754 ));
755 }
756 };
757 let (attend_keys, attend_values) = (
758 self.expand_cached_heads(&keys)?,
759 self.expand_cached_heads(&values)?,
760 );
761 let scale = 1.0 / ((self.model_width / self.num_heads) as f32).sqrt();
762 let scores = bmm_nt(&query, &attend_keys)?;
763 let scaled = core_matrix::scale(&scores, scale)?;
764 let probabilities = core_matrix::softmax(&scaled, -1)?;
765 let context = bmm(&probabilities, &attend_values)?;
766 cache.keys = Some(keys);
767 cache.values = Some(values);
768 cache.position += 1;
769 let context = merge_heads(&context, cache.batch_size, 1, self.num_heads)?;
770 self.output_projection.forward(&context)
771 }
772
773 pub fn set_backend(&self, backend: AttentionBackend) {
775 self.backend.set(backend);
776 }
777
778 pub fn backend(&self) -> AttentionBackend {
780 self.backend.get()
781 }
782
783 pub fn last_backend(&self) -> AttentionBackend {
785 self.last_backend.get()
786 }
787
788 pub fn set_mode(&self, mode: AttentionMode) {
790 self.mode.set(mode);
791 }
792
793 pub fn mode(&self) -> AttentionMode {
795 self.mode.get()
796 }
797
798 pub const fn model_width(&self) -> usize {
799 self.model_width
800 }
801 pub const fn num_heads(&self) -> usize {
802 self.num_heads
803 }
804
805 pub const fn num_kv_heads(&self) -> usize {
811 self.num_kv_heads
812 }
813 pub fn sequence_length(&self) -> usize {
814 self.sequence_length.get()
815 }
816
817 pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
823 if sequence_length == 0 {
824 return Err(Error::invalid_argument(
825 "attention sequence length must be nonzero",
826 ));
827 }
828 if self.sequence_length.replace(sequence_length) != sequence_length {
829 self.mask_cache.borrow_mut().clear();
830 }
831 Ok(())
832 }
833
834 pub fn has_bias(&self) -> bool {
836 self.query_projection.has_bias()
837 }
838
839 pub const fn dropout_probability(&self) -> f32 {
841 self.dropout_probability
842 }
843}
844
845impl Module for MultiHeadAttention {
846 fn forward(&self, input: &Matrix) -> Result<Matrix> {
847 MultiHeadAttention::forward(self, input)
848 }
849 fn registry(&self) -> &ModuleRegistry {
850 &self.registry
851 }
852}
853
854#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
858pub enum LinearAttentionMode {
859 #[default]
866 Causal,
867 Bidirectional,
871}
872
873pub struct CausalLinearAttention {
889 model_width: usize,
890 num_heads: usize,
891 sequence_length: Cell<usize>,
892 query_projection: Rc<Linear>,
893 key_projection: Rc<Linear>,
894 value_projection: Rc<Linear>,
895 output_projection: Rc<Linear>,
896 mode: Cell<LinearAttentionMode>,
897 registry: ModuleRegistry,
898}
899
900impl CausalLinearAttention {
901 #[allow(clippy::too_many_arguments)]
902 pub fn new_with_seed(
903 model_width: usize,
904 num_heads: usize,
905 sequence_length: usize,
906 seed: u64,
907 ) -> Result<Self> {
908 Self::new_with_seed_on(
909 &Runtime::current()?,
910 model_width,
911 num_heads,
912 sequence_length,
913 seed,
914 )
915 }
916
917 pub fn new_with_seed_on(
924 runtime: &Runtime,
925 model_width: usize,
926 num_heads: usize,
927 sequence_length: usize,
928 seed: u64,
929 ) -> Result<Self> {
930 Self::new_with_seed_and_options_on(runtime, model_width, num_heads, sequence_length, true, seed)
931 }
932
933 #[allow(clippy::too_many_arguments)]
934 pub fn new_with_seed_and_bias(
935 model_width: usize,
936 num_heads: usize,
937 sequence_length: usize,
938 bias: bool,
939 seed: u64,
940 ) -> Result<Self> {
941 Self::new_with_seed_and_bias_on(
942 &Runtime::current()?,
943 model_width,
944 num_heads,
945 sequence_length,
946 bias,
947 seed,
948 )
949 }
950
951 pub fn new_with_seed_and_bias_on(
958 runtime: &Runtime,
959 model_width: usize,
960 num_heads: usize,
961 sequence_length: usize,
962 bias: bool,
963 seed: u64,
964 ) -> Result<Self> {
965 Self::new_with_seed_and_options_on(runtime, model_width, num_heads, sequence_length, bias, seed)
966 }
967
968 #[allow(clippy::too_many_arguments)]
969 pub fn new_with_seed_and_options(
970 model_width: usize,
971 num_heads: usize,
972 sequence_length: usize,
973 bias: bool,
974 seed: u64,
975 ) -> Result<Self> {
976 Self::new_with_seed_and_options_on(
977 &Runtime::current()?,
978 model_width,
979 num_heads,
980 sequence_length,
981 bias,
982 seed,
983 )
984 }
985
986 pub fn new_with_seed_and_options_on(
994 runtime: &Runtime,
995 model_width: usize,
996 num_heads: usize,
997 sequence_length: usize,
998 bias: bool,
999 seed: u64,
1000 ) -> Result<Self> {
1001 if model_width == 0
1002 || num_heads == 0
1003 || sequence_length == 0
1004 || !model_width.is_multiple_of(num_heads)
1005 {
1006 return Err(Error::invalid_argument(
1007 "CausalLinearAttention requires positive D/H/S and D divisible by H",
1008 ));
1009 }
1010 let query_projection = Rc::new(Linear::new_with_seed_and_bias_on(
1011 runtime,
1012 model_width,
1013 model_width,
1014 bias,
1015 seed,
1016 )?);
1017 let key_projection = Rc::new(Linear::new_with_seed_and_bias_on(
1018 runtime,
1019 model_width,
1020 model_width,
1021 bias,
1022 seed.wrapping_add(1),
1023 )?);
1024 let value_projection = Rc::new(Linear::new_with_seed_and_bias_on(
1025 runtime,
1026 model_width,
1027 model_width,
1028 bias,
1029 seed.wrapping_add(2),
1030 )?);
1031 let output_projection = Rc::new(Linear::new_with_seed_and_bias_on(
1032 runtime,
1033 model_width,
1034 model_width,
1035 bias,
1036 seed.wrapping_add(3),
1037 )?);
1038 let mut registry = ModuleRegistry::new();
1039 registry.register_module("q_proj", query_projection.clone())?;
1040 registry.register_module("k_proj", key_projection.clone())?;
1041 registry.register_module("v_proj", value_projection.clone())?;
1042 registry.register_module("out_proj", output_projection.clone())?;
1043 Ok(Self {
1044 model_width,
1045 num_heads,
1046 sequence_length: Cell::new(sequence_length),
1047 query_projection,
1048 key_projection,
1049 value_projection,
1050 output_projection,
1051 mode: Cell::new(LinearAttentionMode::Causal),
1052 registry,
1053 })
1054 }
1055
1056 fn geometry(&self, input: &Matrix) -> Result<usize> {
1059 let sequence_length = self.sequence_length.get();
1060 let [rows, width] = input.shape() else {
1061 return Err(Error::invalid_argument(
1062 "CausalLinearAttention expects F32 [B*S, D] input",
1063 ));
1064 };
1065 if input.dtype() != DType::F32
1066 || *width != self.model_width
1067 || *rows == 0
1068 || !rows.is_multiple_of(sequence_length)
1069 {
1070 return Err(Error::invalid_argument(format!(
1071 "CausalLinearAttention expects nonempty F32 [B*S, {}] with S={}; found {:?} {}",
1072 self.model_width,
1073 sequence_length,
1074 input.shape(),
1075 input.dtype().token(),
1076 )));
1077 }
1078 Ok(rows / sequence_length)
1079 }
1080
1081 fn feature_map(x: &Matrix) -> Result<Matrix> {
1086 core_matrix::add(
1087 &core_matrix::exp(&core_matrix::clamp_max(x, 0.0)?)?,
1088 &super::super::matrix::relu(x)?,
1089 )
1090 }
1091
1092 fn forward_causal(&self, input: &Matrix) -> Result<Matrix> {
1106 let batch = self.geometry(input)?;
1107 let sequence_length = self.sequence_length.get();
1108 let head_dim = self.model_width / self.num_heads;
1109
1110 if head_dim <= 64 {
1111 let q = split_heads(
1112 &self.query_projection.forward(input)?,
1113 batch,
1114 sequence_length,
1115 self.num_heads,
1116 )?;
1117 let k = split_heads(
1118 &self.key_projection.forward(input)?,
1119 batch,
1120 sequence_length,
1121 self.num_heads,
1122 )?;
1123 let v = split_heads(
1124 &self.value_projection.forward(input)?,
1125 batch,
1126 sequence_length,
1127 self.num_heads,
1128 )?;
1129 let context = super::super::matrix::causal_linear_attention(&q, &k, &v, 1.0e-6)?;
1130 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
1131 return self.output_projection.forward(&context);
1132 }
1133
1134 let phi_q = Self::feature_map(&self.query_projection.forward(input)?)?;
1135 let phi_k = Self::feature_map(&self.key_projection.forward(input)?)?;
1136 let phi_v = self.value_projection.forward(input)?;
1137
1138 let phi_q = split_heads(&phi_q, batch, sequence_length, self.num_heads)?;
1140 let phi_k = split_heads(&phi_k, batch, sequence_length, self.num_heads)?;
1141 let phi_v = split_heads(&phi_v, batch, sequence_length, self.num_heads)?;
1142
1143 let batch_heads = batch
1144 .checked_mul(self.num_heads)
1145 .ok_or_else(|| Error::invalid_argument("linear attention batch-head count overflows"))?;
1146
1147 let kv_count = batch_heads
1149 .checked_mul(head_dim)
1150 .and_then(|n| n.checked_mul(head_dim))
1151 .ok_or_else(|| Error::invalid_argument("linear attention kv size overflows"))?;
1152 let ksum_count = batch_heads
1153 .checked_mul(head_dim)
1154 .ok_or_else(|| Error::invalid_argument("linear attention k_sum size overflows"))?;
1155 let kv = Matrix::allocate(
1156 input.runtime(),
1157 vec![batch_heads, head_dim, head_dim],
1158 kv_count,
1159 DType::F32,
1160 )?;
1161 kv.write_values(&vec![0.0_f32; kv_count])?;
1162 let k_sum = Matrix::allocate(
1163 input.runtime(),
1164 vec![batch_heads, head_dim, 1],
1165 ksum_count,
1166 DType::F32,
1167 )?;
1168 k_sum.write_values(&vec![0.0_f32; ksum_count])?;
1169
1170 let mut kv = kv;
1172 let mut k_sum = k_sum;
1173 let mut steps: Vec<Matrix> = Vec::with_capacity(sequence_length);
1174 for t in 0..sequence_length {
1175 let t_i64 = t as i64;
1176 let phi_q_t = core_matrix::slice(&phi_q, 1, t_i64, t_i64 + 1)?;
1178 let phi_k_t = core_matrix::slice(&phi_k, 1, t_i64, t_i64 + 1)?;
1179 let phi_v_t = core_matrix::slice(&phi_v, 1, t_i64, t_i64 + 1)?;
1180
1181 kv = core_matrix::add(&kv, &bmm_tn(&phi_k_t, &phi_v_t)?)?;
1183
1184 let phi_k_t_col = phi_k_t.reshape([batch_heads, head_dim, 1])?;
1187 k_sum = core_matrix::add(&k_sum, &phi_k_t_col)?;
1188
1189 let ctx_t = bmm(&phi_q_t, &kv)?;
1191
1192 let denom_t = bmm(&phi_q_t, &k_sum)?;
1194
1195 steps.push(core_matrix::div(
1197 &ctx_t,
1198 &core_matrix::clamp_min(&denom_t, 1.0e-6)?,
1199 )?);
1200 }
1201
1202 let context = core_matrix::concat(&steps, 1)?;
1204 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
1205 self.output_projection.forward(&context)
1206 }
1207
1208 fn forward_bidirectional(&self, input: &Matrix) -> Result<Matrix> {
1219 let batch = self.geometry(input)?;
1220 let sequence_length = self.sequence_length.get();
1221 let head_dim = self.model_width / self.num_heads;
1222
1223 let phi_q = Self::feature_map(&self.query_projection.forward(input)?)?;
1224 let phi_k = Self::feature_map(&self.key_projection.forward(input)?)?;
1225 let phi_v = self.value_projection.forward(input)?;
1226
1227 let phi_q = split_heads(&phi_q, batch, sequence_length, self.num_heads)?;
1229 let phi_k = split_heads(&phi_k, batch, sequence_length, self.num_heads)?;
1230 let phi_v = split_heads(&phi_v, batch, sequence_length, self.num_heads)?;
1231
1232 let batch_heads = batch
1233 .checked_mul(self.num_heads)
1234 .ok_or_else(|| Error::invalid_argument("linear attention batch-head count overflows"))?;
1235
1236 let kv = bmm_tn(&phi_k, &phi_v)?;
1238
1239 let context_raw = bmm(&phi_q, &kv)?;
1241
1242 let k_sum = core_matrix::sum(&phi_k, 1)?;
1244
1245 let k_sum_col = k_sum.reshape([batch_heads, head_dim, 1])?;
1247 let denom = bmm(&phi_q, &k_sum_col)?;
1248
1249 let context = core_matrix::div(&context_raw, &core_matrix::clamp_min(&denom, 1.0e-6)?)?;
1251
1252 let context = merge_heads(&context, batch, sequence_length, self.num_heads)?;
1253 self.output_projection.forward(&context)
1254 }
1255
1256 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
1268 match self.mode.get() {
1269 LinearAttentionMode::Causal => self.forward_causal(input),
1270 LinearAttentionMode::Bidirectional => self.forward_bidirectional(input),
1271 }
1272 }
1273
1274 pub fn set_mode(&self, mode: LinearAttentionMode) {
1276 self.mode.set(mode);
1277 }
1278
1279 pub fn mode(&self) -> LinearAttentionMode {
1281 self.mode.get()
1282 }
1283
1284 pub const fn model_width(&self) -> usize {
1285 self.model_width
1286 }
1287 pub const fn num_heads(&self) -> usize {
1288 self.num_heads
1289 }
1290 pub fn sequence_length(&self) -> usize {
1291 self.sequence_length.get()
1292 }
1293
1294 pub fn set_sequence_length(&self, sequence_length: usize) -> Result<()> {
1300 if sequence_length == 0 {
1301 return Err(Error::invalid_argument(
1302 "linear attention sequence length must be nonzero",
1303 ));
1304 }
1305 self.sequence_length.set(sequence_length);
1306 Ok(())
1307 }
1308
1309 pub fn has_bias(&self) -> bool {
1311 self.query_projection.has_bias()
1312 }
1313}
1314
1315impl Module for CausalLinearAttention {
1316 fn forward(&self, input: &Matrix) -> Result<Matrix> {
1317 CausalLinearAttention::forward(self, input)
1318 }
1319 fn registry(&self) -> &ModuleRegistry {
1320 &self.registry
1321 }
1322}