Skip to content

[Newton] Redesign Newton Manager [5/N] - #8927

Closed
StafaH wants to merge 12 commits into
isaac-sim:mainfrom
StafaH:newton/redesign-5-mask-resets-env
Closed

StafaH wants to merge 12 commits into
isaac-sim:mainfrom
StafaH:newton/redesign-5-mask-resets-env

Conversation

@StafaH

@StafaH StafaH commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Part 5 of the Newton manager redesign (overview).
Follows [4/N] #8926, now on main.

ManagerBasedRLEnv.step called nonzero() on reset_buf and on the command resampling timers every step, so
the host waited on the device twice per step. The step now resets on the reset mask every step and never compacts
it on the host.

Environment

  • The env owns one stable Warp mask of the environments reset within a step. _reset_mask(env_mask, env_ids=None)
    resets them; _reset_idx(env_ids) builds a mask and calls it with the indices.
  • Each manager reports takes_env_ids, whether one of its terms takes indices. A reset computes the indices at most
    once, only when a term needs them, and shares them with every index-based term; when they are empty the reset is
    skipped. With only mask terms, as in every built-in task, a reset never waits on the device.
  • Environments that override _reset_idx or have active recorder terms still receive indices (one sync).
  • Episode logs in extras["log"] stay device tensors and keep their last value on steps without a reset.
  • compute_final_obs=True computes the terminal observation every step instead of only on steps with a reset.

Managers and terms

  • Managers take env_mask next to env_ids and pass terms a ProxyArray mask. Event, command, curriculum and
    observation terms whose function, reset or _resample_command declares env_mask run on every reset or
    update and leave unselected environments unchanged. Terms that take env_ids keep working.
  • ManagerTermBase.reset takes only env_mask; ported terms no longer keep an env_ids fallback.
    CommandTerm.reset also takes the indices when the env already resolved them, so an index-based
    _resample_command reuses them. A full reset passes index-based terms the same selection as before (None for
    observation and action terms, slice(None) for the others). A curriculum modify_fn that takes env_mask runs on every update, so it must give the same result
    when called again; the docstring examples show both kinds.
  • SceneEntityCfg.finalize(device, scene) also builds joint_mask, fixed_tendon_mask and body_mask, so reset
    events select joints and bodies for the mask writers without allocating every step.
  • Interval timers and command resampling sample into preallocated buffers. MicroDuck commands resample from masks.
  • randomize_joint_parameters and randomize_fixed_tendon_parameters check when created that the configured limit
    ranges cannot put a lower limit above an upper one, instead of reading every sample on the host.
  • TerrainImporter.update_env_origins and the lift set_reset_state each have one mask implementation.
  • Breaking: built-in event, command, curriculum, action, observation and reward terms, the Newton event and
    task-space terms, and the task terms take env_mask instead of env_ids. CommandTerm._resample takes
    env_mask. SceneEntityCfg.finalize takes the scene. TerrainImporter.update_env_origins takes a Warp mask and
    moves for every environment.

Performance

RTX PRO 6000 Blackwell, main at 2742c2d5e. isaaclab benchmark runtime --task <task> --num_envs 4096 --num_steps 1000 --warmup_steps 100 --visualizer none physics=newton_mjwarp, mean of two alternating sequential
rounds (steps/s):

Task main this PR vs main
Cartpole 2.693M 3.174M +17.9%
Flat ANYmal-D 260.4k 279.8k +7.4%
Reach-Franka 969.3k 1.217M +25.5%

Step-time variance also drops (Cartpole std 1.29M on main, 0.12M here).

Host syncs inside env.step (200 steps at 256 envs, torch.cuda.set_sync_debug_mode("warn")): 0 on Cartpole,
Flat ANYmal-D, Reach-Franka and Reorient-Cube-Allegro, which resets environments during the run.

Not covered

  • Action terms still write through the deprecated set_joint_*_target_index, which LEAPP export intercepts; moving
    them to actuators.target_command needs LEAPP support first.
  • DifficultyScheduler reads its mean difficulty on the host every curriculum update (Lift-KukaAllegro), and the
    NIST curriculum compares it on the host.
  • The RTX re-render after a reset reads reset_buf.any() when RTX sensors render.
  • Task terms that still take env_ids (for example in Keyboard-SO101 and Stack-Cube) sync once per reset.
  • Reset events sample every environment and keep the selected ones, which allocates per event; Newton reset-mode
    randomization queues a model change every step.
  • Delay buffers and delayed actuators draw lags with the Torch RNG, which a fully captured env step cannot record;
    a per-environment Warp RNG is a follow-up.
  • PhysX *_mask writers still call nonzero().

