Sub topic 7
Overriding values from the command line
This chapter assumes you can write Python functions and modules and run commands in a terminal. It also assumes you have the flat YAML config and the TrainConfig loader from the previous chapter. A config file records the default values for a project. This chapter covers how to change a few of them for a single run without editing the file.
Why overrides exist
Suppose you want to try learning_rate=0.01 once. You have three options, and two of them cause problems:
- Edit the YAML file. The change sits in your working tree. You may commit it by accident, or forget what the default was.
- Copy the file to
train_lr01.yaml. Soon theconfigs/folder holds dozens of near-duplicates, and no one knows how they differ. - Pass an override. The file keeps the agreed defaults, and the one-off change appears in the command you ran.
An override is a key=value pair given on the command line that replaces one value from the config file for that run only. The command line documents the experiment, and your shell history, a pipeline definition, or a tracking tool can record it.
How overrides flow through the loader
The loader reads the YAML into a dictionary, applies overrides to that dictionary, and only then builds the typed config object. The order matters. Applying overrides last means they always win, and validating after means a bad override fails before any training starts.
The override function
This is the code from the previous chapter, repeated so you can read it in full:
from dataclasses import dataclass
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def apply_overrides(raw, overrides):
for item in overrides:
key, value = item.split("=", 1)
raw[key] = yaml.safe_load(value)
return raw
def load_config(path, overrides=()):
with open(path) as f:
raw = yaml.safe_load(f)
raw = apply_overrides(raw, overrides)
return TrainConfig(**raw)Two details do most of the work.
split("=", 1) splits only at the first equals sign. A value can then contain = itself, as in data_path=data/run=3/train.csv. The key is data_path and the value is data/run=3/train.csv.
yaml.safe_load(value) parses the value the same way the config file would. Everything on the command line arrives as a string. If you stored it as-is, batch_size=64 would give the string "64", and a later batch_size * 2 would produce "6464" and no error. Parsing each value with YAML gives it the type it would have had in the file. Using safe_load and not load matters for security, because safe_load refuses to construct arbitrary Python objects from the text.
Wiring it to a command
Put the command-line entry point in src/my_project/train.py. It takes a --config path and any number of positional key=value arguments:
import argparse
import json
from dataclasses import asdict
from my_project.config import load_config
def parse_args(argv=None):
parser = argparse.ArgumentParser(description="Train a model.")
parser.add_argument("--config", default="configs/train.yaml")
parser.add_argument("overrides", nargs="*", help="key=value pairs")
return parser.parse_args(argv)
def main(argv=None):
args = parse_args(argv)
cfg = load_config(args.config, args.overrides)
print(json.dumps(asdict(cfg), indent=2))
if __name__ == "__main__":
main()Run it with two overrides:
python -m my_project.train --config configs/train.yaml learning_rate=0.01 batch_size=64The printed result shows the resolved configuration, meaning the defaults with your overrides applied:
{
"data_path": "data/processed/train.csv",
"seed": 42,
"learning_rate": 0.01,
"batch_size": 64
}Because main accepts an argv list, a test can call main(["--config", "configs/train.yaml", "seed=1"]) directly, without starting a subprocess.
How values are parsed
YAML decides the type, so you need to know what it does with common inputs.
| Command-line text | Parsed value | Python type |
|---|---|---|
| `learning_rate=0.01` | `0.01` | `float` |
| `batch_size=64` | `64` | `int` |
| `data_path=data/raw/a.csv` | `"data/raw/a.csv"` | `str` |
| `use_cache=true` | `True` | `bool` |
| `limit=null` | `None` | `NoneType` |
| `learning_rate=1e-3` | `"1e-3"` | `str` (see below) |
Gotchas and edge cases
Scientific notation without a dot
PyYAML follows YAML 1.1, which requires a decimal point in a float. 1e-3 is read as a string, while 1.0e-3 is read as the float 0.001. The loader above raises no error for this. TrainConfig is a plain dataclass, and Python does not check annotations at runtime, so learning_rate quietly becomes the string "1e-3". The failure then appears later, inside the optimizer.
Strings that look like other types
A value such as name=yes becomes True, and version=1.10 becomes the float 1.1. If you need the literal text, quote it for YAML and for the shell: 'version="1.10"'.
Unknown and missing keys
TrainConfig(**raw) raises a TypeError for a key the class does not define, such as the typo learning_rat=0.01. It also raises one if a required key is missing. This is the behavior you want. A misspelled override should stop the run, not create an ignored setting.
A malformed argument
An argument without =, such as learning_rate 0.01 passed as one token, makes the tuple unpacking in apply_overrides raise a ValueError. That is acceptable for a small project, and the message points at the line.
Mutating the input
apply_overrides modifies the dictionary it receives and also returns it. This is fine inside load_config, where the dictionary is freshly read. If you reuse a dictionary across calls, pass dict(raw) so one call does not leak into the next.
Flat keys only
The loader supports only top-level keys. If the config later gains nested sections such as optimizer: {lr: 0.1}, you must decide how to address them. Dotted keys like optimizer.lr=0.1 are a common choice. Libraries such as Hydra and OmegaConf implement this and add config composition. A flat config does not need that yet.
Catching wrong types
Since the dataclass does not check types, add a check to the class itself. Frozen dataclasses can still run __post_init__, because it only reads fields:
from dataclasses import dataclass, fields
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def __post_init__(self):
for f in fields(self):
value = getattr(self, f.name)
allowed = (int, float) if f.type is float else (f.type,)
is_bad_bool = isinstance(value, bool) and f.type is not bool
if is_bad_bool or not isinstance(value, allowed):
raise TypeError(
f"{f.name} must be {f.type.__name__}, got {value!r}"
)Now learning_rate=1e-3 fails immediately with learning_rate must be float, got '1e-3'. The check accepts an int for a float field, so learning_rate=1 is allowed. It rejects True where an int is expected, because bool is a subclass of int in Python. This version works only while annotations are real classes. If you add from __future__ import annotations, f.type becomes a string and the check needs adjusting.
Testing overrides
The loader is small enough to test without files. This test checks that overrides replace existing values, add new ones, and arrive as numbers:
from my_project.config import apply_overrides
def test_apply_overrides_parses_types():
raw = {"learning_rate": 0.1}
out = apply_overrides(raw, ["learning_rate=0.01", "batch_size=32"])
assert out == {"learning_rate": 0.01, "batch_size": 32}A second test should cover the failure path, so a typo cannot start passing silently. Call load_config with an unknown key and assert that it raises TypeError.
Keeping the record
An override helps only if you can find it later. Two habits make that possible:
- Write the resolved config, not the YAML file, into the run's output folder. For example, dump
asdict(cfg)toresolved_config.jsonnext to the model. It then shows exactly which values were used. - Give the same values to your experiment tracker. The next chapters cover this, and pipeline tools can also read the same keys. In the
dvc.yamlfrom the pipeline chapter,learning_rateandbatch_sizeare tracked parameters, so changing them marks thetrainstage as out of date.
Summary of rules
- Keep defaults in the YAML file, and use overrides only for per-run changes.
- Parse values with
yaml.safe_loadso numbers, booleans, andnullkeep their types. - Apply overrides before building the typed config, and fail on unknown keys and wrong types.
- Save the resolved configuration with every run.
Exercise
You run python -m my_project.train learning_rate=1e-3 and the optimizer later fails with a confusing error about a string. Why does this happen with the loader shown here, and what are two ways to fix it?
Show answer
PyYAML follows YAML 1.1, which needs a decimal point in a float, so 1e-3 is parsed as the string "1e-3". The dataclass does not check types, so the string is stored in learning_rate without an error. One fix is to write the value as 1.0e-3 or 0.001. The other is to add a type check, such as the __post_init__ shown above, so the run fails at load time with a clear message.
Exercise
Why does apply_overrides use item.split("=", 1) and not item.split("=")?
Show answer
With a limit of 1, the string is split only at the first equals sign, so the value may contain further = characters, as in data_path=data/run=3/train.csv. Without the limit, the unpacking into key, value would fail with a ValueError because there would be more than two parts.