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"""GQA Ulysses/KV-AllGather and Ring execution over the shared CP family."""
16
17from __future__ import annotations
18
19import math
20from dataclasses import dataclass
21from functools import lru_cache
22from itertools import accumulate
23from typing import Any
24
25import torch
26
27from hyper_parallel.components.functional.npu_fusion_attention import (
28 PACKED_SEQUENCE_ARGUMENTS, resolve_packed_sequence_lengths,
29)
30from hyper_parallel.distributed.context_parallel.cp_context import CPContext
31from hyper_parallel.distributed.context_parallel.ring_attention import ring_attention
32from hyper_parallel.distributed.module_binding import ParallelModuleSpec
33from .grouped_query_attention import GQAInputs, GroupedQueryAttentionModule
34from .grouped_query_attention_family import _gqa_cp_options, validate_gqa_layout
35
36
37# Ordinary CP document and mask helpers.
38@lru_cache(maxsize=128)
39def _query_documents(lengths: tuple[int, ...], batch: int, global_length: int,
40 query_length: int, query_rank: int, causal: bool) -> tuple:
41 """Map each batch-local query interval to its documents and visible KV prefixes.
42
43 Lengths describe the global, batch-major TND sequence. A document may cross
44 rank or batch boundaries: each local query fragment gets the correct KV
45 prefix (or whole document for noncausal attention), not other documents.
46 The returned ranges address a flattened global KV tensor. No device reads
47 or S-by-S document mask are needed.
48 """
49 ranges, query_counts, key_counts = [], [], []
50 starts = (0, *lengths[:-1])
51 for batch_index in range(batch):
52 query_begin = batch_index * global_length + query_rank * query_length
53 query_end = query_begin + query_length
54 for start, end in zip(starts, lengths):
55 begin, stop = max(start, query_begin), min(end, query_end)
56 if begin < stop:
57 key_end = stop if causal else end
58 ranges.append((start, key_end))
59 query_counts.append(stop - begin)
60 key_counts.append(key_end - start)
61 return tuple(ranges), tuple(accumulate(query_counts)), tuple(accumulate(key_counts))
62
63
64def _select_document_keys(tensor: torch.Tensor, ranges: tuple) -> torch.Tensor:
65 """Select batch-major KV document fragments while autograd sums reused prefixes."""
66 flat = tensor.flatten(0, 1)
67 # Preserve document boundaries in FA metadata without copying a complete
68 # contiguous KV span. Keep partial multi-document spans compact: a view
69 # would otherwise retain the entire gathered storage until FA backward.
70 if (ranges[0][0] == 0 and ranges[-1][1] == flat.shape[0]
71 and all(left[1] == right[0] for left, right in zip(ranges, ranges[1:]))):
72 return flat.unsqueeze(0)
73 pieces = [flat.narrow(0, begin, end - begin) for begin, end in ranges]
74 return (pieces[0] if len(pieces) == 1 else torch.cat(pieces, dim=0)).unsqueeze(0)
75
76
77def _local_mask(mask: torch.Tensor, global_length: int, query_length: int,
78 query_begin: int, key_end: int) -> torch.Tensor:
79 """Slice global Q/K masks; two-dimensional non-square masks are batch padding."""
80 if mask.shape[-1] != global_length:
81 raise ValueError("GQA CP mask must cover the global key sequence")
82 if mask.ndim == 2 and mask.shape == (global_length, global_length):
83 mask = mask[None, None]
84 if mask.ndim >= 3 and mask.shape[-2] not in (1, query_length):
85 if mask.shape[-2] != global_length:
86 raise ValueError("GQA CP query mask must cover the local or global query interval")
87 mask = mask[..., query_begin:query_begin + query_length, :]
88 return mask[..., :key_end]
89
90
91def _valid_query_rows(mask: torch.Tensor | None, batch: int, global_length: int,
92 query_length: int, query_rank: int) -> torch.Tensor | None:
93 """Restore query padding after CP makes the Q and KV lengths unequal.
94
95 The common FA can infer padded queries from a self-attention mask only
96 when Q/K cover the same tokens. Here the CP rank owns a query interval
97 inside global KV; slice its rows explicitly after FA.
98 """
99 if mask is None or mask.ndim != 2 or mask.shape == (global_length, global_length):
100 return None
101 if mask.shape != (batch, global_length):
102 raise ValueError("GQA CP padding mask must have shape [batch, global_sequence]")
103 begin = query_rank * query_length
104 return mask[:, begin:begin + query_length].to(torch.bool)
105
106
107# Per-call state records for the concrete CP algorithms.
108@dataclass(frozen=True)
109class CPGQAPreparedInputs:
110 """Ordinary CP prepared state; Ring CP never consumes this type.
111
112 Pending transfers are consumed only by ordinary CP's exchange stage.
113
114 Q/K/V use BSND order. A non-None pending field owns an unfinished transfer;
115 the corresponding tensor has not yet changed to its destination layout.
116 This state stays local to forward and is released before FA execution.
117 """
118
119 query: torch.Tensor
120 key: torch.Tensor
121 value: torch.Tensor
122 query_pending: Any
123 key_pending: Any
124 value_pending: Any
125 attention_mask: torch.Tensor | None
126 lengths: tuple[int, ...] | None
127 options: dict[str, Any]
128 output_state: Any
129
130
131@dataclass(frozen=True)
132class CPGQAOutputState:
133 """Output-only invocation state; it must not retain the exchanged Q/K/V."""
134
135 query_shape: tuple[int, int]
136 valid_queries: torch.Tensor | None
137 projection_state: Any
138
139
140@dataclass(frozen=True)
141class RingGQAPreparedInputs:
142 """Ring-only projected operands and global packed-document metadata."""
143
144 query: torch.Tensor
145 key: torch.Tensor
146 value: torch.Tensor
147 input_layout: str
148 document_lengths: tuple[int, ...] | None
149 causal: bool
150 cp_mesh: Any
151 load_balance: str
152 prune_documents: bool
153 output_state: CPGQAOutputState
154
155
156def _prepare_cp_attention_metadata(module: torch.nn.Module, hidden_states: torch.Tensor,
157 attention_mask: torch.Tensor | None, past_key_values: Any,
158 actual_seq_len: Any, kwargs: dict[str, Any]) -> tuple:
159 """Validate common CP metadata and remove packed-sequence aliases from options."""
160 if past_key_values is not None:
161 raise ValueError("GQA CP training does not support a KV cache")
162 batch, local_length = hidden_states.shape[:2]
163 global_length = local_length * module.cp_context.size
164 options = dict(kwargs, actual_seq_len=actual_seq_len)
165 q_lengths, k_lengths = resolve_packed_sequence_lengths(
166 options, query_tokens=batch * global_length, key_tokens=batch * global_length)
167 if q_lengths != k_lengths:
168 raise ValueError("GQA CP self-attention requires matching global query/KV document lengths")
169 if q_lengths is not None and attention_mask is not None:
170 raise ValueError("GQA CP packed lengths cannot be combined with an explicit mask")
171 options = {name: value for name, value in kwargs.items() if name not in PACKED_SEQUENCE_ARGUMENTS}
172 return q_lengths, options
173
174
175# Ring-only document planning helpers.
176def _lengths_from_cumulative(values: Any) -> tuple[int, ...]:
177 """Convert model-facing cumulative endpoints to Ring planner document lengths."""
178 previous = 0
179 lengths = []
180 for endpoint in values:
181 length = int(endpoint) - previous
182 if length < 1:
183 raise ValueError("Ring GQA packed document endpoints must be strictly increasing")
184 lengths.append(length)
185 previous = int(endpoint)
186 return tuple(lengths)
187
188
189def _ring_document_lengths(cumulative_lengths: Any, options: dict[str, Any]) -> tuple[int, ...] | None:
190 """Resolve packed lengths supplied as cumulative endpoints or explicit document sizes."""
191 lengths = None if cumulative_lengths is None else _lengths_from_cumulative(cumulative_lengths)
192 explicit_lengths = options.get("document_lengths")
193 if explicit_lengths is None:
194 return lengths
195 explicit_lengths = tuple(explicit_lengths)
196 if not explicit_lengths or any(not isinstance(length, int) or isinstance(length, bool) or length < 1
197 for length in explicit_lengths):
198 raise ValueError("Ring GQA document_lengths must contain positive integers")
199 if lengths is not None and lengths != explicit_lengths:
200 raise ValueError("document_lengths conflicts with packed sequence metadata")
201 return explicit_lengths
202
203
204def _validate_ring_options(module: torch.nn.Module, attention_mask: torch.Tensor | None,
205 options: dict[str, Any]) -> bool:
206 """Validate Ring's supported GQA options and return the causal setting."""
207 if attention_mask is not None:
208 raise ValueError("Ring GQA does not support an explicit attention mask")
209 if module.training and module.attention_dropout != 0:
210 raise ValueError("Ring GQA requires attention dropout=0")
211 if module.sliding_window is not None:
212 raise ValueError("Ring GQA does not support sliding_window")
213 if (not isinstance(module.scaling, (int, float)) or isinstance(module.scaling, bool)
214 or not math.isclose(module.scaling, module.qk_head_dim ** -0.5, rel_tol=1e-12)):
215 raise ValueError("Ring GQA requires the default inverse-square-root attention scaling")
216 for name in ("sliding_window", "window_size", "softcap", "alibi_slopes", "attention_bias"):
217 if options.get(name) is not None:
218 raise ValueError(f"Ring GQA does not support {name}")
219 if options.get("use_cache", False):
220 raise ValueError("Ring GQA does not support a KV cache")
221 if options.get("output_attentions", False):
222 raise ValueError("Ring GQA does not return attention weights")
223 # These are model dispatch metadata; the attention already receives RoPE embeddings.
224 ignored = {"position_ids", "output_router_logits"}
225 supported = {"is_causal", "use_cache", "output_attentions", "document_lengths"}
226 unknown = sorted(name for name, value in options.items()
227 if name not in supported and name not in ignored and value is not None)
228 if unknown:
229 raise ValueError(f"Ring GQA does not support attention options {unknown}")
230 causal = options.get("is_causal", module.is_causal)
231 if not isinstance(causal, bool):
232 raise ValueError("Ring GQA is_causal must be bool")
233 return causal
234
235
236def _ring_layout(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
237 batch: int, local_length: int, ring_size: int,
238 lengths: tuple[int, ...] | None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, str]:
239 """Validate packed metadata and return Ring operands in BSND or TND layout."""
240 if lengths is None:
241 return query, key, value, "BSND"
242 if batch != 1:
243 raise ValueError("Ring GQA packed attention requires batch size one")
244 if sum(lengths) != local_length * ring_size:
245 raise ValueError("Ring GQA document lengths must sum to the global token count")
246 query, key, value = (tensor.squeeze(0).contiguous() for tensor in (query, key, value))
247 return query, key, value, "TND"
248
249
250class _CPGroupedQueryAttentionBase(GroupedQueryAttentionModule):
251 """Shared CP runtime for ordinary and Ring GQA members.
252
253 This base owns CP configuration, mesh binding, position slicing and output
254 restoration. Concrete subclasses own their prepared state, communication
255 schedule and attention evaluation.
256 """
257
258 def __init__(self, *, module: torch.nn.Module | None = None, config: Any = None,
259 module_fqn: str = "", context: Any = None, fuse_qkv: bool = True) -> None:
260 """Read CP scheduling options from the attention config, outside local GQA math."""
261 del module_fqn, context
262 super().__init__(config=config, module=module, fuse_qkv=fuse_qkv)
263 options = _gqa_cp_options(self.config)
264 self.ulysses_cp_size = options["ulysses_cp_size"]
265 self.ulysses_cp_strategy = options["ulysses_cp_strategy"]
266 self.kv_cp_size = options["kv_cp_size"]
267 self.kv_cp_strategy = options["kv_cp_strategy"]
268 self.ring_cp_size = options["ring_cp_size"]
269 self.ring_cp_strategy = options["ring_cp_strategy"]
270 self.cp_comm_overlap = options["cp_comm_overlap"]
271
272 def parallel_module_spec(self) -> ParallelModuleSpec:
273 """Request borrowed CP resources in addition to the shared TP boundary."""
274 return ParallelModuleSpec("attention.gqa.cp", "cp",
275 {"prepare_attention_inputs": ("hidden_states", "positions"),
276 "exchange_attention": ("prepared",),
277 "restore_attention": ("output", "output_state")},
278 validate=validate_gqa_layout)
279
280 def bind_parallel(self, binding: Any) -> None:
281 """Bind the configured CP axes once and validate TP-local head divisibility.
282
283 Args:
284 binding: Final module layout and the existing job's TP/CP resources.
285 """
286 if binding.cp_context is None:
287 raise ValueError("GQA CP requires a bound CPContext")
288 self.cp_context = binding.cp_context
289 configured_cp_size = self.ulysses_cp_size * self.kv_cp_size * self.ring_cp_size
290 if configured_cp_size != self.cp_context.size:
291 raise ValueError(
292 "GQA CP factors must multiply to accelerator.cp_size: "
293 f"{self.ulysses_cp_size} × {self.kv_cp_size} × {self.ring_cp_size} "
294 f"!= {self.cp_context.size}"
295 )
296 # The row-major rank order is [ring, kv, ulysses]. Ring and KV are
297 # mutually exclusive domains; when present, Ulysses ranks own adjacent
298 # source chunks within their Ring or KV group.
299 factors = (self.ring_cp_size, self.kv_cp_size, self.ulysses_cp_size)
300 names = ("ring", "kv", "ulysses")
301 mesh = self.cp_context.mesh
302 if mesh.size() > 1:
303 mesh = mesh._unflatten("cp", factors, names) # pylint: disable=protected-access
304 self.ring_context, self.kv_context, self.ulysses_context = (
305 CPContext(mesh[name]) for name in names
306 )
307 if self.num_heads % self.ulysses_cp_size or self.num_key_value_heads % self.ulysses_cp_size:
308 raise ValueError("GQA ulysses_cp_size must divide TP-local Q and KV heads")
309
310 def prepare_positions(self, query_shape: tuple[int, int], positions: Any) -> Any:
311 """Map global position tables into this rank's original local token interval."""
312 if not hasattr(self, "cp_context"):
313 raise RuntimeError("Bind GQA CP execution before forward")
314 if positions is None:
315 return None
316 local_length = query_shape[1]
317 global_length = local_length * self.cp_context.size
318 parts = []
319 for part in positions:
320 if part.shape[-2] == global_length:
321 part = part.narrow(-2, self.cp_context.rank * local_length, local_length)
322 elif part.shape[-2] != local_length:
323 raise ValueError("GQA CP positions must cover the local or global token sequence")
324 parts.append(part)
325 return tuple(parts)
326
327 def restore_attention(self, output: torch.Tensor,
328 output_state: CPGQAOutputState) -> tuple[torch.Tensor, Any]:
329 """Restore token and head ownership before the output projection."""
330 output = output.reshape(*output_state.query_shape, output.shape[-2], output.shape[-1])
331 if output_state.valid_queries is not None:
332 output = output.masked_fill(~output_state.valid_queries[:, :, None, None], 0)
333 if self.ulysses_cp_size > 1:
334 output = self.ulysses_context.head_to_sequence(output)
335 return output, output_state.projection_state
336
337
338class CPGroupedQueryAttentionModule(_CPGroupedQueryAttentionBase):
339 """GQA CP member for Ulysses and KV AllGather execution."""
340
341 def bind_parallel(self, binding: Any) -> None:
342 """Bind ordinary CP and identify the KV rank that owns local queries."""
343 super().bind_parallel(binding)
344 self.query_context = self.kv_context
345
346 def _transfer_input(self, tensor: torch.Tensor, *, is_query: bool) -> tuple[torch.Tensor, Any]:
347 """Keep Q local for KV AllGather; exchange operands for Ulysses."""
348 if self.ulysses_cp_size > 1:
349 if self.cp_comm_overlap:
350 return tensor, self.ulysses_context.launch_sequence_to_head(tensor)
351 return self.ulysses_context.sequence_to_head(tensor), None
352 if self.cp_comm_overlap and self.kv_cp_size > 1 and not is_query:
353 return tensor, self.query_context.launch_gather_sequence(tensor).collective
354 return tensor, None
355
356 def _finish_input_transfers(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
357 query_pending: Any, key_pending: Any, value_pending: Any) -> tuple:
358 """Complete ordinary CP's Ulysses and KV AllGather transfers."""
359 if self.cp_comm_overlap:
360 if self.ulysses_cp_size > 1:
361 if self.kv_cp_size > 1:
362 key_gather = self.query_context.launch_gather_sequence(key_pending.wait())
363 value_gather = self.query_context.launch_gather_sequence(value_pending.wait())
364 return query_pending.wait(), key_gather.wait()[0], value_gather.wait()[0]
365 return query_pending.wait(), key_pending.wait(), value_pending.wait()
366 if self.kv_cp_size > 1:
367 return query, key_pending.wait(), value_pending.wait()
368 elif self.kv_cp_size > 1:
369 key = self.query_context.gather_sequence(key)[0]
370 value = self.query_context.gather_sequence(value)[0]
371 return query, key, value
372
373 def _attention_operands(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
374 attention_mask: torch.Tensor | None, lengths: Any, options: dict,
375 output_state: Any) -> GQAInputs:
376 """Convert global packed metadata into the actual FA query/KV document fragments."""
377 batch, query_length = query.shape[:2]
378 global_length = key.shape[1]
379 query_rank = self.query_context.rank if self.kv_cp_size > 1 else 0
380 causal = options.pop("is_causal", self.is_causal)
381 window = options.pop("sliding_window", self.sliding_window)
382 packed_options = {}
383 valid_queries = _valid_query_rows(attention_mask, batch, global_length, query_length, query_rank)
384 if lengths is not None and self.kv_cp_size == 1:
385 # Pure Ulysses already owns the complete sequence. Do not repack KV
386 # by document: FA can consume the original batch-major TND directly.
387 packed_options = {"actual_seq_len": lengths}
388 elif lengths is not None or (self.kv_cp_size > 1 and attention_mask is None):
389 if attention_mask is not None:
390 raise ValueError("GQA CP packed attention requires document lengths without an explicit mask")
391 documents = tuple(lengths or range(global_length, (batch + 1) * global_length, global_length))
392 ranges, q_lengths, kv_lengths = _query_documents(
393 documents, batch, global_length, query_length, query_rank, causal)
394 query = query.flatten(0, 1).unsqueeze(0)
395 key, value = (_select_document_keys(tensor, ranges) for tensor in (key, value))
396 packed_options = {"actual_seq_qlen": q_lengths, "actual_seq_kvlen": kv_lengths}
397 elif attention_mask is not None:
398 query_begin = query_rank * query_length
399 # Prefix truncation lets the common FA use its ordinary right-aligned causal contract.
400 key_end = query_begin + query_length if causal else global_length
401 key, value = key[:, :key_end], value[:, :key_end]
402 attention_mask = _local_mask(attention_mask, global_length, query_length, query_begin, key_end)
403 if query_length != key_end:
404 # The explicit mask already includes the global query offset.
405 # Kernel-local next_tokens=0 can incorrectly clip unequal-Q/K backward.
406 options.setdefault("next_tokens", 2147483647)
407 options.update(is_causal=causal, sliding_window=window, **packed_options)
408 output_state = CPGQAOutputState((batch, query_length), valid_queries, output_state)
409 return GQAInputs(
410 query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2),
411 attention_mask, options, output_state)
412
413 def prepare_attention_inputs(self, hidden_states: torch.Tensor, positions: Any,
414 attention_mask: torch.Tensor | None = None, past_key_values: Any = None,
415 actual_seq_len: Any = None, **kwargs: Any) -> CPGQAPreparedInputs:
416 """Project inputs and submit ready transfers without completing the exchange.
417
418 The same algorithm methods serve local and CP members. Early submission
419 here keeps projection/communication overlap; waits and FA layout mapping
420 belong to exchange_attention.
421
422 Args:
423 hidden_states: Original local input tokens in BSH layout.
424 positions: Local cosine/sine tables, or None.
425 attention_mask: Optional global padding or visibility mask.
426 past_key_values: Must be None for CP training.
427 actual_seq_len: Global cumulative document endpoints.
428 **kwargs: Attention options and supported packed-length aliases.
429
430 Returns:
431 Invocation-local BSND projections, transfer handles and global metadata.
432 Overlap handles are not waited here; exchange_attention consumes them.
433 """
434 q_lengths, options = _prepare_cp_attention_metadata(
435 self, hidden_states, attention_mask, past_key_values, actual_seq_len, kwargs,
436 )
437 if self.fuse_qkv:
438 query, key, value, output_state = self.split_projection(hidden_states)
439 query = self.normalize_position(query, self.q_norm, positions)
440 query, query_pending = self._transfer_input(query, is_query=True)
441 key = self.normalize_position(key, self.k_norm, positions)
442 key, key_pending = self._transfer_input(key, is_query=False)
443 value, value_pending = self._transfer_input(value, is_query=False)
444 else:
445 query = self.project_query(hidden_states, positions)
446 query, query_pending = self._transfer_input(query, is_query=True)
447 key = self.project_key(hidden_states, positions)
448 key, key_pending = self._transfer_input(key, is_query=False)
449 value = self.project_value(hidden_states)
450 value, value_pending = self._transfer_input(value, is_query=False)
451 output_state = None
452 return CPGQAPreparedInputs(
453 query, key, value, query_pending, key_pending, value_pending,
454 attention_mask, q_lengths, options, output_state)
455
456 def exchange_attention(self, prepared: CPGQAPreparedInputs) -> GQAInputs:
457 """Complete this invocation's transfers and produce ready FA operands.
458
459 Args:
460 prepared: BSND projections, optional pending transfers, global mask
461 and document metadata returned by prepare_attention_inputs.
462
463 Returns:
464 Ready BNSD inputs with local document coordinates and output state.
465 """
466 query, key, value = self._finish_input_transfers(
467 prepared.query, prepared.key, prepared.value,
468 prepared.query_pending, prepared.key_pending, prepared.value_pending)
469 return self._attention_operands(
470 query, key, value, prepared.attention_mask, prepared.lengths,
471 prepared.options, prepared.output_state)
472
473
474class RingCPGroupedQueryAttentionModule(_CPGroupedQueryAttentionBase):
475 """GQA CP member that replaces KV AllGather execution with Ring Attention."""
476
477 def __init__(self, *, module: torch.nn.Module | None = None, config: Any = None,
478 module_fqn: str = "", context: Any = None, fuse_qkv: bool = True) -> None:
479 """Read Ring-only execution controls after initializing shared CP state."""
480 super().__init__(module=module, config=config, module_fqn=module_fqn,
481 context=context, fuse_qkv=fuse_qkv)
482 options = _gqa_cp_options(self.config)
483 self.ring_cp_load_balance = options["ring_cp_load_balance"]
484 self.prune_documents = options["prune_documents"]
485
486 def prepare_attention_inputs(self, hidden_states: torch.Tensor, positions: Any,
487 attention_mask: torch.Tensor | None = None,
488 past_key_values: Any = None, actual_seq_len: Any = None,
489 **kwargs: Any) -> RingGQAPreparedInputs:
490 """Project local Q/K/V and prepare the Ring-specific packed layout."""
491 q_lengths, options = _prepare_cp_attention_metadata(
492 self, hidden_states, attention_mask, past_key_values, actual_seq_len, kwargs,
493 )
494 return self._prepare_ring_inputs(
495 hidden_states, positions, attention_mask, q_lengths, options,
496 )
497
498 def _prepare_ring_inputs(self, hidden_states: torch.Tensor, positions: Any,
499 attention_mask: torch.Tensor | None, cumulative_lengths: Any,
500 options: dict[str, Any]) -> RingGQAPreparedInputs:
501 """Project rank-local inputs while leaving sequence communication to Ring."""
502 causal = _validate_ring_options(self, attention_mask, options)
503 lengths = _ring_document_lengths(cumulative_lengths, options)
504 query, key, value, projection_state = self.project_qkv(hidden_states, positions)
505 if self.ulysses_cp_size > 1:
506 if self.cp_comm_overlap:
507 pending = tuple(self.ulysses_context.launch_sequence_to_head(tensor)
508 for tensor in (query, key, value))
509 query, key, value = (transfer.wait() for transfer in pending)
510 else:
511 query, key, value = (self.ulysses_context.sequence_to_head(tensor)
512 for tensor in (query, key, value))
513 batch, local_length = query.shape[:2]
514 ring_context = self.ring_context
515 query, key, value, input_layout = _ring_layout(
516 query, key, value, batch, local_length, ring_context.size, lengths,
517 )
518 output_state = CPGQAOutputState((batch, local_length), None, projection_state)
519 return RingGQAPreparedInputs(
520 query, key, value, input_layout, lengths, causal, ring_context.mesh,
521 self.ring_cp_load_balance, self.prune_documents, output_state,
522 )
523
524 def exchange_attention(self, prepared: RingGQAPreparedInputs) -> RingGQAPreparedInputs:
525 """Return Ring operands without applying ordinary CP transfers."""
526 return prepared
527
528 def run_attention(self, inputs: RingGQAPreparedInputs) -> tuple[torch.Tensor, torch.Tensor | None]:
529 """Run Ring Attention for the Ring-specific prepared operands."""
530 output = ring_attention(
531 inputs.query, inputs.key, inputs.value, inputs.cp_mesh,
532 causal=inputs.causal, input_layout=inputs.input_layout, overlap=self.cp_comm_overlap,
533 load_balance=inputs.load_balance, prune_documents=inputs.prune_documents,
534 document_lengths=inputs.document_lengths,
535 )
536 if inputs.input_layout == "TND":
537 output = output.unsqueeze(0)
538 return output, None
539
540
541def build_cp_grouped_query_attention(*, module: torch.nn.Module | None = None,
542 config: Any = None, module_fqn: str = "",
543 context: Any = None, fuse_qkv: bool = True) -> torch.nn.Module:
544 """Construct the ordinary or Ring GQA CP member from configured CP factors."""
545 attention_config = config if config is not None else getattr(module, "config", None)
546 options = _gqa_cp_options(attention_config)
547 member = (RingCPGroupedQueryAttentionModule
548 if options["ring_cp_size"] > 1 else CPGroupedQueryAttentionModule)
549 return member(config=config, module=module, module_fqn=module_fqn,
550 context=context, fuse_qkv=fuse_qkv)