Designing a Repeat-and-Aggregate Pipeline for Noisy LLM Scores
Machine LearningModel answerLast updated
Design a latency-bounded pipeline that averages repeated LLM sentiment scores, measures run-to-run stability, and computes how many samples a 95% error target needs.
Context
Your team serves an LLM that reads unstructured financial text and returns a numeric sentiment score (for example in [-1, 1]). The model is sampled stochastically, so calling it several times on the same text gives different numbers. A downstream consumer needs a steady, trustworthy value for each input.
Questions
- Architecture. Propose a way to make the served score stable. How would you choose the number of repeated calls,
n, so that variance falls without breaking the latency limit? - Measuring stability. You have 100 past inferences collected over a set of inputs. Which statistical measures would you compute to quantify how stable the outputs are?
- Sample size. A stakeholder wants the averaged score to land within a margin
eof the true mean with 95% confidence. For a brand-new input, how do you derive thenrequired?
Requirements
- Give pseudo-code or workflow logic for orchestrating the repeated calls.
- Discuss the trade-off between sampling temperature and the number of repeats.
- Explain how you would check, using a correlation measure such as Pearson against a benchmark or expert labels, that the stabilization step has not introduced bias.
- Numbers to work with: each model call takes about 200 ms, and the whole inference process must finish within 1 second.
Hints
Hint 1
Treat each model call as a draw from a distribution. The spread of the mean shrinks like sigma divided by the square root of n, so the sample size follows from the margin you need.
Hint 2
Sequential calls only fit about four in a second. Think about firing calls concurrently in a small first wave, estimating the spread from it, and then deciding whether a second wave is affordable.
Hint 3
A stable answer is not necessarily a correct one. Plan a separate comparison against expert labels, and consider lowering temperature or reading token probabilities to cut variance per call.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
Treat each LLM score as a random variable with an unknown mean and variance. Then (a) turn the stakeholder's "within e at 95%" into a sample size, (b) fit that sample size into the 1 s budget, and (c) verify that stable also means valid.
1. Requirements to pin down
- Output: a scalar score, parsed and validated. Malformed or out-of-range outputs are retried or dropped.
- Latency: 200 ms per call, 1 s total, including parsing, aggregation and network. Keep about 150 ms headroom.
- Precision: mean within ±e at 95% confidence (e.g. e = 0.05 on a [-1, 1] scale).
- Cost: n repeats cost n times the tokens and rate-limit capacity.
- Auditability: the same input, prompt and model version should return the same served value, so cache results.
2. Architecture
Request -> cache lookup (hash of input, prompt ver, model ver, params)
-> orchestrator: parallel fan-out of n0 calls, deadline-aware
-> parser/validator
-> aggregator: mean + CI half-width
-> half-width > e and time left? -> second wave
-> response {score, ci, n_used, stable_flag} -> cache + metrics
Latency math. Sequential calls fit only about 4 in the budget, which is too few. Parallel fan-out makes latency roughly the slowest of n calls, so a wave of 5 to 8 calls finishes around 250 to 300 ms at p99. That allows two waves: a pilot wave to estimate the spread, then a second sized from that estimate. To trim tails, hedge by sending n0 + 2 calls and using the first n0 that return.
async def stable_score(x, e, deadline=0.85, n0=6, n_max=24):
if (hit := cache.get(key(x))): return hit
t0 = now()
samples = valid(await first_k(n0, [llm(x) for _ in range(n0 + 2)], timeout=0.35))
while True:
k = len(samples); m = mean(samples); s = stdev(samples)
half = t_crit(0.975, k - 1) * s / sqrt(k)
if half <= e or k >= n_max: break
if now() - t0 + 0.3 > deadline: break # no time for another wave
need = ceil((t_crit(0.975, k - 1) * s / e) ** 2)
extra = min(need - k, n_max - k)
samples += valid(await first_k(extra, [llm(x) for _ in range(extra + 1)], timeout=0.3))
out = Result(m, half, k, stable=(half <= e))
cache.put(key(x), out); log(x, samples, out)
return out
If the deadline arrives before the target precision is reached, still return the estimate, but with stable=False and its CI so the consumer can down-weight it. Never claim precision you do not have.
3. Quantifying stability on the 100 historical runs
Assume the 100 runs are K inputs times m repeats (e.g. 20 × 5).
- Per-input dispersion: standard deviation s_i (or MAD for robustness). The coefficient of variation s_i/|mean_i| is useful only when scores are far from zero; near neutral sentiment report SD instead.
- Pooled within-input variance: the average of s_i². This is the noise that averaging removes.
- Intraclass correlation (ICC): σ²_between / (σ²_between + σ²_within). It is the share of variance that is real signal. ICC above 0.9 means one call is already fairly reliable. For an n-sample mean, Spearman–Brown gives ICC_n = n·ICC / (1 + (n−1)·ICC).
- Distribution of s_i: noise is usually heteroscedastic, with ambiguous texts much noisier. Inspect quantiles, not just the mean, because you will size n from them.
4. Deriving n for a new input
For i.i.d. samples, the mean is approximately N(μ, σ²/n), so the standard error is σ/√n. Requiring the 95% half-width to be at most e:
n ≥ (1.96 · σ / e)²
Example: σ = 0.15 and e = 0.05 give n ≥ (1.96 × 3)² ≈ 34.6, so n = 35. That does not fit a 1 s budget, which is why variance reduction matters.
Since σ is unknown for a new input, combine:
- Historical prior: use a high quantile of s_i (say the 90th), not the mean, which under-covers noisy inputs.
- Pilot plus t-correction: estimate s from n0 samples and require n ≥ (t_{0.975, n−1} · s / e)². Inflate s slightly since it is noisy at small n0.
- Predicted σ: a small regressor from features (length, hedging words, entity count) to s_i can pre-size the first wave.
Caveat: the i.i.d. assumption holds only with T > 0 and independent seeds. Batching and caching can correlate samples, so confirm empirically that the SEM shrinks like 1/√n.
5. Temperature versus repeats
| Low T (0 to 0.3) | High T (0.7 to 1.0) | |
|---|---|---|
| Per-call σ | Small, few repeats needed | Large, n grows with σ² |
| Mean estimates | Near the model's mode | The expected score |
| Risk | Narrow CI around a possibly biased value | Cost and latency blow-up |
Because n scales with σ², halving σ via lower temperature cuts n by 4×. T = 0 is not perfectly deterministic (GPU batching, floating-point effects) but is close.
The strongest single-call option is often to constrain the output to a discrete score token and read the logprobs, computing E[score] = Σ p(k)·k directly. That gives the expected value with no sampling variance in one 200 ms call. Repeats then serve mainly to cover prompt or parse variability.
6. Checking for bias
Stability is not validity. On a benchmark with expert labels:
- Compute Pearson r between stabilized scores and labels, plus Spearman ρ if ranking matters. Report bootstrap CIs.
- Compare against r for single-call outputs. Averaging should raise or hold the correlation; a drop signals that aggregation or low temperature is washing out signal.
- Check calibration: regress labels on stabilized scores and look at slope and intercept, since low T or a robust mean can compress the range.
- Slice by input type (length, sector, ambiguity), as bias often hides in subgroups.
- Monitor in production: drift in ICC, in the fraction of
stable=Falseresponses, and in correlation on a refreshed labeled sample.
Common mistakes
- Using a z value of 1.96 with a tiny pilot instead of a t value.
- Sizing n from the average σ, so noisy inputs miss the target.
- Running calls sequentially and blowing the budget.
- Reporting a tight CI that reflects model consistency, not correctness.
- Using CV near zero-mean scores.