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

      CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes

      A candidate model passes all 4 tests and beats the champion overall by one point, and the gate still blocks it, because new customers drop from 44.51% to 40.66%. The rules, the exit code, a pinned validation file and the CI job chain.

      Chaand Sheikh

      ·27 November 2026Pipelines, CI/CD and Cloud

      What you will learn

      • Tell code tests apart from a model quality gate
      • Write gate rules before the candidate arrives: a minimum overall gain and a maximum drop per group
      • Return a non-zero exit code so a failing gate stops the CI job
      • Protect the gate's data: pin the validation file with a hash and keep the final test set closed

      Before you start

      • CI with GitHub Actions
      • Slice Evaluation and Fairness Checks
      • Train-Test Split and Data Leakage

      CI with GitHub Actions made every push run the tests. That checks the code. But a model can have perfect code and still be worse than the one you're running today. So in this article we put a quality gate on the model itself.

      The idea is a contract: a few rules, written down before the candidate shows up. You'll see a candidate that passes every test, beats the champion overall, and still gets blocked.

      Two words: champion and candidate

      Training gives us a new model. We call it the candidate, and it wants to replace the champion, the model in use today. Tests check its code. The gate judges the model. Only once the gate says yes does it get packaged. (If you've used a model registry, the champion is the version the alias points at; see MLflow registry aliases.)

      Check the jar, taste the sauce

      Think of a restaurant that bottles its own sauce. Someone checks the jar: lid on, label straight, weight right. That's your tests, and they say nothing about what's inside. So someone also opens a jar and tastes it next to the batch they're selling today. That's the gate.

      And one spoon isn't enough, because a batch can taste fine on top and be burnt at the bottom. So you taste in more than one place. In ML, those places are slices: groups of rows, like customer types.

      All green, still worse

      The project has a champion (logistic regression on five columns) and a candidate called lean, a smaller logistic regression that uses only two columns. The data is synthetic, customers we generated ourselves, with two groups: returning and new.

      CANDIDATES = {
          "champion": (LogisticRegression, FEATURES),
          "boosted": (lambda: GradientBoostingClassifier(
              random_state=0), FEATURES),
          "lean": (LogisticRegression, ["x0", "x1"]),
      }

      Pytest says everything is fine:

      ....                                                                     [100%]
      4 passed in 3.54s

      Overall, the champion scores 75.73% accuracy and lean scores 76.73%. One point up. Now split it by group:

      Champion vs lean, overall and by group 75.73 76.73 overall 80.05 81.71 returning (1,318) 44.51 40.66 new (182) champion lean
      Validation accuracy (%) on 1,500 synthetic customers. Lean is up overall and for returning customers, and down for new ones.

      Returning customers go up to 81.71%. New customers go down, from 44.51% to 40.66%. In the validation set there are 1,318 returning customers and 182 new ones, about seven to one, so the big group hid the drop in the average. Every test was green, and the model is still worse for a whole group. (Scoring group by group is the idea behind slice evaluation; here it becomes a rule that can block a release.)

      gate.py: the limits and the score

      Here's the contract. The two limits are set before any candidate arrives:

      MIN_GAIN = 0.005   # overall accuracy must rise by this
      SLICE_DROP = 0.02  # no group may fall by more than this
      
      
      def score(name):
          model, cols = train(name)
          df = load_validation()
          hit = model.predict(df[cols]) == df["y"]
          out = {"overall": round(float(hit.mean()), 4)}
          for g, rows in df.groupby("group"):
              out[g] = round(float(hit[rows.index].mean()), 4)
          return out

      MIN_GAIN: overall accuracy has to rise by at least half a point. SLICE_DROP: no group may fall by more than two points.

      score trains the model and predicts on the validation set. hit is True or False for each row. Overall is the mean of the hits, and a short loop gives each group its own mean.

      check() and the return code

      def check(cand, champ):
          fails = []
          gain = round(cand["overall"] - champ["overall"], 4)
          if gain < MIN_GAIN:
              fails.append(f"overall gain {gain} < {MIN_GAIN}")
          for g in ("returning", "new"):
              drop = round(champ[g] - cand[g], 4)
              if drop > SLICE_DROP:
                  fails.append(f"slice {g} fell by {drop}")
          return fails
      
      
      def main(name):
          if digest(DATA / "validation.csv") != VALIDATION_SHA:
              print("FAIL: validation set changed")
              return 1
          champ, cand = score("champion"), score(name)
          print("champion", champ)
          print("candidate", cand)
          fails = check(cand, champ)
          for f in fails:
              print("FAIL:", f)
          print("GATE", "FAILED" if fails else "PASSED")
          return 1 if fails else 0
      
      
      if __name__ == "__main__":
          sys.exit(main(sys.argv[1]))

      check compares the two sets of scores and collects failures in a list. For lean, the gain is 0.01, which clears 0.005. Returning rose. New fell by 0.0385, more than 0.02, so a failure goes on the list.

      python -m ci_gate.gate lean
      champion {'overall': 0.7573, 'new': 0.4451, 'returning': 0.8005}
      candidate {'overall': 0.7673, 'new': 0.4066, 'returning': 0.8171}
      FAIL: slice new fell by 0.0385
      GATE FAILED

      main returns 1, and sys.exit(1) gives a non-zero exit code. In CI, a non-zero exit code fails the job. That's the whole trick: the gate speaks the same language as pytest.

      Now the other candidate, boosted, through the same rules:

      python -m ci_gate.gate boosted
      champion {'overall': 0.7573, 'new': 0.4451, 'returning': 0.8005}
      candidate {'overall': 0.822, 'new': 0.8516, 'returning': 0.8179}
      GATE PASSED

      Overall 82.2%, new customers 85.16%, the list stays empty, exit code 0. The data is synthetic, so that jump isn't a benchmark. Note that a gate on overall accuracy alone would have passed both candidates.

      Protect the data the gate trusts

      A gate is only as honest as its data. Drop a few hard rows from the validation file, and every candidate looks better, though no model improved. So gate.py pins that file with a fingerprint, a SHA-256 hash:

      # pinned hash of data/validation.csv
      VALIDATION_SHA = (
          "6dfdd5a94b8a75415ff4d6f3043d96a9"
          "d2a1bc28127fe0b955f666a34719d4a6")

      Edit one cell in validation.csv, run boosted again, and the gate refuses before scoring anything:

      FAIL: validation set changed

      The final test set gets a different guard. If you keep tweaking against a score, you slowly fit that score, so the final test stays closed until the end:

      def load_final_test():
          """Final test set. Release day only, never in CI."""
          if os.environ.get("RELEASE_DAY") != "1":
              raise PermissionError("final test is protected")
          return make(1500, seed=3)
      PermissionError: final test is protected

      Anyone can set RELEASE_DAY, so it's a guard rail and not a lock. It stops accidents, not people.

      Connect the gate to the build

      Here's .github/workflows/ci.yml, with three jobs:

      name: CI
      on: [push, pull_request]
      jobs:
        test:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - uses: actions/setup-python@v5
              with:
                python-version: "3.13"
            - run: pip install -e .[dev]
            - run: pytest -q
        gate:
          needs: test
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - uses: actions/setup-python@v5
              with:
                python-version: "3.13"
            - run: pip install -e .
            - run: python -m ci_gate.gate boosted
        package:
          needs: gate
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - uses: actions/setup-python@v5
              with:
                python-version: "3.13"
            - run: pip wheel . --no-deps -w dist
      test, gate, package test pytest -q gate needs: test package needs: gate exit 0 ci_gate-0.1.0-py3-none-any.whl exit 1: red cross, no package
      The gate sits between the tests and the package. A failing gate stops the chain.

      Gate needs test, and package needs gate. If the gate returns 1, package never starts. If it returns 0, package builds the wheel, ci_gate-0.1.0-py3-none-any.whl. GitHub Actions runs this on every push and pull request, and a failing gate shows up as a red cross, so nothing gets merged past it.

      GitHub Actions itself wasn't run for this lesson. Each job's commands were run by hand in a clean python:3.13-slim container: the tests (4 passed), the gate on boosted (GATE PASSED) and the wheel build.

      Common mistakes

      • Treating green tests as a green light. Tests check the jar. Only the gate tastes the sauce.
      • Gating on the average only. Both candidates here pass an overall-only rule. A drop for a small group hides inside the mean.
      • Setting the limits after seeing the result. Then the rule bends to fit the candidate you wanted.
      • An unguarded validation file. If it can change quietly, the gate can be passed quietly.

      Recap

      PieceIn this project
      Rules firstMIN_GAIN = 0.005, SLICE_DROP = 0.02
      Overall and every groupLean: +0.01 overall, new customers −0.0385, GATE FAILED
      Exit code1 fails the CI job, 0 lets package run
      Pinned dataVALIDATION_SHA; any edit gives "validation set changed"
      Closed final testPermissionError unless RELEASE_DAY=1

      Try it yourself: in gate.py, change SLICE_DROP to 0.05, run the gate on lean again, and read what it prints.

      Built this? Share your solution in the StudyEasy AI Community.

      Join free on Skool →
      ← Previous
      CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      Next →
      Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      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
      • Two words: champion and candidate
      • Check the jar, taste the sauce
      • All green, still worse
      • gate.py: the limits and the score
      • check() and the return code
      • Protect the data the gate trusts
      • Connect the gate to the build
      • 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.