Sub topic 11
Keeping CI fast and affordable
This chapter assumes you can write pytest tests, read a GitHub Actions workflow, and have already built the layered test suite from earlier chapters: code tests, data tests, and model tests. Here the question changes from "what should we test?" to "how often, and at what price?"
Why cost matters in ML CI
A CI pipeline that takes 40 minutes gets ignored. Developers push less often, batch changes into large pull requests, or merge while checks are still running. Slow CI also costs money, because hosted runners bill by the minute and GPU runners bill at a much higher rate.
ML projects reach this point quickly. Dependencies such as scikit-learn, PyTorch, or TensorFlow are large. Datasets are bigger than source files. Training takes minutes or hours, not seconds. The goal is to keep the feedback on every pull request in the range of a few minutes. Everything slower is moved to a place where it does not block developers.
There are three levers:
- Do less work per run: caching and small test data.
- Run only when needed: triggers and path filters.
- Move heavy work elsewhere: scheduled and on-demand jobs.
Cut the work in each run
Cache dependencies
Installing dependencies is often the largest fixed cost in a fast test run. The workflow from the earlier chapter already uses cache: pip in actions/setup-python. That action stores the pip download cache and keys it on a hash of your dependency files. When requirements.txt has not changed, the next run restores the cache and skips downloads.
Two details decide whether this works:
- The cache key comes from your dependency file. If you do not pin versions, or if the file changes often, you get few cache hits.
- Caching saves download time, not install time. Large packages with compiled parts still need to be unpacked and installed.
If installs are still slow, you can cache the whole virtual environment, or run the job inside a container image that already has the dependencies. Container images give faster starts but add a build-and-publish step you must maintain.
Cache data and derived files
If a test downloads a dataset or builds a feature file, cache it with actions/cache. Use a key that includes a hash of the inputs, so a changed input produces a new key and a stale file is never reused.
name: ml-ci-cached-data
on:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Restore reference data
uses: actions/cache@v4
with:
path: .cache/reference
key: reference-${{ hashFiles('data/reference.dvc', 'scripts/build_reference.py') }}
- name: Build reference data if missing
run: python scripts/build_reference.py --out .cache/reference
- name: Fast tests
run: pytest tests/unit tests/data -qIn this example the build script should skip work when the output already exists. If it always rebuilds, the cache saves nothing.
A rule for caches: the key must change whenever the cached content would change. A key that is too broad gives you stale data and tests that pass for the wrong reason. A key that is too narrow gives you no hits.
Use small data for pull requests
The data tests from earlier chapters read a small committed sample, for example tests/data/sample.csv. That is deliberate. A pull request check does not need the full dataset. It needs enough rows to exercise every code path and every validation rule.
Good test data for CI has these properties:
- A few hundred rows at most, small enough to commit to the repository.
- Covers each column, each category value, and a few known edge cases such as a missing value.
- Fixed. If the sample changes, the change shows up in the pull request diff.
The same applies to model tests. The behavioral tests earlier trained a logistic regression on 200 synthetic rows with a fixed seed. That trains in milliseconds. If a test needs a larger model, ask whether it is testing behavior (use a tiny model) or accuracy (move it to a quality gate on a slower schedule).
Run fast tests first and stop early
Order steps from cheapest to most expensive. A lint failure or a schema error should end the run before any model is trained. Two settings help:
- GitHub Actions stops a job at the first failing step by default, so put cheap steps first.
pytest -xstops at the first failing test, andpytest --durations=10prints the ten slowest tests so you can find what to trim.
You can also mark slow tests and exclude them from the default run:
import pytest
@pytest.mark.slow
def test_full_training_reaches_target_accuracy():
# Trains on a larger dataset; run on a schedule, not on every pull request.
...Register the marker so pytest does not warn about it. Put this in pytest.ini:
[pytest]
markers =
slow: tests that take more than a few seconds; skipped on pull requestsThen pull request jobs run pytest -m "not slow" and the scheduled job runs pytest -m slow.
Run only when needed
Path filters
Not every change affects every test. A change to documentation should not trigger a training job. Use paths or paths-ignore in the trigger to skip the workflow when only unrelated files change.
name: ml-ci-paths
on:
pull_request:
paths:
- "src/**"
- "tests/**"
- "requirements.txt"
- ".github/workflows/ml-ci.yml"
push:
branches: [main]
paths:
- "src/**"
- "tests/**"
- "requirements.txt"
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- run: pytest tests/unit tests/data -qInclude the workflow file itself and the dependency file in the list. A change to either can break the build even though no source file changed.
There is a catch with required checks. If branch protection requires a status check and a path filter prevents the workflow from running, the check never reports and the pull request can stay blocked. Teams handle this either by not filtering the required workflow, or by adding a small always-running job that reports success when nothing relevant changed.
Cancel superseded runs
When a developer pushes three commits in a row, the first two runs are useless. A concurrency block cancels them:
concurrency:
group: ml-ci-${{ github.ref }}
cancel-in-progress: trueAdd this at the top level of the workflow. Use it for pull request checks. Do not use it for runs on main that publish artifacts, because cancelling a half-finished publish can leave things inconsistent.
Set timeouts
A hung test can burn runner minutes until the platform default limit, which is long. Set timeout-minutes on each job, at roughly two to three times its normal duration:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15Move heavy work off the critical path
Some checks are valuable but too slow or too costly for every pull request:
- Retraining on the full dataset and comparing to the baseline.
- Drift checks against a large reference dataset.
- Tests on GPU hardware.
- Fairness or robustness evaluations that run many model predictions.
Run these on a schedule, on demand, or after merge. GitHub Actions supports all three through triggers.
name: ml-nightly
on:
schedule:
- cron: "0 2 * * *"
workflow_dispatch:
jobs:
heavy:
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Slow model tests
run: pytest -m slow -qThe schedule trigger runs the job at 02:00 UTC every day. The workflow_dispatch trigger adds a "Run workflow" button, so a developer can start the same job manually, for example before a release or when a pull request touches training code.
Scheduled workflows run on the default branch only. Also, GitHub may delay scheduled runs during busy periods, so do not depend on exact timing.
The trade-off is detection delay. A regression caught nightly is found hours after the change that caused it, and the cause may be one of several commits. Keep the fast per-pull-request tests strong enough to catch most problems, and treat the nightly job as a safety net. When a nightly failure appears, the commit list since the last green run narrows the search.
A middle tier: smoke tests after merge
Between "every pull request" and "nightly" sits the post-merge run. A pipeline smoke test (from the earlier chapter) runs the whole flow on a small sample. It takes a few minutes, so it fits on pushes to main but may be too much for every pull request commit. For pull requests that change training code, you can add a label-based or manual trigger to run it before merging.
Choosing the runner
Most pull request checks should run on a standard CPU runner. GPU runners cost much more per minute and often have queue delays. Keep GPU use to the tests that actually need it, such as one short check that a model runs on the device. Use a tiny model and a few batches, not a real training run.
Self-hosted runners can reduce per-minute cost for heavy jobs, but you take on maintenance and security. Do not run untrusted pull request code from forks on a self-hosted runner that has access to your network or secrets.
Measure before optimizing
Guessing leads to wasted effort. Look at the data first:
- The Actions run page shows the time of each step. Find the biggest one.
pytest --durations=10lists the slowest tests.- Track total runner minutes per month in your billing or usage page.
A useful target for a pull request run is under ten minutes, with a stricter goal of five if you can. If the install step takes four minutes, caching has more payoff than test tuning. If one test takes three minutes, marking it slow has more payoff than caching.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Cache key does not include input hashes | Stale data, tests pass for the wrong reason | Hash the files that define the cached content |
| Path filter on a required check | Pull request blocked waiting for a check that never runs | Always run the required check, or add a pass-through job |
| Full training in the pull request job | Slow feedback, high cost | Use a tiny seeded model; move accuracy checks to a schedule |
| No timeout | A hung job burns minutes | Set `timeout-minutes` |
| Cancel-in-progress on publish runs | Partial artifacts | Only cancel pull request runs |
| Nightly job nobody reads | Failures go unnoticed | Send failures to a channel or open an issue automatically |
Exercise
Your pull request workflow takes 18 minutes. The step breakdown is: dependency install 5 minutes, unit and data tests 1 minute, a model test that trains on 50,000 rows 9 minutes, lint 1 minute, setup overhead 2 minutes. Name three changes, in order of expected payoff, and say what risk each introduces.
Show answer
First, move the 50,000-row training test out of the pull request run. Mark it slow and run it nightly and on demand, and replace it with a behavioral test on a small seeded model. This saves about 9 minutes. The risk is that an accuracy regression is found later than the commit that caused it, so keep a baseline quality gate in the nightly job. Second, cache dependencies with cache: pip and a pinned requirements file, which should cut most of the 5-minute install. The risk is a stale cache if the key does not track the dependency file. Third, add concurrency with cancel-in-progress and path filters so superseded and irrelevant runs do not consume minutes. The risk is a required check that never reports on filtered pull requests, which needs a pass-through job.
Exercise
A teammate caches a feature file with the key "features-v1" and never changes it. Three weeks later, the feature code changes, but tests still pass using the old file. What went wrong, and how do you fix the key?
Show answer
The key does not change when the inputs change, so the runner restores the old file even though the code that produces it is different. Fix it by including a hash of the producing script and input data definition in the key, for example features-${{ hashFiles('src/features.py', 'data/raw.dvc') }}. Then any change to those files creates a new key and forces a rebuild.