I. Why Model Evaluation Is Needed
The parameter scale, training data volume, and architectural complexity of a large model do not directly represent its effectiveness in real-world applications.
A model with more parameters is not necessarily better than a smaller model on every task; a model that ranks high on public leaderboards is not necessarily suitable for an enterprise's internal knowledge Q&A, code generation, or agent tasks.
The core goal of model evaluation is to answer the following questions:
- Is the capability sufficient? Can the model complete the target task, correctly understand the input, and generate the right result?
- Is the quality stable? Does the output remain consistent when faced with different questions, different phrasings, and complex inputs?
- Does the performance meet requirements? Do response latency, throughput, concurrency capacity, and resource consumption meet the requirements?
- Is the cost reasonable? How much compute cost is required per request, per token, or per successful task?
- Is the safety reliable? Is the model prone to hallucinations, policy-violating content, privacy leakage, or prompt injection issues?
- Is it suitable for production? Can it reliably provide service under real traffic, complex dependencies, and continuous operation?
Model evaluation is not a single accuracy test, but a comprehensive engineering effort covering model capability, inference performance, business value, and production reliability.
1. The Three Dimensions of Model Evaluation
| Dimension | Main Focus | Typical Metrics |
|---|---|---|
| Model quality evaluation | Whether the output is correct, useful, and reliable | Accuracy, F1, EM, Pass@k, human rating |
| Benchmark testing | Overall capability on standard tasks | MMLU, GSM8K, HumanEval, MATH |
| Performance testing | Service speed, throughput, and resource efficiency | TTFT, TPOT, TPS, QPS, P95, GPU utilization |
The three are connected, but they cannot substitute for one another.
For example:
- A high Benchmark score does not mean fast inference.
- High TPS does not mean the model answers correctly.
- Low average latency does not mean it remains stable under high concurrency.
- Excellent human evaluation does not mean the model has no safety issues.
2. The Complete Model Evaluation Process
flowchart TD
A["Define evaluation goals"] --> B["Define evaluation dimensions and metrics"]
B --> C["Build evaluation dataset"]
C --> D["Select models and test configurations"]
D --> E["Run model evaluation"]
E --> F["Compute metrics and analyze results"]
F --> G{"Are goals met?"}
G -->|Met| H["Produce evaluation report"]
G -->|Not met| I["Identify issues and optimize the model"]
I --> D
H --> J["Deployment validation and continuous monitoring"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#EAF3EC,stroke:#83A995,color:#315D49
style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style H fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style I fill:#F7EAE7,stroke:#C98D7C,color:#754438
style J fill:#E5F0E9,stroke:#83A995,color:#315D49
II. Core Metrics of Model Evaluation
Different tasks require different evaluation methods. The evaluation metrics for classification, generation, reasoning, code, and retrieval tasks differ noticeably.
1. Accuracy
Accuracy is the proportion of samples that the model predicts correctly out of all samples.
Where:
- TP: true positive — actually positive and predicted positive.
- TN: true negative — actually negative and predicted negative.
- FP: false positive — actually negative but predicted positive.
- FN: false negative — actually positive but predicted negative.
For example, the model makes predictions on 1000 classification samples, of which 920 are correct:
Accuracy is suitable for classification tasks with a relatively balanced class distribution.
But if the positive and negative samples are extremely imbalanced, accuracy can be misleading.
For example, in a fraud detection dataset, 99% of transactions are normal transactions. Even if the model always predicts "normal," it can achieve 99% accuracy, yet it is completely unable to identify fraudulent behavior.
Therefore, it needs to be analyzed together with Precision, Recall, and F1.
2. Precision
Precision is the proportion of samples that the model predicts as positive that are actually positive.
The higher the precision, the fewer false positives the model produces.
It is suitable for scenarios where the cost of false positives is high, for example:
- Spam detection.
- Fraudulent transaction identification.
- Policy-violating content detection.
- Automated banning and risk blocking.
3. Recall
Recall represents the proportion of all actual positive instances that the model successfully identifies.
The higher the recall, the fewer missed detections.
It is suitable for scenarios where the cost of false negatives is high, such as:
- Medical screening support.
- Security threat detection.
- Fraud detection.
- Fault alerting.
Precision and Recall usually have a trade-off relationship.
Raising the recognition threshold may reduce false positives but may also increase false negatives; lowering the recognition threshold may increase recall but may also increase false positives.
4. F1 Score: Comprehensive Evaluation Metric
F1 is the harmonic mean of Precision and Recall.
F1 is high only when both Precision and Recall are high.
F1 is suitable for tasks that need to consider both false positives and false negatives.
If the business values the two differently, you can use F_\beta:
- \beta>1: More emphasis on Recall.
- \beta<1: More emphasis on Precision.
- \beta=1: This is F1.
5. Exact Match: Exact Matching
Exact Match (EM) is used to measure whether a model's answer exactly matches the reference answer.
For example:
Reference answer:
The capital of France is Paris.
Model answer:
Paris
If strict string matching is used, the two may be judged as not matching.
Therefore, in actual evaluation, answer normalization is needed first, for example:
- Remove extra spaces.
- Standardize capitalization.
- Handle punctuation.
- Remove formatting differences that do not affect meaning.
EM is suitable for tasks with clear answer boundaries, but it is not suitable for directly evaluating open-ended text generation.
6. BLEU: Machine Translation Evaluation
BLEU is mainly used for machine translation. It evaluates by calculating the degree of n-gram overlap between the model-generated text and the reference text.
The core idea is:
- Count the n-grams that appear in the generated text.
- Calculate how well these n-grams match the reference text.
- Use a length penalty to prevent the model from obtaining a high score by generating overly short text.
BLEU usually uses a geometric mean:
Where:
- p_n: n-gram precision.
- w_n: weights of different n-grams.
- BP: length penalty factor.
BLEU is relatively sensitive to wording differences, so it cannot fully represent translation quality.
7. ROUGE: Text Summarization Evaluation
ROUGE is commonly used for summarization tasks, focusing on the degree of content overlap between the generated summary and the reference summary.
Common types:
| Metric | Meaning |
|---|---|
| ROUGE-1 | Word-level overlap |
| ROUGE-2 | Overlap of two consecutive words |
| ROUGE-L | Overlap based on the longest common subsequence |
ROUGE-L can identify the relative order of words in a sequence, but it still cannot fully judge whether the semantics are correct.
For example, if two sentences express the same fact using different wording, ROUGE may give a lower score.
8. Perplexity
Perplexity (PPL) is a classic metric for measuring the predictive capability of language models.
For a Token sequence of length N:
It can be understood as the degree of uncertainty when the model predicts the next Token.
Usually:
- The lower the PPL, the more accurately the model predicts the test corpus.
- The higher the PPL, the more uncertain the model's prediction on the test corpus.
However, note the following:
- PPL values across different Tokenizers are not necessarily directly comparable.
- Different corpora, text lengths, and preprocessing methods can affect the results.
- A low PPL does not necessarily mean the model has stronger reasoning ability.
- PPL cannot directly measure whether a response aligns with user intent.
Therefore, PPL is better suited to language modeling research and training process analysis, and is not suitable as a standalone final quality metric for general-purpose large models.
III. LLM-Specific Evaluation Metrics
Traditional machine learning metrics cannot fully measure the capabilities of large language models.
LLMs not only need to generate correct content, but also need to understand instructions, follow formats, perform reasoning, call tools, and maintain consistency in complex contexts.
1. Task Success Rate
Task success rate measures whether a model successfully completes a predefined task.
For example, an agent needs to complete the following:
- Query the order.
- Calculate the fee.
- Call the payment API.
- Return the processing result.
A task is considered successful only when it reaches the expected final state.
For an agent, a single correct model call does not mean the entire task is successful.
Therefore, evaluation needs to be performed at the task level, not just at the token or single-turn response level.
2. Instruction-Following Ability
Instruction Following measures whether a model accurately understands and follows user requirements.
Typical evaluation criteria:
- Whether the output is in the specified format.
- Whether the length limit is followed.
- Whether the specified language is used.
- Whether required fields are retained.
- Whether prohibited content is avoided.
- Whether multi-step constraints are followed.
For example:
User request:
Please return name, age, and occupation in JSON format.
Do not add any explanation.
Model output:
{
"name": "Alice",
"age": 28,
"occupation": "Engineer"
}
Such tasks can be automatically scored using JSON Schema, field completeness, type checking, and other methods.
3. Hallucination Rate
Hallucination Rate is used to measure the proportion of content generated by a model that is false or unsupported.
During evaluation, it is necessary to clarify what counts as a hallucination:
- Fabricating facts that do not exist.
- Inventing citations and sources.
- Describing uncertain content as established fact.
- Citing information that does not exist in the referenced materials.
- Misinterpreting retrieved evidence.
For RAG systems, it is also necessary to distinguish:
- Retrieval error: correct materials were not found.
- Generation error: retrieval results were correct, but the model misunderstood them.
- Insufficient evidence: the materials cannot support the conclusion, but the model still answers.
An evidence-based faithfulness metric can be further designed:
Note that hallucination detection itself can also make mistakes. Automated evaluators should be combined with manual spot checks.
4. Reasoning Ability
Reasoning ability usually needs to be evaluated through multi-step problems.
For example:
- Mathematical reasoning.
- Logical reasoning.
- Causal inference.
- Complex conditional judgment.
- Multi-hop knowledge reasoning.
- Long-context information integration.
Common evaluation methods include:
- Final answer accuracy.
- Pass rate on reasoning tasks.
- Completion rate of multi-step tasks.
- Stability under changes in input conditions.
For mathematical and logical tasks, use verifiable final answers or programmatic verifiers where possible, rather than only judging whether the model's explanation is fluent.
5. Tool-Calling Ability
For agents and tool-augmented models, the accuracy of tool calls needs to be evaluated.
| Metric | Description |
|---|---|
| Tool Selection Accuracy | Whether the correct tool is selected |
| Parameter Accuracy | Whether parameters are correct |
| Tool Call Success Rate | Whether the tool call succeeds |
| Tool Argument Validity | Whether parameters satisfy the Schema |
| End-to-End Success Rate | Whether the entire task is completed |
| Unnecessary Call Rate | Whether unnecessary calls were made |
Tool-call evaluation cannot only check whether the model outputs the correct function name.
It also needs to check parameters, execution results, and the final task state.
6. Long-Context Ability
Long-context evaluation focuses on whether a model can accurately find, understand, and use information in longer inputs.
Typical tests:
- Long Context Retrieval: locating information in long texts.
- Multi-hop QA: integrating answers across multiple paragraphs.
- Needle-in-a-Haystack: finding specified information in a large amount of distracting text.
- Long Document Summarization: long document summarization.
- Context Consistency: information consistency in long contexts.
Particular attention should be paid to the fact that a model supporting a 128K token context does not mean it can still maintain high quality at 128K tokens.
Quality changes under different context lengths should be tested.
7. Safety Evaluation
Safety evaluation usually includes:
- Harmful content generation.
- Resistance to jailbreak attacks.
- Resistance to prompt injection.
- Sensitive information leakage.
- Privacy protection.
- Bias and fairness.
- Unsafe tool calls.
- Multi-tenant data isolation.
Common metrics include:
ASR stands for Attack Success Rate.
For security testing, a lower ASR is generally better, but the coverage of attack samples and the definition of a successful attack must be clearly specified.
IV. Benchmark: Model Benchmarking
A benchmark is a standardized mechanism for test tasks, datasets, evaluation rules, and result reporting.
Its purpose is to allow different models to be compared under relatively consistent conditions.
1. Components of a Benchmark
A complete benchmark usually includes:
- Test dataset.
- Input and output specifications.
- Evaluation metrics.
- Scoring program.
- Test environment.
- Model configuration.
- Result statistics and reporting.
A benchmark is more than just a dataset.
The same dataset can produce markedly different results when different prompts, sampling parameters, or scoring methods are used.
2. Common LLM Benchmarks
MMLU: Multitask Knowledge and Understanding
MMLU evaluates a model's knowledge understanding and reasoning ability through multiple-choice questions across a range of subject areas.
The covered domains include:
- Mathematics.
- Physics.
- Chemistry.
- Biology.
- History.
- Law.
- Medicine.
- Computer science.
Its primary evaluation metric is accuracy.
MMLU is suitable for measuring a model's performance on multidisciplinary knowledge tasks, but it cannot fully represent comprehensive capability in real-world applications.
MMLU-Pro: A More Challenging Knowledge Evaluation
MMLU-Pro raises task difficulty on top of the original multidisciplinary test and improves the question design.
It places greater emphasis on:
- Deep knowledge understanding.
- Complex reasoning.
- Reducing the impact of simple guessing.
- More challenging discrimination among choices.
GSM8K: Mathematical Reasoning Ability
GSM8K is a dataset of grade-school math word problems that primarily tests whether a model can solve problems through multi-step calculation.
For example:
A store has 24 apples.
In the morning it sells 8, and in the afternoon it sells 1/2 of the remaining apples.
How many apples does the store have left?
Correct calculation:
The final answer is 8.
GSM8K can be scored automatically based on the final answer, but it cannot by itself measure the ability to produce complex mathematical proofs.
MATH: High-Difficulty Mathematical Reasoning
MATH is used to test more complex math problems, covering:
- Algebra.
- Geometry.
- Number theory.
- Probability.
- Combinatorics.
- Calculus.
Compared with basic arithmetic tests, it places more emphasis on complex reasoning and the application of mathematical knowledge.
HumanEval: Code Generation Ability
HumanEval evaluates a model's ability to generate executable code through programming problems.
A common metric is Pass@k.
Where:
- n: the total number of code samples generated by the model.
- c: the number of code samples that pass the tests.
- k: the number of samples allowed to be selected from the generated ones.
Pass@1 represents the pass capability when only a single candidate code sample is allowed.
Pass@k represents an estimate of the probability that at least one sample passes when selecting from multiple candidates.
HumanEval verifies code primarily using unit tests; correctness should not be judged solely by textual similarity of the code.
MBPP: Basic Python Programming Ability
MBPP contains a larger number of basic Python programming tasks and is suitable for evaluating a model's ability to complete simple programming problems.
It can complement the test coverage of HumanEval.
BIG-bench: Comprehensive Capability Evaluation
BIG-bench is a comprehensive evaluation suite covering a wide variety of tasks, including:
- Language understanding.
- Mathematical reasoning.
- Commonsense judgment.
- Knowledge question answering.
- Logical tasks.
- Multilingual tasks.
Its value lies in exploring the boundaries of a model's capabilities across many kinds of tasks.
GPQA: Professional Knowledge and Scientific Reasoning
GPQA primarily assesses graduate-level scientific knowledge and reasoning ability.
It covers fields such as physics, chemistry, and biology, and its questions are designed to be professionally challenging.
MT-Bench: Multi-Turn Dialogue Evaluation
MT-Bench evaluates a model's conversational ability using multi-turn dialogue tasks, typically scoring responses with a model-based judge.
It can evaluate:
- Instruction following.
- Multi-turn context understanding.
- Reasoning.
- Role consistency.
- Content quality.
However, model judges themselves are biased, so the scoring results require human calibration.
SWE-bench: Software Engineering Task Evaluation
SWE-bench primarily tests a model's ability to solve problems in real software repositories.
Tasks typically involve:
- Reading the codebase.
- Understanding the issue.
- Modifying code.
- Fixing bugs.
- Running tests.
- Submitting a patch.
It is closer to real software engineering scenarios than simple code generation.
3. Overview of Benchmark Categories
| Benchmark | Main Evaluation Capability | Common Evaluation Method |
|---|---|---|
| MMLU | Multidisciplinary knowledge | Accuracy |
| MMLU-Pro | High-difficulty knowledge reasoning | Accuracy |
| GSM8K | Math word problems | Exact Match |
| MATH | Complex mathematical reasoning | Accuracy |
| HumanEval | Code generation | Pass@k |
| MBPP | Basic programming | Pass@k |
| BIG-bench | Comprehensive task capability | Task-specific metrics |
| GPQA | Expert-level scientific reasoning | Accuracy |
| MT-Bench | Multi-turn dialogue | Judge Score |
| SWE-bench | Software engineering capability | Resolved Rate |
4. Why You Cannot Look at Only One Benchmark
Models have different capabilities across tasks.
For example:
| Model | Math Ability | Coding Ability | Dialogue Ability | Reasoning Ability |
|---|---|---|---|---|
| Model A | High | Medium | High | High |
| Model B | Medium | High | Medium | High |
| Model C | High | High | Medium | Medium |
The results here are illustrative only.
If a company is mainly building a coding assistant, coding ability is more important than general knowledge scores.
If a company is building a customer service system, instruction following, factual accuracy, and response latency may be more critical.
Therefore, benchmarks should be selected based on actual business objectives rather than blindly chasing leaderboard rankings.
5. How to Build Your Own Evaluation Dataset
Public benchmarks are suitable for side-by-side comparison, but enterprise applications often require their own test datasets.
The reason is that public datasets may not cover the following in real business:
- Domain terminology.
- Proprietary knowledge.
- Specialized business processes.
- Complex permission constraints.
- User expression habits.
- Abnormal inputs.
- Specific output formats.
1. Dataset Design Principles
An effective evaluation dataset should meet the following requirements.
Representativeness
Covers real user questions and actual task distributions.
Diversity
Includes different difficulty levels, different ways of expression, and different input lengths.
Verifiability
Each sample should have a clear expected result or evaluation criterion.
Independence
The test set must not heavily overlap with the training set, fine-tuning set, or prompt optimization data.
Stability
Evaluation datasets should be version-controlled to ensure fair comparison between different models.
Security
It should include test samples such as unauthorized access, injection, privacy leakage, and malicious input.
2. Dataset Layering
The evaluation dataset can be divided into five layers:
| Layer | Content | Goal |
|---|---|---|
| Basic Set | Simple routine questions | Verify basic capabilities |
| Core Set | High-frequency business questions | Verify business usability |
| Hard Set | Multi-step, complex inputs | Verify capability ceiling |
| Adversarial Set | Jailbreaks, ambiguity, abnormal inputs | Verify robustness |
| Regression Set | Historical defects and failure cases | Prevent capability regression |
3. Dataset Sample Format
It is recommended to use JSONL for storage, with each line corresponding to one evaluation sample.
{
"id": "qa_0001",
"category": "knowledge_qa",
"difficulty": "medium",
"input": "什么是负载均衡?",
"reference": "负载均衡是将请求分配到多个服务实例的机制。",
"evaluation": {
"method": "rubric",
"required_points": [
"请求分配",
"多个服务实例",
"提高可用性或资源利用率"
]
},
"tags": [
"network",
"backend"
]
}
Different evaluation configurations can be used for different tasks:
- Classification tasks: labels and accuracy.
- Math tasks: reference answers and computational verification.
- Coding tasks: test cases and execution environment.
- RAG tasks: reference answers, evidence documents, and citation requirements.
- Agent tasks: task objectives, tool-call records, and terminal-state judgments.
4. Isolating Training, Validation, and Test Sets
flowchart TD
A["Raw evaluation data"] --> B["Data cleaning and deduplication"]
B --> C["Data classification and annotation"]
C --> D["Training data"]
C --> E["Validation data"]
C --> F["Test data"]
D --> G["Model training or fine-tuning"]
E --> H["Prompt and parameter tuning"]
F --> I["Final independent evaluation"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style F fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#EAF3EC,stroke:#83A995,color:#315D49
style I fill:#DCEFE5,stroke:#4F8B70,color:#24563F
The test set should be kept as independent as possible.
If prompts are repeatedly adjusted based on test-set results, and the same test set is then used to report final performance, test-set overfitting may occur.
More reliable practices include:
- Use the validation set for optimization.
- Use the test set for final evaluation.
- Regularly update the hidden test set.
- Keep historical test sets for regression.
5. Data Contamination
Data Contamination refers to evaluation data having already been exposed to the model during training or fine-tuning.
This can cause the following problems:
- The model memorizes the answers to the questions.
- The model memorizes reference solutions.
- The model gains an advantage from similar samples in the training corpus.
- Public test questions have already been included in the pre-training data.
Data contamination inflates Benchmark scores.
Mitigation methods include:
- Use private test sets.
- Use dynamically generated data.
- Regularly update test samples.
- Check the training and test sets for semantic similarity.
- Add task variants and counterfactual samples.
- Use real business tasks for supplementary evaluation.
VI. LLM-as-a-Judge: Using Models to Evaluate Models
Open-ended generation tasks usually do not have a single correct answer.
For example:
Question: How can system availability be improved?
Answer A:
Add redundant instances, deploy health checks, and configure circuit breaking and failover.
Answer B:
Improve server performance.
Simple string matching cannot determine which answer is better.
In this case, LLM-as-a-Judge can be used, where one model acts as a judge and evaluates the output of another model.
1. Basic Working Principle
The judge model receives:
- The user question.
- The answer generated by the model.
- Evaluation criteria.
- Scoring rules.
It then outputs a score and the rationale for the evaluation.
flowchart TD
A["User question"] --> B["Model being evaluated"]
B --> C["Generated response"]
A --> D["Evaluation task"]
C --> D
D --> E["Judge model (Judge)"]
E --> F["Score and evaluation rationale"]
F --> G["Statistics and quality analysis"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#EAF3EC,stroke:#83A995,color:#315D49
style G fill:#DCEFE5,stroke:#4F8B70,color:#24563F
2. Common Scoring Dimensions
| Dimension | Evaluation content |
|---|---|
| Correctness | Is the content correct |
| Relevance | Does it answer the question |
| Completeness | Does it cover the key content |
| Coherence | Is the logic coherent |
| Clarity | Is it easy to understand |
| Faithfulness | Is it faithful to the reference material |
| Safety | Does it meet safety requirements |
| Instruction Following | Does it follow instructions |
A 1–5 scoring rubric can be set for each dimension.
For example:
| Score | Evaluation criteria |
|---|---|
| 1 | Critical errors, unusable |
| 2 | Obvious flaws |
| 3 | Basically correct, but with omissions |
| 4 | Accurate content, basically complete |
| 5 | Accurate, complete, and well expressed |
3. Judge Prompt Example
You are a strict, objective model evaluation expert.
Please evaluate the model response based on the user question and the scoring criteria.
User question:
{{question}}
Model response:
{{answer}}
Scoring dimensions:
1. Correctness: Are there any factual errors?
2. Completeness: Does it cover the necessary information?
3. Relevance: Does it actually answer the question?
4. Clarity: Are the structure and expression clear?
Scoring range:
1–5 points.
Requirements:
- Do not increase the score because the response is long.
- Do not ignore factual errors because the language is fluent.
- Clearly point out when you are uncertain.
- You must provide the basis for the score.
Output JSON:
{
"correctness": 0,
"completeness": 0,
"relevance": 0,
"clarity": 0,
"overall": 0,
"reason": "Scoring rationale"
}
In production, judge results should be validated against a JSON Schema to prevent the judge model from outputting invalid formats.
4. Common Biases in LLM-as-a-Judge
Position bias
The judge model may favor responses that appear earlier or later.
Solution: Swap the A/B order and repeat the evaluation.
Length bias
Longer responses may receive higher scores because they contain more information, even if the content is redundant.
Solution: Explicitly require evaluation of correctness rather than length.
Self-preference
The judge model may prefer answers whose expression style is similar to its own.
Solution: Use judge models with different architectures and add human calibration.
Scoring drift
Different judge models, prompts, and run times may produce different scores.
Solution: Fix the judge model version, prompt, and scoring criteria.
Factual judgment errors
Judge models may fail to identify subtle factual errors in specialized domains.
Solution: Use reference answers, rule-based validators, external evidence, and manual spot checks.
5. Pairwise Comparison: Paired Comparison
In addition to absolute scoring, you can also have the judge model compare the responses of two models.
Output:
- A is better.
- B is better.
- The two are equivalent.
- Neither is acceptable.
Pairwise comparison usually makes it easier to maintain relative consistency than directly assigning absolute scores.
However, response order bias still needs to be controlled, and repeated experiments should be conducted.
VII. Performance Testing: From Model Capability to Inference Efficiency
Model quality answers whether the model can perform the task well.
Performance testing answers whether the model can complete the task within the specified time and resource constraints.
For online inference services, performance usually includes:
- Response latency.
- First-token latency.
- Token generation speed.
- Request throughput.
- Concurrency handling capacity.
- GPU and VRAM usage.
- Cost per token.
1. QPS: Queries Per Second
QPS (Queries Per Second) indicates the number of requests processed per second.
For example, if 6,000 requests are successfully processed in 60 seconds:
Note that QPS measures request throughput, not token throughput.
For generative models, a request may generate only 10 tokens or as many as 1,000 tokens.
Therefore, looking at QPS alone may not accurately reflect the inference workload.
2. TPS: Tokens Per Second
TPS (Tokens Per Second) is used to measure token processing speed.
In LLM services, it is usually necessary to distinguish:
Input token throughput
Output token throughput
Total token throughput
Different inference frameworks may use different statistical definitions.
For example, whether input tokens that hit the cache are counted as processed tokens should be explicitly stated in the test report.
3. TTFT: Time to First Token
TTFT (Time To First Token) is the time from when a request is sent until the client receives the first generated token.
TTFT mainly reflects:
- Request queuing time.
- Network transmission time.
- Prompt preprocessing.
- Prefill computation.
- First-token scheduling and generation.
The lower the TTFT, the sooner users see the model start to respond.
For streaming chat applications, TTFT is very important to user perception.
4. TPOT: Average Time per Output Token
TPOT (Time Per Output Token) is the average time required per output token during the generation phase.
Where:
- N_{\text{output}}: Number of output tokens.
- The first-token time is not included in the average interval between subsequent tokens.
A lower TPOT generally means faster output generation.
For example, if the model generates 101 tokens:
- The first token arrives at 500 ms.
- The last token arrives at 2500 ms.
Then:
The corresponding average generation speed is approximately:
That is, approximately 50 tokens are generated per second.
5. ITL: Inter-Token Latency
ITL (Inter-Token Latency) is the time interval between the arrivals of two consecutive tokens.
TPOT is usually the average of the token intervals.
However, an average can mask jitter during generation.
For example:
Token 1 → 20ms
Token 2 → 22ms
Token 3 → 18ms
Token 4 → 350ms
Token 5 → 21ms
The average TPOT may look acceptable, but users will clearly perceive a pause in one generation.
Therefore, in addition to average TPOT, you should also examine the P95, P99, and time-series distribution of ITL.
6. Latency Percentiles
Performance tests should not look only at average latency.
Common metrics:
- P50: 50% of requests have a latency no higher than this value.
- P90: 90% of requests have a latency no higher than this value.
- P95: 95% of requests have a latency no higher than this value.
- P99: 99% of requests have a latency no higher than this value.
- P99.9: 99.9% of requests have a latency no higher than this value.
For example:
| Metric | Latency |
|---|---|
| P50 | 400 ms |
| P90 | 700 ms |
| P95 | 900 ms |
| P99 | 1800 ms |
This means most requests are relatively fast, but a small number still have high latency.
For production services, tail latency is especially important.
7. Concurrency and Throughput
Concurrency is the number of requests being processed at the same time.
In model serving, concurrent requests usually compete for:
- GPU compute resources.
- GPU memory.
- KV Cache.
- CPU.
- Network bandwidth.
- Inference scheduling resources.
Increasing concurrency does not necessarily lead to linear throughput growth.
Once the GPU or GPU memory reaches its bottleneck, further increasing concurrency may cause:
- Increased queuing time.
- Higher TTFT.
- Worse TPOT.
- OOM.
- Request timeouts.
- A decline in overall service throughput.
8. Little's Law: Relationship Between Concurrency and Latency
Little's Law is commonly used in queueing systems:
Where:
- L: Average number of requests in the system.
- \lambda: Average arrival rate.
- W: Average time a request spends in the system.
For example:
- 50 requests arrive per second.
- The average request processing time is 2 seconds.
Then the average number of requests in the system is:
requests.
This relationship can be used for a preliminary estimate of service concurrency requirements.
But it cannot directly replace GPU capacity testing, nor can it independently predict the actual performance of LLMs at different token lengths.
8. Key Factors Affecting LLM Inference Performance
Traditional web services mainly focus on request processing time.
LLM inference, by contrast, is jointly affected by factors such as prompt length, output length, model size, concurrency, GPU compute capability, and KV Cache.
1. Prefill Phase
The Prefill phase processes the entire input prompt.
Main characteristics:
- Input tokens can usually be computed in parallel.
- The amount of computation is closely related to input length.
- It needs to generate and write the KV Cache.
- Long prompts can significantly increase TTFT.
Therefore, the number of input tokens is an important factor affecting Prefill performance.
2. Decode Phase
The Decode phase generates output tokens step by step.
Main characteristics:
- It usually generates tokens autoregressively.
- Each step needs to use the previous context state.
- It frequently accesses model weights and the KV Cache.
- It is affected by GPU memory bandwidth, compute resources, and scheduling efficiency.
For large models, the Decode phase may be limited by memory bandwidth.
3. Performance Differences Between Prefill and Decode
| Aspect | Prefill | Decode |
|---|---|---|
| Input | Entire prompt | Context and preceding tokens |
| Computation mode | Massively parallel computation | Token-by-token generation |
| Primary focus | Compute throughput | Token generation speed |
| Main impact | Input length | Output length, concurrency, and KV Cache |
| Main latency | Time to first token latency | Inter-token interval |
4. Main Factors Affecting Inference Performance
| Factor | Impact on Performance |
|---|---|
| Model parameter size | Increases compute and memory requirements |
| Input length | Increases Prefill load |
| Output length | Increases Decode duration |
| Concurrent requests | Increases resource contention |
| Batch Size | Affects GPU utilization and per-request latency |
| KV Cache | Determines the context and concurrency scale that can be accommodated |
| GPU memory bandwidth | Affects weight and cache read efficiency |
| Quantization precision | Affects memory usage and compute performance |
| Tensor parallelism | Changes communication and compute distribution across multiple GPUs |
| Network communication | Affects cross-GPU and cross-node inference efficiency |
5. Impact of KV Cache on Concurrency
The KV Cache stores the Key and Value of historical tokens in the Transformer.
It avoids recomputing the attention representations of all historical tokens during the Decode phase.
However, the KV Cache itself requires GPU memory.
As context length and concurrent requests increase, KV Cache usage also increases.
Therefore, the capacity of an inference service is not determined solely by the size of the model weights; it also needs to take the following into account:
- The context length of each request.
- The maximum number of output tokens.
- The number of concurrent requests.
- The data precision of the KV Cache.
- GPU memory capacity.
- The cache management strategy of the inference framework.
If KV Cache is insufficient, request queuing, cache eviction, preemption, or request rejection may occur.
9. Types of Performance Testing
Different types of performance testing are used to answer different questions.
1. Smoke Test
Smoke testing verifies whether the system can run normally.
Main checks:
- Whether the model loads successfully.
- Whether the API is accessible.
- Whether a single inference can be completed.
- Whether the output format is correct.
- Whether the basic latency is reasonable.
- Whether the GPU is working properly.
Smoke testing usually uses a small number of requests and does not pursue peak performance.
2. Load Test
Load testing verifies whether the system meets performance targets under expected load.
For example:
- 100 requests per second.
- Concurrency of 50.
- Input of 1000 tokens.
- Output of 200 tokens.
- Run continuously for 30 minutes.
Observe:
- P95 and P99 latency.
- TTFT and TPOT.
- Request error rate.
- GPU utilization.
- GPU memory usage.
- Queue length.
3. Stress Test
Stress testing continuously increases system load until the system approaches or reaches its limit.
Objectives include:
- Find the maximum throughput.
- Find the maximum stable concurrency.
- Identify resource bottlenecks.
- Observe behavior under overload.
- Verify whether the system can degrade gracefully.
Stress testing should not only observe when the system crashes; it should also determine whether the system can protect core business functions under overload.
4. Spike Test: Burst Traffic Testing
Burst traffic testing simulates a sudden increase in request volume.
For example:
Normal traffic: 50 QPS
Burst traffic: 500 QPS
Duration: 60 seconds
Recovery traffic: 50 QPS
Key observations:
- Request queueing.
- Auto-scaling speed.
- GPU resource scheduling.
- Rate-limiting strategy.
- Service recovery time.
- Resource reclamation after the burst traffic ends.
5. Soak Test: Long-Term Stability Testing
Soak Test is also called endurance testing.
It usually lasts several hours or even several days.
It primarily detects:
- VRAM leaks.
- Memory leaks.
- Connection pool exhaustion.
- Handle leaks.
- Throughput degradation after long-running operation.
- Queue backlog.
- GPU errors.
- Background task accumulation.
For long-running model services, Soak Test is very important.
6. Scalability Test: Scalability Testing
Scalability testing focuses on whether system throughput can be effectively improved after adding resources.
For example:
| Number of GPUs | Throughput |
|---|---|
| 1 | 1000 tokens/s |
| 2 | 1850 tokens/s |
| 4 | 3400 tokens/s |
| 8 | 6100 tokens/s |
The data here is for illustration only.
If the number of GPUs increases by 8 times but throughput does not increase by 8 times, there may be:
- Communication overhead.
- Scheduling bottlenecks.
- CPU bottlenecks.
- Network bandwidth limitations.
- Reduced model parallelism efficiency.
7. Comparison of Performance Test Types
| Test Type | Primary Purpose | Typical Question |
|---|---|---|
| Smoke Test | Verify basic functionality | Can the service start? |
| Load Test | Verify expected load | Does it meet the target QPS? |
| Stress Test | Verify system limits | What is the maximum stable throughput? |
| Spike Test | Verify burst capacity | What happens when traffic suddenly increases? |
| Soak Test | Verify long-term stability | Does it degrade after long running? |
| Scalability Test | Verify scaling efficiency | Is adding GPUs effective? |
8. Performance Test Execution Process
flowchart TD
A["Define performance goals"] --> B["Prepare model and test environment"]
B --> C["Design request load"]
C --> D["Run warm-up"]
D --> E["Run performance test"]
E --> F["Collect latency and throughput metrics"]
F --> G["Analyze resource bottlenecks"]
G --> H{"Meet SLO?"}
H -->|Yes| I["Establish performance baseline"]
H -->|No| J["Optimize model and inference service"]
J --> C
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style E fill:#EAF3EC,stroke:#83A995,color:#315D49
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style H fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style I fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style J fill:#F7EAE7,stroke:#C98D7C,color:#754438
10. How to Properly Design LLM Performance Tests
The most common problem in performance testing is inconsistency between the test environment and the real production environment.
For example:
- The test uses only very short prompts.
- The test output length is fixed at 10 tokens.
- Only one request is tested.
- There is no sustained concurrency during the test.
- Queueing time is not measured.
- Token throughput is not measured.
- Model warm-up is not considered.
Such test results cannot reflect real production capacity.
1. Fix the Test Conditions
When comparing performance across different models, keep the following as consistent as possible:
| Test condition | Description |
|---|---|
| Model version | Fix model weights and version |
| GPU type | Use identical hardware |
| Number of GPUs | Keep consistent |
| Inference framework | Fix framework version |
| Concurrency | Use the same concurrency configuration |
| Input length | Use the same Prompt length distribution |
| Output length | Use the same generation length |
| Sampling parameters | Fix temperature, top_p, etc. |
| Maximum tokens | Fix output limit |
| Batch strategy | Record the dynamic batching configuration |
| Quantization method | Use consistent precision and quantization configuration |
If Model A uses 8 GPUs while Model B uses 4 GPUs, you cannot determine which is faster based solely on total throughput.
You should also calculate per-GPU throughput and per-unit cost.
2. Design a realistic request distribution
In real business scenarios, request lengths are often not fixed.
You can construct the following test distribution:
| Request type | Input Tokens | Output Tokens | Proportion |
|---|---|---|---|
| Short Q&A | 128 | 64 | 30% |
| General knowledge Q&A | 512 | 256 | 35% |
| Long-context Q&A | 4096 | 512 | 20% |
| Complex reasoning | 8192 | 1024 | 10% |
| Extra-long input | 16384 | 2048 | 5% |
These data are illustrative configurations and should be adjusted according to real traffic.