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

738 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"""Auditable CLI for model inspection, model integration, parity, and precision validation.""" 

16 

17from __future__ import annotations 

18 

19import argparse 

20import json 

21import os 

22import subprocess 

23import sys 

24from pathlib import Path 

25from typing import Any, Iterable, Mapping, Optional 

26 

27import yaml 

28 

29from hyper_parallel.components.checkpoint import STEP_PREFIX 

30from hyper_parallel.tools.model_integration.evidence_store import ( 

31 EvidenceStore, 

32 find_repository_root, 

33) 

34from hyper_parallel.tools.model_integration.structure_inventory import ( 

35 ModelInventory, 

36 build_model_inventory, 

37 diff_inventories, 

38 inspect_local_model_assets, 

39) 

40from hyper_parallel.tools.model_integration.manifest import ( 

41 ManifestError, 

42 ValidationManifest, 

43 load_manifest, 

44) 

45from hyper_parallel.tools.model_integration.module_parity import ( 

46 ParityContext, 

47 run_module_parity, 

48) 

49from hyper_parallel.tools.model_integration.case_compare import ( 

50 compare_checkpoint_layouts, 

51 compare_parameter_probes, 

52 compare_preflight_configs, 

53 compare_scalar_curves, 

54 load_jsonl, 

55 summarize_performance, 

56) 

57from hyper_parallel.tools.model_integration.case_matrix import ( 

58 generate_validation_cases, 

59) 

60from hyper_parallel.tools.model_integration.schemas import ( 

61 ModelIntegrationReport, 

62 FindingSeverity, 

63 IntegrationState, 

64 ModelIntegrationFinding, 

65 SCHEMA_VERSION, 

66) 

67from hyper_parallel.tools.model_integration.integration_validator import ( 

68 validate_final_model, 

69) 

70from hyper_parallel.models.registry import get_model_adapter 

71from hyper_parallel.models.validation_spec import ModelValidationSpec 

72from hyper_parallel.trainer.config.parallelism import FullCheckpointConfig 

73 

74 

75_REPOSITORY_ROOT = find_repository_root() 

76_SHARED_INITIAL_CHECKPOINT_STEP = 1 

77_HCCL_PORT_STRIDE = 256 

78 

79 

80def _manifest_from_args(args: argparse.Namespace) -> ValidationManifest: 

81 manifest = load_manifest(args.manifest, output_dir=args.output_dir) 

82 manifest.validate_for(args.command) 

83 return manifest 

84 

85 

86def _store(manifest: ValidationManifest) -> EvidenceStore: 

87 store = EvidenceStore(manifest.output_dir) 

88 store.write_yaml("manifest.resolved.yaml", manifest.to_dict()) 

89 store.capture_environment() 

90 return store 

91 

92 

93def _ensure_discovered(store: EvidenceStore) -> None: 

94 """Initialize the first validation gate for an existing adapter.""" 

95 if store.current_state() is None: 

96 store.update_state(IntegrationState.DISCOVERED, ("manifest.resolved.yaml",)) 

97 

98 

99def _require_state(store: EvidenceStore, expected: IntegrationState, command: str) -> None: 

100 """Require the previous evidence-backed gate before a dependent command.""" 

101 actual = store.current_state() 

102 if actual is not expected: 

103 actual_name = "none" if actual is None else actual.value 

104 raise ManifestError( 

105 f"{command} requires integration state {expected.value}, got {actual_name}; " 

106 "run the preceding model-integration gates in the same output directory" 

107 ) 

108 

109 

110def _require_precision_handoff( 

111 store: EvidenceStore, 

112 manifest: ValidationManifest, 

113) -> None: 

114 """Accept same-run parity state or import an explicit passing handoff.""" 

115 current_state = store.current_state() 

116 if current_state is IntegrationState.MODULE_PARITY_PASSED: 

117 return 

118 if current_state in (IntegrationState.FAILED, IntegrationState.BLOCKED): 

119 raise ManifestError( 

120 f"validate cannot import a handoff into terminal integration state " 

121 f"{current_state.value}; use a new output directory" 

122 ) 

123 handoff_path = manifest.integration_handoff_path 

124 if handoff_path is None: 

125 _require_state(store, IntegrationState.MODULE_PARITY_PASSED, "validate") 

126 return 

127 handoff = yaml.safe_load(handoff_path.read_text(encoding="utf-8")) 

128 store.write_yaml("integration_handoff.yaml", handoff) 

129 imported_evidence = [] 

130 for handoff_key, default_path, destination in ( 

131 ("structure_findings", "check/findings.json", "check/findings.json"), 

132 ("module_parity", "module_parity/comparison.json", "module_parity/comparison.json"), 

133 ("checkpoint_coverage", "checkpoint/coverage.json", "checkpoint/coverage.json"), 

134 ): 

135 source = Path(handoff.get(handoff_key, default_path)) 

136 if not source.is_absolute(): 

137 source = handoff_path.parent / source 

138 if not source.is_file(): 

139 raise ManifestError( 

140 f"integration_handoff {handoff_key} evidence does not exist: {source}" 

141 ) 

142 try: 

143 payload = json.loads(source.read_text(encoding="utf-8")) 

144 except (OSError, json.JSONDecodeError) as error: 

145 raise ManifestError( 

146 f"could not read integration_handoff {handoff_key} evidence: {error}" 

147 ) from error 

148 store.write_json(destination, payload) 

149 imported_evidence.append(destination) 

150 for state in ( 

151 IntegrationState.DISCOVERED, 

152 IntegrationState.STRUCTURE_VALIDATED, 

153 IntegrationState.MODULE_PARITY_PASSED, 

154 ): 

155 store.advance_if_before( 

156 state, 

157 ("integration_handoff.yaml", *imported_evidence), 

158 reason="imported passing integration handoff", 

159 ) 

160 

161 

162def _build_declared_model(manifest: ValidationManifest, section_name: str) -> Any: 

163 """Build the model declared by one manifest section.""" 

164 section = getattr(manifest, section_name) 

165 builder = section.get("builder") 

166 if not isinstance(builder, Mapping): 

167 raise ManifestError( 

168 f"{section_name}.builder is required and must contain _target_ for this command" 

169 ) 

170 target = builder.get("_target_") 

171 callable_value = manifest.import_callable(target) 

172 kwargs = {name: value for name, value in builder.items() if name != "_target_"} 

173 result = callable_value(**kwargs) 

174 if not hasattr(result, "named_modules"): 

175 raise ManifestError( 

176 f"{section_name}.builder returned {type(result).__name__}, expected a module" 

177 ) 

178 return result 

179 

180 

181def _static_inventory(inspection: Mapping[str, Any], source: Mapping[str, Any]) -> ModelInventory: 

182 return ModelInventory( 

183 source=dict(source), 

184 config=dict(inspection.get("config", {})), 

185 checkpoint=dict(inspection.get("checkpoint", {})), 

186 ) 

187 

188 

189def _inspect_side( 

190 manifest: ValidationManifest, 

191 section_name: str, 

192) -> ModelInventory: 

193 """Collect the module inventory for one manifest section.""" 

194 section = getattr(manifest, section_name) 

195 if isinstance(section.get("builder"), Mapping): 

196 return build_model_inventory( 

197 _build_declared_model(manifest, section_name), 

198 source={ 

199 "section": section_name, 

200 "revision": section.get("revision"), 

201 }, 

202 ) 

203 path = manifest.model_path if section_name == "model" else manifest.reference_path 

204 if path is None: 

205 raise ManifestError( 

206 f"{section_name} requires either a local path or an explicit builder" 

207 ) 

208 return _static_inventory( 

209 inspect_local_model_assets(path), 

210 {"section": section_name, "path": str(path), "revision": section.get("revision")}, 

211 ) 

212 

213 

214def command_inspect(args: argparse.Namespace) -> int: 

215 """Create reference/candidate inventories and a classified diff.""" 

216 manifest = _manifest_from_args(args) 

217 store = _store(manifest) 

218 candidate = _inspect_side(manifest, "model") 

219 store.write_json("inventory/candidate.json", candidate.to_dict()) 

220 differences = [] 

221 if manifest.reference: 

222 reference = _inspect_side(manifest, "reference") 

223 store.write_json("inventory/reference.json", reference.to_dict()) 

224 differences = [ 

225 difference.to_dict() 

226 for difference in diff_inventories(reference, candidate) 

227 ] 

228 store.write_json( 

229 "inventory/structure_diff.json", 

230 {"status": "REVIEW_REQUIRED" if differences else "PASS", "differences": differences}, 

231 ) 

232 store.write_json("source_fingerprints.json", manifest.fingerprint_paths()) 

233 store.advance_if_before( 

234 IntegrationState.DISCOVERED, 

235 ( 

236 "environment.json", 

237 "manifest.resolved.yaml", 

238 "inventory/candidate.json", 

239 "inventory/structure_diff.json", 

240 ), 

241 ) 

242 print(store.root) 

243 return 0 

244 

245 

246_LICENSE = """# Copyright 2026 Huawei Technologies Co., Ltd 

247# 

248# Licensed under the Apache License, Version 2.0 (the \"License\"); 

249# you may not use this file except in compliance with the License. 

250# You may obtain a copy of the License at 

251# 

252# http://www.apache.org/licenses/LICENSE-2.0 

253# 

254# Unless required by applicable law or agreed to in writing, software 

255# distributed under the License is distributed on an \"AS IS\" BASIS, 

256# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

257# See the License for the specific language governing permissions and 

258# limitations under the License. 

259# ============================================================================ 

260""" 

261 

262 

263def command_scaffold(args: argparse.Namespace) -> int: 

264 """Generate a minimal adapter/validation skeleton in a new directory.""" 

265 manifest = _manifest_from_args(args) 

266 destination = Path(args.scaffold_dir).expanduser().resolve() 

267 if destination.exists() and any(destination.iterdir()): 

268 raise ManifestError(f"scaffold destination must be new or empty: {destination}") 

269 adapter_dir = destination / "adapter" 

270 adapter_dir.mkdir(parents=True, exist_ok=True) 

271 family = manifest.family 

