TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › ML Pipelines: Stages, Caching and Orchestrators

ML Pipelines: Stages, Caching and Orchestrators

A model is the last link of a chain: pull raw data, validate it, clean it, build features, split, train, evaluate, and perhaps register the result. Done by hand in a notebook, the chain is fragile in two ways. Steps get skipped or run in the wrong order ("did I rebuild the features after fixing the cleaning bug?"), and everything gets rerun every time, including the two-hour feature job that did not change. An ML pipeline writes the chain down as a graph of stages with declared inputs and outputs, so that a tool can run it in the right order, rerun only what is out of date, and record what produced what.

Stages as a DAG

ingest validate prepare split train evaluate register params.yaml test model solid: data and models flow between stages; dashed: params read by stages

A pipeline is a directed acyclic graph (DAG): each stage is a node, an edge says "this stage needs that stage's output". Acyclic because a stage cannot depend on its own result; the order to run them is a topological sort of the graph, and stages with no path between them (two feature jobs, say) can run in parallel. Each stage declares:

  • its command or code (and the code's version),
  • its dependencies: input files, upstream outputs,
  • the parameters it reads (from a config file such as params.yaml),
  • its outputs: files, models, metrics.

Two properties make such a pipeline trustworthy. Idempotence: running a stage twice on the same inputs gives the same outputs and has no other effect (no appending to a table, no "send email"), so a retry after a crash is safe. Determinism of each stage (fixed seeds, see reproducibility) makes "the same inputs" mean "the same outputs", which is what allows caching.

Caching by input hashes

If a stage is a deterministic function of its inputs, its outputs only need recomputing when an input changes. So the runner computes a key for each stage from everything it depends on (hashes of its input data, its parameter values, its code version) and stores the key in a lock file after a successful run. Next time, an unchanged key and present outputs mean the stage is skipped. A change upstream changes an output's hash, which changes the keys of all stages downstream: invalidation propagates automatically, and nothing else reruns.

From scratch: a caching pipeline runner

Four stages on a toy credit data set (400 rows, income and a default label, 8 rows with a missing income): prepare drops incomplete rows, split makes a 75/25 split, train fits a one-parameter rule (predict default when income is below a quantile of training incomes; a stand-in for a real model, to keep the focus on the runner), evaluate scores it on the held-out 25 %. graphlib.TopologicalSorter from the standard library gives the run order.

python · try it yourself
import hashlib, json
from graphlib import TopologicalSorter
import numpy as np

def h(obj) -> str:
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()[:10]

# --- the stages: pure functions of their inputs and params -----------------------------------
def prepare(raw, p):
    rows = [r for r in raw if r[0] is not None]                       # drop rows with a missing income
    return {"clean": rows}

def split(clean, p):
    rng = np.random.default_rng(p["seed"])
    idx = rng.permutation(len(clean)).tolist()
    n_test = int(len(clean) * p["test_share"])
    return {"train": [clean[i] for i in idx[n_test:]], "test": [clean[i] for i in idx[:n_test]]}

def train(train, p):
    xs = np.array([r[0] for r in train]); ys = np.array([r[1] for r in train])
    thr = float(np.quantile(xs, p["quantile"]))                        # a one-parameter "model"
    return {"model": {"threshold": round(thr, 3), "rule": "default if income < threshold"}}

def evaluate(model, test, p):
    acc = np.mean([(r[0] < model["threshold"]) == r[1] for r in test])
    return {"metrics": {"accuracy": round(float(acc), 3), "n_test": len(test)}}

STAGES = {   # name: (function, inputs, params it reads, outputs)
    "prepare":  (prepare,  ["raw"],            [],                     ["clean"]),
    "split":    (split,    ["clean"],          ["seed", "test_share"], ["train", "test"]),
    "train":    (train,    ["train"],          ["quantile"],           ["model"]),
    "evaluate": (evaluate, ["model", "test"],  [],                     ["metrics"]),
}

def repro(store, params, lock):
    producer = {o: name for name, (_, _, _, outs) in STAGES.items() for o in outs}
    graph = {name: {producer[i] for i in ins if i in producer} for name, (_, ins, _, _) in STAGES.items()}
    ran = []
    for name in TopologicalSorter(graph).static_order():
        fn, ins, pnames, outs = STAGES[name]
        key = h({"code": fn.__name__, "deps": {i: h(store[i]) for i in ins},
                 "params": {k: params[k] for k in pnames}})               # everything the stage depends on
        if lock.get(name) == key and all(o in store for o in outs):
            continue                                                       # same inputs: reuse the outputs
        store.update(fn(*[store[i] for i in ins], {k: params[k] for k in pnames}))
        lock[name] = key
        ran.append(name)
    return ran

rng = np.random.default_rng(0)
income = rng.normal(50, 15, 400).round(1)
default = (income + rng.normal(0, 12, 400) < 40).astype(int)
raw = [[None if i % 50 == 0 else float(x), int(d)] for i, (x, d) in enumerate(zip(income, default))]

store, lock = {"raw": raw}, {}
params = {"seed": 0, "test_share": 0.25, "quantile": 0.1}
print("run 1: ran", repro(store, params, lock), store["model"]["threshold"], store["metrics"])
print("run 2: ran", repro(store, params, lock))
params["quantile"] = 0.3
print("quantile 0.3: ran", repro(store, params, lock), store["model"]["threshold"], store["metrics"])
store["raw"] = raw + [[22.0, 1], [80.0, 0]]
print("new raw rows: ran", repro(store, params, lock), store["model"]["threshold"], store["metrics"])
run 1: ran ['prepare', 'split', 'train', 'evaluate'] 30.73 {'accuracy': 0.806, 'n_test': 98}
run 2: ran []
quantile 0.3: ran ['train', 'evaluate'] 40.19 {'accuracy': 0.786, 'n_test': 98}
new raw rows: ran ['prepare', 'split', 'train', 'evaluate'] 40.6 {'accuracy': 0.765, 'n_test': 98}
  • Run 1 runs all four stages in dependency order: the threshold is 30.73, accuracy 0.806 on 98 held-out rows.
  • Run 2 runs nothing: every key matches the lock.
  • Changing quantile (a parameter only train reads) reruns train and, because the model's hash changed, evaluate. prepare and split are reused. The new threshold 40.19 scores 0.786.
  • Two new raw rows change the hash of raw, so everything downstream reruns, with a new split and a threshold of 40.6.

The held-out score is printed to show what reruns, not to choose quantile; picking a parameter by this number would be tuning on the test set. Note what the key contains: the code name stands in for a code version here, and a real runner hashes the stage's source files too, otherwise a bug fix in train would not trigger a rerun.

The same with DVC: dvc.yaml and dvc repro

DVC implements exactly this. Stages go in dvc.yaml with cmd, deps, params, outs and metrics; dvc repro runs what is out of date and records the hashes of every dependency and output in dvc.lock (committed to Git, so each commit pins the exact data, parameters and outputs of its pipeline). The recorded example (DVC 3.67) has two stages for the running example: prepare writes a 75/25 train/validation split of the 2,000 synthetic rows, train fits the scaled logistic regression with C from params.yaml and writes model.pkl and metrics.json (validation AUC on 500 rows). Outputs listed under outs go into the DVC cache; the small metrics file is kept in Git (cache: false).

python · try it yourself
import os, subprocess, sys, textwrap
import dvc            # the import marks the example as recorded

os.makedirs("proj"); os.chdir("proj")
def sh(*args, show=True):
    r = subprocess.run(list(args), capture_output=True, text=True)
    if show:
        print(r.stdout + r.stderr, end="")
def dvc_(*args):
    print("$ dvc " + " ".join(args)); sh(sys.executable, "-m", "dvc", *args)
def commit(msg):
    sh("git", "add", "-A")
    sh("git", "-c", "user.name=ana", "-c", "user.email=ana@example.com", "commit", "-q", "-m", msg)

def write(path, text):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w") as f:
        f.write(textwrap.dedent(text).lstrip())

write("params.yaml", """
    prepare:
      val_share: 0.25
      seed: 0
    train:
      C: 0.1
""")
write("src/prepare.py", """
    import yaml, numpy as np, pandas as pd
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    p = yaml.safe_load(open("params.yaml"))["prepare"]
    X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
    df = pd.DataFrame(X, columns=[f"f{i}" for i in range(8)]).assign(y=y)
    tr, va = train_test_split(df, test_size=p["val_share"], random_state=p["seed"], stratify=df.y)
    tr.to_csv("data/train.csv", index=False); va.to_csv("data/val.csv", index=False)
""")
write("src/train.py", """
    import json, pickle, yaml, pandas as pd
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import roc_auc_score
    p = yaml.safe_load(open("params.yaml"))["train"]
    tr, va = pd.read_csv("data/train.csv"), pd.read_csv("data/val.csv")
    m = make_pipeline(StandardScaler(), LogisticRegression(C=p["C"])).fit(tr.drop(columns="y"), tr.y)
    pickle.dump(m, open("model.pkl", "wb"))
    auc = roc_auc_score(va.y, m.predict_proba(va.drop(columns="y"))[:, 1])
    json.dump({"val_auc": round(auc, 4), "n_val": len(va)}, open("metrics.json", "w"))
""")
write("dvc.yaml", """
    stages:
      prepare:
        cmd: python src/prepare.py
        deps: [src/prepare.py]
        params: [prepare.val_share, prepare.seed]
        outs: [data/train.csv, data/val.csv]
      train:
        cmd: python src/train.py
        deps: [src/train.py, data/train.csv, data/val.csv]
        params: [train.C]
        outs: [model.pkl]
        metrics:
          - metrics.json:
              cache: false
""")
os.makedirs("data")
sh("git", "init", "-q"); sh(sys.executable, "-m", "dvc", "init", "-q")
dvc_("dag")
dvc_("repro")
commit("pipeline v1")
dvc_("repro")
with open("params.yaml") as f:
    text = f.read()
with open("params.yaml", "w") as f:
    f.write(text.replace("C: 0.1", "C: 0.01"))
dvc_("params", "diff")
dvc_("repro")
dvc_("metrics", "diff")
$ dvc dag
+---------+
| prepare |
+---------+
      *
      *
      *
 +-------+
 | train |
 +-------+
$ dvc repro
Running stage 'prepare':
> python src/prepare.py
Generating lock file 'dvc.lock'
Updating lock file 'dvc.lock'

Running stage 'train':
> python src/train.py
Updating lock file 'dvc.lock'

To track the changes with git, run:

	git add .gitignore dvc.lock data/.gitignore

To enable auto staging, run:

	dvc config core.autostage true
Use `dvc push` to send your updates to remote storage.
$ dvc repro
Stage 'prepare' didn't change, skipping
Stage 'train' didn't change, skipping
Data and pipelines are up to date.
$ dvc params diff
Path         Param    HEAD    workspace
params.yaml  train.C  0.1     0.01
$ dvc repro
Stage 'prepare' didn't change, skipping
Running stage 'train':
> python src/train.py
Updating lock file 'dvc.lock'

To track the changes with git, run:

	git add dvc.lock

To enable auto staging, run:

	dvc config core.autostage true
Use `dvc push` to send your updates to remote storage.
$ dvc metrics diff
Path          Metric    HEAD    workspace    Change
metrics.json  val_auc   0.9328  0.9298       -0.003

What happened, step by step:

  • dvc dag draws the graph DVC derived from the declarations: train depends on prepare because it reads data/train.csv, which prepare outputs.
  • The first dvc repro runs both stages and writes dvc.lock; DVC also adds the outputs to .gitignore files and reminds you to commit (git add ... dvc.lock).
  • The second dvc repro, after the commit, skips both: Stage 'prepare' didn't change, skipping.
  • After editing train.C from 0.1 to 0.01, dvc params diff shows the change against the last commit (HEAD), and dvc repro reruns only train: prepare does not read train.C.
  • dvc metrics diff compares metrics.json with the committed version: validation AUC 0.9328 with C = 0.1, 0.9298 with C = 0.01, a change of -0.003 (on 500 validation rows, within noise). dvc metrics show prints the current values alone, and dvc exp run (DVC experiments) runs parameter variations without a commit for each, as a lightweight tracker.

sklearn.pipeline.Pipeline is a different pipeline

The word means two things, and both appear in the same project:

scikit-learn Pipeline workflow pipeline (DVC, Airflow, ...)
What it chains transformers and an estimator: StandardScaler() then LogisticRegression() whole jobs: ingest, validate, prepare, train, evaluate, register
Runs inside one Python process, on arrays in memory as separate processes or containers, on files, tables, buckets
Purpose fit preprocessing on training data only, ship preprocessing and model as one object (pipelines) order, caching, retries, scheduling, lineage of the whole training process
Saved as one model artifact a DAG definition plus a lock file or run history

The model a workflow pipeline produces is very often a scikit-learn Pipeline, as model.pkl is here: the preprocessing travels with the model into serving, which prevents training/serving skew.

Orchestrators

DVC runs a pipeline on one machine when you call it. Production pipelines also need a schedule (retrain every night, or when new data lands), retries, distribution over many machines or a Kubernetes cluster, backfills (run the pipeline for past dates), alerts and a UI with run history. Those are the jobs of a workflow orchestrator. The common ones, from memory (features change quickly; check current docs):

Tool Pipelines are Runs on Typical use
Apache Airflow Python DAGs of tasks (operators, or the @task TaskFlow API) a scheduler plus workers (Celery, Kubernetes) general data engineering, scheduled batch jobs; the most widespread
Kubeflow Pipelines Python functions compiled to a pipeline spec; each step a container Kubernetes (via Argo Workflows by default) ML on Kubernetes, with caching of step outputs
Prefect plain Python functions decorated with @flow and @task anywhere Python runs, workers pull work Pythonic workflows with dynamic structure
Dagster software-defined assets (the tables and models) rather than tasks its daemon plus executors, Kubernetes data platforms that think in terms of data products and lineage
Argo Workflows YAML custom resources, each step a container Kubernetes, natively container-native CI and ML steps on Kubernetes

Others in the same space: Metaflow, Flyte, ZenML, and the managed pipelines of cloud ML platforms (SageMaker Pipelines, Vertex AI Pipelines, Azure ML pipelines). The principles of this lesson carry over: stages with declared inputs and outputs, idempotent tasks, caching where outputs are deterministic, and the pipeline definition versioned with the code. A CI/CD system often triggers the pipeline; the orchestrator runs it.

Pitfalls

  • Undeclared dependencies. A stage that reads a file not listed in its deps (a lookup table, an environment variable, "today's date") will be skipped when that input changes, and the cache serves stale results. Every input must be declared.
  • Non-deterministic stages. A stage without fixed seeds produces new hashes on every run and invalidates everything downstream.
  • Side effects in stages. A stage that appends to a database or sends a notification is not idempotent: retries and reruns duplicate the effect. Make outputs files or full replacements, and put notifications at the end.
  • Caching across a library upgrade. The key usually does not include the installed library versions; after an upgrade, force a rerun (dvc repro --force) or add the lockfile of the environment as a dependency.
  • Mixing up the two kinds of pipeline, for example fitting a scaler in a prepare stage on all rows before split: that is leakage. Fit preprocessing inside the model's scikit-learn Pipeline, on training rows.

Practice

  1. In the from-scratch runner, which stages rerun if only test_share changes? And if only the code of evaluate changes (in a runner that hashes source files)?
  2. Why must the hash key include the parameter values a stage reads, and only those?
  3. A train stage reads data/train.csv and also config/features.json, but features.json is not in its deps. What goes wrong?
Answers
  1. test_share is read by split, so split, train and evaluate rerun (prepare is reused). A change of evaluate's code reruns only evaluate.
  2. Parameter values are inputs: changing one changes the output, so the cached output must not be reused. Including parameters the stage does not read would rerun it needlessly (in the DVC example, prepare was not rerun when train.C changed because it does not declare train.C).
  3. Editing the feature list does not change train's key, so dvc repro skips the stage and keeps serving the model trained with the old features. Add the file to deps.

Test yourself

When can a pipeline stage safely be skipped?

  1. When it ran yesterday
  2. When the hashes of its code, inputs and parameters equal those recorded at its last successful run and its outputs exist
  3. When its outputs are large
  4. When it is not the last stage

In the DVC example, train.C changed from 0.1 to 0.01. What did dvc repro do?

  1. Reran both stages
  2. Skipped prepare and reran train
  3. Reran nothing
  4. Reran only prepare

What makes a stage idempotent?

  1. It runs fast
  2. Running it twice on the same inputs gives the same outputs and no extra side effects
  3. It has no parameters
  4. It uses a GPU

What is the main difference between a scikit-learn Pipeline and an Airflow or DVC pipeline?

  1. None
  2. The first chains preprocessing and a model into one object in one process; the second orchestrates whole jobs with ordering, caching and scheduling
  3. Airflow pipelines cannot train models
  4. scikit-learn pipelines run on Kubernetes