Sub topic 7
Overriding Values from the Command Line
Assume you know basic Python, modules, functions, the command line, Git, and how to train a model. This chapter assumes a YAML configuration file already holds the model's normal settings.
A configuration file gives a run a stable baseline. Command-line overrides let you change selected values without editing that file. This is useful for comparing learning rates, batch sizes, or data paths in an automated job.
A common precedence rule is:
- Code defines the available settings.
- The YAML file supplies normal values.
- Command-line overrides replace selected YAML values.
Use a `key=value` override
Suppose configs/train.yaml contains:
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32A training command can change two values:
python train.py --config configs/train.yaml --set learning_rate=0.01 --set batch_size=64The original file remains unchanged. The run uses a learning rate of 0.01 and a batch size of 64.
Use one --set option per override. Avoid accepting an arbitrary string and interpreting it later in the training code. Parse and validate values while loading the configuration.
from dataclasses import dataclass, fields
import argparse
import yaml
@dataclass(frozen=True)
class TrainConfig:
data_path: str
seed: int
learning_rate: float
batch_size: int
def load_config(path: str, overrides: list[str]) -> TrainConfig:
with open(path, encoding="utf-8") as file:
values = yaml.safe_load(file) or {}
allowed = {field.name for field in fields(TrainConfig)}
for item in overrides:
if "=" not in item:
raise ValueError(f"Override must use key=value: {item}")
key, raw_value = item.split("=", 1)
if key not in allowed:
raise ValueError(f"Unknown configuration key: {key}")
values[key] = yaml.safe_load(raw_value)
return TrainConfig(**values)
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("--set", action="append", default=[], dest="overrides")
args = parser.parse_args()
config = load_config(args.config, args.overrides)
print(config)Install the YAML dependency with pip install PyYAML. The safe_load call preserves useful types: 64 becomes an integer, 0.01 becomes a floating-point number, and true becomes a Boolean.
Avoid common override errors
An unknown key should fail immediately. Otherwise, a typo such as lerning_rate=0.01 can create a run that appears successful but uses the old value.
Validate that required keys exist and that values have acceptable ranges. A type annotation does not automatically reject every incorrect value at runtime. For example, a negative batch size may still need an explicit check.
Shell parsing can also change values. Quote paths containing spaces:
python train.py --config configs/train.yaml --set 'data_path=data/my training/train.csv'Record the complete command with the experiment's metrics and code revision. The command is part of the run's provenance, meaning the evidence that explains how its result was produced.
> callout note > Treat command-line overrides as immutable run metadata. Do not silently rewrite them inside the training script.
Exercise
The YAML file sets batchsize to 32. What batch size does the program use with --set batchsize=128, and why?
Show answer
It uses 128 because command-line values are applied after the YAML values and therefore take precedence.