Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Machine Learning
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. MLOps and Production ML

      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.

      Chaand Sheikh

      ·27 November 2026Pipelines, CI/CD and Cloud

      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.
      The training pipeline as a DAG, with features failed ingest features baseline train evaluate publish ok failed blocked blocked blocked blocked
      Day 3: features fails, so everything downstream is blocked. Ingest, upstream, stays done.

      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.

      1. Only ingest is ready, so it goes first.
      2. Now features is ready.
      3. After features, two steps are ready, baseline and train. The list is sorted, so baseline goes first and train right after it.
      4. 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
      StepReadsLeaves behind
      ingestdata/tickets.csvraw.csv (first 400 rows)
      featuresraw.csvsplit.joblib (300 train, 100 test)
      baselinesplit.joblibbaseline.json (always guesses low: 0.51)
      trainsplit.joblibmodel.joblib
      evaluatesplit, model, baseline scoremetrics.json (accuracy 0.74)
      publishmodel and metricsa 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.

      Backfill. The same scheduler can run a range of days: 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

      IdeaIn this project
      The pipeline is a graphDAG dictionary: step to what it needs
      Order comes from the needstopo_order, error on a cycle
      Every arrow is a fileraw.csv, split.joblib, baseline.json, model.joblib, metrics.json
      One retry ruleRETRYABLE = (ConnectionError, TimeoutError), 2 retries
      Failure stops only what followsblocked 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 →
      ← Previous
      Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Next →
      Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      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

      Join free on Skool
      Go deeper with a course

      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.

      On this page
      • A car assembly line
      • Day 3: features never recovers
      • A pipeline is a graph
      • The graph is a dictionary
      • Working out the order
      • Every arrow is a file
      • One retry rule, and a rerun
      • Common mistakes
      • Recap
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      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

      Join free on Skool
      Go deeper with a course

      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)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.