272 files = { 

273 destination / "__init__.py": _LICENSE + f'"""{family} model integration package."""\n', 

274 adapter_dir / "__init__.py": _LICENSE + f'"""{family} adapter providers."""\n', 

275 adapter_dir / "registration.py": _LICENSE 

276 + '"""Register model-owned integration providers."""\n\n' 

277 + "from hyper_parallel.models.adapter_spec import ModelAdapterSpec\n" 

278 + "from hyper_parallel.models.registry import register_model_adapter\n\n\n" 

279 + "def _load_validation():\n" 

280 + ' """Load validation-only declarations lazily."""\n' 

281 + " from .validation import get_validation_spec # pylint: disable=C0415\n\n" 

282 + " return get_validation_spec()\n\n\n" 

283 + "MODEL_ADAPTER_SPEC = ModelAdapterSpec(\n" 

284 + f" architecture={manifest.model.get('architecture', family)!r},\n" 

285 + f" model_type={manifest.model.get('model_type', family)!r},\n" 

286 + " validation=_load_validation,\n" 

287 + ")\n" 

288 + "register_model_adapter(MODEL_ADAPTER_SPEC)\n", 

289 adapter_dir / "validation.py": _LICENSE 

290 + '"""Declare authoritative module and self-consistency validation."""\n\n' 

291 + "from hyper_parallel.models.validation_spec import ModelValidationSpec\n\n\n" 

292 + "def get_validation_spec() -> ModelValidationSpec:\n" 

293 + ' """Return model-owned validation declarations."""\n' 

294 + " return ModelValidationSpec()\n", 

295 destination / "validation.yaml": ( 

296 "schema_version: 2\n" 

297 f"model:\n adapter: {family}\n" 

298 "launcher:\n" 

299 " module: your.training.module\n" 

300 " config: path/to/trainer.yaml\n" 

301 "matrix:\n" 

302 " devices: 1\n" 

303 " steps: 10\n" 

304 ' baseline: {tp: 1, cp: 1, ep: 1, fsdp: 1, recompute_layer: []}\n' 

305 "acceptance:\n same_topology: {loss_max_abs: 0.0, norm_max_abs: 0.0}\n" 

306 ), 

307 destination / "test_registration.py": _LICENSE 

308 + '"""Registration smoke test for the generated model adapter."""\n\n' 

309 + "import unittest\n\n" 

310 + "from hyper_parallel.models.registry import get_model_adapter\n\n\n" 

311 + "from .adapter import registration # noqa: F401\n\n\n" 

312 + "class TestRegistration(unittest.TestCase):\n" 

313 + ' """Verify model-family lookup after registration import."""\n\n' 

314 + " def test_registration(self) -> None:\n" 

315 + ' """Require the generated adapter to be discoverable."""\n' 

316 + f" self.assertIsNotNone(get_model_adapter({family!r}))\n", 

317 } 

318 for path, content in files.items(): 

319 path.write_text(content, encoding="utf-8") 

320 store = _store(manifest) 

321 store.write_json( 

322 "scaffold.json", 

323 {"files": tuple(str(path.relative_to(destination)) for path in files)}, 

324 ) 

325 print(destination) 

326 return 0 

327 

328 

329def command_check(args: argparse.Namespace) -> int: 

330 """Run strict final-tree/materialization/FSDP ownership diagnostics.""" 

331 manifest = _manifest_from_args(args) 

332 store = _store(manifest) 

333 try: 

334 model = _build_declared_model(manifest, "model") 

335 except ManifestError: 

336 raise 

337 except (ImportError, OSError, RuntimeError, TypeError, ValueError) as error: 

338 finding = ModelIntegrationFinding( 

339 phase="D2", 

340 owner_fqn="<model_builder>", 

341 severity=FindingSeverity.ERROR, 

342 message="final model construction failed before model integration could inspect the tree", 

343 facts={"error_type": type(error).__name__, "error": str(error)}, 

344 why_unsafe="a partially built or partially planned model cannot enter training", 

345 remediation="follow the replacement or planner error and rebuild the final model", 

346 related_config=("model.builder", "plan_overrides"), 

347 ) 

348 report = ModelIntegrationReport(findings=[finding]) 

349 store.write_json("check/findings.json", report.to_dict()) 

350 _ensure_discovered(store) 

351 store.update_state( 

352 IntegrationState.FAILED, 

353 ("check/findings.json",), 

354 reason="model construction failed", 

355 ) 

356 print(finding.format_human(), file=sys.stderr) 

357 return 1 

358 report, ownership, fsdp_units = validate_final_model( 

359 model, 

360 context={"manifest": manifest.to_dict()}, 

361 ) 

362 store.write_json("check/findings.json", report.to_dict()) 

363 store.write_json("check/fsdp_units.json", fsdp_units) 

364 store.write_json( 

365 "checkpoint/coverage.json", 

366 report.metadata.get("checkpoint_coverage", {}), 

367 ) 

368 store.write_csv( 

369 "check/parameter_ownership.csv", 

370 (entry.to_dict() for entry in ownership), 

371 fieldnames=( 

372 "parameter_fqn", 

373 "owner_fqn", 

374 "gradient_domain", 

375 "source_mesh", 

376 "source_placements", 

377 "global_shape", 

378 "local_shape", 

379 ), 

380 ) 

381 if report.errors: 

382 store.update_state( 

383 IntegrationState.FAILED, 

384 ("check/findings.json", "check/parameter_ownership.csv"), 

385 reason="structure model integration reported ERROR findings", 

386 ) 

387 print("\n\n".join(finding.format_human() for finding in report.errors), file=sys.stderr) 

388 return 1 

389 _ensure_discovered(store) 

390 store.update_state( 

391 IntegrationState.STRUCTURE_VALIDATED, 

392 ("check/findings.json", "check/parameter_ownership.csv", "check/fsdp_units.json"), 

393 ) 

394 print(store.root) 

395 return 0 

396 

397 

398def _validation_spec(manifest: ValidationManifest) -> ModelValidationSpec: 

399 """Resolve the model-owned validation spec from the adapter.""" 

400 adapter = get_model_adapter(manifest.family) 

401 if adapter is None: 

402 raise ManifestError(f"no model adapter registered for {manifest.family!r}") 

403 provider = adapter.validation 

404 if provider is None or not callable(provider): 

405 raise ManifestError( 

406 f"model adapter {manifest.family!r} does not declare a validation provider" 

407 ) 

408 validation_spec = provider() 

409 if not isinstance(validation_spec, ModelValidationSpec): 

410 raise ManifestError("adapter validation provider returned the wrong type") 

411 return validation_spec 

412 

413 

414def _parameter_tolerance( 

415 acceptance: Mapping[str, Any], 

416 profile: str, 

417) -> dict[str, Any]: 

418 """Resolve strict base parameter limits plus an optional named override.""" 

419 parameters = acceptance.get("parameters", {}) 

420 if not isinstance(parameters, Mapping): 

421 raise ManifestError("acceptance.parameters must be a mapping") 

422 profile_names = ("module_parity", "same_topology", "cross_topology") 

423 tolerance = { 

424 name: value 

425 for name, value in parameters.items() 

426 if name not in profile_names 

427 } 

428 override = parameters.get(profile) 

429 if override is None: 

430 return tolerance 

431 if not isinstance(override, Mapping): 

432 raise ManifestError(f"acceptance.parameters.{profile} must be a mapping") 

433 override = dict(override) 

434 if "summary" in override: 

435 base_summary = tolerance.get("summary", {}) 

436 override_summary = override["summary"] 

437 if not isinstance(base_summary, Mapping) or not isinstance(override_summary, Mapping): 

438 raise ManifestError( 

439 f"acceptance.parameters.{profile}.summary must be a mapping" 

440 ) 

441 override["summary"] = {**base_summary, **override_summary} 

442 tolerance.update(override) 

443 return tolerance 

444 

445 

446def command_parity(args: argparse.Namespace) -> int: 

447 """Run final-module authoritative parity cases from the model provider.""" 

448 manifest = _manifest_from_args(args) 

449 store = _store(manifest) 

450 _require_state(store, IntegrationState.STRUCTURE_VALIDATED, "parity") 

451 validation_spec = _validation_spec(manifest) 

452 tolerance = _parameter_tolerance(manifest.acceptance, "module_parity") 

453 context = ParityContext( 

454 manifest=manifest, 

455 dtype=args.dtype, 

456 device=args.device, 

457 evidence_store=store, 

458 options={"tolerance": tolerance}, 

459 ) 

460 report = run_module_parity(validation_spec, context) 

461 if report["status"] == "PASS": 

462 store.write_yaml( 

463 "integration_handoff.yaml", 

464 { 

465 "schema_version": SCHEMA_VERSION, 

466 "family": manifest.family, 

467 "manifest": "manifest.resolved.yaml", 

468 "structure_findings": "check/findings.json", 

469 "module_parity": "module_parity/comparison.json", 

470 "checkpoint_coverage": "checkpoint/coverage.json", 

471 "status": "PASS", 

472 }, 

473 ) 

474 store.update_state( 

475 IntegrationState.MODULE_PARITY_PASSED, 

476 ("module_parity/comparison.json", "integration_handoff.yaml"), 

477 ) 

478 return 0 

479 terminal = IntegrationState.FAILED if report["status"] == "FAIL" else IntegrationState.BLOCKED 

480 store.update_state(terminal, ("module_parity/comparison.json",), reason=report["status"]) 

481 return 1 if report["status"] == "FAIL" else 2 

482 

483 

484def _phase_train_iters(phase: str, steps: int, split_step: int) -> int: 

485 """Map the launch phase to the number of executed training steps.""" 

486 if phase == "initialize": 

487 return _SHARED_INITIAL_CHECKPOINT_STEP 

488 if phase == "prepare": 

489 return split_step 

490 return steps 

491 

492 

493def _shared_checkpoint_overrides( 

494 manifest: ValidationManifest, 

495 phase: str, 

496) -> dict[str, Any]: 

497 """Replay every measured case from the same warm-start checkpoint.""" 

498 if not bool(manifest.matrix.get("shared_initial_checkpoint")): 

499 return {} 

500 if phase in ("initialize", "restore"): 

501 return {} 

502 initial_checkpoint_dir = ( 

503 manifest.output_dir / "cases" / "baseline" / "initial_checkpoint" 

504 ) 

505 # The warm-start step exists to align model/optimizer/RNG state. Every 

506 # measured case must replay from the same configured data start; a 

507 # stateful Online cursor may also be impossible to restore after TP/CP 

508 # changes the DP world size. True resume phases keep the default and 

509 # restore the cursor saved at resume_split_step. 

510 return { 

511 "checkpoint.restore_from": str( 

512 initial_checkpoint_dir 

513 / f"{STEP_PREFIX}{_SHARED_INITIAL_CHECKPOINT_STEP}" 

514 ), 

515 "checkpoint.restore_dataloader_state": False, 

516 } 

517 

518 

519def _phase_checkpoint_overrides( 

520 manifest: ValidationManifest, 

521 case: Any, 

522 phase: str, 

523 evidence_dir: Path, 

524 resume_dir: Path, 

525 split_step: int, 

526) -> dict[str, Any]: 

527 """Resolve checkpoint save/restore overrides for one launch phase.""" 

528 initial_checkpoint_dir = ( 

529 manifest.output_dir / "cases" / "baseline" / "initial_checkpoint" 

530 ) 

531 if phase == "initialize": 

532 return { 

533 "checkpoint.save_ckpt": True, 

534 "checkpoint.save_steps": 1, 

535 "checkpoint.save_epochs": 0, 

536 "checkpoint.checkpoint_dir": str(initial_checkpoint_dir), 

537 } 

538 if phase == "prepare": 

