Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / attention / multi_latent_attention / cp_multi_latent_attention.py: 67%

421 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

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"""Dense MLA Ulysses with expanded QKV or shared latent-KV communication.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable, Sequence 

20from dataclasses import dataclass 

21from functools import lru_cache 

22import math 

23from typing import Any, Literal 

24 

25import torch 

26from torch import nn 

27 

28from hyper_parallel.components.modules.attention.multi_latent_attention.cp_mla_backward_overlap import ( 

29 CPMLAKVLinear, CPMLAOutputLinear, MLAOutputProjectionState, _LatentInputA2AWait, 

30) 

31from hyper_parallel.distributed.context_parallel.ulysses_overlap import ( 

32 UlyssesInputA2AState, UlyssesQKVA2AState, finish_qkv_inputs, launch_input_a2a, 

33) 

34from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention import ( 

35 MLAInputs, MLALatentInputs, MultiLatentAttentionModule, apply_mla_rope as _apply_mla_rope, 

36) 

37from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention import ( 

38 prepare_mla_attention_mask, 

39) 

40from hyper_parallel.distributed.module_binding import ParallelModuleSpec 

41from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention_family import ( 

42 validate_mla_layout, 

43) 

44from hyper_parallel.distributed.context_parallel.collectives import ( 

45 async_cp_allgather_launch, 

46) 

47from hyper_parallel.components.functional.npu_fusion_attention import ( 

48 PACKED_SEQUENCE_ARGUMENTS, resolve_packed_sequence_lengths, 

49) 

50from hyper_parallel.core.utils.communication import ( 

51 differentiable_all_to_all_single, 

52 differentiable_all_to_all_single_async, wait_async_tensor, 

53) 

54 

55 

56MLACPStrategy = Literal["expanded_ulysses", "latent_kv_head"] 

57# Preserve the existing helper import path while the mathematical implementation moves into its family. 

58apply_mla_rope = _apply_mla_rope 

59 

60MLA_CP_STRATEGIES = ("expanded_ulysses", "latent_kv_head") 

61 

62 

63@dataclass(frozen=True) 

64class MLADimensions: 

65 """Global MLA dimensions; the latent ranks are not partitioned across heads.""" 

66 

67 heads: int 

68 q_rank: int 

69 kv_rank: int 

70 nope_dim: int 

71 rope_dim: int 

72 value_dim: int 

73 

74 def __post_init__(self) -> None: 

75 for name, value in vars(self).items(): 

76 if not isinstance(value, int) or isinstance(value, bool) or value <= 0: 

77 raise ValueError(f"{name} must be a positive integer, got {value}") 

78 if self.rope_dim % 2: 

79 raise ValueError("rope_dim must be even") 

80 

81 @property 

82 def qk_dim(self) -> int: 

83 """Return the score dimension, including the decoupled RoPE band.""" 

84 return self.nope_dim + self.rope_dim 

85 

86 

87@dataclass(frozen=True) 

88class MLACPPlan: 

89 """Validated explicit execution strategy; no uncalibrated automatic selection.""" 

90 

91 dimensions: MLADimensions 

92 cp_degree: int 

93 strategy: MLACPStrategy = "expanded_ulysses" 

94 tp_degree: int = 1 

95 overlap: bool = False 

96 ulysses_degree: int | None = None 

97 kv_exchange: Literal["all_gather", "all_to_all_v"] = "all_gather" 

98 

99 def __post_init__(self) -> None: 

100 if not isinstance(self.overlap, bool): 

101 raise ValueError("overlap must be bool") 

102 if self.ulysses_degree is None: 

103 object.__setattr__(self, "ulysses_degree", self.cp_degree) 

104 for name in ("cp_degree", "tp_degree", "ulysses_degree"): 

105 value = getattr(self, name) 

106 if not isinstance(value, int) or isinstance(value, bool) or value < 1: 

107 raise ValueError(f"{name} must be a positive integer") 

108 if self.strategy not in MLA_CP_STRATEGIES: 

109 raise ValueError(f"Unknown MLA CP strategy: {self.strategy}") 

110 if self.cp_degree % self.ulysses_degree: 

111 raise ValueError("ulysses_degree must divide cp_degree") 

112 if self.dimensions.heads % (self.tp_degree * self.ulysses_degree): 

113 raise ValueError("MLA heads must be divisible by TP degree times Ulysses degree") 

114 if self.kv_exchange not in ("all_gather", "all_to_all_v"): 

115 raise ValueError("kv_exchange must be all_gather or all_to_all_v") 

116 if self.kv_exchange == "all_to_all_v" and self.all_gather_degree == 1: 

117 raise ValueError("selective KV exchange requires query-partitioned MLA CP") 

118 if self.tp_degree > 1 and self.all_gather_degree > 1: 

119 raise ValueError("MLA KV AllGather and hybrid CP currently require TP1") 

120 

121 @property 

122 def local_heads(self) -> int: 

123 """Heads in the persistent TP parameter shard, before CP redistribution.""" 

124 return self.dimensions.heads // self.tp_degree 

125 

126 @property 

127 def compute_heads(self) -> int: 

128 """Heads used by this rank's query-partition attention kernel.""" 

