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

464 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"""Document-aware Ring Attention with NPU fused block forward/backward. 

16 

17The baseline waits for each exchange on the current stream. Optional overlap 

18prefetches the next KV block while computing the current one, and defers waiting 

19for incoming dKV until its next accumulation. KV and FP32 dKV use separate pairs 

20of reusable receive buffers; no remote KV survives forward. 

21 

22Algorithm: https://arxiv.org/abs/2310.01889. The NPU block-kernel contract was 

23cross-checked against Yunchang's ring_npu_flash_attn.py: 

24https://github.com/feifeibear/long-context-attention/tree/main/yunchang/ring 

25""" 

26 

27from __future__ import annotations 

28 

29from dataclasses import dataclass 

30from functools import lru_cache 

31from itertools import accumulate 

32from typing import Any 

33 

34# Native Torch is required; the legacy lint rule predates the Torch-only migration. 

35import torch # pylint: disable=forbidden-backend-import 

36import torch.distributed as dist # pylint: disable=forbidden-backend-import 

37from torch.autograd.function import once_differentiable # pylint: disable=forbidden-backend-import 

38 

39from hyper_parallel.distributed.context_parallel.ring_layout import ( 

40 PrunedRingPlan, pruned_ring_plan, redistribute_ring_qkv, redistribute_ring_rows, 

41 ring_task_plan, 

42) 

43from hyper_parallel.distributed.context_parallel.ring_transport import ( 

44 _PackedRingExchange, _communication_stream, _pack_ring_kv, _return_ring_gradient, 

45) 

46 

47 

48@dataclass(frozen=True) 

49class _RingContext: 

50 group: Any = None 

51 rank: int = 0 

52 size: int = 1 

53 next_rank: int = 0 

54 previous_rank: int = 0 

55 

56 

57def _ring_context(cp_mesh): 

58 """Resolve CP process-group rank and circular neighbors from the mesh.""" 

59 if cp_mesh is None: 

60 return _RingContext() 

61 if cp_mesh.ndim != 1: 

62 raise ValueError("ring_attention requires a one-dimensional CP mesh") 

63 group = cp_mesh.get_group() 

64 rank, size = dist.get_rank(group), dist.get_world_size(group) 

65 if rank < 0 or size < 1: 

66 raise ValueError("the current rank must belong to the CP group") 

67 if size != cp_mesh.size() or rank != cp_mesh.get_local_rank(): 

68 raise ValueError("CP mesh coordinates must match process-group rank order") 

69 if size == 1: 

70 return _RingContext(group, rank, size) 

71 return _RingContext( 

72 group, rank, size, 

73 dist.get_global_rank(group, (rank + 1) % size), 

74 dist.get_global_rank(group, (rank - 1) % size), 

75 ) 

76 

77 

78class _RingExchange: 

79 """Rotate one packed payload with disjoint send/receive storage and bounded buffers.""" 

80 

81 def __init__(self, tensors: tuple[torch.Tensor, ...], ring: _RingContext) -> None: 

82 """Allocate two packed receive slots and persistent views of their components.""" 

83 self._ring = ring 

84 sizes = tuple(tensor.numel() for tensor in tensors) 

85 self._buffers = tuple(tensors[0].new_empty(sum(sizes)) for _ in range(2)) if ring.size > 1 else () 

86 self._views = tuple(tuple(part.view_as(tensor) for part, tensor in zip(buffer.split(sizes), tensors)) 

87 for buffer in self._buffers) 

88 self._slot = 0 

89 self._works = [] 

90 self._sending = None 

91 self._send_buffer = None 

92 self._received = None 

93 

94 def launch(self, tensors: tuple[torch.Tensor, ...]) -> None: 

95 """Post one send/receive pair and retain both source tensors and packed storage. 

96 

97 HCCL records a dependency on the current stream. Once received, components 

98 remain views of packed storage, so later rounds forward that storage without 

99 repacking. KV and dKV exchanges retain independent buffer pairs. 

100 """ 

101 if self._received is not None: 

102 raise RuntimeError("wait for the pending Ring exchange before launching another") 

103 self._sending = tensors 

104 self._received = self._views[self._slot] if self._ring.size > 1 else tensors 

105 if self._ring.size == 1: 

106 return 

107 previous = 1 - self._slot 

108 if all(tensor is view for tensor, view in zip(tensors, self._views[previous])): 

109 self._send_buffer = self._buffers[previous] 

110 else: 

111 self._send_buffer = torch.cat(tuple(tensor.reshape(-1) for tensor in tensors)) 

112 buffer = self._buffers[self._slot] 

113 # Alternating submission order initializes matching peer links without 

114 # a cyclic dependency, including noncontiguous process-group ranks. 

115 if self._ring.rank % 2 == 0: 

116 send = dist.isend(self._send_buffer, dst=self._ring.next_rank, group=self._ring.group) 

117 receive = dist.irecv(buffer, src=self._ring.previous_rank, group=self._ring.group) 

118 else: 

119 receive = dist.irecv(buffer, src=self._ring.previous_rank, group=self._ring.group) 

120 send = dist.isend(self._send_buffer, dst=self._ring.next_rank, group=self._ring.group) 

121 self._works.extend((send, receive)) 

122 

123 def wait(self) -> tuple[torch.Tensor, ...]: 

124 """Order sends/receives complete before exposing views or reusing either slot. 

125 

126 Launch and wait must use the same compute stream. Its ordering protects the 

127 previous consumer before buffer reuse, without a device-wide synchronization. 

128 """ 

129 if self._received is None: 

130 raise RuntimeError("no pending Ring exchange to wait for") 

131 for work in self._works: 

132 work.wait() 

133 received = self._received 

134 self._works.clear() 

135 self._sending = None 

136 self._send_buffer = None 

137 self._received = None 

138 self._slot = 1 - self._slot 

139 return received 

140 

141 def rotate(self, tensors: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]: 

142 """Post and immediately wait for a rotation in the synchronous schedule.""" 

143 self.launch(tensors) 

144 return self.wait() 

145 

146 

147@lru_cache(maxsize=8) 

148def _causal_mask(device): 

149 # Sparse mode 2 uses a fixed compressed mask, independent of global sequence length. 

150 return torch.ones((2048, 2048), device=device, dtype=torch.bool).triu_(1) 

151 

152 

153def _kernel_options(query, input_layout, diagonal_causal): 

154 return { 

155 "head_num": query.shape[2 if input_layout == "BSND" else 1], 

156 "input_layout": input_layout, 

157 "atten_mask": _causal_mask(query.device) if diagonal_causal else None, 

158 "sparse_mode": 2 if diagonal_causal else 0, 

159 "pre_tockens": 2147483647, 

160 "next_tockens": 0 if diagonal_causal else 2147483647, 

161 "keep_prob": 1.0, 

162 } 

163 

164 

165def _merge_blocks(state, block, input_layout): 

166 """Merge two attention blocks using stable online-softmax statistics.""" 

167 output, maximum, denominator = state 

168 block_output, block_maximum, block_denominator = block 

169 combined_maximum = torch.maximum(maximum, block_maximum) 

170 previous_mass = denominator * torch.exp(maximum - combined_maximum) 

171 block_mass = block_denominator * torch.exp(block_maximum - combined_maximum) 

172 combined_denominator = previous_mass + block_mass 

173 previous_weight = (previous_mass / combined_denominator)[..., :1] 

174 block_weight = (block_mass / combined_denominator)[..., :1] 

175 if input_layout == "BSND": 

176 previous_weight = previous_weight.transpose(1, 2) 

177 block_weight = block_weight.transpose(1, 2) 

178 return ( 

179 output * previous_weight + block_output.float() * block_weight, 

180 combined_maximum, 

181 combined_denominator, 

182 ) 

183 

184 

185def _ring_forward(query, key, value, ring, causal, scale, input_layout, overlap): 

186 """Rotate KV blocks and accumulate this rank's attention output.""" 

187 exchange = _RingExchange((key, value), ring) 

188 current_key, current_value = key, value 

189 state = None 

190 for step in range(ring.size): 

191 if overlap and step + 1 < ring.size: 

192 exchange.launch((current_key, current_value)) 

193 owner = (ring.rank - step) % ring.size 

194 if not causal or owner <= ring.rank: 

195 options = _kernel_options(query, input_layout, causal and owner == ring.rank) 

196 block = torch.ops.npu.npu_fusion_attention( 

197 query, current_key, current_value, scale=scale, **options, 

198 )[:3] 

199 if state is None: 

200 state = (block[0].float(), block[1], block[2]) 

201 else: 

202 state = _merge_blocks(state, block, input_layout) 

203 if step + 1 < ring.size: 

204 current_key, current_value = (exchange.wait() if overlap 

205 else exchange.rotate((current_key, current_value))) 

206 return state[0].to(query.dtype), state[1], state[2] 

207 

208 

209def _ring_backward(saved, grad_output, ring, causal, scale, input_layout, overlap): 

210 """Accumulate local dQ and circulate each KV owner's dK/dV gradients.""" 

211 query, key, value, output, maximum, denominator = saved 

212 grad_query = torch.zeros_like(query, dtype=torch.float32) 

213 grad_key = torch.zeros_like(key, dtype=torch.float32) 

214 grad_value = torch.zeros_like(value, dtype=torch.float32) 

215 kv_exchange = _RingExchange((key, value), ring) 

216 grad_exchange = _RingExchange((grad_key, grad_value), ring) 

217 current_key, current_value = key, value 

218 for step in range(ring.size): 

219 if overlap and step + 1 < ring.size: 

220 kv_exchange.launch((current_key, current_value)) 

221 owner = (ring.rank - step) % ring.size 

222 delta_key, delta_value = None, None 

223 if not causal or owner <= ring.rank: 

224 options = _kernel_options(query, input_layout, causal and owner == ring.rank) 

