Skip to content

Fix pre-reset final observations for history, delay and stateful terms - #8868

Open
rafaelcathomen wants to merge 11 commits into
isaac-sim:mainfrom
rafaelcathomen:review/final-obs-preview
Open

rafaelcathomen wants to merge 11 commits into
isaac-sim:mainfrom
rafaelcathomen:review/final-obs-preview

Conversation

@rafaelcathomen

@rafaelcathomen rafaelcathomen commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

compute_final_obs previously omitted the current history or delay sample, or advanced stateful observation processing a second time before autoreset. This PR previews the current successor before an automatic reset, command update, or interval event and returns a snapshot with its own storage. A step without automatic reset clears the previous final_obs entry.

Manager-based previews preserve built-in history, delays, processors, and camera frame stacks. Nested manager reads share the same preview scope. Direct and multi-agent tasks expose env.is_observation_preview so stateful task hooks can return prospective values without advancing their state. Existing environment adapters without that flag continue to use the regular camera observation path. Custom ObservationManager.compute overrides must accept and forward preview=False, and custom stateful tensor processors must override preview. Additional reads from active recorder terms are outside this state-preservation guarantee. Warp terminal capture remains unsupported.

Disabling compute_final_obs skips the extra preview.

Part of #8863.

Validation

  • 166 focused cases passed, including the seven Leapp and Lift cases that had failed in CI. Three CUDA-only cases were skipped.
  • Repository formatting, lint, and changelog checks passed.
  • A clean Sphinx HTML build passed with warnings treated as errors.

Type of change

  • Bug fix

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with uv run isaaclab --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

Signed-off-by: Rafael Cathomen <rcathomen@nvidia.com>
@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Oct 28, 2026
Signed-off-by: Rafael Cathomen <rcathomen@nvidia.com>
Signed-off-by: Rafael Cathomen <rcathomen@nvidia.com>
@AntoineRichard
AntoineRichard marked this pull request as ready for review November 9, 2026 22:15
@AntoineRichard
AntoineRichard requested a review from a team November 9, 2026 22:15

@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 (5), Compatibility and deprecation (1), Implementation (1), Style consistency (2), Test quality (3). Other reviewed categories look good.

  • PR description: Correct size figures, qualify read-only/disabled claims, acknowledge Warp warnings, and report validation; benchmark reset-heavy previews using baseline/candidate revisions, command, hardware, backend, environment count, environment, warmup, latency, and peak memory.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: Minimal implementation: Extend ObservationManager, CircularBuffer, DelayBuffer, CameraFrameStack, tensor processors, existing environments, and task hooks; no source modules were added. Collapse duplicate preview flags, inline the manager capture delegate, remove redundant preview allocations, and exclude the unrelated math tolerance edit. Keep prospective reads followed by one pre-reset capture. Replace with one smaller PR: these existing source files, configuration documentation, changelogs, and focused buffer, processor, environment-step, and task validation.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: manual UI resets now trigger configured RTX reset rerenders even with compute_final_obs disabled; preserve the previous manual-only rendering behavior.
  • Implementation: Shadow Hand previews still overwrite live embedding caches; retain prospective embeddings locally and update task caches only during ordinary reads.
  • Style consistency: Direct configuration docstrings advertise manager-owned guarantees their hooks do not implement; document actual direct-task preview obligations.
  • Test quality: The step matrix lacks record_post_step for manager rows and cfg.possible_agents for MARL rows, failing before assertions; complete those doubles and consolidate duplicate capture and cleanup coverage.

Significant concerns. Posted 12 inline findings.

Automated review; human maintainers own approval decisions.

self.reward_buf = self._get_rewards()

# Include UI-requested boundaries in the same pre-reset capture and reset pass.
if self.sim.consume_reset_request():

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.

🟡 Warning · Compatibility — Preserve manual-reset rendering behavior

Putting UI resets through the automatic reset pass also runs configured RTX reset rerenders for them, including when compute_final_obs=False; the previous manual path did not. Keep capture unified without rerendering manual-only resets.

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.

Duplicate finding; see the detailed response. Configured UI-reset rerenders were retained and explicitly documented.

