Evaluation Metrics for Generative Models
How to measure generative models: FID and precision-recall for images, perplexity and BLEU for text, pass@k for code, LLM judges and human review.
A classifier is easy to grade: compare its label with the true label and count. A generative model has no true label. There are many good answers to “write a product description” or “draw a cat on a skateboard”, and the model is supposed to produce new ones, not copies of the training data. So evaluation has to answer harder questions: do the outputs look like real data, are they varied, do they follow the prompt, and are they correct where correctness exists?
No single number answers all of these. This article goes through the metrics people actually use, grouped by what kind of output they grade: likelihood-based scores, sample-based image metrics such as FID, reference-based text metrics such as BLEU and ROUGE, functional checks such as pass@k for code, and model-graded and human evaluation. It ends with how to combine them into a test suite, and what the managed evaluation services on AWS, Google Cloud and Azure provide.
The previous article on fine-tuning ended by saying that evaluation decides whether a fine-tune worked. This is the detail behind that.
What you are trying to measure
Most metrics target one or more of four properties.
- Fidelity. Individual samples look realistic or read well. A blurry face or an ungrammatical sentence fails here.
- Diversity. The set of samples covers the variety in real data. A GAN that draws the same three faces has high fidelity and terrible diversity; this is mode collapse.
- Conditioning. The output matches the input: the caption, the class label, the instruction, the source document.
- Correctness and safety. Facts are right, code runs, answers are grounded in the provided context, and nothing harmful comes out.
The first two describe the model’s distribution as a whole, so they need many samples. The last two can be judged one output at a time. Keeping that split in mind explains most of the design of the metrics below.
flowchart TB
Q["What does the model produce?"] --> I["Images, audio"]
Q --> T["Free text"]
Q --> C["Code or structured output"]
I --> I1["Distribution: FID, KID, precision and recall"]
I --> I2["Prompt match: CLIP score"]
T --> T1["Has references: BLEU, ROUGE, BERTScore"]
T --> T2["Open-ended: LLM judge, human review"]
C --> C1["Run it: pass@k, schema checks"]
Q --> L["Any model with a likelihood: NLL, perplexity"]
Likelihood: log-likelihood and perplexity
If a model assigns a probability to data, you can ask how probable it finds held-out real data. A model that has learned the distribution well assigns high probability to examples it never saw.
Autoregressive language models, normalizing flows and diffusion models (through a bound) all expose a likelihood. For language models the usual summary is perplexity, the exponential of the average negative log-likelihood per token:
perplexity = exp( -(1/N) * sum over tokens of log p(token | previous tokens) )
A perplexity of 10 means the model is, on average, as uncertain as if it were choosing uniformly between 10 tokens. Lower is better. Measuring it with Hugging Face transformers takes a few lines, because passing labels makes the model return the mean cross-entropy loss:
import math
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "openai-community/gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).eval()
text = "The cloud provider charges for compute by the second."
enc = tokenizer(text, return_tensors="pt")
with torch.no_grad():
out = model(**enc, labels=enc["input_ids"])
print(f"loss {out.loss.item():.3f} perplexity {math.exp(out.loss.item()):.1f}")
For images, the same idea is reported as bits per dimension: negative log-likelihood in base 2, divided by the number of pixel values. VAEs report the ELBO, which is a lower bound on log-likelihood; the mathematical foundations of VAEs article derives it.
Likelihood has two limits you should know before relying on it.
- It is only comparable under the same tokenizer and data. A model with a larger vocabulary has fewer, harder tokens per sentence, so its per-token perplexity is not comparable to a model with a smaller vocabulary. Compare models on the same tokenization, or normalise per byte or per character.
- It does not track sample quality closely. Theis and colleagues showed in 2016 that a model can have excellent likelihood and poor samples, or the reverse. GANs have no likelihood at all. And for instruction-tuned chat models, perplexity on web text says little about whether the answers are helpful.
Perplexity is still the right tool for pretraining curves, for comparing checkpoints of the same model, and as a quick regression check after fine-tuning.
Image metrics: comparing distributions
Sample-based metrics skip the likelihood entirely. They generate a large set of images, embed them with a pretrained network, and compare the embedded generated set with an embedded set of real images.
Inception Score
The Inception Score (Salimans and colleagues, 2016) runs each generated image through an Inception v3 classifier. Good samples should get a confident prediction (one class dominates), and the set as a whole should spread across many classes. The score is the exponential of the average KL divergence between each image’s class distribution and the overall class distribution. Higher is better.
It is rarely used alone now. It never looks at real images, so it cannot tell whether your samples resemble your dataset, only whether they resemble ImageNet classes. It is meaningless for faces, medical scans or anything far from ImageNet.
Fréchet Inception Distance
FID (Heusel and colleagues, 2017) fixes that by comparing against real data. Take the 2,048-dimensional pooling features of Inception v3 for a set of real images and a set of generated images, fit a Gaussian to each set, and compute the Fréchet distance between the two Gaussians:
FID = ||mu_real - mu_gen||^2 + Tr( Sigma_real + Sigma_gen - 2 * (Sigma_real * Sigma_gen)^(1/2) )
The first term catches a shift in average content; the second catches differences in spread and correlation, which is where missing modes show up. Lower is better, and 0 means identical statistics.
FID became the standard for GANs and diffusion models, and the GAN training and StyleGAN articles use it for picking checkpoints. Its numbers are fragile, though:
- It is biased by sample count. FID computed on 5,000 samples is systematically higher than on 50,000. Papers usually report FID on 50,000 generated images; only compare scores computed with the same count.
- Implementation details move it. The image resizing method, the exact Inception weights and JPEG compression of the reference set all change the result. Use one implementation for every model you compare.
- It collapses two properties into one number. A worse FID does not tell you whether fidelity or diversity got worse.
- The feature space has its own biases. Inception features were trained on ImageNet labels, so FID can reward images that trigger the right ImageNet features rather than images people prefer. Some recent work swaps in other encoders such as DINOv2 for this reason.
Computing FID with torchmetrics looks like this. By default it expects uint8 image tensors of shape [N, 3, H, W]:
import torch
from torchmetrics.image.fid import FrechetInceptionDistance
fid = FrechetInceptionDistance(feature=2048)
# real_batches and fake_batches yield uint8 tensors, shape [N, 3, H, W]
for real in real_batches:
fid.update(real, real=True)
for fake in fake_batches:
fid.update(fake, real=False)
print(f"FID: {fid.compute().item():.2f}")
Kernel Inception Distance (KID, Bińkowski and colleagues, 2018) uses the same features but a kernel-based distance that is unbiased with respect to sample size. It is a better choice when you can only afford a few thousand samples, for example on small datasets.
Precision and recall for generative models
To pull fidelity and diversity apart, Sajjadi and colleagues (2018) and then Kynkäänniemi and colleagues (2019) defined precision and recall for distributions. In the improved version, each set of embeddings is turned into a rough manifold by drawing a ball around every point that reaches its k-th nearest neighbour.
- Precision is the fraction of generated samples that fall inside the real manifold. Low precision means many unrealistic samples.
- Recall is the fraction of real samples that fall inside the generated manifold. Low recall means the model misses parts of the data, as in mode collapse.
This is the most useful diagnostic when a change moves FID and you want to know why. Truncation in StyleGAN, for example, trades recall for precision, and classifier-free guidance in diffusion models does the same.
CLIP score for text-to-image
For text-to-image models, FID only tells you the images look like the reference set, not that they match their prompts. CLIP score embeds the prompt and the image with a CLIP model and takes their cosine similarity, clipped at zero and rescaled (CLIPScore, Hessel and colleagues, 2021). Higher means better alignment. CLIP is weak at counting, spatial relations and text inside images, so benchmarks for compositional prompts often add question-answering checks or human ratings on top.
| Metric | Needs real data | Measures | Direction | Main weakness |
|---|---|---|---|---|
| Inception Score | No | Confidence and class spread | Higher | Ignores your dataset; ImageNet-only |
| FID | Yes | Overall distribution match | Lower | Biased by sample count; mixes fidelity and diversity |
| KID | Yes | Overall distribution match | Lower | Same feature-space bias as FID |
| Precision | Yes | Fidelity of samples | Higher | Sensitive to k and outliers |
| Recall | Yes | Coverage of the data | Higher | Sensitive to k and outliers |
| CLIP score | No (needs prompts) | Prompt alignment | Higher | Weak on counting and layout |
After a change, your GAN's FID gets worse. Which metric tells you whether the model lost diversity rather than image quality?
Correct! Recall measures how much of the real data the generated samples cover, so a drop points to lost diversity.
Text metrics with references
When a task has reference outputs, such as human translations or reference summaries, you can score a generated output by how much it overlaps with them.
BLEU (Papineni and colleagues, 2002) counts how many of the candidate’s n-grams, up to length 4, appear in the references, combines the four precisions with a geometric mean, and applies a brevity penalty so very short outputs cannot score well by being cautious. It was built for machine translation and is still reported there. Use sacrebleu for reported numbers: it fixes the tokenization, so scores from different papers are comparable.
ROUGE (Lin, 2004) is the recall-oriented counterpart used for summarization. ROUGE-1 and ROUGE-2 count unigram and bigram overlap; ROUGE-L uses the longest common subsequence.
BERTScore (Zhang and colleagues, 2020) replaces exact matches with similarity between contextual embeddings, so “the car is fast” and “the vehicle is quick” score as close. It correlates better with human judgement than BLEU on many tasks.
The Hugging Face evaluate library wraps all three:
import evaluate
predictions = ["the cat sat on the mat"]
references = [["a cat was sitting on the mat"]]
bleu = evaluate.load("sacrebleu")
rouge = evaluate.load("rouge")
print(bleu.compute(predictions=predictions, references=references)["score"])
print(rouge.compute(predictions=predictions, references=[r[0] for r in references]))
These metrics are cheap, deterministic and fine for tracking a model on a fixed task over time. They break down for open-ended generation. A chat answer can be excellent and share few words with the reference, or share most words and get one critical fact wrong. Overlap with one reference is a weak proxy when many answers are correct, which is why instruction-tuned models are rarely judged on BLEU.
Functional checks: does it work?
Some outputs can be tested directly, and when they can, that beats any similarity score.
For code, the standard is pass@k, from the Codex paper (Chen and colleagues, 2021): generate k samples per problem and count the problem as solved if any sample passes its unit tests. Sampling only k completions gives a noisy estimate, so the paper generates n samples (n greater than k), counts the c that pass, and uses an unbiased estimator:
from math import comb
def pass_at_k(n: int, c: int, k: int) -> float:
"""Probability that at least one of k samples drawn from n passes, given c passed."""
if n - c < k:
return 1.0
return 1.0 - comb(n - c, k) / comb(n, k)
# 200 samples, 37 pass the tests
print(round(pass_at_k(200, 37, 1), 3)) # 0.185
print(round(pass_at_k(200, 37, 10), 3)) # about 0.88
pass@1 is the number that matters when a user takes the first answer. pass@10 or pass@100 matters when you can generate several candidates and filter them, for example by running tests.
The same idea applies wherever a validator exists: does the JSON parse and match the schema, does the SQL execute and return the expected rows, does the extracted invoice total match the ledger, does the generated configuration pass a linter. These checks are cheap enough to run on every output, in testing and in production.
Model-graded evaluation
For open-ended text there is often no reference and no test. The practical answer that took over from 2023 onward is to have a strong model grade the output, usually called LLM-as-a-judge. Zheng and colleagues, in the paper that introduced MT-Bench and Chatbot Arena, found that a strong judge model agreed with human preferences about as often as humans agreed with each other on their benchmark.
There are three common setups.
- Single-answer grading. The judge scores one response on a scale, such as 1 to 5 for helpfulness, often with a rubric.
- Pairwise comparison. The judge sees two responses to the same prompt and picks the better one. This is more stable than absolute scores and suits A/B decisions such as “did the fine-tune beat the base model”.
- Reference-guided or rubric grading. The judge gets a reference answer or a checklist of what a good answer contains, and grades against it. This is how faithfulness or groundedness checks for retrieval-augmented systems work: the judge checks every claim in the answer against the retrieved passages.
sequenceDiagram
participant D as Eval dataset
participant M as Model under test
participant J as Judge model
participant R as Results
D->>M: Prompt
M->>J: Response
D->>J: Rubric or reference
J->>R: Score and reasoning
Note over J,R: Spot-check a sample against human labels
Judges have known biases, and an evaluation that ignores them produces confident wrong numbers.
- Position bias. In pairwise mode, judges tend to favour whichever answer comes first (or second, depending on the model). Run each pair twice with the order swapped and only count consistent verdicts.
- Verbosity bias. Longer answers tend to score higher whether or not they are better. State in the rubric that length is not a merit, and watch average length alongside scores.
- Self-preference. A judge may prefer outputs from its own model family. Where possible, use a judge from a different family than the model under test.
- Drift. A judge model update changes your scores. Pin the judge model version and treat a judge change like any other change to the test.
The way to trust a judge is to measure it. Have people label a few hundred examples, run the judge on the same examples, and check agreement before you rely on the judge for decisions.
You use a judge model to compare outputs from model A and model B, always showing A's answer first. What should you change?
Correct! Swapping the order controls for position bias, a well-documented tendency of judge models.
Human evaluation
People remain the reference that every other metric is checked against. Human evaluation comes in the same forms as model grading: ratings on a scale, side-by-side preferences, and checklists. Public leaderboards such as LMArena (formerly Chatbot Arena) collect large numbers of pairwise votes and turn them into rankings with a Bradley-Terry style model, similar to chess ratings.
For your own product, a smaller and more careful study is usually more useful than a big noisy one. Write clear guidelines with examples of each score, have at least two people rate the same items so you can measure agreement, and hide which model produced which output. Human review is slow and costly, so the usual pattern is to use it to calibrate automatic metrics and judges, and then to spot-check them, not to grade every run.
Building an evaluation suite
In practice you combine several of these, from cheapest to most expensive, and run them at different points.
flowchart LR
A["Code or model change"] --> B["Fast checks: schema, tests, perplexity"]
B -->|Pass| C["Task metrics on held-out set"]
C -->|Pass| D["Judge model, pairwise vs current"]
D -->|Pass| E["Human spot-check"]
E --> F["Ship and monitor"]
B -->|Fail| X["Fix"]
C -->|Fail| X
D -->|Fail| X
A few habits make the numbers trustworthy.
- Build the dataset from real use. A few hundred examples that look like production traffic, including the hard and embarrassing cases, beat thousands of generic ones. Add every bug report to the set.
- Keep it out of training. Public benchmarks leak into pretraining data, so a high score on a famous benchmark may reflect memorisation. Your private set is more honest, as long as it never ends up in a fine-tuning run. The model training and evaluation article covers held-out data in general.
- Fix the sampling settings. Temperature, top-p and the random seed change outputs. Evaluate with the settings you will use in production, and run more than one sample per prompt when outputs vary.
- Compare, don’t just score. An absolute score of 4.1 out of 5 means little. “The fine-tune wins 62% of pairwise comparisons against the base model on our set” is a decision.
- Track several numbers. Quality, safety, latency and cost per request all matter. A change that raises quality while doubling cost may not be worth shipping.
This loop is also what powers preference tuning: the same judges and human preferences become the reward signal described in Introduction to Reinforcement Learning in Generative AI.
Managed evaluation in the cloud
All three major clouds now have evaluation services aimed at generative AI, mostly built around LLM-as-a-judge. They differ in detail and change often, so check the current documentation before you build on a specific metric.
| AWS | Google Cloud | Azure | |
|---|---|---|---|
| Service | Amazon Bedrock Evaluations | Gen AI evaluation service on Vertex AI | Evaluations in Microsoft Foundry |
| Judge-based metrics | Correctness, completeness, faithfulness, harmfulness, answer refusal | Rubric metrics such as general quality, instruction following and grounding | Evaluators such as groundedness, relevance and coherence |
| Retrieval systems | Evaluates Bedrock Knowledge Bases or your own RAG pipeline | Grounding against provided context | Retrieval and groundedness evaluators |
| Other options | Human evaluation jobs, bring your own responses | Custom judge prompts, computation-based metrics | Python SDK (azure-ai-evaluation), safety evaluators |
On Bedrock, AWS maintains the judge models and judge prompts, and you can evaluate responses from models hosted elsewhere if you supply them in the expected JSONL format. On Google Cloud, the recommended starting point is adaptive rubrics, where the service writes a set of pass or fail checks for each prompt and reports the pass rate. In Foundry, evaluators return a score with a written reason, and several are still marked as preview.
These services save you writing judge prompts and plumbing, and they fit naturally if your model already runs on that platform. They do not remove the need for your own dataset, or for checking the judge against human labels. For the wider picture of each platform, see the overviews for AWS, Google Cloud and Azure.
You adopt a managed LLM-as-a-judge service. What do you still need to provide yourself?
Correct! The service runs the judging, but only you can supply data that reflects real use and verify that the judge agrees with people.
Further reading
- GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium, Heusel and colleagues, 2017 (FID)
- Improved Precision and Recall Metric for Assessing Generative Models, Kynkäänniemi and colleagues, 2019
- Demystifying MMD GANs, Bińkowski and colleagues, 2018 (KID)
- Evaluating Large Language Models Trained on Code, Chen and colleagues, 2021 (pass@k)
- Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena, Zheng and colleagues, 2023
- BERTScore: Evaluating Text Generation with BERT, Zhang and colleagues
- Amazon Bedrock Evaluations, Gen AI evaluation service overview and Foundry built-in evaluators
Key takeaways
- Generative models have no single right answer, so evaluation measures several properties: fidelity, diversity, conditioning, and correctness and safety.
- Perplexity and other likelihood scores suit pretraining and checkpoint comparisons, but only under the same tokenizer and data, and they do not track sample quality closely.
- FID is the standard image metric. Compare it only with the same sample count and implementation, and use precision and recall to see whether fidelity or diversity changed.
- BLEU, ROUGE and BERTScore work when references exist and outputs are constrained; they are weak for open-ended answers.
- When an output can be tested, test it: pass@k for code, schema and execution checks for structured output.
- LLM judges scale open-ended evaluation, but control for position and length bias, pin the judge version, and validate it against human labels.
- A useful suite runs cheap checks on every change and expensive ones before release, on a private dataset built from real use. Managed cloud services run the judging, not the dataset work.
Part 12 of 12 · Deep Dive into Generative Models
- 01Mathematical Foundations of VAEs
- 02Implementing VAEs: A Step-by-Step Guide
- 03Training GANs: Tips, Tricks, and Common Pitfalls
- 04Conditional GANs: Controlling the Output
- 05StyleGAN: Generating High-Resolution Images
- 06CycleGAN: Image-to-Image Translation
- 07Text Generation Models: From RNNs to Transformers
- 08The Transformer Architecture: Self-Attention Explained
- 09Implementing Transformers for Text Generation
- 10BERT vs. GPT: Encoders, Decoders, and Their Impact on NLP
- 11Fine-Tuning Pre-Trained Models for Specific Tasks
- 12Evaluation Metrics for Generative Models
