CI/CD for ML
CI/CD for ML
Learn how Continuous Integration and Continuous Delivery practices automate the validation, packaging, registration, deployment, promotion, monitoring, and rollback of Machine Learning applications, pipelines, models, data contracts, and infrastructure.
Introduction
Machine Learning systems contain more than application code. Their behavior also depends on data, feature definitions, preprocessing, training configuration, dependency versions, model artifacts, decision thresholds, input schemas, infrastructure, and monitoring policies.
A traditional software CI/CD pipeline validates code and deploys an application build. An ML CI/CD pipeline must additionally validate data contracts, preprocessing logic, model quality, prediction consistency, artifact lineage, serving compatibility, and responsible-use requirements.
Continuous Integration provides rapid evidence about proposed changes. Continuous Delivery prepares an approved release that can be deployed safely. Continuous Deployment automatically promotes a release after all required controls pass.
Learning Objectives
By the End of This Lesson
- Define CI/CD for Machine Learning
- Distinguish Continuous Integration, Delivery, and Deployment
- Explain how ML CI/CD differs from software CI/CD
- Understand Continuous Training
- Identify ML-specific pipeline triggers
- Version code, data, models, schemas, and environments
- Validate data and feature contracts
- Run model-quality and baseline-comparison tests
- Create immutable model and container artifacts
- Separate training from production promotion
- Use development, testing, staging, and production environments
- Apply manual and automated approval gates
- Use rolling, blue-green, canary, and shadow releases
- Manage CI/CD identities and secrets safely
- Scan dependencies, containers, and infrastructure definitions
- Validate a deployment with smoke and consistency tests
- Monitor releases after promotion
- Define fallback and rollback procedures
- Understand GitOps for ML deployments
- Create an ML CI/CD readiness checklist
Prerequisites
Recommended Knowledge
- Git and branch-based development
- Pull requests and code review
- Automated software testing
- ML pipelines
- Model evaluation and monitoring
- Saving and loading models
- Docker fundamentals
- Cloud or Kubernetes deployment
- YAML fundamentals
- Identity and secret-management fundamentals
What Is CI/CD?
| Practice | Purpose | Typical Result |
|---|---|---|
| Continuous Integration | Frequently integrates and validates proposed changes | Tested source revision and validation evidence |
| Continuous Delivery | Creates a release that is ready for controlled deployment | Approved, immutable release candidate |
| Continuous Deployment | Automatically deploys a release after all gates pass | Automatically promoted production release |
| Continuous Training | Runs a controlled training workflow after an approved trigger | Evaluated model candidate |
| Continuous Monitoring | Observes service, data, model, and business behavior | Metrics, alerts, incidents, and improvement evidence |
Software CI/CD vs ML CI/CD
| Area | Software CI/CD | ML CI/CD |
|---|---|---|
| Primary Inputs | Code, configuration, and dependencies | Code, data, features, configuration, models, and dependencies |
| Tests | Unit, integration, security, and performance tests | Software tests plus data, feature, model, fairness, and drift tests |
| Release Artifact | Application package or container image | Application, model, preprocessing, threshold, schema, and metadata |
| Behavior Change | Usually caused by code or configuration changes | Can also be caused by data, labels, retraining, or feature changes |
| Promotion Decision | Software tests and release policy | Software, data, model, operational, risk, and governance evidence |
| Production Monitoring | Availability, errors, latency, and resources | Software signals plus input quality, drift, model quality, and business outcomes |
End-to-End ML CI/CD Architecture
| Layer | Responsibility |
|---|---|
| Source Control | Versions code, configuration, manifests, tests, and documentation |
| CI Runner | Executes automated validation in a controlled environment |
| Data and Artifact Store | Stores versioned data, models, reports, and packages |
| Training Platform | Runs reproducible training and evaluation components |
| Model Registry | Tracks model versions, metrics, lineage, and approval status |
| Container Registry | Stores immutable serving images |
| Deployment Platform | Runs candidate and production inference workloads |
| Monitoring Platform | Tracks service, input, prediction, quality, risk, and business signals |
Source-Control Workflow
Repository Controls
- Use protected branches
- Require pull requests
- Require relevant reviewers
- Require successful automated checks
- Prevent secret commits
- Use signed commits or releases where required
- Restrict direct production changes
- Preserve source revision identifiers
- Use clear commit and release descriptions
What Should Be Versioned?
| Asset | Why It Matters |
|---|---|
| Training Code | Defines candidate-model creation |
| Inference Code | Defines production request processing |
| Data Reference | Identifies training, validation, and test information |
| Feature Definitions | Define model inputs and their calculation semantics |
| Training Configuration | Controls algorithms, parameters, splits, and seeds |
| Model Artifact | Contains approved fitted behavior |
| Decision Threshold | Converts scores into decisions |
| Input and Output Schemas | Define integration contracts |
| Container Image | Defines exact application and runtime content |
| Infrastructure Definition | Defines the deployment environment |
| Monitoring Configuration | Defines baselines, metrics, alerts, and responses |
Continuous Integration Workflow
Check Out the Source
Retrieve the exact proposed revision and required version references.
Create the Test Environment
Install or activate the declared dependencies in an isolated runner.
Validate Code
Run formatting, linting, static analysis, and unit tests.
Validate Data Contracts
Test schemas, feature definitions, ranges, categories, and partition rules.
Run Pipeline Smoke Tests
Execute a small approved dataset through the training workflow.
Validate Model Behavior
Confirm deterministic requirements, output shape, value ranges, and baseline comparisons.
Scan the Change
Review dependencies, containers, secrets, licenses, and infrastructure definitions.
Publish Evidence
Attach test results, metrics, reports, and identified artifacts to the proposed change.
ML-Specific CI Tests
| Test | Purpose |
|---|---|
| Data-Schema Test | Ensures required fields and types remain compatible |
| Data-Quality Test | Validates missingness, ranges, categories, duplicates, and freshness |
| Feature Test | Validates calculation logic and prediction-time availability |
| Leakage Test | Checks partition isolation and prohibited future information |
| Training Smoke Test | Confirms the pipeline can train on controlled data |
| Model-Quality Test | Compares measured results with approved requirements |
| Artifact Test | Confirms save, load, metadata, checksum, and prediction consistency |
| Inference-Contract Test | Checks valid and invalid API input and output |
| Fairness Test | Checks documented group-level criteria where applicable |
| Performance Test | Measures latency, throughput, startup, and resources |
Model-Quality Gate
def evaluate_release_gate(
candidate_metrics,
baseline_metrics,
required_minimums,
required_maximums=None
):
failures = []
required_maximums = (
required_maximums
or {}
)
for metric_name, minimum_value in (
required_minimums.items()
):
candidate_value = (
candidate_metrics.get(
metric_name
)
)
if candidate_value is None:
failures.append(
f"Missing metric: {metric_name}"
)
elif candidate_value < minimum_value:
failures.append(
f"{metric_name} is below "
"the required minimum."
)
for metric_name, maximum_value in (
required_maximums.items()
):
candidate_value = (
candidate_metrics.get(
metric_name
)
)
if candidate_value is None:
failures.append(
f"Missing metric: {metric_name}"
)
elif candidate_value > maximum_value:
failures.append(
f"{metric_name} exceeds "
"the permitted maximum."
)
baseline_f1 = baseline_metrics.get(
"f1"
)
candidate_f1 = candidate_metrics.get(
"f1"
)
if (
baseline_f1 is not None
and candidate_f1 is not None
and candidate_f1 < baseline_f1
):
failures.append(
"Candidate F1 is below baseline F1."
)
return {
"passed": len(
failures
) == 0,
"failures": failures
}
Build Immutable Release Artifacts
Release Package
- Fitted preprocessing and model
- Model metadata
- Input and output schemas
- Class mappings
- Decision threshold
- Dependency or environment definition
- Evaluation report
- Model card
- Artifact checksum
- Application container image
- Infrastructure manifests
docker build \
--tag customer-churn-api:1.0.0 \
.
docker image inspect \
customer-churn-api:1.0.0
Continuous Delivery Workflow
Environment Promotion
| Environment | Purpose |
|---|---|
| Development | Component development and rapid validation |
| Integration Test | Validates interaction with services and data contracts |
| Staging | Runs production-like deployment, security, load, and smoke tests |
| Production | Serves approved users and workloads under operational controls |
Approval Gates
| Gate | Required Evidence |
|---|---|
| Data Approval | Authorized source, quality, lineage, and freshness |
| Model Approval | Metrics, baseline comparison, errors, calibration, and limitations |
| Responsible-AI Approval | Relevant group evaluation, transparency, oversight, and permitted use |
| Security Approval | Identities, secrets, dependencies, images, network, and vulnerabilities |
| Operational Approval | Load tests, alerts, runbooks, fallback, rollback, and ownership |
| Business Approval | Workflow readiness and accepted operating conditions |
Deployment Strategies
| Strategy | Approach | Main Consideration |
|---|---|---|
| Rolling | Gradually replaces old serving instances | Old and new versions coexist temporarily |
| Blue-Green | Maintains separate current and candidate environments | Requires temporary duplicate capacity |
| Canary | Sends a controlled traffic share to the candidate | Requires version-specific monitoring |
| Shadow | Sends production-like requests to the candidate without using its outputs | Requires privacy, capacity, and comparison controls |
| A/B Experiment | Assigns eligible users according to an experimental design | Requires valid allocation and outcome evaluation |
Post-Deployment Validation
Validate Immediately After Deployment
- Health endpoint
- Readiness endpoint
- Model version
- Application version
- Schema version
- Representative valid request
- Representative invalid request
- Prediction consistency
- Authentication and authorization
- Latency and error rate
- Monitoring-event generation
- Fallback availability
import numpy as np
import requests
def verify_deployed_prediction(
endpoint_url,
request_payload,
expected_probability,
authorization_header
):
response = requests.post(
endpoint_url,
json=request_payload,
headers={
"Authorization": (
authorization_header
)
},
timeout=10
)
response.raise_for_status()
response_payload = response.json()
actual_probability = float(
response_payload[
"positive_class_probability"
]
)
np.testing.assert_allclose(
actual_probability,
expected_probability,
rtol=1e-8,
atol=1e-10
)
return response_payload
GitHub Actions CI Example
name: Validate ML Project
on:
pull_request:
push:
branches:
- main
permissions:
contents: read
jobs:
validate:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
- name: Run static checks
run: |
python -m compileall app src tests
- name: Run unit and integration tests
run: |
python -m pytest -v
- name: Validate data contract
run: |
python -m src.validate_data \
--configuration config/ci.json
- name: Run training smoke test
run: |
python -m src.train \
--configuration config/smoke-test.json
- name: Validate generated artifact
run: |
python -m src.validate_artifact \
--artifact pipeline-output/model.joblib
Container Build and Test Job
jobs:
build-container:
needs:
- validate
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Build image
run: |
docker build \
--tag customer-churn-api:test \
.
- name: Start container
run: |
docker run \
--detach \
--name customer-churn-api-test \
--publish 8000:8000 \
customer-churn-api:test
- name: Wait for readiness
run: |
for attempt in $(seq 1 30); do
if curl --fail \
http://127.0.0.1:8000/ready; then
exit 0
fi
sleep 2
done
docker logs customer-churn-api-test
exit 1
- name: Run smoke tests
run: |
python -m tests.container_smoke_test
- name: Show logs on failure
if: failure()
run: |
docker logs customer-churn-api-test
- name: Remove test container
if: always()
run: |
docker rm \
--force \
customer-churn-api-test
Azure Pipelines Example
trigger:
branches:
include:
- main
pr:
branches:
include:
- main
pool:
vmImage: ubuntu-latest
stages:
- stage: Validate
displayName: Validate ML project
jobs:
- job: Test
displayName: Run automated checks
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: "3.12"
- script: |
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
displayName: Install dependencies
- script: |
python -m pytest -v
displayName: Run tests
- script: |
python -m src.validate_data \
--configuration config/ci.json
displayName: Validate data contract
- script: |
python -m src.train \
--configuration config/smoke-test.json
displayName: Run training smoke test
- stage: Package
displayName: Package release
dependsOn:
- Validate
condition: succeeded()
jobs:
- job: Build
steps:
- script: |
docker build \
--tag customer-churn-api:$(Build.BuildId) \
.
displayName: Build immutable image
Continuous Training
Continuous Training automates a repeatable training pipeline when an approved trigger occurs. The output should be a candidate, not an automatically trusted production model.
| Trigger | Required Check |
|---|---|
| New Data | Authorization, completeness, schema, and label maturity |
| Schedule | Whether sufficient new information exists |
| Drift Alert | Whether drift is valid and affects model behavior |
| Code Change | Whether feature or training logic changed intentionally |
| Business Change | Whether the target and success criteria remain appropriate |
| Manual Request | Authorized initiator and documented reason |
Identity and Secret Management
Required Controls
- Separate CI, delivery, and runtime identities
- Grant minimum permissions
- Use temporary workload credentials where supported
- Protect production environments
- Restrict model-registry write access
- Restrict container-registry push access
- Use an approved secret store
- Mask secrets in logs
- Rotate credentials
- Audit privileged pipeline operations
Supply-Chain Security
| Asset | Control |
|---|---|
| Source Code | Review, protected branches, and traceable revisions |
| Third-Party Actions | Review source and use approved immutable references |
| Python Dependencies | Pin, scan, review, and update packages |
| Base Images | Use approved sources and controlled versions |
| Model Artifacts | Verify source, version, checksum, and approval |
| Container Images | Scan, sign where required, and record digests |
| Infrastructure Definitions | Validate syntax, policy, permissions, and destructive changes |
| Pipeline Logs | Protect secrets, sensitive data, and artifact locations |
Monitor the Release
| Monitoring Layer | Release Signal |
|---|---|
| Pipeline | Stage duration, failures, retries, and approval status |
| Deployment | Health, readiness, version, and replica status |
| Service | Availability, latency, throughput, and errors |
| Input | Schema failures, missing values, and categories |
| Prediction | Score, class, and threshold-selection distributions |
| Model Quality | Delayed performance and calibration |
| Responsible Use | Relevant group behavior, complaints, and overrides |
| Business | Task success, value, fallback usage, and impact |
Rollback
Rollback restores a previous approved combination of application, model, preprocessing, schema, threshold, environment, and infrastructure configuration.
Rollback Requirements
- Previous model artifact remains available
- Previous container image remains available
- Previous schema and threshold are known
- Configuration remains compatible
- Traffic restoration is documented
- Rollback authority is defined
- Health and smoke tests are automated
- Incident evidence is preserved
- Recovery is verified through monitoring
GitOps for ML
GitOps stores declarative deployment configuration in version control and uses an authorized controller to reconcile the target environment with the approved repository state.
GitOps Requirements
- Version-controlled deployment manifests
- Protected branches and review
- Immutable image references
- Traceable model versions
- No plaintext secrets in Git
- Automated schema and policy checks
- Environment-specific promotion controls
- Drift detection
- Auditable reconciliation
- Tested rollback
Responsible CI/CD for ML
Responsible Release Controls
- Use only authorized training and validation data
- Preserve independent test evidence
- Evaluate relevant operating groups
- Document intended and prohibited uses
- Record known limitations
- Version thresholds and business rules
- Require human approval for consequential workflows
- Prevent automatic promotion after failed safety checks
- Monitor harmful or unequal outcomes
- Support correction, appeal, fallback, and rollback
- Preserve release and approval evidence
- Retire releases that are no longer suitable
Common CI/CD Mistakes
Recommended ML CI/CD Workflow
Version the System
Track code, data references, features, configuration, models, schemas, images, infrastructure, and monitoring.
Protect the Repository
Require pull requests, reviewers, automated checks, and approved merge policies.
Build ML-Aware CI
Validate software, data, features, training, models, artifacts, security, and contracts.
Train Reproducibly
Use versioned data, configuration, environments, and pipeline components.
Apply Quality Gates
Compare actual candidate evidence with approved technical, operational, security, fairness, and business requirements.
Publish Immutable Artifacts
Register the model and publish a versioned serving image with complete lineage.
Deploy to Staging
Run integration, security, load, contract, and smoke tests in a production-like environment.
Promote Safely
Apply required approvals and use a rollout strategy aligned with risk.
Monitor the Release
Track pipeline, deployment, service, data, prediction, quality, responsible-use, and business signals.
Improve or Roll Back
Investigate evidence, correct defects, restore approved versions, and preserve incident learning.
Hands-On Practice
Create a CI Workflow
Add formatting, unit, data-contract, pipeline smoke, and artifact-loading tests.
Create Quality Gates
Define approved data, model, fairness, security, latency, and operational criteria.
Build a Versioned Image
Package the application and model into an immutable serving image.
Deploy to Staging
Validate health, readiness, schemas, authentication, latency, and prediction consistency.
Configure an Approval Gate
Require authorized review before production promotion.
Practice Canary Release
Route a controlled traffic share to a candidate and compare version-specific signals.
Practice Rollback
Restore the previous approved release and verify its operational and prediction behavior.
Audit the Release
Confirm complete lineage from source revision and data reference to deployed model and image versions.
Knowledge Check
What is Continuous Integration for ML?
Explain frequent automated validation of code, data contracts, features, pipelines, models, and artifacts.
What is Continuous Delivery?
Explain how it creates an approved release candidate ready for controlled deployment.
What is Continuous Deployment?
Explain automatic production promotion after every required gate has passed.
How does ML CI/CD differ from ordinary CI/CD?
Explain data, features, training, models, thresholds, statistical evaluation, and drift.
Why should Continuous Training create a candidate?
Explain independent evaluation, comparison, registration, approval, and promotion.
Why promote the same artifact through environments?
Explain reproducibility and prevention of environment-specific rebuilding differences.
What is a canary release?
Explain controlled exposure of a candidate to a limited traffic share before broader promotion.
Why must CI/CD identities use least privilege?
Explain limiting the impact of credential misuse or pipeline compromise.
Why are post-deployment tests necessary?
Explain that successful deployment does not prove readiness, contract compatibility, or prediction consistency.
What must an ML rollback restore?
Explain application, model, preprocessing, threshold, schema, environment, and infrastructure compatibility.
CI/CD Readiness Checklist
Confirm Before Production Automation
- Source repositories use protected branches
- Pull requests and relevant reviews are required
- Code, data, features, models, and schemas are versioned
- Pipeline configuration is versioned
- CI runs isolated and repeatable environments
- Unit and integration tests pass
- Data-schema and quality tests pass
- Feature and leakage tests pass
- Training smoke tests pass
- Model-quality gates use actual approved criteria
- Relevant group analysis is included
- Artifacts pass save, load, checksum, and consistency tests
- Dependencies and images are scanned
- Secrets are not stored in code or workflow files
- Pipeline identities use minimum permissions
- Models and images use immutable versions
- Artifact checksums and image digests are recorded
- The same artifact is promoted through environments
- Staging is sufficiently production-like
- Deployment smoke tests are automated
- Prediction consistency is verified
- Production approval requirements are documented
- The rollout strategy matches model risk
- Version-specific monitoring is configured
- Alerts have responsible owners
- Fallback is documented and tested
- The complete rollback procedure is tested
- Continuous Training creates candidates only
- Responsible-use gates cannot be bypassed
- Release and approval evidence is retained
Lesson Summary
| CI/CD Area | Main Outcome |
|---|---|
| Continuous Integration | Validates proposed ML-system changes rapidly |
| Continuous Delivery | Produces a deployment-ready approved release |
| Continuous Deployment | Automates promotion after all required gates pass |
| Continuous Training | Produces evaluated candidates after approved triggers |
| Version Control | Preserves traceability across every behavior-changing asset |
| ML Testing | Validates software, data, features, models, artifacts, and contracts |
| Quality Gates | Prevent unsuitable candidates from progressing |
| Immutable Artifacts | Enable reproducible promotion and rollback |
| Environment Promotion | Moves the same release through controlled environments |
| Deployment Strategy | Introduces a release according to operational risk |
| Security | Protects identities, secrets, artifacts, dependencies, and infrastructure |
| Monitoring | Validates behavior during and after release |
| Rollback | Restores a complete previous approved release |
| Responsible AI | Preserves appropriate use, oversight, safety, and accountability |
Key Takeaway
CI/CD for Machine Learning automates how changes to code, data contracts, features, models, schemas, environments, and infrastructure are validated and delivered. Continuous Integration provides rapid technical and ML-specific feedback. Continuous Delivery creates an immutable, deployment-ready release. Continuous Deployment may promote that release automatically only when every required quality, security, operational, governance, and responsible-use gate has passed. Continuous Training is related but distinct: it creates new candidates that still require independent evaluation and controlled promotion. A reliable ML release process preserves complete lineage, promotes the same artifact through environments, validates production behavior after deployment, monitors version-specific outcomes, and maintains tested fallback and rollback paths.
Get Machine Learning updates by email
Short, practical lessons and course updates from Rumman Ansari. No spam.