[Feature] Add DistillationLoss for token-level LLM knowledge distillation
Description
Implements DistillationLoss, the on-policy KL knowledge-distillation objective for LLM policies proposed in #3921, under torchrl/objectives/llm/.
A student policy is distilled toward a (typically stronger, frozen) teacher by minimizing a KL divergence estimated from the per-token log-probabilities the two models assign to the same tokens. It mirrors SFTLoss and reuses the same teacher log-prob plumbing as GRPOLoss/SFTLoss:
- student log-probs are computed by running
actor_networkon the input history; - teacher log-probs are consumed from the tensordict, as written by
RetrieveLogProb(teacher, log_probs_full_key=("teacher_log_probs", "full"))or an offline scoring pass, and are detached inside the loss; - the KL is estimated per token with the k3 estimator, exposed as
reverse_kl_token_estimate(the sameexpm1(d) - dapproximation the GRPO/SFT KL regularizers inline); - masking follows the SFT convention: assistant-and-attention masks from
("masks", ...)when present, tokenizer fallback otherwise; masked positions are zeroed on both log-prob tensors before the estimator so extreme masked values cannot poison gradients.
Both directions are supported via kl_direction:
"reverse"(default):KL(student || teacher)for on-policy distillation on student-generated tokens (mode-seeking, GKD-style);"forward":KL(teacher || student)for off-policy distillation on teacher/corpus data (mass-covering).
Plus reduction (mean/sum/none), normalize_by_seq_length, assistant_only=False for plain-corpus distillation, and set_keys() support for custom key layouts.
Example
transform = RetrieveLogProb(
teacher,
log_probs_full_key=("teacher_log_probs", "full"),
assistant_only=True,
tokenizer=tokenizer,
)
with torch.no_grad():
data = transform(data)
loss = DistillationLoss(actor_network=student, tokenizer=tokenizer, kl_direction="reverse")
loss_vals = loss(data)
loss_vals.loss_distill.backward()
The class docstring contains a complete runnable example (verified end-to-end against a randomly initialized OPT pair).
Tests
TestDistillation in test/llm/test_llm_objectives.py, following the TestSFT pattern (tiny OPT models + RetrieveLogProb):
- estimator: exact zero at equality, nonnegativity, closed-form equivalence, shape validation, and a gradient-descent check confirming a step on the loss moves the student toward the teacher (all transformers-free);
- loss in both directions: output type/shapes, finiteness, gradients reach the student;
- exact-zero loss when the teacher is the student (both directions);
- reduction semantics (
mean/sumconsistent withnone) and length normalization; - custom teacher key via
set_keys(); missing-teacherKeyError; invalidkl_direction/reductionvalidation.
Docs entries added to llms.rst and llms_objectives.rst.
Notes
- No Hydra config companion: no LLM loss currently has one (
GRPOLoss/SFTLossincluded), so this follows the existing pattern. - A sota-style teacher/student recipe is planned as a follow-up PR, mirroring how SFT/GRPO recipes are sequenced.
Closes #3921
:link: Helpful Links
:test_tube: See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4038
- :page_facing_up: Preview Python docs built from this PR
Note: Links to docs will display an error until the docs builds have been completed.
:x: 3 New Failures, 3 Unrelated Failures
As of commit 99ee4fa645f66bff4fb31b5d2216d4fa1b8ea632 with merge base 4bf281a7c7cb8aad6c1e49a657d7cec64610f266 ():
NEW FAILURES - The following jobs have failed:
- LLM Tests on Linux / unittests-sglang (3.12, 12.9) / linux-job (gh)
RuntimeError: Command docker exec -t 06e8878fe00dc57e5d793b31617fccaa69b67db6a990f94be2f49c8d60ef7274 /exec failed with exit code 1 - SOTA Tests on Linux / tests (3.10, 13.0, 1) / linux-job (gh)
RuntimeError: Command docker exec -t 7dbe3882c195ae37b4a17348cca23003e3dc8a2fcff1679e866cc4295edc056d /exec failed with exit code 1 - SOTA Tests on Linux / tests (3.10, 13.0, 2) / linux-job (gh)
RuntimeError: Command docker exec -t 15dfe7f9e7a2d52cc47ab4277cd96db333ee998b3dab29b6a82bf0523251b8a9 /exec failed with exit code 1
FLAKY - The following job failed but was likely due to flakiness present on trunk:
- Unit-tests on Linux / tests-cpu (3.14, bulk) / linux-job (gh) (similar failure)
test/test_configs.py::TestLoggerConfigs::test_trackio_logger_config_instantiation
BROKEN TRUNK - The following jobs failed but was present on the merge base:
👉 Rebase onto the `viable/strict` branch to avoid these failures
- Unit-tests on Linux / tests-cpu (3.10, bulk) / linux-job (gh) (trunk failure)
test/test_configs.py::TestLoggerConfigs::test_trackio_logger_config_instantiation - Unit-tests on Linux / tests-cpu (3.13, bulk) / linux-job (gh) (trunk failure)
test/test_configs.py::TestLoggerConfigs::test_trackio_logger_config_instantiation
This comment was automatically generated by Dr. CI and updates every 15 minutes.