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_exchange = MLAInputExchange(self.ulysses_mesh)
key_exchange = MLAInputExchange(self.ulysses_mesh)
value_exchange = MLAInputExchange(self.ulysses_mesh)
exchanges = MLAExpandedInputExchange(query_exchange, key_exchange, value_exchange, 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(value, content, value_exchange, 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(key, state.query_latent, key_exchange, 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(query, input_gate.hidden, query_exchange, paired)
final_input = input_gate.project(gate_input)
elif not paired:
query_exchange.forward_exchange = async_ulysses_seq_to_head_launch(query, 1, 2, self.ulysses_mesh)
query, key, value = (_ExpandedInputWait.apply(final_input, exchanges) if paired else exchanges.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()
exchange = MLAInputExchange(self.ulysses_mesh)
bridge = _InputLaunch.apply(query, payload, exchange)
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 = _LatentInputWait.apply(key, value, exchange)
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."""