Currently consumed by the :class:`~isaaclab_rl.sb3.Sb3VecEnvWrapper` wrapper.
"""Whether to preview terminal observations before Same-Step autoreset. Defaults to False.

When any environment terminates, times out or is manually reset, capture every observation

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.

🟡 Warning · Style Consistency — Describe direct preview behavior accurately

The direct and MARL config docstrings copy manager-specific guarantees about command updates, recorders, delay buffers, and tensor processors. Their hooks do not provide those guarantees; document their actual preview obligations.

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.

Duplicate finding; see the detailed response. The DirectRL/MARL preview documentation was corrected in 198cb51.


return self.obs_buf, self.reward_buf, self.reset_terminated, self.reset_time_outs, self.extras

def _capture_final_obs(self) -> None:

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.

🟡 Warning · Scope Complexity — Inline the forwarding capture method

_capture_final_obs only assigns one manager call, adding a private entry point used otherwise by tests. Inline it in step and keep capture validation at the step boundary.

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.

Duplicate finding; see the detailed response. The manager forwarding helper was inlined in 198cb51.

Raises:
ValueError: If input ``group_name`` is not a valid group handled by the manager.
"""
preview = self._is_preview

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.

🟡 Warning · Scope Complexity — Keep one preview-mode owner

compute maintains manager and environment preview flags for the same lifecycle, while terms and compute_group read different flags. Use the environment signal for both and remove _is_preview synchronization.

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.

Duplicate finding; see the detailed response. The duplicate manager flag was removed, and nested calls now share the environment preview scope.

data = data.to(dtype=self._buffer.dtype)
history = torch.cat((self.buffer[:, 1:], data.unsqueeze(1)), dim=1)
fresh = (self._num_pushes == 0).view(self.batch_size, *([1] * data.ndim))
return torch.where(fresh, data.unsqueeze(1), history)

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.

🟡 Warning · Scope Complexity — Reuse allocated prospective history

torch.cat allocates an owned full history, then torch.where allocates another for fresh rows on every preview. Fill the existing history in place and return it.

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.

Duplicate finding; see the detailed response. The allocation optimization is deferred to preserve the existing autograd behavior.

