Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / tools / model_integration / case_matrix.py: 90%

162 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"""Precision-validation case matrix generation from manifest topology specs.""" 

16 

17from __future__ import annotations 

18 

19import dataclasses 

20import json 

21from dataclasses import asdict, dataclass, field 

22from typing import Any, Iterable, Mapping, Optional 

23 

24from hyper_parallel.models.validation_spec import TopologyConstraint 

25from hyper_parallel.trainer.config.parallelism import FullCheckpointConfig 

26 

27_TOPOLOGY_DEFAULTS = { 

28 "tp": 1, 

29 "cp": 1, 

30 "ep": 1, 

31 "fsdp": 1, 

32 "sequence_parallel": False, 

33 "recompute_layer": [], 

34} 

35_PARALLEL_TOPOLOGY_FIELDS = ( 

36 "tp", 

37 "cp", 

38 "ep", 

39 "fsdp", 

40 "sequence_parallel", 

41) 

42 

43 

44@dataclass(frozen=True) 

45class ValidationCase: 

46 """One resolved precision-validation topology and execution role.""" 

47 

48 name: str 

49 topology: dict[str, Any] 

50 kind: str = "topology" 

51 compare_to: str = "baseline" 

52 metadata: dict[str, Any] = field(default_factory=dict) 

53 

54 def to_dict(self) -> dict[str, Any]: 

55 """Return a JSON-serializable representation.""" 

56 return asdict(self) 

57 

58 

59def _case_name(topology: Mapping[str, Any], prefix: str = "") -> str: 

60 """Build a stable case name from the topology fields present.""" 

61 ordered = (*_PARALLEL_TOPOLOGY_FIELDS, "recompute_layer") 

62 pieces = [] 

63 for name in ordered: 

64 if name not in topology: 

65 continue 

66 value = topology[name] 

67 if name == "recompute_layer": 

68 value = "off" if not value else "layers" + "-".join(str(index) for index in value) 

69 pieces.append(f"{name}{value}") 

70 name = "_".join(str(piece).replace("/", "-") for piece in pieces) 

71 return f"{prefix}_{name}" if prefix else name 

72 

73 

74def _validate_recompute_layers(value: Any, path: str) -> list[int | str]: 

75 """Validate one explicit full-checkpoint layer set.""" 

76 if not isinstance(value, list): 

77 raise ValueError(f"{path} must be a list of layer numbers or ranges") 

78 if not value: 

79 return [] 

80 try: 

81 return list(FullCheckpointConfig(recompute_layer=value).recompute_layers) 

82 except ValueError as error: 

83 raise ValueError(str(error).replace("activation_checkpoint.full.recompute_layer", path)) from error 

84 

85 

86def _validate_topology(topology: Mapping[str, Any], path: str) -> dict[str, Any]: 

87 """Reject fields that the standard Trainer launcher cannot consume.""" 

88 if not isinstance(topology, Mapping): 

89 raise ValueError(f"{path} must be a mapping") 

90 resolved = dict(topology) 

91 unsupported = tuple(name for name in resolved if name not in _TOPOLOGY_DEFAULTS) 

92 if unsupported: 

93 supported = ", ".join(_TOPOLOGY_DEFAULTS) 

94 raise ValueError( 

95 f"{path} contains unsupported fields {unsupported}; supported fields: {supported}" 

96 ) 

97 if "recompute_layer" in resolved: 

98 resolved["recompute_layer"] = _validate_recompute_layers( 

99 resolved["recompute_layer"], 

100 f"{path}.recompute_layer", 

101 ) 

102 return resolved 

103 

104 

105def _acceptance_class( 

106 baseline: Mapping[str, Any], 

107 candidate: Mapping[str, Any], 

108) -> str: 

109 """Classify tolerances from the parallel topology actually launched.""" 

110 for field_name in _PARALLEL_TOPOLOGY_FIELDS: 

111 default = _TOPOLOGY_DEFAULTS[field_name] 

112 if baseline.get(field_name, default) != candidate.get(field_name, default): 

113 return "cross_topology" 

114 return "same_topology" 

115 

116 

117def _axis_cases( 

118 matrix: Mapping[str, Any], 

119 baseline: Mapping[str, Any], 

120 seen: set[str], 

121) -> list[ValidationCase]: 

122 """Generate one case per declared single-axis deviation.""" 

123 axes = matrix.get("axes") or {} 

124 if not isinstance(axes, Mapping): 

125 raise ValueError("matrix.axes must be a mapping") 

126 cases = [] 

127 for axis, values in axes.items(): 

128 if axis not in _TOPOLOGY_DEFAULTS: 

129 supported = ", ".join(_TOPOLOGY_DEFAULTS) 

130 raise ValueError( 

131 f"matrix.axes contains unsupported field {axis!r}; " 

132 f"supported fields: {supported}" 

133 ) 

134 if not isinstance(values, list) or not values: 

135 raise ValueError(f"matrix.axes.{axis} must be a non-empty list") 

136 for value in values: 

137 topology = dict(baseline) 

138 topology[axis] = value 

139 key = json.dumps(topology, sort_keys=True) 

140 if key in seen: 

141 continue 

142 seen.add(key) 

143 cases.append( 

144 ValidationCase(_case_name(topology, f"axis-{axis}"), topology) 

145 ) 

146 return cases 

147 

148 

149def _combined_cases( 

150 matrix: Mapping[str, Any], 

151 baseline: Mapping[str, Any], 

152 seen: set[str], 

153) -> list[ValidationCase]: 

154 """Generate one case per declared multi-axis combination.""" 

155 cases = [] 

156 for index, combined in enumerate(matrix.get("combined") or ()): 

157 if not isinstance(combined, Mapping): 

158 raise ValueError("matrix.combined entries must be mappings") 

159 topology = dict(baseline) 

160 topology.update(_validate_topology(combined, f"matrix.combined[{index}]")) 

161 key = json.dumps(topology, sort_keys=True) 

162 if key in seen: 

163 continue 

164 seen.add(key) 

165 cases.append(ValidationCase(_case_name(topology, f"combined-{index}"), topology)) 

166 return cases 

167 

168 

169def _recompute_cases( 

170 matrix: Mapping[str, Any], 

171 baseline: Mapping[str, Any], 

172 seen: set[str], 

173) -> list[ValidationCase]: 

174 """Generate one case per requested full-checkpoint layer set.""" 

175 requested_layer_sets = matrix.get("recompute_layers") or () 

176 if not isinstance(requested_layer_sets, (list, tuple)): 

177 raise ValueError("matrix.recompute_layers must be a list") 

178 cases = [] 

179 for index, requested_layers in enumerate(requested_layer_sets): 

180 recompute_layers = _validate_recompute_layers( 

181 requested_layers, 

182 f"matrix.recompute_layers[{index}]", 

183 ) 

184 topology = dict(baseline) 

185 topology.update( 

186 _validate_topology( 

187 matrix.get("recompute_topology") or {}, 

188 "matrix.recompute_topology", 

189 ) 

190 ) 

191 topology["recompute_layer"] = recompute_layers 

192 key = json.dumps(topology, sort_keys=True) 

193 if key in seen: 

194 continue 

195 seen.add(key) 

196 cases.append( 

197 ValidationCase(_case_name(topology, "recompute"), topology) 

198 ) 

199 return cases 

200 

201 

202def _ep1_fallback_case( 

203 cases: list[ValidationCase], 

204 baseline: Mapping[str, Any], 

205) -> Optional[ValidationCase]: 

206 """Retain a single-device-EP reference when every case parallelizes experts.""" 

207 if int(baseline.get("ep", 1)) <= 1 or any( 

208 int(case.topology.get("ep", 1)) == 1 for case in cases 

209 ): 

210 return None 

211 topology = dict(baseline) 

212 topology["ep"] = 1 

213 return ValidationCase(_case_name(topology, "axis-ep"), topology) 

214 

215 

216def _production_validate_cases( 

217 matrix: Mapping[str, Any], 

218 baseline: Mapping[str, Any], 

219) -> list[ValidationCase]: 

220 """Generate the production/validate placement pair when declared.""" 

221 production_validate = matrix.get("production_validate_pair") 

222 if not production_validate: 

223 return [] 

224 production_validate = _validate_topology( 

225 production_validate, 

226 "matrix.production_validate_pair", 

227 ) 

