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

54 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"""Pixel-unshuffle spatial merging followed by a two-layer GELU projector.""" 

16from __future__ import annotations 

17 

18from typing import Any 

19 

20from torch import Tensor, nn 

21from torch.nn import functional as F 

22 

23from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family 

24from hyper_parallel.models.replacement import module_replacement 

25 

26 

27class SpatialMergeProjectorModule(nn.Module): 

28 """Own V4.1-compatible channel-major spatial merging and its projections.""" 

29 

30 def __init__(self, *, config: Any = None, module: nn.Module | None = None) -> None: 

31 """Construct logical dimensions or reuse a compatible source's loaded projections.""" 

32 super().__init__() 

33 if (config is None) == (module is None): 

34 raise ValueError("provide exactly one of config or module") 

35 if module is not None: 

36 self.downsample_ratio = module.downsample_ratio 

37 if not all(isinstance(getattr(module, key, None), nn.Linear) for key in ("w1", "w2")): 

38 raise TypeError("spatial projector source requires w1/w2 linear projections") 

39 self.w1, self.w2 = module.w1, module.w2 

40 self.train(module.training) 

41 else: 

42 self.downsample_ratio = config.downsample_ratio 

43 for key in ("input_size", "hidden_size", "output_size"): 

44 value = getattr(config, key) 

45 if isinstance(value, bool) or not isinstance(value, int) or value < 1: 

46 raise ValueError(f"{key} must be a positive integer") 

47 if not isinstance(config.bias, bool): 

48 raise TypeError("bias must be bool") 

49 self._validate_ratio() 

50 self.w1 = nn.Linear(config.input_size * self.downsample_ratio**2, config.hidden_size, bias=config.bias) 

51 self.w2 = nn.Linear(config.hidden_size, config.output_size, bias=config.bias) 

52 self._validate_ratio() 

53 if self.w1.in_features % self.downsample_ratio**2 or self.w1.out_features != self.w2.in_features: 

54 raise ValueError("spatial projector dimensions do not match the merge ratio and hidden projection") 

55 

56 def _validate_ratio(self) -> None: 

57 """Reject fractional, boolean or nonpositive spatial ratios.""" 

58 if (isinstance(self.downsample_ratio, bool) or not isinstance(self.downsample_ratio, int) 

59 or self.downsample_ratio < 1): 

60 raise ValueError("downsample_ratio must be a positive integer") 

61 

62 def forward(self, hidden_states: Tensor, grid_height: int | None = None, 

63 grid_width: int | None = None, *, input_is_merged: bool = False) -> Tensor: 

64 """Project a full image grid or already merged channel-major output rows. 

65 

66 Args: 

67 hidden_states: Image patch rows, or [output_rows, ratio**2 * input_size]. 

68 grid_height: Full image patch height for ordinary spatial merging. 

69 grid_width: Full image patch width for ordinary spatial merging. 

70 input_is_merged: Use preassembled independent spatial blocks. This 

71 retains the module forward boundary for FSDP and checkpointing. 

72 """ 

73 if input_is_merged: 

74 if grid_height is not None or grid_width is not None: 

75 raise ValueError("premerged projector inputs do not take image grid dimensions") 

76 if hidden_states.ndim != 2 or hidden_states.shape[1] != self.w1.in_features: 

77 raise ValueError("premerged projector rows must match w1.in_features") 

78 return self.w2(F.gelu(self.w1(hidden_states))) # pylint: disable=not-callable 

79 

80 if any(isinstance(size, bool) or not isinstance(size, int) or size < 1 for size in (grid_height, grid_width)): 

81 raise ValueError("grid dimensions must be positive integers") 

82 channels = self.w1.in_features // self.downsample_ratio**2 

83 if hidden_states.ndim != 2 or hidden_states.shape != (grid_height * grid_width, channels): 

84 raise ValueError("features must have shape [grid_height * grid_width, input_size]") 

85 ratio = self.downsample_ratio 

86 grid = hidden_states.reshape(grid_height, grid_width, channels).permute(2, 0, 1) 

87 grid = F.pad(grid, (0, -grid_width % ratio, 0, -grid_height % ratio)) 

88 merged = F.unfold(grid.unsqueeze(0), ratio, stride=ratio).squeeze(0).transpose(0, 1) 

89 return self.w2(F.gelu(self.w1(merged))) # pylint: disable=not-callable 

90 

91 

92@module_replacement 

93def SpatialMergeProjector( # pylint: disable=invalid-name 

94 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "", 

95 context: Any = None, mesh: Any = None, 

96) -> nn.Module: 

97 """Build the spatial-merging family; window/LayerNorm mergers require a different contract.""" 

98 return build_family(SpatialMergeProjector, config=config, module=module, module_fqn=module_fqn, 

99 context=context, mesh=mesh) 

100 

101 

102register_module_family(ModuleFamily( 

103 name="spatial_merge_projector", baseline=SpatialMergeProjector, 

104 variants={"local": 

105 "hyper_parallel.components.modules.common.spatial_merge_projector.SpatialMergeProjectorModule"}, 

106 default_variant="local", 

107))