Skip to content

[Algorithm] HIL-SERL in simulation - #4774

Open
theap06 wants to merge 34 commits into
pytorch:mainfrom
theap06:pr/hil-serl-recipe
Open

theap06 wants to merge 34 commits into
pytorch:mainfrom
theap06:pr/hil-serl-recipe

Conversation

@theap06

@theap06 theap06 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds sota-implementations/hil_serl/, HIL-SERL (arXiv 2410.21845) in simulation: SAC on robosuite Lift with robomimic demos, a scripted human that takes over through InterventionModule, 50/50 demo and online batches from ReplayBufferEnsemble, and a reward from the simulator's success flag or a trained success classifier, with the paper's loop of retraining the classifier on its false positives. The README lists the expected results (77% success with the simulator reward, 34% with the classifier after three retraining rounds, 10 seeds each) and the recipe has a sota-check script and a CI smoke entry.

Motivation and Context

This adds a human-in-the-loop recipe built from stock TorchRL components; it is stacked on the four PRs below, so only the commits touching sota-implementations/hil_serl/ and the SOTA CI files are new here.

Stack (merge in this order; #4771, #4772, #4773 and #4799 are independent of each other and each is based on main, #4774 needs all four):

  1. [BugFix] Run ModuleTransform on reset when it declares observations #4771 [BugFix] Run ModuleTransform on reset when it declares observations
  2. [Feature] InterventionModule for human or scripted takeovers #4772 [Feature] InterventionModule for human or scripted takeovers
  3. [Feature] Mixed-source replay with ReplayBufferEnsemble #4773 [Feature] Mixed-source replay with ReplayBufferEnsemble
  4. [Feature] SACLoss backup_entropy option #4799 [Feature] SACLoss backup_entropy option
  5. [Algorithm] HIL-SERL in simulation #4774 [Algorithm] HIL-SERL in simulation (this PR)
  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • Example (update in the folder of examples)

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

Makes ReplayBufferEnsemble usable for RLPD, offline-to-online and HIL-SERL
style training, where each batch mixes data from several sources. Every new
behavior is opt-in and the defaults are unchanged.

- Mixed member samplers: a prioritized member next to a uniform member no
  longer crashes when infos are stacked. Uniform rows get priority_weight 1.
  Any other info key missing from some members raises a KeyError naming the
  key, and members with different index layouts raise a clear ValueError.
- Routed priority updates: update_priority and update_tensordict_priority
  send each row to the member it came from, with member-local indices.
- Exact quotas: fractions=[...] gives every batch the same per-member counts
  (largest-remainder rounding) and a flat [batch_size] batch ordered by
  member. With slice samplers the counts are in slices. A member that cannot
  serve its share blocks sampling instead of passing it on. fractions is
  settable between batches, saved in state_dict, kept (renormalized) by
  rb[...] sub-ensembles, and exposed on SamplerEnsembleConfig.
- Multi-membership writes: routing_mode="mask" writes a record to every
  member marked in a boolean mask and returns [N, num_members] addresses
  with a present mask. update_if_present and update_priority skip absent
  copies, and a per-record patch reaches every copy. The mask is not stored.
- Performance: ReplayBuffer.sample counted items with torch.as_tensor on the
  ensemble's index tensordict, which walks it row by row (the change
  proposed in pytorch#4720). Flat sampling, mask writes and priority updates avoid
  per-row work. Adds test_mixed_source_replay_buffer, which compares the
  ensemble against equivalent hand-wired code.

CPU, batch 256, 1k-frame writes, median us (ensemble vs hand-wired):
sample 585 vs 517, extend 778 vs 620, priority update 197 vs 168.
A ModuleTransform with observation_spec_transform adds observations to the
spec but only ran after steps, so reset outputs lacked them: check_env_specs
failed and collectors could not stack the first step with the rest. With
observation_spec_transform set, the module now also runs at reset.
Transforms without it are unchanged.
A post-policy module, composed as TensorDictSequential(actor,
InterventionModule(intervener)) like EGreedyModule. The intervener runs on
every exploration step and proposes an action plus a take-over flag. Where
the flag is set the intervener's action is executed (optionally clipped to a
spec); elsewhere the policy's action is used unchanged. The policy's action
and the flag are saved so replay can route intervened steps. In
deterministic mode the intervener is not called. Used by HIL-SERL
(arXiv 2410.21845).
SAC on robosuite Lift with demos, scripted takeovers and a learned success
reward, following HIL-SERL (arXiv 2410.21845).

- A stall-triggered scripted controller plays the human through
  InterventionModule; takeovers last at most 30 steps.
