Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_activation_with_axis.py: 98%
50 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2025-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"""
16Activation with axis distributed operator implementation.
17"""
19import copy
20from typing import Tuple
22from .parallel_ops import DistributedOp
25# Preserve Torch keyword names for calls forwarded by __torch_function__.
26# pylint: disable-next=redefined-builtin
27def _normalize_activation_with_axis_args(input, dim=-1, dtype=None, *, _stacklevel=None):
28 """Preserve dtype and the stack level forwarded by functional.softmax."""
29 kwargs = {}
30 if dtype is not None:
31 kwargs['dtype'] = dtype
32 if _stacklevel is not None:
33 kwargs['_stacklevel'] = _stacklevel
34 return (input, dim), kwargs
37class ActivationWithAxisDistributedOp(DistributedOp):
38 """
39 Distributed implementation for activation-with-axis operators (e.g., softmax).
41 Inherits from DistributedOp and provides activation-with-axis specific implementations.
42 """
44 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
45 """
46 Preprocess arguments for activation-with-axis operators.
48 Args:
49 args (tuple): Input arguments, first element is the input tensor.
50 kwargs (dict): Keyword arguments, including dim and dtype.
52 Returns:
53 tuple: (local_args, local_kwargs, cache_values)
54 """
55 args, local_kwargs = _normalize_activation_with_axis_args(*args, **kwargs)
56 input_tensor = args[0]
57 axis = args[1]
59 local_args = (input_tensor.to_local(), axis)
60 # Functional softmax chooses its implicit dimension from the global rank.
61 if axis is None:
62 ndim = len(input_tensor.shape)
63 axis = 0 if ndim in (0, 1, 3) else 1
64 cache_values = [input_tensor.layout, axis]
65 return local_args, local_kwargs, cache_values
67 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]: # pylint: disable=W0221
68 """
69 Infer output layouts for activation-with-axis operations.
71 Rules:
72 1. Input must not have Partial status.
73 2. axis must be an int or tuple.
74 3. Activation axes must not be sharded.
75 4. If multiple input layouts are provided, all tensor inputs must share the same layout.
76 5. Output layout is identical to the input layout.
78 Args:
79 cache_values (list): [input_layout, axis], or [input_layouts..., axis]
81 Returns:
82 tuple: ((output_layout,), None)
84 Raises:
85 ValueError: If input has Partial status, axis is invalid, or an activation
86 axis is sharded.
87 """
88 axis = cache_values[-1]
89 layouts = cache_values[:-1]
90 if not layouts:
91 return None
93 if not self._allow_partial_inputs:
94 self._check_partial_inputs(layouts)
96 self.check_layout(layouts, axis)
98 first_layout = None
99 for layout in layouts:
100 if first_layout is None and layout is not None:
101 first_layout = layout
102 if layout is not None and first_layout is not None and layout != first_layout:
103 raise ValueError(
104 f"For {self.op_name}, requires all tensor inputs to have the same layout. "
105 f"Input a: {first_layout}, Input b: {layout}"
106 )
108 return (copy.deepcopy(first_layout),), None
110 def check_layout(self, layouts, axis):
111 """
112 check_layout
113 """
114 min_slice_num = 1
115 x_dict = layouts[0].to_dict()
116 x_dev = x_dict["tensor_map"]
118 if not isinstance(axis, (int, tuple)):
119 raise ValueError(
120 f"For {self.op_name}, axis should be int or tuple, but got {type(axis)}"
121 )
123 axes = (axis,) if isinstance(axis, int) else axis
124 for axis_index in axes:
125 tensor_map = x_dev[axis_index]
126 if tensor_map == -1:
127 continue
128 axis_strategy = x_dict["mesh_shape"][len(x_dict["mesh_shape"]) - tensor_map - 1]
129 if axis_strategy != min_slice_num:
130 raise ValueError(
131 f"For {self.op_name}, the axis dimension (in dim {axis_index}) is sharded "
132 f"(strategy is {axis_strategy}). This operation requires the reduction axis to be un-sharded."
133 )