225 delta_query, delta_key, delta_value = torch.ops.npu.npu_fusion_attention_grad( 

226 query, current_key, current_value, grad_output, 

227 softmax_max=maximum, softmax_sum=denominator, attention_in=output, 

228 scale_value=scale, **options, 

229 )[:3] 

230 grad_query.add_(delta_query.float()) 

231 # This block's derivatives do not depend on incoming dKV. Defer the wait 

232 # until accumulation so the preceding gradient rotation can overlap compute. 

233 if overlap and step > 0: 

234 grad_key, grad_value = grad_exchange.wait() 

235 if delta_key is not None: 

236 grad_key.add_(delta_key.float()) 

237 grad_value.add_(delta_value.float()) 

238 if not overlap and step + 1 < ring.size: 

239 current_key, current_value = kv_exchange.rotate((current_key, current_value)) 

240 # All ranks communicate, including skipped future causal blocks. The last 

241 # gradient rotation completes the cycle and returns dKV to its original owner. 

242 if overlap: 

243 grad_exchange.launch((grad_key, grad_value)) 

244 if step + 1 < ring.size: 

245 current_key, current_value = kv_exchange.wait() 

246 else: 

247 grad_key, grad_value = grad_exchange.wait() 

248 else: 

249 grad_key, grad_value = grad_exchange.rotate((grad_key, grad_value)) 

250 return grad_query.to(query.dtype), grad_key.to(key.dtype), grad_value.to(value.dtype) 

251 

252 

253def _token_axis(layout): 

254 return {"BNSD": 2, "BSND": 1, "TND": 0}[layout] 

255 

256 

257def _block_view(tensor, start, end, axis): 

258 return tensor.narrow(axis, start, end - start) 

259 

260 

261def _planned_options(query, key, layout, causal): 

262 options = _kernel_options(query, layout, causal) 

263 if causal: 

264 options["sparse_mode"] = 3 

265 if layout == "TND": 

266 options.update(head_num=query.shape[1], actual_seq_qlen=(query.shape[0],), 

267 actual_seq_kvlen=(key.shape[0],)) 

268 return options 

269 

270 

271def _empty_state(query, layout): 

272 shape = (*query.shape[:2], 8) if layout == "TND" else ( 

273 query.shape[0], query.shape[1 if layout == "BNSD" else 2], query.shape[_token_axis(layout)], 8, 

274 ) 

275 return (torch.zeros_like(query, dtype=torch.float32), 

276 query.new_full(shape, -float("inf"), dtype=torch.float32), 

277 query.new_zeros(shape, dtype=torch.float32)) 

278 

279 

280def _row_span(bounds): 

281 if all(left[1] == right[0] for left, right in zip(bounds, bounds[1:])): 

282 return bounds[0][0], bounds[-1][1] - bounds[0][0] 

283 return None 

284 

285 

286def _take_rows(tensor, indices, span): 

287 return tensor.narrow(0, *span) if span is not None else tensor.index_select(0, indices) 

288 

289 

290def _update_rows(target, source, indices, span, *, add=False): 

291 """Copy or add selected rows into an optional contiguous target span.""" 

292 if span is not None: 

293 view = target.narrow(0, *span) 

294 if add: 

295 view.add_(source) 

296 else: 

297 view.copy_(source) 

298 elif add: 

299 target.index_add_(0, indices, source) 

300 else: 

301 # Query rows are disjoint within a batch; indexed assignment avoids the 

302 # NPU scatter-copy kernel's expensive row-wise updates for wide heads. 

303 target.index_put_((indices,), source) 

304 

305 

306@lru_cache(maxsize=32) 

307@torch.inference_mode(False) 

308def _packed_indices(blocks, heads, device): 

309 """Create packed row indices and segment offsets for an attention batch.""" 

310 queries = tuple(row for part in blocks for row in range(part.query_start, part.query_end)) 

311 keys = tuple(row for part in blocks for row in range(part.key_start, part.key_end)) 

312 qlengths = tuple(part.query_end - part.query_start for part in blocks) 

313 klengths = tuple(part.key_end - part.key_start for part in blocks) 

314 decode, encode, offset = [], [], 0 

315 # Native varlen statistics use N,T order separately inside each segment. 

316 for length in qlengths: 

317 decode.extend(offset + head * length + row for row in range(length) for head in range(heads)) 

318 encode.extend(offset + row * heads + head for head in range(heads) for row in range(length)) 

319 offset += length * heads 

320 tensors = tuple(torch.tensor(rows, device=device, dtype=torch.long) for rows in (queries, keys, decode, encode)) 

321 qspan = _row_span(tuple((part.query_start, part.query_end) for part in blocks)) 

322 kspan = _row_span(tuple((part.key_start, part.key_end) for part in blocks)) 

323 return (*tensors, tuple(accumulate(qlengths)), tuple(accumulate(klengths)), qspan, kspan) 

324 

325 

326def _packed_options(query, key, blocks, ends): 

