Skip to content

Frozen-teacher distillation inside PPO (DAgger as a scheduled loss) + Craftax and mujoco_playground vision envs - #378

Open
Denys88 wants to merge 25 commits into
masterfrom
feature/teacher-distillation
Open

Denys88 wants to merge 25 commits into
masterfrom
feature/teacher-distillation

Conversation

@Denys88

@Denys88 Denys88 commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner

Summary

Distillation from a frozen privileged-state teacher as a loss term inside the existing PPO agents, with weight schedules, so DAgger, DAgger → PPO fine-tune and teacher-guided RL are config variants of one mechanism. Plus two vision envs to try it on. Docs: docs/DISTILLATION.md.

Mechanism — rl_games/common/distillation.py

  • distillation block in the algo config: teacher_config, teacher_checkpoint, loss (discrete KL; continuous KL or MSE, with teacher_mu_clip to bound the targets) and three piecewise-linear epoch schedules: coef (distillation weight), ppo_coef (0 = pure DAgger), beta (P(env action from the teacher), student neglogp recomputed so PPO ratios stay valid).
  • Agent hooks: states stored and passed into minibatches whenever distillation is on; action mixing in get_action_values; loss = ppo_coef·ppo + coef·distill in calc_gradients; central value warm-started from every teacher tensor with matching name and shape.

Envs

  • CraftaxVecEnv (craftax): Craftax-Classic in JAX, obs: symbolic | pixels | both, ~90k steps/s at 1024 envs, CraftaxObserver logs Crafter score.
  • PlaygroundVecEnv (playground): any mujoco_playground env, obs: state | pixels | both via mujoco 3.12's built-in Warp batch renderer; Panda pick-cube ~30k steps/s (state) / ~7k (pixels) at 1024 worlds.

Results (one seed each)

task student from scratch distilled student teacher
Craftax-Classic, 98M frames, reward 16.1 16.5 (reaches 16.1 at 40M, ~2.5× fewer frames) 17.0
Panda pick-cube from 64×64 pixels, 9.8M frames, success 0.00 1.00 (from 4M frames on) 1.00

A third arm, the same pixel student with a privileged-state regression head instead of a teacher (actor_critic_state_aux, state_aux: {}), stays at 0.00 success: the state is decodable from pixels (normalised MSE 0.17) but the bottleneck is exploration, which only the teacher's actions supply.

Two things the Panda run needed: a fixed learning rate (the distillation term inflates the between-update KL and the adaptive schedule collapsed the lr to 5e-6) and clipping the teacher's means to the action range.

Tests

tests/test_distillation.py (6), tests/test_state_aux.py (3), tests/test_craftax_env.py (5, incl. end-to-end discrete), tests/test_playground_env.py (5, incl. end-to-end continuous and state-aux); master PPO regression suites pass (78). The JAX env tests need the 3.11 venv (jax[cuda12], craftax, playground, warp-lang==1.16.0; under WSL2 LD_LIBRARY_PATH=/usr/lib/wsl/lib).

🤖 Generated with Claude Code

https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL

DenSumy and others added 7 commits September 5, 2026 13:52
…vision env

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
… + CraftaxVecEnv

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
states stored/passed into minibatches whenever distillation is on, DAgger
beta-mixing in get_action_values, scheduled ppo_coef/coef loss mix in
calc_gradients (discrete + continuous), central value warm start from the
teacher. Configs: symbolic teacher, pixel student (scratch), pixel student
distilled. End-to-end 2-epoch test on Craftax-Classic.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
… 17.0, Crafter score 60)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…renderer

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
@Denys88
Denys88 force-pushed the feature/teacher-distillation branch from a258452 to ea5d630 Compare September 5, 2026 20:56
@Denys88
Denys88 changed the base branch from feature/envpool-soccer-league to master September 5, 2026 20:56
DenSumy and others added 7 commits September 5, 2026 16:00
…r) with state | pixels | both obs

state vector = the env's own _get_obs(data, info) in every mode, pixels from
the built-in renderer as uint8; time_outs derived from the retained step
counter; PlaygroundObserver logs env metrics. WSL2 note: Warp needs
LD_LIBRARY_PATH=/usr/lib/wsl/lib (the CUDA toolkit stub shadows the driver).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…dent, distilled student

Also: continuous agent's prepare_dataset now carries states for distillation
(only the discrete path had it); end-to-end continuous distillation test on
CartpoleBalance vision; scripts/playground_train.py re-execs with the WSL
CUDA driver path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…inset); env_state() accessor

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…onfig v2 (mse, clipped means, fixed lr)

