Sub topic 5
Keeping Configuration Out of Code
This chapter assumes basic Python modules and functions, command-line use, and a little YAML. You should also understand model hyperparameters such as learning rate and batch size.
Why separate configuration from code?
Configuration is the set of values that changes between runs. It includes:
- Input and output paths
- Random seeds
- Model hyperparameters
- Batch sizes and training limits
- Feature or preprocessing options
When these values are written directly in training code, changing an experiment requires editing the program. That makes runs harder to compare and reproduce. It also encourages accidental code changes.
Keep the program responsible for how training works. Keep a configuration file responsible for which values a run uses.
A useful boundary looks like this:
| Belongs in code | Belongs in configuration |
|---|---|
| How a model is trained | Learning rate |
| How a file is parsed | Data path |
| Validation rules | Batch size |
| Logging behavior | Random seed |
Write a YAML configuration
YAML is a text format designed for structured values. A file such as configs/train.yaml can hold one run's settings:
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32Use descriptive names and stable units. For example, learning_rate is clearer than lr_value, and max_epochs is clearer than limit.
Do not put secrets such as API keys or database passwords in this file. Read secrets from environment variables or a secret manager instead.
Load configuration into a typed object
A typed configuration object gives the rest of the program a stable interface. The loader validates required fields because the dataclass constructor raises an error for a missing or unknown field.
Install the YAML dependency with python -m pip install pyyaml. Then save this as config_loader.py:
from dataclasses import dataclass
import sys
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, encoding="utf-8") as file:
raw = yaml.safe_load(file) or {}
return TrainConfig(**apply_overrides(raw, overrides))
if __name__ == "__main__":
config = load_config(sys.argv[1], sys.argv[2:])
print(config)Run it with:
python config_loader.py configs/train.yaml learning_rate=0.01 batch_size=64yaml.safe_load preserves numeric types. Therefore, batch_size=64 becomes an integer instead of the string "64". The frozen=True option prevents training code from silently changing configuration after loading.
Choose an override strategy
A base YAML file is easy to review and commit. Command-line overrides are useful for short experiments without creating many nearly identical files. For important runs, save the final resolved configuration with the model artifact.
Avoid accepting arbitrary keys without validation. A misspelled option such as learnig_rate should fail rather than be ignored.
Exercise
Why should a learning rate normally be in a configuration file rather than hard-coded in the training function?
Show answer
It changes between experiments, so separating it lets you compare runs without modifying reusable training code.