group = ObservationGroupCfg()
group.value = ObservationTermCfg(func=managed_observe)
env.observation_manager = ObservationManager({"policy": group}, env)
env.recorder_manager = SimpleNamespace(

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.

🟡 Warning · Test Quality — Complete the step-test doubles

Manager rows lack record_post_step; MARL rows lack cfg.possible_agents. Both fail before the terminal-observation assertions. Supply the required members so every parametrized row tests its intended boundary.

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.

Duplicate finding; see the detailed response. Both fixture members were supplied in 78b2e1d; the lifecycle cases pass.

ObservationManager({"policy": cfg}, setup_env)


@pytest.mark.parametrize("capture_final_obs", [False, True], ids=["direct", "final_obs"])

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.

🟡 Warning · Test Quality — Remove the duplicate capture row

The final_obs parameter repeats manager preview through a one-line delegate; the environment step test covers capture dispatch. Retain the direct row's state and cache assertions once.

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.

Duplicate finding; see the detailed response. The duplicate capture axis was removed and its checks folded into existing owner coverage.

Comment thread source/isaaclab/test/utils/test_math.py Outdated
t02_compare, q02_compare = math_utils.combine_frame_transforms(t01, q01, t12_value, q12_value)

torch.testing.assert_close(t02_expected, t02_compare, atol=1e-3, rtol=1e-4)
torch.testing.assert_close(t02_expected, t02_compare, atol=2e-3, rtol=1e-4)

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.

🟡 Warning · Scope Complexity — Separate the numerical tolerance fix

Relaxing a frame-transform assertion is independent of terminal observations and changes a separate test contract. Revert it here and submit its supplied flake evidence with a focused test-only fix.

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.

Duplicate finding; see the detailed response. The unrelated tolerance change was reverted in 78b2e1d and removed from the PR description.

(N, 27).
"""
if self.cfg.write_image_to_file:
if self.cfg.write_image_to_file and not preview:

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.

🟡 Warning · Style Consistency — Qualify the image-saving guarantee

The adjacent public docstring says image saving always runs first, but this branch skips it during preview. Limit that statement to ordinary calls.

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.

Duplicate finding; see the detailed response. The image-saving statement now applies explicitly to ordinary calls.

pose_loss, embeddings = self.feature_extractor.step(
self._tiled_camera.data.output,
object_pose,
preview=self.is_observation_preview,

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.

🟡 Warning · Implementation — Keep preview embeddings local

This preview call still reaches the assignment to self.embeddings; the manager-based term likewise replaces its environment embedding cache. Terminal reads change live task state. Assign those caches only on ordinary reads.

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.

Kept these assignments intentionally. Both caches pass the current policy embedding to the critic during the same observation computation. Skipping the assignments during preview would give the terminal critic stale embeddings. A focused check with the actual task/feature-extractor methods confirmed that the terminal critic receives the current embedding and the next ordinary read matches the no-preview result. These are computation caches rather than temporal history.

@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 (3), Compatibility and deprecation (2), Implementation (1), Style consistency (5), Test quality (4). Other reviewed categories look good.

  • PR description: Qualify read-only and flag-off claims, update size and validation, and measure terminal camera throughput/memory against baseline with revisions, command, hardware, backend, environment count and warmup.
  • Design and architecture: Separate manager and environment flags give preview state two owners; pass preview explicitly to compute_group and retain one environment signal.
  • Scope and over-engineering: Minimal implementation: Extend existing environment steps, ObservationManager, CircularBuffer, DelayBuffer, CameraFrameStack, processors and task terms; no source modules were added. Delete the forwarding manager capture helper and redundant preview allocations, and exclude the unrelated math tolerance edit. Replace with one smaller PR: retain these existing envs, managers, utils and task files with focused owner and step-boundary validation.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: terminal capture rejects existing compute overrides without preview support, and manual-only resets gain RTX rerenders; preserve override compatibility through deprecation and retain the previous rendering condition.
  • Implementation: Non-deferred camera previews clone an already owned stack; return the prospective result directly to avoid another full-stack copy.
  • Style consistency: Direct configuration docstrings promise manager-owned command and history behavior absent from those workflows; document task-managed previews and interval-event ordering instead.
  • Test quality: Manager step rows lack record_post_step and MARL rows lack cfg.possible_agents, preventing terminal assertions; complete the fixtures before retaining this regression coverage.

Significant concerns. Posted 16 inline findings.

Automated review; human maintainers own approval decisions.

"""Whether to preview terminal observations before Same-Step autoreset. Defaults to False.

When any environment terminates, times out or is manually reset, capture every observation
group once before reset, command updates and interval events in ``extras["final_obs"]``.

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.

🟡 Warning · Style Consistency — Document direct preview behavior accurately

Direct step has no command-manager update or managed delay/history pipeline. This copied guarantee also appears in DirectMARLEnvCfg. Describe task-managed previews, resets and interval events instead.

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.

Addressed in 198cb51ce5. The DirectRL and MARL docs now describe task-owned observation state and the is_observation_preview obligation, without promising manager-owned command updates, buffers, processors, or recorder behavior.

self.recorder_manager.record_post_step()

# Consume UI resets before capture, so every boundary has a pre-reset observation.
if self.sim.consume_reset_request():

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.

🟡 Warning · Compatibility — Avoid new manual reset renders

Manual-only resets now enter the RTX rerender branch, including when compute_final_obs is false; the direct environment changes likewise. Preserve the prior rendering condition unless this behavior receives a transition.

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 behavior change is real, but the configured rerenders are intentional: num_rerenders_on_reset already promises sensor refresh after each reset. The old manual path left camera observations stale. We kept the unified reset pass and documented manual/UI rerenders, including when compute_final_obs is disabled, in the config, changelog, and PR description.


return self.obs_buf, self.reward_buf, self.reset_terminated, self.reset_time_outs, self.extras

def _capture_final_obs(self) -> None:

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.

🟡 Warning · Scope Complexity — Inline the forwarding capture method

_capture_final_obs makes one assignment for one production caller and owns no separate behavior. Inline it in step and test capture at the step boundary.

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.

Addressed in 198cb51ce5. The one-line manager capture helper is inlined into step; the camera manager test calls compute(preview=True) directly. Existing lifecycle tests own capture routing. The substantive DirectRL/MARL capture helpers remain.


def _capture_final_obs(self) -> None:
"""Capture owned observations before reset, command updates and interval events."""
self.extras["final_obs"] = self.observation_manager.compute(preview=True)

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.

🟡 Warning · Compatibility — Preserve compute overrides during transition

A compute(update_history=False) override previously handled terminal capture; passing preview=True now raises TypeError. Keep the old override functional and provide the prescribed warning, migration guidance and old/new-path validation.

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.

Added migration guidance in 198cb51ce5: custom ObservationManager.compute overrides must accept and forward keyword-only preview=False. No affected stable-manager override was found in the repository. We did not add a fallback to ordinary compute, since that could silently advance state and restore the incorrect terminal-observation behavior this PR fixes.

if preview and update_history:
raise ValueError("An observation preview cannot also update history")
was_preview = self._is_preview
self._is_preview = preview

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.

🟡 Warning · Design Architecture — Use one preview state owner

compute_group reads the manager flag while terms read the environment flag. Nested or direct reads can disagree. Pass preview explicitly to compute_group and retain one term-facing environment signal.

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.

Addressed in 198cb51ce5 with one environment-owned preview scope. Nested compute() and compute_group() calls inherit it, preserve the committed cache, and reject history updates while previewing. No compute_group parameter was added. The existing two processor cases now exercise both nested entry points; both failed before the fix and pass afterward, without adding cases.


def test_preview_includes_current_frame_without_advancing_delay_or_history():
"""Terminal observations include the successor while live episode history advances once."""
import copy

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.

🟡 Warning · Style Consistency — Move ordinary test imports up

The new tests import copy and SimpleNamespace inside functions without deferring an optional dependency. Move them to the module import block.

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 cited function-local copy and SimpleNamespace imports disappeared when the duplicate standalone tests were folded into existing coverage in 78b2e1d; there is no remaining change needed at those locations.

ObservationManager({"policy": cfg}, setup_env)


@pytest.mark.parametrize("capture_final_obs", [False, True], ids=["direct", "final_obs"])

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.

🟡 Warning · Test Quality — Remove the duplicate capture row

The final_obs row repeats the same manager preview through a one-line delegate; the step test owns capture routing. Keep the direct manager row and remove this axis.

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.

Already addressed in 78b2e1d. The duplicate standalone capture test and parameter axis were removed. Existing callable-term coverage owns preview state/cache behavior, existing history coverage owns prospective samples, and lifecycle coverage owns capture routing.

saved_rng = torch.random.get_rng_state()
preview = buffer.compute(data * 50, update_history=False, preview=True)
torch.random.set_rng_state(saved_rng)
expected = reference.compute(data * 50)

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.

🟡 Warning · Test Quality — Assert the prospective lag independently

Another DelayBuffer.compute call produces the expected preview, so a shared lag-selection error passes both sides. Fix the sampled lag and assert its expected delayed value directly.

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.

Already addressed in 78b2e1d. The test fixes prospective lags to [0, 3] and asserts literal delayed values, unchanged lag/counter state, the oldest retained sample before committing, and the next committed result. It no longer derives expected values from another DelayBuffer.compute call or saves/restores the global RNG.

Comment thread source/isaaclab/test/utils/test_math.py Outdated
t02_compare, q02_compare = math_utils.combine_frame_transforms(t01, q01, t12_value, q12_value)

torch.testing.assert_close(t02_expected, t02_compare, atol=1e-3, rtol=1e-4)
torch.testing.assert_close(t02_expected, t02_compare, atol=2e-3, rtol=1e-4)

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.

🟡 Warning · Scope Complexity — Separate the unrelated tolerance edit

The frame-transform tolerance has no dependency on terminal observations and changes an independent test contract. Revert it here and submit its supplied flakiness evidence separately.

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.

Already addressed in 78b2e1d. The tolerance edit was reverted and is absent from the PR diff. The PR description has also been updated to remove its stale reference to that change.

camera_output: Dictionary mapping data type names to image tensors from the
tiled camera sensor.
gt_pose: Ground truth pose tensor (position and keypoint corners). Shape: (N, 27).
preview: Extract features without training the CNN or saving images. Defaults to False.

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.

🟡 Warning · Style Consistency — Qualify the image-saving guarantee

The step docstring still says image saving always runs first, while preview skips it. Limit that statement to ordinary calls.

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.

Addressed in 198cb51ce5. The image-saving statement is now explicitly limited to ordinary calls; preview calls continue to skip both image saving and CNN training.

@greptile-apps

greptile-apps Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable defects were found.

Summary

This PR captures terminal observations before reset without advancing built-in observation state.

  • Terminal observations capture the current state before reset work.
  • Observation previews read the next sample without advancing built-in history.

No actionable issues were found. Tests were inspected but not run during this review.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Advance physics] --> B[Compute rewards and episode boundaries]
    B --> C[Include visualizer reset requests]
    C --> D{Any environments reset?}
    D -- Yes, capture enabled --> E[Preview terminal observations without advancing history]
    E --> F[Store owned final observations]
    F --> G[Reset selected environments]
    D -- Yes, capture disabled --> G
    G --> H[Run configured reset rerenders]
    H --> I[Update commands and interval events]
    D -- No --> I
    I --> J[Compute ordinary observations and advance history]