v1 failed: the distillation term inflates the between-update policy KL, so the
adaptive lr schedule sank to 5e-6, and the teacher's unbounded means (+-3 with
the env clipping at +-1) were unreachable targets.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
@Denys88 Denys88 changed the title Frozen-teacher distillation inside PPO (DAgger as a scheduled loss) + Craftax-Classic vision env Frozen-teacher distillation inside PPO (DAgger as a scheduled loss) + Craftax and mujoco_playground vision envs Sep 6, 2026
DenSumy and others added 7 commits September 5, 2026 19:42
…ary loss (no teacher)

Third arm for the pixel-student comparison: same CNN as the scratch student,
plus an MSE head on the actor trunk predicting the (running-normalised)
privileged state. `state_aux: {}` in the algo config stores states and hands
them to the network; the loss flows through model.get_aux_loss(), which now
delegates to the network.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
… re-exec

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…rd scale

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…se, action masks, clear config errors

- a2c_discrete built its model dict as `config` but stored state_shape into
  `build_config`: NameError for every discrete agent with a central value
  (flake8 F821, the lint CI failure)
- ppo_coef now scales the policy part of the PPO loss only
  (TeacherDistillation.combine); the value head keeps fitting the student's
  returns through a pure-DAgger phase instead of meeting PPO cold
- discrete envs with use_action_masks: the teacher's logits get the student's
  masks in the loss and in the beta-mixing (unmasked, KL(teacher||student) is
  +inf wherever the student has -inf); mixing also runs on the masked rollout
  path
- from_config checks the teacher's action space type against the student's
  and rejects recurrent teachers; multi-discrete logits raise instead of
  failing on a list
- env_reset names the config block (central_value_config / distillation /
  state_aux) when the env returns no 'states'
- minibatches carry 'states' whenever the buffer stores them (prepare_dataset
  no longer touches agent attributes that stub-based tests do not set)
- playground: `pixel_range` env option (dm_control vision envs emit
  mean-centred grayscale in [-0.5, 0.5], not RGB in [0, 1]); craftax: same
  GPU guard as playground in _to_jax; play scripts: no NaN when no episode
  finishes, inset crop for large cam_res; teacher_checkpoint placeholders
  instead of local run dirs
- tests: masks, multi-discrete, combine, from_config round trip through
  ModelBuilder (incl. _orig_mod. prefix, frozen normaliser, rnn/type
  rejection), and end-to-end agent tests (discrete + CV + distillation
  converges towards the teacher, value head trains at ppo_coef 0, missing
  states error, state_aux through the agent)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@Denys88
Denys88 requested a review from ViktorM November 8, 2026 04:15

@ViktorM ViktorM left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean design: one opt-in loss with three schedules covers DAgger, fine-tuning and teacher-guided RL. Two points matter most, both inline: β-mixing under PPO (distillation.py) and the results write-up, where the privileged critic is a confound (DISTILLATION.md). There are also two bugs: a state_aux model can't be played, and num_agents > 1 misaligns states.

Splitting the PR into the distillation core, state_aux (a negative result; a doc paragraph may be enough) and the env wrappers would make it easier to review. The Craftax/playground version pins live only in the docs; pyproject.toml extras would make the results reproducible, and those tests are skipped in CI.

Missing tests: β overlapping PPO, the multi-agent guard, a state_aux play round trip, an RNN student, AMP.

Tested on CPU only: 22 passed, 9 skipped (Craftax/playground). Merges cleanly with master.


Generated by Claude Code


# ------------------------------------------------------------- mixing

def mix_actions(self, res_dict, states, epoch, action_masks=None):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

β-mixing and PPO don't compose. Actions come from μ = (1−β)π_S + βπ_T, so at θ_old the surrogate gradient is (1−β)·E_{π_S}[A∇log π] + β·E_{π_T}[A∇log π]: the PG plus advantage-weighted BC on teacher actions. Recomputing the student's neglogp makes the ratio start at 1; it doesn't make the estimator unbiased. For Gaussians the extra term scales as (a−μ_s)/σ_s², unbounded for teacher samples far from the student's mean. teacher_mu_clip isn't applied here (line 206), so out-of-range samples are stored raw.

The shipped configs avoid this only because β reaches 0 before ppo_coef turns on. Reject the overlap, or store a from_teacher mask and drop those rows from the actor loss (keep them for the critic and the distill term).


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fd60326. Beta-mixed rows are flagged from_teacher (experience buffer -> minibatch) and get no actor loss; they still train the critic and the distillation term. Mixing now also samples around the clipped teacher mean when teacher_mu_clip is set. Tests cover both action types.