327 options = _planned_options(query, key, "TND", blocks[0].causal) 

328 options.update(actual_seq_qlen=ends[0], actual_seq_kvlen=ends[1]) 

329 return options 

330 

331 

332def _forward_packed(query, key, value, state, blocks, scale): 

333 """Run one packed attention batch and update its online-softmax state.""" 

334 rows, keys, decode, _, qends, kends, qspan, kspan = _packed_indices(blocks, query.shape[1], query.device) 

335 q_block = _take_rows(query, rows, qspan) 

336 k_block, v_block = (_take_rows(tensor, keys, kspan) for tensor in (key, value)) 

337 output, maximum, denominator = torch.ops.npu.npu_fusion_attention( 

338 q_block, k_block, v_block, scale=scale, **_packed_options(q_block, k_block, blocks, (qends, kends)), 

339 )[:3] 

340 maximum, denominator = (stat.reshape(-1, 8).index_select(0, decode).view(-1, query.shape[1], 8) 

341 for stat in (maximum, denominator)) 

342 previous = tuple(_take_rows(tensor, rows, qspan) for tensor in state) 

343 merged = _merge_blocks(previous, (output, maximum, denominator), "TND") 

344 for target, updated in zip(state, merged): 

345 _update_rows(target, updated, rows, qspan) 

346 

347 

348def _backward_packed(saved, grad_output, key, value, gradients, blocks, scale): 

349 """Compute packed block gradients and scatter them into owner buffers.""" 

350 query, _, _, output, maximum, denominator = saved 

351 rows, keys, _, encode, qends, kends, qspan, kspan = _packed_indices(blocks, query.shape[1], query.device) 

352 q_block, out, dout = (_take_rows(tensor, rows, qspan) for tensor in (query, output, grad_output)) 

353 max_block, sum_block = (_take_rows(stat, rows, qspan).reshape(-1, 8).index_select(0, encode) 

354 .view(-1, query.shape[1], 8) for stat in (maximum, denominator)) 

355 k_block, v_block = (_take_rows(tensor, keys, kspan) for tensor in (key, value)) 

356 values = torch.ops.npu.npu_fusion_attention_grad( 

357 q_block, k_block, v_block, dout, softmax_max=max_block, softmax_sum=sum_block, attention_in=out, 

358 scale_value=scale, **_packed_options(q_block, k_block, blocks, (qends, kends)), 

359 )[:3] 

360 for target, delta, indices, span in zip(gradients, values, (rows, keys, keys), (qspan, kspan, kspan)): 

361 _update_rows(target, delta.float(), indices, span, add=True) 

362 

363 

364def _forward_blocks(query, key, value, state, blocks, scale, layout, batches): 

365 """Execute rectangular blocks in batches and merge their attention states.""" 

366 if layout == "TND" and len(blocks) > 1: 

367 for batch in batches: 

368 _forward_packed(query, key, value, state, batch, scale) 

369 return 

370 axis, stats_axis = _token_axis(layout), 0 if layout == "TND" else 2 

371 for part in blocks: 

372 q_block = _block_view(query, part.query_start, part.query_end, axis).contiguous() 

373 k_block = _block_view(key, part.key_start, part.key_end, axis).contiguous() 

374 v_block = _block_view(value, part.key_start, part.key_end, axis).contiguous() 

375 block = torch.ops.npu.npu_fusion_attention( 

376 q_block, k_block, v_block, scale=scale, **_planned_options(q_block, k_block, layout, part.causal), 

377 )[:3] 

378 if layout == "TND": 

379 # NPU exposes [T,N,8] metadata but stores each single-segment statistic 

380 # in N,T order. Decode before row-wise merging; backward re-encodes it. 

381 block = (block[0], *(stat.reshape(q_block.shape[1], q_block.shape[0], 8).transpose(0, 1) 

382 for stat in block[1:])) 

383 previous = tuple(_block_view(tensor, part.query_start, part.query_end, dim) 

384 for tensor, dim in zip(state, (axis, stats_axis, stats_axis))) 

385 merged = _merge_blocks(previous, block, layout) 

386 for target, source in zip(previous, merged): 

387 target.copy_(source) 

388 

389 

390def _planned_forward(query, key, value, ring, scale, layout, overlap, plan): 

391 """Run a task-planned Ring forward pass with bounded KV transport.""" 

392 exchange = _RingExchange((key, value), ring) 

393 state = _empty_state(query, layout) 

394 for step in range(ring.size): 

395 if overlap and step + 1 < ring.size: 

396 exchange.launch((key, value)) 

397 owner = (ring.rank - step) % ring.size 

398 _forward_blocks(query, key, value, state, plan.blocks[owner], scale, layout, plan.batches[owner]) 

399 if step + 1 < ring.size: 

400 key, value = exchange.wait() if overlap else exchange.rotate((key, value)) 

401 return state[0].to(query.dtype), state[1], state[2] 

402 

403 

