Cold Starts, Rejection Sampling, and Distillation › A CPU-sized implementation

Michael BrenndoerferNovember 29, 202617 min read
Language AI HandbookAll chapters
Part 40 of 67Reasoning Post-Training and Verifiable Rewards
Chapter 302Cold Starts, Rejection Sampling, and Distillation › A CPU-sized implementation
Reading section 9 of 12 · A CPU-sized implementation · 17 minSection 9 of 12 · 17 min

Section 9 of 12 · 17 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The example fits a three-strategy policy, queries a seeded stochastic simulator, scores the resulting answers with two verifiers, and compares those filters on the same proposals. Strategy labels stand in for token sequences so we can examine selection and target distributions without training a language model.

The toy is not an estimate of how any deployed model performs. Its numbers are illustrative of the direction and mechanism of each effect, nothing more.

The hidden setup cell calls seed_book_plots() to seed the plot random generators. The figure cells apply the shared style. The simulator uses the imports and seeded random generator in the displayed setup below.

The 64 problems are ordered pairs (a,b)(a,b) with both operands from 2 through 9. NumPy’s seed-7 permutation leaves the last 16 ordered pairs for evaluation and the other 48 for fitting. Ten of the held-out pairs have their reverse in training. The split excludes identical ordered prompts but not every previously seen multiplication fact.

PythonIn [9]
CollapseExpand
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
PAIRS = [(a, b) for a in range(2, 10) for b in range(2, 10)]
perm = rng.permutation(len(PAIRS))
train_pairs = [PAIRS[i] for i in perm[:48]]
heldout_pairs = [PAIRS[i] for i in perm[48:]]

STRATEGIES = ["fact_recall", "repeated_addition", "guess"]
STRAT_TO_ID = {s: i for i, s in enumerate(STRATEGIES)}
N_STRATS = len(STRATEGIES)
ConsoleOut [10]
CollapseExpand
Total problems: 64
Train problems: 48    Held-out problems: 16
Example train problem: (4, 2) -> 8
Example held-out problem: (3, 9) -> 27

Each problem gets a small feature vector. The features include the operands and their exact product. This toy assumes the product is already available to the policy when it selects a strategy label. Held-out accuracy here compares strategies under that assumption rather than testing arithmetic fact learning.

PythonIn [11]
CollapseExpand
def features(a, b):
    prod = a * b
    return np.array(
        [
            1.0,
            0.1 * a,
            0.1 * b,
            0.02 * prod,
            0.1 * (a + b),
            0.1 * abs(a - b),
            float(a == b),
            float(min(a, b) <= 4),
            float(max(a, b) >= 7),
        ],
        dtype=float,
    )


X_train = np.stack([features(a, b) for a, b in train_pairs])
X_held = np.stack([features(a, b) for a, b in heldout_pairs])

The oracle knows the true product exactly. The three strategies are simulated as follows:

  • fact_recall is correct with probability 0.600.60. When wrong, it produces a near-miss offset from {−1,+1,−a,+a,−b,+b}\{-1, +1, -a, +a, -b, +b\}. With probability 0.080.08 it forgets to format the answer, which the verifier treats as rejection.
  • repeated_addition is correct with probability 0.750.75. When wrong, it slips by ±1\pm 1 or ±2\pm 2.
  • guess produces a uniformly random integer in [2,81][2, 81]. Its expected accuracy is 1/801/80.

These probabilities are simulator settings. Repeated addition has success probability 0.75 for every pair, so it is the best action everywhere in this toy. Always choosing it attains the 0.75 ceiling. The experiment compares how filters and teacher targets affect fitted policies under that known ceiling.

PythonIn [12]
CollapseExpand
P_CORRECT = {
    "fact_recall": 0.60,
    "repeated_addition": 0.75,
    "guess": 1.0 / 80.0,
}


def run_strategy(name, a, b, rng):
    correct = a * b
    if name == "fact_recall":
        if rng.random() < 0.60:
            ans = correct
        else:
            offset = int(rng.choice([-1, 1, -a, a, -b, b]))
            ans = max(2, correct + offset)
        formatted = rng.random() > 0.08
        return {"strategy": name, "answer": ans, "formatted": formatted}
    if name == "repeated_addition":
        if rng.random() < 0.75:
            ans = correct
        else:
            ans = max(2, correct + int(rng.choice([-1, 1, -2, 2])))
        return {"strategy": name, "answer": ans, "formatted": True}
    if name == "guess":
        ans = int(rng.integers(2, 82))
        return {"strategy": name, "answer": ans, "formatted": True}
    raise ValueError(name)

The two verifiers implement the two error modes from the worked example. The strict verifier requires a parseable response and exact value. The buggy verifier accepts any even answer when the true product is even, and rejects unformatted traces.

PythonIn [13]
CollapseExpand
def verifier_buggy(trace, a, b):
    if not trace["formatted"]:
        return False
    correct = a * b
    if trace["answer"] == correct:
        return True
    if correct % 2 == 0 and trace["answer"] % 2 == 0:
        return True
    return False


def verifier_strict(trace, a, b):
    if not trace["formatted"]:
        return False
    return trace["answer"] == a * b

The student is a linear softmax over strategy labels. Its expected task accuracy averages the probability of producing the correct numeric value on a held-out problem. Both verifiers also require the answer format, so a numerically correct attempt can fail either filter.

PythonIn [14]
CollapseExpand
def softmax(Z):
    Z = Z - Z.max(axis=1, keepdims=True)
    E = np.exp(Z)
    return E / E.sum(axis=1, keepdims=True)


def fit_softmax(X, Y, epochs=400, lr=0.1, l2=1e-4):
    N, D = X.shape
    C = Y.shape[1]
    W = np.zeros((D, C))
    for _ in range(epochs):
        P = softmax(X @ W)
        G = X.T @ (P - Y) / N + l2 * W
        W -= lr * G
    return W


def predict_proba(W, x):
    return softmax(x.reshape(1, -1) @ W)[0]


def expected_accuracy(W, pairs):
    total = 0.0
    for a, b in pairs:
        p = predict_proba(W, features(a, b))
        total += sum(p[i] * P_CORRECT[STRATEGIES[i]] for i in range(N_STRATS))
    return total / len(pairs)

expected_accuracy is the student's expected accuracy on a set of problems, computed analytically from its strategy mixture and the per-strategy accuracy. It is a clean way to evaluate without a sampling step, and it isolates the policy's accuracy from simulator noise. We report it on the held-out problems.

The cold-start set is a small collection of preset strategy labels restricted to training prompts. A softmax can assign positive probability to a strategy even if that strategy has no explicit label in the set.

PythonIn [15]
CollapseExpand
cold_start_examples = [
    (2, 3, "fact_recall"),
    (2, 4, "fact_recall"),
    (3, 3, "fact_recall"),
    (3, 4, "fact_recall"),
    (2, 5, "fact_recall"),
    (2, 6, "fact_recall"),
    (2, 5, "repeated_addition"),
    (3, 5, "repeated_addition"),
    (4, 4, "repeated_addition"),
    (3, 6, "repeated_addition"),
    (4, 5, "repeated_addition"),
    (5, 5, "repeated_addition"),
    (2, 4, "guess"),
    (3, 2, "guess"),
]

cold_start_examples = [
    row for row in cold_start_examples if row[:2] in train_pairs
]
assert all(row[:2] not in heldout_pairs for row in cold_start_examples)
X_cold = np.stack([features(a, b) for a, b, _ in cold_start_examples])
Y_cold = np.zeros((len(cold_start_examples), N_STRATS))
for i, (_, _, s) in enumerate(cold_start_examples):
    Y_cold[i, STRAT_TO_ID[s]] = 1.0

W_cold = fit_softmax(X_cold, Y_cold, epochs=800, lr=0.1)
ConsoleOut [16]
CollapseExpand
Cold-start student held-out expected accuracy: 0.699
Expected accuracy if every problem uses repeated addition: 0.750
Expected accuracy with a uniform strategy mixture: 0.454

The warm-started classifier has higher expected accuracy here than a uniform mixture. One preset guess example survives training-prompt filtering. The softmax model may assign probability to each strategy even without an explicit example for that strategy.

Next we sample many attempts per training problem, apply both verifiers to the same attempts (so the comparison is controlled), and measure verifier precision and recall against the true oracle.

PythonIn [17]
CollapseExpand
def sample_attempts(W, pairs, k=8, rng=rng):
    rows = []
    for a, b in pairs:
        p = predict_proba(W, features(a, b))
        for _ in range(k):
            s_id = rng.choice(N_STRATS, p=p)
            s = STRATEGIES[s_id]
            trace = run_strategy(s, a, b, rng)
            rows.append(
                {
                    "a": a,
                    "b": b,
                    "strategy": s,
                    "answer": trace["answer"],
                    "formatted": trace["formatted"],
                    "true_answer": a * b,
                    "truly_correct": trace["answer"] == a * b,
                }
            )
    return pd.DataFrame(rows)


def apply_verifier(df, verifier):
    df = df.copy()
    df["accepted"] = [
        verifier({"answer": r.answer, "formatted": r.formatted}, r.a, r.b)
        for r in df.itertuples()
    ]
    return df


def verifier_report(df):
    accepted = df["accepted"].values
    correct = df["truly_correct"].values
    tp = int((accepted & correct).sum())
    fp = int((accepted & ~correct).sum())
    fn = int((~accepted & correct).sum())
    precision = tp / (tp + fp) if (tp + fp) else np.nan
    recall = tp / (tp + fn) if (tp + fn) else np.nan
    return {
        "precision": precision,
        "recall": recall,
        "accepted": int(accepted.sum()),
        "tp": tp,
        "fp": fp,
        "fn": fn,
    }
PythonIn [18]
CollapseExpand
attempts = sample_attempts(W_cold, train_pairs, k=8)
df_buggy = apply_verifier(attempts, verifier_buggy)
df_strict = apply_verifier(attempts, verifier_strict)
report_buggy = verifier_report(df_buggy)
report_strict = verifier_report(df_strict)
summary_df = pd.DataFrame(
    [
        {"verifier": "buggy (parity)", **report_buggy},
        {"verifier": "strict (exact)", **report_strict},
    ]
).set_index("verifier")
ConsoleOut [19]
CollapseExpand
Total attempts: 384
Traces that were actually correct: 266 (69.3%)

Verifier behavior on the same attempt set:
                accepted   tp  fp  fn  precision  recall
verifier                                                
buggy (parity)       305  260  45   6      0.852   0.977
strict (exact)       260  260   0   6      1.000   0.977

Both verifiers give the same decisions for truly correct candidates. They accept a correct value if it is formatted and reject it otherwise. The extra acceptances under the permissive verifier are wrong answers. The observed precision gap describes the fraction of retained responses that are correct under each filter.

VisualizationOut [20]
CollapseExpand
Grouped bars for the buggy and strict verifiers on identical sampled traces. In each group the left bar is precision and the right bar is recall.
Precision (left bar) and recall (right bar) measured on the same sampled attempts. Both verifiers reject unformatted responses. The permissive verifier additionally accepts formatted incorrect even values for even products.

Recall is the fraction of numerically correct attempts that pass the filter. The two filters agree on every numerically correct attempt, so their recall is equal whenever the pool contains at least one. Recall is undefined for both filters when the pool has no numerically correct attempts. The permissive rule can raise the false-positive rate by accepting extra incorrect answers.

We run four rejection rounds under each verifier, starting from the same cold policy and random seed. The current policy proposes examples. A nonempty round then fits a fresh coefficient matrix from zero on the new retained examples. Once policies diverge, the same random seed need not produce the same candidates.

PythonIn [21]
CollapseExpand
def train_rejection(W, pairs, rounds=4, k=8, verifier=verifier_buggy, rng=rng):
    W = W.copy()
    history = [expected_accuracy(W, heldout_pairs)]
    for _ in range(rounds):
        attempts = sample_attempts(W, pairs, k=k, rng=rng)
        accepted = apply_verifier(attempts, verifier)
        accepted = accepted[accepted["accepted"]]
        if len(accepted) == 0:
            history.append(expected_accuracy(W, heldout_pairs))
            continue
        X_a = np.stack([features(r.a, r.b) for r in accepted.itertuples()])
        Y_a = np.zeros((len(accepted), N_STRATS))
        for i, r in enumerate(accepted.itertuples()):
            Y_a[i, STRAT_TO_ID[r.strategy]] = 1.0
        W = fit_softmax(X_a, Y_a, epochs=400, lr=0.1)
        history.append(expected_accuracy(W, heldout_pairs))
    return W, history
PythonIn [22]
CollapseExpand
W_buggy, hist_buggy = train_rejection(
    W_cold,
    train_pairs,
    rounds=4,
    verifier=verifier_buggy,
    rng=np.random.default_rng(11),
)
W_strict, hist_strict = train_rejection(
    W_cold,
    train_pairs,
    rounds=4,
    verifier=verifier_strict,
    rng=np.random.default_rng(11),
)
ConsoleOut [23]
CollapseExpand
 round  buggy verifier  strict verifier
     0           0.699            0.699
     1           0.712            0.725
     2           0.720            0.731
     3           0.729            0.735
     4           0.734            0.739