if self.loss_type == 'mse':
per_row = ((mu_t - mu_s) ** 2).sum(dim=-1)
else:
per_row = (torch.log(sig_s / sig_t)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

KL(N_t‖N_s) also pulls σ_s toward the teacher's σ, usually annealed small, so the student starts PPO with the teacher's exploration noise. It also scales the mean gradient by 1/σ_s². MSE drops both, which may explain why it was the stable choice on Panda better than the unbounded means do. Detach σ_s in the kl variant, or note this in the docs?


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, kept kl as is and documented it (8d717bd, "Continuous losses" in DISTILLATION.md): kl also matches sigma and scales the mean gradient by 1/sigma_s^2, mse matches means only. mse stays the recommendation for continuous.

def piecewise_linear(spec, epoch):
"""[[epoch, value], ...] -> value at `epoch` (linear between knots,
constant outside). A scalar spec is a constant; None is 0."""
if spec is None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty ppo_coef: in YAML parses to None, hence 0: pure DAgger for the whole run, silently. Raise on None?


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fd60326: a schedule key that is present but empty raises, and malformed schedules (bool, wrong shape) are rejected.

Comment thread rl_games/common/distillation.py Outdated
raise NotImplementedError('distillation does not support multi-discrete action spaces')
logits = logits.float()
if action_masks is not None:
# invalid actions get -inf like CategoricalMasked does for the student,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CategoricalMasked uses −1e8, not −inf. Gradients stay finite here (I checked an all-masked row; masked_fill zeroes them), but Categorical in mix_actions raises on an all-masked row. −1e8 would match the student.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fd60326: the teacher's masked logits use the same finite fill (-1e8) as CategoricalMasked, so an all-masked row no longer breaks the sampler in mix_actions.

Comment thread rl_games/algos_torch/a2c_discrete.py Outdated
value_loss = 0.5 * c_loss * self.critic_coef
loss = a_loss + value_loss - entropy * self.entropy_coef
if self.distill is not None:
d_loss = self.distill.loss(res_dict, input_dict['states'], rnn_masks,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The teacher runs on every minibatch of every mini-epoch, and keeps running after coef reaches 0 only for the log (Craftax: epochs 600–1500, 60% of the run). With 0 * d_loss in the graph, a NaN in this term still poisons the update. Cache the teacher's logits/mus once per epoch in prepare_dataset (they're tiny), skip the term at coef == 0, and log it every N epochs under no_grad. Same in a2c_continuous.py.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fd60326, both algos: the teacher labels the whole rollout once per epoch in prepare_dataset (chunked, no_grad); minibatches carry its logits / mus and sigmas. At coef 0 the term is logged only and stays out of the graph.

from rl_games.common.ivecenv import IVecEnv


def _preload_wsl_cuda():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WSL-specific; it belongs in the scripts or the docs rather than the library module.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still in the module for now; will move it to the scripts.

Comment thread docs/DISTILLATION.md
distilled pixel student reaches the teacher's 100% success by 4M frames,
i.e. as fast as the state teacher itself learned.

**Privileged state as an auxiliary target instead of a teacher**

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confound: both distilled arms run an asymmetric critic on states, warm-started from the teacher. The scratch and state-aux arms have no CV, and on Panda they also use adaptive instead of fixed LR. So 0.00 vs 1.00 doesn't isolate the teacher's actions, and "the bottleneck is exploration" needs pixels + asymmetric CV (cold and warm-started) at the same LR. The asymmetric critic alone matters a lot for pixel manipulation (Pinto et al., 2017). I'd still bet on distillation, but without the CV the state-aux negative result says little.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. 8d717bd states the confound in DISTILLATION.md (warm-started asymmetric CV and fixed lr only in the distilled arm, missing control named, one seed) and downgrades the exploration reading to a hypothesis. It also turned up that the pixel arms run a different task variant (playground's vision flag changes the success criterion and reward terms), which is now documented.

Comment thread docs/DISTILLATION.md
## Vision env: Craftax-Classic

`rl_games/envs/craftax_vecenv.py` (env name `craftax`, JAX, 3.11 venv) renders
the same Craftax-Classic (Crafter) state as a 1345-d symbolic vector and a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1345 = 7×9×21 + 22: the symbolic vector holds the same local map, inventory and intrinsics the image renders. So Craftax tests cross-modal distillation (representation), not privileged information, and has no imitation gap by construction. The case where forward-KL DAgger breaks, a teacher that sees what the student can't, isn't covered. Also: single seed, and the frame counts exclude the teacher's 98M.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, documented in 8d717bd: Craftax-Classic is cross-modal distillation, no imitation gap by construction, single seed, teacher frames not counted.

Comment thread docs/DISTILLATION.md
|---|---|---|---|
| pure DAgger | 0 | 1 | 0.5 -> 0 |
| DAgger -> PPO fine-tune | 0 then 1 | 1 -> 0 | 0.5 -> 0 |
| teacher-guided RL | 1 | small constant | 0 |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: this row is Kickstarting (Schmitt et al., 2018), and student-driven distillation is analyzed in Czarnecki et al., 2019 (Distilling Policy Distillation). Both are worth citing.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 8d717bd.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agent planning notes, like the spec under docs/superpowers/specs/. Drop both from the PR?


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will drop both before merge.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZnNwekkavvwMEKBnkA
… and state_aux play

Teacher actions and PPO
- beta-mixed rows are flagged `from_teacher` (experience buffer -> minibatch)
  and carry no actor loss. A teacher-chosen action is not a sample of the
  student, so a PPO term on it is advantage-weighted behaviour cloning, not a
  policy gradient. The rows still train the critic and the distillation term.
- mixing samples around the clipped teacher mean when `teacher_mu_clip` is set.

Teacher targets
- the teacher labels the rollout once per epoch (`TeacherDistillation.targets`,
  chunked); minibatches carry its logits / means and the update no longer
  calls it. `states` go into the minibatch only for state_aux.
- at coef 0 the term is monitoring only and stays out of the graph, so a
  non-finite distillation loss cannot reach the update.

Guards (all at init)
- multi-agent envs are rejected for distillation and state_aux: states are
  stored per env, observations per agent, so rows would not line up.
- Dict state spaces and multi-discrete students are rejected with a clear error.
- a schedule key that is present but empty (yaml `ppo_coef:`) is an error
  instead of 0; malformed schedules are rejected.
- lr_schedule: adaptive with a pure-distillation phase warns.

Warm start
- a `separate: True` teacher keeps its critic in critic_mlp / critic_cnn; that
  trunk is now copied into the central value's single trunk. By name alone the
  teacher's value head ended up on its actor trunk (reported as fully copied).

state_aux
- built without `state_shape` (players, play scripts) the network has no head
  and loads a training checkpoint as the plain actor-critic; before, a
  state_aux model could not be played. A training run without the algo block
  is a clear error instead.
- `state_shape` is passed to the network only for state_aux, not for every
  central-value config.

Smaller
- masked logits use CategoricalMasked's finite fill, so a row without valid
  actions no longer breaks the teacher's sampler.
- relative teacher paths fall back to the repository root.
- ExperienceBuffer.has_central_value -> store_states; drop the unused
  BaseModelNetwork.get_aux_loss hook.

Tests: teacher rows and the actor loss (both action types), cached targets,
recurrent student, warm start from shared and separate teachers, state_aux
checkpoint through a head-less build, and each guard.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZnNwekkavvwMEKBnkA
…esults

- DISTILLATION.md: teacher rows and the actor loss, once-per-epoch teacher
  targets, warm start from a separate teacher, what continuous kl does to
  sigma, the limits checked at init, prior work (Kickstarting; Distilling
  Policy Distillation).
- Caveats on the reported comparisons, no numbers changed: the Panda teacher
  and the pixel arms run different task variants (playground's `vision` flag
  changes the success criterion and reward terms); only the distilled arms
  have the warm-started central value (and, on Panda, the fixed lr);
  Craftax-Classic's symbolic vector holds what the image shows, so that run
  is cross-modal, not privileged-information, distillation.
- PlaygroundVecEnv: the docstring no longer claims locomotion envs (their
  _get_obs returns a dict), which now fail with a clear message; the task
  difference between obs modes is documented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZnNwekkavvwMEKBnkA
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FabfZnNwekkavvwMEKBnkA
@Denys88

Denys88 commented Nov 23, 2026

Copy link
Copy Markdown
Owner Author

Thanks for the review. fd60326 and 8d717bd address most of it, CI green on 7c1c9a1 (master merged in).

Fixed: beta-mixed rows carry no actor loss (from_teacher), teacher targets once per epoch and out of the graph at coef 0, empty schedule keys raise, finite masked fill, multi-agent and Dict state spaces rejected at init, state_aux models playable (head-less build), state_shape only for state_aux, store_states rename, dead hook removed. Docs: citations, the privileged-critic confound, the Craftax cross-modal caveat, and a new one: the pixel arms run a different playground task variant than the state teacher. Also found while fixing warm start: a separate: True teacher's critic trunk was not being copied.

Still open: Craftax config is still adaptive (warning added, LR not yet checked), throughput numbers in the wrapper docstring vs the docs, the WSL preload in the module, the planning docs, an AMP test. The split into core / state_aux / env wrappers and pyproject extras for the env pins I will decide on before merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants