Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / attention / multi_latent_attention / multi_latent_attention_family.py: 92%

77 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"""MLA family selection and complete parameter/layout ownership.""" 

16 

17from __future__ import annotations 

18 

19from importlib import import_module 

20from typing import Any 

21 

22from torch import nn 

23 

24from hyper_parallel.components.modules.module_family import ( 

25 ModuleFamily, VariantRule, build_family, register_module_family, 

26) 

27from hyper_parallel.core.dtensor.placement_types import Partial, Replicate, Shard 

28from hyper_parallel.distributed.module_binding import ParallelModuleSpec 

29from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec 

30from hyper_parallel.distributed._builder.family_layout import validate_tp_boundary 

31from hyper_parallel.models.replacement import module_replacement 

32 

33 

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

35 """Validate logical ownership before allocating or replacing any parameter.""" 

36 del context 

37 config = config if module is None else module.config 

38 if config is None: 

39 raise ValueError("MLA requires source configuration") 

40 options = member.arguments 

41 if not isinstance(options.get("overlap", False), bool): 

42 raise TypeError("MLA overlap must be boolean") 

43 if options.get("strategy", "expanded_ulysses") not in ("expanded_ulysses", "latent_kv_head"): 

44 raise ValueError("Unknown MLA CP strategy") 

45 exchange = options.get("kv_exchange", "all_gather") 

46 if exchange not in ("all_gather", "all_to_all_v"): 

47 raise ValueError("kv_exchange must be all_gather or all_to_all_v") 

48 cp, tp = member.axis_sizes["cp"], member.axis_sizes["tp"] 

49 degree = options.get("ulysses_degree") 

50 degree = cp if degree is None else degree 

51 if not isinstance(degree, int) or isinstance(degree, bool) or degree < 1: 

52 raise ValueError("MLA Ulysses degree must be a positive integer") 

53 if config.num_attention_heads % tp: 

54 raise ValueError("MLA heads must be divisible by TP degree") 

55 _validate_mla_topology(config, cp, tp, degree, exchange) 

56 

57 

58def _validate_mla_topology(config, cp, tp, degree, exchange): 

59 """Check active CP decomposition after validating selector syntax.""" 

60 # CP1 may retain a valid future CP request for promotion. Validate syntax 

61 # now; validate the actual factorization once CP topology becomes active. 

62 if cp > 1: 

63 if cp % degree or config.num_attention_heads % (tp * degree): 

64 raise ValueError("MLA Ulysses degree must divide CP degree and TP-local heads") 

65 if exchange == "all_to_all_v" and cp == degree: 

66 raise ValueError("selective KV exchange requires query-partitioned MLA CP") 

67 if tp > 1 and cp != degree: 

68 raise ValueError("MLA KV AllGather and hybrid CP currently require TP1") 

69 

70def mla_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec: 

71 """Own all MLA parameters and declare the actual external token layout.""" 

72 del module_fqn, member 

73 placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes} 

74 # Every supported parameter has an explicit role. A new/quantized projection 

75 # must declare its layout instead of silently inheriting Replicate. 

76 columns = {f"{name}.{suffix}" for name in ('q_b_proj', 'kv_b_proj', 'g_proj') 

77 for suffix in ("weight", "bias")} 

78 replicated = {f"{name}.{suffix}" for name in ('linear_qkv', 'q_a_layernorm', 'kv_a_layernorm') 

79 for suffix in ("weight", "bias")} 

80 roles = {**dict.fromkeys(columns, Shard(0)), **dict.fromkeys(replicated, Replicate()), 

81 "o_proj.weight": Shard(1), "o_proj.bias": Replicate()} 

82 params = {} 

83 for name, _ in module.named_parameters(): 

84 if name not in roles: 

85 raise ValueError(f"MLA parameter {name!r} has no declared sharding role") 

86 params[name] = dict(placements) 

87 if context.axis_sizes["tp"] > 1: 

88 params[name]["tp"] = roles[name] 

89 tokens = dict(placements) 

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

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

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

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

94 # CP ownership describes the external token shard. Ulysses changes head / 