404def _backward_blocks(saved, grad_output, key, value, grad_query, blocks, scale, layout, batches): 

405 """Accumulate gradients for one set of planned query/key blocks.""" 

406 query, _, _, output, maximum, denominator = saved 

407 axis, stats_axis = _token_axis(layout), 0 if layout == "TND" else 2 

408 delta_key, delta_value = torch.zeros_like(key, dtype=torch.float32), torch.zeros_like(value, dtype=torch.float32) 

409 if layout == "TND" and len(blocks) > 1: 

410 for batch in batches: 

411 _backward_packed(saved, grad_output, key, value, (grad_query, delta_key, delta_value), batch, scale) 

412 return delta_key, delta_value 

413 for part in blocks: 

414 q_block, out, dout = (_block_view(tensor, part.query_start, part.query_end, axis).contiguous() 

415 for tensor in (query, output, grad_output)) 

416 max_block, sum_block = (_block_view(tensor, part.query_start, part.query_end, stats_axis).contiguous() 

417 for tensor in (maximum, denominator)) 

418 if layout == "TND": 

419 max_block, sum_block = (stat.transpose(0, 1).contiguous().reshape(q_block.shape[0], q_block.shape[1], 8) 

420 for stat in (max_block, sum_block)) 

421 k_block, v_block = (_block_view(tensor, part.key_start, part.key_end, axis).contiguous() 

422 for tensor in (key, value)) 

423 dq, dk, dv = torch.ops.npu.npu_fusion_attention_grad( 

424 q_block, k_block, v_block, dout, softmax_max=max_block, softmax_sum=sum_block, 

425 attention_in=out, scale_value=scale, **_planned_options(q_block, k_block, layout, part.causal), 

426 )[:3] 

427 _block_view(grad_query, part.query_start, part.query_end, axis).add_(dq.float()) 

428 _block_view(delta_key, part.key_start, part.key_end, axis).add_(dk.float()) 

429 _block_view(delta_value, part.key_start, part.key_end, axis).add_(dv.float()) 

430 return delta_key, delta_value 

431 

432 

433def _planned_backward(saved, grad_output, ring, scale, layout, overlap, plan): 

434 """Run backward for planned blocks and return each KV gradient to its owner.""" 

435 query, key, value = saved[:3] 

436 grad_query, grad_key, grad_value = (torch.zeros_like(tensor, dtype=torch.float32) for tensor in saved[:3]) 

437 exchange = _RingExchange((key, value), ring) 

438 grad_exchange = _RingExchange((grad_key, grad_value), ring) 

439 for step in range(ring.size): 

440 if overlap and step + 1 < ring.size: 

441 exchange.launch((key, value)) 

442 owner = (ring.rank - step) % ring.size 

443 delta_key, delta_value = _backward_blocks(saved, grad_output, key, value, grad_query, 

444 plan.blocks[owner], scale, layout, plan.batches[owner]) 

445 if overlap and step: 

446 grad_key, grad_value = grad_exchange.wait() 

447 grad_key.add_(delta_key) 

448 grad_value.add_(delta_value) 

449 if not overlap and step + 1 < ring.size: 

450 key, value = exchange.rotate((key, value)) 

451 if overlap: 

452 grad_exchange.launch((grad_key, grad_value)) 

453 if step + 1 < ring.size: 

454 key, value = exchange.wait() 

455 else: 

456 grad_key, grad_value = grad_exchange.wait() 

457 else: 

458 grad_key, grad_value = grad_exchange.rotate((grad_key, grad_value)) 

459 return grad_query.to(query.dtype), grad_key.to(key.dtype), grad_value.to(value.dtype) 

460 

461 

462def _launch_pruned(exchange, packet, overlap, step): 

463 if not overlap: 

464 exchange.stream.wait_stream(torch.npu.current_stream()) 

465 received = exchange.launch(packet, step) 

466 if not overlap: 

467 received.ready() 

468 return received 

469 

470 

471def _pruned_forward(query, key, value, ring, scale, overlap, plan): 

472 """Execute Ring forward using each owner's pruned document-local KV spans.""" 

473 initial = _pack_ring_kv((key, value), plan.source_spans, ring, plan.counts) 

474 exchange = _PackedRingExchange(key, plan, ring, _communication_stream(query.device, False)) 

475 state, packet = _empty_state(query, "TND"), initial 

476 for step in range(max(plan.hops) + 1): 

477 following = exchange.launch(packet, step) if overlap and step < max(plan.hops) else None 

478 blocks, batches = (plan.local_blocks, plan.local_batches) if step == 0 else ( 

479 plan.blocks[packet.owner], plan.batches[packet.owner]) 

480 if blocks: 

481 packet.ready() 

482 keys, values = (key, value) if step == 0 else packet.tensors() 

483 _forward_blocks(query, keys, values, state, blocks, scale, "TND", batches) 

484 packet.consumed_now() 

485 if not overlap and step < max(plan.hops): 

486 following = _launch_pruned(exchange, packet, False, step) 

