Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / shard / ops / parallel_matmul.py: 79%
256 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"""
16Distributed implementation for MatMul operator.
17"""
19from typing import Callable, Optional, Tuple
21from hyper_parallel.core.dtensor.layout import Layout
22from .parallel_ops import DistributedOp
25def _propagate_partial_from_inputs(out_layout, x_layout, w_layout):
26 """
27 Propagate Partial status from input layouts to the output layout for matmul-like operations.
29 For matmul ``y = x @ w``, the output should inherit Partial state from its inputs in addition
30 to any Partial state induced by the contracting dimension being sharded.
32 **Semantic rules for input Partial propagation:**
34 +-------------------+----------------------------+----------------------------------------------+
35 | x input | w / weight | output behavior |
36 +-------------------+----------------------------+----------------------------------------------+
37 | **Partial(d)** | **Replicate** (contracting) | **Propagate Partial(d)**. |
38 | | | Distributive law: |
39 | | | ``(x0 + x1) @ w = x0 @ w + x1 @ w``. |
40 | | | Output carries Partial(d). |
41 +-------------------+----------------------------+----------------------------------------------+
42 | Replicate | **Partial(d)** | **Propagate Partial(d)**. Symmetric to above.|
43 +-------------------+----------------------------+----------------------------------------------+
44 | **Partial(d1)** | **Partial(d2)**, d1 != d2 | **Propagate both**. |
45 | | | Each partial axis is independent; |
46 | | | ``(sum over d2)`` applied to x is legal. |
47 +-------------------+----------------------------+----------------------------------------------+
48 | **Partial(d)** | **Partial(d)** same axis | **Error**. Cross-terms ``x0 @ w1`` and |
49 | | same/different ops | ``x1 @ w0`` cannot be computed locally. |
50 +-------------------+----------------------------+----------------------------------------------+
51 | **Partial(d)** | **Shard(d)** on the same | **Error** naturally raised by |
52 | | device axis in the output | ``Layout.set_partial_by_dev_axis``: |
53 | | dimension map | "Partial dim must be replicate." |
54 +-------------------+----------------------------+----------------------------------------------+
56 Args:
57 out_layout (Layout): The partially-built output layout whose ``alias_tensor_map``
58 has already been set (via ``Layout.__call__``).
59 x_layout (Layout): Layout of the first input tensor (activations).
60 w_layout (Layout): Layout of the second input tensor (weight / matrix).
62 Raises:
63 ValueError: If both ``x_layout`` and ``w_layout`` have Partial on the same device
64 axis with different reduce operations (e.g. one is 'sum' and the other 'avg').
65 """
66 if x_layout is None or w_layout is None:
67 return
69 # Propagate x's partial status to output
70 for dev_idx, op in enumerate(x_layout.partial):
71 if op is not None:
72 out_layout.set_partial_by_dev_axis(
73 x_layout.alias_name[dev_idx], op
74 )
76 # Propagate w's partial status to output, checking for conflicts with x's partial
77 for dev_idx, op in enumerate(w_layout.partial):
78 if op is not None:
79 axis_alias = w_layout.alias_name[dev_idx]
80 existing = out_layout.get_partial_by_dev_id(axis_alias)
81 if existing is not None and existing != op:
82 raise ValueError(
83 f"Cannot propagate Partial from both input layouts: "
84 f"x has Partial({existing}) on axis '{axis_alias}' while "
85 f"w has Partial({op}) on the same axis. "
86 f"Partial on the same axis with different reduce ops for both inputs is invalid."
87 )
88 out_layout.set_partial_by_dev_axis(axis_alias, op)
91# Preserve Torch keyword names for calls forwarded by __torch_function__.
92# pylint: disable-next=redefined-builtin
93def _normalize_matmul_ext_args(input, other):
94 return (input, other), {}
97class MatMulExtDistributedOp(DistributedOp):
98 """Distributed implementation for MatMul operator."""
100 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
101 """
102 Preprocess arguments for MatMulExt operator.
104 Args:
105 args (tuple): Input arguments containing x and w tensors.
106 kwargs (dict): Keyword arguments (unused).
108 Returns:
109 tuple: (local_args, local_kwargs, cache_values) where local_args contains
110 local tensors for x and w; cache_values contains [x_layout, w_layout].
111 """
112 args, kwargs = _normalize_matmul_ext_args(*args, **kwargs)
113 x_tensor, w_tensor = args[0], args[1]
114 local_args = (x_tensor.to_local(), w_tensor.to_local())
115 local_kwargs = {}
116 cache_values = [x_tensor.layout, w_tensor.layout]
117 return local_args, local_kwargs, cache_values
119 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
120 """
121 Infer output layout for MatMul operator (output = x @ w).
123 Rules:
124 1. Inputs must share the same mesh_shape.
125 2. Contracting dimensions must have the same layout.
126 3. Output dimensions inherit layouts from non-contracting dimensions.
127 4. Input Partial status is propagated to the output.
129 Args:
130 cache_values (list): [x_layout, w_layout]
132 Returns:
133 tuple: ((output_layout,), None)
135 Raises:
136 ValueError: If any rule above is violated.
137 """
138 x_layout = cache_values[0]
139 w_layout = cache_values[1]
140 if not x_layout or not w_layout:
141 raise ValueError(
142 f"For {self.op_name}, x_layout: {x_layout}, w_layout: {w_layout}"
143 )
144 x_mesh_shape = x_layout.mesh_shape
145 w_mesh_shape = w_layout.mesh_shape
146 if x_mesh_shape != w_mesh_shape:
147 raise ValueError(
148 f"For {self.op_name}, inputs must have same mesh_shape, "
149 f"but got x: {x_mesh_shape} and w: {w_mesh_shape}"
150 )
152 x_map = x_layout.alias_tensor_map
153 w_map = w_layout.alias_tensor_map
154 contract_dim = len(x_map) - 1
155 w_contract_dim = len(w_map) - 2
156 if x_map[contract_dim] != w_map[w_contract_dim]:
157 raise ValueError(
158 f"For {self.op_name}, contracting dimensions must have same layout, "
159 f"but got x: {x_map[contract_dim]} and w: {w_map[w_contract_dim]}"
160 )
162 output_dim = len(w_map) - 1
163 output_map = x_map[:-1] + (w_map[output_dim],)
165 output_layout = Layout(
166 mesh_shape=x_layout.mesh_shape,
167 alias_name=x_layout.alias_name,
168 rank_list=x_layout.rank_list
169 )
170 out_layout = output_layout(*output_map)
172 # Propagate Partial from inputs (e.g., x already has Partial from a prior matmul)
173 _propagate_partial_from_inputs(out_layout, x_layout, w_layout)
175 # Set partial status from contracting dimension sharding
176 if x_map[contract_dim] != "None":
177 if isinstance(x_map[contract_dim], tuple):
178 for axis in x_map[contract_dim]:
179 out_layout.set_partial_by_dev_axis(axis, 'sum')
180 else:
181 out_layout.set_partial_by_dev_axis(x_map[contract_dim], 'sum')
183 return ((out_layout,), None)
186def _normalize_matmul_args(x, w, transpose_a=False, transpose_b=False):
187 return (x, w, transpose_a, transpose_b), {}
190class MatMulDistributedOp(DistributedOp):
191 """Distributed implementation for MatMul operator."""
193 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
194 """
195 Preprocess arguments for MatMul operator.
197 Args:
198 args (tuple): Input arguments containing x, w tensors and optional transpose flags.
199 kwargs (dict): Keyword arguments (unused).
201 Returns:
202 tuple: (local_args, local_kwargs, cache_values) where local_args contains
203 local tensors for x and w; cache_values contains [x_layout, w_layout, transpose_a, transpose_b].
204 """
205 args, kwargs = _normalize_matmul_args(*args, **kwargs)
206 x_tensor, w_tensor, transpose_a, transpose_b = args
207 local_args = (x_tensor.to_local(), w_tensor.to_local(), transpose_a, transpose_b)
208 local_kwargs = {}
209 cache_values = [x_tensor.layout, w_tensor.layout, transpose_a, transpose_b]
210 return local_args, local_kwargs, cache_values
212 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
213 """
214 Infer output layout for MatMul operator (output = x @ w, with possible transpose).
216 Rules:
217 1. Inputs must share the same mesh_shape.
218 2. Contracting dimensions must have the same layout (adjusted by transpose flags).
219 3. Output dimensions inherit layouts from non-contracting dimensions.
220 4. Input Partial status is propagated to the output.
222 Args:
223 cache_values (list): [x_layout, w_layout, transpose_a, transpose_b]
225 Returns:
226 tuple: ((output_layout,), None)
228 Raises:
229 ValueError: If any rule above is violated.
230 """
231 x_layout = cache_values[0]
232 w_layout = cache_values[1]
233 transpose_a = cache_values[2]
234 transpose_b = cache_values[3]
236 if not x_layout or not w_layout:
237 raise ValueError(
238 f"For {self.op_name}, x_layout: {x_layout}, w_layout: {w_layout}"
239 )
241 x_mesh_shape = x_layout.mesh_shape
242 w_mesh_shape = w_layout.mesh_shape
243 if x_mesh_shape != w_mesh_shape:
244 raise ValueError(
245 f"For {self.op_name}, inputs must have same mesh_shape, "
246 f"but got x: {x_mesh_shape} and w: {w_mesh_shape}"
247 )
249 x_map = x_layout.alias_tensor_map
250 w_map = w_layout.alias_tensor_map
252 # Determine contracting dimensions based on transpose flags
253 if transpose_a:
254 x_input_dim = len(x_map) - 1
255 x_contract_dim = len(x_map) - 2 # Second to last dimension
256 else:
257 x_input_dim = len(x_map) - 2
258 x_contract_dim = len(x_map) - 1 # Last dimension
260 if transpose_b:
261 w_output_dim = len(w_map) - 2
262 w_contract_dim = len(w_map) - 1 # Last dimension
263 else:
264 w_output_dim = len(w_map) - 1
265 w_contract_dim = len(w_map) - 2 # Second to last dimension
267 # Validate contracting dimensions
268 if x_map[x_contract_dim] != w_map[w_contract_dim]:
269 raise ValueError(
270 f"For {self.op_name}, contracting dimensions must have same layout, "
271 f"but got x: {x_map[x_contract_dim]} and w: {w_map[w_contract_dim]}"
272 )
274 # Create output layout
275 output_layout = Layout(
276 mesh_shape=x_layout.mesh_shape,
277 alias_name=x_layout.alias_name,
278 rank_list=x_layout.rank_list
279 )
280 output_map = list(x_map[:-2]) + [x_map[x_input_dim]] + [w_map[w_output_dim]]
281 out_layout = output_layout(*output_map)
283 # Propagate Partial from inputs (e.g., x already has Partial from a prior matmul)
284 _propagate_partial_from_inputs(out_layout, x_layout, w_layout)
286 # Set partial status
287 if x_map[x_contract_dim] != "None":
288 if isinstance(x_map[x_contract_dim], tuple):
289 for axis in x_map[x_contract_dim]:
290 out_layout.set_partial_by_dev_axis(axis, 'sum')
291 else:
292 out_layout.set_partial_by_dev_axis(x_map[x_contract_dim], 'sum')
294 return ((out_layout,), None)
297class BaseBatchMatMulDistributedOp(DistributedOp):
298 """Base class for BatchMatMul distributed implementations."""
300 def _merge_batch_entry(self, x_dims, w_dims):
301 """
302 Merge two batch tensor_map entries with broadcasting:
303 - none vs X -> X
304 - X vs none -> X
305 - X vs X (exact same after normalization) -> X
306 - otherwise -> conflict
307 """
308 if self._is_none_entry(x_dims) and self._is_none_entry(w_dims):
309 return "None"
310 if self._is_none_entry(x_dims):
311 return w_dims
312 if self._is_none_entry(w_dims):
313 return x_dims
314 if x_dims == w_dims:
315 return x_dims
316 raise ValueError(f"Incompatible batch sharding between inputs: {x_dims} vs {w_dims}")
318 def _is_none_entry(self, entry):
319 """An entry is 'none' (no sharding) if it is 'None' or tuple of all 'None'."""
320 if isinstance(entry, tuple):
321 return all(i == "None" for i in entry)
322 return entry == "None"
324 def _merge_batches(self, x_map, w_map):
325 """Right-align and merge batch dims from x_map and w_map."""
326 x_batch = list(x_map[:-2])
327 w_batch = list(w_map[:-2])
328 max_b = max(len(x_batch), len(w_batch))
329 x_batch = ["None"] * (max_b - len(x_batch)) + x_batch
330 w_batch = ["None"] * (max_b - len(w_batch)) + w_batch
331 merged_batch = []
332 for xb, wb in zip(x_batch, w_batch):
333 merged_batch.append(self._merge_batch_entry(xb, wb))
334 return merged_batch
336 def _build_output_layout(self, x_layout, w_layout, merged_batch, x_n, w_p, x_contract):
337 """Construct output layout from merged dims and set partial status if needed."""
338 output_map = tuple(merged_batch) + (x_n, w_p)
340 output_layout = Layout(
341 mesh_shape=x_layout.mesh_shape,
342 alias_name=x_layout.alias_name,
343 rank_list=x_layout.rank_list
344 )
345 output_layout = output_layout(*output_map)
347 # Propagate Partial from inputs
348 _propagate_partial_from_inputs(output_layout, x_layout, w_layout)
350 # Set partial status
351 if x_contract != "None":
352 if isinstance(x_contract, tuple):
353 for axis in x_contract:
354 output_layout.set_partial_by_dev_axis(axis, 'sum')
355 else:
356 output_layout.set_partial_by_dev_axis(x_contract, 'sum')
358 return output_layout
361def _normalize_batch_matmul_ext_args(x, w):
362 return (x, w), {}
365class BatchMatMulExtDistributedOp(BaseBatchMatMulDistributedOp):
366 """Distributed implementation for BatchMatMulExt operator."""
368 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
369 """
370 Preprocess arguments for BatchMatMulExt operator.
372 Args:
373 args (tuple): Input arguments containing x and w tensors.
374 kwargs (dict): Keyword arguments (unused).
376 Returns:
377 tuple: (local_args, local_kwargs, cache_values) where local_args contains
378 local tensors for x and w; cache_values contains [x_layout, w_layout].
379 """
380 args, kwargs = _normalize_batch_matmul_ext_args(*args, **kwargs)
381 x_tensor, w_tensor = args[0], args[1]
382 local_args = (x_tensor.to_local(), w_tensor.to_local())
383 local_kwargs = {}
384 cache_values = [x_tensor.layout, w_tensor.layout]
385 return local_args, local_kwargs, cache_values
387 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
388 """
389 Infer output layout for BatchMatMulExt operator (output = x @ w).
391 Inputs shape are x=[b, n, m] and w=[b, m, p].
393 Rules:
394 1. Inputs must share the same mesh_shape.
395 2. Contracting K dims must have identical layout: x[-1] == w[-2].
396 3. Batch dims are right-aligned with broadcast semantics.
397 4. Output batch dims = merged batch dims; N inherits x[-2], P inherits w[-1].
398 5. Input Partial status is propagated to the output.
400 Args:
401 cache_values (list): [x_layout, w_layout]
403 Returns:
404 tuple: ((output_layout,), None)
406 Raises:
407 ValueError: If any rule above is violated.
408 """
409 x_layout = cache_values[0]
410 w_layout = cache_values[1]
412 if not x_layout or not w_layout:
413 raise ValueError(
414 f"For {self.op_name}, x_layout: {x_layout}, w_layout: {w_layout}"
415 )
417 if x_layout.mesh_shape != w_layout.mesh_shape:
418 raise ValueError(
419 f"For {self.op_name}, inputs must have same mesh_shape, "
420 f"but got x: {x_layout.mesh_shape} and w: {w_layout.mesh_shape}"
421 )
423 x_map = x_layout.alias_tensor_map
424 w_map = w_layout.alias_tensor_map
426 # contracting dims
427 x_contract = x_map[-1]
428 w_contract = w_map[-2]
429 if x_contract != w_contract:
430 raise ValueError(
431 f"For {self.op_name}, contracting (M) dim layouts must match, "
432 f"but got x: {x_contract} and w: {w_contract}"
433 )
435 merged_batch = self._merge_batches(x_map, w_map)
436 x_n = x_map[-2]
437 w_p = w_map[-1]
439 return ((self._build_output_layout(x_layout, w_layout, merged_batch, x_n, w_p, x_contract),), None)
442def _normalize_batch_matmul_args(x, w, transpose_a=False, transpose_b=False):
443 return (x, w, transpose_a, transpose_b), {}
446class BatchMatMulDistributedOp(BaseBatchMatMulDistributedOp):
447 """Distributed implementation for BatchMatMul operator."""
449 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
450 """
451 Preprocess arguments for BatchMatMul operator.
453 Args:
454 args (tuple): Input arguments containing x, w tensors and optional transpose flags.
455 kwargs (dict): Keyword arguments (unused).
457 Returns:
458 tuple: (local_args, local_kwargs, cache_values) where local_args contains
459 local tensors for x and w; cache_values contains
460 [x_layout, w_layout, transpose_a, transpose_b].
461 """
462 args, kwargs = _normalize_batch_matmul_args(*args, **kwargs)
463 x_tensor, w_tensor, transpose_a, transpose_b = args
464 local_args = (x_tensor.to_local(), w_tensor.to_local(), transpose_a, transpose_b)
465 local_kwargs = {}
466 cache_values = [x_tensor.layout, w_tensor.layout, transpose_a, transpose_b]
467 return local_args, local_kwargs, cache_values
469 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
470 """
471 Infer output layout for BatchMatMul operator (output = x @ w, with possible transpose).
473 Inputs shape are x=[b, n, m] and w=[b, m, p].
475 Rules:
476 1. Inputs must share the same mesh_shape.
477 2. Contracting K dims must have identical layout (adjusted by transpose flags).
478 3. Batch dims are right-aligned with broadcast semantics.
479 4. Output batch dims = merged batch dims; N/P dims inherit per transpose flags.
480 5. Input Partial status is propagated to the output.
482 Args:
483 cache_values (list): [x_layout, w_layout, transpose_a, transpose_b]
485 Returns:
486 tuple: ((output_layout,), None)
488 Raises:
489 ValueError: If any rule above is violated.
490 """
491 x_layout = cache_values[0]
492 w_layout = cache_values[1]
493 transpose_a = cache_values[2]
494 transpose_b = cache_values[3]
496 if not x_layout or not w_layout:
497 raise ValueError(
498 f"For {self.op_name}, x_layout: {x_layout}, w_layout: {w_layout}"
499 )
501 if x_layout.mesh_shape != w_layout.mesh_shape:
502 raise ValueError(
503 f"For {self.op_name}, inputs must have same mesh_shape, "
504 f"but got x: {x_layout.mesh_shape} and w: {w_layout.mesh_shape}"
505 )
507 x_map = x_layout.alias_tensor_map
508 w_map = w_layout.alias_tensor_map
510 # handle transpose
511 if transpose_a:
512 x_n = x_map[-1]
513 x_contract = x_map[-2]
514 else:
515 x_n = x_map[-2]
516 x_contract = x_map[-1]
518 if transpose_b:
519 w_contract = w_map[-1]
520 w_p = w_map[-2]
521 else:
522 w_contract = w_map[-2]
523 w_p = w_map[-1]
525 if x_contract != w_contract:
526 raise ValueError(
527 f"For {self.op_name}, contracting (M) dim layouts must match, "
528 f"but got x: {x_contract} and w: {w_contract}"
529 )
531 merged_batch = self._merge_batches(x_map, w_map)
533 return ((self._build_output_layout(x_layout, w_layout, merged_batch, x_n, w_p, x_contract),), None)
536# Preserve Torch keyword names for calls forwarded by __torch_function__.
537# pylint: disable-next=redefined-builtin
538def _normalize_linear_args(input, weight, bias=None):
539 return (input, weight, bias), {}
542class LinearDistributedOp(DistributedOp):
543 """Distributed implementation for Linear operator."""
545 def preprocess(self, args: tuple, kwargs: dict) -> tuple:
546 """
547 Preprocess arguments for Linear operator.
549 Args:
550 args (tuple): Input arguments containing x and weight tensors.
551 kwargs (dict): Keyword arguments, may contain bias.
553 Returns:
554 tuple: (local_args, local_kwargs, cache_values) where local_args contains
555 local tensors for x, weight, and bias; local_kwargs is empty; and
556 cache_values contains layouts and None-sentinel for absent bias.
557 """
558 args, kwargs = _normalize_linear_args(*args, **kwargs)
559 x_tensor, w_tensor, bias = args[0], args[1], args[2]
560 local_args = (
561 x_tensor.to_local(),
562 w_tensor.to_local(),
563 bias.to_local() if hasattr(bias, '_layout') else bias,
564 )
565 local_kwargs = {}
566 cache_values = [
567 x_tensor.layout,
568 w_tensor.layout,
569 bias.layout if hasattr(bias, '_layout') else None,
570 ]
571 return local_args, local_kwargs, cache_values
573 def infer_layout(self, cache_values: list) -> Tuple[tuple, None]:
574 """
575 Infer output layout for Linear operator (output = x @ weight.T + bias).
577 Rules:
578 1. x and weight must share the same mesh_shape.
579 2. weight must be 2D [out_features, in_features].
580 3. Contracting dimensions (in_features) must have the same layout.
581 4. Output batch dimensions inherit from x; output feature dim inherits from weight dim 0.
582 5. Partial state is set on the output when the contracting dimension is sharded.
584 Args:
585 cache_values (list): [x_layout, w_layout, bias_layout] where bias_layout may be None.
587 Returns:
588 tuple: ((out_layout,), None)
590 Raises:
591 ValueError: If cache_values length is not 3, layouts are invalid, mesh shapes differ,
592 weight is not 2D, contracting dims mismatch, or bias sharding is inconsistent.
593 """
594 if len(cache_values) != 3:
595 raise ValueError(
596 f"For {self.op_name}, cache_values length should be 3, but got {len(cache_values)}"
597 )
598 x_layout = cache_values[0]
599 w_layout = cache_values[1]
600 bias_layout = cache_values[2]
602 if not x_layout or not w_layout:
603 raise ValueError(f"x_layout : {x_layout}, w_layout : {w_layout}")
605 x_mesh_shape = x_layout.mesh_shape
606 w_mesh_shape = w_layout.mesh_shape
607 if x_mesh_shape != w_mesh_shape:
608 raise ValueError(
609 f"For {self.op_name}, x and weight must have the same mesh_shape, "
610 f"but got x: {x_mesh_shape} and weight: {w_mesh_shape}"
611 )
612 if bias_layout and bias_layout.mesh_shape != x_mesh_shape:
613 raise ValueError(
614 f"For {self.op_name}, bias and x must have the same mesh_shape, "
615 f"but got bias: {bias_layout.mesh_shape} and x: {x_mesh_shape}"
616 )
618 x_map = x_layout.alias_tensor_map
619 w_map = w_layout.alias_tensor_map
621 if len(w_map) != 2:
622 raise ValueError(
623 f"For {self.op_name}, weight should be 2D [out_features, in_features], "
624 f"but got {len(w_map)}D"
625 )
627 x_contract_dim = len(x_map) - 1
628 w_contract_dim = len(w_map) - 1
629 if x_map[x_contract_dim] != w_map[w_contract_dim]:
630 raise ValueError(
631 f"For {self.op_name}, contracting dimensions must have the same layout, "
632 f"but got x: {x_map[x_contract_dim]} and weight: {w_map[w_contract_dim]}"
633 )
635 output_dim = 0
636 output_map = x_map[:-1] + (w_map[output_dim],)
637 if bias_layout and bias_layout.alias_tensor_map[0] != w_map[output_dim]:
638 raise ValueError(
639 f"For {self.op_name}, bias output dim sharding must match weight output dim sharding, "
640 f"but got weight: {w_map[output_dim]} and bias: {bias_layout.alias_tensor_map[0]}"
641 )
643 output_layout = Layout(
644 mesh_shape=x_layout.mesh_shape,
645 alias_name=x_layout.alias_name,
646 rank_list=x_layout.rank_list,
647 )
648 out_layout = output_layout(*output_map)
650 # Propagate Partial from inputs (e.g., x already has Partial from a prior matmul)
651 _propagate_partial_from_inputs(out_layout, x_layout, w_layout)
653 # Set partial status when contracting dimension is sharded
654 if x_map[x_contract_dim] != "None":
655 if isinstance(x_map[x_contract_dim], tuple):
656 for axis in x_map[x_contract_dim]:
657 out_layout.set_partial_by_dev_axis(axis, 'sum')
658 else:
659 out_layout.set_partial_by_dev_axis(x_map[x_contract_dim], 'sum')
661 return ((out_layout,), None)
663 def get_expand_impl(self, func: Callable, infer_result: tuple,
664 cache_values: list) -> Optional[Callable]:
665 """
666 Return a custom expand implementation when bias scaling is needed.
668 When the contracting dimension is sharded each rank computes a partial sum
669 (x_shard @ w_shard.T + bias). After AllReduce the bias would accumulate
670 scaling_factor times. The returned closure pre-divides bias by scaling_factor
671 to keep the result numerically correct.
673 Args:
674 func: Original operator callable.
675 infer_result (tuple): ((out_layout,), None) from infer_layout.
676 cache_values (list): [x_layout, w_layout, bias_layout].
678 Returns:
679 callable | None: expand_impl closure when scaling is required, else None.
680 """
681 x_layout = cache_values[0]
682 bias_layout = cache_values[2]
683 x_map = x_layout.alias_tensor_map
684 x_contract_dim = len(x_map) - 1
686 # Guard: scaling only needed when contract dim is sharded AND bias is present
687 if x_map[x_contract_dim] == "None" or not bias_layout:
688 return None
690 output_layout = infer_result[0][0]
691 scaling_factor = 1
692 if isinstance(x_map[x_contract_dim], tuple):
693 for axis in x_map[x_contract_dim]:
694 scaling_factor *= output_layout.mesh.get_device_num_along_axis(axis)
695 else:
696 scaling_factor *= output_layout.mesh.get_device_num_along_axis(x_map[x_contract_dim])
698 def expand_impl(x: object, w: object, bias: object) -> object:
699 """Pre-scale bias to counteract the AllReduce accumulation over shards.
701 Args:
702 x (object): Local input activation tensor.
703 w (object): Local weight tensor.
704 bias (object): Local bias tensor to be pre-scaled.
706 Returns:
707 object: Result of the linear operation with pre-scaled bias.
708 """
709 return func(x, w, bias / scaling_factor)
711 return expand_impl