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"""Gate-specific input dependencies and output derivatives for MLA overlap."""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from dataclasses import dataclass
21from typing import Any
22
23# Gate math and its autograd scheduling use native Torch.
24import torch
25from torch import nn
26from torch.autograd.function import once_differentiable
27from torch.nn import functional as F
28
29from hyper_parallel.distributed.context_parallel.collectives import (
30 AsyncCPCollective, async_ulysses_seq_to_head_launch,
31)
32from hyper_parallel.distributed.context_parallel.ulysses_overlap import (
33 UlyssesQKVA2AState, launch_input_a2a,
34)
35
36
37class CPGatedMLAOutputLinear(nn.Linear):
38 """Managed output projection with the gated MLA derivative contract."""
39
40 def __init__(self, source: nn.Linear) -> None:
41 """Preserve the source parameter tree and train/freeze state."""
42 nn.Module.__init__(self)
43 if type(source) is not nn.Linear and not isinstance(source, CPGatedMLAOutputLinear): # pylint: disable=unidiomatic-typecheck
44 raise ValueError("Gated MLA scheduled output requires a plain Linear")
45 self.in_features, self.out_features = source.in_features, source.out_features
46 self.weight, self.bias = source.weight, source.bias
47 self.train(source.training)
48
49 def forward(self, attention_output: torch.Tensor, *, mla_output_state: Any = None,
50 mla_output_gate: torch.Tensor | None = None) -> torch.Tensor:
51 """Enter the existing output Function only for an explicit CP invocation.
52
53 Args:
54 attention_output: Local or head-partitioned attention output.
55 mla_output_state: Invocation-local layout and optional gate-gradient handoff.
56 mla_output_gate: Sigmoid gate paired with a scheduled CP output.
57 """
58 if mla_output_state is None:
59 if mla_output_gate is not None:
60 raise ValueError("Scheduled gated output requires a state")
61 return F.linear(attention_output, self.weight, self.bias)
62 if mla_output_gate is None:
63 raise ValueError("Scheduled gated output requires its sigmoid gate")
64 return _GatedOutputProjection.apply(attention_output, self.weight, self.bias, mla_output_gate, mla_output_state)
65
66
67class GatedMLAInputState:
68 """Invocation-local gate values and the optional deferred native derivative.
69
70 The adapter supplies the model-owned gate computation. It is released after
71 forward; the remaining state belongs only to this invocation's paired nodes.
72 With defer_gate_gradient, the output saves dG and the input consumer returns
73 it only after submitting the input-gradient A2As.
74 """
75
76 def __init__(self, hidden: torch.Tensor | None,
77 projection: Callable[[torch.Tensor], torch.Tensor] | None,
78 defer_gate_gradient: bool) -> None:
79 """Keep one identity across the input/output autograd nodes and FSDP hooks.
80
81 FSDP maps tensors recursively inside dataclass arguments. This shared
82 handoff is an opaque control object, not a tensor container to rebuild.
83 Its forward-only hidden/projection references are released by project().
84 """
85 self.hidden = hidden
86 self.projection = projection
87 self.defer_gate_gradient = defer_gate_gradient
88 self.value: torch.Tensor | None = None
89 self.gradient: torch.Tensor | None = None
90
91 def project(self, source: torch.Tensor) -> torch.Tensor:
92 """Run the managed gate and release its temporary forward-only references.
93
94 Args:
95 source: Local hidden states, optionally carrying the input launch edge.
96
97 Returns:
98 The model's post-activation gate in local-token layout.
99 """
100 if self.projection is None:
101 raise RuntimeError("MLA input gate must be projected exactly once")
102 self.value = self.projection(source)
103 self.hidden, self.projection = None, None
104 return self.value
105
106 def take_gradient(self) -> torch.Tensor:
107 """Consume the output multiplication's deferred gate gradient once."""
108 if self.gradient is None:
109 raise RuntimeError("MLA output projection did not release its gate gradient")
110 gradient, self.gradient = self.gradient, None
111 return gradient
112
113
114class _GatedExpandedInputA2AWait(torch.autograd.Function):
115 """Release gate backward only after the attention input gradients are sent."""
116
117 @staticmethod
118 def forward(ctx: Any, gate: torch.Tensor, state: UlyssesQKVA2AState,
119 gate_state: GatedMLAInputState) -> tuple:
120 """Consume Q/K/V after native gate compute, keeping its gradient edge.
121
122 Args:
123 ctx: Autograd context for communication and gate-gradient ownership.
124 gate: Post-sigmoid local-token gate, whose backward is deferred here.
125 state: Q/K/V transfers already submitted before gate compute.
126 gate_state: Invocation-local handoff from the gated output derivative.
127
128 Returns:
129 Completed attention inputs in query, key, value order.
130 """
131 # Output projection consumes the gate value. This argument keeps the
132 # edge on which this consumer will return the deferred dG.
133 del gate
134 ctx.state, ctx.gate_state = state, gate_state
135 return state.wait()
136
137 @staticmethod
138 @once_differentiable
139 def backward(ctx: Any, grad_query: torch.Tensor, grad_key: torch.Tensor,
140 grad_value: torch.Tensor) -> tuple:
141 """Launch dQ/dK/dV before delivering dG to native sigmoid/g_proj backward.
142
143 Args:
144 ctx: This invocation's communication and gate-gradient states.
145 grad_query: Head-local query gradient from attention.
146 grad_key: Head-local key gradient from attention.
147 grad_value: Head-local value gradient from attention.
148
149 Returns:
150 Gate gradient and no gradients for either state object.
151 """
152 ctx.state.launch_backward(grad_query, grad_key, grad_value)
153 return ctx.gate_state.take_gradient(), None, None
154
155
156def finish_gated_expanded_inputs(
157 query: torch.Tensor, state: UlyssesQKVA2AState, gate_state: GatedMLAInputState,
158) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
159 """Cover the last Q A2A with the model-owned native gate projection.
160
161 Args:
162 query: Final token-local query, after V and K have been submitted.
163 state: This invocation's Q/K/V communication state.
164 gate_state: Model gate computation and its selected gradient handoff.
165
166 Returns:
167 Completed attention inputs in head-local layout; gate is saved in gate_state.
168 """
169 gate_input = launch_input_a2a(
170 query, gate_state.hidden, state.query, overlap_backward=gate_state.defer_gate_gradient,
171 )
172 gate = gate_state.project(gate_input)
173 if gate_state.defer_gate_gradient:
174 return _GatedExpandedInputA2AWait.apply(gate, state, gate_state)
175 return state.wait()
176
177
178@dataclass
179class GatedMLAOutputProjectionState:
180 """Own gated output communication and optional input-side gate gradients.
181
182 A pre-launched O transfer covers the native gate projection. For input-side
183 gating, input_gate instead delivers dG to the paired input consumer, which
184 releases the native gate backward after submitting the input gradients.
185 """
186
187 mesh: Any
188 head_dim: int
189 input_gate: GatedMLAInputState | None = None
190 forward_a2a_handle: AsyncCPCollective | None = None
191
192
193class _GatedOutputProjection(torch.autograd.Function):
194 """Own gated output multiplication, Linear and the inverse output A2A."""
195
196 @staticmethod
197 def forward(ctx: Any, attention_output: torch.Tensor, weight: torch.Tensor,
198 bias: torch.Tensor | None, gate: torch.Tensor,
199 state: GatedMLAOutputProjectionState) -> torch.Tensor:
200 """Restore the FA output, multiply its required gate and apply Wo.
201
202 Args:
203 ctx: Autograd context for operands, layout and autocast settings.
204 attention_output: FA output in [batch, sequence, local_heads, value_dim].
205 weight: Managed output-projection weight.
206 bias: Optional output-projection bias.
207 gate: Native post-sigmoid gate in token-local layout.
208 state: Output layout, O transfer and deferred gate consumer.
209
210 Returns:
211 Gated and projected local hidden states.
212 """
213 output_a2a_handle, state.forward_a2a_handle = state.forward_a2a_handle, None
214 if output_a2a_handle is None:
215 output_a2a_handle = async_ulysses_seq_to_head_launch(attention_output, 2, 1, state.mesh)
216 # This Function owns the collective's derivative. Native g_proj and
217 # sigmoid stay outside it so their module hooks and autograd still run.
218 local_output = output_a2a_handle.wait().flatten(2)
219 projected = local_output * gate
220 ctx.save_for_backward(local_output, projected, weight, gate)
221 ctx.state, ctx.has_bias = state, bias is not None
222 ctx.device_type = local_output.device.type
223 ctx.autocast_enabled = torch.is_autocast_enabled(ctx.device_type)
224 ctx.autocast_dtype = torch.get_autocast_dtype(ctx.device_type) if ctx.autocast_enabled else None
225 return F.linear(projected, weight, bias) # pylint: disable=not-callable
226
227 @staticmethod
228 @once_differentiable
229 def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor | None, ...]:
230 """Overlap dO A2A with gate multiplication gradients and Wo wgrad.
231
232 Args:
233 ctx: Saved operands, autocast settings and output layout.
234 gradient: Gradient of the projected hidden states.
235
236 Returns:
237 FA output, weight, bias, gate and no state gradients. Input-side
238 gating delivers dG through its paired consumer instead.
239 """
240 with torch.autocast(ctx.device_type, enabled=ctx.autocast_enabled, dtype=ctx.autocast_dtype):
241 return _gated_output_projection_backward(ctx, gradient)
242
243
244def _gated_output_projection_backward(ctx, gradient):
245 """Keep the dO launch before wgrad and the wait before returning dF."""
246 local_output, projected, weight, gate = ctx.saved_tensors
247 state = ctx.state
248 needs_attention_grad, needs_weight_grad, needs_bias_grad, needs_gate_grad = ctx.needs_input_grad[:4]
249 needs_gate = needs_gate_grad or state.input_gate is not None
250 grad_projected = gradient.matmul(weight).to(projected.dtype) if needs_attention_grad or needs_gate else None
251 grad_output_a2a = None
252 if needs_attention_grad:
253 grad_local_output = (grad_projected * gate).reshape(*local_output.shape[:2], -1, state.head_dim)
254 grad_output_a2a = async_ulysses_seq_to_head_launch(grad_local_output, 1, 2, state.mesh)
255 grad_gate = grad_projected * local_output if needs_gate else None
256 if state.input_gate is not None:
257 state.input_gate.gradient = grad_gate
258 grad_gate = None
259 flat_input = projected.reshape(-1, projected.shape[-1])
260 flat_gradient = gradient.reshape(-1, gradient.shape[-1])
261 grad_weight = None
262 if needs_weight_grad:
263 grad_weight = flat_input.transpose(0, 1).matmul(flat_gradient).transpose(0, 1)
264 grad_bias = flat_gradient.sum(0) if ctx.has_bias and needs_bias_grad else None
265 grad_attention_output = grad_output_a2a.wait() if grad_output_a2a is not None else None
266 return grad_attention_output, grad_weight, grad_bias, grad_gate, None