487 packet = following 

488 if step == max(plan.hops): 

489 exchange.finish(initial) 

490 return state[0].to(query.dtype), state[1], state[2] 

491 

492 

493def _pruned_delta(saved, grad_output, grad_query, packet, plan, scale, step): 

494 blocks, batches = (plan.local_blocks, plan.local_batches) if step == 0 else ( 

495 plan.blocks[packet.owner], plan.batches[packet.owner]) 

496 if not blocks: 

497 return None 

498 packet.ready() 

499 keys, values = saved[1:3] if step == 0 else packet.tensors() 

500 delta = _backward_blocks(saved, grad_output, keys, values, grad_query, blocks, scale, "TND", batches) 

501 packet.consumed_now() 

502 return delta 

503 

504 

505def _pruned_accumulate(gradient, delta, local_gradients, ring, plan, step): 

506 """Accumulate local dKV and add contributions received from Ring workers.""" 

507 if delta is None: 

508 return 

509 gradient.ready() 

510 if step == 0: 

511 for target, source in zip(local_gradients, delta): 

512 target.add_(source) 

513 _pack_ring_kv(local_gradients, plan.source_spans, ring, plan.counts, out=gradient) 

514 return 

515 for target, source in zip(gradient.tensors(), delta): 

516 target.add_(source) 

517 gradient.produced_now() 

518 

519 

520def _restore_pruned_gradient(local_gradients, gradient, ring, plan): 

521 gradient.ready() 

522 for target, source in zip(local_gradients, gradient.tensors()): 

523 offset = 0 

524 for start, end in plan.source_spans[ring.rank]: 

525 length = end - start 

526 target[start:end].copy_(source[offset:offset + length]) 

527 offset += length 

528 gradient.consumed_now() 

529 

530 

531def _pruned_backward(saved, grad_output, ring, scale, overlap, plan): 

532 """Backpropagate pruned Ring blocks and restore local KV gradient layout.""" 

533 query, key, value = saved[:3] 

534 grad_query, grad_key, grad_value = (torch.zeros_like(tensor, dtype=torch.float32) for tensor in saved[:3]) 

535 initial = _pack_ring_kv((key, value), plan.source_spans, ring, plan.counts) 

536 grad_initial = _pack_ring_kv((grad_key, grad_value), plan.source_spans, ring, plan.counts) 

537 exchange = _PackedRingExchange(key, plan, ring, _communication_stream(query.device, False)) 

538 grad_exchange = _PackedRingExchange(grad_key, plan, ring, _communication_stream(query.device, True)) 

539 packet, gradient = initial, grad_initial 

540 for step in range(max(plan.hops) + 1): 

541 following = exchange.launch(packet, step) if overlap and step < max(plan.hops) else None 

542 delta = _pruned_delta(saved, grad_output, grad_query, packet, plan, scale, step) 

543 _pruned_accumulate(gradient, delta, (grad_key, grad_value), ring, plan, step) 

544 if not overlap and step < max(plan.hops): 

545 following = _launch_pruned(exchange, packet, False, step) 

546 next_gradient = _launch_pruned(grad_exchange, gradient, overlap, step) if step < max(plan.hops) else None 

547 if not overlap: 

548 grad_exchange.stream.wait_stream(torch.npu.current_stream()) 

549 _return_ring_gradient(gradient, grad_initial, plan, ring, grad_exchange.stream, step) 

550 packet, gradient = following, next_gradient 

551 if step == max(plan.hops): 

552 _restore_pruned_gradient((grad_key, grad_value), grad_initial, ring, plan) 

553 exchange.finish(initial) 

554 grad_exchange.finish(grad_initial) 

555 return tuple(grad.to(tensor.dtype) for grad, tensor in zip((grad_query, grad_key, grad_value), saved[:3])) 

556 

557 

558class _RingAttention(torch.autograd.Function): 

559 """Pair raw P2P forward transport with an explicit gradient-return ring.""" 

560 

561 @staticmethod 

562 def forward( 

563 ctx: Any, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

564 ring: _RingContext, causal: bool, scale: float, input_layout: str, overlap: bool, 

565 plan: Any = None, 

566 ) -> torch.Tensor: 

567 """Save only local inputs, the final output and global softmax statistics.""" 

568 query, key, value = (tensor.contiguous() for tensor in (query, key, value)) 

569 if isinstance(plan, PrunedRingPlan): 

570 output, maximum, denominator = _pruned_forward(query, key, value, ring, scale, overlap, plan) 

571 elif plan is None: 

572 output, maximum, denominator = _ring_forward( 

573 query, key, value, ring, causal, scale, input_layout, overlap, 

574 ) 

575 else: 

576 output, maximum, denominator = _planned_forward( 

577 query, key, value, ring, scale, input_layout, overlap, plan, 

578 ) 

579 ctx.save_for_backward(query, key, value, output, maximum, denominator) 

580 ctx.ring = ring 

581 ctx.causal = causal 

582 ctx.scale = scale 