Loading

Reviews (2) · Last reviewed commit: "Simplify preview state and address revie..." · Reviewed by Greptile

@AntoineRichard

Copy link
Copy Markdown
Collaborator

Reviewed the bot findings against the current code. The follow-up is pushed in 198cb51ce5, and the PR description now reflects the final behavior and validation. Repeated findings from the two review runs are grouped below.

Implemented or clarified

  • Thread: The behavior change is real, but the configured rerenders are intentional: num_rerenders_on_reset already promises sensor refresh after each reset. The old manual path left camera observations stale. We kept the unified reset pass and documented manual/UI rerenders, including when compute_final_obs is disabled, in the config, changelog, and PR description.
  • Thread: Addressed in 198cb51ce5. The DirectRL and MARL docs now describe task-owned observation state and the is_observation_preview obligation, without promising manager-owned command updates, buffers, processors, or recorder behavior.
  • Thread: Addressed in 198cb51ce5. The one-line manager capture helper is inlined into step; the camera manager test calls compute(preview=True) directly. Existing lifecycle tests own capture routing. The substantive DirectRL/MARL capture helpers remain.
  • Thread: Addressed in 198cb51ce5 with one environment-owned preview scope. Nested compute() and compute_group() calls inherit it, preserve the committed cache, and reject history updates while previewing. No compute_group parameter was added. The existing two processor cases now exercise both nested entry points; both failed before the fix and pass afterward, without adding cases.
  • Thread: Addressed in 198cb51ce5. Owned preview stacks return directly after the deferred-normalization branch; ordinary ring-buffer-backed results still clone. Existing camera tests and ownership checks passed for both channel orders.
  • Thread: Addressed in 198cb51ce5. The image-saving statement is now explicitly limited to ordinary calls; preview calls continue to skip both image saving and CNN training.
  • Thread: Added migration guidance in 198cb51ce5: custom ObservationManager.compute overrides must accept and forward keyword-only preview=False. No affected stable-manager override was found in the repository. We did not add a fallback to ordinary compute, since that could silently advance state and restore the incorrect terminal-observation behavior this PR fixes.
  • Thread: Addressed in 198cb51ce5. The summary now states that the default delegates to call, and the body explicitly says it does not suppress state updates and that stateful processors must override preview. The compatibility implementation remains unchanged.

