_config_loader.py 6.14 KB
Newer Older
Baber's avatar
Baber committed
1
2
3
4
5
6
7
8
9
10
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path
from typing import Any

import yaml


Baber's avatar
Baber committed
11
12
13
_Base = (
    yaml.CSafeLoader if getattr(yaml, "__with_libyaml__", False) else yaml.FullLoader
)
Baber's avatar
Baber committed
14
15
16
17
18
19
20
_IGNORE_DIRS = {"__pycache__", ".ipynb_checkpoints"}


def _mk_function_ctor(base_dir: Path, resolve: bool):
    def ctor(loader: yaml.Loader, node: yaml.Node):
        spec = loader.construct_scalar(node)  # type: ignore[arg-type]
        if not resolve:
Baber's avatar
Baber committed
21
22
            return str(base_dir.expanduser() / spec)
        return _import_func_in_yml(spec, base_dir)
Baber's avatar
Baber committed
23
24
25
26
27
28
29
30

    return ctor


def _make_loader(base_dir: Path, *, resolve_funcs: bool) -> type[yaml.Loader]:
    class Loader(_Base): ...  # type: ignore[no-redef]

    yaml.add_constructor(
Baber's avatar
Baber committed
31
32
33
        "!function",
        _mk_function_ctor(base_dir, resolve_funcs),
        Loader=Loader,
Baber's avatar
Baber committed
34
35
36
37
    )
    return Loader


Baber's avatar
Baber committed
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
def _load_module_with_cache(module_path: Path) -> Any:
    """Load a module from a file path with caching and hot-reload support.

    Args:
        module_path: Path to the Python file to load

    Returns:
        The loaded module
    """
    # Determine module name based on location
    path_str = str(module_path)

    # Check if this is a built-in task module
    if "/lm_eval/tasks/" in path_str:
        # Find the position of lm_eval/tasks/ in the path
        tasks_idx = path_str.find("/lm_eval/tasks/")
        if tasks_idx != -1:
            # Extract path starting from lm_eval/tasks/
            # e.g., /path/to/lm_eval/tasks/hellaswag/utils.py → hellaswag/utils.py
            relative_path = path_str[tasks_idx + len("/lm_eval/tasks/") :]
            # Remove .py and convert to module name
            # e.g., hellaswag/utils.py → lm_eval.tasks.hellaswag.utils
            module_parts = relative_path.replace(".py", "").replace("/", ".")
            module_name = f"lm_eval.tasks.{module_parts}"
        else:
Baber's avatar
cleanup  
Baber committed
63
            # Fallback to a full path if a pattern not found
Baber's avatar
Baber committed
64
65
            module_name = str(module_path.with_suffix(""))
    else:
Baber's avatar
cleanup  
Baber committed
66
        # External module - use a full path without extension
Baber's avatar
Baber committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        module_name = str(module_path.with_suffix(""))

    # Check if we need to reload the module
    if module_name in sys.modules:
        existing_module = sys.modules[module_name]
        # Check if it was modified
        current_mtime = module_path.stat().st_mtime_ns
        if (
            hasattr(existing_module, "__mtime__")
            and existing_module.__mtime__ == current_mtime
        ):
            # Module hasn't changed, reuse it
            return existing_module

    # Load or reload the module
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load module from {module_path}") from None
    module = importlib.util.module_from_spec(spec)
    # Store mtime for future checks
Baber's avatar
cleanup  
Baber committed
87
    module.__mtime__ = module_path.stat().st_mtime_ns  # type: ignore
Baber's avatar
Baber committed
88
89
90
91
92
    spec.loader.exec_module(module)  # type: ignore[arg-type]
    sys.modules[module_name] = module
    return module


Baber's avatar
Baber committed
93
94
95
96
97
98
99
def _import_func_in_yml(qual: str, base_dir: Path):
    """Import function from qual: utils.process_doc, checking local files first then standard imports.

    Args:
        qual: Qualified function name (e.g., 'utils.process_doc')
        base_dir: Directory to search for local modules
    """
