Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / grouped_swiglu.py: 100%
54 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"""Bias-free expert-major grouped SwiGLU."""
17from __future__ import annotations
19from typing import Protocol
21import torch
22from torch.nn import functional as F
24from .._dependency import require_package, require_symbol
25from ..registry import OpRegistry
26from ..spec import OpSpec
27from .grouped_matmul import check_torch_grouped_mm
30class GroupedSwiGLUFn(Protocol):
31 """Apply gate, up and down projections to the token rows assigned to each expert."""
33 def __call__(
34 self, x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor,
35 counts: torch.Tensor, scores: torch.Tensor | None = None,
36 ) -> torch.Tensor:
37 """Run bias-free SwiGLU, weighting intermediates before the down projection if requested."""
40GROUPED_SWIGLU = OpSpec[GroupedSwiGLUFn](config_key="grouped_swiglu")
43def _weighted(x: torch.Tensor, scores: torch.Tensor | None) -> torch.Tensor:
44 return x if scores is None else x * scores.unsqueeze(-1)
47def _empty_output(
48 x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor, scores: torch.Tensor | None,
49) -> torch.Tensor:
50 zeros = w1[:0].sum() + w2[:0].sum() + w3[:0].sum()
51 if scores is not None:
52 zeros = zeros + scores.sum()
53 return x + zeros.to(x.dtype)
56def native_grouped_swiglu(
57 x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor,
58 counts: torch.Tensor, scores: torch.Tensor | None = None,
59) -> torch.Tensor:
60 """Compute SwiGLU one expert at a time, keeping empty experts in the gradient graph."""
61 if x.shape[0] == 0:
62 return _empty_output(x, w1, w2, w3, scores)
63 tokens = x.split(counts.tolist())
64 routing = [None] * len(tokens) if scores is None else scores.split([part.shape[0] for part in tokens])
65 parts = [
66 _weighted(F.silu(part @ gate.T) * (part @ up.T), score) @ down.T
67 for part, gate, down, up, score in zip(tokens, w1.unbind(), w2.unbind(), w3.unbind(), routing)
68 ]
69 return torch.cat(parts)
72def _cuda(
73 x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor,
74 counts: torch.Tensor, scores: torch.Tensor | None = None,
75) -> torch.Tensor:
76 """Apply grouped expert SwiGLU with optional intermediate routing weights."""
77 if x.shape[0] == 0:
78 return _empty_output(x, w1, w2, w3, scores)
79 offs = counts.cumsum(0, dtype=torch.int32)
80 # Transpose views preserve the parameter storage across pending forwards.
81 grouped_mm = torch._grouped_mm # pylint: disable=protected-access
82 gate = grouped_mm(x, w1.transpose(1, 2), offs=offs)
83 up = grouped_mm(x, w3.transpose(1, 2), offs=offs)
84 return grouped_mm(_weighted(F.silu(gate) * up, scores), w2.transpose(1, 2), offs=offs)
87def _load_cuda() -> GroupedSwiGLUFn:
88 require_symbol(torch, "_grouped_mm")
89 return _cuda
92def _load_npu() -> GroupedSwiGLUFn:
93 """Load the NPU expert projections with native activation rounding."""
94 extension = require_package("torch_npu")
95 require_symbol(extension, "npu_grouped_matmul")
96 # This autograd implementation imports the optional NPU extension.
97 from hyper_parallel.components.functional.grouped_matmul import ( # pylint: disable=import-outside-toplevel
98 grouped_matmul,
99 )
101 def run(
102 x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor,
103 counts: torch.Tensor, scores: torch.Tensor | None = None,
104 ) -> torch.Tensor:
105 """Apply NPU gate, up and down projections with the reference routing semantics."""
106 if x.shape[0] == 0:
107 return _empty_output(x, w1, w2, w3, scores)
108 offsets = counts.cumsum(0, dtype=torch.int64)
109 # Separate projections preserve native's two rounded input-gradient
110 # contributions. SiLU must also round before multiplying by up.
111 gate = grouped_matmul(x, w1.transpose(1, 2), group_list=offsets)
112 up = grouped_matmul(x, w3.transpose(1, 2), group_list=offsets)
113 hidden = _weighted(F.silu(gate) * up, scores)
114 return grouped_matmul(hidden, w2.transpose(1, 2), group_list=offsets)
116 return run
119def register_grouped_swiglu(registry: OpRegistry) -> None:
120 """Register equivalent expert SwiGLU implementations on CPU, CUDA and NPU."""
121 registry.register_family("grouped_swiglu", specs=(GROUPED_SWIGLU,))
122 registry.register_impl(
123 GROUPED_SWIGLU, name="native", devices=("cpu", "cuda", "npu"), load=lambda: native_grouped_swiglu,
124 )
125 registry.register_impl(GROUPED_SWIGLU, name="torch_npu", devices=("npu",), load=_load_npu)
126 registry.register_impl(
127 GROUPED_SWIGLU, name="torch_grouped_mm", devices=("cuda",), load=_load_cuda,
128 check_compatibility=check_torch_grouped_mm,
129 )