Sub topic 6
Writing and Loading a Config File
Assume you know basic Python modules, functions, and command-line arguments. You also know how to train a model with a library such as scikit-learn or PyTorch. This chapter focuses on making training settings explicit, typed, and easy to change.
Why separate configuration from code?
A training script contains the steps of an experiment. A configuration contains values that may change between experiments, such as:
- The training data path
- The random seed
- The learning rate
- The batch size
- The number of training epochs
If these values are hard-coded, comparing experiments becomes difficult. You must edit the script, remember what changed, and avoid accidentally committing a temporary value. A separate configuration file lets the same code run with different settings.
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32YAML is a text format designed for configuration. Its indentation and key: value syntax make it readable. Keep the file in a directory such as configs/train.yaml.
Load YAML into a typed object
A Python dataclass is a class whose fields describe data. A frozen dataclass prevents the training code from changing configuration after loading. This makes the configuration a stable input to the run.
Install the YAML parser if necessary:
python -m pip install pyyamlCreate src/my_project/config.py:
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def apply_overrides(raw: dict, overrides: Iterable[str]) -> dict:
result = dict(raw)
for item in overrides:
if "=" not in item:
raise ValueError(f"Override must have the form key=value: {item}")
key, value = item.split("=", 1)
result[key] = yaml.safe_load(value)
return result
def load_config(path: str, overrides: Iterable[str] = ()) -> TrainConfig:
with Path(path).open() as file:
raw = yaml.safe_load(file) or {}
values = apply_overrides(raw, overrides)
return TrainConfig(**values)yaml.safe_load converts values to Python types. For example, 32 becomes an integer and 0.001 becomes a float. The TrainConfig(**values) call checks the field names. A missing field or an unknown field raises an error instead of silently producing a partial configuration.
Override values for one run
A training entry point can pass command-line overrides without changing the YAML file:
import argparse
from my_project.config import load_config
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("overrides", nargs="*")
args = parser.parse_args()
config = load_config(args.config, args.overrides)
print(config)Run it like this:
python -m my_project.train --config configs/train.yaml learning_rate=0.01 batch_size=64The YAML file remains the default. The command records the exceptional values in the shell history or experiment log.
Exercise
What happens when the command uses learningrate=0.01 while train.yaml contains learningrate: 0.001?
Show answer
The command-line value replaces the YAML value for that run, and yaml.safe_load converts 0.01 to a floating-point number.