def _expanded_ulysses_overlap(self, module, state, positions, key_rope, input_gate, schedule_backward):
"""Send V/K/Q in order; an optional model gate extends the final wait window."""
# Frozen gate inputs retain native autograd ownership of all exchanges.
paired = schedule_backward and (input_gate is None or input_gate.defer_backward)
query_a2a = MLAInputA2AState(self.ulysses_mesh)
key_a2a = MLAInputA2AState(self.ulysses_mesh)
value_a2a = MLAInputA2AState(self.ulysses_mesh)
input_a2a = MLAExpandedInputA2AState(query_a2a, key_a2a, value_a2a, input_gate)
projected = module.kv_b_proj(state.kv_latent)
projected = projected.view(*state.kv_latent.shape[:2], self.plan.local_heads,
module.qk_nope_head_dim + module.v_head_dim)
content, value = projected.split((module.qk_nope_head_dim, module.v_head_dim), dim=-1)
content = _launch_expanded_input_a2a(value, content, value_a2a, paired)
shared_key = key_rope.unsqueeze(2).expand(-1, -1, self.plan.local_heads, -1)
key = torch.cat((content, shared_key), dim=-1)
query_latent = _launch_expanded_input_a2a(key, state.query_latent, key_a2a, paired)
query = _query(module, query_latent, positions, self.plan.local_heads).transpose(1, 2)
final_input = query
if input_gate is not None:
gate_input = _launch_expanded_input_a2a(query, input_gate.hidden, query_a2a, paired)
final_input = input_gate.project(gate_input)
elif not paired:
query_a2a.forward_a2a_handle = async_ulysses_seq_to_head_launch(query, 1, 2, self.ulysses_mesh)
query, key, value = (_ExpandedInputA2AWait.apply(final_input, input_a2a) if paired else input_a2a.wait())
return query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
def _latent_backward_overlap(self, module, state, positions, key_rope):
"""Cover inverse Q with KV backward, then latent reduction with KV wgrad."""
payload = torch.cat((state.kv_latent, key_rope), dim=-1)
pending = async_cp_allgather_launch(payload, 1, self.cp_mesh)
query = _query(module, state.query_latent, positions, self.plan.local_heads).transpose(1, 2)
# The managed projection below owns the gather's single gradient edge.
with torch.no_grad():
gathered = pending.wait()
query_a2a = MLAInputA2AState(self.ulysses_mesh)
bridge = _InputA2ALaunch.apply(query, payload, query_a2a)
heads = self.plan.compute_heads
start = self.head_rank * heads
projected, shared_key = module.kv_b_proj(
bridge, mla_head_range=(start, start + heads),
mla_gathered=gathered, mla_cp_mesh=self.cp_mesh,
)
key, value = _assemble_key_value(module, projected, shared_key, heads)
query, key, value = _LatentInputA2AWait.apply(key, value, query_a2a)
return query.transpose(1, 2), key, value
def _head_projection_request(projection: nn.Linear, head_dim: int) -> _ForwardRewriteRequest:
"""Select head rows inside the original Linear call to preserve parameter hooks."""