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"""Distributed implementation for RotaryPositionEmbedding operator."""
16import copy
17from typing import Optional, Tuple
18
19from .parallel_ops import DistributedOp
20
21
22# Preserve Torch keyword names for calls forwarded by __torch_function__.
23# pylint: disable-next=redefined-builtin
24def _normalize_npu_rotary_mul_args(input, r1, r2, rotary_mode=None):
25 """Normalize npu_rotary_mul args to canonical positional form.
26
27 Maps ``rotary_mode`` (string, keyword-only) to ``mode`` (int, positional).
28
29 Mapping:
30 - ``None`` / not specified / ``"half"`` → mode=0 (rotate_half)
31 - ``"interleave"`` → mode=1 (rotate_interleaved)
32
33 Args:
34 input: Input tensor.
35 r1: Cosine position encoding tensor.
36 r2: Sine position encoding tensor.
37 rotary_mode: Rotation mode string, optional.
38
39 Returns:
40 tuple: ((input, r1, r2, mode), {})
41
42 Raises:
43 ValueError: If rotary_mode is not None, 'half', or 'interleave'.
44 """
45 if rotary_mode in (None, "half"):
46 mode = 0
47 elif rotary_mode == "interleave":
48 mode = 1
49 else:
50 raise ValueError(
51 f"npu_rotary_mul: unsupported rotary_mode '{rotary_mode}'. "
52 f"Supported values: None, 'half', 'interleave'."
53 )
54 return (input, r1, r2, mode), {}
55
56
57class RotaryPositionEmbeddingDistributedOp(DistributedOp):
58 """Distributed operator for npu_rotary_mul.
59
60 Computes rotary position embedding element-wise:
61 y = x * cos + x_rotate * sin
62
63 where x_rotate is obtained by rotating within the last (D) dimension.
64 Output shape equals x shape exactly.
65
66 Serves ``torch_npu.npu_rotary_mul`` (rotary_mode keyword-only).
67
68 Sharding constraints:
69 - D (last dim) must be replicated for x, cos, and sin: the kernel rotates
70 within D and the operation is indivisible along that axis.
71 - B, N, S dims are fully independent across positions and can be freely
72 sharded.
73 - cos/sin may have any subset of non-D dims replicated (broadcast case),
74 but if cos/sin is sharded on a dimension, it must match x's sharding
75 on that dimension.
76
77 MODE / rotary_mode does not affect layout inference: all modes produce
78 output shape == x shape and leave B/N/S independence unchanged.
79
80 Output:
81 Single tensor with the same shape and layout as x.
82 """
83
84 def _validate_input_layouts(self, x_layout, cos_layout, sin_layout) -> None:
85 """Validate sharding constraints for all input tensors.
86
87 Rules (applied to both 4-D BNSD/BSND/SBND and 3-D TND layouts):
88 - x's last dim (D) must be replicated.
89 - cos and sin's last dim (D) must be replicated.
90 - For any non-D dimension d: if cos/sin is sharded there, the mesh
91 axis must equal x's mesh axis on the same dimension.
92
93 Args:
94 x_layout: Layout of the x tensor.
95 cos_layout: Layout of the cos tensor.
96 sin_layout: Layout of the sin tensor.
97
98 Raises:
99 ValueError: If D is sharded for any input, or if cos/sin sharding
100 is inconsistent with x on any non-D dimension.
101 """
102 x_tm = x_layout.tensor_map
103
104 if x_tm[-1] != -1:
105 raise ValueError(
106 f"For {self.op_name}, D (last dim) of x must be replicated, "
107 f"but got tensor_map={x_tm}"
108 )
109
110 for name, layout in [('cos', cos_layout), ('sin', sin_layout)]:
111 tm = layout.tensor_map
112 if tm[-1] != -1:
113 raise ValueError(
114 f"For {self.op_name}, D (last dim) of {name} must be replicated, "
115 f"but got tensor_map={tm}"
116 )
117 for d in range(len(tm) - 1):
118 x_d = x_tm[d] if d < len(x_tm) - 1 else -1
119 if tm[d] != -1 and tm[d] != x_d:
120 raise ValueError(
121 f"For {self.op_name}, {name} sharding on dim {d} must match x "
122 f"or be replicated, but got x={x_d}, {name}={tm[d]}"
123 )
124
125 def preprocess(self, args: tuple, kwargs: dict) -> Optional[tuple]:
126 """Extract local tensors and build the layout cache.
127
128 Normalizes with ``_normalize_npu_rotary_mul_args``, mapping the
129 ``rotary_mode`` keyword onto ``mode``; ``rotary_mode`` (keyword-only)
130 stays in ``local_kwargs``.
131
132 Args:
133 args: Positional arguments, may include DTensors.
134 kwargs: Keyword arguments.
135
136 Returns:
137 tuple: (local_args, local_kwargs, cache_values) where
138 cache_values = [x_layout, cos_layout, sin_layout].
139 """
140 # Step 1: normalize to canonical (x, cos, sin, mode_int), {}.
141 norm_args, _ = _normalize_npu_rotary_mul_args(*args, **kwargs)
142
143 x, cos, sin, mode = norm_args
144
145 # Step 2: assemble local_args / local_kwargs; keyword-only params go
146 # in kwargs.
147 local_args = (x.to_local(), cos.to_local(), sin.to_local())
148 local_kwargs = {}
149 if mode == 1:
150 local_kwargs['rotary_mode'] = 'interleave'
151
152 cache_values = [x.layout, cos.layout, sin.layout]
153 return local_args, local_kwargs, cache_values
154
155 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
156 """Infer output layout for the single output tensor.
157
158 Rules:
159 1. Partial inputs are rejected.
160 2. D (last dim) must be replicated for x, cos, and sin.
161 3. cos/sin sharding on non-D dims must match x or be replicated.
162 4. Output layout = deep copy of x_layout (output shape == x shape).
163
164 Args:
165 cache_values: [x_layout, cos_layout, sin_layout]
166
167 Returns:
168 tuple: ((output_layout,), None)
169
170 Raises:
171 ValueError: If any input has Partial status, D is sharded,
172 or cos/sin sharding is inconsistent with x.
173 """
174 x_layout = cache_values[0]
175 cos_layout = cache_values[1]
176 sin_layout = cache_values[2]
177
178 self._check_partial_inputs([x_layout, cos_layout, sin_layout])
179 self._validate_input_layouts(x_layout, cos_layout, sin_layout)
180 return (copy.deepcopy(x_layout),), None