Compare the two curves for this fixed seed. They show how the two filters affect this simulated training loop.

VisualizationOut [24]
CollapseExpand
Line chart of held-out accuracy over four rejection sampling rounds for buggy and strict verifiers.
Held-out expected accuracy over four simulated refitting rounds for both verifiers. The starting policy and random seed are the same. Later proposals can diverge as the policies change.

Both curves rise in this run. The permissive filter changes the mix of examples that the policy sees, and the fitted policy changes future proposals. For each product parity in this split, both trained policies assign a lower mean probability to the guess strategy than the cold-start policy does. The strategy-mixture table below prints the probabilities used in the heatmap.

We can see the strategy distribution directly. On the held-out set, split by the parity of the true product, compare the average strategy mixture of the cold-start student, the buggy student, and the strict student.

PythonIn [25]
CollapseExpand
def avg_strategy_mix(W, pairs):
    probs = np.stack([predict_proba(W, features(a, b)) for a, b in pairs])
    return probs.mean(axis=0)


even_held = [(a, b) for a, b in heldout_pairs if (a * b) % 2 == 0]
odd_held = [(a, b) for a, b in heldout_pairs if (a * b) % 2 == 1]

policies = [
    ("Cold start", W_cold),
    ("Buggy filter", W_buggy),
    ("Strict filter", W_strict),
]
rows = []
for name, W in policies:
    for parity, pairs in [
        ("even product", even_held),
        ("odd product", odd_held),
    ]:
        mix = avg_strategy_mix(W, pairs)
        for s, p in zip(STRATEGIES, mix):
            rows.append(
                {
                    "policy": name,
                    "parity": parity,
                    "strategy": s,
                    "prob": float(p),
                }
            )
strategy_df = pd.DataFrame(rows)
ConsoleOut [26]
CollapseExpand
strategy                    fact_recall  guess  repeated_addition
policy        parity                                             
Buggy filter  even product        0.077  0.005              0.919
              odd product         0.084  0.006              0.910
Cold start    even product        0.172  0.034              0.794
              odd product         0.149  0.038              0.813
Strict filter even product        0.049  0.004              0.947
              odd product         0.052  0.004              0.943
VisualizationOut [27]
CollapseExpand
Heatmap of strategy probabilities across policies and problem parities.
Average strategy mixture on held-out problems grouped by true product parity. Each row is a policy-parity combination. Columns show the three strategy probabilities.

Each row shows a learned strategy mixture. The verifier changes which outcomes enter training, but the direction of a fitted strategy probability also depends on the realized sample, features, and optimizer.

