Sub topic 5
Keeping configuration out of code
This chapter assumes you can write Python functions and modules, run commands in a terminal, and read a short YAML file. You should also have trained at least one model. It covers what configuration is, how to tell it apart from code and data, and the mistakes that make configuration hard to trust. The next chapter covers writing and loading a config file.
What counts as configuration
Configuration is the set of values that change what a run does without changing how the code works. Learning rate, batch size, random seed, and the path to the training file are typical examples. The code that computes a gradient step is the same whether the learning rate is 0.1 or 0.001. Only the value differs.
If these values are written inside functions, every experiment needs a code edit. That causes three problems:
- Unclear history. The only record of "which learning rate did I use last Tuesday?" is a Git diff, if you committed at all.
- Risky edits. Changing a number means editing a file that also holds logic, so a typo can break something unrelated.
- Hidden coupling. The same value gets copied into several files, and the copies drift apart.
Separating configuration gives you one place to look for the values of a run. Those values can be saved next to the results, compared across runs, and changed without touching logic.
Sorting values into the right place
Not every constant belongs in a config file. A useful working rule is to ask who changes the value, and why.
| Kind of value | Example | Where it belongs |
|---|---|---|
| Experiment parameter | `learning_rate`, `batch_size`, `seed` | Config file |
| Location | `data_path`, output directory | Config file, as a path relative to the project root |
| Fixed algorithm detail | The formula for a loss function | Code |
| Schema fact | Name of the label column your features were built for | Code, or config if several datasets share the pipeline |
| Secret | API key, database password | Environment variable or secrets manager |
| The data itself | Training rows | Data folder, versioned outside Git |
Two rows deserve more attention.
Secrets are not configuration. A config file is meant to be committed, shared, and saved with every run. A password in it ends up in Git history and in your experiment logs. Read secrets from the environment instead:
import os
api_key = os.environ["TRACKING_API_KEY"]Indexing with os.environ[...] raises a KeyError if the variable is missing, which is what you want. A missing secret should stop the run at once.
Data is not configuration. A list of 10,000 training rows in a YAML file is data. Configuration points at data with a path. It does not contain it.
A worked refactor
Here is a small training script of the kind that grows in a notebook. It fits a linear model with gradient descent on synthetic data. Every value is buried in the code:
import numpy as np
rng = np.random.default_rng(42)
X = rng.normal(size=(200, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + rng.normal(scale=0.1, size=200)
w = np.zeros(3)
for _ in range(100):
grad = 2 * X.T @ (X @ w - y) / len(y)
w -= 0.05 * grad
print(w)To try a learning rate of 0.1 you edit the loop. To change the seed you edit the first line. Nothing records what you tried.
The first step is to turn the logic into functions whose parameters are the values that vary. Then gather those values in one place:
import numpy as np
def make_data(seed, n_rows):
rng = np.random.default_rng(seed)
X = rng.normal(size=(n_rows, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + rng.normal(scale=0.1, size=n_rows)
return X, y
def fit(X, y, learning_rate, epochs):
w = np.zeros(X.shape[1])
for _ in range(epochs):
grad = 2 * X.T @ (X @ w - y) / len(y)
w -= learning_rate * grad
return w
settings = {"seed": 42, "n_rows": 200, "learning_rate": 0.05, "epochs": 100}
if __name__ == "__main__":
X, y = make_data(settings["seed"], settings["n_rows"])
print(fit(X, y, settings["learning_rate"], settings["epochs"]))The functions no longer know which values will be used. They receive them as arguments, so a test can call fit with epochs=1, and a sweep can call it with ten different learning rates. The settings dictionary is still inside the script, so this is an intermediate step. In the next chapter that dictionary becomes a YAML file, along these lines:
seed: 42
n_rows: 200
learning_rate: 0.05
epochs: 100The shape of the refactor is what carries over: the logic takes explicit parameters, and a single object holds the values for one run.
Rules that keep the separation useful
Pass values in, don't reach out for them
A function that reads a global config object is harder to test than one that takes arguments. Read the config once at the entry point, then hand each function only the values it needs. Functions then stay reusable from notebooks, tests, and other scripts.
Keep one source for each default
If learning_rate defaults to 0.01 in train.py and 0.001 in the config file, the real default depends on which code path runs. Put defaults in one place. Many teams make the config file the only source and require every key to be present, so a forgotten value fails loudly instead of silently using a stale default.
Store paths relative to the project root
An absolute path such as /home/ana/data/train.csv works on one machine. A relative path such as data/processed/train.csv works for anyone who clones the repository and runs from the root. If a path really differs per machine, such as a shared mount, supply it through an environment variable or an override, not a committed value.
Keep logic out of the config
Config values should be plain data: numbers, strings, booleans, lists, and nested mappings. Once a config file contains expressions or conditionals, it becomes a second programming language that is harder to test and debug than Python. If you find yourself writing batch_size: 32 if gpu else 8, make that decision in code from two plain values.
Don't make everything configurable
Every option adds a combination to test and explain. A value that has never changed and has no reason to change, such as the number of features in a fixed schema, can stay in code. Promote a value to config when you actually vary it, or when different environments need different values.
Save the config with every run
A config only helps reproducibility if you can recover the one that produced a given model. Write a copy of the resolved values, meaning defaults plus any overrides, into the run's output folder. A config file in Git tells you what the settings are now. A saved copy tells you what they were then.
Common errors
- Values that look right but have the wrong type. A value read from text as
"0.01"is a string, not a float. Code that multiplies by it fails, or worse, repeats the string. Use a parser that returns typed values and check types when the config is loaded. - Silent typos. If code reads
config.get("learnin_rate", 0.01), a misspelled key quietly falls back to the default and the run looks fine. Prefer a structure that rejects unknown or missing keys. - Config that drifts from code. A key stays in the file after the code stops reading it, and people keep "tuning" a value that does nothing. Remove unused keys when you remove the code that uses them.
- Duplicated derived values. If
n_featuresis in config and also computed from the data, the two can disagree. Store the source value and compute the derived one. - One file for everything. Mixing experiment parameters, deployment settings, and secrets in one file makes it unclear what is safe to share and what to log. Keep them apart by who changes them.
Exercise
A training function contains if epoch % 10 == 0: save_checkpoint(), a hard-coded 0.2 validation split, and a line token = "abc123" used to upload the model. For each of the three values, say whether it belongs in the config file, in code, or in an environment variable, and give a reason.
Show answer
The checkpoint interval of 10 and the 0.2 validation split are experiment parameters that you may want to vary between runs, so both belong in the config file (for example checkpoint_every: 10 and val_fraction: 0.2). The token is a secret. It must not be committed or saved with run logs, so it belongs in an environment variable read with os.environ["UPLOAD_TOKEN"]. The condition epoch % 10 == 0 itself is logic and stays in code, now using the configured interval. The token that was already committed should also be revoked and replaced.