Testing

Targeted tests pass, run file by file: event, observation, reward, recorder, termination, command and base managers, MDP events,
scene entity config, array utilities, root state events, event requirements, actions, camera image MDP, DiffIK
aliasing, Pink IK components, RL env reset dispatch, LEAPP export, Newton events, articulation, rigid object, cable and Newton actuators,
experimental frontend, and the lift, reorient, handover, microduck, DrLegs, Franka-Pour, shoelace, stack, UR10 and
curriculum task tests. Kit-only tests not run locally: PhysX and OV event, gain and material tests, test_modify_env_param_curr_term.py.

New tests cover the reset dispatch (indices computed once, only when a term or recorder needs them, empty resets
skipped), command terms resampling only the selected environments and reusing the resolved indices, and the
full-reset selection index-based observation terms receive at construction.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have added changelog fragments

@StafaH StafaH mentioned this pull request Nov 4, 2026
6 tasks done
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 4, 2026
@StafaH
StafaH force-pushed the newton/redesign-5-mask-resets-env branch 3 times, most recently from 7038a30 to f1d644b Compare November 10, 2026 04:57
@StafaH
StafaH marked this pull request as ready for review November 10, 2026 04:57
@StafaH
StafaH requested a review from a team November 10, 2026 04:57
@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5

[High impact] The change reaches the shared simulation step and many managers, task terms, and backends.

Fix the gear-assembly reset failure, missing Gaussian limit safeguard, and broken OV tests before merging.

Findings

  1. P1 Gear assembly cannot reset ▶
  2. P1 Random limits can cross ▶
  3. P1 OV event tests fail ▶

Summary

Moves environment resets, command resampling, and interval events to device masks.

  • Environment resets now use a reusable mask for selected environments.
  • Managers now pass masks to terms that can update selected environments directly.
  • Built-in and task terms now update selected environments from masks.
  • Assets and terrain now accept masks for selected environment updates.

Acknowledged exclusions from StafaH: host reads in DifficultyScheduler and remaining index-based task terms; Newton model-change notifications on every reset call; PhysX mask writers that still compact masks; and the intentionally index-based handover command. These were not reported.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Compute episode-end flags] --> B[Copy flags into stable mask]
  B --> C{Recorder or index reset override?}
  C -->|Yes| D[Build indices and call reset hook]
  C -->|No| E[Reset through mask]
  D --> E
  E --> F[Update curriculum and scene]
  F --> G[Run reset events and managers]
  G --> H[Update commands and interval events]
  H --> I[Compute next observations]
Loading

Reviews (1) · Last reviewed commit: "Resolve reset indices once and take only..." · Reviewed by Greptile

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isaac Lab Review Bot

Needs attention: Scope and over-engineering (4), Compatibility and deprecation (13), Implementation (4), Style consistency (2), Test quality (3). Other reviewed categories look good.

  • PR description: The diff includes Part 4 propagation beyond the title’s scope; clarify scope, qualify synchronization claims, and correct variance terminology, retaining measured comparisons while adding candidate revision and software environment for reproducibility.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: Minimal implementation: extend ManagerBasedEnv, ManagerBasedRLEnv, ManagerBase, InteractiveScene, and existing term owners; delete the per-reset entity tuple, reuse finalized joint masks and command scratch, and retain direct indexed writes instead of full-batch staging; essential flow remains mask dispatch, selective writes, and indexed compatibility; no source modules were added. Scope is cohesive; no split recommended.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: indexed term and lifecycle calls, positional SceneEntityCfg fields, finalize(device), scene extensions, terrain/reset-state writes, reset_to_target, goal counting, SurfaceGripper indices, and InteractiveSceneWarp paths lack functional warned bridges, migration/removal guidance, and transition coverage.
  • Implementation: EventManager.reset defaults env_ids to slice(None) even with a partial mask, resetting every environment in indexed class terms; default to None and derive indices from the mask.
  • Style consistency: New manager properties and private helpers violate the required member ordering, scattering interface definitions; place properties before public operations and private helpers afterward.
  • Test quality: Changed OV material and gravity tests pass Torch tensors where wrappers require ProxyArray masks, failing before backend assertions; supply the documented mask type.

