1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Multi-head latent attention module using the Hyper projection layout."""
16
17from __future__ import annotations
18
19from collections.abc import Callable, Sequence
20from dataclasses import dataclass
21import math
22from types import SimpleNamespace
23from typing import Any
24
25# This package provides PyTorch-specific high-performance modules.
26import torch
27from torch import nn
28from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter
29
30from hyper_parallel.components import functional
31from hyper_parallel.components.checkpoint import ConcatenateWithSections
32from hyper_parallel.components.functional.npu_fusion_attention import npu_fusion_attention_forward
33from hyper_parallel.components.modules.common.rms_norm import RMSNorm
34
35
36
37def prepare_mla_attention_mask(
38 attention_mask: torch.Tensor | None,
39 query_length: int,
40 key_length: int,
41) -> torch.Tensor | None:
42 """Disambiguate MLA Q/K masks before calling a shared attention interface.
43
44 Args:
45 attention_mask: Optional mask. A two-dimensional Q/K matrix takes
46 precedence over padding in MLA, including when batch equals query length.
47 query_length: Number of query tokens visible to the attention interface.
48 key_length: Number of key tokens visible to the attention interface.
49
50 Returns:
51 A broadcastable four-dimensional view for a Q/K matrix. Other inputs
52 pass through unchanged, preserving padding and compressed causal paths.
53 """
54 if (attention_mask is not None and attention_mask.ndim == 2
55 and attention_mask.shape == (query_length, key_length)):
56 # Shared FA interprets 2D masks as batch padding; MLA also accepts Q/K matrices.
57 return attention_mask[None, None, :, :]
58 return attention_mask
59
60
61def apply_mla_rope(
62 tensor: torch.Tensor,
63 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
64 *,
65 interleaved: bool = False,
66) -> torch.Tensor:
67 """Rotate one BSND tensor so Q and shared K can be scheduled independently.
68
69 Args:
70 tensor: Query or unexpanded shared key, with rotary features in the last dimension.
71 position_embeddings: Cosine/sine tables in SD or BSD, or None for an identity operation.
72 interleaved: Whether the input stores real/imaginary features in adjacent pairs.
73
74 Returns:
75 Rotated BSND features. Interleaved inputs become the half-band order consumed by MLA.
76 No extra contiguous conversion is imposed on the caller's layout.
77 """
78 if position_embeddings is None:
79 return tensor
80 cos, sin = (part.to(tensor.dtype) for part in position_embeddings)
81 if cos.ndim == 2:
82 cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
83 if interleaved:
84 cos, sin = (part[..., :tensor.shape[-1] // 2].repeat_interleave(2, dim=-1)
85 for part in (cos, sin))
86 cos, sin = (part.expand(tensor.shape[0], -1, -1).transpose(0, 1) for part in (cos, sin))
87 rotated = functional.apply_rotary_pos_emb_single(
88 tensor.transpose(0, 1), cos, sin,
89 rotary_interleaved=interleaved, use_fused_rotary_pos_emb=True,
90 )
91 if interleaved:
92 # V3 consumes real/imaginary half-bands; the kernel returns adjacent pairs.
93 rotated = rotated.permute(1, 2, 0, 3)
94 return rotated.unflatten(-1, (-1, 2)).transpose(-1, -2).flatten(-2).transpose(1, 2)
95 return rotated.transpose(0, 1)
96
97
98@dataclass(frozen=True)
99class MLALatentInputs:
100 """Normalized token-local features before query/KV head expansion."""
101
102 query_latent: torch.Tensor
103 kv_latent: torch.Tensor
104 key_rope: torch.Tensor
105
106
107@dataclass(frozen=True)
108class MLAInputs:
109 """Ready BNSD operands and invocation-local attention/output metadata."""
110
111 query: torch.Tensor
112 key: torch.Tensor
113 value: torch.Tensor
114 attention_mask: torch.Tensor | None
115 options: dict[str, Any]
116 output_state: Any = None
117
118
119class MultiLatentAttentionModule(nn.Module):
120 """Transformers-compatible MLA using a fused latent projection.
121
122 ``q_a_proj`` and ``kv_a_proj_with_mqa`` are fused into ``linear_qkv``.
123 Unchanged child modules retain their source names and checkpoint layout.
124 Construction only creates the target structure; ``make_transforms``
125 declares the checkpoint conversion.
126 """
127
128 def __init__(
129 self,
130 *,
131 module: nn.Module | None = None,
132 config: Any = None,
133 attention_interface: Callable[..., tuple[torch.Tensor, torch.Tensor | None]] = (
134 npu_fusion_attention_forward
135 ),
136 ) -> None:
137 """Construct MLA projections and attention math from a source module or config.
138
139 Args:
140 module: Optional source with Q-LoRA, KV-LoRA and managed projection children.
141 An already-fused MLA reuses all child modules and their Parameters.
142 config: Direct construction dimensions and attention options; exclusive with module.
143 Uses the DeepSeek parameter layout: optional down/output bias, bias-free up projections.
144 attention_interface: Local FA implementation returning BSND output and optional weights.
145
146 Note:
147 Source conversion keeps the existing checkpoint transforms. Direct construction
148 initializes native Linear weights and unit RMSNorm scales, without creating an HF model.
149 """
150 super().__init__()
151 self.attention_interface = attention_interface
152 self._config_initialization = module is None or getattr(module, "_config_initialization", False)
153 if module is None:
154 if config is None:
155 raise ValueError("MLA construction requires config or a source module")
156 self._initialize_config(config)
157 return
158 if config is not None:
159 raise ValueError("MLA construction accepts config or module, not both")
160 self._initialize_source(module)
161
162 def _initialize_source(self, module: nn.Module) -> None:
163 """Read source math options and reuse its managed projection children."""
164 self._source_is_fused = hasattr(module, "linear_qkv")
165 required = (
166 "q_a_layernorm",
167 "q_b_proj",
168 "kv_a_layernorm",
169 "kv_b_proj",
170 "o_proj",
171 )
172 required += ("linear_qkv",) if self._source_is_fused else ("q_a_proj", "kv_a_proj_with_mqa")
173 missing = [name for name in required if not hasattr(module, name)]
174 if missing:
175 raise TypeError(f"MultiLatentAttention source module is missing: {missing}")
176
177 config = module.config
178 self.config = config
179 self.layer_idx = getattr(module, "layer_idx", getattr(module, "layer_number", None))
180 self.num_heads = getattr(module, "num_heads", config.num_attention_heads)
181 self.num_key_value_heads = getattr(
182 module,
183 "num_key_value_heads",
184 getattr(config, "num_key_value_heads", self.num_heads),
185 )
186 if self.num_key_value_heads is None:
187 self.num_key_value_heads = self.num_heads
188 self.num_key_value_groups = self.num_heads // self.num_key_value_heads
189 self.q_lora_rank = getattr(module, "q_lora_rank", config.q_lora_rank)
190 self.kv_lora_rank = getattr(module, "kv_lora_rank", config.kv_lora_rank)
191 if self.q_lora_rank is None:
192 raise ValueError("MultiLatentAttention requires the Q-LoRA projection path")
193 self.qk_rope_head_dim = getattr(module, "qk_rope_head_dim", config.qk_rope_head_dim)
194 self.qk_nope_head_dim = getattr(module, "qk_nope_head_dim", config.qk_nope_head_dim)
195 self.v_head_dim = getattr(module, "v_head_dim", config.v_head_dim)
196 self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
197 self.scaling = getattr(module, "scaling", self.qk_head_dim**-0.5)
198 self.attention_dropout = getattr(module, "attention_dropout", 0.0)
199 if isinstance(self.attention_dropout, nn.Dropout):
200 self.attention_dropout = self.attention_dropout.p
201 self.is_causal = getattr(module, "is_causal", True)
202 self.sliding_window = getattr(
203 module, "sliding_window", getattr(config, "sliding_window", None)
204 )
205 self.rotary_interleaved = bool(
206 getattr(module, "rotary_interleaved", getattr(config, "rope_interleave", False))
207 )
208 # These source variants change attention math; ignoring the flags would
209 # silently replace them with ordinary MLA. Keep only construction guards.
210 if getattr(module, "param_sink_number", 0) > 0:
211 raise ValueError(
212 "MultiLatentAttention only implements standard MLA; parameter-sink attention "
213 "must use the sink high-performance interfaces."
214 )
215 if getattr(module, "use_mome", False):
216 raise NotImplementedError(
217 "MultiLatentAttention only implements standard MLA; MOME must use the "
218 "aggregate_hidden high-performance path."
219 )
220
221 self._initialize_latent_projection(module)
222
223 self.q_a_layernorm = module.q_a_layernorm
224 self.kv_a_layernorm = module.kv_a_layernorm
225 self.q_b_proj = module.q_b_proj
226 self.kv_b_proj = module.kv_b_proj
227 self.o_proj = module.o_proj
228
229 self.train(module.training)
230
231 def _initialize_latent_projection(self, module: nn.Module) -> None:
232 """Fuse compatible down projections or retain an already-fused source."""
233 self._q_latent_output_size = self.q_lora_rank
234 self._kv_latent_output_size = self.kv_lora_rank + self.qk_rope_head_dim
235 if self._source_is_fused:
236 self.linear_qkv = module.linear_qkv
237 self.attention_interface = module.attention_interface
238 else:
239 q_a = module.q_a_proj
240 kv_a = module.kv_a_proj_with_mqa
241 self._q_latent_output_size = q_a.out_features
242 self._kv_latent_output_size = kv_a.out_features
243 can_fuse = (
244 q_a.in_features == kv_a.in_features
245 and q_a.weight.requires_grad == kv_a.weight.requires_grad
246 and (q_a.bias is None) == (kv_a.bias is None)
247 and (q_a.bias is None or q_a.bias.requires_grad == kv_a.bias.requires_grad)
248 )
249 if not can_fuse:
250 raise ValueError(
251 "Q and KV latent projections cannot be represented by one fused projection"
252 )
253 self.linear_qkv = nn.Linear(
254 q_a.in_features,
255 q_a.out_features + kv_a.out_features,
256 bias=q_a.bias is not None,
257 device=q_a.weight.device,
258 dtype=q_a.weight.dtype,
259 )
260 self.linear_qkv.weight.requires_grad_(q_a.weight.requires_grad)
261 if q_a.bias is not None:
262 self.linear_qkv.bias.requires_grad_(q_a.bias.requires_grad)
263
264 def _initialize_config(self, config: Any) -> None:
265 """Construct the same parameter tree directly, without an intermediate HF model."""
266 self.config = config
267 self.layer_idx = getattr(config, "layer_idx", None)
268 dimensions = {
269 "num_heads": config.num_attention_heads,
270 "q_lora_rank": config.q_lora_rank,
271 "kv_lora_rank": config.kv_lora_rank,
272 "qk_nope_head_dim": config.qk_nope_head_dim,
273 "qk_rope_head_dim": config.qk_rope_head_dim,
274 "v_head_dim": config.v_head_dim,
275 }
276 if any(not isinstance(value, int) or isinstance(value, bool) or value <= 0 for value in dimensions.values()):
277 raise ValueError("MLA dimensions must be positive integers, including q_lora_rank")
278 if dimensions["qk_rope_head_dim"] % 2:
279 raise ValueError("MLA rotary dimension must be even")
280 for name, value in dimensions.items():
281 setattr(self, name, value)
282 self.num_key_value_heads = self.num_heads
283 self.num_key_value_groups = 1
284 self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
285 self.scaling = self.qk_head_dim ** -0.5
286 self.scaling = self._config_scaling(config, self.scaling)
287 self.attention_dropout = getattr(config, "attention_dropout", 0.0)
288 self.is_causal = getattr(config, "is_causal", True)
289 self.sliding_window = getattr(config, "sliding_window", None)
290 self.rotary_interleaved = bool(getattr(config, "rotary_interleaved", getattr(config, "rope_interleave", False)))
291 if getattr(config, "use_mome", False) or getattr(config, "param_sink_number", 0) > 0:
292 raise ValueError("MLA config construction does not support MOME or parameter-sink attention")
293 self._source_is_fused = True
294 self._q_latent_output_size = self.q_lora_rank
295 self._kv_latent_output_size = self.kv_lora_rank + self.qk_rope_head_dim
296 hidden_size = config.hidden_size
297 if not isinstance(hidden_size, int) or isinstance(hidden_size, bool) or hidden_size <= 0:
298 raise ValueError("MLA hidden_size must be a positive integer")
299 dtype = getattr(config, "dtype", None)
300 bias = getattr(config, "attention_bias", False)
301 self.linear_qkv = nn.Linear(
302 hidden_size, self._q_latent_output_size + self._kv_latent_output_size, bias=bias, dtype=dtype,
303 )
304 eps = getattr(config, "rms_norm_eps", 1e-6)
305 self.q_a_layernorm = RMSNorm(
306 config=SimpleNamespace(hidden_size=self.q_lora_rank, eps=eps), use_fused_ops=True,
307 ).to(dtype=dtype)
308 self.kv_a_layernorm = RMSNorm(
309 config=SimpleNamespace(hidden_size=self.kv_lora_rank, eps=eps), use_fused_ops=True,
310 ).to(dtype=dtype)
311 self.q_b_proj = nn.Linear(self.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False, dtype=dtype)
312 self.kv_b_proj = nn.Linear(
313 self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False, dtype=dtype,
314 )
315 self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, hidden_size, bias=bias, dtype=dtype)
316
317 @staticmethod
318 def _config_scaling(config: Any, default: float) -> float:
319 """Keep the source-compatible YaRN factor and explicit scaling override."""
320 rope = getattr(config, "rope_parameters", None) or getattr(config, "rope_scaling", None) or {}
321 if rope.get("rope_type", rope.get("type", "default")) != "default" and rope.get("mscale_all_dim", 0):
322 factor = rope["factor"]
323 mscale = 1.0 if factor <= 1 else 0.1 * rope["mscale_all_dim"] * math.log(factor) + 1.0
324 default *= mscale * mscale
325 return getattr(config, "scaling", default)
326
327 def reset_parameters(self) -> None:
328 """Initialize direct-config parameters without overriding a source model's initializer."""
329 # HF initialization already visits converted Linear/Norm children. The replacement
330 # framework also invokes this method after it, so source conversions must not reset them again.
331 if not self._config_initialization:
332 return
333 for projection in (self.linear_qkv, self.q_b_proj, self.kv_b_proj, self.o_proj):
334 projection.reset_parameters()
335 nn.init.ones_(self.q_a_layernorm.weight)
336 nn.init.ones_(self.kv_a_layernorm.weight)
337
338 def make_transforms(self) -> list[WeightConverter]:
339 """Describe reversible source-checkpoint to high-performance conversion."""
340 if self._source_is_fused:
341 return []
342 suffixes = ("weight", "bias") if self.linear_qkv.bias is not None else ("weight",)
343 sections = (self._q_latent_output_size, self._kv_latent_output_size)
344 return [
345 WeightConverter(
346 source_patterns=[f"q_a_proj.{suffix}", f"kv_a_proj_with_mqa.{suffix}"],
347 target_patterns=f"linear_qkv.{suffix}",
348 operations=[ConcatenateWithSections(sections=sections, dim=0)],
349 )
350 for suffix in suffixes
351 ]
352
353 def project_latent_inputs(
354 self, hidden_states: torch.Tensor,
355 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
356 """Compute shared latent inputs before head expansion.
357
358 Args:
359 hidden_states: Input tokens with shape [batch, sequence, hidden].
360
361 Returns:
362 Normalized query and KV latents, and the unrotated shared RoPE key.
363 """
364 latent_states = self.linear_qkv(hidden_states)
365 query_latent, kv_nope, key_rope = torch.split(
366 latent_states,
367 (self.q_lora_rank, self.kv_lora_rank, self.qk_rope_head_dim),
368 dim=-1,
369 )
370 return self.q_a_layernorm(query_latent), self.kv_a_layernorm(kv_nope), key_rope
371
372 def apply_position(
373 self, tensor: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
374 *, interleaved: bool | None = None,
375 ) -> torch.Tensor:
376 """Rotate query/shared-key features before head replication.
377
378 Args:
379 tensor: Features in BSND; shared K has a singleton head dimension.
380 position_embeddings: Local token positions in SD or BSD.
381 interleaved: Optional input-order override; defaults to the module's source convention.
382
383 Returns:
384 BSND features in the MLA key/query feature order.
385 """
386 return apply_mla_rope(
387 tensor, position_embeddings,
388 interleaved=self.rotary_interleaved if interleaved is None else interleaved,
389 )
390
391 def project_query(
392 self, latent: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
393 *, heads: int | None = None, rotary_fn: Callable | None = None,
394 ) -> torch.Tensor:
395 """Expand query heads without changing token ownership.
396
397 Args:
398 latent: Normalized query latent in BSR.
399 position_embeddings: Local token cosine/sine tables, or None.
400 heads: Number of heads produced by the query projection.
401 rotary_fn: Optional legacy local callback; defaults to this algorithm's position method.
402
403 Returns:
404 BNSD queries. The NoPE identity path preserves the projection view.
405 """
406 heads = self.num_heads if heads is None else heads
407 projected = self.q_b_proj(latent).view(*latent.shape[:2], heads, self.qk_head_dim)
408 content, rotary = projected.split((self.qk_nope_head_dim, self.qk_rope_head_dim), dim=-1)
409 rotation = self.apply_position if rotary_fn is None else rotary_fn
410 rotated = rotation(rotary, position_embeddings, interleaved=self.rotary_interleaved)
411 if rotated is rotary:
412 return projected.transpose(1, 2)
413 return torch.cat((content, rotated), dim=-1).transpose(1, 2)
414
415 def project_key_value_parts(
416 self, latent: torch.Tensor, *, heads: int | None = None,
417 ) -> tuple[torch.Tensor, torch.Tensor]:
418 """Project K content and V before assembling the shared key features.
419
420 Args:
421 latent: Normalized KV latent in BSR.
422 heads: Projection head count, or the module's local head count.
423
424 Returns:
425 K content and V views in BSND. A scheduler can consume V before K is assembled.
426 """
427 heads = self.num_heads if heads is None else heads
428 projected = self.kv_b_proj(latent).view(
429 *latent.shape[:2], heads, self.qk_nope_head_dim + self.v_head_dim,
430 )
431 return projected.split((self.qk_nope_head_dim, self.v_head_dim), dim=-1)
432
433 @staticmethod
434 def assemble_key(content: torch.Tensor, shared_key: torch.Tensor) -> torch.Tensor:
435 """Join BSND content with one already-transformed shared key per token.
436
437 Args:
438 content: Head-specific key features in BSND.
439 shared_key: BSR features after RoPE/NoPE; expansion itself is a view.
440
441 Returns:
442 Full BSND keys with content followed by shared features.
443 """
444 return torch.cat((content, shared_key.unsqueeze(2).expand(-1, -1, content.shape[2], -1)), dim=-1)
445
446 def assemble_key_value(
447 self, projected: torch.Tensor, shared_key: torch.Tensor, *, heads: int | None = None,
448 ) -> tuple[torch.Tensor, torch.Tensor]:
449 """Unpack the result of a managed KV projection.
450
451 Args:
452 projected: Projection output with K/V features interleaved per head.
453 shared_key: Already-positioned BSR shared key features.
454 heads: Number of heads represented by projected.
455
456 Returns:
457 BNSD keys and values, preserving the projection's token order.
458 """
459 heads = self.num_heads if heads is None else heads
460 projected = projected.view(*projected.shape[:2], heads, self.qk_nope_head_dim + self.v_head_dim)
461 content, value = projected.split((self.qk_nope_head_dim, self.v_head_dim), dim=-1)
462 return self.assemble_key(content, shared_key).transpose(1, 2), value.transpose(1, 2)
463
464 def project_key_value(
465 self, latent: torch.Tensor, shared_key: torch.Tensor, *, heads: int | None = None,
466 head_range: tuple[int, int] | None = None,
467 ) -> tuple[torch.Tensor, torch.Tensor]:
468 """Project owned heads through the child Module, preserving its parameter hooks.
469
470 Args:
471 latent: Normalized KV features in BSR.
472 shared_key: Positioned shared features for the same tokens.
473 heads: Number of heads in the returned tensors.
474 head_range: Optional half-open head slice within the managed projection.
475 Requires kv_b_proj to accept the mla_head_range keyword.
476
477 Returns:
478 Expanded keys and values in BNSD.
479 """
480 projected = (self.kv_b_proj(latent) if head_range is None
481 else self.kv_b_proj(latent, mla_head_range=head_range))
482 return self.assemble_key_value(projected, shared_key, heads=heads)
483
484 def validate_inputs(self, past_key_values: Any) -> None:
485 """Validate per-call constraints before executing projections.
486
487 Args:
488 past_key_values: Optional compressed cache accepted by the local algorithm.
489 """
490 del past_key_values
491
492 @staticmethod
493 def prepare_positions(position_embeddings: Any) -> Any:
494 """Preserve the algorithm's positional inputs; NoPE overrides this stage.
495
496 Args:
497 position_embeddings: Model-provided cosine/sine tables, or None.
498 """
499 return position_embeddings
500
501 def prepare_attention_inputs(self, hidden_states: torch.Tensor) -> tuple[MLALatentInputs, Any]:
502 """Compute normalized Q/KV latents and shared-key features before head expansion.
503
504 Args:
505 hidden_states: Original local input tokens in BSH layout.
506
507 Returns:
508 Local Q/KV latents, shared-key features and optional output-stage state.
509 """
510 return MLALatentInputs(*self.project_latent_inputs(hidden_states)), None
511
512 def exchange_attention(self, state: MLALatentInputs,
513 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
514 attention_mask: torch.Tensor | None = None, past_key_values: Any = None,
515 actual_seq_len: torch.Tensor | Sequence[int] | None = None, *,
516 output_state: Any = None, **kwargs: Any) -> MLAInputs:
517 """Expand local operands without changing sequence or head ownership.
518
519 Args:
520 state: Already-computed normalized latents and shared-key features.
521 position_embeddings: Local cosine/sine tables.
522 attention_mask: Optional padding or visibility mask.
523 past_key_values: Optional compressed inference cache.
524 actual_seq_len: Cumulative document endpoints.
525 output_state: Optional invocation-local state passed to the output stages.
526 **kwargs: Additional attention options.
527 """
528 query = self.project_query(state.query_latent, position_embeddings)
529 shared_key = self.apply_position(state.key_rope.unsqueeze(2), position_embeddings).squeeze(2)
530 kv_latent = state.kv_latent
531 if past_key_values is not None:
532 kv_latent, shared_key = past_key_values.update(
533 kv_latent.unsqueeze(1), shared_key.unsqueeze(1), self.layer_idx,
534 )
535 kv_latent, shared_key = kv_latent.squeeze(1), shared_key.squeeze(1)
536 key, value = self.project_key_value(kv_latent, shared_key)
537 return MLAInputs(query, key, value, attention_mask,
538 dict(kwargs, actual_seq_len=actual_seq_len), output_state)
539
540 def run_attention(self, inputs: MLAInputs) -> tuple[torch.Tensor, torch.Tensor | None]:
541 """Apply the shared FA contract to ready BNSD inputs and return BSND output.
542
543 Args:
544 inputs: Expanded Q/K/V, mask and attention options for this invocation.
545 Its optional attention_interface selects the FA callback for this invocation.
546
547 Returns:
548 BSND attention output and optional attention weights.
549 """
550 attention_mask = prepare_mla_attention_mask(
551 inputs.attention_mask, inputs.query.shape[2], inputs.key.shape[2])
552 options = {"dropout": self.attention_dropout if self.training else 0.0,
553 "scaling": self.scaling, "sliding_window": self.sliding_window}
554 options.update(inputs.options)
555 interface = options.pop("attention_interface", None)
556 if interface is None:
557 interface = self.attention_interface
558 return interface(self, inputs.query, inputs.key, inputs.value, attention_mask, **options)
559
560 def restore_attention(self, output: torch.Tensor, hidden_states: torch.Tensor,
561 output_state: Any) -> tuple[torch.Tensor, Any]:
562 """Preserve local query ownership before the output projection.
563
564 Args:
565 output: Attention output in BSND layout.
566 hidden_states: Original local input for output-stage algorithms; unused here.
567 output_state: Optional invocation-local output state.
568
569 Returns:
570 Unchanged local-token output and state consumed by project_output.
571 """
572 del hidden_states
573 return output, output_state
574
575 def project_output(self, attention_output: torch.Tensor, hidden_states: torch.Tensor,
576 output_state: Any) -> torch.Tensor:
577 """Flatten local heads and project to the original hidden dimension.
578
579 Args:
580 attention_output: Token-local attention output in BSND layout.
581 hidden_states: Original local input defining batch and sequence dimensions.
582 output_state: Unused by ordinary local MLA; specialized members own their output state.
583
584 Returns:
585 Projected local hidden states in BSH layout.
586 """
587 del output_state
588 output = attention_output.reshape(*hidden_states.shape[:2], -1).contiguous()
589 return self.o_proj(output)
590
591 def forward(
592 self,
593 hidden_states: torch.Tensor,
594 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
595 attention_mask: torch.Tensor | None = None,
596 past_key_values: Any | None = None,
597 actual_seq_len: torch.Tensor | Sequence[int] | None = None,
598 **kwargs: Any,
599 ) -> tuple[torch.Tensor, torch.Tensor | None]:
600 """Run the shared MLA algorithm through operand and output stages.
601
602 Args:
603 hidden_states: Input tokens in batch, sequence, hidden order.
604 position_embeddings: Optional precomputed RoPE cosine and sine.
605 attention_mask: Optional mask in the attention interface convention.
606 past_key_values: Optional cache for incremental decoding.
607 actual_seq_len: Optional cumulative packed document endpoints.
608 **kwargs: Additional arguments for the attention interface.
609
610 Returns:
611 Projected attention output and optional attention weights.
612 """
613 self.validate_inputs(past_key_values)
614 positions = self.prepare_positions(position_embeddings)
615 state, output_state = self.prepare_attention_inputs(hidden_states)
616 inputs = self.exchange_attention(
617 state, positions, attention_mask, past_key_values, actual_seq_len,
618 output_state=output_state, **kwargs)
619 del state
620 output, weights = self.run_attention(inputs)
621 output_state = inputs.output_state
622 # Output stages need only output_state, not an extra owner of QKV.
623 # Tensors saved for backward remain owned by autograd.
624 del inputs
625 output, output_state = self.restore_attention(output, hidden_states, output_state)
626 return self.project_output(output, hidden_states, output_state), weights