Discuss common metrics and approaches used to evaluate the quality of text generated by Large Language Models (LLMs).
Evaluating LLM-generated text combines intrinsic likelihood metrics (perplexity), reference-based overlap or embedding metrics (BLEU, ROUGE, METEOR, BERTScore), and task-specific execution or accuracy benchmarks. Because n-gram metrics correlate poorly with open-ended instruction quality and perplexity cannot be compared across different tokenizers, modern pipelines rely heavily on human preference ratings and calibrated LLM-as-a-Judge evaluations. A rigorous evaluation framework balances automatic scalability with human or judge audits for factuality, coherence, and safety.
Study Card: Evaluating Text Quality in LLMs
Direct Answer
Evaluating LLM-generated text requires combining intrinsic likelihood metrics, reference-based automatic metrics, task/verifiable benchmarks, and human or judge-based preference evaluation, since no single score captures fluency, factuality, helpfulness, and safety simultaneously.
- Perplexity (PPL) measures how well an autoregressive model predicts a held-out sequence:
Crucially, perplexity depends directly on tokenizer granularity (vocabulary size and tokens-per-word) and measures sequence probability rather than factual accuracy or instruction adherence.
- Lexical -gram metrics (BLEU, ROUGE, METEOR) compare surface token overlap against reference texts. They are fast and reproducible for constrained translation or summarization, but fail when valid paraphrases or creative responses differ lexically from references.
- Embedding & Judge approaches (BERTScore, LLM-as-a-Judge such as MT-Bench/G-Eval, and pairwise human preference / Elo ratings like Chatbot Arena) capture semantic equivalence, reasoning coherence, and instruction following—though LLM judges require position-swapping and length calibration to mitigate verbosity and self-enhancement biases.
Key Terms
- Perplexity: Exponential of average token negative log-likelihood; lower indicates tighter fit to the test corpus under a fixed tokenizer.
- BLEU (Bilingual Evaluation Understudy): Precision-oriented -gram overlap with a brevity penalty, standard in machine translation.
- ROUGE (Recall-Oriented Understudy for Gisting Evaluation): Recall- and F1-oriented -gram (
ROUGE-1/2) and longest common subsequence (ROUGE-L) overlap used in summarization. - METEOR: Incorporates stemming, synonymy, and chunk fragmentation penalties alongside word alignment.
- BERTScore: Computes precision, recall, and F1 over greedy cosine matching of contextual token embeddings rather than exact surface strings.
- LLM-as-a-Judge: Using a strong frontier model with structured rubrics or pairwise comparison to approximate human preference judgments at scale.
Example
Suppose an LLM generates a summary or open-ended technical explanation:
- Perplexity verifies whether the base model assigns sensible probability to held-out domain text, while bits-per-byte (BPB) normalizes likelihood across different tokenizers.
- ROUGE-L and BERTScore check whether a generated summary covers key reference points (with BERTScore still crediting valid synonyms like
"physician"vs."doctor"). - Verifiable benchmarks (
pass@kunit tests for code, exact numeric check for GSM8K/MATH) eliminate reference ambiguity where ground-truth execution exists. - Pairwise human / LLM-judge evaluations catch subtle hallucinations, tone mismatches, and formatting violations invisible to -gram metrics.
Code Implementation
import torch
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
# Optional libraries for model-based metrics:
# import transformers
# from rouge_score import rouge_scorer
# from bert_score import score as bert_score
# 1. Perplexity from token-level cross-entropy loss (exact formula)
vocab_size = 100
seq_len = 8
logits = torch.randn(1, seq_len, vocab_size)
input_ids = torch.randint(0, vocab_size, (1, seq_len))
# Autoregressive causal shift: predict token t+1 from logits at step t
shift_logits = logits[:, :-1, :].contiguous()
shift_labels = input_ids[:, 1:].contiguous()
nll_loss = torch.nn.functional.cross_entropy(
shift_logits.view(-1, vocab_size), shift_labels.view(-1)
)
perplexity = torch.exp(nll_loss)
print(f"Perplexity: {perplexity.item():.2f}")
# 2. Word-level BLEU score (MUST pass tokenized word lists, NOT raw strings!)
reference = "The quick brown fox jumps over the lazy dog."
candidate = "The quick brown fox jumped over the lazy dog."
ref_tokens = [reference.lower().rstrip(".").split()]
cand_tokens = candidate.lower().rstrip(".").split()
smooth = SmoothingFunction().method1
bleu = sentence_bleu(ref_tokens, cand_tokens, smoothing_function=smooth)
print(f"Word-level BLEU: {bleu:.4f}")
# 3. ROUGE and BERTScore usage (requires `rouge-score` / `bert-score` installed):
# scorer = rouge_scorer.RougeScorer(["rouge1", "rougeL"], use_stemmer=True)
# rouge_scores = scorer.score(reference, candidate)
# P, R, F1 = bert_score([candidate], [reference], lang="en")
Related Concepts
- Tokenizer-Normalized Likelihood (Bits-per-Byte): Enables fair perplexity comparisons across models with different BPE vocabularies.
- Evaluation Biases: LLM judges exhibit position bias, verbosity bias, and self-preference; human evaluations can suffer inter-annotator variance and prompt distribution skew.
- Execution-Based & Reasoning Metrics:
pass@kfor code synthesis and outcome/process verification for multi-step math. - Factuality & RAG Metrics: Faithfulness, context recall, and citation precision (e.g., RAGAS / TruLens) for grounded generation.
- Quality vs. Diversity Trade-off: Decoding settings (temperature, top-) trade off peak accuracy against lexical and reasoning diversity.