Needs rework. Posted 26 inline findings.

The full PR diff was reviewed; some supplemental surrounding file context was omitted.

Automated review; human maintainers own approval decisions.

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Isaac Lab Review Bot

Needs attention: Design and architecture (1), Scope and over-engineering (4), Compatibility and deprecation (12), Implementation (6), Style consistency (1), Test quality (2). Other reviewed categories look good.

  • PR description: The diff includes Part 4 changes omitted from the body; disclose them, narrow sync and limit guarantees, and add the measured candidate revision and software environment to the otherwise useful throughput comparison.
  • Design and architecture: image_features hides its model callback’s index requirement behind a mask signature, causing independent compaction; expose that requirement and consume the environment’s shared indices.
  • Scope and over-engineering: Minimal implementation: Extend ManagerBasedEnv, ManagerBasedRLEnv, ManagerBase, InteractiveScene, and existing term owners; remove entity tuple packing, reuse sampling and joint-mask buffers, and preserve partial indexed state writes; no source modules were added; essential flow remains one mask and shared indices only when required. Suggested PR breakdown: (1) asset/scene resets, validated across backends; (2) manager dispatch and recorder lifecycle, validated at reset boundaries; (3) term migration and compatibility bridges, validated by focused task and transition tests.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: reset signatures, positional SceneEntityCfg fields, finalization, terrain updates, Warp scene imports, SurfaceGripper keywords, goal counting, and state writes lack complete deprecation bridges; preserve old behavior with warnings, migration/removal guidance, and transition coverage.
  • Implementation: EventManager.reset retains the default full slice alongside a partial mask, resetting every environment in index-based class terms; discard default indices and derive the mask’s selection.
  • Style consistency: The expanded array re-export exceeds the trusted stub guide’s 100-character limit; use a parenthesized multiline import.
  • Test quality: OV event tests pass Torch tensors or indices into ProxyArray dispatch and fail before backend assertions; finish caller migration while retaining distinct physical and backend coverage.

Needs rework. Posted 26 inline findings.

The full PR diff was reviewed; some supplemental surrounding file context was omitted.

Automated review; human maintainers own approval decisions.

@StafaH
StafaH force-pushed the newton/redesign-5-mask-resets-env branch 2 times, most recently from fb91c3e to 2f24183 Compare November 10, 2026 17:47

@maxkra15 maxkra15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two things still need fixing: legacy observation initialization and the remaining in-repo event callers. I also left a note about command resets compacting masks again after the env has already resolved the indices.

275 targeted checks passed. The existing CPU cable test fails, and separate before/after probes reproduce the observation failure and hidden command synchronization. A real Newton env with staggered resets ran 30 steps on CPU and CUDA, including sync-debug checks after warm-up on the mask-only path. Kit-only paths weren't run.

StafaH added a commit that referenced this pull request Nov 10, 2026
# Description

Part 4 of the Newton manager redesign
([overview](#8218 (comment))).
Builds on [2c-ii/N] #8870 (merged), which made the backend reset flags
mask-only. The env/MDP layer is [5/N] #8927.

Everything below the managers resets from a boolean device mask. A
masked reset changes only the selected
environments and does not synchronize the device, so [5/N] can reset on
the reset mask every step.

## Assets and scene

- `AssetBase.reset(env_ids=None, env_mask=None)` matches the sensor
signature on `main`. Every asset honors
`env_mask` (a `wp.bool` array of shape `(num_envs,)`), and it takes
precedence over `env_ids`.
- `InteractiveScene.reset(env_ids=None, env_mask=None)` passes both to
every asset and sensor.
- Fixed: on `main`, a reset with only `env_mask` reset the actuator
state of every environment (Newton, PhysX, OV
articulations), and the external wrenches of every environment (Newton
and PhysX rigid objects and collections).
- **Breaking:** `SurfaceGripper.reset` takes `env_ids` and `env_mask`
instead of `indices`.
- **Breaking:** `InteractiveSceneWarp` is removed. The base scene now
resets every entity from the mask, and the
  override passed indices to the sensors.

## Actuators

- `ActuatorBase.reset(env_ids=None, env_mask=None)`;
`ActuatorCollection.reset` forwards the mask to every group
  and to the backend-native actuators.
- `DelayedPDActuator` draws a delay for every environment and keeps the
selected ones; the actuator nets clear the
  masked history.
- `NewtonActuatorAdapter.reset(env_mask=...)` builds the per-DOF masks
of stateful actuators into preallocated
  arrays and skips stateless ones.
- Contrib `Thruster` and `Multirotor` resample and reset the masked
environments.

## Buffers and processors

- `DelayBuffer.reset` takes a boolean mask and redraws sampled lags with
`torch.where`.
- `TensorProcessor.reset`, `DigitalFilter`, `Integrator`, `NoiseModel`
and `NoiseModelWithAdditiveBias` take
  `env_mask`.
- Ray-caster drift resampling selects environments with the resolved
reset mask instead of `nonzero()`.

**Breaking:** custom subclasses of `AssetBase`, `ActuatorBase`,
`TensorProcessor` and `NoiseModel` must accept
`env_mask` and leave unselected environments unchanged.

## Testing

Targeted tests pass, run file by file: actuator collection and Newton
adapter (masked reset; the collection test
runs under `torch.cuda.set_sync_debug_mode("error")`), delay buffer,
tensor processors, noise, Newton
articulation, rigid object, cable, Newton actuators, Newton ray caster,
articulation and rigid object contracts
(`-k newton`), and the experimental frontend. Kit-only tests not run
locally: interactive scene, ray caster
sensor, sensor base, thruster, PhysX/OV assets.

## Checklist

- [x] I have read and understood the [contribution
guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html)
- [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with
`./isaaclab.sh --format`
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have added changelog fragments
ManagerBasedRLEnv.step compacted reset_buf and the command resampling
timers into indices with nonzero() every step, which waited on the
device. The step now resets on the reset mask every step, the env owns
one stable Warp mask, and managers pass it to terms as a ProxyArray.
Built-in and task event, command, curriculum, action, observation and
reward terms take env_mask and leave unselected environments unchanged.

Terms that still take env_ids keep working through
env_selection_kwargs, which hands them indices and skips the call when
none are selected. Episode logs stay on the device and keep their last
value on steps without a reset.
@StafaH
StafaH force-pushed the newton/redesign-5-mask-resets-env branch from 2f24183 to 42595ed Compare November 10, 2026 22:47
@StafaH
StafaH requested a review from maxkra15 November 10, 2026 22:47

@AntoineRichard AntoineRichard 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.

Review findings covering observation state, empty camera resets, direct event selection, and Newton IK root-frame validation.

# note: the reset runs every step on the reset mask, so the step never waits on the device
if self.cfg.compute_final_obs:
# expose the terminal observation before reset for Same-Step autoreset
self.extras["final_obs"] = self.observation_manager.compute()

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.

[P1] Avoid advancing stateful observations twice per environment step

With compute_final_obs=True, this now calls ObservationManager.compute() on every nonterminal step, followed by the normal observation computation at line 275. The default update_history=False only suppresses delay/history updates; stateful observation terms and tensor processors still execute and mutate their state. Integrators and digital filters therefore advance twice per environment step, including in TorchRL, which enables this flag.

A CPU reproduction using the real ObservationManager and IntegratorCfg(dt=1) with constant input returns 0.5 for one normal update, versus 1.5 after this extra read and an empty reset. Please make terminal observation reads non-mutating, or reuse computation while ensuring each stateful term and processor advances only once per environment step.

self.curriculum_manager.compute(env_ids=env_ids, env_mask=env_mask)
# reset the internal buffers of the scene elements
self.scene.reset(env_ids)
self.scene.reset(env_mask=env_mask.warp)

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.

[P2] Preserve camera lifecycle state for an empty reset mask

In mask-only environments this runs on ordinary steps with an all-false mask, but Camera.reset() does not treat that selection as a no-op: it unconditionally calls the renderer reset hook, and global cameras discard the mask and reset their entire state. Global cameras consequently reset their clocks and become outdated on every nonterminal step, bypassing update_period. Asynchronous OVRTX cameras also discard their pending rendering pipeline on every empty reset.

A CPU reproduction executing the actual reset methods and Warp reset kernel changes a global camera timestamp from 5 to 0, marks it outdated, and calls renderer.reset(..., None) for an all-false mask. Please ensure empty selections preserve camera timing and renderer lifecycle state before resetting the scene unconditionally.

# set into the physics simulation
asset.write_joint_position_to_sim_index(position=joint_pos, joint_ids=asset_cfg.joint_ids, env_ids=env_ids)
asset.write_joint_velocity_to_sim_index(velocity=joint_vel, joint_ids=asset_cfg.joint_ids, env_ids=env_ids)
joint_mask = asset_cfg.joint_mask

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.

[P2] Preserve explicit joint selections in direct event calls

asset_cfg.joint_mask defaults to None, which the mask writers interpret as every joint. Previously, direct callers could pass SceneEntityCfg("robot", joint_ids=[0]) without finalizing it. After migrating only the environment selector to env_mask, that same call now silently resets all joints because the explicit joint_ids selection is no longer consulted here.

A CPU reproduction comparing the actual baseline and head functions starts from [[10,20,30]] and applies a deterministic +1 reset to joint 0: baseline yields [[1,20,30]], head yields [[1,1,1]], and additionally resolving/finalizing the configuration restores the intended result. Please preserve explicit selections for direct callers, or reject unfinalized subsets clearly and document the additional migration requirement.

# Each pose objective maps its action slice to a prototype-world target,
# written straight into its Warp target arrays.
self._validate_matching_root_orientations()
if not self._root_orientations_validated:

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.

[P2] Revalidate the IK root-frame invariant after root changes

This caches successful validation forever, but later resets can change fixed-base root orientations through the supported root-pose writers. The solver's prototype model remains the one finalized at construction. After the first valid step, rotating only environment 0's root and end effector by 90 degrees is now accepted; the baseline raises on the next process_actions() call.

A CPU reproduction using the actual base/head process_actions() methods and the head target kernel produces approximately [0,1,0] for a zero-displacement target whose unchanged prototype end-effector position is [1,0,0]. Please preserve validation when roots change, or explicitly maintain and enforce an immutable prototype frame, so the optimization cannot silently generate targets in a mismatched frame.

@maxkra15 maxkra15 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

reproduced Antoine's stateful-observation issue (0.5 for one update versus 1.5 with the extra terminal read), the empty-mask global-camera reset and the stale IK root-frame validation. Found one more MicroDuck synchronization issue below

return
def _resample_command(self, env_mask: ProxyArray):
# Read the bounds on every resample: the curriculum widens the head-pose ranges during training.
low, high = torch.tensor(self.cfg.ranges, device=self.device).unbind(-1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we cache these bounds on the device and refresh them only when the curriculum changes the ranges? This now runs even for an empty reset mask. With the real UniformPoseDeltaCommand in a CommandManager, a warmed empty reset raises called a synchronizing CUDA operation under sync-debug mode at this torch.tensor upload. Both MicroDuck head and body pose commands use it.

Caching the bounds removes that sync while still picking up changed curriculum ranges; I checked both an empty reset and a selected reset after changing the ranges. The old index-based path skipped this upload when nothing was selected.

self.recorder_manager.record_pre_reset(env_ids)
self._reset_idx(env_ids)
else:
self._reset_mask(env_mask)

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.

On PhysX every step now runs torch.nonzero once per mask writer (Cartpole: 1 sync per step to 4), and on steps without resets the root writers pass a zero-length index array to the tensor API (L565), which main never did. Could you A/B Isaac-Cartpole with physics=isaacsim_physx against main before merge?

ranges could not sample a lower limit above an upper limit, and to clamp each sampled lower limit to its upper
limit on the device, instead of reading every sample on the host.
* Changed :func:`~isaaclab.utils.dict.class_to_dict` to keep Warp arrays as they are, like Torch tensors.
* **Breaking:** Built-in event, command, curriculum, action, observation and reward terms took ``env_mask``, 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.

Dropping env_ids from the built-in terms breaks existing callers on upgrade; this needs a deprecation and migration path before merge, which the contribution guide requires for public API removals.

@maxkra15 maxkra15 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The reset docs give the mask precedence when both selectors are supplied, but index-based terms still use env_ids. Can we make them agree so one reset can’t update two different sets of environments?

@StafaH

StafaH commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: we're focusing on MDP2 and leaving the manager-based environments as they are, so the env_ids to env_mask API changes here won't land. The one change MDP2 needs, reading the MJWarp update_data_interval from the solver configuration on resets, moved to #9016.

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

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants