Unit 8 of 10 · about 5 hours · derive, measure

Token entropy, sequence diversity, KL direction and KL estimators

KL and entropy traces are the early warning for collapse and drift. The wrong direction or estimator makes the warning point backwards.

You'll be able to

  • Derive token entropy and the reverse-KL penalty from their expectations, and state the sampling distribution each needs.
  • Compute the k1, k2 and k3 estimators on hand log probabilities and state the bias, sign and variance of each.
  • Measure token entropy and sequence diversity separately and name the estimator behind every reported KL number.

Covers

Token-level entropy and sequence-level diversityForward and reverse KL direction vocabularyReference-policy KL estimators and approximation limits
1

Read

In this order, only the parts listed

0 of 4 done

  1. KL, entropy and the Monte Carlo estimatorsRLHF Book Course - Lectures 0 and 1

    Slides 23 and 24 of 31: cross-entropy as entropy plus KL, the Monte Carlo KL with the log-ratio integrand, the high-variance k1, and the low-variance non-negative k3 with r as reference over policy

  2. Three estimators in codeKL Estimators - Schulman's Note and the RLHF Book Code

    approx_kl1, approx_kl2 and approx_kl3 with masked_mean, read against Schulman's note Approximating KL Divergence linked at the top of the file; approx_kl1 returns the negated log ratio (expectation negative KL), approx_kl3 uses the reciprocal ratio (policy over reference), and approx_kl2 is symmetric under swapping the two policies

  3. Reverse KL and the implementation exampleRLHF Book - Introduction, Training Overview and Instruction Tuning

    KL Divergence in RL Optimization (reverse KL to the reference, Equation 4 over samples from the trained model) with Implementation Example Steps 1 to 5 and kl_approx

    Use kl_approx only. Skip the kl_full line: it returns NaN in torch 2.14.

  4. Correct k3 referenceTRL GRPO Trainer - KL estimation and loss

    Estimating the KL divergence: the k3 formula with the reference-over-policy ratio, with the default KL-coefficient note beside it

2

Focus on

  • The RLHF penalty is reverse KL : samples come from the trained policy. It penalizes most where the new policy puts mass the reference calls unlikely. Forward KL is the distillation direction.
  • k1 (mean log ratio) is unbiased but noisy and negative on single samples. k2 (half squared log ratio) is non-negative with small bias near the reference. k3 (mean with ) is unbiased and non-negative.
  • The book code estimators do not match the slide: approx_kl1 estimates negative KL and approx_kl3 uses the reciprocal ratio, so its expectation misses exact KL (0.0247 versus 0.0253 on the hand example). Report traces with the slide and TRL form.
  • Token entropy (expected per-position spread) is not sequence diversity (spread across completions). A peaked-per-token policy can still repeat one answer; measure both.
Common mistakes · 3
  • Reading a negative k1 sample as negative divergence. Single-sample k1 can be negative; only its expectation estimates KL.
  • Copying approx_kl1 or approx_kl3 as the reported KL. One has the wrong sign and the other the wrong ratio; both disagree with the exact value on the hand example.
  • Calling low token entropy high diversity or vice versa. Entropy averages per-position uncertainty under one policy; diversity compares whole completions, for example by distinct n-grams or vote spread.
3

Try it yourself

Closed-book, before checking anything

Closed-book, for sampled policy q = [0.5, 0.3, 0.2] against reference p = [0.4, 0.4, 0.2], derive exact KL 0.0253, Schulman k1 mean 0.0253, the book code approx_kl1 mean of negative 0.0253, mean k2 of 0.0249, code-k3 mean of 0.0247, and true-k3 mean of 0.0253. State which estimators agree with the exact value.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does reverse KL suit the RLHF penalty better than forward KL?Answer

    Reverse KL averages under the trained policy and punishes mass where the reference is thin, which is exactly drift into unseen regions. Forward KL averages under the reference and punishes missing reference modes, which suits distillation, not drift control.

  2. 2.On the hand example, which estimators match exact KL in expectation, and what are the other two?Answer

    Schulman k1 (0.0253) and true k3 (0.0253) match. k2 gives 0.0249 (small bias), the book code approx_kl1 gives negative 0.0253 (negated) and approx_kl3 gives 0.0247 (reciprocal-ratio bias).

  3. 3.A trace shows KL near zero but outputs are near-identical across prompts. What happened?Answer

    The policy collapsed while staying near the reference on average, or diversity was never measured. KL to the reference does not measure spread across completions; add a diversity metric.

  4. 4.Beta is 0.0 in the TRL default noted in the study. What does the KL term do then?Answer

    Nothing, and there is no trace either: with beta=0.0 TRL does not load the reference model, so no reference KL is computed or logged. Drift is unconstrained, so load a reference separately or log another drift signal.