- A ReplayBufferEnsemble holds a demo and an online buffer, with exact
  50/50 batches; intervened steps are written to both (routing_mode="mask").
- The reward and episode end come from the simulator's success or from a
  success classifier (train_reward_classifier.py: 200 successes, 1000
  failures, held-out error rates saved with the model).
- train_reward_classifier.py can also train on recorded human demos
  (robomimic proficient and multi-human Lift), as the paper's classifier
  does.
- robomimic Lift demos with an observation alignment check, or scripted
  demos when no file is given (used by the CI smoke test).
- SAC settings from the authors' code (two critic updates per actor update,
  discount 0.97), 10 critics and a 4-D position plus gripper action. With 2 critics the critic diverges once
  the scripted human takes over often; 10 critics reach about 70% oracle
  success at 40k steps over 5 seeds.
- Throughput options: soft simulator resets (1 ms instead of 755 ms per
  reset), replay prefetch, and an optional asynchronous collector that
  steps the simulator in a separate process, as in HIL-SERL.
- sota-check script, CI smoke test entry and environment updates.

Depends on the ReplayBufferEnsemble, ModuleTransform and InterventionModule
changes earlier in this branch.
intervention.reaction_delay makes the scripted human take over that many
steps after it notices a stall or the gripper leaving the workspace, so
experiments can use a slower, less perfect helper. The default of 0 keeps the
previous behavior; checked step by step against the old intervener on random
trajectories.
…hares

Extends test_mixed_source_replay_buffer to every pair of uniform and
prioritized members and to 10% or 100% of rows routed to both members. The
hand-wired baseline now does the same work as the ensemble: writes return the
write generation of every copy, and sampled batches carry each row's member,
index and write generation, which routed write-back needs.

CPU (Mac, under load), ensemble time over hand-wired time:
sample 0.86 to 0.98, priority update 1.00 to 1.11, extend 1.09 to 1.17 with
10% shared rows and 0.85 to 0.87 with 100% shared rows.
The recipe's default device is MPS on a Mac, and the smoke run crashes inside
Metal there; network.device=cpu runs it.
@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4774

Note: Links to docs will display an error until the docs builds have been completed.

❌ 3 New Failures

As of commit 9940403 with merge base df1db3d (image):

NEW FAILURES - The following jobs have failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@theap06 theap06 added the ci/optdeps Run the full tests-optdeps suite on this PR label Nov 23, 2026
@github-actions github-actions Bot added Documentation Improvements or additions to documentation CI Has to do with CI setup (e.g. wheels & builds, tests...) Benchmarks rl/benchmark changes sota-implementations/ ReplayBuffers Modules Transforms Trainers Integrations/torch_geometric Integrations new algo New algorithm request or PR labels Nov 23, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 23, 2026
A module that reads a key only present after a step, such as reward, now
keeps the previous behavior and runs only after steps, instead of raising a
KeyError at reset.
…policy dtype

Without this, removing the dtype cast passed every InterventionModule test.
update_priority with a plain tensor index goes to the ensemble's sampler as
it did before, instead of raising a TypeError. Class-level defaults for
routing_mode and the sampler's fractions let whole-object pickles saved
before this change load, sample and extend.
The classifier's synthetic rollouts followed the training env, so position-only
actions, soft resets and shorter episodes changed its data: held-out false
successes rose from under 1% to 3.5 to 7%. classifier.collect_env and
classifier.episode_steps now fix that setup (full-pose controller, hard
resets, 100 steps); with the defaults the held-out rates are back to 0.3%
false successes and 11.9% missed successes on 5,000 states.
Adds backup_entropy to SACLoss, DiscreteSACLoss and SACLossConfig. When
False, the critic target uses only the smallest next-state Q value, as in
the SERL and HIL-SERL reference code. Defaults to True, so existing
behavior is unchanged.
…rget

Sets optim.backup_entropy to false, matching the reference HIL-SERL code.
With the entropy term in the target, 13 of 14 oracle-reward runs collapsed
late in training, against 1 of 10 without it.
Split flat batches by the sampled member ids instead of recomputing the
quotas, so a fractions change during prefetch cannot mislabel rows, and
take the replay lock in the fractions setter. dumps and loads now keep
fractions, non-strict slice samplers are rejected with fractions,
samples_returned counts records for multi-dim members, and mask-mode
update_priority accepts one priority per record.
…iction

Each replay member samples with its own seeded generator, on the device its
sampler draws on, so runs repeat with prefetch on. Prefetch is turned off on
MPS, where sampling from the prefetch thread aborts the process. In
classifier mode, eval_predicted_success now reports the classifier's verdict
instead of the simulator's.
…ccess

reward.end_episode_on_success=false lets episodes run to env.max_steps
and marks successful steps terminal only in the stored data, so a false
success from the classifier does not cut the episode short.
…efault

Over 10 seeds with the true reward, env.hard_reset=true scored 67% vs
56% final and never collapsed (2 of 10 runs did without it), for about
20% more wall time. It is also robosuite's own default.
hil_serl.py saves the states where the classifier claimed a success that
did not happen (reward.false_positives_out), and train_reward_classifier.py
adds saved states to the classifier's failures (classifier.extra_negatives).
Alternating the two for a few rounds is how HIL-SERL fixes a classifier the
policy has learned to exploit.
…logger

The SOTA smoke job installs its dependencies from run_all.sh, which did not list robosuite or h5py. It also runs every recipe with logger.backend= , so the recipe now skips logging when there is no logger.
Groups the README into how it works, setup, running, the learned reward and expected results, names the config keys behind each setting, and notes that training on MPS learns much worse.
The alignment check now reads the demos in the order they are loaded (demo_10 after demo_9, not after demo_1). The simulated human rebuilds its state when the device changes. train_predicted_success reads the reward, so it is right when episodes do not end on success. A run that fails before collecting anything no longer hides its error behind the false-positive save. The smoke test passes logger.backend= like the other recipes, and make_loss says why it reads target_entropy.
Running the module at reset wrote every output into the reset data, so a module that also writes a reward or done entry put a reward computed from the reset observation at the root. At reset the module now reads only its inputs and only its non-reward, non-done outputs are written back.

(cherry picked from commit 481e2f2)
…one flag per action

The intervener's outputs were listed in out_keys but are not written in deterministic mode, so a strict select of the policy's outputs failed during evaluation. The take-over flag was also reshaped to the tensordict's batch size, which broke actions with extra leading dims such as one action per agent; it now follows the action's shape.

(cherry picked from commit 4a74112)
…e them unset too

Assigning fractions after construction skipped the check that they cannot be combined with p, sample_from_all or num_buffer_sampled, which were then silently ignored; the setter now raises like the constructor. Checkpoints only stored fractions when set, so loading one saved without them kept the fractions already on the buffer; the current value is now always saved, None included. The docstrings also say a tensor is accepted.

(cherry picked from commit 6fbcd2d)
robosuite depends on opencv-python, whose GUI build needs libgthread-2.0,
which the SOTA image does not have. Every recipe importing cv2 then failed,
hil_serl included. Swap it for opencv-python-headless after the installs.
With robosuite installed, vla_grpo asks EGL how many devices exist and maps
a render GPU outside that range to device 0. The single-GPU SOTA runner has
one EGL device, so the requested GPU 3 became 0 and the test failed. The
test checks worker assignment, so it now runs with the device count unknown.
train_reward_classifier.py now seeds the environments it collects from, so
classifier.seed makes the dataset reproducible, with separate seeds for the
training and held-out sets. States from episodes that never succeed no longer
count as near misses.
Priority updates now hold the ensemble's locks, so they cannot run while a
prefetched sample reads the same priority trees. Samples drawn with fractions
are pinned when pin_memory=True. Fractions are renormalized so large batches
always get counts that add up to the batch size. update_priority skips members
without a prioritized sampler, as documented.
Removes optim.bc_weight, intervention.reaction_delay,
reward.end_episode_on_success and replay.demo_prioritized (with alpha and
beta). None was on by default or shown to help. The false-positive file is
no longer written when there are none, the classifier report keeps the
extra negatives under train and writes null instead of NaN for an empty
class, and the README states what the recipe was validated on and how demos
and seeds affect the results.
… on the policy's device

The flag's batch shape is now the action's shape without its event dimension
only when the action has one, so a discrete action of shape [B] works in both
exploration and evaluation. The take-over flag is moved to the policy action's
device, the saved policy action is a copy in deterministic mode, and the
docstring says which exploration types call the intervener.
The reset filter used the parent env's reward and done keys, so a reward key
added by the transform's own reward_spec_transform was still written at reset,
and inside a RayModuleTransform actor, which has no parent, every output was.
Reset now writes only the outputs present in the transformed observation spec,
and nothing when there is no parent env.
@theap06
theap06 marked this pull request as ready for review November 29, 2026 09:13

This branch has not been deployed

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

Labels

Benchmarks rl/benchmark changes ci/optdeps Run the full tests-optdeps suite on this PR CI Has to do with CI setup (e.g. wheels & builds, tests...) CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Documentation Improvements or additions to documentation Integrations/torch_geometric Integrations Modules new algo New algorithm request or PR Objectives ReplayBuffers sota-implementations/ Trainers Transforms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant