AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⚙ML Development & MLOps
  1. The ML development stack
  2. The ML lifecycle & MLOps maturity
  3. Experiment tracking with MLflow
  4. Model Registry, data versioning & lineage
  5. Deployment & model serving
  6. Monitoring, data drift & concept drift
  7. CI/CD, continuous training & feature stores
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/ML Development & MLOps

CI/CD, continuous training & feature stores

Test data, features and models automatically; build a GitHub Actions pipeline with a model quality gate; add continuous training; and avoid training-serving skew with a feature store.

Advanced~24 min·5 references
Key terms
CI/CDMLOpsFeature storeModel registryDVC (Data Version Control)Model monitoringBaseline

In normal software, CI/CD means every change is automatically built and tested (Continuous Integration) and can be released safely at any time (Continuous Delivery/Deployment). ML adds two twists: the system's behaviour depends on data as much as on code, and models decay, so you also need Continuous Training (CT) — automatically retraining and validating models as new data arrives[1].

≈
A factory with quality control at every station
A car factory doesn't test only the finished car. Steel is checked on arrival (data tests), each part is measured at its station (unit tests), the assembled car is driven on a test track (model evaluation), and only cars that pass all checks leave the gate (quality gate). CT is the assembly line restarting automatically whenever a fresh batch of steel arrives.

CI vs CD vs CT in ML

PracticeTriggered byWhat runsOutput
CIPull request / pushLint, unit tests for features, data-schema tests, a quick training smoke test on a small sampleGreen/red check on the PR
CDMerge to main / new approved model versionBuild Docker image, deploy pipeline or serving service, canary, rollback on failureRunning service / pipeline
CTSchedule, new data, drift alertFull training pipeline → evaluation → quality gate → registryNew model version (+ alias if it wins)
Loading interactive…
CI, CT and CD as three lanes of one pipeline. Walk through it from a git push to production, and tap the small gate circle to see the promotion rule. Notice that two different things start the training pipeline — a code merge and the retraining loop coming back from monitoring — and that nothing reaches users without passing the gate.

What to test: the ML Test Score

Breck et al. (Google) proposed a rubric of concrete tests in four areas — data, model development, ML infrastructure and monitoring — to measure production readiness and reduce technical debt[2]. Examples you can automate:

  • Data: schema and types, allowed ranges, null rates, label balance, no duplicate IDs, no train/test overlap, feature expectations encoded as tests.
  • Features & code: unit tests for every transformation (edge cases: zeros, missing values, unseen categories).
  • Model: beats the Baseline and the current champion; no slice regresses; invariance tests (changing a customer's name must not change the score); a tiny overfit test (can the model memorise 32 examples?).
  • Infrastructure: training is reproducible, the serving model gives the same predictions as offline (no training-serving skew), the model loads and answers within the latency budget, rollback works.
python
import numpy as np
import pandas as pd
import pytest

@pytest.fixture(scope="module")
def df():
    return pd.read_parquet("data/processed/train.parquet")

def test_schema(df):
    expected = {"customer_id", "tenure_months", "monthly_charges", "contract", "churned"}
    assert expected <= set(df.columns)

def test_ranges_and_nulls(df):
    assert df["tenure_months"].between(0, 600).all()
    assert (df["monthly_charges"] > 0).all()
    assert df["churned"].isin([0, 1]).all()
    assert df["monthly_charges"].isna().mean() < 0.01

def test_no_duplicate_customers(df):
    assert df["customer_id"].is_unique

# --- model behaviour tests ---------------------------------------------
from src.model import load_model, predict_proba   # your own code

def test_invariance_to_irrelevant_field():
    m = load_model()
    a = pd.DataFrame([{"tenure_months": 5, "monthly_charges": 70.0,
                       "contract": "monthly", "customer_name": "Ana"}])
    b = a.assign(customer_name="Budi")
    assert np.isclose(predict_proba(m, a), predict_proba(m, b)).all()

def test_directional_expectation():
    m = load_model()
    short = pd.DataFrame([{"tenure_months": 1, "monthly_charges": 90.0, "contract": "monthly"}])
    loyal = short.assign(tenure_months=60, contract="two_year")
    assert predict_proba(m, short)[0] > predict_proba(m, loyal)[0]
tests/test_data.py and tests/test_model.py — run with pytest

A GitHub Actions pipeline for ML

yaml
name: ml-pipeline
on:
  pull_request:
  push:
    branches: [main]
  schedule:
    - cron: "0 3 * * 1"          # continuous training: Mondays 03:00 UTC
  workflow_dispatch:              # manual "retrain now" button

jobs:
  test-train-gate:
    runs-on: ubuntu-latest
    env:
      MLFLOW_TRACKING_URI: ${{ secrets.MLFLOW_TRACKING_URI }}
      AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
      - run: pip install -r requirements.txt     # includes dvc[s3], mlflow, pytest

      - name: Lint and unit tests
        run: |
          ruff check src tests
          pytest -q tests/unit

      - name: Pull versioned data
        run: dvc pull

      - name: Data validation tests
        run: pytest -q tests/test_data.py

      - name: Train (sample on PRs, full data on main/schedule)
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            python -m src.train --config configs/ci_sample.yaml
          else
            python -m src.train --config configs/full.yaml --register-as challenger
          fi

      - name: Model tests + quality gate
        if: github.event_name != 'pull_request'
        run: |
          pytest -q tests/test_model.py
          python -m src.quality_gate --model churn-clf --min-gain 0.005
.github/workflows/ml.yaml — CI on every PR, CT every Monday. Secrets come from the repository settings, never from code.
python
import argparse, sys
from mlflow import MlflowClient

p = argparse.ArgumentParser()
p.add_argument("--model"); p.add_argument("--min-gain", type=float, default=0.0)
args = p.parse_args()

client = MlflowClient()
def score(alias):
    mv = client.get_model_version_by_alias(args.model, alias)
    return mv, client.get_run(mv.run_id).data.metrics["val_pr_auc"]

challenger, s_new = score("challenger")
champion, s_old = score("champion")
print(f"challenger v{challenger.version}: {s_new:.4f}  champion v{champion.version}: {s_old:.4f}")

if s_new < s_old + args.min_gain:
    sys.exit("Quality gate FAILED - champion stays")     # non-zero exit fails the CI job
client.set_registered_model_alias(args.model, "champion", challenger.version)
print("Promoted to @champion")
src/quality_gate.py — promote the challenger only if it beats the champion

Notice the pattern: tests and training run in CI, results land in MLflow, and the registry alias is the deployment contract. The serving service (previous lesson) loads @champion, so a successful gate deploys the new model without changing serving code; a failed gate leaves production untouched. GitHub Actions workflows are YAML files in .github/workflows/ triggered by events like pull_request, push, schedule and workflow_dispatch[3].

knobquality-gate margin (min gain)
What it is
How much the challenger must beat the champion on the validation metric to be promoted.
↑ If you increase it
Avoids churn from noise-level “wins”; may reject genuinely better models when gains are small.
↓ If you decrease it
0 or negative (“not worse than”) keeps models fresh after drift, but random fluctuations can swap models back and forth.
Typical values
About the run-to-run standard deviation of the metric (measure it with several seeds).
knobCI training sample size
What it is
How much data the quick training smoke test on each pull request uses.
↑ If you increase it
Catches more problems (e.g. convergence issues) but CI gets slow and costly; developers start skipping it.
↓ If you decrease it
Fast feedback (minutes), but only proves the pipeline runs end to end, not that the model is good.
Typical values
A fixed, versioned sample of 1–5% of the data or a few thousand rows; keep CI under ~10 minutes.
knobCT schedule (cron)
What it is
How often the full continuous-training pipeline runs automatically (in addition to drift-triggered runs).
↑ If you increase it
More frequent retrains track fast-changing data, at higher compute cost and more model churn to monitor.
↓ If you decrease it
Cheaper and calmer, but the model ages between runs.
Typical values
Daily for news/ads, weekly–monthly for most business models.

Feature stores and training-serving skew

Training-serving skew happens when a feature is computed one way in the training pipeline (e.g. SQL over historical tables) and another way in the online service (e.g. Python over a live request) — the model then sees subtly different inputs in production. A [[feature-store]] defines each feature once and serves it from two places: an offline store (historical values with point-in-time-correct joins, so training never peeks at future values) and an online store (latest values with millisecond lookups for serving)[4].

python
from feast import FeatureStore
import pandas as pd

store = FeatureStore(repo_path="feature_repo")   # after: feast apply
features = ["customer_stats:avg_monthly_charges_90d",
            "customer_stats:support_tickets_30d"]

# Training: point-in-time-correct join against historical labels
labels = pd.read_parquet("data/labels.parquet")  # customer_id, event_timestamp, churned
train_df = store.get_historical_features(entity_df=labels, features=features).to_df()

# Serving: latest values from the online store (after feast materialize-incremental)
online = store.get_online_features(
    features=features, entity_rows=[{"customer_id": 1001}]).to_dict()
Feast: the same feature definitions for training and serving
knobfeature materialisation interval (freshness)
What it is
How often feature values are computed and copied from the offline source into the online store.
↑ If you increase it
Materialising more often (or streaming) gives fresher features and better predictions for fast-moving signals, at higher infrastructure cost.
↓ If you decrease it
Cheaper, but serving sees stale values — a form of skew if training used fresher ones.
Typical values
Hourly–daily batch for slow aggregates; streaming for minute-level signals (fraud).
!
CI/CD-for-ML pitfalls
• Only testing code, never data — most ML incidents start with data. • Full training on every PR → hour-long CI that people bypass. • Automatic promotion with no gate, or a gate on a single noisy metric with no slice checks. • Secrets (cloud keys, tracking tokens) committed in YAML instead of repository secrets. • Non-deterministic tests (random seeds not fixed) → flaky CI. • A feature computed differently online and offline because no one owns a single definition.
▸Go deeper: how the ML Test Score is computed

In Breck et al.'s rubric each test earns half a point if it is done manually with documented results and a full point if it is automated and runs repeatedly. Points are summed per section (data, model, infrastructure, monitoring), and the final score is the minimum of the four section scores — a team with perfect model tests but no monitoring still scores low, because the weakest area is what breaks in production[2]. Combined with Google's maturity levels (manual → pipeline automation → CI/CD automation)[1], it gives a practical roadmap: automate the weakest section first.

Kreuzberger et al. list the same building blocks as core MLOps components: source-code repository, CI/CD component, workflow orchestration, feature store, model training infrastructure, model registry, ML metadata store and monitoring[5].

Quiz

1.
What does Continuous Training (CT) add on top of classic CI/CD?
2.
A feature avg_spend_30d is computed in SQL for training and in Python for the API, with a small rounding difference. What is this problem called?
3.
In the ML Test Score, a team has perfect data and model tests but zero monitoring tests. Its final score is…
4.
Your quality gate uses --min-gain 0 and the champion changes almost every week, sometimes swapping back to an older version. What should you try?
5.
Why is a point-in-time-correct join important when building training data from a feature store?
Score: 0/5

References

  1. [1]
    MLOps: Continuous delivery and automation pipelines in machine learning
    ArticleGoogle Clouddocs.cloud.google.com
  2. [2]
    The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction
    PaperBreck et al.2017research.google
  3. [3]
    GitHub Actions documentation
    DocsGitHubdocs.github.com
  4. [4]
    Feast documentation
    DocsFeastdocs.feast.dev
  5. [5]
    Machine Learning Operations (MLOps): Overview, Definition, and Architecture
    PaperKreuzberger et al.2022arxiv.org
← Previous
Monitoring, data drift & concept drift
Next → · Advanced & Frontier Topics
Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding