Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_masked_scatter.py: 96%
26 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 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"""
16Distributed implementation for MaskedScatter operator.
17"""
19from typing import Tuple
21from .parallel_ops import DistributedOp
24# Preserve Torch keyword names for calls forwarded by __torch_function__.
25# pylint: disable-next=redefined-builtin
26def _normalize_masked_scatter_args(input, mask, source):
27 return (input, mask, source), {}
30class MaskedScatterDistributedOp(DistributedOp):
31 """Distributed implementation for torch.Tensor.masked_scatter."""
33 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
34 """
35 Preprocess arguments for MaskedScatter operator.
37 torch.masked_scatter(input, mask, source) takes three positional tensor inputs
38 with no keyword-only parameters.
40 Args:
41 args (tuple): Positional arguments (input, mask, source).
42 kwargs (dict): Keyword arguments (none expected).
44 Returns:
45 tuple: (local_args, local_kwargs, cache_values)
46 """
47 args, kwargs = _normalize_masked_scatter_args(*args, **kwargs)
48 input_tensor, mask, source = args[0], args[1], args[2]
49 local_args = (
50 input_tensor.to_local(),
51 mask.to_local(),
52 source.to_local(),
53 )
54 local_kwargs = {}
55 cache_values = [
56 input_tensor.layout,
57 mask.layout,
58 source.layout,
59 ]
60 return local_args, local_kwargs, cache_values
62 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
63 """
64 Infer output layout for torch.Tensor.masked_scatter.
66 PyTorch semantics:
67 masked_scatter_(mask, source)
68 Copies elements from source into self tensor at positions where the mask is True.
69 Elements from source are taken in order.
71 Distributed restrictions:
72 Because `masked_scatter` consumes elements from `source` sequentially based on
73 the flattened index of `True` values in `mask`, sharding the input or mask
74 would require a global prefix sum (scan) to determine the correct offset
75 in `source` for each rank. Without this communication overhead, correct
76 behavior cannot be guaranteed on sharded tensors.
78 Therefore, this implementation enforces that all inputs (input, mask, source)
79 must be fully Replicated (Unsharded).
81 Rules:
82 1. Inputs must not have Partial status.
83 2. All inputs (input, mask, source) must be fully Replicated — no dimension may be sharded.
84 3. Output layout follows the input layout.
86 Args:
87 cache_values (list): [input_layout, mask_layout, source_layout]
89 Returns:
90 tuple: ((output_layout,), None)
92 Raises:
93 ValueError: If any input tensor is sharded.
94 """
95 input_layout = cache_values[0]
96 mask_layout = cache_values[1]
97 source_layout = cache_values[2]
99 layouts = [input_layout, mask_layout, source_layout]
100 if not self._allow_partial_inputs:
101 self._check_partial_inputs(layouts)
103 # Check strict replication for all involved distributed tensors
104 for i, layout in enumerate(layouts):
105 if layout is None:
106 continue
108 # Use alias_tensor_map for sharding checks — it handles StridedShard tuple mappings.
109 # "None" means Replicated; anything else indicates sharding.
110 for dim_alias in layout.alias_tensor_map:
111 if dim_alias != "None":
112 raise ValueError(
113 f"For {self.op_name}, input {i} is sharded (Layout: {layout}). "
114 f"masked_scatter currently only supports fully Replicated (Unsharded) tensors "
115 f"due to sequential dependency on source elements."
116 )
118 # Output layout follows input layout (which we verified is Replicated/None)
119 return ((input_layout,), None)