Evaluating Small Models in Context
Learn how to evaluate small models in deployment context: measure task fit, latency, energy, privacy, and reliability on the target device under real workloads.
Language AI HandbookAll chapters Evaluating Small Models in Context
A phone-based redaction assistant and a hosted research summarizer have different jobs. The redaction assistant may have to keep every message on the phone. The summarizer might run once an hour and have a more generous latency budget. A leaderboard score alone cannot tell you which system to deploy.
Evaluate small models in the conditions where they will run. Begin with task quality, then measure latency, energy, privacy, and reliability under the target workload. The comparison includes the tokenizer, the weights and their representation, the runtime, the prompt, and any fallback.
This builds directly on the compression and inference work in Part XLI: Model Compression and Part XLII: Inference Optimization. Those chapters explained how to make models small and fast. This chapter asks a different question: once you have made one small and fast, how do you know if it is good enough? We assume you have already read the energy, latency, and privacy tradeoffs raised throughout the book, and we now put those tradeoffs under measurement.
Start by asking how much quality the task needs. A small model may be worth the compromise if it clears that floor and meets a requirement on latency, inference energy, or local processing.
For small models, the evaluation question is not "which model scores highest?" but "which system satisfies the task's quality, latency, energy, privacy, and reliability requirements at acceptable cost, on the target device, under the target workload?" Every number in this chapter should be read as an answer to that question, not as a ranking.
Why small-model evaluation is different
A benchmark run with a fixed prompt measures performance under those particular conditions. A deployment comparison has to account for changes in the rest of the stack as well.
A tokenizer changes the number of positions the model processes. A different prompt or numeric precision can change its predictions. A different device can change latency even when the model and input are identical. Conversely, if the comparison varies only the weights, its conclusions apply to that fixed configuration.
Four sensitivities dominate.
Tokenizer sensitivity. Tokenizers can encode comparable text into different numbers of tokens. Extra tokens use more of a fixed context window and increase the number of positions the model must process. Measure token counts on the task slices using each system's tokenizer, especially when inputs include domain-specific strings or multiple languages. Petrov et al. document tokenization-length disparities across languages. The tokenization chapters explain how the underlying segmentation works.
Prompt format sensitivity. Chat templates, system prompts, few-shot examples, and even formatting can change the measured score. Sclar et al. show this for meaning-preserving variations in few-shot classification prompts. Declare the prompt configuration and tune it on separate development examples before measuring held-out performance.
Quantization sensitivity. Lower-precision weights approximate the original weights. Even a small change in aggregate accuracy can hide a larger drop on a particular slice, so compare the quantized system with its higher-precision baseline under the same protocol. The inference optimization chapters describe the representations.
Device dependence. Latency and energy depend on the chip, memory bandwidth, thermal state, inference runtime, batch size, and concurrency. Report the hardware and workload with the measurements. The MLPerf Client benchmark uses specified workloads such as creative writing and code analysis, with input and expected output lengths for each category.
Record the choices that differ between candidates. To isolate the effect of one choice, such as weight precision, hold other conditions fixed. To choose a deployment, compare the actual candidate systems.
The evaluation protocol: five questions
We will structure the protocol as five questions. Each one produces a required measurement or declaration. A small-model evaluation that cannot answer all five is incomplete.
- Task fit: does the model, on a matched task slice, clear the minimum quality bar for the intended use?
- Cost: what are the measured latency, throughput, and energy under the target workload?
- Privacy: what data leaves the device, under what policy, and is that policy enforceable?
- Reliability: how does quality degrade on the tail: hard slices, distribution shift, adversarial inputs, and repeated runs?
- System comparison: how does the full system (tokenizer + weights + runtime + prompt + fallback) compare to alternatives on a cost-aware objective?
The questions are ordered deliberately. Task fit comes first because a system that cannot do the task at all is not worth the cost of measuring. Cost, privacy, and reliability each isolate a dimension that the average-based quality number hides, and each must be stated explicitly because none of them is captured by a single accuracy figure. Only once all four are characterized can the fifth question, the comparison, be answered, because the comparison depends on all of them. We will take these in order, then put them together in a worked comparison.
Question 1: Task fit on matched slices
The first mistake is evaluating on a benchmark that does not resemble the deployment task. A model that wins on a general knowledge benchmark may fail on your specific extraction, classification, or summarization task because the distribution is different: different vocabulary, different output lengths, different error costs. The fix is to construct a task slice: a labeled sample of inputs drawn from (or closely resembling) the deployment distribution, with a defined target and a defined scoring rule.
The word "matched" in "matched task slice" is doing important work. A matched slice is one whose inputs, targets, and error structure resemble the deployment, not merely one whose topic is similar. A slice of clean, well-formed English support tickets that are all short is not matched to a deployment whose users write in a mix of languages and sometimes paste half a page of context. To match the workload, include those input groups in the evaluation and report their results separately when the decision depends on them.
A task slice has five declared components:
- Input distribution: where the examples come from, and how they were sampled. If they are synthetic, say so and validate against real inputs.
- Target definition: what counts as a correct or acceptable output. For generation tasks this is usually a rubric rather than exact match.
- Scoring rule: exact match, F1, ROUGE, an LLM judge, or a human rubric. State it, including tie-breaking.
- Minimum bar: the quality below which the system is unacceptable, derived from the business or user requirement, not from the model's score.
- Slice structure: the subpopulations (length buckets, languages, domains, difficulty levels) on which you will report separately, because averages hide failures.
Each of these declarations exists to close a loophole. Declaring the input distribution prevents the quiet substitution of an easy benchmark for a hard deployment. Declaring the target and the scoring rule prevents the metric from drifting after the results are seen, which is a subtle form of p-hacking. The minimum bar is perhaps the most important and least natural of the five: it must come from the user requirement, set before you see the model's score, because a bar set afterward will inevitably be drawn just below wherever the model landed. And the slice structure is what converts a single aggregate number into a diagnosis, telling you not just whether the system fails but where.
The reason to insist on slices rather than a single number is that small models fail unevenly. A model may match a larger baseline on short inputs and collapse on long ones, or on rare entities, or on inputs containing numbers. Reporting only the mean hides exactly the failures that will hurt in deployment. Consider a concrete illustration that is exact at its stated precision. The first model scores 0.85 on every slice. The second scores 0.95 on nine slices and 0.10 on a tenth, which contains a low-frequency but important input group. With equal slice weights, the second model's average is (9 × 0.95 + 0.10) / 10 = 0.865, about 1.5 points above the first model's 0.85, while the deployment outcomes could hardly be more different. The slice table is what makes this visible. We already saw, in Comparing Architecture Families Fairly, how averaging over mismatched settings produces misleading rankings; the same principle applies here.
If your evaluation inputs overlap the training data, the measured score may overstate generalization to fresh examples. Li et al. observed larger accuracy increases on contaminated C-Eval and HellaSwag examples than on MMLU. Exact matches and near-duplicates can both matter. Hold out a fresh slice, check for near-duplicates against known training corpora where possible, and state the provenance of your evaluation data. This connects to the dataset-transparency concerns in Dataset Lineage and Provenance.
A high score alone cannot tell you whether the test examples were seen during training. Hold out fresh data and document how you obtained and sampled it. If the training data is unavailable, state that overlap could not be ruled out.
Question 2: Cost, measured versus synthetic
Cost for a small model has three components that are often conflated. Each must be measured on the target hardware, not estimated from parameter counts:
- Latency: time to first token and time to completion.
- Throughput: requests or tokens per second under concurrency.
- Energy can be measured in joules per request within a declared system boundary. A change in battery percentage over a fixed session is a separate device-side drain proxy; it depends on the device and session.
These three are distinct and can move in different directions, which is why they must be reported separately. A configuration might have low time-to-first-token (because the prompt processes quickly) but poor tokens-per-second during generation, or high single-request latency but good throughput under batching. Energy is distinct again: sustained high throughput on a phone may be thermally sustainable only briefly, so a system that looks cheap on a single request can be expensive across a session. Collapsing these into a single "cost" number loses the very information a deployment decision needs.
There is a strong temptation to use a synthetic cost model: bytes read, FLOPs, or a theoretical tokens-per-second formula. Synthetic costs are useful for early design (they let you reason about memory bandwidth and compute before you have hardware), but they systematically mislead on real devices for three reasons.
- Memory-bound decode. At low batch sizes, reading weights and the KV cache can dominate autoregressive decoding. A FLOP-only estimate misses that memory traffic.
- Runtime overhead. Kernel launch overhead, tokenization time, sampling, and host-device transfer can dominate for very small models, where the compute is tiny.
- Thermal and power limits. Phones and laptops throttle. A model that meets latency at the start of a session may exceed it after sustained load.
For dense autoregressive decoding at batch size one, the linear layers repeatedly use their weights to produce each new token. If those weights exceed the available cache, reading them can dominate decoding time. The balance changes with batching, model architecture, sequence length, and hardware, which is why the measured workload matters.
So the rule is: measure latency, throughput, and energy on the target device under the target workload, and report the measurement setup. If you must use synthetic costs for extrapolation, label them as such and validate a subset against measured numbers.
A minimal cost measurement must declare:
- Device: chip, RAM, whether the device is plugged in, ambient temperature if thermal throttling is a risk.
- Runtime and quantization: e.g., llama.cpp with Q4_K_M, or ONNX Runtime INT8, or a GPU server with FP16.
- Workload: input and output length distribution, batch size, concurrency.
- Warm-up and steady state: whether numbers include the first request (which pays model load) and whether throttling was reached.
Measure time to first token and the rate of later tokens from the same workload. Start the TTFT clock at request submission and stop at the first emitted token. For a response with at least two tokens and a positive measured interval, divide the number emitted after the first by the elapsed time from the first to the last emission. If a response emits no tokens, report that outcome separately. If timing resolution cannot distinguish the first and last emissions, the per-response decode rate is undefined. Longer prompts can emphasize prefill costs, while longer continuations provide more observations of decode timing. Report cache and warm-up conditions because the first request may include model loading. Sarathi-Serve describes the distinct prefill and decode phases.
Question 3: Privacy and data leaving the device
Privacy is where small models can offer something a hosted model usually cannot: data minimization by construction. If the model runs on the device and no network call is made, the input text does not leave the device. That is a strong, auditable property, if it is implemented and verified.
A hosted model must receive the input it processes. Retention policies and access controls can restrict what happens after the transfer. A system whose inputs stay on the device can satisfy a requirement that forbids the transfer itself.
The evaluation question is: which data leaves the device, under what policy, and can you prove it? The relevant facts are:
- Where inference runs: on-device, edge server, or cloud.
- What is logged: inference inputs, telemetry, crash reports, model output. Logging can quietly turn an on-device model into a data-export channel.
- What is transmitted: feature extraction, fallback routing, prompt caching to a cloud service, analytics.
- Enforceability: is "no network" a code guarantee (network disabled in the sandbox) or a policy promise? Audit the implementation and any organizational controls that the policy depends on.
A privacy claim covers every component that handles user data. On-device inference can still transmit input through telemetry. A hosted system with no retention still receives input for processing; these are distinct data-flow and retention properties. Privacy must be evaluated as an end-to-end property, with the data-flow diagram as evidence. This complements the detection-and-removal techniques in PII Removal: PII redaction is a preprocessing decision, but whether the residual data left the device is a deployment decision.
Audit the actual data flow and the controls that enforce it. A sandbox that denies direct network access limits one route. Check what the host process, loggers, telemetry, and sync services can still send. Revisit the audit when a new feature adds a path.
Question 4: Reliability: the tail rather than the mean
For reliability, record how often the system fails and which kinds of failure occur. Check performance under distribution shift, on difficult inputs, and across stochastic runs where applicable.
-
Distribution shift. A model tuned on one domain (say, standard English customer-support messages) may degrade sharply on a neighboring domain (regional dialect, code-switching, emoji-heavy chat). Measure the matched slice and a separate held-out slice for the shift. The multilingual evaluation concerns in Cultural and Multilingual Evaluation and Code-Switching and Mixed-Language Text apply here: a mismatch between the test slice and the deployment population can bias the reported reliability in either direction. The subtlety is that distribution shift is not a single axis. A model may handle changes in formality while struggling with longer inputs, or do well on one dialect and poorly on another. The shifted slice should therefore sample the kinds of variation you expect to encounter, and the report should name which shift it measured.
-
Input difficulty. Slice by length, by ambiguity, by presence of numbers or rare entities. Report each slice's quality, the lowest slice score, and the micro-average. A system that is excellent on 90% of inputs and catastrophically wrong on the remaining 10% may be worse in deployment than a slightly weaker system with a flat profile, depending on error cost. Whether the flat profile or the peaky one wins is a question the deployment must answer: if errors on the hard 10% are cheap and recoverable, a peaky model that shines on the common case is fine; if those errors are expensive and silent, the flat profile is worth its lower ceiling.
-
Decoding stochasticity. Small models are sensitive to decoding settings: temperature, top-p, and seed. Run the evaluation under a fixed, declared decoding configuration for the headline number, and separately report a stability check: re-run under a small set of seeds or a temperature sweep and report the variance. An accuracy number without a decoding spec is not reproducible. We covered the mechanics in Decoding Temperature and Nucleus Sampling; here they become evaluation controls. The reason both a fixed configuration and a stability check are needed is that they answer different questions. The fixed configuration answers "what does this system do under a declared setting?" The stability check answers "how much would that answer move if I had chosen differently?" A system with a stable answer is one you can reason about; a system whose answer swings widely across seeds is one whose single reported number is partly luck.
Define what counts as a failure before scoring. For example, if a system routes a request to a fallback when its first answer is flagged, record whether the first answer failed, whether a check caught the failure, whether the fallback ran, and whether the final answer passed. Report the initial failure rate over all evaluated requests. Compute detection among failed requests by dividing detected initial failures by all initial failures. Report it as undefined if there were no initial failures, and track fallback recovery separately. Score final answers over all requests so uncaught failures and unsuccessful fallback attempts affect the result.
Question 5: Comparing systems, not parameter counts
The final question is how to compare two candidate systems. A system here means the tuple:
Parameter count helps estimate the storage needed for weights once you know their precision. Quality, latency, energy, and reliability also depend on the model and deployment configuration. Measure those quantities with the tokenizer, runtime, and workload you plan to use.
The tuple framing is the conceptual heart of the chapter. Each element is a lever that changes the behavior of the deployed system, and evaluating any single lever without the others is like measuring one gear and inferring the engine's power. Weights and quantization determine the function and its noise. The tokenizer determines how many units of work each input costs. The runtime determines how efficiently the hardware is used. The prompt policy determines whether the model is asked in a form it can handle. And the fallback determines what happens when it fails, which is a first-class part of the delivered quality. A comparison that varies only the weights holds the rest fixed and attributes all differences to the model, so it cannot isolate the effects of the choices it held fixed.
A principled comparison uses a cost-aware objective. Define, for each candidate system on slice :
- : measured quality on slice (your chosen metric).
- : measured latency (e.g., p50 and p95 completion time).
- : measured energy per request.
- is a declared reliability statistic with larger values preferred. The worked example uses accuracy on the long slice. Another option is one minus the fraction of all evaluated requests with an uncaught failure; pair that with a quality or final failure-rate requirement if detected failures can still reach users. Keep detection among initial failures as a separate diagnostic.
- : privacy posture (categorical: on-device-only, edge, cloud-with-contract, cloud-default).
A simple scalarization that makes tradeoffs explicit is:
Here, is the nonnegative weight for slice , with the weights summing to one in this example. The nonnegative coefficients and convert the selected latency statistic and energy per request to the quality score's scale. Eligibility is subject to hard constraints and . The weights , , , and the constraints encode the deployment's actual requirements. The point is not that this specific formula is correct for your situation (it rarely is exactly), but that writing it down forces you to declare what you are optimizing and what you are not willing to trade.
The structure of the formula is worth reading closely, because it encodes a decision principle. Quality is a reward that accumulates across slices, weighted by how much each slice matters. Latency and energy are penalties subtracted from the reward, with coefficients expressing how much a unit of latency or energy costs you in quality terms. The constraints sit outside the objective entirely and are checked first: a privacy posture outside the allowed set or a reliability score below the minimum disqualifies the system regardless of its objective value. This structure reflects how real deployments work, where some requirements are negotiated as soft tradeoffs and others are inviolable gates. Writing the objective down turns an argument about which model is better into an argument about which weights and constraints are right, which is a far more productive and auditable conversation.
Notice what this does to parameter count: it disappears. Parameter count is a proxy that correlates with quality, latency, and memory, but the objective uses the measured quantities directly. Suppose both systems pass the gates and use equal energy. If the 3B system has higher weighted quality and lower p95 latency, it has higher utility whenever the latency term uses p95 with a nonnegative coefficient. The proxy exists because parameter count is easy to read and available before you have hardware. Those measurements describe the system users will encounter. The whole point of an in-context evaluation is to replace the proxy with the measurement precisely when the two disagree, because that is when the proxy would have misled you.
Worked example: comparing two small systems on a classification task
Let us make this concrete with a task that is common in on-device deployments: classifying short support messages into a small set of intent categories. We will compare two hypothetical systems and compute the cost-aware objective by hand, so the mechanics are transparent. (The numbers below are illustrative and constructed to expose tradeoffs; in a real evaluation they would be measured.)
The task is deliberately mundane. Intent classification over a fixed label set is exactly the kind of high-volume, latency-sensitive workload where on-device deployment is attractive, and it is simple enough that the arithmetic of the objective stays visible. The point of the worked example is not the specific numbers but the shape of the reasoning: two systems that are each "good" on some dimensions, a set of constraints that rules one out, and a minimum bar that judges the other on its weakest slice.
The task. Classify each customer message into one of four intents: refund, shipping, technical, or billing. Evaluate two slices, short (up to 60 characters) and long (more than 60). Length is a useful stress variable if the deployment serves both short and long messages.
The two systems:
- System A: a 7B model, FP16, cloud-hosted, general tokenizer.
- System B: a 3B model, 4-bit quantized, on-device, domain-adapted tokenizer.
Illustrative quality and cost assumptions:
| Metric | System A (7B cloud) | System B (3B on-device) |
|---|---|---|
Quality short | 0.91 | 0.89 |
Quality long | 0.88 | 0.79 |
| p50 latency | 700 ms | 120 ms |
| p95 latency | 1400 ms | 260 ms |
| Client inference energy / request charged to the objective | 0 J (server energy excluded) | 0.8 J |
| Privacy posture | cloud default | on-device only |
| Worst-slice quality | 0.88 | 0.79 |
System B has lower latency and lower quality in both slices. The gap is 2 percentage points on short inputs (0.91 minus 0.89) and 9 on long inputs (0.88 minus 0.79). Equal weights average these two gaps to 5.5 points. The corresponding mean qualities are 0.895 for A and 0.840 for B. The client energy term charges B for local inference and excludes A's server energy. This boundary cannot establish which system uses less total energy.
- With only a no-export requirement, A fails and B passes.
- With only a long-slice quality floor of 0.85, A passes at 0.88 and B fails at 0.79. When both gates apply, neither passes. Improving B on long inputs is one way to try to make it eligible without relaxing the privacy requirement.
- When both systems pass the declared requirements, compare objective values. At 0.10 per second of p95 latency and 0.05 per joule of client inference energy, the illustrative utility is 0.755 for A and 0.774 for B before gating.
Report each gate separately. If one system qualifies, there is no ranking to break. If no system qualifies, the failed checks tell you what needs to change before considering the objective.
The ranking depends on the requirements and weights. In the hand example, A gives higher quality and B has lower latency. With both deployment gates in place, neither system qualifies.
Implementation: a small evaluation harness
We will now build a compact harness that turns this protocol into code. It will:
- Load a small labeled task slice with slice tags and length buckets.
- Score a (simulated) system's outputs, computing per-slice quality.
- Compute latency statistics (p50, p95) from a list of measured request times.
- Combine per-slice quality, latency, energy, and privacy into a cost-aware objective.
The example runs without model weights or a GPU. To reuse the harness, supply one row per labeled request with its slice, the expected intent, and the predicted intent or a missing value. Supply measured request times for the latency comparison. Parse model responses into this schema before scoring.
The design principle here is separation of concerns. The data-generation step, which we simulate, is quarantined from the scoring, slicing, and objective steps, which are real code you would keep. This matters because the most common failure when building an evaluation harness is to let the simulation leak into the analysis: a simulated "model" that produces its outputs using knowledge of the scoring function, or a simulated latency that is generated from the same distribution as the threshold that judges it. The scoring and decision steps consume the same fields whether the rows come from the simulator or from a labeled deployment workload.
The reader-facing cells use NumPy and pandas. Run them in order. The notebook's hidden setup supplies the shared plot style, and the first visible cell fixes the simulation seed.
PythonIn [2]Expand
import numpy as np
import pandas as pd
np.random.seed(0)Next, we construct a task slice. In practice this comes from labeled deployment data; here we synthesize one with a clear structure so the slice results are interpretable. Each row has an ID, a gold intent, a synthetic length in characters, and a slice tag (short or long). We deliberately make the synthetic model weaker on the long slice, matching the pattern we discussed.
PythonIn [4]Expand
intents = ["refund", "shipping", "technical", "billing"]
# Build a task slice: 400 examples, half short, half long.
n_per_slice = 200
records = []
for i in range(n_per_slice):
gold = intents[np.random.randint(len(intents))]
length = np.random.randint(20, 60) # short slice
records.append({"id": i, "slice": "short", "length": length, "gold": gold})
for i in range(n_per_slice):
gold = intents[np.random.randint(len(intents))]
length = np.random.randint(61, 200) # long slice
records.append(
{"id": n_per_slice + i, "slice": "long", "length": length, "gold": gold}
)
df = pd.DataFrame(records)ConsoleOut [5]Expand
Task slice: 400 examples
mean min max
slice
long 136.505 61.0 199.0
short 39.075 20.0 59.0The slice contains 400 examples split evenly across the two length buckets, with mean lengths that clearly separate them. This is the unit on which we will report quality separately; averaging across buckets would hide the degradation we care about.
The histogram summarizes how the artificial lengths were sampled:
PythonIn [6]Expand
short_lengths = df.loc[df["slice"] == "short", "length"].to_numpy()
long_lengths = df.loc[df["slice"] == "long", "length"].to_numpy()
length_bin_edges = np.arange(0, 221, 10)
short_counts, _ = np.histogram(short_lengths, bins=length_bin_edges)
long_counts, _ = np.histogram(long_lengths, bins=length_bin_edges)VisualizationOut [7]Expand

