Skip to main content

oa/ml/nn/
attention.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_attention.json
3// generator_version=8; schema_sha256=e93ea64ec964d0ba615d8a86d752a4340dafb6afb03323d3bd4568fc6454e8b5
4
5use 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// OA donor: oacpp/source/cpp/lib/oa/ml/nn/attention/multiheadattention/multiHeadAttention.cpp
23// Adaptation: Complete generation of established Rust composition, explicit policy enums, replay-safe dropout and geometry-keyed mask cache; adds Katharopoulos linear attention as CausalLinearAttention with ELU+1 feature map — bidirectional composition and fused bounded-state causal forward/adjoints share projections with MultiHeadAttention
24/// Execution policy for scaled dot-product attention.
25///
26/// `Auto` selects only a route proven by device-specific performance evidence.
27/// It currently preserves the compositional [`AttentionBackend::Standard`]
28/// provider on every device.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum AttentionBackend {
31	/// Use the internally proven provider policy.
32	#[default]
33	Auto,
34	/// Use BMM-NT, scaled/masked Softmax, and BMM.
35	Standard,
36	/// Explicitly request the fused causal Flash provider.
37	Flash,
38	/// Katharopoulos kernel-trick linear attention with bounded scan state,
39	/// independent of sequence length.  Bidirectional uses a single global KV
40	/// accumulation; causal uses a per-position lower-triangular KV scan.
41	Linear,
42}
43
44/// Token-visibility contract for self-attention.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub enum AttentionMode {
47	/// A query may observe only itself and preceding tokens.
48	#[default]
49	Causal,
50	/// Every query may observe every token in its sequence.
51	Bidirectional,
52}
53
54/// Multi-head self-attention over packed `[B*S, D]` values.
55pub 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
82/// Caller-owned incremental-decode key/value cache for `MultiHeadAttention`.
83///
84/// Each [`MultiHeadAttention::step`] call appends one `[B*H, 1, D/H]` key/value pair and
85/// attends over every cached position. The cache binds to the constructing
86/// module instance; presenting it to another attention module fails closed.
87pub 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	/// Return the fixed batch size accepted by this cache.
97	pub const fn batch_size(&self) -> usize {
98		self.batch_size
99	}
100
101	/// Return the number of cached positions.
102	pub const fn len(&self) -> usize {
103		self.position
104	}
105
106	/// Return whether no positions are cached.
107	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	/// Construct four biased projections with causal visibility and automatic
130	/// backend policy.
131	///
132	/// # Errors
133	///
134	/// Returns an error unless dimensions are positive and `model_width` is
135	/// divisible by `num_heads`, or child construction/registration fails.
136	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	/// Construct four projections with explicit optional bias.
173	///
174	/// # Errors
175	///
176	/// Returns an error unless dimensions are positive and `model_width` is
177	/// divisible by `num_heads`, or child construction/registration fails.
178	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	/// Construct attention with explicit dropout and projection-bias policy.
198	///
199	/// Dropout is applied to attention probabilities only while the module is in
200	/// training mode. Its Philox stream is derived from `seed` and advances on
201	/// captured-program replay through the ordinary Matrix Dropout contract.
202	///
203	/// # Errors
204	///
205	/// Returns an error unless dimensions are valid, `dropout_probability` is
206	/// finite and in `[0, 1)`, or child construction/registration fails.
207	#[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	/// Construct grouped-query attention with explicit key/value head count.
250	///
251	/// `num_kv_heads` must divide `num_heads`; `num_kv_heads == 1` is
252	/// multi-query attention and `num_kv_heads == num_heads` degenerates to
253	/// ordinary multi-head attention. Every group of
254	/// `num_heads / num_kv_heads` query heads shares one key/value head, so
255	/// the key and value projections own `num_kv_heads * (model_width /
256	/// num_heads)` output columns each.
257	///
258	/// # Errors
259	///
260	/// Returns an error under the same contract as
261	/// [`Self::new_with_seed_and_options_on`], or when `num_kv_heads` is
262	/// zero or does not divide `num_heads`.
263	#[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	/// Split a projected key or value into `[B*KV, S, D/H]` heads and
383	/// repeat each head over its query-head group, yielding `[B*H, S, D/H]`.
384	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	/// Repeat `[B*KV, T, D/H]` cached heads over their query-head group.
393	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	/// Apply self-attention using the configured visibility and provider policy.
523	///
524	/// `Auto` deliberately uses the standard provider until a device-specific
525	/// benchmark qualifies another route. Explicit Flash fails closed unless the
526	/// operation is causal F32 with `S <= 1024`.
527	///
528	/// # Errors
529	///
530	/// Returns an error for invalid input geometry, an ineligible explicit Flash
531	/// request, or failed operation recording.
532	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	/// Apply standard bidirectional attention with an additive `[B*H*S, S]` mask.
557	///
558	/// The arbitrary mask route is never silently sent to Flash.
559	///
560	/// # Errors
561	///
562	/// Returns an error when Flash is explicitly selected, mask/input geometry is
563	/// invalid, or operation recording fails.
564	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	/// Apply cross-attention: queries from `input` attend over keys and
574	/// values projected from `key_value_source`.
575	///
576	/// `input` is F32 `[B*S_q, D]` under the configured query sequence
577	/// length; `key_value_source` is F32 `[B*S_kv, D]` for the same batch
578	/// and model width with any positive source length. Visibility is
579	/// bidirectional — every query observes every source position — so
580	/// [`Self::mode`] does not apply. The composed score/softmax/context
581	/// route is used because query and key lengths may differ; it records
582	/// ordinary adjoints and admits training-mode attention dropout.
583	///
584	/// # Errors
585	///
586	/// Returns an error when Flash is explicitly selected, either input's
587	/// geometry or dtype is invalid, the runtimes differ, or operation
588	/// recording fails.
589	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	/// Apply cross-attention with an explicit additive `[B*H*S_q, S_kv]` mask.
594	///
595	/// # Errors
596	///
597	/// Returns an error under the same contract as [`Self::forward_kv`], or
598	/// when the mask does not match the flattened cross-attention score
599	/// geometry.
600	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	/// Allocate an empty incremental-decode cache owned by this module.
685	///
686	/// The cache fixes the accepted batch size and holds one `[B*H, T, D/H]`
687	/// key/value pair per [`Self::step`] call.
688	///
689	/// # Errors
690	///
691	/// Returns an error when `batch_size` is zero.
692	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	/// Advance one autoregressive position against `cache`.
708	///
709	/// `input` must be F32 `[batch, model_width]` for the cache's batch size.
710	/// The projected key and value append to the cache, then the query attends
711	/// over every cached position — causality is structural, so no mask is
712	/// needed. This is an inference-only operation: cache differentiation is
713	/// not admitted, and calling it while a [`crate::ml::GradientTape`] is
714	/// active returns an error.
715	///
716	/// # Errors
717	///
718	/// Returns an error for an active gradient tape, a cache owned by another
719	/// module, mismatched batch/shape/dtype, or failed recording.
720	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	/// Select the requested attention provider policy.
774	pub fn set_backend(&self, backend: AttentionBackend) {
775		self.backend.set(backend);
776	}
777
778	/// Return the requested attention provider policy.
779	pub fn backend(&self) -> AttentionBackend {
780		self.backend.get()
781	}
782
783	/// Return the provider used by the most recent successful forward call.
784	pub fn last_backend(&self) -> AttentionBackend {
785		self.last_backend.get()
786	}
787
788	/// Select causal or bidirectional token visibility.
789	pub fn set_mode(&self, mode: AttentionMode) {
790		self.mode.set(mode);
791	}
792
793	/// Return the configured token-visibility contract.
794	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	/// Return the key/value head count each query-head group shares.
806	///
807	/// Equals [`Self::num_heads`] unless the module was constructed through
808	/// [`Self::new_with_seed_and_options_grouped_on`]; `1` is multi-query
809	/// attention.
810	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	/// Change runtime sequence geometry without rebuilding projection weights.
818	///
819	/// # Errors
820	///
821	/// Returns an error when `sequence_length` is zero.
822	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	/// Return whether all four projections own trainable biases.
835	pub fn has_bias(&self) -> bool {
836		self.query_projection.has_bias()
837	}
838
839	/// Return the probability dropped from attention weights during training.
840	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// ── Linear attention ──────────────────────────────────────────────────────────
855
856/// Token-visibility contract for linear attention.
857#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
858pub enum LinearAttentionMode {
859	/// Each position attends only to itself and earlier positions.
860	///
861	/// Implemented as a cumulative-KV prefix scan: at each step `t` the
862	/// running `[B*H, d, d]` accumulator `kv_t = Σ_{i≤t} phi(k_i)ᵀ phi(v_i)`
863	/// is queried by `phi(q_t)`.  No S×S matrix is ever materialised.
864	/// Bounded fused scan state; projections and adjoints scale with S.
865	#[default]
866	Causal,
867	/// Every position attends to every other position.
868	///
869	/// Uses the true O(B·H·d_head²) global KV accumulation.
870	Bidirectional,
871}
872
873/// Multi-head linear attention over packed `[B*S, D]` values.
874///
875/// Uses the Katharopoulos (2020) ELU+1 kernel rather than softmax.
876/// Causal heads up to 64 use fused forward and recomputed prefix/suffix
877/// adjoints. Saved projections/context scale as O(B*H*S*d), with bounded
878/// O(d²) scan state per head. Larger heads retain the compositional path,
879/// whose training tape saves O(B*H*S*d²) prefixes. Bidirectional mode uses
880/// the global KV composition. Standard attention stores S² probabilities;
881/// Flash recomputes them and does not store a global S² score matrix.
882///
883/// ## Parameter layout
884///
885/// Four biased projections (`q_proj`, `k_proj`, `v_proj`, `out_proj`)
886/// with the same names and seed stride as [`MultiHeadAttention`], so checkpoints are
887/// transferable between the two modules.
888pub 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	/// Construct four biased projections with causal visibility.
918	///
919	/// # Errors
920	///
921	/// Returns an error unless dimensions are positive, `model_width` is
922	/// divisible by `num_heads`, or child construction/registration fails.
923	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	/// Construct four projections with explicit optional bias.
952	///
953	/// # Errors
954	///
955	/// Returns an error unless dimensions are positive, `model_width` is
956	/// divisible by `num_heads`, or child construction/registration fails.
957	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	/// Construct with explicit bias policy; initial mode is
987	/// [`LinearAttentionMode::Causal`].
988	///
989	/// # Errors
990	///
991	/// Returns an error unless dimensions are positive, `model_width` is
992	/// divisible by `num_heads`, or child construction/registration fails.
993	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	// ── forward paths ─────────────────────────────────────────────────────────
1057
1058	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	/// ELU(x, α=1) + 1 — the Katharopoulos feature map phi(x).
1082	///
1083	/// Evaluates the negative branch directly to avoid ELU + 1 cancellation.
1084	/// Extreme negative inputs may still underflow; normalization has a floor.
1085	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	/// Causal linear attention: cumulative-KV prefix scan.
1093	///
1094	/// For each position `t` in `0..S`:
1095	/// ```text
1096	/// kv_t    += phi(K)[t]ᵀ ⊗ V[t]     [B*H, d, d]  running accumulator
1097	/// k_sum_t += phi(K)[t]                   [B*H, 1, d]  running normaliser
1098	/// ctx_t    = phi(Q)[t] @ kv_t            [B*H, 1, d]
1099	/// denom_t  = phi(Q)[t] @ k_sum_tᵀ       [B*H, 1, 1]
1100	/// out_t    = ctx_t / denom_t             [B*H, 1, d]
1101	/// ```
1102	/// `out_t` is concatenated into `[B*H, S, d]`.  No S×S matrix is ever
1103	/// materialised. The compositional fallback retains prefixes for reverse
1104	/// mode. Heads up to 64 use the fused bounded-state Matrix provider.
1105	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		// [B*H, S, d_head]
1139		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		// Zero accumulators: kv [B*H, d, d], k_sum [B*H, d, 1].
1148		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		// Prefix scan over sequence positions.
1171		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			// phi_q_t, phi_k_t, phi_v_t : [B*H, 1, d_head]
1177			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 += phi_k_t^T @ phi_v_t  — [B*H, d, d]
1182			kv = core_matrix::add(&kv, &bmm_tn(&phi_k_t, &phi_v_t)?)?;
1183
1184			// k_sum += phi_k_t^T  — [B*H, d, 1]
1185			// phi_k_t is [B*H, 1, d]; reshape to [B*H, d, 1] for column accumulation.
1186			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			// ctx_t = phi_q_t @ kv  — [B*H, 1, d]
1190			let ctx_t = bmm(&phi_q_t, &kv)?;
1191
1192			// denom_t = phi_q_t @ k_sum  — [B*H, 1, 1]
1193			let denom_t = bmm(&phi_q_t, &k_sum)?;
1194
1195			// out_t = ctx_t / denom_t  — [B*H, 1, d]
1196			steps.push(core_matrix::div(
1197				&ctx_t,
1198				&core_matrix::clamp_min(&denom_t, 1.0e-6)?,
1199			)?);
1200		}
1201
1202		// Concatenate [B*H, 1, d] steps into [B*H, S, d].
1203		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	/// Bidirectional linear attention: true O(B·H·d_head²) workspace.
1209	///
1210	/// Computes:
1211	/// ```text
1212	/// kv          = phi(K)ᵀ @ phi(V)          [B*H, d, d]
1213	/// context_raw = phi(Q) @ kv                [B*H, S, d]
1214	/// k_sum       = sum_seq(phi(K))            [B*H, 1, d]
1215	/// denom       = phi(Q) @ k_sum^T           [B*H, S, 1]
1216	/// context     = context_raw / denom        [B*H, S, d]
1217	/// ```
1218	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		// [B*H, S, d_head]
1228		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		// KV accumulation: phi(K)^T @ phi(V) → [B*H, d_head, d_head].
1237		let kv = bmm_tn(&phi_k, &phi_v)?;
1238
1239		// Unnormalised context: phi(Q) @ kv → [B*H, S, d_head].
1240		let context_raw = bmm(&phi_q, &kv)?;
1241
1242		// Key column sum: sum over sequence axis → [B*H, 1, d_head] (keepdim).
1243		let k_sum = core_matrix::sum(&phi_k, 1)?;
1244
1245		// Denominator: phi(Q) @ k_sum^T → [B*H, S, 1].
1246		let k_sum_col = k_sum.reshape([batch_heads, head_dim, 1])?;
1247		let denom = bmm(&phi_q, &k_sum_col)?;
1248
1249		// Normalise: [B*H, S, d_head] / [B*H, S, 1] (broadcast).
1250		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	// ── public API ────────────────────────────────────────────────────────────
1257
1258	/// Apply linear attention using the configured visibility policy.
1259	///
1260	/// Accepts packed F32 `[B*S, D]` input where `B` is the batch size and `S`
1261	/// is the configured sequence length.
1262	///
1263	/// # Errors
1264	///
1265	/// Returns an error for invalid input geometry or failed operation
1266	/// recording.
1267	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	/// Select causal or bidirectional visibility.
1275	pub fn set_mode(&self, mode: LinearAttentionMode) {
1276		self.mode.set(mode);
1277	}
1278
1279	/// Return the configured visibility contract.
1280	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	/// Change runtime sequence geometry without rebuilding projection weights.
1295	///
1296	/// # Errors
1297	///
1298	/// Returns an error when `sequence_length` is zero.
1299	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	/// Return whether all four projections own trainable biases.
1310	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}