129 return self.local_heads // self.ulysses_degree 

130 

131 @property 

132 def all_gather_degree(self) -> int: 

133 """Number of query owners for each Ulysses head partition.""" 

134 return self.cp_degree // self.ulysses_degree 

135 

136 def validate_scale(self, scale: float) -> None: 

137 """Reject invalid scales without replacing an explicit YaRN scale. 

138 

139 Args: 

140 scale: The model's attention score scale, including any YaRN factor. 

141 

142 Raises: 

143 ValueError: If the scale is nonfinite or nonpositive. 

144 """ 

145 if not math.isfinite(scale) or scale <= 0: 

146 raise ValueError("MLA attention scaling must be finite and positive") 

147 

148 

149def mla_all_gather(tensor: torch.Tensor, sequence_dim: int, cp_mesh: Any) -> torch.Tensor: 

150 """Gather source tokens and sum all consumer gradients back to their owner. 

151 

152 Args: 

153 tensor: Equal-sized local sequence shard. 

154 sequence_dim: Dimension along which source shards are concatenated. 

155 cp_mesh: CP mesh, or None for communication-free execution. 

156 

157 Returns: 

158 Full-sequence tensor in CP group-rank order. 

159 """ 

160 if cp_mesh is None or cp_mesh.size() == 1: 

161 return tensor 

162 # Share the overlap path's SUM ReduceScatter adjoint, but wait immediately. 

163 # PyTorch's generic autograd AllGather falls back to AllToAll + local sum on 

164 # HCCL, changing BF16 reduction order when only the overlap flag changes. 

165 return async_cp_allgather_launch(tensor, sequence_dim, cp_mesh).wait() 

166 

167 

168def _validate_query_partition(causal, attention_mask): 

169 """Reject query-partition modes whose FA metadata contract is not implemented.""" 

170 if not causal or attention_mask is not None: 

171 raise ValueError("MLA KV AllGather and hybrid CP require causal attention without an explicit mask") 

172 

173 

174@dataclass(frozen=True) 

175class _CausalPartition: 

176 """One continuous query partition and its document-local causal KV prefixes.""" 

177 

178 key_begin: int 

179 key_end: int 

180 query_lengths: tuple[int, ...] 

181 key_lengths: tuple[int, ...] 

182 documents: tuple[int, ...] 

183 

184 def select(self, tensor: torch.Tensor, sequence_dim: int) -> torch.Tensor: 

185 """Keep a view of the needed prefix before either projection or attention. 

186 

187 Args: 

188 tensor: Gathered KV features in global sequence order. 

189 sequence_dim: Axis containing the gathered tokens. 

190 

191 Returns: 

192 A view of the KV interval needed by this query partition. 

193 """ 

194 return tensor.narrow(sequence_dim, self.key_begin, self.key_end - self.key_begin) 

195 

196 

197def _causal_partition(lengths, query_length, query_rank, batch) -> _CausalPartition: 

198 """Coalesce adjacent document prefixes without copying their KV tensors.""" 

199 query_begin = query_rank * query_length 

200 query_end = query_begin + query_length 

201 query_ends, key_ends = [], [] 

202 query_count = key_count = document_begin = 0 

203 key_begin = None 

204 for document_end in lengths: 

205 begin, end = max(document_begin, query_begin), min(document_end, query_end) 

206 if begin < end: 

207 if key_begin is None: 

208 key_begin = document_begin 

209 query_count += end - begin 

210 key_count += end - document_begin 

211 query_ends.append(query_count) 

212 key_ends.append(key_count) 

213 document_begin = document_end 

214 if query_count != query_length: 

215 raise ValueError("MLA document boundaries do not cover the query partition") 

216 # Continuous Q ownership makes all selected document prefixes adjacent. 

217 return _CausalPartition( 

218 key_begin, query_end, 

219 tuple(end + index * query_count for index in range(batch) for end in query_ends), 

220 tuple(end + index * key_count for index in range(batch) for end in key_ends), 

221 tuple(lengths), 

222 ) 

223 

224 

225@lru_cache(maxsize=128) 

226def _kv_exchange_ranges(documents, source_length, query_length, head_copies, degree, rank): 

227 """Cache only host intervals shared by layers; never retain activation tensors.""" 

