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"""Shared halo exchange scheduling before local causal convolution."""
16from typing import Optional
17
18import torch
19import torch.distributed as dist
20from torch import nn
21
22from hyper_parallel.core.dtensor.device_mesh import DeviceMesh
23from hyper_parallel.core.utils import communication
24from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import PackedSequenceInfo
25from hyper_parallel.components.functional.linear_attention_convolution import run_causal_short_conv
26
27
28def causal_convolutions_with_halo(
29 projected: tuple[torch.Tensor, ...],
30 convolutions: tuple[nn.Conv1d, ...],
31 cp_mesh: DeviceMesh,
32 cp_rank: int,
33 cp_size: int,
34 sequence_info: Optional[PackedSequenceInfo] = None,
35 backend: str = "eager",
36) -> tuple[torch.Tensor, ...]:
37 """Run causal depthwise convolutions with one packed halo exchange.
38
39 Args:
40 projected: Token-aligned projections before causal convolution.
41 convolutions: Causal convolution modules corresponding to the projections.
42 cp_mesh: Sequence-ordered CP device mesh.
43 cp_rank: Rank index within the CP mesh.
44 cp_size: Number of ranks in the CP mesh.
45 sequence_info: Immutable document metadata for this local token interval.
46 backend: Explicit local operator implementation to dispatch.
47 """
48 halo_widths = {
49 (conv.kernel_size[0] - 1) * conv.dilation[0] for conv in convolutions
50 }
51 if len(halo_widths) != 1:
52 raise ValueError("Linear attention CP requires Q/K/V ShortConv halo widths to match.")
53 halo_width = halo_widths.pop()
54 if halo_width == 0 or cp_size == 1:
55 return tuple(
56 run_causal_short_conv(tensor, convolution, sequence_info=sequence_info, backend=backend)
57 for tensor, convolution in zip(projected, convolutions)
58 )
59 if projected[0].shape[1] < halo_width:
60 raise ValueError(
61 "Linear attention CP ShortConv requires local_seq_len >= halo width, got "
62 f"{projected[0].shape[1]} < {halo_width}."
63 )
64
65 channel_sizes = [tensor.shape[-1] for tensor in projected]
66 packed_tail = torch.cat(
67 [tensor[:, -halo_width:, :] for tensor in projected],
68 dim=-1,
69 ).contiguous()
70 packed_halo = _exchange_previous_rank_halo(
71 packed_tail,
72 cp_mesh,
73 cp_rank,
74 cp_size,
75 )
76 halos = torch.split(packed_halo, channel_sizes, dim=-1)
77 return tuple(
78 run_causal_short_conv(tensor, convolution, halo, sequence_info=sequence_info, backend=backend)
79 for tensor, halo, convolution in zip(projected, halos, convolutions)
80 )
81
82
83def _exchange_previous_rank_halo(
84 tail: torch.Tensor,
85 cp_mesh: DeviceMesh,
86 cp_rank: int,
87 cp_size: int,
88) -> torch.Tensor:
89 """Send a causal-convolution halo only to the next CP rank.
90
91 Args:
92 tail: Trailing tokens to exchange with the adjacent sequence rank.
93 cp_mesh: Sequence-ordered CP device mesh.
94 cp_rank: Rank index within the CP mesh.
95 cp_size: Number of ranks in the CP mesh.
96 """
97 if cp_size == 1:
98 return torch.zeros_like(tail)
99
100 cp_group = cp_mesh.get_group()
101 group_ranks = tuple(int(rank) for rank in dist.get_process_group_ranks(cp_group))
102 rank_list = tuple(int(rank) for rank in cp_mesh.rank_list)
103 rank_to_group_index = {rank: index for index, rank in enumerate(group_ranks)}
104 halo_width = tail.shape[1]
105
106 input_splits = [0] * cp_size
107 exchange_input = tail.permute(1, 0, 2).contiguous()
108 if cp_rank < cp_size - 1:
109 input_splits[rank_to_group_index[rank_list[cp_rank + 1]]] = halo_width
110 else:
111 exchange_input = exchange_input[:0]
112
113 output_splits = [0] * cp_size
114 if cp_rank > 0:
115 output_splits[rank_to_group_index[rank_list[cp_rank - 1]]] = halo_width
116
117 exchange_output = communication.differentiable_all_to_all_single(
118 exchange_input,
119 input_splits,
120 output_splits,
121 group=cp_group,
122 )
123 if cp_rank == 0:
124 return torch.zeros_like(tail) + exchange_output.sum().to(tail.dtype) * 0
125 return exchange_output.permute(1, 0, 2).contiguous()