Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / context_parallel / wrappers.py: 67%

445 statements  

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

1# Copyright 2025-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.wrappers: built-in CP-aware inner attention wrappers (public, explicit injection). 

16 

17Since the explicit-injection rework the framework NEVER picks a CP wrapper 

18automatically: the built-ins below are referenced explicitly — by 

19registry name in an internal plan, by callable, or by a public forward 

20replacement pointing at one of these functions: 

21 

22.. code-block:: yaml 

23 

24 plan_overrides: 

25 - match: "*.self_attn.forward" 

26 when: cp 

27 replace: 

28 kind: method 

29 implementation: hyper_parallel.distributed.context_parallel.wrappers.sdpa_hf_cp_wrapper 

30 

31Wrapper contract (also the Target factory contract — at apply time the 

32Target is built with its declared context, filled by name):: 

33 

34 @inner_wrapper 

35 fn(target_module, mesh, tp_mesh, cp_mesh, ep_mesh, <configured params...>) 

36 

37The ``@inner_wrapper`` decorator is MANDATORY (injection discipline, 

38see recipe_spec.py): the mesh family (``mesh``/``tp_mesh``/``cp_mesh``/ 

39``ep_mesh``) plus the anchor ``target_module`` are REQUIRED context 

40params, ALL filled by the framework at apply time (None for inactive 

41axes) — the user just uses them. 

42Undecorated wrappers fail fast in the resolution chain; *args/**kwargs 

43are forbidden. In-repo wrappers RETURN the replacement — a forward 

44callable or _ForwardRewriteRequest(s) — and the forward rewriter 

45validates, installs and rolls back (05 §15.2.3: module.forward is 

46assigned only by distributed/_builder/forward_rewriter.py); external 

47wrappers may still replace ``target_module.forward`` in place and return 

48None. The replaced forward must accept the original forward's params 

49(validated at apply time). 

50 

51- ``sdpa_qkv_cp_wrapper``: NeMo convention ``forward(q, k, v, ...)`` — explicit 

52 K/V all-gather + D-04 offset-aware causal mask (fixes the is_causal 

53 alignment error under CP); 

54- ``sdpa_hf_cp_wrapper``: HF convention ``forward(hidden_states, ...)`` — 

55 primitive interception of ``F.scaled_dot_product_attention`` (reuses HF 

56 projections/RoPE), with misfire detection (raises if no call is 

57 intercepted); 

58- ``flex_qkv_cp_wrapper`` / ``flex_hf_cp_wrapper``: the two isomorphic 

59 FlexAttention entries (block_mask must be built for the global kv length). 

60- ``*_ulysses_cp_wrapper``: Pure Ulysses variants that exchange Q/K/V from 

61 sequence shards to head shards before attention and restore the local 

62 sequence shard afterward. 

63- ``*_hybrid_cp_wrapper``: local-tensor Hybrid variants that run Ulysses 

64 all-to-all inside each subgroup and K/V all-gather across the complementary 

65 Colossal subgroup. 

66- ``sdpa_*_load_balance_cp_wrapper``: local-tensor Colossal Head-Tail variants 

67 for Q exchange, K/V all-gather, dual SDPA execution, output restoration, 

68 and backward communication. 

69 

70 

71Users may register their own named schemes:: 

72 

73 INNER_WRAPPER_REGISTRY["my_flash"] = my_fn 

74 

75after which ``spec.inner_wrapper="my_flash"`` references it by name. 

76 

77The ``is_*_attention`` helpers are public utilities for authors of custom 

78wrappers (choosing a scheme programmatically); the framework itself no 

79longer dispatches heuristically on them. 

80""" 

81 

82import functools 

83import importlib 

84import inspect 

85import logging 

86from typing import Any, Callable 

87 

88import torch 

89import torch.nn.functional as F 

90from torch.nn import Module 

91 

92from hyper_parallel.distributed._builder.forward_rewriter import ( 

93 _ForwardRewriteRequest, 

94) 

95from hyper_parallel.distributed.context_parallel.collectives import ( 

96 _build_hybrid_cp_submeshes, 

97 _ULYSSES_WRAPPED_FLAG, 

98 _UlyssesContext, 

99 _slice_sequence, 

100 _validate_ulysses_head_counts, 

101 flex_cp_allgather, 

102 hybrid_cp_attention, 

103 ulysses_head_to_seq, 

104 ulysses_seq_to_head, 

105) 

106from hyper_parallel.distributed.context_parallel.attention import ( 

107 _cp_offset_causal_mask, 

108 _dsa_cp_alltoall, 

109 _mla_cp_alltoall, 

110 _mome_cp_halo_exchange, 

111 head_tail_load_balance_attention, 

112) 

113from hyper_parallel.distributed.recipe_spec import ( 

114 inner_wrapper, 

115) 

116 

117logger = logging.getLogger(__name__) 

118 

119 

120# ──────────────────────────────────────────────────────────────────────────── 

121# Style-detection helpers (public utilities for custom wrapper authors) 

122# ──────────────────────────────────────────────────────────────────────────── 

123 

124def _attn_implementation(module): 

125 cfg = getattr(module, "config", None) 

126 impl = getattr(cfg, "_attn_implementation", None) 

127 if impl is None and isinstance(cfg, dict): 

128 impl = cfg.get("attn_implementation") 

129 return impl 

130 

131 

132def is_sdpa_attention(module: Any) -> bool: 

133 """True when the module is configured for or named as SDPA attention.""" 

134 impl = _attn_implementation(module) 

135 return (impl == "sdpa") or ("SdpaAttention" in type(module).__name__) 

136 

137 

138def is_flex_attention(module: Any) -> bool: 

139 """True when the module is configured for or named as FlexAttention.""" 

140 impl = _attn_implementation(module) 

141 return (impl == "flex_attention") or ("FlexAttention" in type(module).__name__) 

142 

143 

144def is_hf_style_attention(module: Any) -> bool: 

145 """HF style (forward(hidden_states,...), projections inside forward) -> the primitive-interception path.""" 

146 has_proj = (hasattr(module, "q_proj") and hasattr(module, "k_proj") 

147 and hasattr(module, "v_proj")) 

148 if not has_proj: 

149 return False 

150 try: 

151 sig = inspect.signature(module.forward) 

152 first_param = next(iter(sig.parameters.values()), None) 

153 return first_param is not None and first_param.name == "hidden_states" 

154 except (ValueError, TypeError): 

155 return type(module).__name__.endswith("Attention") 

156 

157 

158# ──────────────────────────────────────────────────────────────────────────── 

159# CP-aware SDPA core (K/V all-gather + D-04 offset causal mask) 

160# ──────────────────────────────────────────────────────────────────────────── 

161 

162def _prepare_cp_sdpa_kwargs( 

163 kwargs: dict[str, Any], *, q_len: int, kv_len: int, 

164 query_offset: int, device: Any) -> dict[str, Any]: 

165 """Adapt a complete SDPA mask to one CP-local query interval.""" 

166 call_kwargs = dict(kwargs) 

167 attention_mask = call_kwargs.get("attn_mask") 

168 if attention_mask is not None: 

169 if not isinstance(attention_mask, torch.Tensor): 

170 raise TypeError( 

171 "CP SDPA attn_mask must be a Tensor or None, got " 

172 f"{type(attention_mask).__name__}" 

173 ) 

174 if attention_mask.ndim < 2: 

175 raise ValueError( 

176 "CP SDPA attn_mask must expose query and KV dimensions, got " 

177 f"shape {tuple(attention_mask.shape)}" 

178 ) 

179 if attention_mask.shape[-1] != kv_len: 

180 raise ValueError( 

181 "CP SDPA attn_mask must cover the complete KV sequence: " 

182 f"mask KV length={attention_mask.shape[-1]}, expected {kv_len}" 

183 ) 

184 mask_q_len = attention_mask.shape[-2] 

185 if mask_q_len != q_len: 

186 if mask_q_len < query_offset + q_len: 

187 raise ValueError( 

188 "CP SDPA attn_mask does not cover the required query range " 

189 f"[{query_offset}, {query_offset + q_len}); mask query " 

190 f"length={mask_q_len}" 

191 ) 

192 attention_mask = attention_mask.narrow( 

193 -2, query_offset, q_len 

194 ) 

195 call_kwargs["attn_mask"] = attention_mask 

196 if call_kwargs.get("is_causal"): 

197 call_kwargs["is_causal"] = False 

198 return call_kwargs 

199 

200 if call_kwargs.get("is_causal"): 

201 call_kwargs["is_causal"] = False 

202 call_kwargs["attn_mask"] = _cp_offset_causal_mask( 

203 q_len, kv_len, query_offset, device 

204 ) 

205 return call_kwargs 

206 

207 

208def _prepare_head_tail_sdpa_kwargs( 

209 kwargs: dict[str, Any], query: Any, key: Any, 

210 cp_mesh: Any) -> tuple[dict[str, Any], dict[str, Any]]: 

211 """Prepare complete-mask query rows for both Head-Tail attention calls.""" 

212 local_q_len = query.shape[2] 

213 if local_q_len % 2: 

214 raise ValueError( 

215 "Head-Tail load balance requires an even local Q sequence " 

216 f"length, got {local_q_len}" 

217 ) 

218 half_q_len = local_q_len // 2 

219 local_rank = cp_mesh.get_local_rank() 

220 peer_rank = cp_mesh.size() - 1 - local_rank 

221 global_kv_len = key.shape[2] * cp_mesh.size() 

222 keep_kwargs = _prepare_cp_sdpa_kwargs( 

223 kwargs, 

224 q_len=half_q_len, 

225 kv_len=global_kv_len, 

226 query_offset=local_rank * local_q_len, 

227 device=query.device, 

228 ) 

229 peer_kwargs = _prepare_cp_sdpa_kwargs( 

230 kwargs, 

231 q_len=half_q_len, 

232 kv_len=global_kv_len, 

233 query_offset=peer_rank * local_q_len + half_q_len, 

234 device=query.device, 

235 ) 

236 return keep_kwargs, peer_kwargs 

237 

238 

239def _prepare_hybrid_sdpa_kwargs( 

240 kwargs: dict[str, Any], query: Any, key: Any, 

241 cp_mesh: Any, ulysses_degree: int) -> dict[str, Any]: 

242 """Prepare complete-mask query rows for Hybrid attention.""" 

243 _, colossal_mesh = _build_hybrid_cp_submeshes(cp_mesh, ulysses_degree) 

244 hybrid_q_len = query.shape[2] * ulysses_degree 

245 return _prepare_cp_sdpa_kwargs( 

246 kwargs, 

247 q_len=hybrid_q_len, 

248 kv_len=key.shape[2] * cp_mesh.size(), 

249 query_offset=colossal_mesh.get_local_rank() * hybrid_q_len, 

250 device=query.device, 

251 ) 

252 

253 

254def _cp_sdpa_call(orig_sdpa, cp_mesh, q, k, v, kwargs): 

255 """CP-aware SDPA: K/V all-gather + D-04 offset-aware causal mask.""" 

256 cp_dim = 2 # sequence dim of the [B, N, S, H] layout 

257 global_k, global_v = flex_cp_allgather( 

258 k.contiguous(), v.contiguous(), cp_dim, cp_mesh) 

259 if cp_mesh.size() > 1: 

260 kwargs = _prepare_cp_sdpa_kwargs( 

261 kwargs, 

262 q_len=q.shape[cp_dim], 

263 kv_len=global_k.shape[cp_dim], 

264 query_offset=cp_mesh.get_local_rank() * q.shape[cp_dim], 

265 device=q.device, 

266 ) 

267 return orig_sdpa(q, global_k, global_v, **kwargs) 

268 

269 

270def _ulysses_attention_call( 

271 attention_fn, cp_mesh, query, key, value, kwargs, 

272 *, seq_dim=2, head_dim=1): 

273 """Run attention in the Pure Ulysses full-sequence/head-sharded layout.""" 

274 _validate_ulysses_head_counts( 

275 query, key, value, cp_mesh.size(), "Pure Ulysses CP" 

276 ) 

277 query, key, value = ( 

278 ulysses_seq_to_head(tensor, seq_dim, head_dim, cp_mesh) 

279 for tensor in (query, key, value) 

280 ) 

281 output = attention_fn(query, key, value, **kwargs) 

282 return ulysses_head_to_seq(output, seq_dim, head_dim, cp_mesh) 

283 

284 

285def _ulysses_qkv_forward(original_forward, cp_mesh, args, kwargs): 

286 """Preserve a QKV forward signature while applying Pure Ulysses.""" 

287 signature = inspect.signature(original_forward) 

288 bound = signature.bind(*args, **kwargs) 

289 names = list(signature.parameters) 

290 if len(names) < 3: 

291 raise TypeError("Ulysses QKV wrapper requires at least three forward inputs") 

292 try: 

293 query, key, value = ( 

294 bound.arguments[names[index]] for index in range(3) 

295 ) 

296 except KeyError as exc: 

297 raise TypeError( 

298 "Ulysses QKV wrapper requires query, key, and value inputs" 

299 ) from exc 

300 _validate_ulysses_head_counts( 

301 query, key, value, cp_mesh.size(), "Pure Ulysses CP" 

302 ) 

303 query, key, value = ( 

304 ulysses_seq_to_head(tensor, 2, 1, cp_mesh) 

305 for tensor in (query, key, value) 

306 ) 

307 bound.arguments[names[0]] = query 

308 bound.arguments[names[1]] = key 

309 bound.arguments[names[2]] = value 

310 output = original_forward(*bound.args, **bound.kwargs) 

311 return ulysses_head_to_seq(output, 2, 1, cp_mesh) 

312 

313 

314def _require_ulysses_cp_mesh(cp_mesh, wrapper_name): 

315 """Validate the communication context required by Pure Ulysses.""" 

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

317 raise ValueError( 

318 f"Ulysses wrapper {wrapper_name!r} requires an active CP mesh" 

319 ) 

320 

321 

322# ──────────────────────────────────────────────────────────────────────────── 

323# The four built-in wrappers 

324# ──────────────────────────────────────────────────────────────────────────── 

325 

326@inner_wrapper 

327def sdpa_qkv_cp_wrapper( 

328 target_module: Module, mesh: Any, tp_mesh: Any, 

329 cp_mesh: Any, ep_mesh: Any) -> Callable: 

330 """NeMo/Megatron SDPA path (registry "sdpa_qkv"): explicit all-gather K/V. 

331 

332 Assumes the inner_attention.forward(q,k,v,...) signature convention. 

333 **Local-only** (injection discipline): the dual-mode adapter converts 

334 DTensor inputs to local and re-wraps the output — this wrapper never 

335 touches DTensor. Since it wraps an inner submodule, the plan MUST 

336 declare ``inner_out_src: "first_input"`` (its output layout == q's 

337 layout). cp_mesh is framework-filled context; fail fast when the plan 

338 has no cp axis. 

339 """ 

340 

341 del mesh, tp_mesh, ep_mesh 

342 if cp_mesh is None: 

343 raise ValueError( 

344 "The in-repo CP wrapper reference implementation 'sdpa_qkv' requires an " 

345 "active cp axis (the communication domain for K/V all-gather), but the " 

346 "framework-filled cp_mesh is None (the current plan has no cp axis) — " 

347 "without CP, use a custom @inner_wrapper wrapper instead (the " 

348 "cp_mesh=None semantics are then your own responsibility), or use the " 

349 "local_compute_fn channel (see " 

350 "examples/distributed/perf_replacement.py)") 

351 

352 original_forward = target_module.forward 

353 

354 @functools.wraps(original_forward) 

355 def cp_forward(q: Any, k: Any, v: Any, **kwargs: Any) -> Any: 

356 """All-gather K/V along CP, then run the original QKV SDPA forward.""" 

357 return _cp_sdpa_call(original_forward, cp_mesh, q, k, v, kwargs) 

358 

359 return cp_forward 

360 

361 

362@inner_wrapper 

363def flex_qkv_cp_wrapper( 

364 target_module: Module, mesh: Any, tp_mesh: Any, 

365 cp_mesh: Any, ep_mesh: Any) -> Callable: 

366 """NeMo/Megatron FlexAttention path (registry "flex_qkv"): explicit all-gather K/V. 

367 

368 **Local-only** (see sdpa_qkv_cp_wrapper); requires 

369 ``inner_out_src: "first_input"`` in the plan. Constraint: the 

370 block_mask must be built for the global kv length. cp_mesh is 

371 framework-filled context; fail fast when the plan has no cp axis. 

372 """ 

373 

374 del mesh, tp_mesh, ep_mesh 

375 if cp_mesh is None: 

376 raise ValueError( 

377 "The in-repo CP wrapper reference implementation 'flex_qkv' requires an " 

378 "active cp axis (the communication domain for K/V all-gather), but the " 

379 "framework-filled cp_mesh is None (the current plan has no cp axis) — " 

380 "without CP, use a custom @inner_wrapper wrapper instead (the " 

381 "cp_mesh=None semantics are then your own responsibility), or use the " 

382 "local_compute_fn channel (see " 

383 "examples/distributed/perf_replacement.py)") 

384 

385 original_forward = target_module.forward 

386 

387 @functools.wraps(original_forward) 

388 def cp_forward(q: Any, k: Any, v: Any, **kwargs: Any) -> Any: 

389 """All-gather K/V along CP, then run the original QKV Flex forward.""" 

390 global_k, global_v = flex_cp_allgather( 

391 k.contiguous(), v.contiguous(), 2, cp_mesh) 

392 return original_forward(q, global_k, global_v, **kwargs) 

393 

394 return cp_forward 

395 

396 

397@inner_wrapper 

398def sdpa_hf_cp_wrapper( 

399 target_module: Module, mesh: Any, tp_mesh: Any, 

400 cp_mesh: Any, ep_mesh: Any) -> Callable: 

401 """HF standard SDPA path: forward(hidden_states,...) -> primitive interception (05 §4.4.2). 

402 

403 **Local-only** (see sdpa_qkv_cp_wrapper): the adapter handles DTensor 

404 unwrap/param-unwrap/rewrap; the rewrap uses the boundary's declared 

405 out_src (this wrapper targets the boundary module itself). The 

406 primitive interception is a temporary global function replacement 

407 (restored via try/finally) and is not thread-safe; it is safe under 

408 single-process SPMD training (consistent with the TorchTitan CP 

409 implementation). 

410 Misfire detection: the wrapper may be applied to a module that does not 

411 call F.sdpa -- if the primitive did not intercept a single call, the K/V 

412 were not gathered (a silent numerical error), so raise a RuntimeError 

413 immediately. 

414 """ 

415 

416 del mesh, tp_mesh, ep_mesh 

417 if cp_mesh is None: 

418 raise ValueError( 

419 "The in-repo CP wrapper reference implementation 'sdpa_hf' requires an " 

420 "active cp axis (the communication domain for K/V all-gather), but the " 

421 "framework-filled cp_mesh is None (the current plan has no cp axis) — " 

422 "without CP, use a custom @inner_wrapper wrapper instead (the " 

423 "cp_mesh=None semantics are then your own responsibility), or use the " 

424 "local_compute_fn channel (see " 

425 "examples/distributed/perf_replacement.py)") 

426 

427 setattr(target_module, "_hp_sdpa_hf_cp_mesh", cp_mesh) 

428 setattr(target_module, "_hp_sdpa_hf_original_forward", target_module.forward) 

429 

430 @functools.wraps(target_module.forward) 

431 def cp_forward(hidden_states: Any, *args: Any, **kwargs: Any) -> Any: 

432 """Delegate to the source-visible SDPA helper shared with Codegen.""" 

433 return sdpa_hf_cp_forward(target_module, hidden_states, *args, **kwargs) 

434 

435 return cp_forward 

436 

437 

438def sdpa_hf_cp_forward( 

439 target_module: Module, hidden_states: Any, 

440 *args: Any, **kwargs: Any) -> Any: 

441 """Run an HF attention forward while intercepting SDPA for CP.""" 

442 cp_mesh = getattr(target_module, "_hp_sdpa_hf_cp_mesh") 

443 original_forward = getattr(target_module, "_forward_impl", None) 

444 if original_forward is None: 

445 original_forward = getattr(target_module, "_hp_sdpa_hf_original_forward") 

446 orig_sdpa = F.scaled_dot_product_attention 

447 fired = {"hit": False} 

448 

449 def cp_aware_sdpa(q: Any, k: Any, v: Any, **kw: Any) -> Any: 

450 """CP-aware SDPA replacement: all-gather K/V plus the D-04 mask.""" 

451 fired["hit"] = True 

452 return _cp_sdpa_call(orig_sdpa, cp_mesh, q, k, v, kw) 

453 

454 F.scaled_dot_product_attention = cp_aware_sdpa 

455 try: 

456 out = original_forward(hidden_states, *args, **kwargs) 

457 finally: 

458 F.scaled_dot_product_attention = orig_sdpa 

459 if not fired["hit"]: 

460 raise RuntimeError( 

461 f"CP wrapper 'sdpa_hf' did not intercept any " 

462 f"F.scaled_dot_product_attention call on " 

463 f"{type(target_module).__name__} -- the wrapper does " 

464 f"not match the module implementation (K/V were not " 

465 f"all-gathered; continuing would produce silent numerical " 

466 f"errors). Please explicitly set inner_wrapper='sdpa_qkv' " 

467 f"(the (q,k,v) convention), or provide a custom inner_wrapper " 

468 f"callable") 

469 return out 

470 

471 

472@inner_wrapper 

473def flex_hf_cp_wrapper( 

474 target_module: Module, mesh: Any, tp_mesh: Any, 

475 cp_mesh: Any, ep_mesh: Any) -> Callable: 

476 """HF standard FlexAttention path: intercept flex_attention (same structure as the SDPA path). 

477 

478 **Local-only** (see sdpa_qkv_cp_wrapper). Constraint: 

479 score_mod/block_mask pass through verbatim via kwargs -- under CP, 

480 kv_len changes from S/cp to S, so the block_mask must be built for the 

481 **global kv length** (constructed on the full sequence in the data 

482 pipeline / model side), otherwise shapes and semantics are misaligned. 

483 The wrapper does not validate this. 

484 Misfire detection is the same as 'sdpa_hf': if no flex_attention call is 

485 intercepted, raise a RuntimeError. 

486 """ 

487 

488 del mesh, tp_mesh, ep_mesh 

489 if cp_mesh is None: 

490 raise ValueError( 

491 "The in-repo CP wrapper reference implementation 'flex_hf' requires an " 

492 "active cp axis (the communication domain for K/V all-gather), but the " 

493 "framework-filled cp_mesh is None (the current plan has no cp axis) — " 

494 "without CP, use a custom @inner_wrapper wrapper instead (the " 

495 "cp_mesh=None semantics are then your own responsibility), or use the " 

496 "local_compute_fn channel (see " 

497 "examples/distributed/perf_replacement.py)") 

498 

499 original_forward = target_module.forward 

500 # FlexAttention is optional on older supported PyTorch versions. 

501 flex_attention_module = importlib.import_module( 

502 "torch.nn.attention.flex_attention") 

503 original_flex_attention = flex_attention_module.flex_attention 

504 

505 @functools.wraps(original_forward) 

506 def cp_forward(hidden_states: Any, *args: Any, **kwargs: Any) -> Any: 

507 """Run the HF forward with flex_attention temporarily replaced.""" 

508 fired = {"hit": False} 

509 

510 def cp_aware_flex(q: Any, k: Any, v: Any, **kw: Any) -> Any: 

511 """CP-aware FlexAttention replacement: all-gather K/V first.""" 

512 fired["hit"] = True 

513 global_k, global_v = flex_cp_allgather( 

514 k.contiguous(), v.contiguous(), 2, cp_mesh) 

515 return original_flex_attention(q, global_k, global_v, **kw) 

516 

517 flex_attention_module.flex_attention = cp_aware_flex 

518 try: 

519 out = original_forward(hidden_states, *args, **kwargs) 

520 finally: 

521 flex_attention_module.flex_attention = original_flex_attention 

522 if not fired["hit"]: 

523 raise RuntimeError( 

524 f"CP wrapper 'flex_hf' did not intercept any flex_attention " 

525 f"call on {type(target_module).__name__} -- the wrapper " 

526 f"does not match the module implementation (K/V were " 

527 f"not all-gathered; continuing would produce silent numerical " 

528 f"errors). Please explicitly set inner_wrapper='flex_qkv' " 

529 f"(the (q,k,v) convention), or provide a custom inner_wrapper " 

530 f"callable") 

531 return out 

532 

533 return cp_forward 

534 

535 

536# ──────────────────────────────────────────────────────────────────────────── 

537# Colossal Head-Tail load-balance wrappers (explicit plan_overrides methods) 

538# ──────────────────────────────────────────────────────────────────────────── 

539 

540@inner_wrapper 

541def sdpa_qkv_load_balance_cp_wrapper( 

542 target_module: Module, mesh: Any, tp_mesh: Any, 

543 cp_mesh: Any, ep_mesh: Any) -> Callable: 

544 """Apply Colossal Head-Tail load balancing to a QKV-style SDPA module. 

545 

546 Args: 

547 target_module: Attention module whose first three inputs are Q/K/V. 

548 mesh: Framework-owned root mesh; unused by this wrapper. 

549 tp_mesh: Framework-owned TP mesh; unused by this wrapper. 

550 cp_mesh: Framework-owned CP communication mesh. 

551 ep_mesh: Framework-owned EP mesh; unused by this wrapper. 

552 """ 

553 del mesh, tp_mesh, ep_mesh 

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

555 raise ValueError( 

556 "sdpa_qkv_load_balance_cp_wrapper requires an active CP mesh" 

557 ) 

558 original_forward = target_module.forward 

559 

560 @functools.wraps(original_forward) 

561 def cp_forward(q: Any, k: Any, v: Any, **kwargs: Any) -> Any: 

562 """Route local Q/K/V tensors through Head-Tail communication.""" 

563 def attention_call( 

564 query: Any, key: Any, value: Any, 

565 call_kwargs: dict[str, Any]) -> Any: 

566 """Invoke the original QKV forward with transformed tensors.""" 

567 return original_forward(query, key, value, **call_kwargs) 

568 

569 keep_kwargs, peer_kwargs = _prepare_head_tail_sdpa_kwargs( 

570 kwargs, q, k, cp_mesh 

571 ) 

572 return head_tail_load_balance_attention( 

573 attention_call, 

574 q, 

575 k, 

576 v, 

577 keep_kwargs, 

578 cp_mesh, 

579 peer_attention_kwargs=peer_kwargs, 

580 ) 

581 

582 return cp_forward 

583 

584 

585@inner_wrapper 

586def sdpa_hf_load_balance_cp_wrapper( 

587 target_module: Module, mesh: Any, tp_mesh: Any, 

588 cp_mesh: Any, ep_mesh: Any) -> Callable: 

589 """Apply Colossal Head-Tail load balancing at an HF SDPA primitive. 

590 

591 Args: 

592 target_module: HF-style attention containing an SDPA primitive call. 

593 mesh: Framework-owned root mesh; unused by this wrapper. 

594 tp_mesh: Framework-owned TP mesh; unused by this wrapper. 

595 cp_mesh: Framework-owned CP communication mesh. 

596 ep_mesh: Framework-owned EP mesh; unused by this wrapper. 

597 """ 

598 del mesh, tp_mesh, ep_mesh 

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

600 raise ValueError( 

601 "sdpa_hf_load_balance_cp_wrapper requires an active CP mesh" 

602 ) 

603 original_forward = target_module.forward 

604 original_sdpa = F.scaled_dot_product_attention 

605 

606 @functools.wraps(original_forward) 

607 def cp_forward( 

608 hidden_states: Any, *args: Any, **kwargs: Any) -> Any: 

609 """Intercept the module's SDPA primitive for one forward call.""" 

610 fired = {"hit": False} 

611 

612 def load_balanced_sdpa( 

613 q: Any, k: Any, v: Any, 

614 **call_kwargs: Any) -> Any: 

615 """Run one intercepted SDPA call with Head-Tail communication.""" 

616 fired["hit"] = True 

617 keep_kwargs, peer_kwargs = _prepare_head_tail_sdpa_kwargs( 

618 call_kwargs, q, k, cp_mesh 

619 ) 

620 

621 def _call_original_sdpa(query, key, value, attention_kwargs): 

622 return original_sdpa(query, key, value, **attention_kwargs) 

623 

624 return head_tail_load_balance_attention( 

625 _call_original_sdpa, 

626 q, 

627 k, 

628 v, 

629 keep_kwargs, 

630 cp_mesh, 

631 peer_attention_kwargs=peer_kwargs, 

632 ) 

633 

634 F.scaled_dot_product_attention = load_balanced_sdpa 

635 try: 

636 output = original_forward(hidden_states, *args, **kwargs) 

637 finally: 

638 F.scaled_dot_product_attention = original_sdpa 

639 if not fired["hit"]: 

640 raise RuntimeError( 

641 "CP wrapper 'sdpa_hf_load_balance' did not intercept any " 

642 "F.scaled_dot_product_attention call on " 

643 f"{type(target_module).__name__}; choose the QKV wrapper or " 

644 "provide a matching custom inner_wrapper" 

645 ) 

646 return output 

647 

648 return cp_forward 

649 

650 

651# ──────────────────────────────────────────────────────────────────────────── 

652# Pure Ulysses attention wrappers (explicit plan_overrides methods) 

653# ──────────────────────────────────────────────────────────────────────────── 

654 

655@inner_wrapper 

656def sdpa_qkv_ulysses_cp_wrapper( 

657 target_module: Module, mesh: Any, tp_mesh: Any, 

658 cp_mesh: Any, ep_mesh: Any) -> Callable: 

659 """Apply Pure Ulysses to a separated ``forward(query, key, value, ...)``.""" 

660 del mesh, tp_mesh, ep_mesh 

661 _require_ulysses_cp_mesh(cp_mesh, "sdpa_qkv_ulysses") 

662 original_forward = target_module.forward 

663 

664 @functools.wraps(original_forward) 

665 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

666 """Run the original QKV forward in the Ulysses head-sharded layout.""" 

667 return _ulysses_qkv_forward(original_forward, cp_mesh, args, kwargs) 

668 

669 return cp_forward 

670 

671 

672@inner_wrapper 

673def flex_qkv_ulysses_cp_wrapper( 

674 target_module: Module, mesh: Any, tp_mesh: Any, 

675 cp_mesh: Any, ep_mesh: Any) -> Callable: 

676 """Apply Pure Ulysses to a separated FlexAttention QKV forward.""" 

677 del mesh, tp_mesh, ep_mesh 

678 _require_ulysses_cp_mesh(cp_mesh, "flex_qkv_ulysses") 

679 original_forward = target_module.forward 

680 

681 @functools.wraps(original_forward) 

682 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

683 """Run the original FlexAttention QKV forward in the Ulysses layout.""" 

684 return _ulysses_qkv_forward(original_forward, cp_mesh, args, kwargs) 

685 

686 return cp_forward 

687 

688 

689@inner_wrapper 

690def sdpa_hf_ulysses_cp_wrapper( 

691 target_module: Module, mesh: Any, tp_mesh: Any, 

692 cp_mesh: Any, ep_mesh: Any) -> Callable: 

693 """Apply Pure Ulysses by intercepting HF SDPA primitive calls.""" 

694 del mesh, tp_mesh, ep_mesh 

695 _require_ulysses_cp_mesh(cp_mesh, "sdpa_hf_ulysses") 

696 original_forward = target_module.forward 

697 original_sdpa = F.scaled_dot_product_attention 

698 

699 @functools.wraps(original_forward) 

700 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

701 """Run the HF forward with F.sdpa temporarily Ulysses-exchanged.""" 

702 fired = {"hit": False} 

703 

704 def ulysses_sdpa( 

705 query: Any, key: Any, value: Any, 

706 **attention_kwargs: Any) -> Any: 

707 """Run one intercepted SDPA call in the Ulysses layout.""" 

708 fired["hit"] = True 

709 return _ulysses_attention_call( 

710 original_sdpa, 

711 cp_mesh, 

712 query, 

713 key, 

714 value, 

715 attention_kwargs, 

716 ) 

717 

718 F.scaled_dot_product_attention = ulysses_sdpa 

719 try: 

720 output = original_forward(*args, **kwargs) 

721 finally: 

722 F.scaled_dot_product_attention = original_sdpa 

723 if not fired["hit"]: 

724 raise RuntimeError( 

725 "CP wrapper 'sdpa_hf_ulysses' did not intercept any " 

726 "F.scaled_dot_product_attention call; the selected wrapper " 

727 "does not match the module implementation" 

728 ) 

729 return output 

730 

731 return cp_forward 

732 

733 

734@inner_wrapper 

735def flex_hf_ulysses_cp_wrapper( 

736 target_module: Module, mesh: Any, tp_mesh: Any, 

737 cp_mesh: Any, ep_mesh: Any) -> Callable: 

738 """Apply Pure Ulysses by intercepting HF FlexAttention primitive calls.""" 

739 del mesh, tp_mesh, ep_mesh 

740 _require_ulysses_cp_mesh(cp_mesh, "flex_hf_ulysses") 

741 original_forward = target_module.forward 

742 flex_attention_module = importlib.import_module( 

743 "torch.nn.attention.flex_attention" 

744 ) 

745 original_flex_attention = flex_attention_module.flex_attention 

746 

747 @functools.wraps(original_forward) 

748 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

749 """Run the HF forward with flex_attention temporarily Ulysses-exchanged.""" 

750 fired = {"hit": False} 

751 

752 def ulysses_flex( 

753 query: Any, key: Any, value: Any, 

754 **attention_kwargs: Any) -> Any: 

755 """Run one intercepted FlexAttention call in the Ulysses layout.""" 

756 fired["hit"] = True 

757 return _ulysses_attention_call( 

758 original_flex_attention, 

759 cp_mesh, 

760 query, 

761 key, 

762 value, 

763 attention_kwargs, 

764 ) 

765 

766 flex_attention_module.flex_attention = ulysses_flex 

767 try: 

768 output = original_forward(*args, **kwargs) 

769 finally: 

770 flex_attention_module.flex_attention = original_flex_attention 

771 if not fired["hit"]: 

772 raise RuntimeError( 

773 "CP wrapper 'flex_hf_ulysses' did not intercept any " 

774 "flex_attention call; the selected wrapper does not match " 

775 "the module implementation" 

776 ) 

777 return output 

778 

779 return cp_forward 

780 

781 

782# ──────────────────────────────────────────────────────────────────────────── 

783# Hybrid attention wrappers (explicit Target with wrapper-local degree) 

784# ──────────────────────────────────────────────────────────────────────────── 

785 

786def _validate_hybrid_config( 

787 cp_mesh: Any, ulysses_degree: int, wrapper_name: str) -> None: 

788 """Validate Hybrid topology at wrapper installation time.""" 

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

790 raise ValueError( 

791 f"Hybrid wrapper {wrapper_name!r} requires an active CP mesh" 

792 ) 

793 if isinstance(ulysses_degree, bool) or not isinstance(ulysses_degree, int): 

794 raise TypeError( 

795 f"Hybrid wrapper {wrapper_name!r} requires integer " 

796 f"ulysses_degree, got {type(ulysses_degree).__name__}" 

797 ) 

798 cp_size = cp_mesh.size() 

799 if not 1 < ulysses_degree < cp_size: 

800 raise ValueError( 

801 f"Hybrid wrapper {wrapper_name!r} requires 1 < ulysses_degree " 

802 f"< cp_size, got ulysses_degree={ulysses_degree}, cp_size={cp_size}" 

803 ) 

804 if cp_size % ulysses_degree: 

805 raise ValueError( 

806 f"cp_size ({cp_size}) must be divisible by ulysses_degree " 

807 f"({ulysses_degree})" 

808 ) 

809 

810 

811def _apply_qkv_hybrid_wrapper( 

812 target_module, cp_mesh, ulysses_degree, wrapper_name, *, 

813 prepare_sdpa_mask: bool): 

814 """Replace a separated QKV forward with local-tensor Hybrid CP.""" 

815 _validate_hybrid_config(cp_mesh, ulysses_degree, wrapper_name) 

816 original_forward = target_module.forward 

817 

818 @functools.wraps(original_forward) 

819 def cp_forward(q: Any, k: Any, v: Any, **kwargs: Any) -> Any: 

820 """Run the original QKV forward through local-tensor Hybrid CP.""" 

821 def attention_call( 

822 query: Any, key: Any, value: Any, 

823 call_kwargs: dict[str, Any]) -> Any: 

824 """Invoke the original QKV forward with transformed tensors.""" 

825 return original_forward(query, key, value, **call_kwargs) 

826 

827 if prepare_sdpa_mask: 

828 kwargs = _prepare_hybrid_sdpa_kwargs( 

829 kwargs, q, k, cp_mesh, ulysses_degree 

830 ) 

831 return hybrid_cp_attention( 

832 attention_call, 

833 q, 

834 k, 

835 v, 

836 kwargs, 

837 cp_mesh, 

838 ulysses_degree, 

839 ) 

840 

841 return cp_forward 

842 

843 

844@inner_wrapper 

845def sdpa_qkv_hybrid_cp_wrapper( 

846 target_module: Module, mesh: Any, tp_mesh: Any, cp_mesh: Any, 

847 ep_mesh: Any, ulysses_degree: int) -> Callable: 

848 """Apply Hybrid CP to a separated SDPA ``forward(query, key, value, ...)``.""" 

849 del mesh, tp_mesh, ep_mesh 

850 return _apply_qkv_hybrid_wrapper( 

851 target_module, 

852 cp_mesh, 

853 ulysses_degree, 

854 "sdpa_qkv_hybrid", 

855 prepare_sdpa_mask=True, 

856 ) 

857 

858 

859@inner_wrapper 

860def flex_qkv_hybrid_cp_wrapper( 

861 target_module: Module, mesh: Any, tp_mesh: Any, cp_mesh: Any, 

862 ep_mesh: Any, ulysses_degree: int) -> Callable: 

863 """Apply Hybrid CP to a separated FlexAttention QKV forward.""" 

864 del mesh, tp_mesh, ep_mesh 

865 return _apply_qkv_hybrid_wrapper( 

866 target_module, 

867 cp_mesh, 

868 ulysses_degree, 

869 "flex_qkv_hybrid", 

870 prepare_sdpa_mask=False, 

871 ) 

872 

873 

874@inner_wrapper 

875def sdpa_hf_hybrid_cp_wrapper( 

876 target_module: Module, mesh: Any, tp_mesh: Any, cp_mesh: Any, 

877 ep_mesh: Any, ulysses_degree: int) -> Callable: 

878 """Apply Hybrid CP by intercepting HF SDPA primitive calls.""" 

879 del mesh, tp_mesh, ep_mesh 

880 _validate_hybrid_config(cp_mesh, ulysses_degree, "sdpa_hf_hybrid") 

881 original_forward = target_module.forward 

882 original_sdpa = F.scaled_dot_product_attention 

883 

884 @functools.wraps(original_forward) 

885 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

886 """Run the HF attention forward with temporary Hybrid SDPA interception.""" 

887 fired = {"hit": False} 

888 

889 def hybrid_sdpa( 

890 query: Any, key: Any, value: Any, 

891 **attention_kwargs: Any) -> Any: 

892 """Route one intercepted SDPA call through Hybrid CP.""" 

893 fired["hit"] = True 

894 attention_kwargs = _prepare_hybrid_sdpa_kwargs( 

895 attention_kwargs, 

896 query, 

897 key, 

898 cp_mesh, 

899 ulysses_degree, 

900 ) 

901 

902 def _call_original_sdpa(call_query, call_key, call_value, call_kwargs): 

903 return original_sdpa( 

904 call_query, call_key, call_value, **call_kwargs 

905 ) 

906 

907 return hybrid_cp_attention( 

908 _call_original_sdpa, 

909 query, 

910 key, 

911 value, 

912 attention_kwargs, 

913 cp_mesh, 

914 ulysses_degree, 

915 ) 

916 

917 F.scaled_dot_product_attention = hybrid_sdpa 

918 try: 

919 output = original_forward(*args, **kwargs) 

920 finally: 

921 F.scaled_dot_product_attention = original_sdpa 

922 if not fired["hit"]: 

923 raise RuntimeError( 

924 "CP wrapper 'sdpa_hf_hybrid' did not intercept any " 

925 "F.scaled_dot_product_attention call; the selected wrapper " 

926 "does not match the module implementation" 

927 ) 

928 return output 

929 

930 return cp_forward 

931 

932 

933@inner_wrapper 

934def flex_hf_hybrid_cp_wrapper( 

935 target_module: Module, mesh: Any, tp_mesh: Any, cp_mesh: Any, 

936 ep_mesh: Any, ulysses_degree: int) -> Callable: 

937 """Apply Hybrid CP by intercepting HF FlexAttention primitive calls.""" 

938 del mesh, tp_mesh, ep_mesh 

939 _validate_hybrid_config(cp_mesh, ulysses_degree, "flex_hf_hybrid") 

940 original_forward = target_module.forward 

941 flex_attention_module = importlib.import_module( 

942 "torch.nn.attention.flex_attention" 

943 ) 

944 original_flex_attention = flex_attention_module.flex_attention 

945 

946 @functools.wraps(original_forward) 

947 def cp_forward(*args: Any, **kwargs: Any) -> Any: 

948 """Run the HF attention forward with temporary Hybrid Flex interception.""" 

949 fired = {"hit": False} 

950 

951 def hybrid_flex( 

952 query: Any, key: Any, value: Any, 

953 **attention_kwargs: Any) -> Any: 

954 """Route one intercepted FlexAttention call through Hybrid CP.""" 

955 fired["hit"] = True 

956 

957 def _call_original_flex(call_query, call_key, call_value, call_kwargs): 

958 return original_flex_attention( 

959 call_query, call_key, call_value, **call_kwargs 

960 ) 

961 

962 return hybrid_cp_attention( 

963 _call_original_flex, 

964 query, 

965 key, 

966 value, 

967 attention_kwargs, 

968 cp_mesh, 

969 ulysses_degree, 

970 ) 

971 

972 flex_attention_module.flex_attention = hybrid_flex 

973 try: 

974 output = original_forward(*args, **kwargs) 

975 finally: 

976 flex_attention_module.flex_attention = original_flex_attention 

977 if not fired["hit"]: 

978 raise RuntimeError( 

979 "CP wrapper 'flex_hf_hybrid' did not intercept any " 

980 "flex_attention call; the selected wrapper does not match " 

981 "the module implementation" 

982 ) 

983 return output 

984 

985 return cp_forward 

986 

987 

988# ──────────────────────────────────────────────────────────────────────────── 

989# MLA/DSA Ulysses wrapper 

990# ──────────────────────────────────────────────────────────────────────────── 

991 

992def _input_cp_sharding(text_model, context): 

993 """Build the CP-rank input-slicing rewrite request for a text model.""" 

994 if getattr(text_model, _ULYSSES_WRAPPED_FLAG, False): 

995 return None 

996 original_forward = text_model.forward 

997 

998 @functools.wraps(original_forward) 

999 def forward_with_sequence_sharding(*args: Any, **kwargs: Any) -> Any: 

1000 """Slice sequence-dim inputs to this CP rank before the forward.""" 

1001 if getattr(text_model, "_hyper_cp_inside_forward", False): 

1002 return original_forward(*args, **kwargs) 

1003 call_kwargs = kwargs.copy() 

1004 inputs_embeds = call_kwargs.get("inputs_embeds") 

1005 if inputs_embeds is None: 

1006 return original_forward(*args, **kwargs) 

1007 call_kwargs["inputs_embeds"] = _slice_sequence(inputs_embeds, 1, context) 

1008 position_ids = call_kwargs.get("position_ids") 

1009 if position_ids is not None: 

1010 call_kwargs["position_ids"] = _slice_sequence( 

1011 position_ids, position_ids.ndim - 1, context) 

1012 mome_mask = call_kwargs.get("mome_mask") 

1013 if mome_mask is not None: 

1014 call_kwargs["mome_mask"] = _slice_sequence(mome_mask, 1, context) 

1015 if call_kwargs.get("use_cache"): 

1016 raise ValueError("Ulysses CP requires use_cache=False") 

1017 call_kwargs["use_cache"] = False 

1018 setattr(text_model, "_hyper_cp_inside_forward", True) 

1019 try: 

1020 return original_forward(*args, **call_kwargs) 

1021 finally: 

1022 setattr(text_model, "_hyper_cp_inside_forward", False) 

1023 

1024 return _ForwardRewriteRequest( 

1025 text_model, 

1026 forward_with_sequence_sharding, 

1027 companion_attrs={_ULYSSES_WRAPPED_FLAG: True}, 

1028 ) 

1029 

1030 

1031def _validate_ulysses_requirements(target_module, cp_size): 

1032 """Validate the model configuration supported by Ulysses CP.""" 

1033 config = getattr(target_module, "config", None) 

1034 if config is None: 

1035 raise ValueError( 

1036 "MLA/DSA Ulysses wrapper requires target_module.config") 

1037 text_config = getattr(config, "text_config", config) 

1038 if text_config is None: 

1039 raise ValueError( 

1040 "MLA/DSA Ulysses wrapper requires a non-None text_config") 

1041 for name in ("num_attention_heads", "index_num_attention_heads"): 

1042 value = getattr(text_config, name, None) 

1043 if value is None: 

1044 raise ValueError( 

1045 "MLA/DSA Ulysses wrapper requires " 

1046 f"text_config.{name}") 

1047 count = int(value) 

1048 if count % cp_size: 

1049 raise ValueError( 

1050 f"{name}={count} is not divisible by CP size {cp_size}") 

1051 if getattr(text_config, "dsa_dense_warm_up", False): 

1052 raise ValueError("MLA/DSA CP does not support DSA dense warm-up") 

1053 if not getattr(text_config, "apply_fa_rescale", False): 

1054 raise ValueError("MLA/DSA CP requires apply_fa_rescale=True") 

1055 if getattr(text_config, "use_fused_sink_fa", False): 

1056 raise ValueError("MLA/DSA CP does not support fused sink FA") 

1057 

1058 

1059def _collect_mla_dsa_text_models(target_module): 

1060 """Collect text-model modules supported by the MLA/DSA wrapper. 

1061 

1062 Args: 

1063 target_module: Root module whose descendants are inspected. 

1064 

1065 Returns: 

1066 The matching text-model modules in traversal order. 

1067 """ 

1068 text_models = [] 

1069 for name, module in target_module.named_modules(): 

1070 if name.rsplit(".", maxsplit=1)[-1] in {"text_model", "language_model"}: 

1071 text_models.append(module) 

1072 return text_models 

1073 

1074 

1075def _collect_mla_dsa_attention_registries(attention_module): 

1076 """Collect registries that expose both required MLA/DSA backends. 

1077 

1078 Args: 

1079 attention_module: Python module that owns the attention registries. 

1080 

1081 Returns: 

1082 Dictionaries containing both required attention functions. 

1083 """ 

1084 attention_registries = [] 

1085 required_attention_functions = {"npu_fa_rescale", "dsa_sparse_attention"} 

1086 for value in vars(attention_module).values(): 

1087 if isinstance(value, dict) and required_attention_functions <= value.keys(): 

1088 attention_registries.append(value) 

1089 return attention_registries 

1090 

1091 

1092@inner_wrapper 

1093def mla_dsa_ulysses_cp_wrapper( # pylint: disable=inconsistent-return-statements 

1094 target_module: Module, mesh: Any, tp_mesh: Any, 

1095 cp_mesh: Any, ep_mesh: Any) -> Any: 

1096 """Configure input, MoME, MLA and DSA Ulysses adaptations.""" 

1097 del mesh, tp_mesh, ep_mesh 

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

1099 raise ValueError( 

1100 "MLA/DSA Ulysses wrapper requires an active CP mesh") 

1101 if getattr(target_module, _ULYSSES_WRAPPED_FLAG, False): 

1102 return 

1103 _validate_ulysses_requirements(target_module, cp_mesh.size()) 

1104 context = _UlyssesContext(cp_mesh) 

1105 

1106 text_models = _collect_mla_dsa_text_models(target_module) 

1107 if not text_models: 

1108 raise RuntimeError("Cannot find a text or language model") 

1109 requests = [] 

1110 for text_model in text_models: 

1111 request = _input_cp_sharding(text_model, context) 

1112 if request is not None: 

1113 requests.append(request) 

1114 

1115 attention_modules = { 

1116 inspect.getmodule(module) for module in target_module.modules() 

1117 if getattr(module, "attention_type", None) in {"mla", "dsa"}} 

1118 attention_modules.discard(None) 

1119 if len(attention_modules) != 1: 

1120 names = sorted(module.__name__ for module in attention_modules) 

1121 raise RuntimeError( 

1122 f"Expected one MLA/DSA attention module, found {names}") 

1123 attention_module = next(iter(attention_modules)) 

1124 attention_registries = _collect_mla_dsa_attention_registries(attention_module) 

1125 if len(attention_registries) != 1: 

1126 raise RuntimeError( 

1127 "Expected one attention-function registry containing MLA and DSA backends") 

1128 attention_functions = attention_registries[0] 

1129 _mome_cp_halo_exchange(attention_module, context) 

1130 _mla_cp_alltoall(attention_functions, context) 

1131 _dsa_cp_alltoall(attention_module, attention_functions, context) 

1132 

1133 original_forward = target_module.forward 

1134 

1135 @functools.wraps(original_forward) 

1136 def forward_with_ulysses_adapters(*args: Any, **kwargs: Any) -> Any: 

1137 """Pass the forward through; the adapters are installed out of band.""" 

1138 return original_forward(*args, **kwargs) 

1139 

1140 requests.append(_ForwardRewriteRequest( 

1141 target_module, 

1142 forward_with_ulysses_adapters, 

1143 companion_attrs={ 

1144 "_hyper_ulysses_context": context, 

1145 _ULYSSES_WRAPPED_FLAG: True, 

1146 }, 

1147 )) 

1148 return requests 

1149 

1150 

1151 

1152 

1153# {registry_name: wrapper_fn} -- inner-wrapper named registry (05 §4.4.2). 

1154# The mechanism is not CP-gated (declaration means application); the in-repo 

1155# reference implementations carry CP semantics (their self-checks require an 

1156# active cp axis); users may register arbitrary named schemes. 

1157# Contract: @inner_wrapper fn(target_module, mesh, tp_mesh, cp_mesh, 

1158# ep_mesh) RETURNS the replacement forward (K/V all-gather + dual-mode 

1159# tolerance); the forward rewriter installs it (external wrappers may 

1160# still replace in place and return None). Users may register their own 

1161# named schemes: 

1162# INNER_WRAPPER_REGISTRY["my_flash"] = my_fn, after which 

1163# spec.inner_wrapper="my_flash" references it by name. 

1164INNER_WRAPPER_REGISTRY = { 

1165 "sdpa_qkv": sdpa_qkv_cp_wrapper, # NeMo convention forward(q,k,v,...) + D-04 mask 

1166 "sdpa_hf": sdpa_hf_cp_wrapper, # HF convention + F.sdpa primitive interception (misfire detection) 

1167 "flex_qkv": flex_qkv_cp_wrapper, 

1168 "flex_hf": flex_hf_cp_wrapper, 

1169 "sdpa_qkv_ulysses": sdpa_qkv_ulysses_cp_wrapper, 

1170 "flex_qkv_ulysses": flex_qkv_ulysses_cp_wrapper, 

1171 "sdpa_hf_ulysses": sdpa_hf_ulysses_cp_wrapper, 

1172 "flex_hf_ulysses": flex_hf_ulysses_cp_wrapper, 

1173 "mla_dsa_ulysses": mla_dsa_ulysses_cp_wrapper, 

1174} 

1175 

1176# Static requirements for shipped wrappers. Custom registry entries own their 

1177# semantics; built-ins are known to contain CP collectives and therefore must 

1178# run as black-box local regions during placement validation. 

1179INNER_WRAPPER_REQUIREMENTS = { 

1180 name: { 

1181 "requires_cp": True, 

1182 "region_dispatch": False, 

1183 "forward_style": ( 

1184 "hf_hidden_states" 

1185 if name.endswith("_hf") or "_hf_" in name 

1186 else "qkv" 

1187 ), 

1188 } 

1189 for name in INNER_WRAPPER_REGISTRY 

1190}