228 cases = [] 

229 for mode in ("production", "validate"): 

230 topology = dict(baseline) 

231 topology.update(production_validate) 

232 topology["validate_placement"] = mode == "validate" 

233 cases.append( 

234 ValidationCase( 

235 _case_name(topology, mode), 

236 topology, 

237 kind="production_validate", 

238 ) 

239 ) 

240 return cases 

241 

242 

243def _resume_cases( 

244 matrix: Mapping[str, Any], 

245 baseline: Mapping[str, Any], 

246) -> list[ValidationCase]: 

247 """Generate the declared same/cross-topology resume cases.""" 

248 cases = [] 

249 if matrix.get("same_topology_resume"): 

250 cases.append( 

251 ValidationCase( 

252 "same_topology_resume", 

253 dict(baseline), 

254 kind="resume", 

255 metadata={"resume": "same_topology"}, 

256 ) 

257 ) 

258 if matrix.get("cross_topology_resume"): 

259 topology = dict(baseline) 

260 topology.update( 

261 _validate_topology( 

262 matrix["cross_topology_resume"], 

263 "matrix.cross_topology_resume", 

264 ) 

265 ) 

266 if _acceptance_class(baseline, topology) == "same_topology": 

267 raise ValueError( 

268 "matrix.cross_topology_resume must change at least one of " 

269 f"{_PARALLEL_TOPOLOGY_FIELDS}. A recompute-only change is not a " 

270 "cross-topology restore; same_topology_resume always uses the " 

271 "baseline recompute policy, and a recompute-only resume matrix " 

272 "is not supported" 

273 ) 

274 cases.append( 

275 ValidationCase( 

276 "cross_topology_resume", 

277 topology, 

278 kind="resume", 

279 metadata={ 

280 "resume": "cross_topology", 

281 "prepare_topology": dict(baseline), 

282 }, 

283 ) 

284 ) 

285 return cases 

286 

287 

288def _finalize_cases( 

289 cases: list[ValidationCase], 

290 baseline: Mapping[str, Any], 

291 topology_constraints: Iterable[TopologyConstraint], 

292) -> tuple[ValidationCase, ...]: 

293 """Apply topology constraints and classify each case acceptance profile.""" 

294 resolved_cases = [] 

295 for case in cases: 

296 for constraint in topology_constraints: 

297 if not constraint.predicate(case.topology): 

298 raise ValueError( 

299 f"case {case.name!r} violates topology constraint " 

300 f"{constraint.name!r}: {constraint.remediation}" 

301 ) 

302 metadata = dict(case.metadata) 

303 metadata["acceptance"] = _acceptance_class(baseline, case.topology) 

304 resolved_cases.append(dataclasses.replace(case, metadata=metadata)) 

305 return tuple(resolved_cases) 

306 

307 

308def generate_validation_cases( 

309 matrix: Mapping[str, Any], 

310 topology_constraints: Iterable[TopologyConstraint] = (), 

311) -> tuple[ValidationCase, ...]: 

312 """Generate a minimum single-axis-plus-combined validation matrix.""" 

313 baseline = dict(matrix.get("baseline") or {}) 

314 if not baseline: 

315 raise ValueError("matrix.baseline is required") 

316 baseline = _validate_topology(baseline, "matrix.baseline") 

317 cases = [ValidationCase("baseline", baseline, compare_to="baseline")] 

318 seen = {json.dumps(baseline, sort_keys=True)} 

319 cases.extend(_axis_cases(matrix, baseline, seen)) 

320 cases.extend(_combined_cases(matrix, baseline, seen)) 

321 if matrix.get("recompute_layers"): 

322 cases.extend(_recompute_cases(matrix, baseline, seen)) 

323 ep1_case = _ep1_fallback_case(cases, baseline) 

324 if ep1_case is not None: 

325 cases.insert(1, ep1_case) 

326 cases.extend(_production_validate_cases(matrix, baseline)) 

327 cases.extend(_resume_cases(matrix, baseline)) 

328 return _finalize_cases(cases, baseline, topology_constraints) 

329 

330 

331__all__ = [ 

332 "ValidationCase", 

333 "generate_validation_cases", 

334]