From 256c4ebe25628cacca97295f3417d2d60904c12b Mon Sep 17 00:00:00 2001 From: yueming-yuan Date: Mon, 27 Jul 2026 08:54:14 -0700 Subject: [PATCH] Move in-model CP layout helpers out of training_utils into model plugins miles/backends/training_utils/cp_utils.py owns the CP helpers the training backend applies around the model: slicing data, masks, logprobs and logits. build_gdn_cp_context was the one exception -- it runs inside a layer forward, is used only by model plugins, and forced an optional flash-linear-attention dependency (the fla.ops.cp try/except) into a core training module. The zigzag <-> contiguous-shard relayout has the same shape and was private to miles_plugins/models/hf_attention.py, so only the two models built on HuggingfaceAttention could reach it. Collect both in miles_plugins/models/cp_utils.py, which now holds the CP helpers that run inside a forward. To break the resulting import cycle, detect_and_setup_hybrid_cp moves the other way, into hf_attention.py next to the HuggingfaceAttention class it is defined in terms of. Pure move: every relocated definition is byte-identical apart from dropping the underscore prefix on the four newly public relayout helpers. --- miles/backends/megatron_utils/actor.py | 2 +- miles/backends/training_utils/cp_utils.py | 33 ---- miles_plugins/models/cp_utils.py | 168 ++++++++++++++++-- miles_plugins/models/hf_attention.py | 135 +++----------- miles_plugins/models/qwen3_5.py | 2 +- miles_plugins/models/qwen3_next.py | 2 +- .../test_hf_attention_cp_relayout.py | 6 +- 7 files changed, 180 insertions(+), 168 deletions(-) diff --git a/miles/backends/megatron_utils/actor.py b/miles/backends/megatron_utils/actor.py index 733ed364f88..da83933d7f7 100644 --- a/miles/backends/megatron_utils/actor.py +++ b/miles/backends/megatron_utils/actor.py @@ -197,7 +197,7 @@ def init( parallel_state = get_parallel_state() if parallel_state.cp.size > 1: - from miles_plugins.models.cp_utils import detect_and_setup_hybrid_cp + from miles_plugins.models.hf_attention import detect_and_setup_hybrid_cp for model_chunk in self.model: detect_and_setup_hybrid_cp( diff --git a/miles/backends/training_utils/cp_utils.py b/miles/backends/training_utils/cp_utils.py index f43767d5471..66eee6651ce 100644 --- a/miles/backends/training_utils/cp_utils.py +++ b/miles/backends/training_utils/cp_utils.py @@ -3,16 +3,10 @@ import torch import torch.distributed as dist -import torch.nn as nn import torch.nn.functional as F from .parallel import get_parallel_state -try: - from fla.ops.cp import build_cp_context as _fla_build_cp_context -except ImportError: - _fla_build_cp_context = None - logger = logging.getLogger(__name__) @@ -470,30 +464,3 @@ def assemble_log_prob_from_cp( taken += width assert taken == len(chunk), f"cp rank {cp_rank}: consumed {taken} of {len(chunk)} values" return out - - -def build_gdn_cp_context(module: nn.Module, cu_seqlens: torch.Tensor, device: torch.device): - """Build fla CP context for a GatedDeltaNet module from packed sequence boundaries. - - Args: - module: GDN module with ``cp_group`` / ``cp_world_size`` / ``conv_kernel_size``. - cu_seqlens: Global packed sequence boundaries (e.g. ``packed_seq_params.cu_seqlens_q``). - device: Target device. - - Returns ``None`` when CP is not configured on the module (``cp_group`` not set). - Raises ``RuntimeError`` if hybrid CP is configured but ``fla.ops.cp`` is missing. - """ - cp_group = getattr(module, "cp_group", None) - if cp_group is None: - return None - if _fla_build_cp_context is None: - raise RuntimeError( - "Hybrid CP requires fla.ops.cp (flash-linear-attention >= 0.4.2) " "but it could not be imported." - ) - if cu_seqlens is None or cu_seqlens.numel() < 2: - raise ValueError(f"Hybrid CP requires valid cu_seqlens (at least 2 elements) but got {cu_seqlens}") - return _fla_build_cp_context( - cu_seqlens=cu_seqlens.to(device=device, dtype=torch.int32), - group=cp_group, - conv1d_kernel_size=module.conv_kernel_size, - ) diff --git a/miles_plugins/models/cp_utils.py b/miles_plugins/models/cp_utils.py index 87f4205f343..449d4b2d2a9 100644 --- a/miles_plugins/models/cp_utils.py +++ b/miles_plugins/models/cp_utils.py @@ -1,26 +1,158 @@ -import logging +"""CP token-layout helpers used inside model plugin ``forward`` implementations. +Distinct from ``miles.backends.training_utils.cp_utils``, which owns the CP +helpers the training backend applies *around* the model (slicing data, masks, +logprobs and logits). Everything here runs inside a layer. + +Megatron CP stores each rank's tokens in the zigzag load-balanced order that +ring attention wants, while fla's CP operators expect a contiguous rank-local +chunk. Anything that hands a sequence to fla under CP therefore has to relayout +first and undo it afterwards. Lives here rather than in one model plugin because +three of them need it (qwen3_next, qwen3_5, kimi_k3). +""" + +import torch import torch.distributed as dist import torch.nn as nn -from miles_plugins.models.hf_attention import HuggingfaceAttention +try: + from fla.ops.cp import build_cp_context as _fla_build_cp_context +except ImportError: + _fla_build_cp_context = None + + +def build_gdn_cp_context(module: nn.Module, cu_seqlens: torch.Tensor, device: torch.device): + """Build fla CP context for a GatedDeltaNet module from packed sequence boundaries. + + Args: + module: GDN module with ``cp_group`` / ``cp_world_size`` / ``conv_kernel_size``. + cu_seqlens: Global packed sequence boundaries (e.g. ``packed_seq_params.cu_seqlens_q``). + device: Target device. + + Returns ``None`` when CP is not configured on the module (``cp_group`` not set). + Raises ``RuntimeError`` if hybrid CP is configured but ``fla.ops.cp`` is missing. + """ + cp_group = getattr(module, "cp_group", None) + if cp_group is None: + return None + if _fla_build_cp_context is None: + raise RuntimeError( + "Hybrid CP requires fla.ops.cp (flash-linear-attention >= 0.4.2) " "but it could not be imported." + ) + if cu_seqlens is None or cu_seqlens.numel() < 2: + raise ValueError(f"Hybrid CP requires valid cu_seqlens (at least 2 elements) but got {cu_seqlens}") + return _fla_build_cp_context( + cu_seqlens=cu_seqlens.to(device=device, dtype=torch.int32), + group=cp_group, + conv1d_kernel_size=module.conv_kernel_size, + ) + + +def get_cp_sequence_lengths(cu_seqlens, cp_size, local_total_len=None): + global_seq_lengths = [(cu_seqlens[i + 1] - cu_seqlens[i]).item() for i in range(len(cu_seqlens) - 1)] + local_seq_lengths = [] + for global_seq_len in global_seq_lengths: + if global_seq_len % cp_size != 0: + raise ValueError(f"Expected sequence length {global_seq_len} to be divisible by cp_size={cp_size}") + local_seq_lengths.append(global_seq_len // cp_size) + + if local_total_len is not None and sum(local_seq_lengths) != local_total_len: + raise ValueError(f"Expected local total length {local_total_len}, got {sum(local_seq_lengths)}") + + return global_seq_lengths, local_seq_lengths + + +def gather_cp_tensors(x, cp_group): + gathered = [torch.empty_like(x) for _ in range(dist.get_world_size(group=cp_group))] + dist.all_gather(gathered, x.contiguous(), group=cp_group) + return gathered + + +def _zigzag_to_packed_shard_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + """Convert zigzag ring-attn layout to the contiguous packed shard expected by fla CP.""" + global_seq_lengths, local_seq_lengths = get_cp_sequence_lengths(cu_seqlens, cp_size, hidden_states.size(0)) + gathered_by_rank = [ + gathered.split(local_seq_lengths, dim=0) for gathered in gather_cp_tensors(hidden_states, cp_group) + ] + + full_sequences = [] + for seq_idx, global_seq_len in enumerate(global_seq_lengths): + per_rank = [rank_seqs[seq_idx] for rank_seqs in gathered_by_rank] + if global_seq_len % (2 * cp_size) == 0: + subchunk_len = global_seq_len // (2 * cp_size) + full_seq = torch.cat( + [seq[:subchunk_len] for seq in per_rank] + [seq[subchunk_len:] for seq in per_rank][::-1], + dim=0, + ) + else: + # Final local padding is appended contiguously on each rank, not in zigzag order. + full_seq = torch.cat(per_rank, dim=0) + full_sequences.append(full_seq) + + full_stream = torch.cat(full_sequences, dim=0) if full_sequences else hidden_states[:0] + shard_len = hidden_states.size(0) + return full_stream[cp_rank * shard_len : (cp_rank + 1) * shard_len] + + +def _packed_shard_to_zigzag_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + """Convert contiguous packed shard layout back to zigzag ring-attn layout.""" + global_seq_lengths, local_seq_lengths = get_cp_sequence_lengths(cu_seqlens, cp_size, hidden_states.size(0)) + full_stream = torch.cat(gather_cp_tensors(hidden_states, cp_group), dim=0) + full_sequences = full_stream.split(global_seq_lengths, dim=0) + + local_sequences = [] + for full_seq, global_seq_len, local_seq_len in zip( + full_sequences, global_seq_lengths, local_seq_lengths, strict=True + ): + if global_seq_len % (2 * cp_size) == 0: + subchunk_len = global_seq_len // (2 * cp_size) + parts = full_seq.split(subchunk_len, dim=0) + local_sequences.append(torch.cat([parts[cp_rank], parts[2 * cp_size - 1 - cp_rank]], dim=0)) + else: + local_sequences.append(full_seq.split(local_seq_len, dim=0)[cp_rank]) + + return torch.cat(local_sequences, dim=0) if local_sequences else hidden_states[:0] + + +class _ZigzagToPackedShard(torch.autograd.Function): + """Convert zigzag ring-attn layout to contiguous packed shards for native fla CP.""" + + @staticmethod + def forward(ctx, hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + ctx.cp_group = cp_group + ctx.cp_rank = cp_rank + ctx.cp_size = cp_size + ctx.save_for_backward(cu_seqlens) + return _zigzag_to_packed_shard_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) + + @staticmethod + def backward(ctx, grad_output): + (cu_seqlens,) = ctx.saved_tensors + result = _packed_shard_to_zigzag_impl(grad_output, cu_seqlens, ctx.cp_group, ctx.cp_rank, ctx.cp_size) + return result, None, None, None, None + + +class _PackedShardToZigzag(torch.autograd.Function): + """Convert contiguous packed shards back to zigzag ring-attn layout.""" + + @staticmethod + def forward(ctx, hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + ctx.cp_group = cp_group + ctx.cp_rank = cp_rank + ctx.cp_size = cp_size + ctx.save_for_backward(cu_seqlens) + return _packed_shard_to_zigzag_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) + + @staticmethod + def backward(ctx, grad_output): + (cu_seqlens,) = ctx.saved_tensors + result = _zigzag_to_packed_shard_impl(grad_output, cu_seqlens, ctx.cp_group, ctx.cp_rank, ctx.cp_size) + return result, None, None, None, None -logger = logging.getLogger(__name__) +def zigzag_to_packed_shard(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + return _ZigzagToPackedShard.apply(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) -def detect_and_setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> int: - """Scan for GatedDeltaNet modules and configure them for native fla CP.""" - count = 0 - for module in model.modules(): - if isinstance(module, HuggingfaceAttention): - linear_attn = getattr(module, "linear_attn", None) - if linear_attn is not None: - linear_attn.cp_group = cp_group - linear_attn.cp_rank = cp_rank - linear_attn.cp_world_size = cp_world_size - module.hybrid_cp = True - count += 1 - if count > 0: - logger.info(f"Configured hybrid CP on {count} GDN modules (fla native state passing)") - return count +def packed_shard_to_zigzag(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): + return _PackedShardToZigzag.apply(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) diff --git a/miles_plugins/models/hf_attention.py b/miles_plugins/models/hf_attention.py index b152a57a3e3..e69acaf6a11 100644 --- a/miles_plugins/models/hf_attention.py +++ b/miles_plugins/models/hf_attention.py @@ -1,123 +1,18 @@ +import logging from abc import ABC, abstractmethod import torch import torch.distributed as dist +import torch.nn as nn from megatron.core import mpu, tensor_parallel from megatron.core.inference.contexts import BaseInferenceContext from megatron.core.packed_seq_params import PackedSeqParams from megatron.core.transformer.module import MegatronModule from miles.utils.hf_config import load_hf_config +from miles_plugins.models.cp_utils import packed_shard_to_zigzag, zigzag_to_packed_shard - -def _get_cp_sequence_lengths(cu_seqlens, cp_size, local_total_len=None): - global_seq_lengths = [(cu_seqlens[i + 1] - cu_seqlens[i]).item() for i in range(len(cu_seqlens) - 1)] - local_seq_lengths = [] - for global_seq_len in global_seq_lengths: - if global_seq_len % cp_size != 0: - raise ValueError(f"Expected sequence length {global_seq_len} to be divisible by cp_size={cp_size}") - local_seq_lengths.append(global_seq_len // cp_size) - - if local_total_len is not None and sum(local_seq_lengths) != local_total_len: - raise ValueError(f"Expected local total length {local_total_len}, got {sum(local_seq_lengths)}") - - return global_seq_lengths, local_seq_lengths - - -def _gather_cp_tensors(x, cp_group): - gathered = [torch.empty_like(x) for _ in range(dist.get_world_size(group=cp_group))] - dist.all_gather(gathered, x.contiguous(), group=cp_group) - return gathered - - -def _zigzag_to_packed_shard_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - """Convert zigzag ring-attn layout to the contiguous packed shard expected by fla CP.""" - global_seq_lengths, local_seq_lengths = _get_cp_sequence_lengths(cu_seqlens, cp_size, hidden_states.size(0)) - gathered_by_rank = [ - gathered.split(local_seq_lengths, dim=0) for gathered in _gather_cp_tensors(hidden_states, cp_group) - ] - - full_sequences = [] - for seq_idx, global_seq_len in enumerate(global_seq_lengths): - per_rank = [rank_seqs[seq_idx] for rank_seqs in gathered_by_rank] - if global_seq_len % (2 * cp_size) == 0: - subchunk_len = global_seq_len // (2 * cp_size) - full_seq = torch.cat( - [seq[:subchunk_len] for seq in per_rank] + [seq[subchunk_len:] for seq in per_rank][::-1], - dim=0, - ) - else: - # Final local padding is appended contiguously on each rank, not in zigzag order. - full_seq = torch.cat(per_rank, dim=0) - full_sequences.append(full_seq) - - full_stream = torch.cat(full_sequences, dim=0) if full_sequences else hidden_states[:0] - shard_len = hidden_states.size(0) - return full_stream[cp_rank * shard_len : (cp_rank + 1) * shard_len] - - -def _packed_shard_to_zigzag_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - """Convert contiguous packed shard layout back to zigzag ring-attn layout.""" - global_seq_lengths, local_seq_lengths = _get_cp_sequence_lengths(cu_seqlens, cp_size, hidden_states.size(0)) - full_stream = torch.cat(_gather_cp_tensors(hidden_states, cp_group), dim=0) - full_sequences = full_stream.split(global_seq_lengths, dim=0) - - local_sequences = [] - for full_seq, global_seq_len, local_seq_len in zip( - full_sequences, global_seq_lengths, local_seq_lengths, strict=True - ): - if global_seq_len % (2 * cp_size) == 0: - subchunk_len = global_seq_len // (2 * cp_size) - parts = full_seq.split(subchunk_len, dim=0) - local_sequences.append(torch.cat([parts[cp_rank], parts[2 * cp_size - 1 - cp_rank]], dim=0)) - else: - local_sequences.append(full_seq.split(local_seq_len, dim=0)[cp_rank]) - - return torch.cat(local_sequences, dim=0) if local_sequences else hidden_states[:0] - - -class _ZigzagToPackedShard(torch.autograd.Function): - """Convert zigzag ring-attn layout to contiguous packed shards for native fla CP.""" - - @staticmethod - def forward(ctx, hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - ctx.cp_group = cp_group - ctx.cp_rank = cp_rank - ctx.cp_size = cp_size - ctx.save_for_backward(cu_seqlens) - return _zigzag_to_packed_shard_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) - - @staticmethod - def backward(ctx, grad_output): - (cu_seqlens,) = ctx.saved_tensors - result = _packed_shard_to_zigzag_impl(grad_output, cu_seqlens, ctx.cp_group, ctx.cp_rank, ctx.cp_size) - return result, None, None, None, None - - -class _PackedShardToZigzag(torch.autograd.Function): - """Convert contiguous packed shards back to zigzag ring-attn layout.""" - - @staticmethod - def forward(ctx, hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - ctx.cp_group = cp_group - ctx.cp_rank = cp_rank - ctx.cp_size = cp_size - ctx.save_for_backward(cu_seqlens) - return _packed_shard_to_zigzag_impl(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) - - @staticmethod - def backward(ctx, grad_output): - (cu_seqlens,) = ctx.saved_tensors - result = _zigzag_to_packed_shard_impl(grad_output, cu_seqlens, ctx.cp_group, ctx.cp_rank, ctx.cp_size) - return result, None, None, None, None - - -def _zigzag_to_packed_shard(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - return _ZigzagToPackedShard.apply(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) - - -def _packed_shard_to_zigzag(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size): - return _PackedShardToZigzag.apply(hidden_states, cu_seqlens, cp_group, cp_rank, cp_size) +logger = logging.getLogger(__name__) class _AllGatherForDuplicatedComputation(torch.autograd.Function): @@ -209,7 +104,7 @@ def forward( # already provides that layout, so no extra relayout is # needed here. if not self.args.allgather_cp: - hidden_states = _zigzag_to_packed_shard( + hidden_states = zigzag_to_packed_shard( hidden_states, cu_seqlens, mpu.get_context_parallel_group(), @@ -254,7 +149,7 @@ def forward( if mpu.get_context_parallel_world_size() > 1 and self.hybrid_cp: if not self.args.allgather_cp: - output = _packed_shard_to_zigzag( + output = packed_shard_to_zigzag( output, cu_seqlens, mpu.get_context_parallel_group(), @@ -284,3 +179,21 @@ def forward( @abstractmethod def hf_forward(self, hidden_states, packed_seq_params): """Huggingface forward function""" + + +def detect_and_setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> int: + """Scan for GatedDeltaNet modules and configure them for native fla CP.""" + count = 0 + for module in model.modules(): + if isinstance(module, HuggingfaceAttention): + linear_attn = getattr(module, "linear_attn", None) + if linear_attn is not None: + linear_attn.cp_group = cp_group + linear_attn.cp_rank = cp_rank + linear_attn.cp_world_size = cp_world_size + module.hybrid_cp = True + count += 1 + + if count > 0: + logger.info(f"Configured hybrid CP on {count} GDN modules (fla native state passing)") + return count diff --git a/miles_plugins/models/qwen3_5.py b/miles_plugins/models/qwen3_5.py index 70a107097e4..dc909111094 100644 --- a/miles_plugins/models/qwen3_5.py +++ b/miles_plugins/models/qwen3_5.py @@ -16,7 +16,7 @@ pass from miles.backends.megatron_utils.fp32_param_utils import mark_param_dtype -from miles.backends.training_utils.cp_utils import build_gdn_cp_context +from miles_plugins.models.cp_utils import build_gdn_cp_context from .hf_attention import HuggingfaceAttention from .qwen_gdn_backend import get_chunk_gated_delta_rule diff --git a/miles_plugins/models/qwen3_next.py b/miles_plugins/models/qwen3_next.py index 412d1149480..027b790206f 100644 --- a/miles_plugins/models/qwen3_next.py +++ b/miles_plugins/models/qwen3_next.py @@ -16,7 +16,7 @@ except ImportError: pass -from miles.backends.training_utils.cp_utils import build_gdn_cp_context +from miles_plugins.models.cp_utils import build_gdn_cp_context from .hf_attention import HuggingfaceAttention from .qwen_gdn_backend import get_chunk_gated_delta_rule diff --git a/tests/e2e/precision/test_hf_attention_cp_relayout.py b/tests/e2e/precision/test_hf_attention_cp_relayout.py index a09c68a2e4f..e76363efbaf 100644 --- a/tests/e2e/precision/test_hf_attention_cp_relayout.py +++ b/tests/e2e/precision/test_hf_attention_cp_relayout.py @@ -16,7 +16,7 @@ register_cuda_ci(est_time=30, suite="stage-c-4-gpu-h200", labels=["precision"]) register_rocm_ci(est_time=60, suite="nightly-stage-c-4-gpu-mi350", labels=["precision"]) -from miles_plugins.models.hf_attention import _packed_shard_to_zigzag, _zigzag_to_packed_shard +from miles_plugins.models.cp_utils import packed_shard_to_zigzag, zigzag_to_packed_shard def setup_dist(): @@ -74,8 +74,8 @@ def test_relayout(rank: int, world_size: int): zigzag, expected_packed_shard, cu_seqlens = _build_rank_inputs(rank, world_size, device) - packed_shard = _zigzag_to_packed_shard(zigzag, cu_seqlens, cp_group, rank, world_size) - roundtrip = _packed_shard_to_zigzag(packed_shard, cu_seqlens, cp_group, rank, world_size) + packed_shard = zigzag_to_packed_shard(zigzag, cu_seqlens, cp_group, rank, world_size) + roundtrip = packed_shard_to_zigzag(packed_shard, cu_seqlens, cp_group, rank, world_size) packed_ok = torch.equal(packed_shard, expected_packed_shard) roundtrip_ok = torch.equal(roundtrip, zigzag)