Metamorphic Testing for ML Models When Ground Truth Is Missing

You ship a classifier, ranker, or LLM wrapper. Product asks: "Is the new model worse?" You open the eval set and half the cases have no trusted label. Human review costs days. Blind accuracy on a stale gold set misses the bugs that show up after a preprocessing change or a prompt tweak.
This post shows how to test those systems with metamorphic relations: properties that must hold between related inputs even when you cannot name the correct output. You will leave with a concrete relation catalog, a pytest harness you can paste into a model repo, and the failure modes that make weak relations green while the product is broken.
This is not a survey of every academic MR paper, and it is not a substitute for labeled offline eval when you have good labels. Use both. For LLM-generated test code that invents facts, see AI Test Hallucinations: Detection + Fixes. For CI flake patterns around nondeterministic suites, see Flaky Test Detection with Machine Learning.
The oracle problem in ML testing
A test oracle is the rule that decides pass vs fail. Classic software often has one: HTTP 200, balance equals debit minus credit, DOM contains a string.
ML breaks that pattern:
| System | Why a fixed expected value fails |
|---|---|
| Image classifier | Same photo, slight crop: human label may be unchanged, but you rarely store that pair |
| Search / ranking | "Correct" order depends on user and context; only pairwise preferences are stable |
| Toxicity / moderation | Borderline text has no single ground truth across raters |
| LLM assistant | Many answers are acceptable; string equality is a false failure |
| Forecasting | Future values arrive late; you cannot assert the number at train time |
If your only gate is assert pred == label, you either skip those cases or invent brittle labels. Metamorphic testing asks a different question: given input x and a transform T(x), how must f(x) and f(T(x)) relate?
You still need an oracle. It is a relation, not a scalar.
What metamorphic testing is (and is not)
Metamorphic testing (MT) runs the model on a source case and on follow-up cases derived by a known transform, then checks a metamorphic relation (MR) between the outputs.
It is not:
- Data augmentation for training (same transforms, different job)
- Property-based testing of pure functions with Hypothesis alone (related idea; MT is aimed at systems where the expected output is unknown)
- "The model should always be invariant to everything" (many transforms should change the output in a controlled way)
| Approach | Needs labels? | Catches |
|---|---|---|
| Held-out accuracy / F1 | Yes | Overall drop on known distribution |
| Golden snapshots of logits | Soft labels / frozen outputs | Bit-level regressions; brittle to retrains |
| Human side-by-side | Expensive raters | Subjective quality |
| Metamorphic relations | No labels for the pair | Logic breaks under transforms you care about |
MT shines when labels are missing, expensive, or contested, and when you can state a product rule like "mirroring a chest X-ray must not flip left/right disease tags" or "paraphrasing a support ticket should not change intent class."
Before you start
You need:
- A callable model boundary: Python function, HTTP
/predict, or batch scorer. Prefer one stable entry point. - A small source corpus of real inputs (even 50-200 rows). Production samples beat synthetic-only.
- pytest (or equivalent) and a way to pin model version / prompt hash in CI.
- Agreement with product on which transforms are invariants (output must stay equal) vs monotonic (score can move only one direction) vs equivalence classes (same top-1 class).
If your model is stochastic (sampling temperature > 0), set temperature to 0 or seed the RNG for MT jobs. Otherwise every relation becomes a flake.
Pick relations from product behavior, not from textbooks
Weak MRs look smart and catch nothing. Strong MRs encode a promise the product already makes.
Image and vision
| Relation | Transform T | Expected relation |
|---|---|---|
| Label invariance | Horizontal flip when class is flip-safe (cat vs dog) | argmax(f(x)) == argmax(f(T(x))) |
| Anatomy asymmetry | Horizontal flip when labels are side-sensitive (left lung) | Side-specific tags must swap or the pipeline must refuse |
| Brightness band | Gamma in a documented range | Top-1 class unchanged; confidence may drop within a bound |
| JPEG re-encode | Quality 70-90 | Same top-1 on clear cases |
Text classifiers and intent models
| Relation | Transform T | Expected relation |
|---|---|---|
| Case / whitespace | Lowercase, strip, collapse spaces | Same class |
| Synonym paraphrase | Controlled paraphrase list (not free LLM rewrite in CI) | Same class on high-confidence sources |
| Language switch | Documented bilingual pairs | Same intent id |
| Negation flip | Insert / remove negation with a curated template | Class must change when templates say so |
Ranking and recommendations
| Relation | Transform T | Expected relation |
|---|---|---|
| Query synonym | "wireless mouse" vs "cordless mouse" | Overlap in top-k ids above a threshold |
| Candidate shuffle | Permute input candidate list | Output order depends on scores, not input order (unless intentional position bias) |
| Duplicate injection | Append a duplicate of #1 | Duplicate should not outrank the original without a reason |
LLM and RAG answers
| Relation | Transform T | Expected relation |
|---|---|---|
| Paraphrased question | Fixed paraphrase bank | Same retrieved doc ids, or same structured fields |
| Irrelevant context | Append unrelated paragraph to RAG context | Answer must not invent facts from the decoy |
| Permission boundary | Same question as unauthorized role | Refusal / empty tool call preserved |
Write each MR as a one-line product sentence first. If product will not defend that sentence in a bug triage, drop the relation.
Worked path: image classifier invariance in pytest
Assume a local scorer that returns class probabilities. The same pattern wraps an HTTP client.
# tests/metamorphic/test_vision_flip.py
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import pytest
from PIL import Image
from my_model import predict_proba # your boundary: np.ndarray -> dict[str, float]
FLIP_SAFE_CLASSES = {"cat", "dog", "car", "tree"}
@dataclass(frozen=True)
class Case:
path: Path
source_top1: str
def load_rgb(path: Path) -> np.ndarray:
return np.asarray(Image.open(path).convert("RGB"))
def top1(probs: dict[str, float]) -> str:
return max(probs, key=probs.get)
def hflip(img: np.ndarray) -> np.ndarray:
return np.ascontiguousarray(img[:, ::-1, :])
@pytest.fixture(scope="module")
def source_cases() -> list[Case]:
root = Path("fixtures/vision/source")
cases: list[Case] = []
for path in sorted(root.glob("*.jpg")):
probs = predict_proba(load_rgb(path))
label = top1(probs)
if label in FLIP_SAFE_CLASSES and probs[label] >= 0.7:
cases.append(Case(path=path, source_top1=label))
if len(cases) < 20:
pytest.skip("need >=20 high-confidence flip-safe sources")
return cases
@pytest.mark.metamorphic
@pytest.mark.parametrize("case_idx", range(20))
def test_hflip_preserves_top1(source_cases: list[Case], case_idx: int) -> None:
case = source_cases[case_idx]
original = load_rgb(case.path)
flipped = hflip(original)
assert top1(predict_proba(flipped)) == case.source_top1How you know it worked:
- Failures name a fixture file and the two top-1 labels.
- Re-running the same commit is stable with a frozen model artifact.
- A deliberate bug (swap left/right channels only on flip path, or disable flip in preprocessing) turns the suite red.
Worked path: text intent with curated paraphrases
Do not call a second LLM in CI to "paraphrase freely." That injects a second oracle problem. Keep a checked-in table.
source,paraphrase,intent
"I want to cancel my subscription","Please cancel my plan",cancel
"I want to cancel my subscription","How do I stop auto-renew?",cancel
"Where is my package?","Track my shipment",shipping_status# tests/metamorphic/test_intent_paraphrase.py
import csv
from pathlib import Path
import pytest
from my_model import predict_intent
def rows() -> list[dict[str, str]]:
path = Path("fixtures/intent/paraphrases.csv")
with path.open(newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
@pytest.mark.metamorphic
@pytest.mark.parametrize("row", rows())
def test_paraphrase_keeps_intent(row: dict[str, str]) -> None:
source_intent = predict_intent(row["source"])
follow_intent = predict_intent(row["paraphrase"])
assert source_intent == row["intent"]
assert follow_intent == source_intentThe first assert is optional when source itself is unlabeled. Keep it when you trust the CSV intent column. The metamorphic core is follow_intent == source_intent after you accept source_intent as the reference for that pair.
Ranking: permutation independence
Many rankers should score candidates independently. If shuffling the candidate list changes the order of ids, you found position bias or a bug in batching.
import random
import pytest
from my_ranker import rank # rank(query, candidates) -> list[str] ids
@pytest.mark.metamorphic
def test_candidate_order_does_not_change_ranking(seed: int = 7) -> None:
query = "noise cancelling headphones"
candidates = [f"sku-{i}" for i in range(30)]
baseline = rank(query, candidates)
rng = random.Random(seed)
shuffled = candidates[:]
rng.shuffle(shuffled)
assert rank(query, shuffled) == baselineIf product wants position bias (exploration, sponsored slots), encode that as an MR with an allowlist of slots, not as silence.
Wire metamorphic tests into CI without drowning the team
Treat MT as a separate job from unit tests:
- Marker:
@pytest.mark.metamorphic. - Nightly or pre-release on the model artifact that will ship, not on every docs PR.
- Fail the job on any relation break for blocking MRs. Quarantine experimental MRs behind a second marker until they earn trust.
- Publish a small report: relation name, fail count, example inputs. Engineers debug fixtures, not a single exit code.
# .github/workflows/model-metamorphic.yml
name: model-metamorphic
on:
workflow_dispatch:
schedule:
- cron: "0 5 * * *"
jobs:
mt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -r requirements-model.txt -r requirements-test.txt
- run: pytest -m metamorphic --maxfail=20 --junitxml=mt-junit.xmlPin the model artifact id in the workflow env. If the job pulls "latest" from a mutable registry, a red suite cannot tell model drift from infra drift.
Failure modes that waste a sprint
1. Relations that are always true.
assert len(pred) > 0 after a transform is not an MR. If both sides can return empty and still "pass" your check, delete it.
2. Relations that fight the product.
Forcing flip invariance on medical laterality labels will page the wrong on-call and train the team to ignore MT.
3. Stochastic decoding.
Temperature 0.7 + assert answer_a == answer_b creates flakes. Seed, use greedy decoding, or compare structured fields (JSON keys, tool names) instead of full prose.
4. Transform noise that exceeds the model’s contract.
Aggressive paraphrases and heavy JPEG compression are training augmentations, not CI MRs, unless product documents that guarantee.
5. Label leakage disguised as MT.
If you only keep source cases where top1 already matches a gold label, you quietly reintroduced a labeled suite and shrunk coverage to easy cases.
6. Flaky I/O.
Remote GPU endpoints with retries will desync source and follow-up calls. Prefer local or sticky sessions for the pair.
7. Over-wide confidence filters.
Requiring prob >= 0.95 to enter the suite means you never test the decision boundary where bugs live. Prefer a band (for example 0.6-0.9) for some relations.
How metamorphic results pair with labeled eval
Use a split of duties:
| Signal | Job |
|---|---|
| Labeled holdout metrics | Absolute quality vs known distribution |
| Slice metrics (locale, device) | Bias and long-tail drops |
| Metamorphic suite | Behavioral contracts under transforms |
| Online shadow / A-B | User outcome, not just model math |
A model can keep accuracy and break an MR (preprocessing bug). A model can fail an MR during a valid retrain if the relation was wrong. Triage both like product bugs: reopen the MR definition before blaming the weights.
Decision checklist
Ship a metamorphic gate when:
- You can write three product-backed relations in plain language.
- You have a frozen model entry point and a source corpus from real traffic or staging.
- CI can run the suite in a bounded time with deterministic decoding.
- Failures produce artifact paths or text snippets a human can inspect in minutes.
Wait (or keep MT advisory-only) when:
- Transforms are still debated by product and clinical / legal owners.
- The only available interface is a nondeterministic third-party API you cannot seed.
- You already have dense, trusted labels and your regressions are mostly distribution shift (invest in slices first).
Minimal starter set for most teams:
- One invariance MR on the dominant input modality.
- One "must change" MR (negation, class swap, permission denial).
- One pipeline MR (candidate shuffle, decoy context, or JPEG re-encode).
When those three stay green across two release candidates, expand the catalog. When one is chronically red and product shrugs, delete it. A short honest suite beats a long ignored one.
Summarize this post
Opens the chat with a prompt copied — paste to start.
Get the next guide in your inbox
Weekly AI testing insights, templates, and tool notes — unsubscribe anytime.