5

Practice

  • Hands-on Modern RL 13.9: hand-calculate one token KL penalty

    Hand-calculate one token's KL penalty: actor log probability negative 1.2, reference negative 1.6, giving negative 0.02 with reward-model score 1.3 at EOS (page read 2026-10-14)

    Then recompute the same token with the k3 form and state which estimator each of your traces uses. The section mini-project records the same diagnostics on your rollouts.

You're done when

You reproduce all five hand numbers, can derive each estimator expectation, and every KL you report names its estimator and direction.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 6 more in the section
  • RLHF Book - Introduction, Training Overview and Instruction TuningNathan Lambert · primary

    Study Chapter 1 (introduction), Chapter 3 (training overview: problem formulation and canonical recipes), Chapter 4 (instruction tuning: chat templates and implementation details) and Appendix A (definitions) at https://rlhfbook.com/c/. Map every RLHF component into the track trajectory schema, then implement assistant-only sequence log probabilities and completion masks against hand examples.

  • RLHF Book Course - Lectures 0 and 1Nathan Lambert · required

    Watch Lecture 0 (the ML foundations of post-training, including KL) and Lecture 1 (overview of Chapters 1 to 3), with slides under https://rlhfbook.com/teach/course/. Produce a component and state-ownership diagram tied to executable tests, not a second set of general notes.

  • KL Estimators - Schulman's Note and the RLHF Book CodeJohn Schulman; Nathan Lambert · required

    Read John Schulman's note "Approximating KL Divergence" (on joschu.net, linked from the code) for the three Monte Carlo estimators , , and their bias and variance, then the approx_kl1, approx_kl2 and approx_kl3 functions in this file at commit 1042143. Compute all three on sampled tokens from two small policies whose exact KL you know, and say which one each library you use reports.

  • TRL GRPO Trainer - KL estimation and lossHugging Face · reference

    Read Estimating the KL divergence for the k3 formula with the reference-over-policy ratio, and the default KL-coefficient note. Use it as the correct-ratio reference beside the RLHF Book code estimators.

Also in this section

  • Training Language Models to Follow Instructions with Human FeedbackOpenAI · required

    Study the demonstration, comparison, reward-model and PPO pipeline plus evaluation design. Reconstruct the data and policy dependencies and state which results cannot be inferred from the paper at small scale.

  • Berkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - LLM RLUC Berkeley · support

    Slides are public at https://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-N.pdf; current videos are not, and the public Fall 2023 playlist numbers lectures differently. Study Lecture 14 (LLM RL) for the language-model-as-policy formulation and how it maps onto the policy-gradient lectures.

  • Build a Reasoning Model (From Scratch) - Chapters 2 to 5Sebastian Raschka (Manning) · support

    Use Chapter 2 (loading Qwen3 0.6B and a minimal generation function), Chapter 4 (temperature, top-p and self-consistency) and Chapter 5 (token probabilities to log probabilities and sequence scores) as a code companion for log-probability, mask and inference-policy oracles. Chapters 2 to 5 run on a CPU.

  • Stanford CS224R 2026 LLM RL Default ProjectStanford University · support

    Read Sections 1.1 through 1.4 for the Countdown task, distinct SFT, preference and verifier datasets, objective boundaries and evaluation. Use it as a design specification and write independent code; do not submit, copy or publish Stanford course solutions.

  • Hands-on Modern RL - Chapter 13 RLHF PipelineWalking Labs · support

    Use the base-model-to-assistant page and the PPO-RLHF loop page for the pipeline and the token-level ratio, clip and KL order of operations. Its KL sketch is the simple log-ratio difference; audit masks and log probabilities independently and defer scale engineering to RL-12. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its code/chapterNN folders do not follow the site chapter numbers.

  • LLM Post-Training Laboratory - Baseline and State ContractRoadmap-Final · required

    Build or reuse the laboratory frozen base, SFT and evaluation baseline plus immutable tokenizer, template, model, policy and rollout manifests. Complete fixed log-probability, mask and state-identity tests only in this stage.