95 # sequence ownership internally and restores this same shard before return. 

96 compute_input, compute_output = dict(tokens), dict(tokens) 

97 if context.axis_sizes["tp"] > 1: 

98 compute_input["tp"], compute_output["tp"] = Replicate(), Partial() 

99 return ModuleShardingSpec( 

100 params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input}, 

101 out_src={"output": compute_output}, out_dst={"output": dict(tokens)}, 

102 out_names=("output", "attention_weights"), is_boundary=True, 

103 ) 

104 

105 

106def validate_mla_layout(*, module: nn.Module, sharding: Any, context: Any) -> None: 

107 """Reject incompatible parameter overrides before any collectives can be bound.""" 

108 expected = mla_sharding(module=module, module_fqn="", member=None, context=context) 

109 validate_tp_boundary(sharding, expected, name="MLA") 

110 if context.axis_sizes["tp"] > 1 and getattr(module, "use_nope", False): 

111 raise ValueError("Gated MLA currently supports TP1 only") 

112 

113 

114def mla_local_parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec: 

115 """Keep layout validation outside the standalone algorithm.""" 

116 del module, member 

117 return ParallelModuleSpec("attention.mla.local", validate=validate_mla_layout) 

118 

119 

120def _build_local( 

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

122 strategy: str = "expanded_ulysses", overlap: bool = False, 

123 ulysses_degree: int | None = None, kv_exchange: str = "all_gather", 

124) -> nn.Module: 

125 """Consume family-only options; the saved request retains them for CP preparation.""" 

126 # Resolve after family registration; concrete members import this module's layout validators. 

127 implementation = import_module('.multi_latent_attention', __package__).MultiLatentAttentionModule 

128 

129 del module_fqn, context, strategy, overlap, ulysses_degree, kv_exchange 

130 return implementation(config=config, module=module) 

131 

132 

133@module_replacement 

134def MultiLatentAttention( # pylint: disable=invalid-name 

135 *, config: Any = None, module: nn.Module | None = None, 

136 module_fqn: str = "", context: Any = None, mesh: Any = None, 

137 strategy: str = "expanded_ulysses", overlap: bool = False, 

138 ulysses_degree: int | None = None, kv_exchange: str = "all_gather", 

139) -> nn.Module: 

140 """Build the MLA member from dimensions or a supported source module. 

141 

142 Args: 

143 config: Full model dimensions and attention options for direct construction. 

144 module: Optional source attention; exclusive with config. 

145 module_fqn: Source path supplied by model replacement. 

146 context: Logical build constraints. Topology selects the local or CP implementation. 

147 mesh: Optional existing job mesh used by the shared layout planner. 

148 strategy: Expanded QKV Ulysses or shared latent-KV communication. 

149 overlap: Enable existing forward and supported backward scheduling. 

150 ulysses_degree: CP head-parallel factor; the remaining factor partitions queries. 

151 kv_exchange: Full AllGather or selective causal-document AllToAllV. 

152 

153 Returns: 

154 The concrete MLA algorithm with family provenance and unchanged parameter FQNs. 

155 """ 

156 return build_family(MultiLatentAttention, config=config, module=module, 

157 module_fqn=module_fqn, context=context, mesh=mesh, 

158 strategy=strategy, overlap=overlap, ulysses_degree=ulysses_degree, kv_exchange=kv_exchange) 

159 

160 

161register_module_family(ModuleFamily( 

162 name="multi_latent_attention", baseline=MultiLatentAttention, 

163 variants={"local": ( 

164 "hyper_parallel.components.modules.attention.multi_latent_attention." 

165 "multi_latent_attention_family._build_local" 

166 ), "cp": ( 

167 "hyper_parallel.components.modules.attention.multi_latent_attention." 

168 "cp_multi_latent_attention.CPMultiLatentAttentionModule" 

169 )}, 

170 default_variant="local", parallel_axis="cp", 

171 variant_rules=(VariantRule({"parallel": True}, "cp"),), 

172 sharding=mla_sharding, validate=validate_mla_family, parallel_spec=mla_local_parallel_spec, 

173))