Sub topic 8
Order and label balance
What this chapter assumes
You should already know how to write consistent input and output pairs and how to pick examples that cover the input range. You should be able to read short Python. You should also know how to score a prompt on held-out labeled data.
This chapter covers two decisions that remain once you have chosen your examples. The first is how many examples carry each label. The second is the order in which the examples appear.
Why these two choices matter
A model reads your examples as evidence about the task. It also picks up patterns you did not intend. If three of four examples end in "positive," the model may learn that "positive" is a likely answer, whatever the input says. If the last example is "negative," that label may get extra weight on the next input. This is a statistical effect, not a rule, so it varies by model and task. It is still large enough to measure, and it costs nothing to control.
Research on in-context learning has reported these effects. The same set of examples, shuffled into different orders, has produced accuracy ranging from near chance to near the best published results on some tasks. Other work found three recurring biases: toward the majority label, toward the label of the most recent example, and toward common tokens. Treat these findings as a reason to test your own prompt, not as fixed numbers.
Label balance
How imbalance leaks into predictions
Take a three-way sentiment task with these examples: positive, positive, positive, negative. The model sees "positive" three times as often as any other label. For an ambiguous review, it leans toward the label it has seen most.
The effect is strongest where the input is ambiguous, which is exactly where you need the model to reason. Clear inputs usually survive the bias. Borderline ones tip toward the majority label.
Building a balanced set
Count the labels first, then sample equal numbers per label. The code below does both, and it fails loudly if the pool is too small, so a skewed prompt does not slip through.
import random
from collections import Counter, defaultdict
def label_counts(examples):
return Counter(label for _, label in examples)
def balanced_sample(pool, per_label, seed=0):
rng = random.Random(seed)
by_label = defaultdict(list)
for example in pool:
by_label[example[1]].append(example)
chosen = []
for label, items in by_label.items():
if len(items) < per_label:
raise ValueError(
f"Label {label!r} has {len(items)} examples, need {per_label}"
)
chosen.extend(rng.sample(items, per_label))
return chosen
pool = [
("The battery lasts all day.", "positive"),
("Charging is fast and the screen is sharp.", "positive"),
("It stopped working after a week.", "negative"),
("The speakers crackle at low volume.", "negative"),
("The package arrived on Tuesday.", "neutral"),
("The box contains a charger and a manual.", "neutral"),
]
chosen = balanced_sample(pool, per_label=1)
print(label_counts(chosen))With three labels, the number of examples should be a multiple of three. Four examples cannot be balanced across three labels. In that case, add or drop one example rather than accept a skew.
When to unbalance on purpose
Equal counts are a sensible default, not a law. Suppose 90 percent of your real inputs are "neutral." A balanced prompt may push the model to over-predict "positive" and "negative" on inputs that are plainly neutral. Here you have two options:
- Keep the prompt balanced and measure how often the model over-predicts the rare labels on a held-out set that matches production proportions.
- Tilt the examples toward the real distribution, and verify that rare labels are still recognized.
Choose by testing. Do not assume that either option is safe.
Balance applies to more than classification labels. If your task extracts fields, balance examples where a field is present against examples where it is missing. If every example has a value, the model will invent one when none exists.
Order
Recency and primacy
Models often weigh the last example more than the others. Some also give extra weight to the first. The middle examples tend to have the least pull. This means the example nearest your query acts as a strong hint, whether or not you meant it to.
Three habits reduce the risk:
- Do not end the examples with a long run of one label.
- Do not group examples by label ("all positives, then all negatives"). The model may read the grouping as a pattern.
- Do not put your easiest, most typical example last if the query is usually harder.
Interleaving labels
A simple fix is to alternate labels. The function below takes examples, groups them by label, and emits them round-robin, so no label forms a run.
from collections import defaultdict
def interleave(examples):
by_label = defaultdict(list)
for example in examples:
by_label[example[1]].append(example)
queues = list(by_label.values())
ordered = []
while any(queues):
for queue in queues:
if queue:
ordered.append(queue.pop(0))
return ordered
for text, label in interleave(pool):
print(label, "|", text)The label cycle is always the same, such as positive, negative, neutral, positive, and so on. A fixed cycle is itself a pattern, so shuffle the example order within each label, or shuffle the final list, and check that the result has no long runs.
Measuring order sensitivity
You cannot tell whether order matters for your prompt by reading it. You have to try several orders on the same held-out data and look at the spread of scores. The function below takes any predict_with(order, text) that builds a prompt from an ordered example list and returns the model's answer.
import random
def order_sensitivity(predict_with, examples, held_out, n_orders=5, seed=0):
rng = random.Random(seed)
scores = []
for _ in range(n_orders):
order = examples[:]
rng.shuffle(order)
correct = sum(
predict_with(order, text).strip().lower() == label
for text, label in held_out
)
scores.append(correct / len(held_out))
return min(scores), max(scores), sum(scores) / len(scores)
def toy_predict(order, text):
# Stand-in for a model call: it copies the last example's label
# unless the text contains an obvious keyword.
if "great" in text:
return "positive"
if "broken" in text:
return "negative"
return order[-1][1]
held_out = [
("This is great.", "positive"),
("It arrived broken.", "negative"),
("It came in a box.", "neutral"),
("It was delivered today.", "neutral"),
]
low, high, mean = order_sensitivity(toy_predict, chosen, held_out)
print(f"min={low:.2f} max={high:.2f} mean={mean:.2f}")The toy predictor exaggerates recency on purpose, so the spread is easy to see. With a real model, replace toy_predict with a function that builds the prompt and calls the model. Set the temperature to zero where you can, so that score differences come from order and not from sampling.
Read the result this way:
- A small gap between min and max means order barely matters. Pick one order and fix it.
- A large gap means the prompt is fragile. Add examples, rebalance, or choose the best-performing order after checking it on a second held-out set.
Do not select the best order using the same data you report as your final score. That inflates the number. Use a separate validation set for choosing and a test set for the final check.
Failure modes
| Symptom | Likely cause | What to try |
|---|---|---|
| Model overuses one label on ambiguous inputs | Label imbalance in examples | Equalize counts, or test a tilted prompt on production-like data |
| Output matches the last example's label too often | Recency bias | Interleave labels, shuffle, put a mid-difficulty example last |
| Score changes after you reorder examples | Order sensitivity | Test several orders, add examples, pick the order on validation data |
| Model never outputs a rare label | Rare label missing or buried | Include at least one clear example of each label |
| Score differs between identical runs | Sampling randomness | Lower the temperature, repeat runs, report the average |
Keep the order fixed in production
Once you choose an order, store it with the prompt and keep it. Reshuffling on each request makes results harder to debug, because two users with the same input may get different answers for reasons you cannot reproduce. If you select examples dynamically per query, a later chapter covers how to order those too. Even then, apply the same checks: confirm that the label counts are not skewed and that no run of identical labels sits at the end.
Summary of the working rules
- Count labels before you test anything. Aim for equal counts unless production data says otherwise.
- Never group by label, and avoid a run of one label at the end.
- Treat order as a variable to measure, not a detail to guess.
- Choose the order on validation data and confirm it on separate test data.
- Once chosen, fix the order and record it.
Exercise
A four-example sentiment prompt uses the labels positive, negative, neutral. The examples are ordered: positive, positive, negative, neutral. On a held-out set, the model predicts "neutral" far too often for ambiguous reviews. Name two problems visible in the prompt that could cause this, and describe how you would test whether each one matters.
Show answer
First, the labels are unbalanced: positive appears twice, and the other two once each, and four examples cannot split evenly across three labels. Test this by adding one more example (making six, two per label) or dropping one, then re-scoring on the same held-out set. Second, the last example is "neutral," so recency bias may push the model toward that label. Test this by shuffling the examples into several orders, with "neutral" not last in some of them, and compare the min, max, and mean scores with a function like order_sensitivity. If the scores vary widely, order is a factor. Choose the order on validation data and confirm it on a separate test set.