The user wants a CI pipeline for Machine Learning (ML) code.
The pipeline needs to perform three specific tasks:
- Unit tests: Verify the logic of the code.
- Data contract checks: Ensure data schemas and expectations are met (e.g., using Great Expectations or Pandera).
- Pipeline linting: Check the pipeline definition code (e.g., Airflow DAGs, Kubeflow, or just general Python linting for pipeline scripts).
I need to choose a CI platform. GitHub Actions is the most common and accessible for a general example, but I should mention that this can be adapted to GitLab CI, Jenkins, etc.
Key components of the solution:
- Prerequisites: A Python environment, necessary libraries (pytest, great_expectations/pandera, pylint/black/flake8).
- Directory Structure: To make the example concrete, I need a hypothetical project structure.
src/: ML code.
tests/: Unit tests.
pipelines/: Pipeline definitions.
contracts/: Data contract definitions.
- The CI Workflow (YAML file):
- Triggers: Push/PR to main.
- Environment: Ubuntu, Python setup.
- Steps:
- Checkout.
- Install dependencies.
- Job 1: Linting (Code style + Pipeline specific linting).
- Job 2: Unit Tests (Run pytest).
- Job 3: Data Contract Checks (Run validation against a sample or actual data).
Detailed thought process on specific requirements:
-
Unit Tests:
- Tool:
pytest is the standard.
- Coverage:
pytest-cov adds value.
-
Data Contract Checks:
- What is a data contract? It defines schema (types), ranges, uniqueness, etc.
- Tools: Great Expectations (GX) is powerful but heavy. Pandera is lightweight and code-first. For a CI example, I'll assume a script runs validation. Let's stick to a generic script approach (e.g.,
python scripts/validate_contracts.py) to remain tool-agnostic, but suggest tools like Great Expectations or Soda Core. Let's use a simple Python script example with pandera or just describe the concept. Actually, a script that runs great_expectations checkpoint run is a common pattern. Let's define a step that runs a validation script.
-
Pipeline Linting:
- This usually means checking the definition files (e.g., Airflow DAGs) for import errors or cycle detection, or standard Python linting (
ruff, black, flake8) for the pipeline code.
- Specific tools:
ruff is fast and modern. For Airflow, specific linting plugins exist, but standard Python linting is the baseline.
Structure of the Response:
- Project Structure: Visualizing where files live.
- CI Configuration (GitHub Actions): The core code block.
- Detailed Breakdown of Steps:
- Setup.
- Linting (Code & Pipelines).
- Unit Tests.
- Data Contracts (The "special" ML part).
- Local Implementation Examples:
- Example
pytest.
- Example Data Contract (using Pandera for simplicity in explanation, or GX).
- Example Linting config.
Refining the "Data Contract" part:
In CI, you usually can't run massive data validations against production data. You typically validate a sample of data or validate the schema of the data pipeline logic. I will assume the CI validates a sample dataset stored in tests/fixtures or checks the contract definition code itself.
Drafting the YAML (Mental Check):
jobs:
ci-job:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
- run: pip install -r requirements.txt
- run: ruff check . # Linting
- run: pytest tests/ # Unit tests
- run: python scripts/check_data_contracts.py # Contracts
Let's separate them into jobs or steps? Steps are usually faster for a single environment, jobs allow parallelism. For simplicity and dependency management (linting shouldn't need all heavy ML libs), maybe separate jobs?
Actually, ML libs are heavy. Linting should be fast. Splitting into jobs is better engineering.
- Job 1: Lint (Fast, no heavy torch/tensorflow needed ideally).
- Job 2: Unit Tests (Needs the heavy libs).
- Job 3: Data Contracts (Might need data access or sample data).
Let's stick to a consolidated workflow for readability but mention parallelism.
Code snippet for Data Contract:
I will provide a brief example of what validate_contracts.py might look like using a library like Pandera, as it's very "code-native" and fits CI well.
Code snippet for Pipeline Linting:
I'll suggest ruff for Python and mention specific DAG validation if they use Airflow/Prefect.
Final Polish:
Add a caching step. ML dependencies are huge; caching pip is crucial for a good experience.
Summary of deliverables:
ci.yml file.
- Sample
requirements.txt structure.
- Explanation of the three pillars (Lint, Test, Contract).
- Example scripts for the contracts.
Let's write it out.
A robust ML CI pipeline must validate three distinct layers: the code logic (unit tests), the data structure (contracts), and the pipeline definition (linting). Since ML libraries are often large, managing environment caching is critical for speed.
Below is a comprehensive engineering solution using GitHub Actions. This solution creates a "Matrix" workflow that separates concerns while consolidating reporting.
1. Project Structure Context
To make the CI scripts relevant, assume the following project structure:
ml-project/
├── .github/workflows/ci.yml
├── requirements.txt
├── src/
│ └── transform.py
├── pipelines/
│ └── training_pipeline.py # Or DAG definition
├── tests/
│ ├── test_transform.py # Unit tests
│ └── test_data_contracts.py # Contract tests
└── schemas/
└── input_schema.json # Data contracts
2. The CI Pipeline (.github/workflows/ci.yml)
This pipeline uses a Matrix Strategy to run linting, unit tests, and data checks in parallel. It also employs smart caching to speed up runs.
name: ML CI Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
# JOB 1: Static Analysis & Pipeline Linting
# Fast feedback loop. Fails if code style or pipeline definitions are broken.
lint:
name: Lint & Static Analysis
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
cache: 'pip'
- name: Install Linters
run: |
pip install ruff pylint black
# If using specific pipeline tools like Great Expectations or dbt:
pip install dbt-core great_expectations
- name: Run Python Linting (Ruff/Black)
run: |
black . --check
ruff check .
- name: Pipeline Structure Linting
run: |
# Example: Check if pipeline imports are valid without running them
python -c "from pipelines.training_pipeline import create_pipeline; assert create_pipeline is not None"
# If using dbt:
# dbt parse --profiles-dir .
# JOB 2: Unit Tests
# Tests the logic of your feature engineering and model code.
unit-tests:
name: Run Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
cache: 'pip'
- name: Install Dependencies
run: |
pip install -r requirements.txt
pip install pytest pytest-cov
- name: Run Tests with Coverage
run: |
pytest tests/ --cov=src --cov-report=xml --cov-fail-under=80
- name: Upload Coverage Report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage.xml
# JOB 3: Data Contract Checks
# Validates that data schemas match expectations.
data-contracts:
name: Validate Data Contracts
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
cache: 'pip'
- name: Install Dependencies
run: |
pip install pandera[io] pytest
# Or: pip install great_expectations
- name: Run Contract Validation
run: |
# This assumes you have a test specifically for validating schemas
pytest tests/test_data_contracts.py -v
3. Implementation Details
To make the YAML above work, you need the corresponding code implementations.
A. Unit Tests (tests/test_transform.py)
Standard unit tests should mock data inputs to ensure the logic is sound without needing a database connection.
# src/transform.py
import pandas as pd
def normalize_column(df: pd.DataFrame, col_name: str) -> pd.DataFrame:
df[col_name] = (df[col_name] - df[col_name].mean()) / df[col_name].std()
return df
# tests/test_transform.py
import pandas as pd
import numpy as np
from src.transform import normalize_column
def test_normalize_column():
# Create dummy data
df = pd.DataFrame({'value': [10, 20, 30]})
# Run function
result = normalize_column(df, 'value')
# Assertions
assert np.isclose(result['value'].mean(), 0)
assert np.isclose(result['value'].std(), 1)
B. Data Contract Checks (tests/test_data_contracts.py)
Data contracts ensure that if your input data schema changes (e.g., a column is renamed), the pipeline fails before training starts. We use Pandera here for code-native validation.
# tests/test_data_contracts.py
import pandera as pa
from pandera import Column, Float, Int, Check
import pandas as pd
# Define the contract (Schema)
input_schema = pa.DataFrameSchema({
"age": Column(Int, Check.ge(0)),
"salary": Column(Float, Check.gt(0)),
"department": Column(str)
})
def test_input_data_contract():
"""
Validates that the current raw data sample fits the contract.
In reality, you might load a sample from S3/GCS here.
"""
# Sample data representing your input source
df = pd.DataFrame({
"age": [25, 30, 45],
"salary": [50000.0, 60000.0, 80000.0],
"department": ["sales", "eng", "mkt"]
})
# Validate; raises pa.errors.SchemaError if failed
assert input_schema.validate(df) is not None
C. Pipeline Linting
For the "Pipeline Linting" step, the goal is to catch syntax errors in your ML pipeline definition (e.g., a Kubeflow or Airflow DAG) before it reaches the orchestrator.
If you are using a framework like Kubeflow Pipelines or Prefect, your lint step should import the pipeline code to ensure it builds the Directed Acyclic Graph (DAG) correctly.
# Example logic for the Lint step in CI
# scripts/lint_pipeline.py
from pipelines.training_pipeline import create_pipeline
def main():
try:
# Try to compile/parse the pipeline
pipeline = create_pipeline()
print(f"Pipeline '{pipeline.name}' parsed successfully.")
except Exception as e:
print(f"Pipeline definition error: {e}")
exit(1)
if __name__ == "__main__":
main()
4. Engineering Considerations
- Dependency Caching: ML dependencies (PyTorch, TensorFlow, Scikit-learn) are heavy. The
cache: 'pip' line in the GitHub Action is vital to avoid downloading libraries on every run.
- Separation of Concerns: Notice the
lint job does not install heavy ML frameworks (like PyTorch) if possible. It only installs ruff or black. This makes the "fast feedback" loop significantly faster than the unit tests.
- Fail Fast: Configure the workflow to cancel running jobs if a new commit is pushed to the same branch.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
- Report Artifacts: Always upload artifacts (like
coverage.xml or test failure logs) so you can debug why the CI failed without re-running the job locally.