Sub topic 8
Stages as a Dependency Graph
This chapter assumes you know Python functions and modules, basic machine learning steps such as training and validation, and the difference between training and test data. It also assumes basic command-line and Git usage.
A training pipeline is easier to reason about when its stages form a dependency graph. A stage is one meaningful operation, such as loading data, splitting data, training a model, or calculating metrics. A dependency says that one stage needs an output from another stage before it can run.
From a list of steps to a graph
A notebook often records training as a sequence:
- Load data.
- Clean data.
- Split data.
- Train a model.
- Evaluate the model.
This order works for one manual run, but it hides important facts. For example, evaluation depends on both the trained model and the test data. A graph makes those relationships explicit.
A directed acyclic graph, or DAG, is a graph whose connections have a direction and never form a loop. In a pipeline:
- A node represents a stage.
- An arrow represents a dependency.
- The arrow points from a producer to a consumer.
- A stage can run only after all its upstream dependencies finish.
- “Acyclic” means a stage cannot eventually depend on itself.
The graph contains a branch. Training and test-set preparation both depend on the split, but they do not depend on each other. An orchestrator can run independent branches in parallel when resources allow.
Give every stage an explicit interface
A stage should expose its inputs and outputs. In Python, a function signature is a simple interface:
from dataclasses import dataclass
@dataclass
class Dataset:
features: list[list[float]]
labels: list[int]
@dataclass
class Split:
train: Dataset
test: Dataset
def load_data() -> Dataset:
return Dataset(
features=[[0.0], [1.0], [2.0], [3.0]],
labels=[0, 0, 1, 1],
)
def split_data(data: Dataset) -> Split:
midpoint = len(data.features) // 2
return Split(
train=Dataset(data.features[:midpoint], data.labels[:midpoint]),
test=Dataset(data.features[midpoint:], data.labels[midpoint:]),
)
def train_model(train: Dataset) -> dict:
return {"threshold": 1.5, "train_rows": len(train.features)}
def evaluate(model: dict, test: Dataset) -> dict:
correct = 0
for features, label in zip(test.features, test.labels):
prediction = int(features[0] >= model["threshold"])
correct += prediction == label
return {"accuracy": correct / len(test.labels)}
def run_pipeline() -> dict:
data = load_data()
split = split_data(data)
model = train_model(split.train)
return evaluate(model, split.test)
if __name__ == "__main__":
print(run_pipeline())split_data depends on load_data because it needs the returned Dataset. train_model depends only on the training portion of the split. evaluate needs both the model and the test portion. These requirements are visible in the function arguments rather than hidden in global variables.
A useful interface describes:
- The type and meaning of each input.
- The type and meaning of each output.
- Whether the stage changes external state.
- What errors it can raise.
- Which files, datasets, or services it reads.
Keep dependencies narrow
A stage should receive the smallest useful input. Passing an entire project directory or a global configuration object makes dependencies difficult to inspect. Passing a specific dataset, model, or parameter makes the graph clearer.
Hidden dependencies are a common source of unreliable runs. Examples include:
- Reading a global variable created by another stage.
- Using the current time without recording it.
- Downloading “latest” data during training.
- Reading a file whose path is not declared.
- Depending on a database table that another stage silently modifies.
If a stage needs a value, pass it as an argument or declare it as a named artifact. An artifact is a file or stored object produced by a stage, such as a cleaned dataset or trained model.
Validate the graph before execution
A valid DAG has an execution order called a topological order. Every producer appears before its consumers. A cycle such as train -> evaluate -> train has no valid order and should be rejected before work begins.
When designing a pipeline, draw the graph first. For each stage, ask what it consumes, what it produces, and whether another stage could run without it. This process often reveals unnecessary work and safe opportunities for parallel execution.
Exercise
Evaluation needs a trained model and a test dataset. The model depends on training data, while the test dataset comes from the same split stage. Which stages must finish before evaluation can run?
Show answer
The split stage and the training stage must finish. The split produces the test dataset and training dataset; training consumes the training dataset and produces the model. Evaluation then consumes the model and test dataset.