228 destinations = tuple( 

229 _causal_partition(documents, query_length, peer // head_copies, 1) 

230 for peer in range(degree) 

231 ) 

232 start = rank * source_length 

233 sends, receives = [], [] 

234 local = destinations[rank] 

235 for peer, destination in enumerate(destinations): 

236 begin, end = max(start, destination.key_begin), min(start + source_length, destination.key_end) 

237 sends.append((begin - start, end - begin) if begin < end else (0, 0)) 

238 begin, end = max(peer * source_length, local.key_begin), min((peer + 1) * source_length, local.key_end) 

239 receives.append(max(0, end - begin)) 

240 local_only = all(peer * source_length <= item.key_begin and item.key_end <= (peer + 1) * source_length 

241 for peer, item in enumerate(destinations)) 

242 return tuple(sends), tuple(receives), local_only 

243 

244 

245@dataclass 

246class _SelectiveKVExchange: 

247 """A shared differentiable A2Av and its batch-major receive layout.""" 

248 

249 output: torch.Tensor 

250 receive_tokens: tuple[int, ...] 

251 batch: int 

252 

253 def wait(self) -> torch.Tensor: 

254 """Finish communication before rebuilding batch-major token order.""" 

255 if not self.receive_tokens: 

256 return self.output 

257 output = wait_async_tensor(self.output) 

258 parts, start = [], 0 

259 for count in self.receive_tokens: 

260 rows = self.batch * count 

261 if count: 

262 parts.append(output.narrow(0, start, rows).reshape(self.batch, count, *output.shape[1:])) 

263 start += rows 

264 return parts[0] if len(parts) == 1 else torch.cat(parts, dim=1) 

265 

266 

267def _selective_kv_launch(payload, partition, mesh, head_copies, overlap): 

268 """Send only each query owner's causal document interval, with SUM gradients through repeated slices.""" 

269 batch, source_length = payload.shape[:2] 

270 rank, degree = mesh.get_local_rank(), mesh.size() 

271 sends, receives, local_only = _kv_exchange_ranges( 

272 partition.documents, source_length, partition.query_lengths[-1] // batch, head_copies, degree, rank, 

273 ) 

274 if local_only: 

275 begin, count = sends[rank] 

276 return _SelectiveKVExchange(payload.narrow(1, begin, count), (), batch) 

277 send = torch.cat([payload.narrow(1, begin, count).flatten(0, 1) for begin, count in sends], dim=0) 

278 input_splits = [batch * count for _, count in sends] 

279 output_splits = [batch * count for count in receives] 

280 exchange = differentiable_all_to_all_single_async if overlap else differentiable_all_to_all_single 

281 output = exchange(send, input_splits, output_splits, mesh.get_group()) 

282 return _SelectiveKVExchange(output, receives, batch) 

283 

284 

285def _positions( 

286 embeddings: tuple[torch.Tensor, torch.Tensor] | None, 

287 state: MLALatentInputs, 

288 rope_dim: int, 

289) -> tuple[torch.Tensor, torch.Tensor] | None: 

290 """Validate local-token RoPE frequencies and broadcast only the batch axis.""" 

291 if embeddings is None: 

292 return None 

293 if not isinstance(embeddings, (tuple, list)) or len(embeddings) != 2: 

294 raise ValueError("position_embeddings must be a local (cos, sin) pair") 

295 batch, sequence = state.query_latent.shape[:2] 

296 parts = [] 

297 for tensor in embeddings: 

298 if tensor.ndim == 2: 

299 tensor = tensor.unsqueeze(0) 

300 if tensor.shape not in ((1, sequence, rope_dim), (batch, sequence, rope_dim)): 

301 raise ValueError("RoPE cos/sin must describe local tokens with shape [B, S_local, rope_dim]") 

302 if tensor.requires_grad: 

303 raise ValueError("MLA CP currently requires non-trainable RoPE frequencies") 

304 if tensor.device != state.query_latent.device: 

305 raise ValueError("RoPE and MLA activations must be on the same device") 

306 parts.append(tensor.expand(batch, -1, -1)) 

307 return tuple(parts) 

308 

309 

310def _validate_mask( 

311 mask: torch.Tensor | None, 

312 lengths: Sequence[int] | None, 

313 batch: int, 

314 sequence: int, 

315 device: torch.device, 

316) -> None: 

317 """Require global boolean masks and reject unsupported packed-mask combinations.""" 

318 if mask is None: 

319 return 

320 if lengths is not None: 

321 raise ValueError("packed MLA CP currently accepts document causal/noncausal masks only") 

322 if mask.dtype != torch.bool: 

323 raise ValueError("MLA CP masks must be boolean (True=allowed); additive bias is not supported") 

324 valid = ( 

325 mask.ndim == 2 and mask.shape == (sequence, sequence) 

326 or mask.ndim == 4 and mask.shape[0] in (1, batch) 

327 and mask.shape[1] == 1 and mask.shape[-2:] == (sequence, sequence) 

328 ) 

329 if not valid or mask.device != device: 

330 raise ValueError("attention_mask must cover global Q/K: [S, S] or [B|1, 1, S, S], on the input device") 

331 

332 

333def _validate_forward_kwargs(kwargs, position_embeddings): 

334 """Validate forwarded model options before routing any latent.""" 

335 position_ids = kwargs.pop("position_ids", None) 

336 if position_ids is not None and position_embeddings is None: 

337 raise ValueError("position_ids require precomputed local position_embeddings in MLA CP") 

338 kwargs.pop("cache_position", None) 

339 if kwargs.pop("use_cache", False) or kwargs.pop("output_attentions", False): 

340 raise ValueError("MLA CP does not return KV caches or attention weights") 

341 if kwargs: 

342 raise ValueError(f"Unsupported MLA CP forward arguments: {sorted(kwargs)}") 

343 

344 

345def _validate_state(module: nn.Module, plan: MLACPPlan, state: MLALatentInputs) -> None: 

346 """Check latent shape and NPU kernel requirements before collectives.""" 

347 dimensions = plan.dimensions 

348 query_latent, kv_latent, key_rope = state.query_latent, state.kv_latent, state.key_rope 

349 if query_latent.ndim != 3: 

350 raise ValueError("MLA CP latents must have BSR layout") 

351 batch, sequence = query_latent.shape[:2] 

352 if batch < 1 or sequence < 1: 

353 raise ValueError("MLA CP requires nonempty batches and sequence shards") 

354 for tensor, width in ((query_latent, dimensions.q_rank), (kv_latent, dimensions.kv_rank), 

355 (key_rope, dimensions.rope_dim)): 

356 if (tensor.shape != (batch, sequence, width) or tensor.device != query_latent.device 

357 or tensor.dtype != query_latent.dtype): 

358 raise ValueError("MLA CP latent shapes/devices/dtypes do not match the plan") 

359 if module.training and module.attention_dropout != 0: 

360 raise ValueError("MLA CP requires attention dropout=0") 

361 plan.validate_scale(module.scaling) 

362 if query_latent.device.type != "npu" or query_latent.dtype not in (torch.float16, torch.bfloat16): 

363 raise ValueError("NPU MLA CP requires NPU BF16/FP16 activations") 

364 if dimensions.value_dim > dimensions.qk_dim: 

365 raise ValueError("NPU MLA CP requires value_dim <= qk_dim") 

366 

367 

368class CPMultiLatentAttentionModule(MultiLatentAttentionModule): 

369 """Exchange MLA operands at class-defined stages of the shared algorithm. 

370 

371 CP controls token/head ownership and projection readiness. All projection, 

372 position and attention mathematics belong to the inherited algorithm. 

373 """ 

374 

375 def __init__(self, *, module: nn.Module | None = None, config: Any = None, 

376 module_fqn: str = "", context: Any = None, 

377 strategy: str = "expanded_ulysses", overlap: bool = False, 

378 ulysses_degree: int | None = None, kv_exchange: str = "all_gather", 

379 rotary_fn: Callable | None = None, attention_interface: Callable | None = None) -> None: 

380 """Choose CP ownership before parameter sharding and FSDP construction. 

381 

382 Args: 

383 module: Optional source attention with parameters to retain. 

384 config: Native mathematical configuration, exclusive with module. 

385 module_fqn: Construction context supplied by the family framework. 

386 context: Logical CP and TP sizes before resources are bound. 

387 strategy: Expanded QKV or latent KV representation for communication. 

388 overlap: Enable the existing supported forward/backward schedules. 

389 ulysses_degree: CP ranks assigned to attention heads. 

390 kv_exchange: AllGather or selective variable-size KV exchange. 

391 rotary_fn: Optional BSND position callback; must preserve shape and dtype. 

392 attention_interface: Optional FA callback returning BSND output and weights. 

393 """ 

394 del module_fqn 

395 for name, callback in (("rotary_fn", rotary_fn), ("attention_interface", attention_interface)): 

396 if callback is not None and not callable(callback): 

397 raise TypeError(f"{name} must be callable") 

398 super().__init__(module=module, config=config) 

399 self.rotary_fn = rotary_fn 

400 if attention_interface is not None: 

401 self.attention_interface = attention_interface 

402 if self.attention_dropout != 0 or self.sliding_window is not None: 

403 raise ValueError("MLA CP requires zero dropout and no implicit sliding window") 

404 if type(self.q_b_proj) is not nn.Linear: # pylint: disable=unidiomatic-typecheck 

405 raise ValueError("MLA CP requires a plain Linear query up-projection") 

406 dimensions = MLADimensions(self.config.num_attention_heads, self.q_lora_rank, self.kv_lora_rank, 

407 self.qk_nope_head_dim, self.qk_rope_head_dim, self.v_head_dim) 

408 cp_degree = (context or {}).get("cp_size", 1) 

409 self.cp_plan = MLACPPlan(dimensions, cp_degree, strategy=strategy, tp_degree=(context or {}).get("tp_size", 1), 

410 overlap=overlap, ulysses_degree=ulysses_degree, kv_exchange=kv_exchange) 

411 self.cp_plan.validate_scale(self.scaling) 

412 self.cp_context = self.ulysses_context = self.query_context = None 

413 self.cp_mesh = self.ulysses_mesh = self.all_gather_mesh = None 

414 self.query_rank = self.head_rank = 0 

415 self.kv_b_proj = CPMLAKVLinear(self.kv_b_proj, self.qk_nope_head_dim + self.v_head_dim) 

416 self.prepare_output_projection() 

417 

418 def prepare_output_projection(self) -> None: 

419 """Keep the existing managed dO/wgrad scheduling boundary.""" 

420 if self.cp_plan.overlap and self.cp_plan.tp_degree == 1 and self.cp_plan.ulysses_degree > 1: 

421 self.o_proj = CPMLAOutputLinear(self.o_proj) 

422 

423 def parallel_module_spec(self) -> ParallelModuleSpec: 

424 """Declare operand/output stages; framework TP still owns its outer ports.""" 

425 return ParallelModuleSpec( 

426 "attention.mla.cp", "cp", 

427 {"exchange_attention": ("state",), 

428 "restore_attention": ("output", "hidden_states", "output_state"), 

429 "project_output": ("attention_output", "hidden_states", "output_state")}, 

430 validate=validate_mla_layout, 

431 ) 

432 

433 def bind_parallel(self, binding: Any) -> None: 

434 """Borrow CP transport directly, without installing a whole-layer executor. 

435 

436 Args: 

437 binding: Framework-owned CP context, including existing process groups. 

438 """ 

439 context = binding.cp_context 

440 if context is None: 

441 raise ValueError("MLA CP requires a bound CPContext") 

442 if context.size != self.cp_plan.cp_degree: 

443 raise ValueError("MLACPPlan degree must match the CP mesh") 

444 self.cp_context, self.cp_mesh = context, context.mesh 

445 self.query_rank, self.head_rank = divmod(context.rank, self.cp_plan.ulysses_degree) 

446 self.ulysses_context, self.query_context = context.split(self.cp_plan.ulysses_degree) 

447 self.ulysses_mesh, self.all_gather_mesh = self.ulysses_context.mesh, self.query_context.mesh 

448 

449 def _overlap_output_backward(self) -> bool: 

450 """Keep the existing TP1 output adjoint; input pairing also requires pure Ulysses.""" 

451 plan = self.cp_plan 

452 return plan.overlap and plan.tp_degree == 1 and plan.ulysses_degree > 1 and torch.is_grad_enabled() 

453 

454 def project_output(self, attention_output: torch.Tensor, hidden_states: torch.Tensor, 

455 output_state: Any) -> torch.Tensor: 

456 """Consume deferred restoration inside the existing managed output Function. 

457 

458 Args: 

459 attention_output: Local BSND output, or raw head-partitioned FA output when deferred. 

460 hidden_states: Original local tokens defining the output shape. 

461 output_state: MLAOutputProjectionState for joint O exchange/Wo, or algorithm state. 

462 """ 

463 if isinstance(output_state, MLAOutputProjectionState): 

464 return self.o_proj(attention_output, mla_output_state=output_state) 

465 return super().project_output(attention_output, hidden_states, output_state) 

466 

467 def validate_inputs(self, past_key_values: Any) -> None: 

468 """Reject unsupported calls before projection or collective submission. 

469 

470 Args: 

471 past_key_values: Must be None for CP training with fixed token ownership. 

472 """ 

473 if past_key_values is not None: 

474 raise ValueError("MLA CP training does not support a KV cache") 

475 if self.cp_context is None: 

476 raise RuntimeError("MLA CP resources must be bound before forward") 

477 

478 def exchange_attention(self, state: MLALatentInputs, 

479 position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, 

480 attention_mask: torch.Tensor | None = None, past_key_values: Any = None, 

481 actual_seq_len: torch.Tensor | Sequence[int] | None = None, *, 

482 output_state: Any = None, is_causal: bool | None = None, 

483 **kwargs: Any) -> MLAInputs: 

484 """Schedule algorithm projections around CP transfers and return ready FA operands. 

485 

486 Expanded exchange follows projection; latent KV exchange precedes the 

487 head-selective KV projection. This stage schedules the shared math methods, 

488 not just collectives. The inherited forward owns the subsequent FA call. 

489 

490 Args: 

491 state: Already-computed algorithm latents and shared-key features. 

492 position_embeddings: Local RoPE tables, already discarded by NoPE algorithms. 

493 attention_mask: Optional global mask. 

494 past_key_values: Unsupported by CP training. 

495 actual_seq_len: Global cumulative document endpoints. 

496 output_state: Optional input-side gate dependency for this invocation. 

497 is_causal: Optional causal override. 

498 **kwargs: Supported packed and model attention options. 

499 """ 

500 self.validate_inputs(past_key_values) 

501 mask, positions, partition, options = self._attention_layout( 

502 state, position_embeddings, attention_mask, actual_seq_len, is_causal, kwargs) 

503 rotary_fn = self.apply_position if self.rotary_fn is None else self.rotary_fn 

504 rotated_key = rotary_fn(state.key_rope.unsqueeze(2), positions, 

505 interleaved=self.rotary_interleaved).squeeze(2) 

506 overlap_input = self._overlap_output_backward() and self.cp_plan.all_gather_degree == 1 

507 if output_state is not None: 

508 overlap_input = output_state.defer_gate_gradient 

509 query, key, value = self._prepare_distributed_inputs( 

510 state, positions, rotated_key, partition, overlap_input, output_state, rotary_fn) 

511 return MLAInputs(query, key, value, mask, options, output_state) 

512 

513 def _attention_layout(self, state, positions, attention_mask, actual_seq_len, is_causal, kwargs): 

514 """Resolve global document ownership before submitting any collective.""" 

515 packed_kwargs = {name: kwargs.pop(name) for name in PACKED_SEQUENCE_ARGUMENTS if name in kwargs} 

516 packed_kwargs["actual_seq_len"] = actual_seq_len 

517 _validate_forward_kwargs(kwargs, positions) 

518 dimensions, degree = self.cp_plan.dimensions, self.cp_plan.cp_degree 

519 batch, sequence = state.query_latent.shape[:2] 

520 lengths, key_lengths = resolve_packed_sequence_lengths( 

521 packed_kwargs, batch * sequence * degree, batch * sequence * degree) 

522 if lengths is not None and batch != 1: 

523 raise ValueError("packed MLA CP currently requires batch_size=1") 

524 if lengths != key_lengths: 

525 raise ValueError("MLA CP requires matching global query and key document boundaries") 

526 causal = self.is_causal if is_causal is None else is_causal 

527 if not isinstance(causal, bool): 

528 raise ValueError("is_causal must be bool") 

529 _validate_mask(attention_mask, lengths, batch, sequence * degree, state.query_latent.device) 

530 attention_mask = prepare_mla_attention_mask(attention_mask, sequence * degree, sequence * degree) 

531 partition = None 

532 if self.cp_plan.all_gather_degree > 1: 

533 _validate_query_partition(causal, attention_mask) 

534 partition = _causal_partition( 

535 lengths or (sequence * degree,), sequence * self.cp_plan.ulysses_degree, self.query_rank, batch) 

536 lengths, key_lengths = partition.query_lengths, partition.key_lengths 

537 positions = _positions(positions, state, dimensions.rope_dim) 

538 _validate_state(self, self.cp_plan, state) 

539 options = {"dropout": 0.0, "sliding_window": None, "is_causal": causal, 

540 "actual_seq_qlen": lengths, "actual_seq_kvlen": key_lengths, 

541 "pre_tokens": 2147483647, "next_tokens": 0 if causal else 2147483647, 

542 "mla_head_offset": self.head_rank * self.cp_plan.compute_heads, 

543 "mla_local_heads": self.cp_plan.local_heads} 

544 return attention_mask, positions, partition, options 

545 

546 def _prepare_distributed_inputs(self, state, positions, key_rope, partition, 

547 overlap_input_backward, input_gate, rotary_fn): 

548 """Select input preparation; paired input backward requires pure Ulysses. 

549 

550 Forward overlap also supports KV AllGather and hybrid CP. Those paths 

551 retain native input collective adjoints; their output dO overlap is 

552 selected independently by the output stage. 

553 """ 

554 use_forward_overlap = self.cp_plan.overlap and self.cp_plan.cp_degree > 1 

555 pure_ulysses = self.cp_plan.all_gather_degree == 1 

556 expanded = self.cp_plan.strategy == "expanded_ulysses" 

557 supports_input_gate = use_forward_overlap and pure_ulysses and expanded 

558 if input_gate is not None and not supports_input_gate: 

559 raise ValueError("Input gate overlap requires expanded pure Ulysses with overlap enabled") 

560 if overlap_input_backward and not pure_ulysses: 

561 raise ValueError("Paired MLA input backward currently requires pure Ulysses") 

562 if not use_forward_overlap: 

563 query = self.project_query( 

564 state.query_latent, positions, heads=self.cp_plan.local_heads, rotary_fn=rotary_fn, 

565 ) 

566 prepare = self._expanded_inputs if expanded or self.cp_plan.cp_degree == 1 else self._latent_inputs 

567 return prepare(state, query, key_rope, partition) 

568 # Pure Ulysses has no outer KV AllGather. Expanded Q/K/V use the same 

569 # V/K/Q forward order with or without a gate; overlap_input_backward 

570 # selects paired input gradients versus the native collective adjoints. 

571 if pure_ulysses and expanded: 

572 return self._prepare_expanded_ulysses_inputs( 

573 state, positions, key_rope, input_gate, overlap_input_backward, rotary_fn, 

574 ) 

575 if overlap_input_backward: 

576 # Expanded has returned above and AG/hybrid were rejected earlier: 

577 # this is latent pure Ulysses, pairing Q A2A with KV projection/RS. 

578 return self._prepare_latent_ulysses_inputs(state, positions, key_rope, rotary_fn) 

579 # AG/hybrid inputs and forward-only latent Ulysses use native adjoints. 

580 prepare = self._expanded_overlap_inputs if expanded else self._latent_overlap_inputs 

581 return prepare(state, positions, key_rope, partition, rotary_fn=rotary_fn) 

582 

583 def restore_attention(self, output: torch.Tensor, hidden_states: torch.Tensor, 

584 output_state: Any) -> tuple[torch.Tensor, Any]: 

585 """Restore query ownership, or defer O exchange to the joint output Function. 

586 

587 Args: 

588 output: Attention result in BSND head-partitioned layout. 

589 hidden_states: Original local input, available to gated scheduling overrides. 

590 output_state: Algorithm-owned invocation state. 

591 

592 Returns: 

593 Local BSND output and algorithm state, or unchanged FA output with an 

594 MLAOutputProjectionState. The latter keeps O A2A and Wo in one autograd 

595 Function, allowing backward dO communication to overlap Wo wgrad. 

596 """ 

597 del hidden_states 

598 if self._overlap_output_backward(): 

599 return output, MLAOutputProjectionState(self.ulysses_mesh, self.v_head_dim) 

600 batch, sequence = output.shape[:2] 

601 sequence //= self.cp_plan.ulysses_degree 

602 if self.cp_plan.ulysses_degree > 1: 

603 output = self.ulysses_context.head_to_sequence(output) 

604 expected = (batch, sequence, self.cp_plan.local_heads, self.cp_plan.dimensions.value_dim) 

605 if tuple(output.shape) != expected: 

606 raise RuntimeError(f"MLA CP output has shape {tuple(output.shape)}, expected {expected}") 

607 return output, output_state 

608 

609 def _expanded_inputs(self, state, query, key_rope, partition=None): 

610 """Pack unequal-width QKV into one sequence-to-head exchange.""" 

611 key, value = self.project_key_value(state.kv_latent, key_rope, heads=self.cp_plan.local_heads) 

612 return self._exchange_qkv(query, key, value, partition) 

613 

614 def _exchange_qkv(self, query, key, value, partition): 

615 """Exchange completed expanded operands without performing projection math.""" 

616 if self.cp_plan.ulysses_degree > 1: 

617 widths = (query.shape[-1], key.shape[-1], value.shape[-1]) 

618 payload = torch.cat(tuple(tensor.transpose(1, 2) for tensor in (query, key, value)), dim=-1) 

619 payload = self.ulysses_context.sequence_to_head(payload) 

620 query, key, value = (tensor.transpose(1, 2) for tensor in payload.split(widths, dim=-1)) 

621 if self.cp_plan.all_gather_degree > 1: 

622 widths = (key.shape[-1], value.shape[-1]) 

623 payload = torch.cat((key.transpose(1, 2), value.transpose(1, 2)), dim=-1) 

624 if self.cp_plan.kv_exchange == "all_to_all_v": 

625 payload = _selective_kv_launch(payload, partition, self.all_gather_mesh, 1, False).wait() 

626 else: 

627 payload = partition.select(self.query_context.gather_sequence(payload)[0], 1) 

628 key, value = (tensor.transpose(1, 2) for tensor in payload.split(widths, dim=-1)) 

629 return query, key, value 

630 

631 def _latent_inputs(self, state, query, key_rope, partition=None): 

632 """Exchange Q heads, gather shared KV latents, then expand only owned heads.""" 

633 if self.cp_plan.ulysses_degree > 1: 

634 query = self.ulysses_context.sequence_to_head(query, seq_dim=2, head_dim=1) 

635 payload = torch.cat((state.kv_latent, key_rope), dim=-1) 

636 payload = self._launch_latent_kv(payload, partition, overlap=False).wait() 

637 return query, *self._expand_latent(payload, partition) 

638 

639 def _launch_latent_kv(self, payload, partition=None, *, overlap=True): 

640 """Exchange compressed KV before the algorithm's head-selective expansion.""" 

641 if self.cp_plan.kv_exchange == "all_to_all_v": 

642 return _selective_kv_launch(payload, partition, self.cp_mesh, self.cp_plan.ulysses_degree, overlap) 

643 return self.cp_context.launch_gather_sequence(payload).collective 

644 

645 def _expand_latent(self, payload, partition=None): 

646 """Keep the same managed head-selective projection for both communication schedules.""" 

647 if partition is not None and self.cp_plan.kv_exchange == "all_gather": 

648 payload = partition.select(payload, 1) 

649 dimensions = self.cp_plan.dimensions 

650 heads = self.cp_plan.compute_heads 

651 start = self.head_rank * heads 

652 kv_latent, key_rope = payload.split((dimensions.kv_rank, dimensions.rope_dim), dim=-1) 

653 # A contiguous latent preserves the native Linear bias-fusion path after payload splitting. 

654 return self.project_key_value( 

655 kv_latent.contiguous(), key_rope, heads=heads, head_range=(start, start + heads), 

656 ) 

657 

658 def _expanded_overlap_inputs(self, state, positions, key_rope, partition=None, *, rotary_fn): 

659 """Overlap KV transfer with Q preparation, respecting the two-stage hybrid dependency.""" 

660 key, value = self.project_key_value(state.kv_latent, key_rope, heads=self.cp_plan.local_heads) 

661 payload = torch.cat((key.transpose(1, 2), value.transpose(1, 2)), dim=-1) 

662 use_ulysses = self.cp_plan.ulysses_degree > 1 

663 if use_ulysses: 

664 kv_transfer_handle = self.ulysses_context.launch_sequence_to_head(payload) 

665 else: 

666 kv_transfer_handle = self._launch_expanded_kv(payload, partition) 

667 query = self.project_query(state.query_latent, positions, heads=self.cp_plan.local_heads, rotary_fn=rotary_fn) 

668 query_a2a_handle = (self.ulysses_context.launch_sequence_to_head(query.transpose(1, 2)) 

669 if use_ulysses else None) 

670 payload = kv_transfer_handle.wait() 

671 if use_ulysses and self.cp_plan.all_gather_degree > 1: 

672 payload = self._launch_expanded_kv(payload, partition).wait() 

673 if query_a2a_handle is not None: 

674 query = query_a2a_handle.wait().transpose(1, 2) 

675 if partition is not None and self.cp_plan.kv_exchange == "all_gather": 

676 payload = partition.select(payload, 1) 

677 key, value = payload.split((self.qk_head_dim, self.v_head_dim), dim=-1) 

678 return query, key.transpose(1, 2), value.transpose(1, 2) 

679 

680 def _launch_expanded_kv(self, payload, partition): 

681 """Complete the sequence dimension after Ulysses has selected this head shard.""" 

682 if self.cp_plan.kv_exchange == "all_to_all_v": 

683 return _selective_kv_launch(payload, partition, self.all_gather_mesh, 1, True) 

684 return self.query_context.launch_gather_sequence(payload).collective 

685 

686 def _latent_overlap_inputs(self, state, positions, key_rope, partition=None, *, rotary_fn): 

687 """Cover latent transfer with Q preparation, then Q A2A with KV expansion.""" 

688 payload = torch.cat((state.kv_latent, key_rope), dim=-1) 

689 kv_transfer_handle = self._launch_latent_kv(payload, partition) 

690 query = self.project_query(state.query_latent, positions, heads=self.cp_plan.local_heads, rotary_fn=rotary_fn) 

691 payload = kv_transfer_handle.wait() 

692 query_a2a_handle = (self.ulysses_context.launch_sequence_to_head(query.transpose(1, 2)) 

693 if self.cp_plan.ulysses_degree > 1 else None) 

694 key, value = self._expand_latent(payload, partition) 

695 if query_a2a_handle is not None: 

696 query = query_a2a_handle.wait().transpose(1, 2) 

697 return query, key, value 

698 

699 def _prepare_expanded_ulysses_inputs(self, state, positions, key_rope, input_gate, 

700 overlap_input_backward, rotary_fn): 

701 """Prepare expanded Q/K/V in V/K/Q order and attach the selected adjoints.""" 

702 input_a2a = UlyssesQKVA2AState( 

703 query=UlyssesInputA2AState(self.ulysses_mesh), 

704 key=UlyssesInputA2AState(self.ulysses_mesh), 

705 value=UlyssesInputA2AState(self.ulysses_mesh), 

706 ) 

707 # V needs no positional transform: it is ready as soon as KV up-projection 

708 # is split. Shared-K positional math was already applied by the caller. 

709 key_nope, value = self.project_key_value_parts(state.kv_latent, heads=self.cp_plan.local_heads) 

710 # Keep K assembly inside V's communication window. 

711 key_nope = launch_input_a2a( 

712 value, key_nope, input_a2a.value, overlap_backward=overlap_input_backward, 

713 ) 

714 key = self.assemble_key(key_nope, key_rope) 

715 # K is complete; Q projection and its model-defined rotation can cover it. 

716 query_latent = launch_input_a2a( 

717 key, state.query_latent, input_a2a.key, overlap_backward=overlap_input_backward, 

718 ) 

719 query = self.project_query( 

720 query_latent, positions, heads=self.cp_plan.local_heads, rotary_fn=rotary_fn, 

721 ).transpose(1, 2) 

722 query, key, value = self.finish_input_exchange(query, input_a2a, overlap_input_backward, input_gate) 

723 return query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2) 