Now we turn to distillation. We define a strong teacher with a well-shaped strategy policy, then compare hard-target distillation (one sampled strategy per problem, imitated directly) with soft-target distillation (the teacher's full distribution, matched by KL).

PythonIn [28]
CollapseExpand
def teacher_probs(a, b):
    prod = a * b
    logits = np.array(
        [
            1.2 - 0.04 * prod,
            0.4 + 0.04 * prod,
            -2.0,
        ]
    )
    z = logits - logits.max()
    e = np.exp(z)
    return e / e.sum()


teacher_held = np.stack([teacher_probs(a, b) for a, b in heldout_pairs])
teacher_expected_acc = np.mean(
    [
        sum(
            teacher_probs(a, b)[i] * P_CORRECT[STRATEGIES[i]]
            for i in range(N_STRATS)
        )
        for a, b in heldout_pairs
    ]
)

# Hard-target distillation: one sampled strategy per training problem
rng_hard = np.random.default_rng(0)
hard_labels = []
for a, b in train_pairs:
    p = teacher_probs(a, b)
    s_id = rng_hard.choice(N_STRATS, p=p)
    hard_labels.append(s_id)

X_distill = np.stack([features(a, b) for a, b in train_pairs])
Y_hard = np.zeros((len(train_pairs), N_STRATS))
for i, s_id in enumerate(hard_labels):
    Y_hard[i, s_id] = 1.0
W_hard = fit_softmax(X_distill, Y_hard, epochs=600, lr=0.1)

# Soft-target distillation: match the teacher's full distribution
Y_soft = np.stack([teacher_probs(a, b) for a, b in train_pairs])
W_soft = fit_softmax(X_distill, Y_soft, epochs=600, lr=0.1)
PythonIn [29]
CollapseExpand
def kl_to_teacher(W, pairs):
    total = 0.0
    for a, b in pairs:
        p = predict_proba(W, features(a, b))
        q = teacher_probs(a, b)
        total += float(np.sum(q * np.log(q / p)))
    return total / len(pairs)


def mean_max_prob(W, pairs):
    return float(
        np.mean([predict_proba(W, features(a, b)).max() for a, b in pairs])
    )


def top1_agreement(W, pairs):
    return float(
        np.mean(
            [
                np.argmax(predict_proba(W, features(a, b)))
                == np.argmax(teacher_probs(a, b))
                for a, b in pairs
            ]
        )
    )


distill_results = pd.DataFrame(
    [
        {
            "model": "Teacher (analytic)",
            "accuracy": teacher_expected_acc,
            "kl_to_teacher": 0.0,
            "mean_max_prob": float(np.mean(teacher_held.max(axis=1))),
            "top1_agreement": 1.0,
        },
        {
            "model": "Hard-target student",
            "accuracy": expected_accuracy(W_hard, heldout_pairs),
            "kl_to_teacher": kl_to_teacher(W_hard, heldout_pairs),
            "mean_max_prob": mean_max_prob(W_hard, heldout_pairs),
            "top1_agreement": top1_agreement(W_hard, heldout_pairs),
        },
        {
            "model": "Soft-target student",
            "accuracy": expected_accuracy(W_soft, heldout_pairs),
            "kl_to_teacher": kl_to_teacher(W_soft, heldout_pairs),
            "mean_max_prob": mean_max_prob(W_soft, heldout_pairs),
            "top1_agreement": top1_agreement(W_soft, heldout_pairs),
        },
        {
            "model": "Strict rejection student",
            "accuracy": expected_accuracy(W_strict, heldout_pairs),
            "kl_to_teacher": kl_to_teacher(W_strict, heldout_pairs),
            "mean_max_prob": mean_max_prob(W_strict, heldout_pairs),
            "top1_agreement": top1_agreement(W_strict, heldout_pairs),
        },
    ]
).set_index("model")
ConsoleOut [30]
CollapseExpand
Distillation comparison on held-out problems:
                          accuracy  kl_to_teacher  mean_max_prob  top1_agreement
model                                                                           
Teacher (analytic)           0.701          0.000          0.763           1.000
Hard-target student          0.706          0.033          0.807           0.938
Soft-target student          0.702          0.005          0.764           1.000
Strict rejection student     0.739          0.219          0.945           0.938

The output table lets us compare students on the same held-out prompts. The soft-target student has the lowest KL among the students in this run. The hard-target student has a higher mean maximum strategy probability than the teacher, which describes concentration without measuring calibration. On the 16 held-out pairs selected with seed 7, expected accuracy rounds to 0.701 for the analytic teacher and 0.739 for the strict-rejection student. This illustrates that matching an analytic teacher and maximizing task accuracy can rank policies differently.

The scatter plot places teacher-to-student KL and mean maximum strategy probability on separate axes. The hard-target student differs from the analytic teacher on both measures in this run.

PythonIn [31]
CollapseExpand
model_labels = distill_results.index.tolist()
kl_values = distill_results["kl_to_teacher"].to_numpy()
confidence_values = distill_results["mean_max_prob"].to_numpy()
VisualizationOut [32]
CollapseExpand
Scatter of teacher KL divergence versus mean maximum probability for four models.
Teacher-to-model KL divergence on the horizontal axis and mean maximum strategy probability on the vertical axis. Equal-sized marks identify the four models by shape.
VisualizationOut [33]
CollapseExpand
Bar chart of held-out expected accuracy for the analytic teacher, hard-target student, soft-target student, and strict-rejection student.
Held-out expected accuracy for the teacher and three students. The hard-target and soft-target students are trained on the teacher's samples or distribution, respectively, while the strict-rejection student is trained on its own verified traces. A separate figure compares distributional agreement and confidence.
VisualizationOut [34]
CollapseExpand
Two bar chart panels comparing hard and soft students by teacher-to-student KL in nats and mean maximum strategy probability.
Teacher-to-student KL divergence and mean maximum strategy probability for hard and soft distillation students, shown on separate axes. The second metric describes concentration.

Accuracy, KL, and confidence measure different quantities. Mean maximum strategy probability describes concentration without measuring calibration.

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