| """ |
| 配置管理模块 — 公共模块 (Person E 可以先完成) |
| |
| 功能: 加载 YAML 配置,支持命令行覆盖和多配置合并。 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import logging |
| from pathlib import Path |
| from typing import Any, Optional |
|
|
| from omegaconf import OmegaConf, DictConfig |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| def load_config(config_path: str | Path) -> DictConfig: |
| """ |
| 加载 YAML 配置文件。 |
| |
| Args: |
| config_path: 配置文件路径 |
| |
| Returns: |
| DictConfig: OmegaConf 配置对象 |
| """ |
| config_path = Path(config_path) |
| if not config_path.exists(): |
| raise FileNotFoundError(f"Config file not found: {config_path}") |
|
|
| config = OmegaConf.load(config_path) |
| logger.info("Loaded config from %s", config_path) |
| return config |
|
|
|
|
| def merge_configs(base_config: DictConfig, override_config: DictConfig) -> DictConfig: |
| """ |
| 合并配置 (override 覆盖 base)。 |
| |
| Args: |
| base_config: 基础配置 |
| override_config: 覆盖配置 |
| |
| Returns: |
| DictConfig: 合并后的配置 |
| """ |
| return OmegaConf.merge(base_config, override_config) |
|
|
|
|
| def config_from_cli(config_path: str, cli_args: list[str]) -> DictConfig: |
| """ |
| 从配置文件 + 命令行参数构建最终配置。 |
| |
| 使用方式: python train.py --config configs/default.yaml training.lr=1e-4 model.nhead=16 |
| |
| Args: |
| config_path: 配置文件路径 |
| cli_args: 命令行覆盖参数列表 |
| |
| Returns: |
| DictConfig: 最终配置 |
| """ |
| config = load_config(config_path) |
|
|
| if cli_args: |
| cli_config = OmegaConf.from_cli(cli_args) |
| config = merge_configs(config, cli_config) |
| logger.info("Applied %d CLI overrides", len(cli_args)) |
|
|
| return config |
|
|
|
|
| def config_to_dict(config: DictConfig) -> dict: |
| """ |
| 将 OmegaConf DictConfig 转换为普通 Python dict。 |
| |
| Args: |
| config: OmegaConf 配置对象 |
| |
| Returns: |
| dict: 普通 Python 字典 |
| """ |
| return OmegaConf.to_container(config, resolve=True) |
|
|