Kept or deferred after checking behavior

  • Thread: Confirmed the extra allocation, but deferred this optimization. The straightforward torch.where(..., out=history) replacement raises for gradient-requiring inputs, while the current implementation backpropagates correctly. Keeping the existing behavior here avoids dropping autograd support; a gradient-preserving allocation optimization can be considered separately. No throughput or peak-memory improvement is claimed.
  • Thread: Kept these assignments intentionally. Both caches pass the current policy embedding to the critic during the same observation computation. Skipping the assignments during preview would give the terminal critic stale embeddings. A focused check with the actual task/feature-extractor methods confirmed that the terminal critic receives the current embedding and the next ordinary read matches the no-preview result. These are computation caches rather than temporal history.
  • Thread: No change needed: DigitalFilter._compute already has -> torch.Tensor in the reviewed revision 39fa9b5 and in the current code.

Already addressed by the test-minimality cleanup

  • Thread: Already addressed in 78b2e1d. The exception-only test was removed. Its dictionary and tensor metadata-preservation assertions now run through the ordinary MARL step lifecycle, alongside stale-key cleanup.
  • Thread: Already addressed in 78b2e1d: the recorder stub supplies record_post_step and the MARL fixture supplies cfg.possible_agents. Each environment now reuses one fixture across automatic, no-reset, manual, and mixed boundaries; all three lifecycle cases pass.
  • Thread: Already addressed in 78b2e1d. The duplicate standalone capture test and parameter axis were removed. Existing callable-term coverage owns preview state/cache behavior, existing history coverage owns prospective samples, and lifecycle coverage owns capture routing.
  • Thread: Already addressed in 78b2e1d. The tolerance edit was reverted and is absent from the PR diff. The PR description has also been updated to remove its stale reference to that change.
  • Thread: The cited function-local copy and SimpleNamespace imports disappeared when the duplicate standalone tests were folded into existing coverage in 78b2e1d; there is no remaining change needed at those locations.
  • Thread: Already addressed in 78b2e1d. The test fixes prospective lags to [0, 3] and asserts literal delayed values, unchanged lag/counter state, the oldest retained sample before committing, and the next committed result. It no longer derives expected values from another DelayBuffer.compute call or saves/restores the global RNG.

