Evaluating Small Models in Context › Implementation: a small evaluation harness

Michael BrenndoerferDecember 1, 202611 min read
Language AI HandbookAll chapters
Part 43 of 67Small and On-Device Language Models
Chapter 331Evaluating Small Models in Context › Implementation: a small evaluation harness
Reading section 5 of 8 · Implementation: a small evaluation harness · 11 minSection 5 of 8 · 11 min

Section 5 of 8 · 11 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

We will now build a compact harness that turns this protocol into code. It will:

  1. Load a small labeled task slice with slice tags and length buckets.
  2. Score a (simulated) system's outputs, computing per-slice quality.
  3. Compute latency statistics (p50, p95) from a list of measured request times.
  4. 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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Task slice: 400 examples
          mean   min    max
slice                      
long   136.505  61.0  199.0
short   39.075  20.0   59.0

The 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]
CollapseExpand
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]
CollapseExpand
Histogram of input lengths with short examples on the left and long examples on the right.
Length distribution of the synthetic task slice. Short lengths are sampled from 20 through 59, and long lengths from 61 through 199.

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]
CollapseExpand
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-device
ConsoleOut [9]
CollapseExpand
   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]
CollapseExpand
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]
CollapseExpand
       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]
CollapseExpand
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]
CollapseExpand
     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]
CollapseExpand
# 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]
CollapseExpand
                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]
CollapseExpand
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]
CollapseExpand
Bar chart of the two simulated pre-gate objectives, both labeled inadmissible.
Pre-gate objective values for the seeded simulation. The cloud system fails the privacy gate and the on-device system fails the long-slice quality gate.

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]
CollapseExpand
The 3B on-device system has lower p95 latency and lower mean quality; the 7B cloud system has higher p95 latency and higher mean quality.
Mean per-slice quality versus p95 latency in the seeded simulation. Annotations identify the privacy posture and the client inference energy charged to the objective.

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.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy