Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / moe_token_reorder.py: 65%

49 statements  

« 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-order permutation and weighted restoration with a shared slot layout.""" 

16 

17from __future__ import annotations 

18 

19from typing import Protocol 

20 

21import torch 

22 

23from ..registry import OpRegistry 

24from ..spec import OpSpec 

25from .._dependency import require_package, require_symbol 

26 

27PermutedTokens = tuple[torch.Tensor, torch.Tensor, torch.Tensor] 

28 

29 

30class MoePermuteFn(Protocol): 

31 """Group token rows by expert and carry the original routed slot IDs.""" 

32 

33 def __call__(self, x: torch.Tensor, indices: torch.Tensor) -> PermutedTokens: 

34 """Return expert-major rows, slot order, and the position of each slot.""" 

35 

36 

37class MoeRestoreFn(Protocol): 

38 """Gather expert outputs in token-major order and sum weighted routes.""" 

39 

40 def __call__(self, x: torch.Tensor, slot_positions: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: 

41 """Cast weights to the expert output dtype before weighting and restoring tokens.""" 

42 

43 

44MOE_TOKEN_REORDER = OpSpec[MoePermuteFn](config_key="moe_token_reorder") 

45MOE_TOKEN_RESTORE = OpSpec[MoeRestoreFn](config_key="moe_token_reorder", variant="weighted_restore") 

46 

47 

48def _native_permute(x: torch.Tensor, indices: torch.Tensor) -> PermutedTokens: 

49 order = indices.flatten().argsort(stable=True) 

50 positions = torch.empty_like(order) 

51 positions.scatter_(0, order, torch.arange(order.numel(), device=order.device)) 

52 return x.index_select(0, order.div(indices.shape[1], rounding_mode="floor")), order, positions 

53 

54 

55def _native_restore(x: torch.Tensor, slot_positions: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: 

56 order = torch.empty_like(slot_positions) 

57 order.scatter_(0, slot_positions, torch.arange(order.numel(), device=order.device)) 

58 token_ids = order.div(weights.shape[1], rounding_mode="floor") 

59 ordered_weights = weights.to(x.dtype).flatten().index_select(0, order) 

60 return x.new_zeros((weights.shape[0], x.shape[-1])).index_add_( 

61 0, token_ids, x * ordered_weights.unsqueeze(-1), 

62 ) 

63 

64 

65def _load_npu() -> MoePermuteFn: 

66 """Load the stable NPU token permutation adapter and inverse mapping.""" 

67 extension = require_package("torch_npu") 

68 require_symbol(extension, "npu_moe_token_permute") 

69 require_symbol(extension, "npu_moe_token_unpermute") 

70 

71 def permute(x: torch.Tensor, indices: torch.Tensor) -> PermutedTokens: 

72 """Return routed rows and the shared int64 slot mapping.""" 

73 states, positions = extension.npu_moe_token_permute(x, indices.to(torch.int32)) 

74 positions = positions.to(torch.int64) 

75 order = torch.empty_like(positions) 

76 order.scatter_(0, positions, torch.arange(positions.numel(), device=positions.device)) 

77 return states, order, positions 

78 

79 return permute 

80 

81 

82def _load_npu_restore() -> MoeRestoreFn: 

83 """Load NPU token restoration with native route-weight rounding.""" 

84 extension = require_package("torch_npu") 

85 require_symbol(extension, "npu_moe_token_permute") 

86 require_symbol(extension, "npu_moe_token_unpermute") 

87 

88 def restore(x: torch.Tensor, slot_positions: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: 

89 # Round like the reference before presenting the routing dtype to the kernel. 

90 """Round route weights like native before restoring token order.""" 

91 probabilities = weights.to(x.dtype).to(weights.dtype) 

92 return extension.npu_moe_token_unpermute(x, slot_positions.to(torch.int32), probabilities).to(x.dtype) 

93 

94 return restore 

95 

96 

97def register_moe_token_reorder(registry: OpRegistry) -> None: 

98 """Register Torch and Ascend operators for the same routed-slot layout.""" 

99 registry.register_family("moe_token_reorder", specs=(MOE_TOKEN_REORDER, MOE_TOKEN_RESTORE)) 

100 registry.register_impl( 

101 MOE_TOKEN_REORDER, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_permute, 

102 ) 

103 registry.register_impl( 

104 MOE_TOKEN_RESTORE, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_restore, 

105 ) 

106 registry.register_impl(MOE_TOKEN_REORDER, name="torch_npu", devices=("npu",), load=_load_npu) 

107 registry.register_impl(MOE_TOKEN_RESTORE, name="torch_npu", devices=("npu",), load=_load_npu_restore)