724 

725 def finish_input_exchange(self, query: torch.Tensor, transfers: Any, overlap_backward: bool, 

726 input_gate: Any) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

727 """Finish ordinary Q/K/V; gated MLA overrides this model-specific boundary. 

728 

729 Args: 

730 query: Expanded query whose exchange has not yet been launched. 

731 transfers: Pending key/value exchanges and their backward state. 

732 overlap_backward: Pair backward communication with independent projections. 

733 input_gate: Must be None for ordinary MLA. 

734 """ 

735 if input_gate is not None: 

736 raise ValueError("Ordinary MLA cannot consume a gated input dependency") 

737 return finish_qkv_inputs(query, transfers, overlap_backward) 

738 

739 def _prepare_latent_ulysses_inputs(self, state, positions, key_rope, rotary_fn): 

740 """Prepare latent Ulysses inputs and pair their Q/KV backward dependencies.""" 

741 payload = torch.cat((state.kv_latent, key_rope), dim=-1) 

742 kv_all_gather_handle = self._launch_latent_kv(payload) 

743 query = self.project_query( 

744 state.query_latent, positions, heads=self.cp_plan.local_heads, rotary_fn=rotary_fn, 

745 ).transpose(1, 2) 

746 # wait() normally adds the default AllGather autograd node. Instead, 

747 # _LatentKVLinear launches SUM RS before KV wgrad and returns dPayload 

748 # via kv_input. Keep this numeric buffer off the default gradient path. 

749 with torch.no_grad(): 

750 gathered = kv_all_gather_handle.wait() 

751 query_a2a = UlyssesInputA2AState(self.ulysses_mesh) 

752 # Same payload value, with Q's inverse A2A bracketing its KV backward. 

753 kv_input = launch_input_a2a(query, payload, query_a2a, overlap_backward=True) 

754 heads = self.cp_plan.compute_heads 

755 start = self.head_rank * heads 

756 projected, shared_key = self.kv_b_proj( 

757 kv_input, mla_head_range=(start, start + heads), 

758 mla_gathered=gathered, mla_cp_mesh=self.cp_mesh, 

759 ) 

760 key, value = self.assemble_key_value(projected, shared_key, heads=heads) 

761 query, key, value = _LatentInputA2AWait.apply(key, value, query_a2a) 

762 return query.transpose(1, 2), key, value