539 return { 

540 "checkpoint.save_ckpt": True, 

541 "checkpoint.save_steps": split_step, 

542 "checkpoint.save_epochs": 0, 

543 "checkpoint.checkpoint_dir": str(resume_dir), 

544 } 

545 if phase == "restore": 

546 return { 

547 "checkpoint.save_ckpt": False, 

548 "checkpoint.restore_from": str(resume_dir / f"{STEP_PREFIX}{split_step}"), 

549 "checkpoint.checkpoint_dir": str(resume_dir), 

550 } 

551 checkpoint_enabled = case.name == "baseline" and bool( 

552 manifest.matrix.get("same_topology_resume") 

553 or manifest.matrix.get("cross_topology_resume") 

554 ) 

555 overrides: dict[str, Any] = {"checkpoint.save_ckpt": checkpoint_enabled} 

556 if checkpoint_enabled: 

557 overrides.update( 

558 { 

559 "checkpoint.save_steps": split_step, 

560 "checkpoint.save_epochs": 0, 

561 "checkpoint.checkpoint_dir": str(evidence_dir / "dcp"), 

562 } 

563 ) 

564 return overrides 

565 

566 

567def _active_full_exclude_region( 

568 raw_exclude_region: Any, 

569 recompute_layers: list[int], 

570) -> dict[str, Any]: 

571 """Restrict recipe-owned exclusions to layers active in one matrix case.""" 

572 if not isinstance(raw_exclude_region, Mapping): 

573 raise ManifestError("activation_checkpoint.full.exclude_region must be a mapping") 

574 active_layers = set(recompute_layers) 

575 result: dict[str, Any] = {} 

576 for section in ("save", "swap"): 

577 raw_targets = raw_exclude_region.get(section) or {} 

578 if not isinstance(raw_targets, Mapping): 

579 raise ManifestError(f"activation_checkpoint.full.exclude_region.{section} must be a mapping") 

580 targets = {} 

581 for module_path, raw_layers in raw_targets.items(): 

582 if section == "swap" and module_path in ("group_swap", "cpu_pool"): 

583 continue 

584 try: 

585 normalized = FullCheckpointConfig(recompute_layer=raw_layers).recompute_layers 

586 except ValueError as error: 

587 raise ManifestError( 

588 f"invalid activation_checkpoint.full.exclude_region.{section}.{module_path}: {error}" 

589 ) from error 

590 selected = [layer for layer in normalized if layer in active_layers] 

591 if selected: 

592 targets[module_path] = selected 

593 if not targets: 

594 continue 

595 if section == "swap": 

596 targets = { 

597 key: raw_targets[key] 

598 for key in ("group_swap", "cpu_pool") 

599 if key in raw_targets 

600 } | targets 

601 result[section] = targets 

602 return result 

603 

604 

605def _trainer_launch_argv( 

606 manifest: ValidationManifest, 

607 case: Any, 

608 phase: str, 

609 evidence_dir: Path, 

610 resume_dir: Path, 

611 topology: Optional[Mapping[str, Any]] = None, 

612) -> list[str]: 

613 """Build the standard Trainer command from one concise launcher declaration.""" 

614 launcher = manifest.launcher 

615 module = launcher["module"] 

616 config = manifest.launcher_config_path 

617 if config is None: 

618 raise ManifestError("launcher.config is required for the standard Trainer launcher") 

619 topology = case.topology if topology is None else topology 

620 steps = int(manifest.matrix["steps"]) 

621 split_step = int(manifest.matrix.get("resume_split_step", steps)) 

622 tokens = [ 

623 "torchrun", 

624 "--standalone", 

625 f"--nproc_per_node={manifest.matrix['devices']}", 

626 "--module", 

627 module, 

628 str(config), 

629 ] 

630 activation_checkpoint = {"mode": "off"} 

631 if topology.get("recompute_layer"): 

632 full_config: dict[str, Any] = {"recompute_layer": topology["recompute_layer"]} 

633 recipe = yaml.safe_load(config.read_text(encoding="utf-8")) or {} 

634 recipe_activation = recipe.get("activation_checkpoint") or {} 

635 recipe_full = recipe_activation.get("full") or {} 

636 if "exclude_region" in recipe_full: 

637 exclude_region = _active_full_exclude_region( 

638 recipe_full["exclude_region"], 

639 topology["recompute_layer"], 

640 ) 

641 if exclude_region: 

642 full_config["exclude_region"] = exclude_region 

643 activation_checkpoint = {"mode": "full", "full": full_config} 

644 controlled_overrides = { 

645 "training.train_iters": _phase_train_iters(phase, steps, split_step), 

646 # Split-run preparation stops early but must retain the full-run LR 

647 # curve so its checkpoint is numerically comparable with the baseline. 

648 "training.lr_scheduler_iters": steps, 

649 "accelerator.tp_size": topology.get("tp", 1), 

650 "accelerator.cp_size": topology.get("cp", 1), 

651 "accelerator.ep_size": topology.get("ep", 1), 

652 "accelerator.sequence_parallel": topology.get("sequence_parallel", False), 

653 "fsdp_config.dp_shard_size": topology.get("fsdp", 1), 

654 "activation_checkpoint": activation_checkpoint, 

655 "model_integration.mode": "runtime", 

656 } 

657 if "validate_placement" in topology: 

658 controlled_overrides["model.validate_placement"] = topology["validate_placement"] 

659 controlled_overrides.update(_shared_checkpoint_overrides(manifest, phase)) 

660 controlled_overrides.update( 

661 _phase_checkpoint_overrides( 

662 manifest, 

663 case, 

664 phase, 

665 evidence_dir, 

666 resume_dir, 

667 split_step, 

668 ) 

669 ) 

670 tokens.extend( 

671 f"--{name}={value}" 

672 for name, value in controlled_overrides.items() 

673 ) 

674 return tokens 

675 

676 

677def _resolve_case_launches( 

678 manifest: ValidationManifest, 

679 case: Any, 

680 case_dir: Path, 

681) -> list[tuple[str, list[str], Path]]: 

682 """Resolve train or prepare/restore commands without executing them.""" 

683 resume_dir = case_dir / "resume_checkpoint" 

684 if case.kind != "resume": 

685 launches = [] 

686 if case.name == "baseline" and manifest.matrix.get("shared_initial_checkpoint"): 

687 initialize_dir = case_dir / "initialize" 

688 launches.append( 

689 ( 

690 "initialize", 

691 _trainer_launch_argv( 

692 manifest, 

693 case, 

694 "initialize", 

695 initialize_dir, 

696 resume_dir, 

697 ), 

698 initialize_dir, 

699 ) 

700 ) 

701 launches.append( 

702 ( 

703 "train", 

704 _trainer_launch_argv( 

705 manifest, case, "train", case_dir, resume_dir 

706 ), 

707 case_dir, 

708 ) 

709 ) 

710 return launches 

711 prepare_dir = case_dir / "prepare" 

712 prepare_topology = case.metadata.get("prepare_topology", case.topology) 

713 return [ 

714 ( 

715 "prepare", 

716 _trainer_launch_argv( 

717 manifest, 

718 case, 

719 "prepare", 

720 prepare_dir, 

721 resume_dir, 

722 topology=prepare_topology, 

723 ), 

724 prepare_dir, 

725 ), 

726 ( 

727 "restore", 

728 _trainer_launch_argv( 

729 manifest, case, "restore", case_dir, resume_dir 

730 ), 

731 case_dir, 

732 ), 

733 ] 

734 

735 

736def _case_environment( 

737 case: Any, 

738 phase: str, 

739 evidence_dir: Path, 

740 resume_dir: Path, 

741 *, 

742 port_slot: int = 0, 

743 port_stride: int = 1, 

744) -> dict[str, str]: 

745 """Add case identity and isolate sequential distributed launch ports.""" 

746 environment = os.environ.copy() 

747 environment.update( 

748 { 

749 "HP_MODEL_INTEGRATION_CASE": case.name, 

750 "HP_MODEL_INTEGRATION_KIND": case.kind, 

751 "HP_MODEL_INTEGRATION_PHASE": phase, 

752 "HP_MODEL_INTEGRATION_COMPARE_TO": case.compare_to, 

753 "HP_MODEL_INTEGRATION_EVIDENCE_DIR": str(evidence_dir), 

754 "HP_MODEL_INTEGRATION_RESUME_DIR": str(resume_dir), 

755 "HYPER_PARALLEL_MODEL_INTEGRATION_OUTPUT_DIR": str(evidence_dir), 

756 } 

757 ) 

758 hccl_base_port = environment.get("HCCL_IF_BASE_PORT") 

759 if hccl_base_port is not None: 

760 try: 

761 isolated_port = int(hccl_base_port) + port_slot * port_stride 

762 except ValueError as error: 

763 raise ManifestError( 

764 "HCCL_IF_BASE_PORT must be an integer when model-integration " 

765 f"validation isolates case ports, got {hccl_base_port!r}" 

766 ) from error 

767 if not 0 < isolated_port <= 65535: 

768 raise ManifestError( 

769 "model-integration HCCL port isolation exceeds the valid port " 

770 f"range: base={hccl_base_port}, slot={port_slot}, " 

771 f"stride={port_stride}" 

772 ) 

773 environment["HCCL_IF_BASE_PORT"] = str(isolated_port) 

774 return environment 

775 

776 

777def _execute_case_launch( 

778 manifest: ValidationManifest, 

779 case: Any, 

780 launch: Mapping[str, Any], 

781 resume_dir: Path, 

782) -> tuple[Optional[int], Optional[str]]: 

783 """Execute one resolved process and persist its stdout and stderr.""" 

784 phase = launch["phase"] 

785 evidence_dir = Path(launch["evidence_dir"]) 

786 evidence_dir.mkdir(parents=True, exist_ok=True) 

787 try: 

788 result = subprocess.run( 

789 launch["argv"], 

790 check=False, 

791 capture_output=True, 

792 text=True, 

793 env=_case_environment( 

794 case, 

795 phase, 

796 evidence_dir, 

797 resume_dir, 

798 port_slot=int(launch.get("port_slot", 0)), 

799 port_stride=max( 

800 _HCCL_PORT_STRIDE, 

801 int(manifest.matrix.get("devices", 1)), 

802 ), 

803 ), 

804 cwd=_REPOSITORY_ROOT, 

805 timeout=manifest.launcher.get("timeout_seconds"), 

806 ) 

807 except OSError as error: 

808 return None, f"{phase} launcher could not start: {error}" 

809 except subprocess.TimeoutExpired as error: 

810 evidence_dir.joinpath("stdout.log").write_text(error.stdout or "", encoding="utf-8") 

811 evidence_dir.joinpath("stderr.log").write_text(error.stderr or "", encoding="utf-8") 

812 timeout = manifest.launcher.get("timeout_seconds") 

813 return None, f"{phase} launcher exceeded timeout_seconds={timeout}" 

814 evidence_dir.joinpath("stdout.log").write_text(result.stdout, encoding="utf-8") 