583 ctx.input_layout = input_layout 

584 ctx.overlap = overlap 

585 ctx.plan = plan 

586 return output 

587 

588 @staticmethod 

589 @once_differentiable 

590 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple: 

591 """Sum local dQ and circulate dKV without a CP-size averaging factor.""" 

592 if isinstance(ctx.plan, PrunedRingPlan): 

593 gradients = _pruned_backward(ctx.saved_tensors, grad_output.contiguous(), ctx.ring, ctx.scale, 

594 ctx.overlap, ctx.plan) 

595 elif ctx.plan is None: 

596 gradients = _ring_backward( 

597 ctx.saved_tensors, grad_output.contiguous(), ctx.ring, ctx.causal, ctx.scale, ctx.input_layout, 

598 ctx.overlap, 

599 ) 

600 else: 

601 gradients = _planned_backward(ctx.saved_tensors, grad_output.contiguous(), ctx.ring, ctx.scale, 

602 ctx.input_layout, ctx.overlap, ctx.plan) 

603 return (*gradients, *(None for _ in range(len(ctx.needs_input_grad) - 3))) 

604 

605 

606def _validate_tensor_ranks(tensors, input_layout): 

607 dimensions = 3 if input_layout == "TND" else 4 

608 if any(not isinstance(tensor, torch.Tensor) or tensor.ndim != dimensions for tensor in tensors): 

609 raise ValueError("query, key and value must be three-dimensional TND or four-dimensional BNSD/BSND tensors") 

610 if any(hasattr(tensor, "to_local") for tensor in tensors): 

611 raise ValueError("ring_attention requires local tensors; convert DTensors before calling") 

612 if any(dimension < 1 for tensor in tensors for dimension in tensor.shape): 

613 raise ValueError("query, key and value dimensions must be nonempty") 

614 

615 

616def _validate_tensor_shapes(query, key, value, input_layout): 

617 head_dim = 2 if input_layout == "BSND" else 1 

618 sequence_dim = _token_axis(input_layout) 

619 if key.shape != value.shape: 

620 raise ValueError("key and value must have equal shapes in the initial MHA/GQA implementation") 

621 equal_axes = (0, 2) if input_layout == "TND" else (0, sequence_dim, 3) 

622 if any(query.shape[axis] != key.shape[axis] for axis in equal_axes): 

623 raise ValueError("query and key must have equal batch, local sequence and head dimensions") 

624 if query.shape[head_dim] % key.shape[head_dim]: 

625 raise ValueError("the query head count must be divisible by the KV head count") 

626 

627 

628def _validate_tensor_dtype_device(query, key, value): 

629 tensors = (query, key, value) 

630 if query.dtype not in (torch.float16, torch.bfloat16) or any(tensor.dtype != query.dtype for tensor in tensors): 

631 raise ValueError("query, key and value must share FP16 or BF16 dtype") 

632 if query.device.type != "npu" or any(tensor.device != query.device for tensor in tensors): 

633 raise ValueError("ring_attention currently requires all inputs on the same NPU") 

634 

635 

636def _validate_inputs(query, key, value, causal, input_layout, overlap): 

637 """Validate Ring tensor layout, causal mode, dtype, and device contracts.""" 

638 if not isinstance(overlap, bool): 

639 raise ValueError("overlap must be bool") 

640 if input_layout not in ("BNSD", "BSND", "TND"): 

641 raise ValueError("ring_attention supports only BNSD, BSND and TND layouts") 

642 if not isinstance(causal, bool): 

643 raise ValueError("causal must be bool") 

644 tensors = (query, key, value) 

645 _validate_tensor_ranks(tensors, input_layout) 

646 _validate_tensor_shapes(query, key, value, input_layout) 

647 _validate_tensor_dtype_device(query, key, value) 

648 

649 

650def _prepare_task_plan(query, layout, size, rank, causal, load_balance, lengths, 

651 document_subrings=False): 

652 """Build this rank's exact attention task schedule from global metadata.""" 

653 tokens = query.shape[_token_axis(layout)] * size 

654 if layout == "TND": 

655 if (not isinstance(lengths, tuple) or not lengths 

656 or any(not isinstance(length, int) or isinstance(length, bool) or length < 1 for length in lengths) 

657 or sum(lengths) != tokens): 

658 raise ValueError("TND requires global document_lengths as a host tuple summing to global tokens") 

659 elif lengths is not None: 

660 raise ValueError("document_lengths requires TND layout") 

661 return ring_task_plan((tokens,) if lengths is None else lengths, size, rank, load_balance, causal, 

662 document_subrings=document_subrings) 

663 

664 

665def _validate_pruning(prune_documents): 

666 if not isinstance(prune_documents, bool): 

667 raise ValueError("prune_documents must be bool") 

668 

669 

