How to Set Up CI/CD for Machine Learning Models with GitHub Actions

Shipping a web app is a solved problem: run the tests, build the image, deploy. Shipping a machine learning model is not the same game. A model is not just code. It is code plus training data plus hyperparameters plus a random seed, and retraining on the same pipeline next week can produce a different artifact. If your deployment story is “someone ran a notebook and copied a .pkl file to production,” you do not have a deployment story. This guide builds you one with GitHub Actions: a pipeline that trains, validates, registers, deploys, and rolls back models automatically.

How ML CI/CD differs from regular CI/CD

The mental shift is small but important. In a normal pipeline, the artifact under test is deterministic source code. In ML, the artifact is the product of a stochastic process, and quality is measured against data, not just unit tests.

Regular CI/CD ML CI/CD
Trigger Code change Code change, data change, schedule, or metric drift
Artifact tested Compiled binary or container Trained model plus training metrics
Test oracle Assertions that must pass Statistical thresholds: accuracy, F1, latency budgets
Failure mode Build breaks Silent quality regression: the model builds fine but predicts worse
Rollback unit Previous release tag Previous model version from the registry

Every decision below exists to catch that silent quality regression before it reaches users.

The five pipeline stages

A practical ML pipeline has five stages, and each one maps to a GitHub Actions job:

  1. Train: install dependencies, run the training script, emit a model file and a metrics report.
  2. Validate: compare new metrics against the production baseline. Block deployment if the model regressed.
  3. Register: store the approved model with a version, training config, and metrics, so any deployment can point at an immutable artifact.
  4. Deploy: promote the model through staging to production.
  5. Monitor: watch prediction quality and latency, and trigger retraining when reality drifts.

We will implement the first four as workflows now and cover monitoring as a lightweight addition at the end.

Repository layout that keeps it sane

Before writing YAML, fix the repo structure. Training scripts, configs, and workflow files must live in predictable places or the pipeline becomes archaeology:

ml-cicd/
  ├── .github/workflows/
  │     ├── train.yml
  │     ├── validate.yml
  │     └── deploy.yml
  ├── configs/
  │     └── baseline.yaml
  ├── src/
  │     ├── train.py
  │     ├── evaluate.py
  │     └── check_metrics.py
  ├── requirements.txt
  └── Dockerfile

Pin everything in requirements.txt with exact versions. A training run that installs the latest scikit-learn today and a different latest next month is a source of nondeterminism you can delete in one line.

Workflow 1: train and evaluate on every push

The training workflow fires when training code or configs change, and can also be launched manually for scheduled retraining:

name: train
on:
  push:
    paths:
      – ‘src/**’
      – ‘configs/**’
      – ‘requirements.txt’
  workflow_dispatch:

jobs:
  train:
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      – uses: actions/checkout@v4
      – uses: actions/setup-python@v5
        with:
          python-version: ‘3.11’
          cache: ‘pip’
      – run: pip install -r requirements.txt
      – run: python src/train.py –config configs/baseline.yaml
        env:
          PYTHONHASHSEED: ’42’
      – run: python src/evaluate.py –model artifacts/model.pkl –out metrics.json
      – uses: actions/upload-artifact@v4
        with:
          name: model-${{ github.sha }}
          path: |
            artifacts/model.pkl
            metrics.json

Two details matter here. First, the artifact is named with the commit SHA, which makes it immutable and traceable back to the exact code and config that produced it. Second, train.py must set every random seed it touches (numpy, the framework, the OS hash seed) and write metrics.json with the same keys on every run. Your validation gate can only compare what is consistent.

Workflow 2: validation gates that block bad models

A green build means nothing if the model got worse. The validation workflow downloads the new metrics and the current production baseline, then fails the run if the new model regresses past a threshold:

import json, sys

with open(‘metrics.json’) as f:
    new = json.load(f)
with open(‘production_metrics.json’) as f:
    prod = json.load(f)

delta = new[‘accuracy’] – prod[‘accuracy’]
print(f”new accuracy {new[‘accuracy’]:.4f} vs production {prod[‘accuracy’]:.4f}”)

if delta < -0.005:
    print(‘REGRESSION: accuracy dropped more than 0.5 points. Blocking deploy.’)
    sys.exit(1)

if new[‘p99_latency_ms’] > 200:
    print(‘LATENCY: p99 inference latency exceeds the 200ms budget. Blocking deploy.’)
    sys.exit(1)

print(‘Validation passed.’)

Wire this as a job that runs after training with needs: [train], downloads both artifacts, and runs the check. Exit code 1 fails the job, and a failed job never promotes to deploy. Keep thresholds in a config file rather than hardcoded, and review them whenever the product’s tolerance changes. A gate that is never allowed to fail is decoration.

Workflow 3: deploy to staging, then promote

Only models that pass validation reach this workflow. Use GitHub environments so production requires manual approval while staging deploys automatically:

name: deploy
on:
  workflow_run:
    workflows: [‘train’]
    types: [completed]
    branches: [main]

jobs:
  staging:
    if: ${{ github.event.workflow_run.conclusion == ‘success’ }}
    runs-on: ubuntu-latest
    environment: staging
    steps:
      – uses: actions/download-artifact@v4
        with:
          name: model-${{ github.sha }}
      – run: ./scripts/push_to_registry.sh model.pkl staging

  production:
    needs: [staging]
    runs-on: ubuntu-latest
    environment: production
    steps:
      – run: ./scripts/promote.sh staging production model-${{ github.sha }}

The registry script tags the artifact with the commit SHA in your model registry (MLflow, Weights and Biases, or even a versioned S3 bucket with a manifest). Promotion never re-uploads: it re-points the production alias at the SHA that already passed staging. Because every model is immutable and addressable by SHA, rollback is one command: point production back at the previous SHA and rerun the deploy workflow.

Monitoring and closing the loop

A pipeline without monitoring retrains on a schedule and hopes. Log prediction distributions and p99 latency from your serving layer, and compare them weekly against the training baseline. When a drift check trips, fire the training workflow remotely with workflow_dispatch through the GitHub API and let the same gates decide whether the new model is fit. Manual retraining triggered by a monitoring alert is a fine v1; full automation comes after you trust the gates.

Common pitfalls

  • Training on GitHub-hosted runners without caching. Pip installs and dataset downloads on every run turn a 10-minute job into a 40-minute one. Cache dependencies and keep datasets outside the runner’s ephemeral disk.
  • Nondeterministic training. Unset seeds mean the same commit produces different metrics, and your gate starts failing on noise. Fix seeds in code and in the workflow environment.
  • Secrets in training code. Cloud credentials belong in GitHub Secrets or OIDC, never in configs committed to the repo.
  • No timeouts. A hung training job burns runner minutes silently. Set timeout-minutes on every job.
  • Skipping staging. Latency and serving bugs only appear under realistic traffic. The staging environment exists to catch what metrics cannot.

Key takeaways

  • Version everything: code, config, data snapshot reference, and the resulting artifact.
  • Name artifacts with the commit SHA so every model is immutable and traceable.
  • Gate on metrics, not just exit codes: a model that builds but regresses must fail the pipeline.
  • Deploy through staging with environment approvals before production.
  • Make rollback a one-command promotion of the previous model version.

With these five stages wired into GitHub Actions, retraining stops being a notebook ritual and becomes a repeatable release. The model that reaches your users is the one that earned it. The same release discipline applies to ordinary services, and our comparison of the best CI/CD tools shows how Jenkins, GitHub Actions, and GitLab CI each approach it.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.