The deployment rule would put a 60-character input in the short slice. The simulator never generates that length because the upper bound passed to its integer sampler is exclusive.
Now we simulate two systems' predictions. We make System B (the 3B on-device model) slightly worse on short and notably worse on long, and System A (the 7B cloud model) uniformly strong. The simulation uses a per-slice accuracy parameter to generate correct-or-incorrect predictions; the harness scores them exactly as it would score real outputs. When an incorrect prediction is generated, the simulator picks a wrong label by advancing one position in the intent list, which is a stand-in for the kind of systematic confusion a real model might make; the exact wrong label does not matter for exact-match scoring, but it keeps the simulation from generating impossible failures.
PythonIn [8]Expand
def simulate_system(df, short_acc, long_acc):
"""Generate predicted labels with given per-slice accuracy."""
preds = []
for _, row in df.iterrows():
acc = short_acc if row["slice"] == "short" else long_acc
if np.random.rand() < acc:
preds.append(row["gold"])
else:
preds.append(
intents[(intents.index(row["gold"]) + 1) % len(intents)]
)
return np.array(preds)
df["pred_A"] = simulate_system(df, short_acc=0.91, long_acc=0.88) # 7B cloud
df["pred_B"] = simulate_system(
df, short_acc=0.89, long_acc=0.79
) # 3B on-deviceConsoleOut [9]Expand
slice gold pred_A pred_B 0 short refund refund refund 1 short billing billing billing 2 short billing billing billing 3 short billing billing billing 4 short technical technical technical
With predictions in hand, we score per slice. The key discipline is to report per slice, not only the overall accuracy. We compute exact-match accuracy for each system on each slice. Use one nonmissing gold intent label and one slice per evaluated request. Predictions must be scalar intent labels or missing values. Initialize every match as false, then compare only pairs with two present values. This keeps a request with no prediction in the denominator and allows comparisons between columns with different categorical encodings. The output reports worst-slice quality separately for each system. It is the minimum of that system's per-slice accuracies. Use this value when every slice must clear the same threshold.
PythonIn [10]Expand
def exact_matches(df, pred_col):
gold = df["gold"]
predictions = df[pred_col]
present = (gold.notna() & predictions.notna()).to_numpy()
correct = pd.Series(False, index=df.index)
expected_labels = gold.iloc[present].to_numpy(dtype=object)
predicted_labels = predictions.iloc[present].to_numpy(dtype=object)
correct.iloc[present] = expected_labels == predicted_labels
return correct
def per_slice_accuracy(df, pred_col):
return exact_matches(df, pred_col).groupby(df["slice"]).mean()
acc_A = per_slice_accuracy(df, "pred_A")
acc_B = per_slice_accuracy(df, "pred_B")
quality_table = pd.DataFrame(
{"SystemA_7B_cloud": acc_A, "SystemB_3B_ondevice": acc_B}
)
worst_slice_quality = quality_table.min(axis=0)ConsoleOut [11]Expand
SystemA_7B_cloud SystemB_3B_ondevice slice long 0.89 0.800 short 0.89 0.865 A overall: 0.890 B overall: 0.833 SystemA_7B_cloud 0.89 SystemB_3B_ondevice 0.80 Name: Worst-slice quality, dtype: float64
The per-slice table is the first genuinely useful artifact. Even if the overall averages were close, the long slice shows System B's degradation clearly. The minimum for each system is reported separately below the table. Compare the worst-slice value to the overall accuracy for System B: the overall average pulls the long-slice performance up toward the stronger short-slice number, softening exactly the failure the deployment cares about. The per-slice view restores the truth.
Next, latency. In a real evaluation you would record each request's wall-clock time. Here we simulate latency distributions with a heavy tail: p50 low, p95 several times higher. We report p50, p95, and p99 across the whole simulated workload. For a real workload, use the same statistic separately on slices when latency budgets differ by input length. Tail latency matters because users experience the slow requests, not the average. The simulation uses a lognormal distribution, which is a reasonable stand-in for request latencies because it is right-skewed: most requests complete near the median, and a minority take much longer, which matches the real behavior of systems where occasional cache misses, garbage collection, or resource contention add delay.
PythonIn [12]Expand
def simulate_latency(n, p50_ms, tail_ratio):
"""Draw lognormal latencies with the requested population median and approximate p95 ratio."""
sigma = np.log(tail_ratio) / 1.645
base = np.random.lognormal(mean=np.log(p50_ms), sigma=sigma, size=n)
return base
lat_A = simulate_latency(len(df), p50_ms=700, tail_ratio=2.0)
lat_B = simulate_latency(len(df), p50_ms=120, tail_ratio=2.2)
def latency_stats(lat):
return {
"p50": np.percentile(lat, 50),
"p95": np.percentile(lat, 95),
"p99": np.percentile(lat, 99),
}
latency_table = pd.DataFrame(
{
"SystemA_7B_cloud": latency_stats(lat_A),
"SystemB_3B_ondevice": latency_stats(lat_B),
}
)ConsoleOut [13]Expand
SystemA_7B_cloud SystemB_3B_ondevice p50 706.4 122.6 p95 1539.0 283.8 p99 1847.2 352.2
The latency table reports percentiles from the seeded sample; these differ from the illustrative inputs used in the hand calculation. Compare p95 and p99 alongside p50 to see how the slowest requests differ. The simulator draws latency independently of input length, so the result does not estimate how latency varies with length.
We can now assemble the cost-aware objective using the simulated observations. The quality term is a weighted mean across slices. The p95 latency penalty uses seconds, so the code divides the reported milliseconds by 1,000. The energy term charges client inference energy only. The example requires both an on-device privacy posture and a long-slice accuracy of at least 0.85.
PythonIn [14]Expand
# Declared deployment preferences (make these explicit and justify them).
slice_weights = {"short": 0.5, "long": 0.5} # importance of each slice
lambda_L = 0.10 # latency penalty per (second)
lambda_E = 0.05 # energy penalty per (joule)
# Hard constraints
allowed_privacy = {"on-device-only"}
min_long_quality = 0.85
energy = {
"SystemA_7B_cloud": 0.0,
"SystemB_3B_ondevice": 0.8,
} # J/request (A: server-side, excluded)
privacy = {
"SystemA_7B_cloud": "cloud-default",
"SystemB_3B_ondevice": "on-device-only",
}
def objective(quality_map, latency_summary, energy_J):
# Quality term: weighted per-slice quality.
q = sum(slice_weights[s] * quality_map[s] for s in slice_weights)
# Latency penalty: use p95 (the user-visible tail), in seconds.
lat_pen = lambda_L * (latency_summary["p95"] / 1000.0)
en_pen = lambda_E * energy_J
return q - lat_pen - en_pen
results = []
for name, qcol, lat in [
("SystemA_7B_cloud", "SystemA_7B_cloud", lat_A),
("SystemB_3B_ondevice", "SystemB_3B_ondevice", lat_B),
]:
qmap = quality_table[qcol].to_dict()
stats = latency_stats(lat)
allowed = privacy[name] in allowed_privacy
passes_long = qmap["long"] >= min_long_quality
u = (
objective(qmap, stats, energy[name])
if allowed and passes_long
else float("nan")
)
results.append(
{
"system": name,
"privacy_ok": allowed,
"long_quality_ok": passes_long,
"objective": u,
}
)
results_df = pd.DataFrame(results)ConsoleOut [15]Expand
system privacy_ok long_quality_ok objective 0 SystemA_7B_cloud False True NaN 1 SystemB_3B_ondevice True False NaN
System A fails the privacy gate, and System B fails the long-slice quality gate. Neither is admissible, so both objective entries are NaN. The two diagnostic columns show which condition each system fails.
The final assembly step makes the constraint ordering visually concrete. We compute each system's pre-constraint objective and then mark admission under both declared gates:
PythonIn [16]Expand
preconstraint = []
for name, lat in [("SystemA_7B_cloud", lat_A), ("SystemB_3B_ondevice", lat_B)]:
qmap = quality_table[name].to_dict()
stats = latency_stats(lat)
preconstraint.append(
{
"system": name,
"unconstrained_objective": objective(qmap, stats, energy[name]),
"admissible": privacy[name] in allowed_privacy
and qmap["long"] >= min_long_quality,
}
)
objective_view = pd.DataFrame(preconstraint)
admission_values = objective_view["admissible"].to_numpy()
objective_values = objective_view["unconstrained_objective"].to_numpy()
system_names = ["A: 7B cloud", "B: 3B on-device"]VisualizationOut [17]Expand

The shorter bar can still belong to an admissible system under different constraints. In this run, neither bar represents a deployable candidate even though both scores can be calculated for illustration.
The objective column is only computed for admissible systems. This is intentional: hard constraints dominate soft tradeoffs. A system that violates a hard requirement is ineligible. The figure shows pre-gate scores for comparison.
Finally, we visualize the tradeoff. The figure puts mean per-slice quality against p95 latency, with each system labeled by its privacy posture, so the multidimensional comparison is visible at a glance rather than collapsed into a scalar.
VisualizationOut [18]Expand

The on-device system has lower p95 latency and lower average quality. The energy labels show the client inference boundary used in the objective; the zero charged to the cloud case does not measure server energy.
Limitations & impact
The protocol and harness above make small-model evaluation honest, but honesty has costs and limits that must be stated plainly.
Synthetic slices and simulations are not evaluations. The worked example's numbers are constructed to expose tradeoffs; they are not measurements. A real evaluation must use labeled deployment data (or a validated proxy), real model outputs, and real timings on the target device. The scoring and decision code operates on the declared classification fields and request timings. A real evaluation must build and validate those inputs before using it. The temptation to skip that replacement and report the illustrative numbers as if they were measured is the failure mode to guard against. It is worth naming the specific warning sign: if a number appears in a decision document without a provenance note saying whether it was measured or simulated, treat it as unverified until you can trace it back to the harness step that produced it.
Task slices are expensive and often biased. Building a representative slice requires labeled data that is scarce exactly where small models are often deployed: low-resource languages, specialized domains, edge cases. A convenient public benchmark can misestimate deployment quality when its distribution differs. A slice built from the same source as training data may also contain overlapping examples. The honest response is to state the provenance and the known mismatch rather than pretend the slice is representative. In practice this means writing down, alongside the reported number, the sources the slice was drawn from, the subpopulations it under-represents, and the reason you believe the under-representation does not change the conclusion (or, if it does, how). A slice is never perfect, but a slice with a stated bias is far more useful than one whose bias is hidden, because the stated bias can be argued about.
Measured costs are device- and workload-specific, and do not transfer. A latency number from a phone with a specific NPU, under a specific quantization, with a specific runtime, at a specific thermal state, tells you about that configuration. Measure materially different hardware, quantization, and sustained workloads separately. Energy measurements are worse: phone power models vary by SoC, and even "joules per request" depends on measurement instrumentation and background load. Numbers must travel with their measurement setup, and cross-device comparisons must be re-measured, not extrapolated. This is why the protocol demands a declared setup for every cost number. A useful habit is to treat a cost number as a triple of (value, setup, date): the setup says what it measures and the date says when the hardware and software were in the state described, because runtimes and device firmware both change under you.
Privacy as a code guarantee is a significant engineering claim, and it is easy to break. "On-device only" is only as strong as the weakest telemetry, crash-report, or caching path in the system. An input-logging path breaks a no-export requirement if the logs are transmitted. Evaluating privacy therefore means auditing the whole data flow, which is more work than checking a flag and requires re-auditing every time the system changes. The property is worth having, since it is the main qualitative advantage small on-device models offer, but it is a property of the system, not the model, and it must be maintained as such. The engineering implication is that the guarantee should be encoded structurally where possible (network permissions disabled, telemetry schemas that cannot contain user text) rather than relying on every engineer remembering the policy, and verify that the restrictions still hold after changes to the system.
Stochastic decoding makes single-run numbers unstable, and stability checks add cost. Re-running under multiple seeds multiplies evaluation compute, which is exactly the resource small-model deployments are trying to save. The compromise is to report a fixed-decoding headline number plus the observed range from a declared set of additional runs, and to flag slices where the observed range is wide. An evaluation that reports a single number without a decoding spec is not reproducible and should not be trusted for a deployment decision. A wide observed range indicates that the tested seeds yield different scores, even when the headline result clears the floor.
The objective records one deployment's preferences. A team that can tolerate more latency and requires stronger long-slice performance may reach a different decision from the same measured results. Save the weights and gates with the results so the team can recompute utility and eligibility when the requirements change.
The worked example gives a team the evidence it needs to choose a next experiment. A fails the no-export requirement. B meets it but misses the long-input quality floor. To bring B back for review, retest the long slice after improving local inference. The same principle of matching the conditions applies in Comparing Architecture Families Fairly and the scaling laws chapters.
Summary
Evaluating small models in context means measuring the system against the deployment's requirements, not ranking models by parameter count or a leaderboard score. The chapter's protocol has five parts, each producing a required, declared measurement:
- Task fit on matched slices. Build a slice from the deployment distribution, declare the target, scoring rule, minimum bar, and slice structure, and report quality per slice. Watch for contamination.
- Cost: measured, not synthetic. Measure latency (p50/p95), throughput, and energy on the target device under the target workload, and report the full setup. Synthetic costs are for design, not decisions.
- Privacy as system property. Evaluate which data leaves the device, under what policy, and whether it is enforceable. An on-device model with leaky telemetry is not private.
- Reliability on the tail. Measure distribution shift, input difficulty, and decoding stochasticity, and report a failure profile rather than only an average. Count silent errors separately and use deployment-specific costs to assess their impact.
- System comparison on a cost-aware objective. Compare (weights, quantization, tokenizer, runtime, prompt, fallback) tuples under declared weights and hard constraints. The ranking is undefined until the constraints and preferences are stated.
In the worked example, the cloud system fails the privacy gate and the on-device system misses the long-slice floor, leaving neither eligible when both gates apply. The harness reproduces per-slice scoring, latency percentiles, and the gated objective on synthetic data.
The deeper point is that parameter count is a proxy that the evaluation should replace with measured quantities wherever it appears. A small model evaluated in context is judged on whether this system, on this device, under this workload, satisfies these requirements. That is a harder question than "which model scores highest," and it is the only one that matters for deployment. The next chapters extend this contextual view: Hybrid Edge-Cloud Inference elaborates the fallback policies this chapter treated as a system component, and Part XLIV: Retrieval-Augmented Generation covers the knowledge-augmentation side of making small models useful in production.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about evaluating small models in context.
Evaluating Small Models in Context
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!