Validation: 215 focused tests passed, two CUDA-only cases skipped, formatting/lint/changelog checks passed, and the clean Sphinx build passed. Existing processor cases cover the nested-manager regression without adding test cases. GPU throughput and peak memory were not measured.

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

Source review looks good. 152 focused tests pass, including terminal capture and nested stateful previews. Current head conflicts with main. Rebase and run the activated Docker CI on the resolved head before approval.

@hujc7

hujc7 commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Nov 16, 2026
The key is absent on steps without resets.

Preview reads include the current sample in delay and observation history without committing
it. Custom stateful observation terms should check ``env.is_observation_preview``; stateful

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.

MicroDuck's misaligned_imu term still commits state on a preview read, so once compute_final_obs is on (e.g. RSL-RL SAC, #8866) reset envs get their IMU history one step late; it could use self._buffer.peek_append(reading) when env.is_observation_preview is set, like the Cartpole and Shadow Hand camera terms.

self._resolve_stack_dim(data.ndim)
return data.unsqueeze(1).expand(-1, self.max_length, *data.shape[1:]).clone()
data = data.to(dtype=self._buffer.dtype)
history = torch.cat((self.buffer[:, 1:], data.unsqueeze(1)), dim=1)

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.

Returning early when _need_reset is False (every batch has history) skips the no-op torch.where copy flagged in the bot thread without out=, so autograd keeps working; fine as a follow-up.

Suggested edit:

Suggested change
history = torch.cat((self.buffer[:, 1:], data.unsqueeze(1)), dim=1)
history = torch.cat((self.buffer[:, 1:], data.unsqueeze(1)), dim=1)
if not self._need_reset:
# every batch has history since the last append, so the fresh-row fill is a no-op
return history

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

Thanks for digging into this. The bug is real and worth fixing, but I don't think the preview approach is the right shape for it, and I'd like to suggest a different direction before we go further.

What's actually going wrong

With same-step autoreset, step() only commits observation state once, at the very end, after the reset. When we read final_obs before _reset_idx, the history and delay buffers haven't seen this step's sample yet, so the terminal observation is one step stale. Frame stacks and the stateful processors have the opposite problem: they don't respect update_history at all, so the extra read advances them twice for envs that didn't reset.

So the underlying issue is that writing a sample and advancing history are the same operation, and a terminal capture needs a second read at a different point in the step.

Concerns with the current approach

The PR solves this by adding a speculative "preview" mode and threading it through every stateful piece of the observation pipeline:

  • env._is_observation_preview is global mutable state, toggled with try/finally and read through getattr, and nested compute() calls inherit it implicitly. It's hard to reason about who is in preview at any given point.
  • Every stateful component now has two implementations that need to stay in sync: peek_append next to append, a preview branch in DelayBuffer.compute, DigitalFilter._compute(update_state=...), Integrator.preview, and a preview path in the frame stack.
  • The flag leaks into task code (AMP, cartpole camera, shadow hand), and any custom stateful term has to know to check it. If it doesn't, it's silently wrong. The default TensorProcessor.preview just calls __call__, which mutates state, so the safe-looking default is the incorrect one.
  • With stochastic lags, the delay preview doesn't match what the real commit produces, which the docstring acknowledges.
  • preview and update_history are mutually exclusive booleans, with ValueErrors guarding the invalid combination.
  • It allocates on the step path (torch.cat, expand().clone(), tree_map(clone)). Today that's hidden behind the existing len(reset_env_ids) > 0 gate, but once resets move to masks and that sync goes away, the capture runs every step. At 4096 envs almost every step has a reset anyway.

