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"""Context-parallel scheduling for NoPE MLA with a required sigmoid gate."""
16
17from __future__ import annotations
18
19from dataclasses import dataclass
20from typing import Any
21
22# Model-owned gate math and CP scheduling use native Torch.
23import torch
24
25from hyper_parallel.distributed.context_parallel.collectives import async_ulysses_seq_to_head_launch
26from hyper_parallel.components.modules.attention.gated_multi_latent_attention.cp_gated_mla_backward_overlap import (
27 CPGatedMLAOutputLinear, GatedMLAInputState, GatedMLAOutputProjectionState, finish_gated_expanded_inputs,
28)
29from hyper_parallel.components.modules.attention.multi_latent_attention.cp_multi_latent_attention import (
30 CPMultiLatentAttentionModule,
31)
32from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention import MLALatentInputs
33from hyper_parallel.components.modules.attention.gated_multi_latent_attention.gated_multi_latent_attention import (
34 GatedMultiLatentAttentionModule,
35)
36
37
38@dataclass(frozen=True)
39class CPGatedMLAOutputState:
40 """Carry the ready local gate and any deferred joint O-exchange/Wo operation."""
41
42 gate: torch.Tensor
43 projection: GatedMLAOutputProjectionState | None = None
44
45
46class CPGatedMultiLatentAttentionModule(CPMultiLatentAttentionModule, GatedMultiLatentAttentionModule):
47 """Use shared MLA forward with NoPE/gate math and gated CP stage overrides."""
48
49 def prepare_output_projection(self) -> None:
50 """Install the existing gated output derivative inside its managed Linear."""
51 if self.cp_plan.tp_degree != 1:
52 raise ValueError("Gated MLA CP currently supports TP1 only")
53 if self.cp_plan.overlap and self.cp_plan.ulysses_degree > 1:
54 self.o_proj = CPGatedMLAOutputLinear(self.o_proj)
55
56 def _prepare_input_gate(self, hidden_states: torch.Tensor) -> GatedMLAInputState | None:
57 """Reserve a gate in the expanded pure-Ulysses input window, when enabled."""
58 plan = self.cp_plan
59 if not plan.overlap or plan.ulysses_degree <= 1:
60 return None
61 if plan.strategy != "expanded_ulysses" or plan.all_gather_degree != 1:
62 return None
63 # Frozen inputs keep native gate backward; the paired consumer otherwise
64 # releases it after the input gradient collectives have been submitted.
65 defer_gate = self._overlap_output_backward() and hidden_states.requires_grad
66 return GatedMLAInputState(hidden_states, self.project_gate, defer_gate)
67
68 def prepare_attention_inputs(
69 self, hidden_states: torch.Tensor,
70 ) -> tuple[MLALatentInputs, GatedMLAInputState | None]:
71 """Attach the input-side gate dependency to the shared latent projection stage.
72
73 Args:
74 hidden_states: Local tokens supplying down projections and the algorithm-owned gate.
75
76 Returns:
77 Normalized latents and an optional gate state for expanded pure Ulysses.
78 """
79 input_gate = self._prepare_input_gate(hidden_states)
80 state, _ = super().prepare_attention_inputs(hidden_states)
81 return state, input_gate
82
83 def finish_input_exchange(self, query: torch.Tensor, transfers: Any, overlap_backward: bool,
84 input_gate: Any) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
85 """Place algorithm-owned gate computation between Q submission and input waits.
86
87 Args:
88 query: Ready query tensor in BSND layout.
89 transfers: Pending input collective state shared with paired backward nodes.
90 overlap_backward: Whether to retain the paired input adjoints.
91 input_gate: This invocation's deferred gate, or None for ordinary scheduling.
92 """
93 if input_gate is None:
94 return super().finish_input_exchange(query, transfers, overlap_backward, None)
95 return finish_gated_expanded_inputs(query, transfers, input_gate)
96
97 def restore_attention(self, output: torch.Tensor, hidden_states: torch.Tensor,
98 output_state: GatedMLAInputState | None) -> tuple[torch.Tensor, CPGatedMLAOutputState]:
99 """Schedule token restoration and gate readiness before the managed output projection.
100
101 Args:
102 output: Head-partitioned FA output in BSND layout.
103 hidden_states: Original local tokens used by the gate algorithm.
104 output_state: Optional input-side gate state from expanded pure Ulysses.
105
106 Returns:
107 Restored output, or raw FA output when joint backward requires deferred
108 restoration; the typed state carries the gate and the deferred operation.
109 """
110 input_gate = output_state
111 output_a2a_handle = None
112 if input_gate is None and self.cp_plan.overlap and self.cp_plan.ulysses_degree > 1:
113 # The gate remains a native child-module call, with its original
114 # FSDP hooks/autograd, while O communication is in flight.
115 output_a2a_handle = async_ulysses_seq_to_head_launch(output, 2, 1, self.ulysses_mesh)
116 if input_gate is None:
117 gate = self.project_gate(hidden_states)
118 else:
119 gate, input_gate.value = input_gate.value, None
120 if self._overlap_output_backward():
121 deferred_gate = input_gate if input_gate is not None and input_gate.defer_gate_gradient else None
122 state = GatedMLAOutputProjectionState(
123 self.ulysses_mesh, self.v_head_dim, input_gate=deferred_gate, forward_a2a_handle=output_a2a_handle,
124 )
125 return output, CPGatedMLAOutputState(gate, state)
126 if output_a2a_handle is not None:
127 output = output_a2a_handle.wait()
128 else:
129 output, _ = super().restore_attention(output, hidden_states, None)
130 return output, CPGatedMLAOutputState(gate)
131
132 def project_output(self, attention_output: torch.Tensor, hidden_states: torch.Tensor,
133 output_state: CPGatedMLAOutputState) -> torch.Tensor:
134 """Apply the ready gate through the algorithm or the existing joint output Function.
135
136 Args:
137 attention_output: Restored token-local output, or raw FA output for the joint Function.
138 hidden_states: Original local tokens defining the output shape.
139 output_state: Gate and optional O-exchange/Wo state produced by restore_attention.
140 """
141 if output_state.projection is not None:
142 return self.o_proj(attention_output, mla_output_state=output_state.projection,
143 mla_output_gate=output_state.gate)
144 return super().project_output(attention_output, hidden_states, output_state.gate)