File size: 2,060 Bytes
c1a46f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d572bbd
 
 
 
 
c1a46f7
d572bbd
 
 
 
 
 
 
c1a46f7
 
 
 
 
 
d572bbd
 
 
 
 
 
c1a46f7
d572bbd
c1a46f7
 
 
 
 
 
 
d572bbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1a46f7
d572bbd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
配置管理模块 — 公共模块 (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)