Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mhc / _utils.py: 81%

59 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"""Validation and layout contracts shared by mHC implementations.""" 

16from __future__ import annotations 

17 

18from math import isfinite 

19from typing import Any 

20 

21from torch import nn 

22 

23from hyper_parallel.core.dtensor.placement_types import Replicate, Shard 

24from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

25 

26 

27def _required_attribute(module: nn.Module, name: str) -> Any: 

28 """Return a required source-module attribute.""" 

29 if not hasattr(module, name): 

30 raise TypeError(f"{module.__class__.__name__} is missing required attribute '{name}'") 

31 return getattr(module, name) 

32 

33 

34def _required_config_value(module: nn.Module, name: str) -> Any: 

35 """Return a required value from the source module or its config.""" 

36 if hasattr(module, name): 

37 return getattr(module, name) 

38 config = getattr(module, "config", None) 

39 if config is None or not hasattr(config, name): 

40 raise TypeError(f"{module.__class__.__name__} is missing required MHC setting '{name}'") 

41 return getattr(config, name) 

42 

43 

44def _num_stream(module: nn.Module) -> int: 

45 """Return and validate the source module's residual-stream count.""" 

46 value = getattr(module, "num_stream", None) 

47 if value is None: 

48 value = _required_config_value(module, "mhc_num_stream") 

49 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

50 raise ValueError(f"MHC num_stream must be a positive integer, but got {value}") 

51 return value 

52 

53 

54def _parameter(module: nn.Module, name: str) -> nn.Parameter: 

55 """Return a required source parameter.""" 

56 value = _required_attribute(module, name) 

57 if not isinstance(value, nn.Parameter): 

58 raise TypeError(f"MHC attribute '{name}' must be an nn.Parameter") 

59 return value 

60 

61 

62def _validate_parameter_layout(phi: nn.Linear, parameters: tuple[nn.Parameter, ...]) -> None: 

63 """Validate that MHC parameters share the projection's device and dtype.""" 

64 for parameter in parameters: 

65 if parameter.device != phi.weight.device or parameter.dtype != phi.weight.dtype: 

66 raise ValueError("MHC projection and branch parameters must share device and dtype") 

67 

68 

69def _validate_settings(num_stream: int, hidden_size: int | None = None, sinkhorn_iters: int = 20, 

70 hc_eps: float = 1e-6, norm_eps: float = 1e-6, use_gamma: bool = False) -> None: 

71 """Validate logical settings independently of the caller's config class.""" 

72 sizes = {"num_stream": num_stream} 

73 if hidden_size is not None: 

74 sizes.update(hidden_size=hidden_size, sinkhorn_iters=sinkhorn_iters) 

75 for name, value in sizes.items(): 

76 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

77 raise ValueError(f"{name} must be a positive integer") 

78 for name, value in (("hc_eps", hc_eps), ("norm_eps", norm_eps)): 

79 if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value <= 0: 

80 raise ValueError(f"{name} must be finite and positive") 

81 if not isinstance(use_gamma, bool): 

82 raise TypeError("use_gamma must be bool") 

83 

84 

85def pipelined_mhc_sharding(*, module: nn.Module, module_fqn: str, member: Any, 

86 context: Any) -> ModuleShardingSpec: 

87 """Own every coefficient matrix and keep token-local coefficient outputs aligned.""" 

88 del module_fqn, member 

89 replicated = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes} 

90 tokens = dict(replicated) 

91 if context.axis_sizes["cp"] > 1: 

92 tokens["cp"] = Shard(1) 

93 if context.axis_sizes["tp"] > 1 and context.sequence_parallel: 

94 tokens["tp"] = Shard(1) 

95 outputs = {name: dict(tokens) for name in ("pre", "post", "residual")} 

96 return ModuleShardingSpec( 

97 params={name: dict(replicated) for name, _ in module.named_parameters()}, 

98 in_src={"hidden_streams": dict(tokens)}, in_dst={"hidden_streams": dict(tokens)}, 

99 out_src=outputs, out_dst={name: dict(value) for name, value in outputs.items()}, 

100 out_names=("pre", "post", "residual"), is_boundary=True, 

101 ) 

102 

103 

104def _validate_pipelined(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None: 

105 """Reject fused execution without the matching shifted boundary protocol.""" 

106 del config, module, context 

107 if member.selectors["megakernel"] and not member.selectors["shifted"]: 

108 raise ValueError("Native pipelined mHC requires shifted=True")