The PR also bundles a few unrelated changes: the UI reset reorder, the RTX rerender fix, popping stale final_obs, and the removal of test_camera_image_obs_manager.py. I'd prefer those as separate PRs so each can be reviewed on its own.

Suggested direction

1. Opt-in next-step autoreset for off-policy training. For the SAC/SuperMimic use case in #8863, I think the cleaner fix is to stop resetting in the same step. Envs that are done this step return their real s_{t+1} through the normal observation path, and they get reset at the start of the next step, using the previous dones as the reset mask. That gives you:

  • one observation pass per step, with no final_obs capture and nothing to preview;
  • correct history and delay terms for free, since the terminal observation is just the normally committed one;
  • no new syncs, which fits the mask-reset and graph-capture work.

The cost is one dummy transition per episode, which the wrapper has to mask out. That's about 0.1% of samples for 1000-step episodes, more early in training when episodes are short. Physics and inference are batched, so it shouldn't change step time. This is also what Gymnasium 1.x settled on for vector envs, for the same reason. I'd expose it as an autoreset_mode setting rather than changing the default, since PPO and the existing wrappers assume same-step.

2. If we keep compute_final_obs, fix it by separating write from advance. SB3 still relies on final_obs, so it's reasonable to keep it as the explicit two-pass option. Instead of a preview mode, stateful components could split into:

  • write(x), which records the newest sample and returns the result. Repeat writes within a step overwrite the newest slot rather than pushing again.
  • advance(), called once per step by the owner, which is just a host flag or a device-side counter bump.

DelayBuffer already works almost this way, with a spare slot and a device-side _write_index. CircularBuffer can keep its current layout, so stacked stays a zero-copy view on the camera path. With this split, extra reads are safe by construction, including the recorder reads the PR calls out as unsupported, and the preview flag, the preview() methods and the task-level branches all go away. One caveat: moving lag resampling into advance() changes RNG order, so seeded runs will differ and that should go in the changelog.

3. Move side effects out of observation terms. The shadow-hand term trains its CNN, and the direct cartpole camera env and shadow hand write PNGs inside the observation call. Those belong in a step hook. Frame stacking could also live in the manager's history buffer, which already supports stack_dim, and that would make the camera terms pure functions.

Before deciding

I haven't benchmarked any of this yet. It would be good to check the step tail with torch.cuda.set_sync_debug_mode("warn"), and compare env steps/s on one proprio task and one camera task with compute_final_obs off, on, and with next-step autoreset. A short G1 SAC run comparing wall-clock time to a target reward would show whether the dummy transitions matter in practice. If the second observation pass turns out to be cheap, option 2 on its own might be enough for now, with next-step autoreset as a follow-up.

Happy to help prototype either of these.

The misaligned IMU term advanced its history and lags on the terminal
preview read, so with compute_final_obs enabled the following ordinary
read saw the step twice. Preview reads now use peek_append and reuse the
lag redraw that the commit will draw for the same step.

CircularBuffer.peek_append returns early when no row needs the
fresh-row fill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

CI caught the same missing is_observation_preview flag in Leapp export and Lift camera normalization. Can the camera term default it to False for env proxies that don’t provide it?

@ooctipus

Copy link
Copy Markdown
Collaborator

My understanding is that terminal capture needs to include the current sample in history without advancing continuing environments twice. Which is today's bug.

In that case, could update_history take a per-environment mask instead? Before reset, update only terminating environments and capture final_obs; after reset, the normal pass updates all environments. If applied consistently to history, delays, frame stacks, and filters, would that remove the need for a preview mode?

AntoineRichard added a commit that referenced this pull request Nov 19, 2026
# Description

Adds RSL-RL SAC support:

- `time_outs` exclude true terminations. This also affects PPO
bootstrapping.
- One RSL-RL runner factory for train, play, export and benchmarks.
- Typed SAC configs, with a G1 flat velocity preset.