815 evidence_dir.joinpath("stderr.log").write_text(result.stderr, encoding="utf-8") 

816 return result.returncode, None 

817 

818 

819def _run_validation_case( 

820 manifest: ValidationManifest, 

821 store: EvidenceStore, 

822 case: Any, 

823 case_index: int, 

824) -> dict[str, Any]: 

825 """Run one resolved validation case and return its report payload.""" 

826 case_dir = store.path(f"cases/{case.name}") 

827 case_dir.mkdir(parents=True, exist_ok=True) 

828 resume_dir = case_dir / "resume_checkpoint" 

829 launches = _resolve_case_launches(manifest, case, case_dir) 

830 commands = [ 

831 { 

832 "phase": phase, 

833 "argv": phase_argv, 

834 "evidence_dir": str(phase_evidence_dir), 

835 "port_slot": case_index * 2 + launch_index, 

836 } 

837 for launch_index, (phase, phase_argv, phase_evidence_dir) in enumerate(launches) 

838 ] 

839 store.write_json( 

840 f"cases/{case.name}/preflight.json", 

841 {"case": case.to_dict(), "launches": commands}, 

842 ) 

843 returncodes = [] 

844 for launch in commands: 

845 returncode, blocked_reason = _execute_case_launch( 

846 manifest, 

847 case, 

848 launch, 

849 resume_dir, 

850 ) 

851 if blocked_reason is not None: 

852 return {"case": case.name, "status": "BLOCKED", "reason": blocked_reason} 

853 returncodes.append(returncode) 

854 if returncode: 

855 break 

856 return { 

857 "case": case.name, 

858 "status": "PASS" if not any(returncodes) else "FAIL", 

859 "returncodes": returncodes, 

860 "metrics": f"cases/{case.name}/metrics.jsonl", 

861 } 

862 

863 

864def _case_artifact(case_dir: Path, relative_path: str) -> Path: 

865 """Resolve a launcher-owned artifact or the standard Trainer model integration location.""" 

866 direct = case_dir / relative_path 

867 if direct.exists(): 

868 return direct 

869 runtime = case_dir / "cases" / "runtime" / relative_path 

870 return runtime 

871 

872 

873def _performance_summary(case_dir: Path, warmup_steps: int) -> dict[str, Any]: 

874 """Summarize rank-zero timing and maximum allocator usage over all ranks.""" 

875 runtime_dir = case_dir / "cases" / "runtime" 

876 rank_files = tuple(sorted(runtime_dir.glob("performance_rank*.jsonl"))) 

877 memory_rows = [row for path in rank_files for row in load_jsonl(path)] 

878 return summarize_performance( 

879 load_jsonl(_case_artifact(case_dir, "performance.jsonl")), 

880 warmup_steps=warmup_steps, 

881 memory_rows=memory_rows, 

882 ) 

883 

884 

885def _aggregate_statuses(statuses: Iterable[str]) -> str: 

886 """Reduce phase statuses using FAIL > BLOCKED > PASS precedence.""" 

887 statuses = tuple(statuses) 

888 if "FAIL" in statuses: 

889 return "FAIL" 

890 if "BLOCKED" in statuses: 

891 return "BLOCKED" 

892 return "PASS" 

893 

894 

895def _compare_validation_case( 

896 manifest: ValidationManifest, 

897 case: Any, 

898 baseline_dir: Path, 

899 candidate_dir: Path, 

900 launch_statuses: tuple[str, str], 

901) -> dict[str, Any]: 

902 """Compare one candidate against the baseline using declared contracts.""" 

903 try: 

904 tolerance_name = case.metadata["acceptance"] 

905 except (AttributeError, KeyError) as error: 

906 raise ManifestError( 

907 f"validation case {case.name!r} has no acceptance classification; " 

908 "regenerate the case matrix with generate_validation_cases()" 

909 ) from error 

910 preflight = compare_preflight_configs( 

911 baseline_dir, 

912 candidate_dir, 

913 ) 

914 scalar = compare_scalar_curves( 

915 load_jsonl(_case_artifact(baseline_dir, "metrics.jsonl")), 

916 load_jsonl(_case_artifact(candidate_dir, "metrics.jsonl")), 

917 manifest.acceptance.get(tolerance_name, {}), 

918 allow_candidate_subset=case.kind == "resume", 

919 ) 

920 parameter = compare_parameter_probes( 

921 baseline_dir, 

922 candidate_dir, 

923 _parameter_tolerance(manifest.acceptance, tolerance_name), 

924 allow_candidate_subset=case.kind == "resume", 

925 compare_optimizer_states=tolerance_name == "same_topology", 

926 ) 

927 checkpoint_layout = None 

928 statuses = (*launch_statuses, preflight["status"], scalar["status"], parameter["status"]) 

929 if case.kind == "resume": 

930 checkpoint_layout = compare_checkpoint_layouts( 

931 baseline_dir, 

932 candidate_dir, 

933 same_topology=case.metadata.get("resume") == "same_topology", 

934 ) 

935 statuses = (*statuses, checkpoint_layout["status"]) 

936 return { 

937 "status": _aggregate_statuses(statuses), 

938 "preflight": preflight, 

939 "scalar": scalar, 

940 "parameter_probes": parameter, 

941 "checkpoint_layout": checkpoint_layout, 

942 } 

943 

944 

945def _finalize_validation( 

946 store: EvidenceStore, 

947 results: list[dict[str, Any]], 

948 comparisons: Mapping[str, Mapping[str, Any]], 

949 performance: Mapping[str, Mapping[str, Any]], 

950) -> int: 

951 """Persist the matrix result and advance the evidence state machine.""" 

952 status = _aggregate_statuses( 

953 [result["status"] for result in results] 

954 + [comparison["status"] for comparison in comparisons.values()] 

955 ) 

956 store.write_json( 

957 "comparison.json", 

958 { 

959 "status": status, 

960 "cases": results, 

961 "comparisons": comparisons, 

962 "performance": performance, 

963 }, 

964 ) 

965 if status == "PASS": 

966 store.advance_if_before(IntegrationState.MATRIX_PASSED, ("comparison.json",)) 

967 return 0 

968 terminal = IntegrationState.FAILED if status == "FAIL" else IntegrationState.BLOCKED 

969 store.update_state(terminal, ("comparison.json",), reason=status) 

970 return 1 if status == "FAIL" else 2 

971 

972 

973def command_validate(args: argparse.Namespace) -> int: 

974 """Generate and optionally execute the minimum precision matrix.""" 

975 manifest = _manifest_from_args(args) 

976 store = _store(manifest) 

977 _require_precision_handoff(store, manifest) 

978 validation_spec = _validation_spec(manifest) 

979 try: 

980 cases = generate_validation_cases( 

981 manifest.matrix, 

982 validation_spec.topology_constraints, 

983 ) 

984 except (TypeError, ValueError) as error: 

985 raise ManifestError(f"invalid validation matrix: {error}") from error 

986 store.write_json("cases/resolved_cases.json", [case.to_dict() for case in cases]) 

987 if args.generate_only: 

988 print(store.path("cases/resolved_cases.json")) 

989 return 0 

990 results = [ 

991 _run_validation_case(manifest, store, case, case_index) 

992 for case_index, case in enumerate(cases) 

993 ] 

994 results_by_name = {result["case"]: result for result in results} 

995 baseline_dir = store.path("cases/baseline") 

996 warmup_steps = int(manifest.matrix.get("performance_warmup_steps", 1)) 

997 comparisons = {} 

998 performance = {"baseline": _performance_summary(baseline_dir, warmup_steps)} 

999 for case in cases: 

1000 if case.name == "baseline": 

1001 continue 

1002 candidate_dir = store.path(f"cases/{case.name}") 

1003 launch_statuses = ( 

1004 results_by_name["baseline"]["status"], 

1005 results_by_name[case.name]["status"], 

1006 ) 

1007 comparisons[case.name] = _compare_validation_case( 

1008 manifest, 

1009 case, 

1010 baseline_dir, 

1011 candidate_dir, 

1012 launch_statuses, 

1013 ) 

1014 performance[case.name] = _performance_summary(candidate_dir, warmup_steps) 

1015 return _finalize_validation(store, results, comparisons, performance) 

1016 

1017 

1018def _read_json(path: Path) -> Optional[dict[str, Any]]: 

1019 """Read an optional JSON evidence file.""" 

1020 if not path.exists(): 

1021 return None 

1022 return json.loads(path.read_text(encoding="utf-8")) 

1023 

1024 

1025def _report_entries( 

1026 findings: Optional[Mapping[str, Any]], 

1027 parity: Optional[Mapping[str, Any]], 

1028 comparison: Optional[Mapping[str, Any]], 

1029) -> tuple[list[str], list[str], list[str], list[str]]: 

1030 """Render compact structure, parity, precision, and performance entries.""" 

1031 structure_entries = ["not executed"] 

1032 if findings is not None: 

1033 structure_entries = [ 

1034 f"{finding['severity']}: {finding['message']} " 

1035 f"(fix: {finding.get('remediation') or 'n/a'})" 

1036 for finding in findings.get("findings", ()) 

1037 ] or ["PASS: no ERROR findings"] 

1038 parity_entries = ["not executed"] 

1039 if parity is not None: 

1040 parity_entries = [ 

1041 f"{case.get('case', '<unnamed>')}: {case.get('status')}" 

1042 + (f" ({case.get('reason')})" if case.get("reason") else "") 

1043 for case in parity.get("cases", ()) 

1044 ] or [f"{parity.get('status')}: no executed cases"] 

1045 precision_entries = ["not executed"] 

1046 performance_entries = ["not executed"] 

1047 if comparison is not None: 

1048 precision_entries = [ 

1049 f"{name}: {value.get('status')}" 

1050 for name, value in comparison.get("comparisons", {}).items() 

1051 ] or [f"{comparison.get('status')}: baseline only"] 

1052 performance_entries = [ 

1053 f"{name}: step_p50={value.get('step_time_p50_seconds')}, " 

1054 f"tokens/s={value.get('tokens_per_second_p50')}, " 

1055 f"peak_allocated={value.get('peak_memory_allocated_bytes')} bytes" 

1056 for name, value in comparison.get("performance", {}).items() 

1057 ] or ["not measured"] 

1058 return structure_entries, parity_entries, precision_entries, performance_entries 

1059 

1060 

1061def _resolved_report_cases(store: EvidenceStore) -> list[dict[str, Any]]: 

1062 """Load resolved matrix cases for report rendering.""" 

1063 cases_path = store.path("cases/resolved_cases.json") 

1064 if not cases_path.is_file(): 

1065 return [] 

1066 payload = json.loads(cases_path.read_text(encoding="utf-8")) 

1067 return payload if isinstance(payload, list) else [] 

1068 

1069 

1070def _report_manifest(store: EvidenceStore) -> dict[str, Any]: 

1071 """Load the resolved manifest without requiring the original input path.""" 

1072 manifest_path = store.path("manifest.resolved.yaml") 

1073 if not manifest_path.is_file(): 

1074 return {} 

1075 payload = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) or {} 

1076 return payload if isinstance(payload, dict) else {} 

1077 

1078 

1079def _case_category(case: Mapping[str, Any]) -> str: 

1080 """Classify one case without inflating strategy coverage with mechanics.""" 

1081 name = str(case.get("name", "")) 

1082 if name == "baseline": 

1083 return "baseline" 

1084 if name.startswith(("axis-", "combined-")): 

1085 return "strategy" 

1086 if name.startswith("recompute_"): 

1087 return "recompute" 

1088 if case.get("kind") == "resume": 

1089 return "resume" 

1090 if case.get("kind") == "production_validate": 

1091 return "production_validate" 

1092 return "other" 

1093 

1094 

1095def _coverage_counts(resolved_cases: Iterable[Mapping[str, Any]]) -> dict[str, int]: 

1096 """Count independent evidence categories.""" 

1097 counts = { 

1098 "baseline": 0, 

1099 "strategy": 0, 

1100 "recompute": 0, 

1101 "resume": 0, 

1102 "production_validate": 0, 

1103 "other": 0, 

1104 } 

1105 for case in resolved_cases: 

1106 counts[_case_category(case)] += 1 

1107 return counts 

1108 

1109 

1110def _coverage_notes(manifest: Mapping[str, Any], language: str) -> list[str]: 

1111 """Return localized exclusions, falling back to the canonical notes.""" 

1112 matrix = manifest.get("matrix", {}) 

1113 if not isinstance(matrix, Mapping): 

1114 return [] 

1115 key = "coverage_notes_zh" if language == "zh" else "coverage_notes" 

1116 notes = matrix.get(key, matrix.get("coverage_notes", ())) 

1117 if not isinstance(notes, (list, tuple)): 

1118 return [] 

1119 return [note for note in notes if isinstance(note, str)] 

1120 

1121 

1122def _precision_coverage_entries(store: EvidenceStore, language: str = "en") -> list[str]: 

1123 """Summarize real matrix coverage separately from resume mechanics.""" 

1124 resolved_cases = _resolved_report_cases(store) 

1125 counts = _coverage_counts(resolved_cases) 

1126 if language == "zh": 

1127 entries = [ 

1128 f"基线={counts['baseline']},策略泛化={counts['strategy']}," 

1129 f"重计算={counts['recompute']},断点续训={counts['resume']}," 

1130 f"生产/Validate 对照={counts['production_validate']}" 

1131 ] 

1132 else: 

1133 entries = [ 

1134 f"baseline={counts['baseline']}, strategy_generalization={counts['strategy']}, " 

1135 f"recompute={counts['recompute']}, resume={counts['resume']}, " 

1136 f"production_validate={counts['production_validate']}" 

1137 ] 

1138 

1139 manifest = _report_manifest(store) 

1140 exclusion_prefix = "排除项" if language == "zh" else "excluded" 

1141 entries.extend( 

1142 f"{exclusion_prefix}: {note}" 

1143 for note in _coverage_notes(manifest, language) 

1144 ) 

1145 return entries 

1146 

1147 

1148def _format_report_number(value: Any) -> str: 

1149 """Format optional numerical evidence compactly and deterministically.""" 

1150 if value is None: 

1151 return "n/a" 

1152 if isinstance(value, float): 

1153 return f"{value:.6g}" 

1154 return str(value) 

1155 

1156 

1157def _format_topology(topology: Mapping[str, Any]) -> str: 

1158 """Render the stable topology dimensions in one line.""" 

1159 keys = ("tp", "cp", "ep", "fsdp", "sequence_parallel", "recompute") 

1160 return ", ".join(f"{key}={topology.get(key)}" for key in keys) 

1161 

1162 

1163def _scalar_case_summary(comparison: Mapping[str, Any]) -> dict[str, Any]: 

1164 """Collapse per-step scalar evidence while preserving identity gates.""" 

1165 steps = comparison.get("scalar", {}).get("steps", ()) 

1166 

1167 def maximum(name: str) -> Optional[float]: 

1168 """Return the largest observed value without converting absent evidence.""" 

1169 values = [float(row[name]) for row in steps if row.get(name) is not None] 

1170 return max(values, default=None) 

1171 

1172 return { 

1173 "steps": len(steps), 

1174 "max_loss": maximum("loss_max_abs"), 

1175 "max_loss_rel": maximum("loss_max_rel"), 

1176 "max_norm": maximum("norm_max_abs"), 

1177 "max_norm_rel": maximum("norm_max_rel"), 

1178 "max_post_clip_norm": maximum("post_clip_norm_max_abs"), 

1179 "max_post_clip_norm_rel": maximum("post_clip_norm_max_rel"), 

1180 "input_identity": all(bool(row.get("input_identity")) for row in steps) if steps else False, 

1181 "learning_rate_identity": ( 

1182 all(bool(row.get("learning_rate_equal")) for row in steps) if steps else False 

1183 ), 

1184 "finite": all(bool(row.get("finite")) for row in steps) if steps else False, 

1185 } 

1186 

1187 

1188def _parameter_acceptance_entry( 

1189 tolerance: Mapping[str, Any], 

1190 label: str, 

1191 language: str, 

1192) -> str: 

1193 """Render exact-value and summary-only parameter limits without conflating them.""" 

1194 summary = tolerance.get("summary", {}) 

1195 if not isinstance(summary, Mapping): 

1196 summary = {} 

1197 if language == "zh": 

1198 return ( 

1199 f"{label}:完整值 max_abs <= {_format_report_number(tolerance.get('max_abs'))}," 

1200 f"relative_l2 <= {_format_report_number(tolerance.get('relative_l2'))}," 

1201 f"组合规则={tolerance.get('combination', 'all')};仅摘要不声明逐元素误差," 

1202 "L2 范数相对误差 <= " 

1203 f"{_format_report_number(summary.get('l2_norm_relative'))}" 

1204 ) 

1205 return ( 

1206 f"{label}: exact-value max_abs <= {_format_report_number(tolerance.get('max_abs'))}, " 

1207 f"relative_l2 <= {_format_report_number(tolerance.get('relative_l2'))}, " 

1208 f"combination={tolerance.get('combination', 'all')}; summary-only probes make no " 

1209 "elementwise claim, L2-norm relative error <= " 

1210 f"{_format_report_number(summary.get('l2_norm_relative'))}" 

1211 ) 

1212 

1213 

1214def _acceptance_entries(manifest: Mapping[str, Any], language: str) -> list[str]: 

1215 """Render every scalar and parameter threshold used by the matrix.""" 

1216 acceptance = manifest.get("acceptance", {}) 

1217 if not isinstance(acceptance, Mapping): 

1218 acceptance = {} 

1219 same = acceptance.get("same_topology", {}) 

1220 cross = acceptance.get("cross_topology", {}) 

1221 parity_parameters = _parameter_tolerance(acceptance, "module_parity") 

1222 same_parameters = _parameter_tolerance(acceptance, "same_topology") 

1223 cross_parameters = _parameter_tolerance(acceptance, "cross_topology") 

1224 if language == "zh": 

1225 return [ 

1226 "同拓扑:" 

1227 f"loss 最大绝对误差 <= {_format_report_number(same.get('loss_max_abs'))}," 

1228 f"loss 最大相对误差 <= {_format_report_number(same.get('loss_max_rel'))}," 

1229 f"梯度范数最大绝对误差 <= {_format_report_number(same.get('norm_max_abs'))}," 

1230 f"梯度范数最大相对误差 <= {_format_report_number(same.get('norm_max_rel'))}," 

1231 f"组合规则={same.get('combination', 'all')}", 

1232 "跨拓扑:" 

1233 f"loss 最大绝对误差 <= {_format_report_number(cross.get('loss_max_abs'))}," 

1234 f"loss 最大相对误差 <= {_format_report_number(cross.get('loss_max_rel'))}," 

1235 f"梯度范数最大绝对误差 <= {_format_report_number(cross.get('norm_max_abs'))}," 

1236 f"梯度范数最大相对误差 <= {_format_report_number(cross.get('norm_max_rel'))}," 

1237 f"组合规则={cross.get('combination', 'all')}", 

1238 _parameter_acceptance_entry(parity_parameters, "模块对拍参数", "zh"), 

1239 _parameter_acceptance_entry(same_parameters, "同拓扑参数", "zh"), 

1240 _parameter_acceptance_entry(cross_parameters, "跨拓扑参数", "zh"), 

1241 ] 

1242 return [ 

1243 "same topology: " 

1244 f"loss max abs <= {_format_report_number(same.get('loss_max_abs'))}, " 

1245 f"loss max rel <= {_format_report_number(same.get('loss_max_rel'))}, " 

1246 f"gradient-norm max abs <= {_format_report_number(same.get('norm_max_abs'))}, " 

1247 f"gradient-norm max rel <= {_format_report_number(same.get('norm_max_rel'))}, " 

1248 f"combination={same.get('combination', 'all')}", 

1249 "cross topology: " 

1250 f"loss max abs <= {_format_report_number(cross.get('loss_max_abs'))}, " 

1251 f"loss max rel <= {_format_report_number(cross.get('loss_max_rel'))}, " 

1252 f"gradient-norm max abs <= {_format_report_number(cross.get('norm_max_abs'))}, " 

1253 f"gradient-norm max rel <= {_format_report_number(cross.get('norm_max_rel'))}, " 

1254 f"combination={cross.get('combination', 'all')}", 

1255 _parameter_acceptance_entry(parity_parameters, "module parity parameters", "en"), 

1256 _parameter_acceptance_entry(same_parameters, "same-topology parameters", "en"), 

1257 _parameter_acceptance_entry(cross_parameters, "cross-topology parameters", "en"), 

1258 ] 

1259 

1260 

1261def _baseline_detail_entry( 

1262 category: str, 

1263 name: str, 

1264 topology: str, 

1265 default_steps: Any, 

1266 language: str, 

1267) -> str: 

1268 """Render the reference-curve entry for the baseline case.""" 

1269 if language == "zh": 

1270 return ( 

1271 f"[{category}] `{name}`:{topology};正式步数={default_steps};作为参考曲线。" 

1272 ) 

1273 return ( 

1274 f"[{category}] `{name}`: {topology}; measured_steps={default_steps}; reference curve." 

1275 ) 

1276 

1277 

1278def _checkpoint_layout_status( 

1279 case: Mapping[str, Any], 

1280 case_comparison: Mapping[str, Any], 

1281 language: str, 

1282) -> str: 

1283 """Render the DCP layout verdict or explain why none was recorded.""" 

1284 checkpoint = case_comparison.get("checkpoint_layout") 

1285 if isinstance(checkpoint, Mapping): 

1286 return checkpoint.get("status", "n/a") 

1287 if case.get("kind") != "resume": 

1288 return ( 

1289 "not applicable (non-resume case)" 

1290 if language == "en" 

1291 else "不适用(非断点续训用例)" 

1292 ) 

1293 return "not recorded" if language == "en" else "未记录" 

1294 

1295 

1296def _case_detail_entry( 

1297 case: Mapping[str, Any], 

1298 name: str, 

1299 category: str, 

1300 topology: str, 

1301 comparisons: Mapping[str, Any], 

1302 acceptance: Any, 

1303 language: str, 

1304) -> str: 

1305 """Render thresholds, scalar gates, probes, and DCP for one case.""" 

1306 case_comparison = comparisons.get(name, {}) 

1307 scalar = _scalar_case_summary(case_comparison) 

1308 metadata = case.get("metadata", {}) 

1309 profile = metadata.get("acceptance", "unknown") 

1310 threshold = acceptance.get(profile, {}) if isinstance(acceptance, Mapping) else {} 

1311 parameter = case_comparison.get("parameter_probes", {}) 

1312 checkpoint_status = _checkpoint_layout_status(case, case_comparison, language) 

1313 identity_status = "PASS" if scalar["input_identity"] else "FAIL" 

1314 lr_status = "PASS" if scalar["learning_rate_identity"] else "FAIL" 

1315 finite_status = "PASS" if scalar["finite"] else "FAIL" 

1316 if language == "zh": 

1317 return ( 

1318 f"[{category}] `{name}`:{topology};阈值档={profile} " 

1319 f"(loss<={_format_report_number(threshold.get('loss_max_abs'))}, " 

1320 f"loss_rel<={_format_report_number(threshold.get('loss_max_rel'))}, " 

1321 f"norm<={_format_report_number(threshold.get('norm_max_abs'))}, " 

1322 f"norm_rel<={_format_report_number(threshold.get('norm_max_rel'))}, " 

1323 f"组合={threshold.get('combination', 'all')});" 

1324 f"对比步数={scalar['steps']};max_loss_abs={_format_report_number(scalar['max_loss'])};" 

1325 f"max_loss_rel={_format_report_number(scalar['max_loss_rel'])};" 

1326 f"max_norm_abs={_format_report_number(scalar['max_norm'])};" 

1327 f"max_norm_rel={_format_report_number(scalar['max_norm_rel'])};" 

1328 f"max_post_clip_norm_abs={_format_report_number(scalar['max_post_clip_norm'])};" 

1329 f"max_post_clip_norm_rel={_format_report_number(scalar['max_post_clip_norm_rel'])};" 

1330 f"输入身份={identity_status};LR 身份={lr_status};有限性={finite_status};" 

1331 f"参数探针={parameter.get('status', 'n/a')} " 

1332 f"(optimizer 数值={parameter.get('optimizer_state_numeric_comparison', 'n/a')}, " 

1333 f"跳过状态数={parameter.get('skipped_optimizer_states', 0)});" 

1334 f"checkpoint layout={checkpoint_status};总状态={case_comparison.get('status', 'n/a')}。" 

1335 ) 

1336 return ( 

1337 f"[{category}] `{name}`: {topology}; tolerance_profile={profile} " 

1338 f"(loss<={_format_report_number(threshold.get('loss_max_abs'))}, " 

1339 f"loss_rel<={_format_report_number(threshold.get('loss_max_rel'))}, " 

1340 f"norm<={_format_report_number(threshold.get('norm_max_abs'))}, " 

1341 f"norm_rel<={_format_report_number(threshold.get('norm_max_rel'))}, " 

1342 f"combination={threshold.get('combination', 'all')}); " 

1343 f"compared_steps={scalar['steps']}; max_loss_abs={_format_report_number(scalar['max_loss'])}; " 

1344 f"max_loss_rel={_format_report_number(scalar['max_loss_rel'])}; " 

1345 f"max_norm_abs={_format_report_number(scalar['max_norm'])}; " 

1346 f"max_norm_rel={_format_report_number(scalar['max_norm_rel'])}; " 

1347 f"max_post_clip_norm_abs={_format_report_number(scalar['max_post_clip_norm'])}; " 

1348 f"max_post_clip_norm_rel={_format_report_number(scalar['max_post_clip_norm_rel'])}; " 

1349 f"input_identity={identity_status}; LR_identity={lr_status}; finite={finite_status}; " 

1350 f"parameter_probes={parameter.get('status', 'n/a')} " 

1351 f"(optimizer_numeric={parameter.get('optimizer_state_numeric_comparison', 'n/a')}, " 

1352 f"skipped_states={parameter.get('skipped_optimizer_states', 0)}); " 

1353 f"checkpoint_layout={checkpoint_status}; overall={case_comparison.get('status', 'n/a')}." 

1354 ) 

1355 

1356 

1357def _precision_detail_entries( 

1358 resolved_cases: Iterable[Mapping[str, Any]], 

1359 comparison: Optional[Mapping[str, Any]], 

1360 manifest: Mapping[str, Any], 

1361 language: str, 

1362) -> list[str]: 

1363 """Render topology, thresholds, scalar gates, probes, and DCP per case.""" 

1364 comparisons = {} if comparison is None else comparison.get("comparisons", {}) 

1365 acceptance = manifest.get("acceptance", {}) 

1366 matrix = manifest.get("matrix", {}) 

1367 default_steps = matrix.get("steps", "n/a") if isinstance(matrix, Mapping) else "n/a" 

1368 entries = [] 

1369 category_names = { 

1370 "en": { 

1371 "baseline": "baseline", 

1372 "strategy": "strategy generalization", 

1373 "recompute": "recompute", 

1374 "resume": "resume", 

1375 "production_validate": "Production/Validate", 

1376 "other": "other", 

1377 }, 

1378 "zh": { 

1379 "baseline": "基线", 

1380 "strategy": "策略泛化", 

1381 "recompute": "重计算", 

1382 "resume": "断点续训", 

1383 "production_validate": "生产/Validate 对照", 

1384 "other": "其他", 

1385 }, 

1386 } 

1387 for case in resolved_cases: 

1388 name = str(case.get("name", "<unnamed>")) 

1389 category = category_names[language][_case_category(case)] 

1390 topology = _format_topology(case.get("topology", {})) 

1391 if name == "baseline": 

1392 entries.append( 

1393 _baseline_detail_entry(category, name, topology, default_steps, language) 

1394 ) 

1395 continue 

1396 entries.append( 

1397 _case_detail_entry( 

1398 case, 

1399 name, 

1400 category, 

1401 topology, 

1402 comparisons, 

1403 acceptance, 

1404 language, 

1405 ) 

1406 ) 

1407 return entries or (["未执行"] if language == "zh" else ["not executed"]) 

1408 

1409 

1410def _worst_case_entries( 

1411 comparison: Optional[Mapping[str, Any]], 

1412 language: str, 

1413) -> list[str]: 

1414 """Identify the worst observed scalar deltas with case and step.""" 

1415 worst_loss = (-1.0, "n/a", "n/a") 

1416 worst_norm = (-1.0, "n/a", "n/a") 

1417 for name, case in ({} if comparison is None else comparison.get("comparisons", {})).items(): 

1418 for row in case.get("scalar", {}).get("steps", ()): 

1419 loss = float(row.get("loss_max_abs", 0.0)) 

1420 norm = float(row.get("norm_max_abs", 0.0)) 

1421 if loss > worst_loss[0]: 

1422 worst_loss = (loss, name, row.get("step")) 

1423 if norm > worst_norm[0]: 

1424 worst_norm = (norm, name, row.get("step")) 

1425 if worst_loss[0] < 0: 

1426 return ["未测量"] if language == "zh" else ["not measured"] 

1427 if language == "zh": 

1428 return [ 

1429 f"全矩阵最大 loss 绝对误差={_format_report_number(worst_loss[0])}," 

1430 f"用例=`{worst_loss[1]}`,step={worst_loss[2]}", 

1431 f"全矩阵最大梯度范数绝对误差={_format_report_number(worst_norm[0])}," 

1432 f"用例=`{worst_norm[1]}`,step={worst_norm[2]}", 

1433 ] 

1434 return [ 

1435 f"matrix maximum loss absolute error={_format_report_number(worst_loss[0])}, " 

1436 f"case=`{worst_loss[1]}`, step={worst_loss[2]}", 

1437 f"matrix maximum gradient-norm absolute error={_format_report_number(worst_norm[0])}, " 

1438 f"case=`{worst_norm[1]}`, step={worst_norm[2]}", 

1439 ] 

1440 

1441 

1442def _detailed_parity_entries( 

1443 parity: Optional[Mapping[str, Any]], 

1444 language: str, 

1445) -> list[str]: 

1446 """Render each native module parity observation and compatibility note.""" 

1447 if parity is None: 

1448 return ["未执行"] if language == "zh" else ["not executed"] 

1449 entries = [] 

1450 for case in parity.get("cases", ()): 

1451 case_name = case.get("case", "<unnamed>") 

1452 entries.append( 

1453 f"`{case_name}`:{case.get('status')}。" if language == "zh" 

1454 else f"`{case_name}`: {case.get('status')}." 

1455 ) 

1456 metric_rows = case.get("metrics", ()) 

1457 for metric in metric_rows: 

1458 maximum = metric.get("max_abs") 

1459 relative_l2 = metric.get("relative_l2") 

1460 if language == "zh": 

1461 entries.append( 

1462 f"模块 `{metric.get('name', '<unnamed>')}`:{metric.get('status')};" 

1463 f"最大绝对误差={_format_report_number(maximum)};" 

1464 f"相对 L2 误差={_format_report_number(relative_l2)}。" 

1465 ) 

1466 else: 

1467 entries.append( 

1468 f"module `{metric.get('name', '<unnamed>')}`: {metric.get('status')}; " 

1469 f"maximum absolute error={_format_report_number(maximum)}; " 

1470 f"relative L2 error={_format_report_number(relative_l2)}." 

1471 ) 

1472 for observation in case.get("observations", ()): 

1473 metrics = observation.get("metrics") 

1474 errors = observation.get("max_abs_errors", {}) 

1475 maximum = ( 

1476 metrics.get("max_abs") 

1477 if isinstance(metrics, Mapping) 

1478 else max((float(value) for value in errors.values()), default=None) 

1479 ) 

1480 relative_l2 = metrics.get("relative_l2") if isinstance(metrics, Mapping) else None 

1481 if language == "zh": 

1482 detail = ( 

1483 f"最大绝对误差={_format_report_number(maximum)};" 

1484 f"相对 L2 误差={_format_report_number(relative_l2)}" 

1485 if maximum is not None 

1486 else f"精确一致性={observation.get('status')}" 

1487 ) 

1488 entries.append( 

1489 f"模块 `{observation.get('name', '<unnamed>')}`:{observation.get('status')};" 

1490 f"{detail}。" 

1491 ) 

1492 else: 

1493 detail = ( 

1494 f"maximum absolute error={_format_report_number(maximum)}; " 

1495 f"relative L2 error={_format_report_number(relative_l2)}" 

1496 if maximum is not None 

1497 else f"exact equality={observation.get('status')}" 

1498 ) 

1499 entries.append( 

1500 f"module `{observation.get('name', '<unnamed>')}`: {observation.get('status')}; " 

1501 f"{detail}." 

1502 ) 

1503 for note in case.get("compatibility", ()): 

1504 prefix = "兼容性说明(原文)" if language == "zh" else "compatibility note" 

1505 entries.append(f"{prefix}: {note}") 

1506 return entries or (["无已执行用例"] if language == "zh" else ["no executed cases"]) 

1507 

1508 

1509def _detailed_performance_entries( 

1510 comparison: Optional[Mapping[str, Any]], 

1511 language: str, 

1512) -> list[str]: 

1513 """Render warm performance and memory without making them precision gates.""" 

1514 performance = {} if comparison is None else comparison.get("performance", {}) 

1515 entries = [] 

1516 for name, value in performance.items(): 

1517 allocated = value.get("peak_memory_allocated_bytes") 

1518 reserved = value.get("peak_memory_reserved_bytes") 

1519 allocated_mib = None if allocated is None else float(allocated) / (1024 ** 2) 

1520 reserved_mib = None if reserved is None else float(reserved) / (1024 ** 2) 

1521 if language == "zh": 

1522 entries.append( 

1523 f"`{name}`:稳态步数={value.get('steady_steps', 'n/a')};" 

1524 f"step p50={_format_report_number(value.get('step_time_p50_seconds'))}s;" 

1525 f"p90={_format_report_number(value.get('step_time_p90_seconds'))}s;" 

1526 f"tokens/s p50={_format_report_number(value.get('tokens_per_second_p50'))};" 

1527 f"samples/s p50={_format_report_number(value.get('samples_per_second_p50'))};" 

1528 f"峰值 allocated={_format_report_number(allocated_mib)} MiB;" 

1529 f"reserved={_format_report_number(reserved_mib)} MiB。" 

1530 ) 

1531 else: 

1532 entries.append( 

1533 f"`{name}`: steady_steps={value.get('steady_steps', 'n/a')}; " 

1534 f"step p50={_format_report_number(value.get('step_time_p50_seconds'))}s; " 

1535 f"p90={_format_report_number(value.get('step_time_p90_seconds'))}s; " 

1536 f"tokens/s p50={_format_report_number(value.get('tokens_per_second_p50'))}; " 

1537 f"samples/s p50={_format_report_number(value.get('samples_per_second_p50'))}; " 

1538 f"peak allocated={_format_report_number(allocated_mib)} MiB; " 

1539 f"reserved={_format_report_number(reserved_mib)} MiB." 

1540 ) 

1541 return entries or (["未测量"] if language == "zh" else ["not measured"]) 

1542 

1543 

1544def _reproducibility_entries( 

1545 store: EvidenceStore, 

1546 environment: Optional[Mapping[str, Any]], 

1547 manifest: Mapping[str, Any], 

1548 language: str, 

1549) -> list[str]: 

1550 """Render revisions and import paths needed to replay the evidence.""" 

1551 environment = environment or {} 

1552 torch_info = environment.get("torch") or {} 

1553 transformers_info = environment.get("transformers") or {} 

1554 framework_info = environment.get("hyper_parallel") or {} 

1555 reference = manifest.get("reference", {}) 

1556 labels = { 

1557 "en": ("resolved manifest", "environment", "repository revision", "framework import", "reference source"), 

1558 "zh": ("已解析清单", "运行环境", "代码仓 revision", "框架导入路径", "参考源码"), 

1559 }[language] 

1560 return [ 

1561 f"{labels[0]}: `{store.path('manifest.resolved.yaml').name}`", 

1562 f"{labels[1]}: `{store.path('environment.json').name}`", 

1563 f"{labels[2]}: `{environment.get('git_revision', 'n/a')}`", 

1564 f"{labels[3]}: `{framework_info.get('import_path', 'n/a')}`", 

1565 f"PyTorch: `{torch_info.get('version', 'n/a')}`; Transformers: " 

1566 f"`{transformers_info.get('version', 'n/a')}`", 

1567 f"{labels[4]}: `{reference.get('source_path', 'n/a')}`", 

1568 ] 

1569 

1570 

1571def _structure_entries( 

1572 findings: Optional[Mapping[str, Any]], 

1573 language: str, 

1574) -> list[str]: 

1575 """Render structure status, inventory size, and actionable findings.""" 

1576 if findings is None: 

1577 return ["未执行"] if language == "zh" else ["not executed"] 

1578 metadata = findings.get("metadata", {}) 

1579 counts = metadata.get("inventory_counts", {}) 

1580 if language == "zh": 

1581 entries = [ 

1582 f"状态={findings.get('status')};model_type={metadata.get('model_type', 'n/a')};" 

1583 f"模块={counts.get('modules', 'n/a')};参数={counts.get('parameters', 'n/a')};" 

1584 f"buffer={counts.get('buffers', 'n/a')}。" 

1585 ] 

1586 else: 

1587 entries = [ 

1588 f"status={findings.get('status')}; model_type={metadata.get('model_type', 'n/a')}; " 

1589 f"modules={counts.get('modules', 'n/a')}; parameters={counts.get('parameters', 'n/a')}; " 

1590 f"buffers={counts.get('buffers', 'n/a')}." 

1591 ] 

1592 for finding in findings.get("findings", ()): 

1593 entries.append( 

1594 f"{finding.get('code')} {finding.get('severity')}: {finding.get('message')} " 

1595 f"(fix: {finding.get('remediation') or 'n/a'})" 

1596 ) 

1597 return entries 

1598 

1599 

1600def _localized_value(value: Mapping[str, Any], key: str, language: str) -> Any: 

1601 """Read a localized evidence field with an English fallback.""" 

1602 localized_key = f"{key}_zh" if language == "zh" else key 

1603 return value.get(localized_key, value.get(key, "n/a")) 

1604 

1605 

1606def _localized_sentence(value: Mapping[str, Any], key: str, language: str) -> str: 

1607 """Return localized prose without duplicate terminal punctuation.""" 

1608 return str(_localized_value(value, key, language)).rstrip(".。") 

1609 

1610 

1611def _verdict_entries( 

1612 store: EvidenceStore, 

1613 findings: Optional[Mapping[str, Any]], 

1614 parity: Optional[Mapping[str, Any]], 

1615 comparison: Optional[Mapping[str, Any]], 

1616 checkpoint: Optional[Mapping[str, Any]], 

1617 language: str, 

1618) -> list[str]: 

1619 """State exactly what the aggregate PASS covers and does not cover.""" 

1620 operator_audit = _read_json(store.path("analysis/operator_support.json")) or {} 

1621 statuses = ( 

1622 (findings or {}).get("status", "NOT_EXECUTED"), 

1623 (parity or {}).get("status", "NOT_EXECUTED"), 

1624 (comparison or {}).get("status", "NOT_EXECUTED"), 

1625 ) 

1626 strict_validate = operator_audit.get("strict_validate_status", "NOT_RECORDED") 

1627 checkpoint_status = (checkpoint or {}).get("status", "NOT_EXECUTED") 

1628 if language == "zh": 

1629 return [ 

1630 f"已执行门禁:结构={statuses[0]};原生模块对齐={statuses[1]};" 

1631 f"已声明精度矩阵={statuses[2]}。", 

1632 "首行 PASS 只适用于 resolved cases 中实际执行的范围;未执行或明确排除的能力不会因该 PASS " 

1633 f"自动视为已覆盖。严格 Validate={strict_validate};预训练 checkpoint={checkpoint_status}。", 

1634 ] 

1635 return [ 

1636 f"executed gates: structure={statuses[0]}; native module parity={statuses[1]}; " 

1637 f"declared precision matrix={statuses[2]}.", 

1638 "The first-line PASS applies only to the executed resolved cases; omitted or explicitly excluded " 

1639 f"capabilities are not covered by that PASS. strict Validate={strict_validate}; " 

1640 f"pretrained checkpoint={checkpoint_status}.", 

1641 ] 

1642 

1643 

1644def _operator_support_entries(store: EvidenceStore, language: str) -> list[str]: 

1645 """Render the exact-callable distributed-operator audit when recorded.""" 

1646 audit = _read_json(store.path("analysis/operator_support.json")) 

1647 if audit is None: 

1648 return ["未记录"] if language == "zh" else ["not recorded"] 

1649 if language == "zh": 

1650 entries = [ 

1651 f"审计状态={audit.get('status', 'n/a')};" 

1652 f"严格 Validate 状态={audit.get('strict_validate_status', 'n/a')}。" 

1653 ] 

1654 for operator in audit.get("operators", ()): 

1655 consumer = _localized_sentence(operator, "consumer", language) 

1656 reason = _localized_sentence(operator, "reason", language) 

1657 entries.append( 

1658 f"`{operator.get('callable', 'n/a')}`:状态={operator.get('status', 'n/a')};" 

1659 f"registry key=`{operator.get('registry_key', 'n/a')}`;" 

1660 f"实现={operator.get('implementation', 'n/a')};" 

1661 f"注册={operator.get('registered', False)};" 

1662 f"使用方={consumer};结论={reason}。" 

1663 ) 

1664 return entries 

1665 entries = [ 

1666 f"audit status={audit.get('status', 'n/a')}; " 

1667 f"strict Validate status={audit.get('strict_validate_status', 'n/a')}." 

1668 ] 

1669 for operator in audit.get("operators", ()): 

1670 consumer = _localized_sentence(operator, "consumer", language) 

1671 reason = _localized_sentence(operator, "reason", language) 

1672 entries.append( 

1673 f"`{operator.get('callable', 'n/a')}`: status={operator.get('status', 'n/a')}; " 

1674 f"registry_key=`{operator.get('registry_key', 'n/a')}`; " 

1675 f"implementation={operator.get('implementation', 'n/a')}; " 

1676 f"registered={operator.get('registered', False)}; " 

1677 f"consumer={consumer}; finding={reason}." 

1678 ) 

1679 return entries 

1680 

1681 

1682def _parallel_ownership_entries(store: EvidenceStore, language: str) -> list[str]: 

1683 """Render actual parameter placements instead of inferring them from launch size.""" 

1684 audit = _read_json(store.path("analysis/parallel_ownership.json")) 

1685 if audit is None: 

1686 return ["未记录"] if language == "zh" else ["not recorded"] 

1687 if language == "zh": 

1688 entries = [ 

1689 f"审计状态={audit.get('status', 'n/a')};证据拓扑=" 

1690 f"{_format_topology(audit.get('topology', {}))}。" 

1691 ] 

1692 for subtree in audit.get("subtrees", ()): 

1693 examples = ";".join( 

1694 subtree.get("placement_evidence_zh", subtree.get("placement_evidence", ())) 

1695 ) or "n/a" 

1696 conclusion = _localized_sentence(subtree, "conclusion", language) 

1697 entries.append( 

1698 f"{_localized_value(subtree, 'name', language)}:" 

1699 f"TP 状态={subtree.get('tp_status', 'n/a')};证据={examples};" 

1700 f"结论={conclusion}。" 

1701 ) 

1702 conclusion = _localized_sentence(audit, "conclusion", language) 

1703 entries.append(f"总体结论:{conclusion}。") 

1704 return entries 

1705 entries = [ 

1706 f"audit status={audit.get('status', 'n/a')}; evidence topology=" 

1707 f"{_format_topology(audit.get('topology', {}))}." 

1708 ] 

1709 for subtree in audit.get("subtrees", ()): 

1710 examples = "; ".join(subtree.get("placement_evidence", ())) or "n/a" 

1711 conclusion = _localized_sentence(subtree, "conclusion", language) 

1712 entries.append( 

1713 f"{_localized_value(subtree, 'name', language)}: " 

1714 f"TP status={subtree.get('tp_status', 'n/a')}; evidence={examples}; " 

1715 f"conclusion={conclusion}." 

1716 ) 

1717 conclusion = _localized_sentence(audit, "conclusion", language) 

1718 entries.append(f"overall conclusion: {conclusion}.") 

1719 return entries 

1720 

1721 

1722def _issue_ledger_entries(store: EvidenceStore, language: str) -> list[str]: 

1723 """Render resolved and open integration issues with stable identifiers.""" 

1724 ledger = _read_json(store.path("analysis/issues.json")) 

1725 if ledger is None: 

1726 return ["未记录"] if language == "zh" else ["not recorded"] 

1727 entries = [] 

1728 for issue in ledger.get("issues", ()): 

1729 title = _localized_value(issue, "title", language) 

1730 detail = _localized_value(issue, "detail", language) 

1731 if language == "zh": 

1732 entries.append( 

1733 f"`{issue.get('id', 'n/a')}` [{issue.get('status', 'n/a')}/" 

1734 f"{issue.get('severity', 'n/a')}] {title}:{detail}" 

1735 ) 

1736 else: 

1737 entries.append( 

1738 f"`{issue.get('id', 'n/a')}` [{issue.get('status', 'n/a')}/" 

1739 f"{issue.get('severity', 'n/a')}] {title}: {detail}" 

1740 ) 

1741 return entries or (["无记录"] if language == "zh" else ["no entries"]) 

1742 

1743 

1744def _checkpoint_entries( 

1745 checkpoint: Optional[Mapping[str, Any]], 

1746 language: str, 

1747) -> list[str]: 

1748 """Explain whether checkpoint tensors were loaded or scratch-initialized.""" 

1749 if checkpoint is None: 

1750 return ["未执行"] if language == "zh" else ["not executed"] 

1751 if language == "zh": 

1752 reason = checkpoint.get("reason", "n/a") 

1753 if reason == "model was initialized from scratch or no load report was retained": 

1754 reason = "模型从随机状态初始化,或没有保留权重加载报告" 

1755 return [ 

1756 f"状态={checkpoint.get('status')};loaded={checkpoint.get('loaded')};" 

1757 f"missing={checkpoint.get('missing')};unexpected={checkpoint.get('unexpected')};" 

1758 f"原因={reason}。" 

1759 ] 

1760 return [ 

1761 f"status={checkpoint.get('status')}; loaded={checkpoint.get('loaded')}; " 

1762 f"missing={checkpoint.get('missing')}; unexpected={checkpoint.get('unexpected')}; " 

1763 f"reason={checkpoint.get('reason', 'n/a')}." 

1764 ] 

1765 

1766 

1767def _report_sections( 

1768 store: EvidenceStore, 

1769 findings: Optional[Mapping[str, Any]], 

1770 parity: Optional[Mapping[str, Any]], 

1771 comparison: Optional[Mapping[str, Any]], 

1772 checkpoint: Optional[Mapping[str, Any]], 

1773 environment: Optional[Mapping[str, Any]], 

1774 language: str, 

1775) -> list[tuple[str, list[str]]]: 

1776 """Build the detailed English or Chinese report sections.""" 

1777 manifest = _report_manifest(store) 

1778 cases = _resolved_report_cases(store) 

1779 if language == "zh": 

1780 headings = ( 

1781 "可复现性", 

1782 "结论与适用范围", 

1783 "结构验证", 

1784 "Checkpoint 覆盖", 

1785 "分布式算子审计", 

1786 "真实并行归属", 

1787 "问题台账", 

1788 "原生模块精度对齐", 

1789 "精度覆盖范围", 

1790 "验收阈值", 

1791 "精度矩阵详情", 

1792 "全局最差误差", 

1793 "性能与内存(不作为精度门禁)", 

1794 "证据索引", 

1795 ) 

1796 evidence_entries = [ 

1797 "完整机器可读比较:`comparison.json`", 

1798 "展开后的用例:`cases/resolved_cases.json`", 

1799 "分布式算子审计:`analysis/operator_support.json`", 

1800 "并行归属证据:`analysis/parallel_ownership.json`", 

1801 "问题台账:`analysis/issues.json`", 

1802 "每个用例的日志、metrics、参数探针和 checkpoint 证据:`cases/<case>/`", 

1803 ] 

1804 else: 

1805 headings = ( 

1806 "Reproducibility", 

1807 "Verdict and scope", 

1808 "Structure validation", 

1809 "Checkpoint coverage", 

1810 "Distributed operator audit", 

1811 "Actual parallel ownership", 

1812 "Issue ledger", 

1813 "Native module parity", 

1814 "Precision coverage", 

1815 "Acceptance thresholds", 

1816 "Precision matrix details", 

1817 "Worst observed errors", 

1818 "Performance and memory (non-gating)", 

1819 "Evidence index", 

1820 ) 

1821 evidence_entries = [ 

1822 "complete machine-readable comparison: `comparison.json`", 

1823 "resolved cases: `cases/resolved_cases.json`", 

1824 "distributed operator audit: `analysis/operator_support.json`", 

1825 "parallel ownership evidence: `analysis/parallel_ownership.json`", 

1826 "issue ledger: `analysis/issues.json`", 

1827 "per-case logs, metrics, parameter probes, and checkpoint evidence: `cases/<case>/`", 

1828 ] 

1829 return [ 

1830 (headings[0], _reproducibility_entries(store, environment, manifest, language)), 

1831 ( 

1832 headings[1], 

1833 _verdict_entries(store, findings, parity, comparison, checkpoint, language), 

1834 ), 

1835 (headings[2], _structure_entries(findings, language)), 

1836 (headings[3], _checkpoint_entries(checkpoint, language)), 

1837 (headings[4], _operator_support_entries(store, language)), 

1838 (headings[5], _parallel_ownership_entries(store, language)), 

1839 (headings[6], _issue_ledger_entries(store, language)), 

1840 (headings[7], _detailed_parity_entries(parity, language)), 

1841 (headings[8], _precision_coverage_entries(store, language)), 

1842 (headings[9], _acceptance_entries(manifest, language)), 

1843 (headings[10], _precision_detail_entries(cases, comparison, manifest, language)), 

1844 (headings[11], _worst_case_entries(comparison, language)), 

1845 (headings[12], _detailed_performance_entries(comparison, language)), 

1846 (headings[13], evidence_entries), 

1847 ] 

1848 

1849 

1850def command_report(args: argparse.Namespace) -> int: 

1851 """Render detailed English and Chinese PASS/FAIL/BLOCKED summaries.""" 

1852 store = EvidenceStore(args.output_dir) 

1853 findings = _read_json(store.path("check/findings.json")) 

1854 parity = _read_json(store.path("module_parity/comparison.json")) 

1855 comparison = _read_json(store.path("comparison.json")) 

1856 checkpoint = _read_json(store.path("checkpoint/coverage.json")) 

1857 environment = _read_json(store.path("environment.json")) 

1858 required_reports = (findings, parity, comparison) 

1859 status = _aggregate_statuses( 

1860 [value.get("status") for value in required_reports if value is not None] 

1861 + (["BLOCKED"] if any(value is None for value in required_reports) else []) 

1862 ) 

1863 english_summary = store.render_summary( 

1864 status, 

1865 "Model integration validation", 

1866 _report_sections( 

1867 store, 

1868 findings, 

1869 parity, 

1870 comparison, 

1871 checkpoint, 

1872 environment, 

1873 "en", 

1874 ), 

1875 ) 

1876 chinese_summary = store.render_summary( 

1877 status, 

1878 "模型接入验证报告", 

1879 _report_sections( 

1880 store, 

1881 findings, 

1882 parity, 

1883 comparison, 

1884 checkpoint, 

1885 environment, 

1886 "zh", 

1887 ), 

1888 relative_path="summary.zh-CN.md", 

1889 ) 

1890 print(f"{status}: {english_summary}; {chinese_summary}") 

1891 return 0 if status == "PASS" else 1 if status == "FAIL" else 2 

1892 

1893 

1894def _parser() -> argparse.ArgumentParser: 

1895 """Build the command-line argument parser.""" 

1896 parser = argparse.ArgumentParser( 

1897 prog="python -m hyper_parallel.tools.model_integration", 

1898 description=__doc__, 

1899 epilog="exit codes: 0=PASS, 1=FAIL or execution error, 2=BLOCKED or manifest error", 

1900 ) 

1901 subparsers = parser.add_subparsers(dest="command", required=True) 

1902 for name, handler, help_text in ( 

1903 ("inspect", command_inspect, "inspect source and final model structure"), 

1904 ("scaffold", command_scaffold, "generate a minimal model adapter scaffold"), 

1905 ("check", command_check, "validate the final built model"), 

1906 ("parity", command_parity, "run model-owned module parity cases"), 

1907 ("validate", command_validate, "run the precision validation matrix"), 

1908 ): 

1909 subparser = subparsers.add_parser(name, help=help_text) 

1910 subparser.add_argument("--manifest", required=True) 

1911 subparser.add_argument("--output-dir") 

1912 subparser.set_defaults(handler=handler) 

1913 if name == "scaffold": 

1914 subparser.add_argument("--scaffold-dir", required=True) 

1915 elif name == "parity": 

1916 subparser.add_argument("--device", default="cpu") 

1917 subparser.add_argument("--dtype", default="float32") 

1918 elif name == "validate": 

1919 subparser.add_argument("--generate-only", action="store_true") 

1920 report_parser = subparsers.add_parser("report", help="render an evidence summary") 

1921 report_parser.add_argument("--output-dir", required=True) 

1922 report_parser.set_defaults(handler=command_report) 

1923 return parser 

1924 

1925 

1926def main(argv: Optional[list[str]] = None) -> int: 

1927 """Execute the selected model-integration command.""" 

1928 args = _parser().parse_args(argv) 

1929 try: 

1930 return int(args.handler(args)) 

1931 except ManifestError as error: 

1932 print(f"manifest error: {error}", file=sys.stderr) 

1933 return 2 

1934 

1935 

1936if __name__ == "__main__": 

1937 raise SystemExit(main())