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"""NoPE MLA with a required sigmoid output gate."""
16
17from __future__ import annotations
18
19from typing import Any
20
21# The high-performance attention modules use native Torch.
22import torch
23from torch import nn
24
25from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention import (
26 MultiLatentAttentionModule,
27)
28
29
30class GatedMultiLatentAttentionModule(MultiLatentAttentionModule):
31 """Define NoPE attention and its mandatory output gate in one math module.
32
33 The shared key features retain the source projection/checkpoint dimensions;
34 NoPE disables their rotation. Model adapters only preserve forward APIs.
35 """
36
37 def __init__(self, *, module: nn.Module | None = None, config: Any = None) -> None:
38 """Construct mandatory-gate NoPE MLA with the ordinary MLA parameter layout.
39
40 Args:
41 module: Optional NoPE source with an enabled plain Linear output gate.
42 config: Direct construction dimensions, exclusive with module; NoPE is intrinsic to this class.
43 """
44 if module is None:
45 super().__init__(config=config)
46 self.use_nope = True
47 self.g_proj = nn.Linear(
48 config.hidden_size, self.num_heads * self.v_head_dim,
49 bias=getattr(config, "attention_bias", False), dtype=getattr(config, "dtype", None),
50 )
51 return
52 if not getattr(module, "use_nope", False):
53 raise ValueError("GatedMultiLatentAttention requires a NoPE source module")
54 if not isinstance(module, GatedMultiLatentAttentionModule) and not getattr(module, "use_output_gate", False):
55 raise ValueError("GatedMultiLatentAttention requires an enabled output gate")
56 if type(module.g_proj) is not nn.Linear: # pylint: disable=unidiomatic-typecheck
57 raise ValueError("Gated MLA requires a plain Linear output gate")
58 super().__init__(module=module, config=config)
59 self.use_nope = True
60 self.g_proj = module.g_proj
61
62 @staticmethod
63 def apply_nope(tensor: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
64 *, interleaved: bool = False) -> torch.Tensor:
65 """Keep Q/shared-K features unchanged through the CP rotary callback.
66
67 Args:
68 tensor: Query or shared-key features in the runtime's BSND layout.
69 position_embeddings: Ignored by NoPE attention.
70 interleaved: Ignored because no positional rotation is applied.
71
72 Returns:
73 The original tensor, without a copy or a positional transform.
74 """
75 del position_embeddings, interleaved
76 return tensor
77
78 def apply_position(
79 self, tensor: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
80 *, interleaved: bool | None = None,
81 ) -> torch.Tensor:
82 """Keep query/shared-key features unchanged because this algorithm uses NoPE.
83
84 Args:
85 tensor: Query or shared-key features, in BSND layout.
86 position_embeddings: Ignored even when supplied by a generic model caller.
87 interleaved: Ignored because no rotation or feature permutation is performed.
88
89 Returns:
90 The original tensor, preserving its identity and view layout.
91 """
92 del position_embeddings, interleaved
93 return tensor
94
95 @staticmethod
96 def prepare_positions(position_embeddings: Any) -> None:
97 """Discard frequencies and their layout because this algorithm is NoPE.
98
99 Args:
100 position_embeddings: Ignored positional input from the model caller.
101 """
102 del position_embeddings
103
104 def project_gate(self, hidden_states: torch.Tensor) -> torch.Tensor:
105 """Compute the mandatory token-local output gate through its managed Linear.
106
107 Args:
108 hidden_states: Original local input in BSH layout.
109 """
110 return self.g_proj(hidden_states).sigmoid()
111
112 def reset_parameters(self) -> None:
113 """Initialize direct-config projections and gate, preserving source initialization."""
114 if self._config_initialization:
115 super().reset_parameters()
116 self.g_proj.reset_parameters()
117
118 def project_output(self, attention_output: torch.Tensor, hidden_states: torch.Tensor,
119 output_state: torch.Tensor | None) -> torch.Tensor:
120 """Apply the source gate before Wo, without an additional output Norm.
121
122 Args:
123 attention_output: Token-local attention output in BSND layout.
124 hidden_states: Original token-local input for the gate projection.
125 output_state: Optional gate already computed by CP scheduling; local execution computes it here.
126
127 Returns:
128 Gated and projected hidden states.
129 """
130 gate = self.project_gate(hidden_states) if output_state is None else output_state
131 attention_output = attention_output.reshape(*hidden_states.shape[:2], -1)
132 return self.o_proj(attention_output * gate)