Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / grouped_matmul.py: 86%
43 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"""Expert-major grouped matrix multiplication adapters."""
17from __future__ import annotations
19from typing import Protocol
21import torch
23from ..registry import OpRegistry
24from ..spec import OpSpec
25from .._dependency import require_package, require_symbol
28class GroupedMatmulFn(Protocol):
29 """Multiply expert-major rows by weights using cumulative group boundaries."""
31 def __call__(self, x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
32 """Multiply expert-major rows without a bias.
34 Args:
35 x: Token rows of shape ``[T, K]``, already grouped by expert.
36 weight: Expert matrices of shape ``[E, K, N]``.
37 group_list: One cumulative end per expert. Ends are nondecreasing,
38 repeated ends represent empty experts, and the final end is T.
40 Returns:
41 Token rows of shape ``[T, N]`` in their input order.
42 """
45GROUPED_MATMUL = OpSpec[GroupedMatmulFn](config_key="grouped_matmul")
48def _native(x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
49 # One small matmul per expert keeps the reference path independent of
50 # grouped kernels without gathering an entire expert weight per token.
51 """Multiply token rows by their expert matrices, retaining empty-expert gradients."""
52 ends = group_list.tolist()
53 starts = [0, *ends[:-1]]
54 if len(ends) != weight.shape[0] or (ends[-1] if ends else 0) != x.shape[0]:
55 raise ValueError("Grouped matmul boundaries must cover every token and contain one entry per expert")
56 if any(start > end for start, end in zip(starts, ends)):
57 raise ValueError("Grouped matmul boundaries must be nondecreasing")
58 if not ends:
59 return x @ weight.sum(dim=0)
60 return torch.cat([x[start:end] @ expert for start, end, expert in zip(starts, ends, weight.unbind())])
63def _load_native() -> GroupedMatmulFn:
64 return _native
67def _load_npu() -> GroupedMatmulFn:
68 """Load the NPU grouped matmul adapter with cumulative row boundaries."""
69 require_symbol(require_package("torch_npu"), "npu_grouped_matmul")
70 # The shared autograd adapter imports the optional NPU package.
71 from hyper_parallel.components.functional.grouped_matmul import ( # pylint: disable=import-outside-toplevel
72 grouped_matmul,
73 )
75 def run(x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
76 """Translate cumulative row boundaries for the selected grouped matmul kernel."""
77 return grouped_matmul(
78 x, weight, bias=None, group_list=group_list.to(torch.int64), group_type=0, group_list_type=0,
79 )
81 return run
84def _load_cuda() -> GroupedMatmulFn:
85 require_symbol(torch, "_grouped_mm")
87 def run(x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
88 """Translate cumulative row boundaries for the selected grouped matmul kernel."""
89 return torch._grouped_mm(x, weight, offs=group_list.to(torch.int32)) # pylint: disable=protected-access
91 return run
94def check_torch_grouped_mm(x: torch.Tensor) -> str | None:
95 """Check CUDA requirements shared by grouped matrix multiplication users."""
96 if x.dtype != torch.bfloat16:
97 return "torch_grouped_mm requires BF16 inputs"
98 if torch.cuda.get_device_capability(x.device)[0] < 8:
99 return "torch_grouped_mm requires compute capability 8.0 or later"
100 return None
103def register_grouped_matmul(registry: OpRegistry) -> None:
104 """Register one grouped GEMM over local expert-major token rows."""
105 registry.register_family("grouped_matmul", specs=(GROUPED_MATMUL,))
106 registry.register_impl(GROUPED_MATMUL, name="native", devices=("cuda", "cpu", "npu"), load=_load_native)
107 registry.register_impl(GROUPED_MATMUL, name="torch_npu", devices=("npu",), load=_load_npu)
108 registry.register_impl(
109 GROUPED_MATMUL, name="torch_grouped_mm", devices=("cuda",), load=_load_cuda,
110 check_compatibility=check_torch_grouped_mm,
111 )