Requires an rsl-rl-lib release with SAC (leggedrobotics/rsl_rl#254) and
a dependency pin bump before merging. The generic final-observation fix
is a separate PR, #8868; SAC on the G1 preset does not need it.

Size: about 550 lines. About 360 are source, almost all in `isaaclab_rl`
(configs and factory) plus the G1 preset. In core `isaaclab`, only the
benchmark scripts change, to use the factory (+9/−25). About 150 lines
are tests.

Part of #8863

## Type of change

- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality)

## Screenshots

G1 velocity learning curves and evaluation can be attached on request.

## Checklist

- [x] I have read and understood the contribution guidelines
- [x] I have run the `pre-commit` checks with `uv run isaaclab --format`
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have validated the changed behavior with focused coverage and
applied the test-audit criteria to any test changes
- [x] I have added a changelog fragment under
`source/<pkg>/changelog.d/` for every touched package
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there

---------

Signed-off-by: Rafael Cathomen <rcathomen@nvidia.com>
Co-authored-by: Lionel Gulich <lgulich@nvidia.com>
Co-authored-by: AntoineRichard <antoiner@nvidia.com>
Co-authored-by: Maximilian Krause <maximiliank@nvidia.com>
AntoineRichard added a commit that referenced this pull request Nov 20, 2026
Three small fixes around terminal observations, split out of #8868 so
that PR only changes how stateful observations are captured.

`extras["final_obs"]` was only written on steps with resets and never
removed. A later step without resets still carried the terminal
observations of an earlier step, and wrappers that check for the key
would pick them up again. Manager-based, direct and multi-agent
environments now drop it at the start of every step and in explicit
`reset()` calls, and manager-based environments also in `reset_to()`.

Direct and multi-agent environments stored the tensors returned by
`_get_observations()` as terminal observations. Tasks may return views
of their own buffers, which the following `_reset_idx()` overwrites, so
the terminal observation could end up holding the reset state. They are
now copied before the reset. Manager-based environments already return
owned tensors.

The Humanoid AMP environment assigned `self.extras = {"amp_obs": ...}`
while computing observations, which replaced the whole dict and dropped
time-outs, episode logs and terminal observations set earlier in the
step. It now only sets its own key.

The env unit test steps a manager-based, a direct and a multi-agent
environment with stubbed physics through an autoreset step, a step
without reset, and an explicit reset (plus `reset_to()` for the
manager-based one). It checks that the terminal observation is the
pre-reset state, that the key is gone after the step without reset and
after the explicit resets, and that an unrelated extras entry survives
throughout. The AMP test calls the real `_get_observations()` with
stubbed robot data and checks that `final_obs` and `time_outs` are kept.
Both fail on main.

Co-authored with Rafael Cathomen and Antoine Richard, who wrote these
changes in #8868.

To run the tests:

```
./isaaclab.sh -p -m pytest source/isaaclab/test/envs/test_manager_based_rl_env_unit.py \
    source/isaaclab_tasks/test/test_humanoid_amp_extras.py
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Rafael Cathomen <rcathomen@nvidia.com>
Co-authored-by: Antoine Richard <antoiner@nvidia.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

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

#9121
please check this pr, should reduce a lot of complexity and hooks introduced in this pr.

AntoineRichard added a commit that referenced this pull request Nov 23, 2026
# Description

The existing RGB camera observation unit test already checks output
values and shapes across frame stacking, channel layout, and
normalization. Have it also check the observation manager's reported
shape for the policy group, then remove the separate Kit test that
existed to check that metadata. This removes a GPU simulator startup
from the camera observation tests.

Split from #8868.

## Validation

- `test_camera_image_mdp.py` passed with 28 tests and one CUDA-only
skip.
- A deliberately incorrect policy group shape fails the new assertion in
all four existing RGB cases.
- Repository formatting, lint, and changelog checks passed.

## Type of change

- Test maintenance

## Checklist

- [x] I have read and understood the contribution guidelines
- [x] I have applied the test-audit criteria and validated the retained
coverage
- [x] I have added a `.skip` changelog fragment for the test-only change
- [x] My name already exists in `CONTRIBUTORS.md`

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

isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants