Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / config / parser.py: 93%
74 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""Training configuration entry point: a YAML file plus dotted CLI overrides."""
17from __future__ import annotations
19__all__ = [
20 "parse_training_args",
21]
23import argparse
24from dataclasses import replace
25from pathlib import Path
26from typing import Sequence
28import yaml
30from hyper_parallel.trainer.config.resolver import (
31 ConfigResolutionError,
32 replace_override_path,
33 resolve_config,
34)
35from hyper_parallel.trainer.config.trainer import TrainerConfig
38class _TrainingConfigLoader(yaml.SafeLoader):
39 """Reject duplicate keys in the YAML ops mapping."""
41 def get_single_data(self) -> object:
42 root = self.get_single_node()
43 if root is None:
44 return None
45 if isinstance(root, yaml.MappingNode):
46 ops_nodes = [value for key, value in root.value if isinstance(key, yaml.ScalarNode) and key.value == "ops"]
47 if len(ops_nodes) > 1:
48 raise ConfigResolutionError("$.ops", "duplicate ops mapping")
49 if ops_nodes and isinstance(ops_nodes[0], yaml.MappingNode):
50 seen = set()
51 for key, _ in ops_nodes[0].value:
52 if isinstance(key, yaml.ScalarNode):
53 if key.value in seen:
54 raise ConfigResolutionError("$.ops", f"duplicate family {key.value!r}")
55 seen.add(key.value)
56 return self.construct_document(root)
59def _parse_override_tokens(tokens: Sequence[str]) -> list[tuple[str, str]]:
60 """Split ``--field=value`` CLI tokens into validated paths and raw values."""
61 parsed = []
62 for token in tokens:
63 if not token.startswith("--") or token == "--":
64 raise ConfigResolutionError(
65 "CLI", f"expected a dotted override in '--field=value' form, got {token!r}"
66 )
67 option = token[2:]
68 if "=" not in option:
69 raise ConfigResolutionError(
70 "CLI", f"expected a dotted override in '--field=value' form, got {token!r}"
71 )
72 path, raw_value = option.split("=", 1)
73 if not path or any(not part for part in path.split(".")):
74 raise ConfigResolutionError("CLI", f"invalid override path {path!r}")
75 parsed.append((path, raw_value))
76 return parsed
79def _apply_typed_overrides(
80 config: TrainerConfig,
81 overrides: Sequence[str],
82) -> TrainerConfig:
83 """Parse CLI override values and apply them to the resolved configuration."""
84 config_with_overrides = config
85 for dot_path, raw_value in _parse_override_tokens(overrides):
86 try:
87 parsed_value = yaml.safe_load(raw_value)
88 except yaml.YAMLError as exc:
89 raise ConfigResolutionError(
90 f"CLI.{dot_path}", f"invalid YAML value {raw_value!r}: {exc}"
91 ) from exc
92 parts = dot_path.split(".")
93 if len(parts) == 2 and parts[0] == "ops":
94 selections = {**config_with_overrides.ops, parts[1]: parsed_value}
95 try:
96 config_with_overrides = replace(config_with_overrides, ops=selections)
97 except ValueError as exc:
98 raise ConfigResolutionError(f"CLI.{dot_path}", str(exc)) from exc
99 else:
100 config_with_overrides = replace_override_path(config_with_overrides, parts, parsed_value, path="")
101 return config_with_overrides
104def _load_training_config(
105 config_file: str | Path,
106 cli_overrides: Sequence[str] = (),
107) -> TrainerConfig:
108 """Load a YAML configuration and apply CLI overrides."""
109 config_path = Path(config_file)
110 try:
111 raw = yaml.load(config_path.read_text(encoding="utf-8"), Loader=_TrainingConfigLoader)
112 except OSError as exc:
113 raise ConfigResolutionError(config_path, f"could not read config file: {exc}") from exc
114 except yaml.YAMLError as exc:
115 raise ConfigResolutionError(config_path, f"invalid YAML: {exc}") from exc
117 config = resolve_config(raw)
118 return _apply_typed_overrides(config, cli_overrides)
121def parse_training_args(argv: Sequence[str] | None = None) -> TrainerConfig:
122 """Parse a YAML configuration path and CLI overrides into a ``TrainerConfig``.
124 Args:
125 argv: Argument tokens excluding the program name. Uses ``sys.argv[1:]``
126 when ``None``. The configuration path precedes any
127 ``--field=value`` overrides.
129 Returns:
130 The resolved configuration with CLI overrides applied.
132 Raises:
133 ConfigResolutionError: The file cannot be read, or the YAML
134 configuration or CLI overrides are invalid.
135 SystemExit: Help is requested or required command-line arguments
136 are missing.
138 Example:
139 config = parse_training_args(["train.yaml", "--accelerator.tp_size=4"])
140 """
141 parser = argparse.ArgumentParser(description="HyperParallel training config")
142 parser.add_argument("config_file", help="Path to the YAML training config")
143 args, overrides = parser.parse_known_args(argv)
144 return load_training_config(args.config_file, overrides)
147def load_training_config(
148 config_file: str | Path,
149 cli_overrides: Sequence[str] = (),
150) -> TrainerConfig:
151 """Load a training YAML into ``TrainerConfig``.
153 Args:
154 config_file: Path to the YAML training config.
155 cli_overrides: Canonical ``--field=value`` dotted overrides.
157 Returns:
158 Resolved training configuration, carrying the resolved YAML path for
159 callers that need the source of the configuration (codegen artifact
160 layout, signature).
161 """
162 config = _load_training_config(config_file, cli_overrides)
163 config._yaml_path = str(Path(config_file).resolve()) # pylint: disable=protected-access
164 return config