Repository navigation
Conversation
…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
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
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
a258452 to
ea5d630
Compare
…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
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
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
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL
…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
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>
ViktorM
left a comment
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
β-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
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Fixed in fd60326: a schedule key that is present but empty raises, and malformed schedules (bool, wrong shape) are rejected.
| 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, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| 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, |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
WSL-specific; it belongs in the scripts or the docs rather than the library module.
Generated by Claude Code
There was a problem hiding this comment.
Still in the module for now; will move it to the scripts.
| 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** |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| ## 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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Agreed, documented in 8d717bd: Craftax-Classic is cross-modal distillation, no imitation gap by construction, single seed, teacher frames not counted.
| |---|---|---|---| | ||
| | 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 | |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Agent planning notes, like the spec under docs/superpowers/specs/. Drop both from the PR?
Generated by Claude Code
There was a problem hiding this comment.
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
|
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 ( Still open: Craftax config is still |
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.pydistillationblock in the algo config:teacher_config,teacher_checkpoint,loss(discrete KL; continuous KL or MSE, withteacher_mu_clipto 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).statesstored and passed into minibatches whenever distillation is on; action mixing inget_action_values;loss = ppo_coef·ppo + coef·distillincalc_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,CraftaxObserverlogs Crafter score.PlaygroundVecEnv(playground): any mujoco_playground env,obs: state | pixels | bothvia 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)
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 WSL2LD_LIBRARY_PATH=/usr/lib/wsl/lib).🤖 Generated with Claude Code
https://claude.ai/code/session_014VbqfktSeifgwrzHd8w1dL