LLMOps

Automating LLM Regression Testing

Large Language Models (LLMs) are inherently probabilistic. Even with a temperature of zero, minor floating-point variations or different GPU architectures can lead to slight output differences. This non-determinism makes traditional "pass/fail" unit testing ineffective for LLM applications. As developers move LLMs into production, we need a new category of testing: regression testing for semantic consistency and quality.

This post explores how to build deterministic evaluation pipelines that handle non-deterministic outputs reliably.

The Challenge of Non-Determinism

Traditional software testing relies on exact string matching. If a function returns "Hello World", we expect exactly that. With LLMs, if a prompt asks for a summary, the model might generate five valid summaries in five different runs. If our test expects one specific string, it will fail 90% of the time, leading to "flaky" tests that erode developer confidence.

To solve this, we must shift from output matching to property-based evaluation. We define what a good output looks like in terms of properties (e.g., length, tone, factual accuracy) rather than exact text.

Building a Robust Evaluation Pipeline

A robust pipeline consists of three layers:

  1. Deterministic Checks: Format validation (JSON, regex), length constraints, and banned words.
  2. Statistical Sampling: Running the LLM multiple times per test case to calculate confidence intervals.
  3. Semantic Evaluation: Using an LLM-as-a-Judge or embedding similarity to check for content quality.

1. Implementing Statistical Sampling

Instead of running a test once, we run it N times. We then calculate the pass rate. If the pass rate falls below a threshold (e.g., 95%), the test fails. This accounts for the stochastic nature of the model.


import asyncio
from typing import List, Dict

class LLMRegressionTest:
    def __init__(self, llm_client, num_samples=5, pass_threshold=0.8):
        self.llm = llm_client
        self.num_samples = num_samples
        self.pass_threshold = pass_threshold

    async def run_test(self, prompt: str, evaluator_func) -> Dict:
        """
        Runs the prompt multiple times and evaluates results.
        """
        results = []
        for _ in range(self.num_samples):
            try:
                response = await self.llm.generate(prompt)
                is_pass = evaluator_func(response)
                results.append(is_pass)
            except Exception as e:
                results.append(False)
        
        pass_rate = sum(results) / len(results)
        success = pass_rate >= self.pass_threshold
        
        return {
            "success": success,
            "pass_rate": pass_rate,
            "total_runs": self.num_samples,
            "passed_runs": sum(results)
        }

2. Defining Deterministic Evaluators

Some checks can be strictly deterministic. For example, if the output must be valid JSON, we can parse it. If it fails to parse, it's a hard fail regardless of content.


import json

def evaluator_json_format(response: str) -> bool:
    """
    Deterministic check: Is the response valid JSON?
    """
    try:
        json.loads(response)
        return True
    except json.JSONDecodeError:
        return False

def evaluator_length(response: str, max_chars=100) -> bool:
    """
    Deterministic check: Is the response under the character limit?
    """
    return len(response.strip()) <= max_chars

3. Semantic Consistency via Embeddings

For cases where exact matches don't matter, we can use cosine similarity between the output and a reference answer (if available) or check for the presence of key entities.


from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

class SemanticEvaluator:
    def __init__(self, model_name="all-MiniLM-L6-v2"):
        self.model = SentenceTransformer(model_name)
        self.threshold = 0.85  # High confidence required

    def evaluate(self, output: str, reference: str) -> bool:
        embeddings = self.model.encode([output, reference])
        similarity = cosine_similarity([embeddings[0]], [embeddings[1]])[0][0]
        return similarity >= self.threshold

Integration into CI/CD

To make this actionable in a CI/CD pipeline, these tests should be tagged as slow or integration since they involve multiple LLM calls. You can use GitHub Actions or GitLab CI to trigger these tests only on PRs that touch the prompt templates or model configuration.

Example GitHub Action snippet:


name: LLM Regression
on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run LLM Regression Tests
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: pytest tests/llm/ -v -m "regression"

Conclusion

Automating regression testing for LLMs requires a mindset shift from exact matching to statistical validation. By combining deterministic format checks, statistical sampling, and semantic evaluation, we can build reliable pipelines that catch regressions without being defeated by the inherent randomness of neural networks. This approach ensures that as your models evolve, you can trust that new changes are improving, not breaking, your application's core capabilities.

Share: