The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
Turn six training commands into a graph: a dictionary of steps and what they need, an order worked out from it, a file on every arrow, one retry rule, and a rerun that skips what already finished.
What you will learn
- Draw a training pipeline as a directed acyclic graph and write it as a Python dictionary
- Work out the running order from what each step needs (a topological order)
- Give every step a file as its input and output, plus one retry rule
- Explain why a failed step blocks only what comes after it, and how a rerun carries on from the gap
Before you start
- Pipelines and ColumnTransformer
- Saving and Loading Models with joblib
- Basic Python dictionaries and loops
Up to now, a person has been typing the training commands one by one: load the data, build the features, train, evaluate, save. A person forgets a step, runs them in the wrong order, or doesn't notice that one of them failed. So the first job is to write the steps down, together with how they connect.
We'll do it on the ticket priority project. The tickets are synthetic, and each "day" is just 400 more of them. Three small files do the work: dag.py (the graph), steps.py (the six steps) and scheduler.py (runs them in order, with retries).
A car assembly line
Think of a car assembly line: frame, then engine, then brakes, then final checks. Every station takes what the last one finished.
Now the brakes station breaks down. The worker tries again, because a stuck tool can come loose. It stays broken, so the line stops right there and the stations after it don't start. Why stop the whole line? Because the other choice is a car leaving the factory without brakes. A stopped line is the safe way to fail.
Day 3: features never recovers
Our pipeline can have the same bad day. We run day 3 and simulate an outage on the features step with the --fail flag (9 failures, more than it will ever try):
python scheduler.py run --day 3 --fail features=9
day 3
ingest ok, try 1: 1200 rows up to day 3
try 1 failed: simulated outage; waiting 1s
try 2 failed: simulated outage; waiting 2s
features FAILED after 3 tries: simulated outage
baseline blocked
train blocked
evaluate blocked
publish blocked
Ingest is fine, 1,200 rows. Features fails, tries again, fails again, and after three tries it gives up. The other four steps say blocked: they didn't run at all. So nothing got published for day 3. That's the car that never left the line.
A pipeline is a graph
How did the scheduler know what to block? It has a picture of the pipeline:
- ingest comes first and needs nothing.
- features needs ingest.
- baseline and train both need features, so the line splits here. A car line can't do that, a graph can.
- evaluate needs train and baseline, because it keeps the model's score next to the baseline's. The line joins again.
- publish needs evaluate.
Directed means every arrow points one way. Acyclic means you can't follow the arrows back to where you started. Put together, a directed acyclic graph, a DAG. And that's why one failed box only stops what comes after it.
The graph is a dictionary
Here's the same picture in code, dag.py. It's just a dictionary: the step on the left, what it needs on the right.
DAG = {
"ingest": [],
"features": ["ingest"],
"baseline": ["features"],
"train": ["features"],
"evaluate": ["train", "baseline"],
"publish": ["evaluate"],
}
Baseline and train both list features (the split). Evaluate lists train and baseline (the join). Running python dag.py prints each step with what it needs:
ingest needs nothing
features needs ingest
baseline needs features
train needs features
evaluate needs train, baseline
publish needs evaluate
order: ingest > features > baseline > train > evaluate > publish
So the graph isn't a drawing somewhere. It's data that our code can read.
Working out the order
Nobody wrote down the running order. topo_order works it out:
def topo_order(dag):
done, order = set(), []
while len(order) < len(dag):
ready = [s for s in sorted(dag) if s not in done
and all(d in done for d in dag[s])]
if not ready:
raise ValueError("cycle in the graph")
done.add(ready[0])
order.append(ready[0])
return order
It starts with nothing done and looks for steps that are ready, meaning everything they need is done.
- Only ingest is ready, so it goes first.
- Now features is ready.
- After features, two steps are ready, baseline and train. The list is sorted, so baseline goes first and train right after it.
- Then evaluate, then publish.
If nothing is ever ready, there's a loop, and it raises an error. So a bad graph stops before any step runs. This is called a topological order: every step comes after the steps it needs.
Every arrow is a file
What actually travels along an arrow? A file. Each day gets its own folder, runs/day-1, runs/day-2 and so on. Here are three of the six steps from steps.py:
ROWS_PER_DAY = 400
def ingest(day, out):
df = pd.read_csv(DATA).iloc[: day * ROWS_PER_DAY]
df.to_csv(out / "raw.csv", index=False)
return f"{len(df)} rows up to day {day}"
def features(day, out):
parts = split(pd.read_csv(out / "raw.csv"))
joblib.dump(parts, out / "split.joblib")
return f"train {len(parts[0])}, test {len(parts[1])}"
def baseline(day, out):
Xtr, Xte, ytr, yte = joblib.load(out / "split.joblib")
low = DummyClassifier(strategy="most_frequent")
guess = low.fit(Xtr, ytr)
acc = accuracy_score(yte, guess.predict(Xte))
f = out / "baseline.json"
f.write_text(json.dumps({"acc": acc}))
return f"always-low accuracy {acc:.4f}"
Each step reads what the step before it left behind and writes its own file. Run day 1:
python scheduler.py run --day 1
day 1
ingest ok, try 1: 400 rows up to day 1
features ok, try 1: train 300, test 100
baseline ok, try 1: always-low accuracy 0.5100
train ok, try 1: logistic regression fitted
evaluate ok, try 1: accuracy 0.74, f1 0.7292
publish ok, try 1: published to registry/day-1
| Step | Reads | Leaves behind |
|---|---|---|
| ingest | data/tickets.csv | raw.csv (first 400 rows) |
| features | raw.csv | split.joblib (300 train, 100 test) |
| baseline | split.joblib | baseline.json (always guesses low: 0.51) |
| train | split.joblib | model.joblib |
| evaluate | split, model, baseline score | metrics.json (accuracy 0.74) |
| publish | model and metrics | a copy in registry/day-1 |
Every step has an input and an output you can open and look at. The model itself is a scikit-learn Pipeline with a ColumnTransformer, saved with joblib.
One retry rule, and a rerun
The last thing each step needs is a retry rule. In this project it's one rule for all six, in scheduler.py:
RETRYABLE = (ConnectionError, TimeoutError)
def run_task(fn, day, out, retries, wait, outages=0):
for attempt in range(1, retries + 2):
try:
if attempt <= outages: # simulated
raise ConnectionError("simulated outage")
return attempt, fn(day, out)
except RETRYABLE as err:
if attempt > retries:
raise
pause = wait * 2 ** (attempt - 1)
print(f" try {attempt} failed: {err}; "
f"waiting {pause:g}s")
time.sleep(pause)
RETRYABLE has two errors on it, connection and timeout, because those can heal. A ValueError isn't on the list, so it's never retried. Two retries means three tries at most, and the wait doubles each time (1 s, then 2 s).
On day 2, ingest hit two simulated outages, and the third try worked:
day 2
try 1 failed: simulated outage; waiting 1s
try 2 failed: simulated outage; waiting 2s
ingest ok, try 3: 800 rows up to day 2
...
When the tries run out, the step fails, like features on day 3. Now run day 3 again, with no outage:
python scheduler.py run --day 3
day 3
ingest skipped, already done
features ok, try 1: train 900, test 300
baseline ok, try 1: always-low accuracy 0.5333
train ok, try 1: logistic regression fitted
evaluate ok, try 1: accuracy 0.6767, f1 0.6166
publish ok, try 1: published to registry/day-3
Ingest says skipped, already done, because state.json remembers which steps finished for each day. Features reads the raw.csv that ingest left behind, and the line clears all the way to publish. That's why the files matter: a rerun carries on from the gap instead of starting over.
python scheduler.py backfill --start 1 --end 6 skipped days 1 to 3 (already done) and ran days 4 and 5, ending with backfill 1..6: 5 of 5 days complete. The end is exclusive, and a range outside days 1 to 5 raises ValueError: backfill 4..9 is outside days 1..5; end is exclusive.Common mistakes
- Hard-coding the order. Write what each step needs and let the code work out the order. Then adding a step can't put it in the wrong place.
- Passing data in memory only. If a step's output isn't saved, a rerun has to start from the top.
- Retrying everything. A bug or a bad file fails the same way every time. Retry only errors that can heal.
- Running steps after a failure. A model trained on missing features is the car without brakes. Block downstream steps.
Recap
| Idea | In this project |
|---|---|
| The pipeline is a graph | DAG dictionary: step to what it needs |
| Order comes from the needs | topo_order, error on a cycle |
| Every arrow is a file | raw.csv, split.joblib, baseline.json, model.joblib, metrics.json |
| One retry rule | RETRYABLE = (ConnectionError, TimeoutError), 2 retries |
| Failure stops only what follows | blocked downstream, rerun skips what's done |
Try it yourself: add a validate step between ingest and features, in the dictionary and in steps.py, then run python dag.py and read the new order. The project files are in the community, free to join.
Next, a real tool takes over the scheduling: Orchestrating ML pipelines with Airflow.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
Next →Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.