670def ring_attention( 

671 query: torch.Tensor, 

672 key: torch.Tensor, 

673 value: torch.Tensor, 

674 cp_mesh: Any = None, 

675 *, 

676 causal: bool = False, 

677 input_layout: str = "BNSD", 

678 overlap: bool = False, 

679 load_balance: str = "none", 

680 prune_documents: bool = True, 

681 document_lengths: tuple[int, ...] | None = None, 

682) -> torch.Tensor: 

683 """Compute NPU MHA/GQA attention and restore original contiguous sequence ownership. 

684 

685 Args: 

686 query: Local Q in BNSD/BSND or packed TND, with tokens equal to global tokens / CP. 

687 key: Compact local K; KV heads need not be divisible by CP degree. 

688 value: Local V with the same shape as K, including head dimension. 

689 cp_mesh: One-dimensional framework CP mesh, or None for single-rank execution. 

690 causal: Apply global causal order, with token shards ordered by CP group rank. 

691 input_layout: BNSD, BSND, or packed TND; shared by Q, K, V and output. 

692 overlap: Prefetch KV and pipeline dKV communication with block computation. 

693 load_balance: Query layout, either contiguous ``none`` or ``zigzag``. 

694 prune_documents: Build per-document Ring subplans; can be combined with load_balance. 

695 document_lengths: Global positive document lengths, required for TND only. 

696 Supply identical host tuples on all ranks; total equals local tokens times CP. 

697 

698 Returns: 

699 Attention output for this rank's Q shard, with Q's shape and dtype. 

700 

701 Raises: 

702 ValueError: If the tensor, mesh, dtype or attention options are unsupported. 

703 

704 Note: 

705 All ranks must use identical shapes, dtypes and options and enter forward 

706 and backward in the same order, including ranks with zero upstream gradient. 

707 Gradients represent the sum of the group ranks' local losses; no CP-size 

708 division is applied. TND documents are isolated; padding must be removed 

709 before calling. Explicit masks, higher-order gradients, and unequal source 

710 shards are unsupported. Internal task sizes may differ; communication pads 

711 to a common capacity and kernels operate only on real rows. Packed attention 

712 batches disjoint query intersections in native TND calls with bounded KV packing. Native backward 

713 may have atomic reduction roundoff; exact repeatability requires 

714 torch.use_deterministic_algorithms(True). 

715 """ 

716 _validate_pruning(prune_documents) 

717 if load_balance not in ("none", "zigzag"): 

718 raise ValueError("load_balance must be none or zigzag") 

719 _validate_inputs(query, key, value, causal, input_layout, overlap) 

720 ring = _ring_context(cp_mesh) 

721 # Register optional NPU operators only when the NPU implementation is invoked. 

722 import torch_npu # pylint: disable=C0415,unused-import 

723 

724 scale = query.shape[-1] ** -0.5 

725 prune_documents = prune_documents and input_layout == "TND" 

726 plan = _prepare_task_plan(query, input_layout, ring.size, ring.rank, causal, load_balance, 

727 document_lengths, document_subrings=prune_documents) 

728 if prune_documents: 

729 if load_balance != "none": 

730 query, key, value = redistribute_ring_qkv( 

731 query, key, value, plan, ring.group, _token_axis(input_layout), 

732 2 if input_layout == "BSND" else 1, 

733 ) 

734 pruning_plan = pruned_ring_plan( 

735 document_lengths, ring.size, ring.rank, causal, plan.assignments, 

736 ) 

737 output = _RingAttention.apply( 

738 query, key, value, ring, causal, scale, "TND", overlap, pruning_plan, 

739 ) 

740 if load_balance != "none": 

741 output = redistribute_ring_rows(output, plan, ring.group, _token_axis(input_layout), inverse=True) 

742 return output 

743 if load_balance == "none" and input_layout != "TND": 

744 return _RingAttention.apply(query, key, value, ring, causal, scale, input_layout, overlap) 

745 axis = _token_axis(input_layout) 

746 if load_balance != "none": 

747 head_dim = 2 if input_layout == "BSND" else 1 

748 query, key, value = redistribute_ring_qkv(query, key, value, plan, ring.group, axis, head_dim) 

749 if input_layout != "TND" and not plan.fast_zigzag: 

750 batch, heads = query.shape[0], query.shape[head_dim] 

751 # Dense samples share the same mask. Folding independent batches into 

752 # heads preserves GQA groups and avoids duplicating the document plan. 

753 query, key, value = (tensor.permute(axis, 0, head_dim, 3).flatten(1, 2) 

754 for tensor in (query, key, value)) 

755 output = _RingAttention.apply(query, key, value, ring, causal, scale, "TND", overlap, plan) 

756 output = output.view(-1, batch, heads, output.shape[-1]) 

757 output = output.permute(1, 2, 0, 3) if input_layout == "BNSD" else output.permute(1, 0, 2, 3) 

758 else: 

759 output = _RingAttention.apply(query, key, value, ring, causal, scale, input_layout, overlap, plan) 

760 if load_balance != "none": 

761 output = redistribute_ring_rows(output, plan, ring.group, axis, inverse=True) 

762 return output