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"""MLA-specific latent and output projection backward scheduling.
16
17Paired launch/wait nodes require a complete first-order training backward.
18Partial autograd.grad calls can prune the consumer and are not supported.
19"""
20
21from __future__ import annotations
22
23from dataclasses import dataclass
24from typing import Any
25
26# This CP scheduler uses the native Torch autograd and communication APIs.
27import torch
28import torch.distributed as dist
29from torch import nn
30from torch.autograd.function import once_differentiable
31from torch.nn import functional as F
32
33from hyper_parallel.distributed.context_parallel.collectives import (
34 async_ulysses_seq_to_head_launch,
35)
36from hyper_parallel.distributed.context_parallel.ulysses_overlap import UlyssesInputA2AState
37
38
39class CPMLAOutputLinear(nn.Linear):
40 """A managed Linear boundary with explicit optional CP output scheduling."""
41
42 def __init__(self, source: nn.Linear) -> None:
43 """Retain source Parameters without registering an extra child prefix."""
44 nn.Module.__init__(self)
45 if type(source) is not nn.Linear and not isinstance(source, CPMLAOutputLinear): # pylint: disable=unidiomatic-typecheck
46 raise ValueError("MLA scheduled output requires a plain Linear")
47 self.in_features, self.out_features = source.in_features, source.out_features
48 self.weight, self.bias = source.weight, source.bias
49 self.train(source.training)
50
51 def forward(self, attention_output: torch.Tensor, *, mla_output_state: Any = None) -> torch.Tensor:
52 """Read materialized parameters after the normal Module pre-hooks.
53
54 Args:
55 attention_output: Local attention output or head-partitioned CP output.
56 mla_output_state: Invocation-local CP layout; absent for an ordinary projection.
57 """
58 if mla_output_state is None:
59 return F.linear(attention_output, self.weight, self.bias)
60 return _OutputProjection.apply(attention_output, self.weight, self.bias, mla_output_state)
61
62
63class CPMLAKVLinear(nn.Linear):
64 """Select computation heads inside the managed KV up-projection boundary."""
65
66 def __init__(self, source: nn.Linear, head_dim: int) -> None:
67 """Reuse full TP-local parameter storage; CP changes only computation ownership."""
68 nn.Module.__init__(self)
69 if type(source) is not nn.Linear and not isinstance(source, CPMLAKVLinear): # pylint: disable=unidiomatic-typecheck
70 raise ValueError("MLA KV projection requires a plain Linear")
71 self.in_features, self.out_features = source.in_features, source.out_features
72 self.weight, self.bias = source.weight, source.bias
73 self.head_dim = head_dim
74 self.train(source.training)
75
76 def forward(self, latent: torch.Tensor, *, mla_head_range: tuple[int, int] | None = None,
77 mla_gathered: torch.Tensor | None = None, mla_cp_mesh: Any = None) -> Any:
78 """Project all heads or selected rows with the existing latent RS adjoint.
79
80 Args:
81 latent: KV latent tokens.
82 mla_head_range: Optional half-open interval of computation heads.
83 mla_gathered: Gathered latent storage used by the scheduled derivative.
84 mla_cp_mesh: CP mesh required by the scheduled latent derivative.
85 """
86 if mla_head_range is None:
87 return F.linear(latent, self.weight, self.bias)
88 begin, end = mla_head_range
89 if not 0 <= begin < end <= self.weight.shape[0] // self.head_dim:
90 raise ValueError("MLA projection head range is outside the managed parameter")
91 rows = slice(begin * self.head_dim, end * self.head_dim)
92 bias = None if self.bias is None else self.bias[rows]
93 if mla_gathered is not None:
94 if mla_cp_mesh is None:
95 raise ValueError("Scheduled latent projection requires its CP mesh")
96 return _LatentKVLinear.apply(latent, self.weight[rows], bias, mla_gathered, mla_cp_mesh)
97 return F.linear(latent, self.weight[rows], bias)
98
99
100@dataclass
101class MLAOutputProjectionState:
102 """Value-only output layout; the projection node owns its O/dO A2A handles.
103
104 FSDP may rebuild this container without affecting the derivative: no paired
105 node relies on mutating it to deliver a gradient or communication handle.
106 """
107
108 mesh: Any
109 head_dim: int
110
111
112class _OutputProjection(torch.autograd.Function):
113 """Own the ordinary output Linear derivative and its dO A2A."""
114
115 @staticmethod
116 def forward(ctx: Any, attention_output: torch.Tensor, weight: torch.Tensor,
117 bias: torch.Tensor | None, state: MLAOutputProjectionState) -> torch.Tensor:
118 """Restore the FA output to local tokens, then apply Wo.
119
120 Args:
121 ctx: Autograd context for operands, layout and autocast settings.
122 attention_output: FA output in [batch, sequence, local_heads, value_dim].
123 weight: Managed output-projection weight.
124 bias: Optional output-projection bias.
125 state: Ulysses output layout owned by this projection node.
126
127 Returns:
128 Projected local hidden states.
129 """
130 output_a2a_handle = async_ulysses_seq_to_head_launch(attention_output, 2, 1, state.mesh)
131 # Function.forward owns both the numeric A2A and its backward. The
132 # collective's internal autograd wrapper is not recorded in this scope.
133 local_output = output_a2a_handle.wait().flatten(2)
134 ctx.save_for_backward(local_output, weight)
135 ctx.state, ctx.has_bias = state, bias is not None
136 ctx.device_type = local_output.device.type
137 ctx.autocast_enabled = torch.is_autocast_enabled(ctx.device_type)
138 ctx.autocast_dtype = torch.get_autocast_dtype(ctx.device_type) if ctx.autocast_enabled else None
139 return F.linear(local_output, weight, bias) # pylint: disable=not-callable
140
141 @staticmethod
142 @once_differentiable
143 def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor | None, ...]:
144 """Submit dO A2A before wgrad and wait before returning the FA gradient.
145
146 Args:
147 ctx: Saved operands, autocast settings and output layout.
148 gradient: Gradient of the projected hidden states.
149
150 Returns:
151 FA output, weight, bias and no state gradients.
152 """
153 with torch.autocast(ctx.device_type, enabled=ctx.autocast_enabled, dtype=ctx.autocast_dtype):
154 return _output_projection_backward(ctx, gradient)
155
156
157def _output_projection_backward(ctx, gradient):
158 """Keep the dO communication handle local to this backward invocation."""
159 local_output, weight = ctx.saved_tensors
160 state = ctx.state
161 needs_attention_grad, needs_weight_grad, needs_bias_grad = ctx.needs_input_grad[:3]
162 grad_output_a2a = None
163 if needs_attention_grad:
164 grad_local_output = gradient.matmul(weight).to(local_output.dtype)
165 grad_local_output = grad_local_output.reshape(*local_output.shape[:2], -1, state.head_dim)
166 grad_output_a2a = async_ulysses_seq_to_head_launch(grad_local_output, 1, 2, state.mesh)
167 flat_input = local_output.reshape(-1, local_output.shape[-1])
168 flat_gradient = gradient.reshape(-1, gradient.shape[-1])
169 grad_weight = None
170 if needs_weight_grad:
171 grad_weight = flat_input.transpose(0, 1).matmul(flat_gradient).transpose(0, 1)
172 grad_bias = flat_gradient.sum(0) if ctx.has_bias and needs_bias_grad else None
173 grad_attention_output = grad_output_a2a.wait() if grad_output_a2a is not None else None
174 return grad_attention_output, grad_weight, grad_bias, None
175
176
177class _LatentInputA2AWait(torch.autograd.Function):
178 """Launch inverse Q before releasing the local KV projection gradients."""
179
180 @staticmethod
181 def forward(ctx: Any, key: torch.Tensor, value: torch.Tensor, state: UlyssesInputA2AState) -> tuple:
182 """Attach completed Q and both KV edges to the paired consumer.
183
184 Args:
185 ctx: Autograd context for the paired Q A2A.
186 key: Expanded head-local keys.
187 value: Expanded head-local values.
188 state: Q A2A submitted before the KV projection.
189
190 Returns:
191 Attention inputs in query, key, value order.
192 """
193 ctx.state = state
194 query = state.forward_a2a_handle.wait()
195 state.forward_a2a_handle = None
196 return query, key.view_as(key), value.view_as(value)
197
198 @staticmethod
199 @once_differentiable
200 def backward(ctx: Any, grad_query: torch.Tensor, grad_key: torch.Tensor,
201 grad_value: torch.Tensor) -> tuple:
202 """Run KV backward while dQ is being returned to its token owner.
203
204 Args:
205 ctx: Autograd context containing the paired Q A2A.
206 grad_query: Attention gradient for head-local queries.
207 grad_key: Attention gradient for head-local keys.
208 grad_value: Attention gradient for head-local values.
209
210 Returns:
211 Key and value gradients, followed by no state gradient.
212 """
213 state = ctx.state
214 if state.needs_send_grad:
215 state.backward_a2a_handle = async_ulysses_seq_to_head_launch(grad_query, 2, 1, state.mesh)
216 return grad_key, grad_value, None
217
218
219class _LatentKVLinear(torch.autograd.Function):
220 """Schedule the gathered latent adjoint before selected-head weight gradients."""
221
222 @staticmethod
223 def forward(ctx: Any, payload: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None,
224 gathered: torch.Tensor, mesh: Any) -> tuple:
225 """Reuse the completed gather inside the managed Linear module.
226
227 Args:
228 ctx: Autograd state for this projection.
229 payload: Local payload supplying the single gather gradient edge.
230 weight: Selected head rows of the managed projection weight.
231 bias: Optional selected projection bias.
232 gathered: Completed full-sequence latent and shared-key payload.
233 mesh: Chronological CP mesh used by the forward gather.
234
235 Returns:
236 Expanded KV heads and the shared key, without duplicating its gradient.
237 """
238 del payload
239 latent = gathered[..., :weight.shape[-1]].contiguous()
240 shared_key = gathered[..., weight.shape[-1]:]
241 ctx.save_for_backward(latent, weight)
242 ctx.mesh, ctx.has_bias = mesh, bias is not None
243 ctx.device_type = latent.device.type
244 ctx.autocast_enabled = torch.is_autocast_enabled(ctx.device_type)
245 ctx.autocast_dtype = torch.get_autocast_dtype(ctx.device_type) if ctx.autocast_enabled else None
246 return F.linear(latent, weight, bias), shared_key.view_as(shared_key) # pylint: disable=not-callable
247
248 @staticmethod
249 @once_differentiable
250 def backward(ctx: Any, gradient: torch.Tensor, shared_gradient: torch.Tensor) -> tuple:
251 """Overlap SUM ReduceScatter with the independent KV weight gradient.
252
253 Args:
254 ctx: Saved projection operands, mesh and autocast state.
255 gradient: Gradient of the expanded head-local KV features.
256 shared_gradient: Gradient of the gathered shared key features.
257
258 Returns:
259 Local payload, weight and optional bias gradients; no gather or mesh gradient.
260 """
261 with torch.autocast(ctx.device_type, enabled=ctx.autocast_enabled, dtype=ctx.autocast_dtype):
262 return _latent_projection_backward(ctx, gradient, shared_gradient)
263
264
265def _latent_projection_backward(ctx, gradient, shared_gradient):
266 """Keep both reduction buffers alive until their local gradient is consumed."""
267 activation, weight = ctx.saved_tensors
268 needs_payload_grad, needs_weight_grad, needs_bias_grad = ctx.needs_input_grad[:3]
269 work = None
270 if needs_payload_grad:
271 grad_latent = gradient.matmul(weight).to(activation.dtype)
272 grad_payload = torch.cat((grad_latent, shared_gradient), dim=-1)
273 send = grad_payload.movedim(1, 0).contiguous()
274 shape = list(send.shape)
275 shape[0] //= ctx.mesh.size()
276 receive = send.new_empty(shape)
277 work = dist.reduce_scatter_tensor(
278 receive, send, op=dist.ReduceOp.SUM, group=ctx.mesh.get_group(), async_op=True,
279 )
280 flat_gradient = gradient.reshape(-1, gradient.shape[-1])
281 grad_weight = None
282 if needs_weight_grad:
283 flat_activation = activation.reshape(-1, activation.shape[-1])
284 grad_weight = flat_gradient.transpose(0, 1).matmul(flat_activation)
285 grad_bias = flat_gradient.sum(0) if ctx.has_bias and needs_bias_grad else None
286 local = None
287 if work is not None:
288 work.wait()
289 local = receive.movedim(0, 1).contiguous()
290 return local, grad_weight, grad_bias, None, None