Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ to 0.109 releases under the wrong numbers; they are yanked.

## Unreleased

- `Selection.trim()`: how many SFT rows your test can see, and which ones. `trim(n)` keeps the first `n` of one
nested order: seeded random by default (arXiv:2410.09335), `by="diverse"` / `"target"` with `embed=`, or
`"bigram"`; duplicates last. `trim({n: scores}, base=)` fits rectified (arXiv:2402.02314), power and log-linear
curves, picks the form that best predicts the largest size (arXiv:2209.06640), and keeps `N*`, the smallest size
past which a doubling gains under `min_gain` (0.01). Seeds or per-item scores add a paired bootstrap range on `N*`
and a detectable-gain check (arXiv:2411.00640). Functions in `whileai.trim`; guide `docs/trim.md`.
- `recipes/papers/context-lm/figures.py`: plain-language titles and subtitles on all five figures.
- `recipes/papers/context-lm/figures.py` adds two figures: right answers by training step, and the untrained vs
trained model's notes on the same held-out log, each line checked against the log's real final values.
Expand Down
3 changes: 2 additions & 1 deletion docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@
"character-training",
"distillation",
"groupwise-grading",
"context-lm"
"context-lm",
"trim"
]
},
{
Expand Down
96 changes: 96 additions & 0 deletions docs/trim.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
title: "Trim SFT data to what the test can see"
sidebarTitle: "Trim SFT data"
description: "Selection.trim fits the learning curve you measured on nested subsets and keeps the smallest N past which one more doubling of rows gains less than a point, with a range on N and a check that your test can see that point."
---

**What you learn:** how many SFT rows still move your test, with an interval, and which rows to keep. **Needs:** a `Selection`, five or more SFT runs on nested subsets (two seeds each), and per-item test scores. **Takes:** one call after the runs.

## The loop

```python
import whileai as wai

rows = wai.select(scored, mode="sft", target=16000)
base = evaluate(base_model) # per-item 0/1 scores on your test

scores = {}
for n in rows.trim_sizes(): # 64, 128, 256, ... len(rows)
scores[n] = [train_and_eval(rows.trim(n), seed) for seed in (0, 1)] # per-item scores per seed

kept = rows.trim(scores, base=base)
print(kept.report["trim"])
kept.export("train.jsonl")
```

```text
verdict: saturated; N* = 5,208 rows (next doubling gains < 0.010)
fit: base + (a - base) * n^c / (d + n^c); base 0.296, a 0.714, c 0.92, d 147
error predicting n=16000 from the rest: rectified 0.007, power 0.014, logit 0.064
N* 90% range 2,239 rows .. 6,214 rows; inside the sizes trained in 100% of draws
last doubling gained +0.007 [+0.000, +0.016]
smallest gain this test can detect: 0.021
note: min_gain 0.010 is under what this test can detect (0.021): add items or seeds
```

That run is a simulation with a known answer (a 1,000-item test, two seeds): the true N* is about 3,700 rows, inside the range. The note is the honest part: this test cannot see a one-point gain, so "saturated" means "nothing the test can see past here". Train every size with the same epochs (or the same steps) and say which; at a fixed step budget, many epochs on few rows can beat one pass on many [16].

## Which rows

`trim(n)` is the first `n` rows of one fixed order, so `trim(64)` sits inside `trim(128)` and every point on the curve comes from one order. Exact duplicates go last; with `embed=`, near duplicates too [9].

| `by=` | What it does | Evidence |
|---|---|---|
| `"random"` (default) | Seeded shuffle | On curated pools, no published selector beat random by more than about a point, and none significantly [1][2] |
| `"diverse"` | k-means on `embed=` vectors, round robin across clusters, longest response first | Embedding diversity tracks fine-tuned quality (r 0.76 to 0.97); lexical diversity does not (r about -0.3) [4]. Clustering added 3 to 5 points in [1] |
| `"target"` | Closest to your `dev=` examples by embedding cosine | RDS+ beat random by about 9 points on a 5.8M-row pool [3] |
| `"bigram"` | New prompt word pairs per prompt word, greedy | No embeddings needed; no study validates it for SFT [4][10] |

Selection pays most on large, noisy pools when the ranker knows the target [3][5]. To see what a ranker is worth on your data, run its curve and a random curve on the same sizes; the gap is the value.

## How many rows

Three curve forms are fit, each point weighted by its noise, `1 / (seed variance / k + item variance / test_n)` [12]:

| Form | Score at n rows | Why it is a candidate |
|---|---|---|
| `rectified` | `base + (a - base) * n^c / (d + n^c)` | The rectified scaling law, which fits the flat start that small SFT sets show [6]. Anchored at the untuned model |
| `power` | `a - b * n^-c` | The classic learning curve [7] |
| `logit` | `logit(score) = alpha + beta * ln n` | Math SFT accuracy is close to linear in `log n` [8] |

The form that best predicts the largest size from the others wins. Forms are compared by extrapolation, not in-sample fit [11].

`N*` is the smallest n past which one more doubling gains less than `min_gain` (default 0.01, one point):

$$\text{score}(2n) - \text{score}(n) < \text{min\_gain}$$

`min_gain` is what a point is worth to you. It is not the test's error bar: a threshold tied to the error bar makes N* grow with the test's size on an identical curve (200, 500, 1,000 and 2,000 items gave 325, 813, 1,627 and 3,254 rows in our first version). The stop rule is progressive sampling's [13], applied to a fitted curve.

## How sure

* **Range on N\*.** A bootstrap resamples test items (the same items at every size, a paired design) and seeds within each size, refits, and reports the 5 to 95% range [12]. The verdict is `saturated` only when N* falls inside the sizes you trained in at least 90% of draws.
* **Can the test see `min_gain`?** The paired detectable gain between the two largest sizes is `2.8 * sqrt(2 * seed_var / k + var(item diffs) / test_n)` [12]. If `min_gain` is smaller, the print says so: add items or seeds.
* **Forecasts.** An N* past twice the largest size is labeled `forecast`. Downstream scores often break from a clean curve [14], and about 15% of learning curves are ill-behaved [15].
* **Other verdicts.** `not identifiable` means over 10% of refits failed, or the power exponent fell under 0.1 (fine-tuning exponents of 0.015 to 0.15 are reported in loss [17]). `flat` means no rising curve fits. Anything but `saturated` or `flat` keeps every row.

One score per size works too, but with equal weights and no range; the print says so.

## References

1. Xia et al. "Rethinking Data Selection at Scale: Random Selection is Almost All You Need." arXiv:2410.09335, 2024.
2. Diddee, Ippolito. "Chasing Random: Instruction Selection Strategies Fail to Generalize." arXiv:2410.15225, 2024.
3. Ivison et al. "Large-Scale Data Selection for Instruction Tuning." arXiv:2503.01807, 2025.
4. "Measuring Data Diversity for Instruction Tuning" (NovelSum). ACL 2025, arXiv:2502.17184.
5. Xia et al. "LESS: Selecting Influential Data for Targeted Instruction Tuning." arXiv:2402.04333, 2024.
6. Lin et al. "Selecting Large Language Model to Fine-tune via Rectified Scaling Law." ICML 2024, arXiv:2402.02314.
7. Hestness et al. "Deep Learning Scaling is Predictable, Empirically." arXiv:1712.00409, 2017.
8. Yuan et al. "Scaling Relationship on Learning Mathematical Reasoning with Large Language Models." arXiv:2308.01825, 2023.
9. Abbas et al. "SemDeDup: Data-efficient learning at web-scale through semantic deduplication." arXiv:2303.09540, 2023.
10. Lin, Bilmes. "Multi-document Summarization via Budgeted Maximization of Submodular Functions." NAACL 2010.
11. Alabdulmohsin, Neyshabur, Zhai. "Revisiting Neural Scaling Laws in Language and Vision." NeurIPS 2022, arXiv:2209.06640.
12. Miller. "Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations." arXiv:2411.00640, 2024.
13. Provost, Jensen, Oates. "Efficient Progressive Sampling." KDD 1999.
14. Lourie, Hu, Cho. "Scaling Laws Are Unreliable for Downstream Tasks: A Reality Check." arXiv:2507.00885, 2025.
15. Yan, Mohr, Viering. "LCDB 1.1." NeurIPS 2025 Datasets and Benchmarks, arXiv:2505.15657.
16. "Data Repetition Beats Data Scaling in Long-CoT SFT." arXiv:2602.11149, 2026.
17. Zhang et al. "When Scaling Meets LLM Finetuning: The Effect of Data, Model and Finetuning Method." ICLR 2024, arXiv:2402.17193.
43 changes: 43 additions & 0 deletions scripts/doc_snippets/trim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""The reader's side of docs/trim.md.

The page trains a model once per subset size, which takes GPUs. This file
stands in for that: `scored` is 16,000 graded SFT rows, and `train_and_eval`
returns per-item scores from a known learning curve (the untuned model at
0.30 rising to 0.70, rectified form, arXiv:2402.02314), so the page's own
`trim` calls run for real and the printed verdict can be checked against a
known answer (N* about 3,700 rows at min_gain 0.01).
"""

import random

base_model = "untuned"


def _row(i):
ask = f"Question {i}: total sales for region r{i % 37} in month m{i % 12}?"
say = f"The total for r{i % 37} in m{i % 12} is {i * 7} dollars."
return {
"prompt": ask,
"final_text": say,
"messages": [{"role": "user", "content": ask}, {"role": "assistant", "content": say}],
"reward": 1.0,
}


scored = [_row(i) for i in range(16000)]

_rng = random.Random(0)
_DIFFICULTY = [_rng.random() for _ in range(1000)]


def _p(n):
return 0.30 + 0.40 * n / (200 + n)


def evaluate(model):
return [1.0 if u < 0.30 else 0.0 for u in _DIFFICULTY]


def train_and_eval(rows, seed):
p = _p(len(rows)) + random.Random(seed * 100003 + len(rows)).gauss(0, 0.005)
return [1.0 if u < p else 0.0 for u in _DIFFICULTY]
181 changes: 181 additions & 0 deletions tests/api/test_trim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
"""``Selection.trim``: the order, the curve fit and the stopping rule."""

from __future__ import annotations

import random

import pytest

from whileai.selection import Selection
from whileai.trim import _n_star, fit_saturation, order, trim_sizes

# a known curve: the untuned model at 0.30, rising to 0.70 (rectified form)
TRUE = (0.30, 0.70, 1.0, 200.0)


def _true_p(n: float) -> float:
base, a, c, d = TRUE
return base + (a - base) * n**c / (d + n**c)


def _simulate(sizes, *, items=500, seeds=2, rng_seed=0):
"""Per-item 0/1 scores per seed; item i passes when its fixed
difficulty is under the model's pass rate (items are paired)."""
rng = random.Random(rng_seed)
difficulty = [rng.random() for _ in range(items)]
curve = {}
for n in sizes:
runs = []
for _ in range(seeds):
p = _true_p(n) + rng.gauss(0, 0.005)
runs.append([1.0 if u < p else 0.0 for u in difficulty])
curve[n] = runs
base = [[1.0 if u < TRUE[0] else 0.0 for u in difficulty]]
return curve, base


def _rows(prompts, responses=None, rewards=None):
responses = responses or ["ok"] * len(prompts)
rewards = rewards or [1.0] * len(prompts)
return Selection(
[
{"prompt": p, "response": r, "reward": w, "id": i}
for i, (p, r, w) in enumerate(zip(prompts, responses, rewards, strict=True))
],
mode="sft",
)


SIZES = [64 * 2**i for i in range(9)] # 64 .. 16,384


# -- order ----------------------------------------------------------------


def test_random_order_nests_and_is_seeded():
rows = _rows([f"question {i} about item {i * 3}" for i in range(50)])
small, big = rows.trim(10), rows.trim(20)
assert [r["id"] for r in small] == [r["id"] for r in big][:10]
assert [r["id"] for r in rows.trim(10, seed=1)] != [r["id"] for r in small]
assert small.report["n_before_trim"] == 50
assert "random order" in str(small)


def test_duplicates_go_last():
rows = _rows(
["sum sales by region", "Sum sales, by region!", "list overdue invoices", "plot revenue"]
)
for by in ("random", "bigram"):
assert order(rows, by)[-1] == 1


def test_near_duplicates_by_embedding_go_last():
vec = {"a": [1.0, 0.0], "b": [0.99, 0.01], "c": [0.0, 1.0]}
rows = _rows(["a", "b", "c"])
idx = order(rows, "random", embed=lambda texts: [vec[t.split()[0]] for t in texts])
assert idx[-1] == 1


def test_diverse_round_robins_clusters():
prompts = [f"x{i}" for i in range(6)] + [f"y{i}" for i in range(6)]

def embed(texts):
return [
[1.0, 0.1 * i] if t.startswith("x") else [-1.0, 0.1 * i] for i, t in enumerate(texts)
]

idx = order(_rows(prompts), "diverse", embed=embed)
first_two = {prompts[i][0] for i in idx[:2]}
assert first_two == {"x", "y"} # one from each cluster before a second from either


def test_target_ranks_closest_to_dev_first():
vec = {"tax": [1.0, 0.0], "cooking": [0.0, 1.0], "audit": [0.6, 0.4]}
rows = _rows(["cooking", "audit", "tax"])
idx = order(rows, "target", embed=lambda ts: [vec[t.split()[0]] for t in ts], dev=["tax"])
assert [rows[i]["prompt"] for i in idx] == ["tax", "audit", "cooking"]


def test_rankers_that_need_embeddings_say_so():
with pytest.raises(ValueError, match="embed="):
order(_rows(["a b"]), "diverse")
with pytest.raises(ValueError, match="dev="):
order(_rows(["a b"]), "target", embed=lambda ts: [[1.0] for _ in ts])
with pytest.raises(ValueError, match="one of"):
order(_rows(["a b"]), "quality")


def test_trim_sizes_double_to_len():
assert trim_sizes(1000) == [64, 128, 256, 512, 1000]
assert trim_sizes(50) == [50]


# -- curve and stopping rule ------------------------------------------------


def test_recovers_known_saturation_point():
truth = _n_star("rectified", TRUE, 0.01, 1) # about 4,000 rows
curve, base = _simulate(SIZES)
fit = fit_saturation(curve, base=base, draws=40)
assert fit.verdict == "saturated"
assert truth / 1.5 < fit.n_saturated < truth * 1.5
assert fit.interval is not None and fit.interval[0] <= fit.n_saturated <= fit.interval[1]
assert "N* 90% range" in str(fit)


def test_n_star_does_not_grow_with_test_size():
# the first version's threshold was the test's error bar, so N* grew
# with test_n on an identical curve; gain per doubling must not
small = fit_saturation(
_simulate(SIZES, items=200)[0], base=_simulate(SIZES, items=200)[1], draws=0
)
large = fit_saturation(
_simulate(SIZES, items=2000)[0], base=_simulate(SIZES, items=2000)[1], draws=0
)
assert 0.6 < small.n_saturated / large.n_saturated < 1.6


def test_curve_still_climbing_is_a_forecast():
curve, base = _simulate(SIZES[:5]) # stops at 1,024; truth is about 4,000
fit = fit_saturation(curve, base=base, draws=40)
assert fit.verdict in ("forecast", "not saturated")
assert not fit.saturated


def test_flat_curve():
fit = fit_saturation({64: 0.60, 128: 0.59, 256: 0.60, 512: 0.58, 1024: 0.59}, base=0.6)
assert fit.saturated and fit.n_saturated <= 128


def test_one_score_per_size_says_no_interval():
fit = fit_saturation({n: _true_p(n) for n in SIZES}, base=TRUE[0])
assert fit.interval is None
assert any("no range on N*" in n for n in fit.notes)


def test_undetectable_min_gain_is_flagged():
curve, base = _simulate(SIZES[:6], items=100) # still climbing at 2,048
fit = fit_saturation(curve, base=base, min_gain=0.001, draws=0)
assert fit.mde is not None and fit.mde > 0.001
assert any("under what this test can detect" in n for n in fit.notes)


def test_trim_with_curve_keeps_n_star_rows():
rows = _rows([f"ask {i} on table t{i}" for i in range(6000)])
curve, base = _simulate([*SIZES[:7], 6000])
kept = rows.trim(curve, base=base)
fit = kept.report["trim"]
if fit.saturated:
assert len(kept) == min(int(fit.n_saturated), 6000)
else:
assert len(kept) == 6000
assert "verdict:" in str(kept)


def test_refusals():
with pytest.raises(ValueError, match="at least 5"):
fit_saturation({64: 0.4, 128: 0.5, 256: 0.55, 512: 0.56})
with pytest.raises(ValueError, match="base="):
fit_saturation({0: 0.3, 64: 0.4, 128: 0.5, 256: 0.55, 512: 0.56})
with pytest.raises(ValueError, match="row count"):
_rows(["a b"]).trim(0)
Loading
Loading