Baber's avatar
Baber committed
100
    mod_path, _, fn_name = qual.rpartition(".")
Baber's avatar
Baber committed
101
    # 1) relative "utils.py" next to YAML
Baber's avatar
Baber committed
102
103
    rel = (base_dir / f"{mod_path.replace('.', '/')}.py").resolve()
    if rel.exists():
Baber's avatar
Baber committed
104
105
        module = _load_module_with_cache(rel)
        return getattr(module, fn_name)
Baber's avatar
Baber committed
106

Baber's avatar
Baber committed
107
    # 2) already-importable module
Baber's avatar
Baber committed
108
109
110
111
    module = __import__(mod_path, fromlist=[fn_name])
    return getattr(module, fn_name)


Baber's avatar
Baber committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def _import_fun_from_str(path_str: str) -> Any:
    """Import a function from a string in the form '/absolute/path/to/module.function_name'."""
    try:
        # Split off the function name from the rightmost dot
        module_path_str, function_name = path_str.rsplit(".", 1)
    except ValueError as e:
        raise ValueError(
            f"Invalid path format: {path_str}. Expected format: /path/to/module.function_name"
        ) from e

    # Convert to Path and handle .py extension
    module_path = Path(module_path_str)
    if not module_path.suffix:
        module_path = module_path.with_suffix(".py")
    elif module_path.suffix != ".py":
        # If it has a non-.py suffix, the user might have included .py in the path
        # e.g., "/path/to/module.py.function_name"
        base_path = module_path.with_suffix("")
        if base_path.with_suffix(".py").exists():
            module_path = base_path.with_suffix(".py")

    if not module_path.exists():
        raise ImportError(f"Module file not found: {module_path}")

Baber's avatar
Baber committed
136
    module = _load_module_with_cache(module_path)
Baber's avatar
Baber committed
137
138
139
140
141
142
143
144
145

    if not hasattr(module, function_name):
        raise AttributeError(
            f"Function '{function_name}' not found in module {module_path}"
        )

    return getattr(module, function_name)


Baber's avatar
Baber committed
146
147
148
def load_yaml(
    path: str | Path,
    *,
Baber's avatar
Baber committed
149
150
    resolve_func: bool = True,
    recursive: bool = True,
Baber's avatar
Baber committed
151
    _seen: set[Path] | None = None,
Baber's avatar
Baber committed
152
153
154
) -> dict[str, Any]:
    """Pure data-loading helper.
    Returns a dict ready for higher-level interpretation.
Baber's avatar
Baber committed
155
156
157
158
159
160
161
162
163
    •No task/group/tag semantics here.
    """
    path = Path(path).expanduser().resolve()
    if _seen is None:
        _seen = set()
    if path in _seen:
        raise ValueError(f"Include cycle at {path}")
    _seen.add(path)

Baber's avatar
Baber committed
164
    loader_cls = _make_loader(path.parent, resolve_funcs=resolve_func)
Baber's avatar
Baber committed
165
166
167
    with path.open("rb") as fh:
        cfg = yaml.load(fh, Loader=loader_cls)

Baber's avatar
Baber committed
168
    if not recursive or "include" not in cfg:
Baber's avatar
Baber committed
169
        return cfg
Baber's avatar
Baber committed
170
171
    else:
        includes = cfg.pop("include")
Baber's avatar
Baber committed
172
173

    merged = {}
Baber's avatar
Baber committed
174
    for inc in includes if isinstance(includes, list) else [includes]:
Baber's avatar
Baber committed
175
176
177
178
        inc_path = (path.parent / inc) if not Path(inc).is_absolute() else Path(inc)
        merged.update(
            load_yaml(
                inc_path,
Baber's avatar
Baber committed
179
180
                resolve_func=resolve_func,
                recursive=True,
Baber's avatar
Baber committed
181
                _seen=_seen,
Baber's avatar
Baber committed
182
            ),
Baber's avatar
Baber committed
183
184
185
        )
    merged.update(cfg)  # local keys win
    return merged