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"""Single-device GQA math and source-checkpoint conversion, without parallel execution."""
16
17from __future__ import annotations
18
19from collections.abc import Sequence
20from dataclasses import dataclass
21from types import SimpleNamespace
22from typing import Any
23
24import torch
25from torch import nn
26
27from hyper_parallel.components.checkpoint import InterleaveQKV
28from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter
29from hyper_parallel.components.functional import apply_rotary_pos_emb_single, npu_fusion_attention_forward
30from hyper_parallel.components.modules.common.rms_norm import RMSNorm
31
32
33def rotate_half(x: torch.Tensor) -> torch.Tensor:
34 """Rotate the two halves of the last dimension as Transformers does."""
35 first = x[..., : x.shape[-1] // 2]
36 second = x[..., x.shape[-1] // 2 :]
37 return torch.cat((-second, first), dim=-1)
38
39
40def _projections_can_fuse(projections: tuple[nn.Linear, ...]) -> bool:
41 """Return whether projections share the layout needed for fusion."""
42 biases = tuple(projection.bias for projection in projections)
43 return (
44 len({projection.in_features for projection in projections}) == 1
45 and len({projection.weight.requires_grad for projection in projections}) == 1
46 and (all(bias is None for bias in biases) or all(bias is not None for bias in biases))
47 and (biases[0] is None or len({bias.requires_grad for bias in biases}) == 1)
48 )
49
50
51def apply_gqa_position(tensor: torch.Tensor, positions: Any, interleaved: bool) -> torch.Tensor:
52 """Rotate one BSND branch, retaining the source half-band/interleaved convention."""
53 if positions is None:
54 return tensor
55 cos, sin = positions
56 if cos.ndim == 2:
57 cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
58 rotary_dim = cos.shape[-1]
59 if rotary_dim > tensor.shape[-1] or rotary_dim % 2:
60 raise ValueError("GQA rotary dimension must be even and fit the head dimension")
61 # Keep partial-width half-layout rotation on its established eager path.
62 if not interleaved and rotary_dim < tensor.shape[-1]:
63 rotary, tail = tensor.split((rotary_dim, tensor.shape[-1] - rotary_dim), dim=-1)
64 return torch.cat((rotary * cos.unsqueeze(2) + rotate_half(rotary) * sin.unsqueeze(2), tail), dim=-1)
65 if interleaved:
66 cos, sin = (part[..., :rotary_dim // 2].repeat_interleave(2, dim=-1) for part in (cos, sin))
67 cos, sin = (part.expand(tensor.shape[0], -1, -1).transpose(0, 1) for part in (cos, sin))
68 result = apply_rotary_pos_emb_single(tensor.transpose(0, 1), cos, sin,
69 rotary_interleaved=interleaved, use_fused_rotary_pos_emb=True)
70 result = result.transpose(0, 1)
71 if interleaved:
72 rotary, tail = result.split((rotary_dim, result.shape[-1] - rotary_dim), dim=-1)
73 rotary = rotary.unflatten(-1, (-1, 2)).transpose(-1, -2).flatten(-2)
74 result = torch.cat((rotary, tail), dim=-1) if tail.shape[-1] else rotary
75 return result
76
77
78@dataclass(frozen=True)
79class GQAInputs:
80 """Attention operands in BNSD order and metadata for this invocation."""
81
82 query: torch.Tensor
83 key: torch.Tensor
84 value: torch.Tensor
85 attention_mask: torch.Tensor | None
86 options: dict[str, Any]
87 output_state: Any
88
89
90class GroupedQueryAttentionModule(nn.Module):
91 """GQA with fused or independent Q/K/V Parameters fixed at construction.
92
93 The source module may expose a fused ``qkv_proj`` or separate
94 ``q_proj``/``k_proj``/``v_proj`` layers. Its checkpoint layout is converted
95 to per-KV-head grouping when fuse_qkv=True; False retains independent
96 projections and their individual parameter identities.
97 Alternatively, ``config`` constructs the selected parameters directly.
98 Source construction declares conversion through ``make_transforms``;
99 native checkpoints already use this module's layout and need no conversion.
100 """
101
102 def _initialize_dimensions(self, module: nn.Module | None) -> None:
103 """Initialize head dimensions and grouped-QKV layout metadata."""
104 config = self.config
105 self.num_heads = config.num_attention_heads
106 self.num_key_value_heads = config.num_key_value_heads
107 dimensions = (config.hidden_size, self.num_heads, self.num_key_value_heads)
108 if any(not isinstance(value, int) or isinstance(value, bool) or value <= 0 for value in dimensions):
109 raise ValueError("GQA hidden size and head counts must be positive integers")
110 if self.num_heads % self.num_key_value_heads:
111 raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
112 self.num_key_value_groups = self.num_heads // self.num_key_value_heads
113 self.qk_head_dim = getattr(module, "head_dim", getattr(config, "head_dim", None))
114 if self.qk_head_dim is None:
115 if config.hidden_size % self.num_heads:
116 raise ValueError("GQA requires an explicit head_dim when hidden_size is not divisible by query heads")
117 self.qk_head_dim = config.hidden_size // self.num_heads
118 self.v_head_dim = getattr(module, "v_head_dim", getattr(config, "v_head_dim", None))
119 if self.v_head_dim is None:
120 self.v_head_dim = self.qk_head_dim
121 if any(not isinstance(value, int) or isinstance(value, bool) or value <= 0
122 for value in (self.qk_head_dim, self.v_head_dim)):
123 raise ValueError("GQA head dimensions must be positive integers")
124 self.qkv_split_sizes = (
125 self.num_key_value_groups * self.qk_head_dim,
126 self.qk_head_dim,
127 self.v_head_dim,
128 )
129 self.qkv_group_width = sum(self.qkv_split_sizes)
130
131 def _initialize_attention_options(self, module: Any) -> None:
132 """Copy supported attention options and reject unsupported variants."""
133 config = self.config
134 self.scaling = getattr(module, "scaling", self.qk_head_dim**-0.5)
135 self.attention_dropout = getattr(module, "attention_dropout", 0.0)
136 if isinstance(self.attention_dropout, nn.Dropout):
137 self.attention_dropout = self.attention_dropout.p
138 self.is_causal = getattr(module, "is_causal", True)
139 self.sliding_window = getattr(module, "sliding_window", getattr(config, "sliding_window", None))
140 self.rotary_interleaved = getattr(
141 module,
142 "rotary_interleaved",
143 getattr(config, "rope_interleave", getattr(config, "rope_interleaved", False)),
144 )
145 # Reject unsupported source mathematics rather than dropping its sink,
146 # normalization or gate while converting the checkpoint.
147 if getattr(module, "param_sink_number", 0) > 0:
148 raise ValueError(
149 "GroupedQueryAttention only implements standard GQA; parameter-sink attention "
150 "must use the sink_attention high-performance interface."
151 )
152 if getattr(module, "attn_groupnorm", False) or getattr(module, "attn_elementwise_gate", False):
153 raise ValueError(
154 "GroupedQueryAttention only implements standard GQA; group normalization and "
155 "elementwise attention gates require a dedicated replacement."
156 )
157
158 def _source_qkv(self, module: nn.Module) -> tuple[nn.Linear, tuple[str, ...]]:
159 """Validate and return the source QKV projection layout."""
160 self._source_is_fused = hasattr(module, "qkv_proj")
161 if self._source_is_fused:
162 if not self.fuse_qkv:
163 raise ValueError("fuse_qkv=False requires separate Q/K/V source projections")
164 source_qkv = module.qkv_proj
165 if not isinstance(source_qkv, nn.Linear):
166 raise TypeError("qkv_proj must be torch.nn.Linear")
167 expected_size = (
168 self.num_heads * self.qk_head_dim
169 + self.num_key_value_heads * self.qk_head_dim
170 + self.num_key_value_heads * self.v_head_dim
171 )
172 if source_qkv.out_features != expected_size:
173 raise ValueError("qkv_proj output size is incompatible with the configured GQA dimensions")
174 return source_qkv, ("qkv_proj",)
175 required = ("q_proj", "k_proj", "v_proj")
176 if any(not hasattr(module, name) for name in required):
177 raise TypeError("GroupedQueryAttention requires qkv_proj or q_proj/k_proj/v_proj on the source module")
178 projections = tuple(getattr(module, name) for name in required)
179 if any(not isinstance(projection, nn.Linear) for projection in projections):
180 raise TypeError("q_proj, k_proj, and v_proj must be torch.nn.Linear")
181 expected_sizes = (
182 self.num_heads * self.qk_head_dim,
183 self.num_key_value_heads * self.qk_head_dim,
184 self.num_key_value_heads * self.v_head_dim,
185 )
186 if tuple(projection.out_features for projection in projections) != expected_sizes:
187 raise ValueError("Q/K/V projection sizes are incompatible with the configured GQA dimensions")
188 if len({projection.in_features for projection in projections}) != 1:
189 raise ValueError("Q/K/V projections must accept the same hidden width")
190 if self.fuse_qkv and not _projections_can_fuse(projections):
191 raise ValueError("Q, K, and V projections cannot be represented by one fused projection")
192 return module.q_proj, required
193
194 def _initialize_projections(self, module: nn.Module, source_qkv: nn.Linear) -> None:
195 """Create fused rows or retain the independent source projection boundaries."""
196 if not isinstance(getattr(module, "o_proj", None), nn.Linear):
197 raise TypeError("GroupedQueryAttention requires o_proj on the source module")
198 if module.o_proj.in_features != self.num_heads * self.v_head_dim:
199 raise ValueError("o_proj input size is incompatible with the configured GQA dimensions")
200 if not self.fuse_qkv:
201 self._initialize_separate_projections(module)
202 return
203 projection_size = self.num_key_value_heads * self.qkv_group_width
204 self.linear_qkv = nn.Linear(
205 source_qkv.in_features,
206 projection_size,
207 bias=source_qkv.bias is not None,
208 device=source_qkv.weight.device,
209 dtype=source_qkv.weight.dtype,
210 )
211 self.linear_qkv.weight.requires_grad_(source_qkv.weight.requires_grad)
212 if self.linear_qkv.bias is not None:
213 self.linear_qkv.bias.requires_grad_(source_qkv.bias.requires_grad)
214 self.o_proj = module.o_proj
215 self.q_norm = getattr(module, "q_norm", None)
216 self.k_norm = getattr(module, "k_norm", None)
217
218 def _initialize_separate_projections(self, module: nn.Module) -> None:
219 """Retain source Linear boundaries for FSDP and independent Q/K/V submission."""
220 for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
221 setattr(self, name, getattr(module, name))
222 for name in ("q_norm", "k_norm"):
223 norm = getattr(module, name, None)
224 # The former three-projection Qwen path used fused direct-scale RMSNorm.
225 # Retain that kernel as a real child Module so FSDP hooks are not bypassed.
226 if norm is not None and hasattr(norm, "variance_epsilon"):
227 if set(dict(norm.named_parameters())) != {"weight"}:
228 raise ValueError("GQA direct-scale RMSNorm requires only a weight parameter")
229 norm = RMSNorm(module=norm, use_fused_ops=True)
230 setattr(self, name, norm)
231
232 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
233 fuse_qkv: bool = True) -> None:
234 """Build fixed QKV parameters from configuration or a supported source.
235
236 Args:
237 config: Native dimensions and math options; exclusive with module.
238 module: Source attention providing weights and checkpoint conversion metadata.
239 fuse_qkv: Use grouped linear_qkv rows or independent Q/K/V children.
240 """
241 super().__init__()
242 if not isinstance(fuse_qkv, bool):
243 raise TypeError("GQA fuse_qkv must be boolean")
244 self.fuse_qkv = fuse_qkv
245 if (config is None) == (module is None):
246 raise ValueError("GroupedQueryAttention requires exactly one of config or module")
247 self._config_initialization = module is None or getattr(module, "_config_initialization", False)
248 self.attention_interface = npu_fusion_attention_forward
249 self.config = config if module is None else module.config
250 source = config if module is None else module
251 self.layer_idx = getattr(source, "layer_idx", getattr(source, "layer_number", None))
252 self._initialize_dimensions(module)
253 if module is None:
254 self._initialize_config(config)
255 return
256 if isinstance(module, GroupedQueryAttentionModule):
257 if self.fuse_qkv != module.fuse_qkv:
258 raise ValueError("GQA promotion cannot change the fused/split parameter representation")
259 if hasattr(self, "gated_qkv_group_width") != hasattr(module, "gated_qkv_group_width"):
260 raise ValueError("GQA promotion cannot add or remove query gate parameters")
261 # Promotion happens before sharding: retain weights, FQNs and conversion provenance.
262 for name in ("_source_is_fused", "_source_projection_names"):
263 setattr(self, name, getattr(module, name, None))
264 # Preserve registration order and aliases as well as parameter names.
265 for name, child in module.named_modules(remove_duplicate=False):
266 if name and "." not in name:
267 self.add_module(name, child)
268 for name in ("q_norm", "k_norm"):
269 if not hasattr(self, name):
270 setattr(self, name, getattr(module, name, None))
271 self._initialize_attention_options(module)
272 self.train(module.training)
273 return
274 self._initialize_attention_options(module)
275 source_qkv, source_projection_names = self._source_qkv(module)
276 self._source_projection_names = source_projection_names
277 self._initialize_projections(module, source_qkv)
278 self.train(module.training)
279
280 def _initialize_config(self, config: Any) -> None:
281 """Create native projections and optional direct-scale Q/K RMSNorm."""
282 self._initialize_attention_options(config)
283 bias = getattr(config, "attention_bias", False)
284 output_bias = getattr(config, "o_proj_bias", bias)
285 qk_norm = getattr(config, "qk_norm", False)
286 if any(not isinstance(value, bool) for value in (bias, output_bias, qk_norm)):
287 raise ValueError("GQA attention_bias, o_proj_bias and qk_norm must be boolean")
288 eps = getattr(config, "rms_norm_eps", 1e-6)
289 if qk_norm and (not isinstance(eps, (int, float)) or isinstance(eps, bool) or not eps > 0):
290 raise ValueError("GQA rms_norm_eps must be positive when qk_norm is enabled")
291 dtype = getattr(config, "dtype", None)
292 self._source_is_fused = False
293 self._source_projection_names = ()
294 self._initialize_config_projections(config, bias, dtype)
295 self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=output_bias, dtype=dtype)
296 # Norm presence is an algorithm choice, not something inferred from model_type
297 # or rms_norm_eps. Native gamma is direct scale; source Norms keep their own convention.
298 self.q_norm = (
299 RMSNorm(config=SimpleNamespace(hidden_size=self.qk_head_dim, eps=eps), use_fused_ops=True).to(dtype=dtype)
300 if qk_norm else None
301 )
302 self.k_norm = (
303 RMSNorm(config=SimpleNamespace(hidden_size=self.qk_head_dim, eps=eps), use_fused_ops=True).to(dtype=dtype)
304 if qk_norm else None
305 )
306
307 def _initialize_config_projections(self, config: Any, bias: bool, dtype: torch.dtype | None) -> None:
308 """Allocate native grouped rows or independent Q/K/V projections."""
309 if self.fuse_qkv:
310 self.linear_qkv = nn.Linear(
311 config.hidden_size, self.num_key_value_heads * self.qkv_group_width, bias=bias, dtype=dtype)
312 else:
313 self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=bias, dtype=dtype)
314 self.k_proj = nn.Linear(
315 config.hidden_size, self.num_key_value_heads * self.qk_head_dim, bias=bias, dtype=dtype)
316 self.v_proj = nn.Linear(
317 config.hidden_size, self.num_key_value_heads * self.v_head_dim, bias=bias, dtype=dtype)
318
319 def reset_parameters(self) -> None:
320 """Initialize native/meta parameters without resetting converted source weights."""
321 if not self._config_initialization:
322 return
323 for name in ("linear_qkv", "q_proj", "k_proj", "v_proj", "o_proj"):
324 projection = getattr(self, name, None)
325 if projection is not None:
326 projection.reset_parameters()
327 for norm in (self.q_norm, self.k_norm):
328 if norm is not None:
329 nn.init.ones_(norm.weight)
330
331 def make_transforms(self) -> list[WeightConverter]:
332 """Describe reversible source-checkpoint to grouped-QKV conversion."""
333 if self._config_initialization or not self.fuse_qkv:
334 return []
335 suffixes = ("weight", "bias") if self.linear_qkv.bias is not None else ("weight",)
336 transforms = []
337 for suffix in suffixes:
338 sources = [f"{name}.{suffix}" for name in self._source_projection_names]
339 transforms.append(WeightConverter(
340 source_patterns=sources[0] if self._source_is_fused else sources,
341 target_patterns=f"linear_qkv.{suffix}",
342 operations=[InterleaveQKV(
343 self.config.num_key_value_heads, self.num_key_value_groups,
344 self.qk_head_dim, self.v_head_dim, self._source_is_fused,
345 )],
346 ))
347 return transforms
348
349 def split_projection(self, hidden_states: torch.Tensor) -> tuple:
350 """Produce grouped Q/K/V and an empty output-stage state for ordinary GQA."""
351 projected = self.linear_qkv(hidden_states).view(
352 *hidden_states.shape[:-1], self.num_key_value_heads, self.qkv_group_width)
353 query, key, value = projected.split(self.qkv_split_sizes, dim=-1)
354 return query.reshape(*hidden_states.shape[:-1], self.num_heads, self.qk_head_dim), key, value, None
355
356 def normalize_position(self, tensor: torch.Tensor, norm: nn.Module | None, positions: Any) -> torch.Tensor:
357 """Apply per-head Norm and position math through ordinary child-module calls."""
358 if norm is not None:
359 tensor = norm(tensor)
360 return apply_gqa_position(tensor, positions, self.rotary_interleaved)
361
362 def project_query(self, hidden_states: torch.Tensor, positions: Any) -> torch.Tensor:
363 """Compute a query from the independent projection representation.
364
365 Args:
366 hidden_states: Local input tokens in BSH layout.
367 positions: Local cosine/sine tables, or None.
368
369 Returns:
370 Query in BSND after its optional Norm and positional transform.
371 """
372 query = self.q_proj(hidden_states).view(*hidden_states.shape[:-1], self.num_heads, self.qk_head_dim)
373 return self.normalize_position(query, self.q_norm, positions)
374
375 def project_key(self, hidden_states: torch.Tensor, positions: Any) -> torch.Tensor:
376 """Compute a key from the independent projection representation.
377
378 Args:
379 hidden_states: Local input tokens in BSH layout.
380 positions: Local cosine/sine tables, or None.
381
382 Returns:
383 Key in BSND after its optional Norm and positional transform.
384 """
385 key = self.k_proj(hidden_states).view(*hidden_states.shape[:-1], self.num_key_value_heads, self.qk_head_dim)
386 return self.normalize_position(key, self.k_norm, positions)
387
388 def project_value(self, hidden_states: torch.Tensor) -> torch.Tensor:
389 """Compute a value from the independent projection representation.
390
391 Args:
392 hidden_states: Local input tokens in BSH layout.
393
394 Returns:
395 Value in BSND without a positional transform.
396 """
397 return self.v_proj(hidden_states).view(*hidden_states.shape[:-1], self.num_key_value_heads, self.v_head_dim)
398
399 def project_qkv(self, hidden_states: torch.Tensor, positions: Any) -> tuple:
400 """Compute local Q/K/V and the optional gate using the selected projections.
401
402 Args:
403 hidden_states: Local input tokens in BSH layout.
404 positions: Local cosine/sine tables, or None.
405
406 Returns:
407 Ready BSND Q/K/V and algorithm-owned output state. Fused parameters
408 use one GEMM; independent parameters keep their ordinary child calls.
409 """
410 if not self.fuse_qkv:
411 query = self.project_query(hidden_states, positions)
412 key = self.project_key(hidden_states, positions)
413 value = self.project_value(hidden_states)
414 return query, key, value, None
415 query, key, value, output_state = self.split_projection(hidden_states)
416 query = self.normalize_position(query, self.q_norm, positions)
417 key = self.normalize_position(key, self.k_norm, positions)
418 return query, key, value, output_state
419
420 def project_output(self, attention_output: torch.Tensor, output_state: Any) -> torch.Tensor:
421 """Project local tokens; ordinary GQA has no output gate."""
422 del output_state
423 return self.o_proj(attention_output.flatten(-2).contiguous())
424
425 def prepare_positions(self, query_shape: tuple[int, int], positions: Any) -> Any:
426 """Preserve the precomputed cosine/sine inputs for these tokens.
427
428 Args:
429 query_shape: Original batch and local sequence dimensions.
430 positions: Token-aligned cosine/sine inputs, or None; these are not position IDs.
431 """
432 del query_shape
433 return positions
434
435 def prepare_attention_inputs(self, hidden_states: torch.Tensor, positions: Any,
436 attention_mask: torch.Tensor | None = None, past_key_values: Any = None,
437 actual_seq_len: torch.Tensor | Sequence[int] | None = None,
438 **kwargs: Any) -> Any:
439 """Prepare local operands using the shared projection and position math.
440
441 This implementation returns ready GQAInputs. The shared forward passes
442 the preparation result to exchange_attention before run_attention.
443
444 Args:
445 hidden_states: Original local input tokens in BSH layout.
446 positions: Local cosine/sine tables, or None.
447 attention_mask: Optional padding or visibility mask.
448 past_key_values: Optional local inference cache.
449 actual_seq_len: Cumulative document endpoints.
450 **kwargs: Additional attention options.
451
452 Returns:
453 Ready local GQAInputs, consumed by exchange_attention.
454 """
455 query, key, value, output_state = self.project_qkv(hidden_states, positions)
456 query, key, value = (tensor.transpose(1, 2) for tensor in (query, key, value))
457 if past_key_values is not None:
458 key, value = past_key_values.update(key, value, self.layer_idx)
459 if attention_mask is not None and attention_mask.ndim == 4:
460 # HF cache masks may reserve more KV slots than the cache currently exposes.
461 attention_mask = attention_mask[..., :key.shape[2]]
462 return GQAInputs(query, key, value, attention_mask,
463 dict(kwargs, actual_seq_len=actual_seq_len), output_state)
464
465 def exchange_attention(self, prepared: Any) -> GQAInputs:
466 """Return ready FA inputs without changing local ownership.
467
468 Args:
469 prepared: Local GQAInputs returned by prepare_attention_inputs.
470
471 Returns:
472 Ready BNSD operands and attention metadata.
473 """
474 return prepared
475
476 def run_attention(self, inputs: GQAInputs) -> tuple[torch.Tensor, torch.Tensor | None]:
477 """Run the common attention algorithm after operands are ready.
478
479 Args:
480 inputs: Ready BNSD operands, mask and FA options for this invocation.
481 """
482 options = dict(inputs.options)
483 options.setdefault("sliding_window", self.sliding_window)
484 return self.attention_interface(
485 self, inputs.query, inputs.key, inputs.value, inputs.attention_mask,
486 dropout=self.attention_dropout if self.training else 0.0, scaling=self.scaling, **options)
487
488 def restore_attention(self, output: torch.Tensor, output_state: Any) -> tuple[torch.Tensor, Any]:
489 """Preserve local query ownership and return algorithm-only output state.
490
491 Args:
492 output: Attention output in BSND layout.
493 output_state: Optional gate tensor produced by the projection stage.
494
495 Returns:
496 Local-token attention output and the state consumed by project_output.
497 """
498 return output, output_state
499
500 def forward(self, hidden_states: torch.Tensor, position_embeddings: Any = None,
501 attention_mask: torch.Tensor | None = None, past_key_values: Any = None,
502 actual_seq_len: torch.Tensor | Sequence[int] | None = None,
503 **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor | None]:
504 """Run shared GQA math with class-defined operand exchange and restoration.
505
506 Args:
507 hidden_states: Local input tokens in BSH layout.
508 position_embeddings: Optional precomputed cosine/sine tables.
509 attention_mask: Optional padding or explicit visibility mask.
510 past_key_values: Optional local inference cache.
511 actual_seq_len: Optional cumulative document endpoints.
512 **kwargs: Additional attention options.
513 """
514 query_shape = hidden_states.shape[:2]
515 positions = self.prepare_positions(query_shape, position_embeddings)
516 prepared = self.prepare_attention_inputs(
517 hidden_states, positions, attention_mask, past_key_values, actual_seq_len, **kwargs)
518 inputs = self.exchange_attention(prepared)
519 del prepared
520 output, weights = self.run_attention(inputs)
521 output_state = inputs.output_state
522 # Output stages need only output_state, not an extra owner of QKV.
523 # Tensors saved for backward remain owned by autograd.
524 del inputs
525 output, output_state = self.restore_attention(output, output_state)
526 return self.project_output(output, output_state), weights