Skip to content

Add MicroDuck ToF obstacle avoidance and deployment tools - #8979

Merged
AntoineRichard merged 3 commits into
isaac-sim:exp/microduckfrom
seun-doherty:feat/microduck-tof-navigation
Nov 16, 2026
Merged

AntoineRichard merged 3 commits into
isaac-sim:exp/microduckfrom
seun-doherty:feat/microduck-tof-navigation

Conversation

@seun-doherty

Copy link
Copy Markdown

Adds MicroDuck obstacle avoidance using an 8×8 ToF sensor and a frozen walking policy. Includes randomized SimReady and primitive obstacles, native Isaac Lab training/playback, and gamepad deployment scripts.

@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 8, 2026
@AntoineRichard
AntoineRichard marked this pull request as ready for review November 16, 2026 17:45

@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 (2), Scope and over-engineering (4), API (3), Compatibility and deprecation (2), Implementation (10), Style consistency (6), Test quality (5).

  • PR description: Title/body match task/deployment scope; add asset prerequisites and validation, plus Newton step-throughput/peak-memory baseline/candidate evidence with revisions, command/workload, hardware, backend, environment count, and warmup.
  • Design and architecture: Action and sensor configurations eagerly load runtime implementations; separate declarative configuration and use resolvable implementation references so configuration imports remain usable before simulator startup.
  • Scope and over-engineering: Minimal implementation: Extend PreTrainedPolicyAction, MicroDuckVelocityCommand, and the native ray camera; keep registration/agents/MDP initializers and stub, actions, commands, events, geometry, observations, rewards, symmetry, terminations, sensors, runner/distribution, environment configuration, and nav_pad/padproxy/relay for their contracts; merge configuration into declarative owners; delete graph diagnostics, Robot forwarding, empty curriculum, and unused braking-only branches. Essential flow remains sensing → residual commands → frozen walking. Suggested PR breakdown: sensor/walker with cadence/reset validation; scene/training with contacts/rewards/PPO validation; deployment with parity/stop validation.
  • API: The registered default scene requires local SimReady packages without reproducible acquisition instructions; document their sources, pinned revisions, and download procedure before training or playback.
  • Compatibility and deprecation: Breaking changes: forced sensor updates are ignored, and reusable action configurations lose their decimation; preserve forced acquisition and clone configuration before constructor adjustments.
  • Implementation: The proxy clears nav_driving before checking expired gamepad requests, allowing continued laptop input to suppress robot.stop; retain the prior driving state until stopping is sent.
  • Style consistency: Environment post-initialization rewrites command, event, scene, and backend defaults; declare defaults in their owning configurations and move necessary cross-configuration preparation to launch.
  • Test quality: Proxy stop cases can pass through the command watchdog when their intended guards fail; disable that fallback in those cases or assert distinct stopping deadlines.

Significant concerns. Posted 32 inline findings.

Automated review; human maintainers own approval decisions.

continue
with state_lock:
state["cmd_t"] = now
drives = state["nav_driving"] = policy_drives()

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.

🔴 Critical · Implementation — Stop before clearing driving state

An expired gamepad request makes policy_drives false and clears nav_driving here. The following watchdog then skips robot.stop while laptop commands continue. Preserve the prior driving state until the stop is sent.

steps_per_apply = env.cfg.decimation if env.sim.backend_manager.handles_decimation() else 1
if cfg.low_level_decimation % steps_per_apply:
raise ValueError("Walking policy period must be divisible by the backend's batched physics steps.")
cfg.low_level_decimation //= steps_per_apply

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.

🔴 Critical · Compatibility — Do not consume configured decimation

Construction divides the caller's low_level_decimation in place; reusing that config changes walker cadence or fails divisibility. Clone the config before adjusting decimation and its observation callback.

return cmd.astype(np.float32)


def load_normalizer(path):

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 — Drop optional ONNX graph scanning

Inference already uses the exported model; this console-only warning reloads its graph and initializers and adds an onnx dependency. Remove the scanner and associated diagnostic state.

self.tof_hist.append((ranges, valid, age))
while len(self.tof_hist) < TOF_HISTORY: # first ticks: empty frames aged 1 s, as at a training reset
self.tof_hist.appendleft((np.zeros(TOF_ZONES, np.float32), np.zeros(TOF_ZONES, np.float32), 1.0))
obs = np.concatenate(

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 — Reuse the flat observation buffer

Every 50 Hz tick concatenates ten frame pairs, allocates padding and ages, then concatenates and casts the whole observation. Fill fixed slices of a reusable float32 buffer.


def centre_min(ranges, valid):
"""Nearest valid reading in the centre four columns, floor rows left out: what the brake checks."""
rows = [r for r in range(8) if r not in BRAKE_IGNORE_ROWS]

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 — Slice the six brake rows

The excluded rows are always the last two, but constructing row indices triggers advanced-index copies on every tick. Slice rows 0:6 in both images.

rotation[:, 1] = torch.sin(pitch / 2.0)
rotation[:, 3] = torch.cos(pitch / 2.0)
# Update native mounting buffers so every ray follows the articulated head.
wp.to_torch(self._offset_pos_wp)[env_ids] = nominal_pos + quat_apply(nominal_quat, height)

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 — Mutate Warp-owned mounts in Warp

Reset converts native Warp mounting buffers to Torch solely to write them. Keep mount updates in Warp, avoiding cross-interface mutation of owned arrays.


def _update_buffers_impl(self, env_mask: wp.array) -> None:
"""Acquire ideal depths, corrupt one packet, then deliver the delayed packet."""
env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).flatten()

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 — Avoid acquisition mask compaction

CUDA nonzero materializes dynamic indices and synchronizes during sensor acquisition. Keep the existing environment mask through batched frame and delivery updates.

@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA))
def test_microduck_native_navigation_terminations_and_episode_reset(device, walking_policy_path, record_property):
"""Real contact, fall and timeout propagate through native navigation accounting and autoreset."""
cfg = parse_env_cfg(TASK, device=device, num_envs=16384, overrides=("presets=backlash",))

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 — Reduce the terminal integration scene

This test observes three terminal environments yet constructs 16,384 robot-and-obstacle scenes. Use the three cases and a control; the remaining scenes add startup and memory cost without another assertion path.

torch.testing.assert_close(env.microduck_front_obstacle_index[1::2], front_before[1::2])
for name in OBSTACLE_CELLS:
torch.testing.assert_close(scene[name].data.root_pos_w.torch[1::2], before[name][1::2])
reset_obstacle_field(env, torch.empty(0, dtype=torch.long), layout=layout, shuffle_groups=groups)

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 empty reset contract

The empty shuffle reset has no subsequent assertions and cannot detect changed poses, layout, front indices, or RNG state. Assert those invariants or delete the invocation.

with torch.no_grad():
actor.mlp[-2].weight.zero_()
actor.mlp[-2].bias.fill_(math.log(math.expm1(1.0))) # All three heads are Beta(2, 2).
checkpoint_path = tmp_path / "actor.pt"

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 fabricated checkpoint persistence

The test writes its own actor_cfg and confirms torch reloads it; production checkpoint packaging is never exercised. Use the actual runner checkpoint boundary or remove this round trip.

@greptile-apps

greptile-apps Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5

[High impact] The PR adds a new simulation workflow and a deployment path that can affect a physical MicroDuck's movement.

The PR needs deployment safety fixes before merging.

Findings

  1. P1 Navigation can keep reversing ▶
  2. P1 Delayed data looks fresh ▶
  3. P1 Stale requests can keep moving ▶
  4. P2 Training setup instructions are missing ▶

Summary

Adds MicroDuck obstacle-avoidance training and laptop-based gamepad deployment.

  • The training scene gives MicroDuck a ToF view of randomized obstacles.
  • The navigation policy steers the frozen walker toward goals while learning to avoid obstacles.
  • A laptop can run the navigation policy with a gamepad and ToF input.
  • Robot-side helpers relay sensor data to the laptop and send adjusted commands back.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    Pad[Gamepad] --> Proxy[Robot proxy]
    Proxy -->|Requested motion| Laptop[Laptop navigation policy]
    Sensors[Robot state and ToF] --> Relay[Robot relay]
    Relay --> Laptop
    Laptop -->|Adjusted motion| Proxy
    Proxy --> Walker[Frozen walking policy]
Loading

Reviews (2) · Last reviewed commit: "Load MicroDuck SimReady props from local..." · Reviewed by Greptile

Comment on lines +240 to +249
with state_lock:
state["cmd_t"] = now
drives = state["nav_driving"] = policy_drives()
if drives:
nav_send(
"robot.move",
{"vx": clamp(vx, MAX_VX), "vy": clamp(vy, MAX_VY), "vyaw": clamp(vyaw, MAX_VYAW)},
)
with state_lock:
stale = state["nav_driving"] and (not policy_drives() or now - state["cmd_t"] > WATCHDOG_S)

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.

P1 Stale requests can keep moving when the gamepad daemon stalls without closing its socket while the laptop keeps sending commands. Once the request expires, this assignment clears nav_driving before the watchdog checks it. The watchdog then skips robot.stop, leaving the last movement command active. Check the previous driving state and send a stop before clearing it. Add a test where laptop commands keep arriving after the gamepad request expires; the current stale-request test sends only one laptop command.

Comment on lines +48 to +52
SIMREADY_ASSET_ROOT = os.environ.get(
"MICRODUCK_NAVIGATION_PROPS",
str(Path(ISAACLAB_ROOT) / "assets" / "simready"),
).rstrip("/")
"""Downloaded SimReady packages; MICRODUCK_NAVIGATION_PROPS overrides the local directory."""

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.

P2 Training setup instructions are missing for the three local SimReady packages and the frozen walker. The task points at specific files, but no download URLs, package revisions, or walker export commands are provided. The added README covers deployment only. Add a reproducible setup section with the exact asset sources, expected directories, walker export, and training command so users can load the scene and match its measured obstacle sizes.

Knowledge Base Used: Task library

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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), Implementation (10), Style consistency (7), Test quality (4). Other reviewed categories look good.

  • PR description: Title/body match task and deployment scope; add validation outcomes and collision-buffer measurements comparing baseline/candidate revisions, command/workload, hardware, backend, environment count, software environment, warmup, throughput, and peak memory.
  • Design and architecture: Configuration imports load USD and Newton runtime implementations before startup; separate runtime code and use resolvable implementation references.
  • Scope and over-engineering: Minimal implementation: Extend PreTrainedPolicyAction and MicroDuckVelocityCommand; flatten Robot’s SSH wrapper and remove unused braking-only and joystick-mixture branches. Keep registration/export modules, navigation_distribution.py, rsl_rl_ppo_cfg.py, actions.py, commands.py, events.py, geometry.py, observations.py, rewards.py, symmetry.py, terminations.py, obstacle_avoidance_env_cfg.py, sensors.py, nav_pad.py, padproxy_on_duck.py, and relay_on_duck.py for shared geometry, manager, sensor, policy, or process contracts. Suggested PR breakdown: (1) sensor/action—cadence/reset validation; (2) scene/rewards/agent—geometry/contact/learning validation; (3) deployment—ONNX/proxy safety validation.
  • API: API changes look good.
  • Compatibility and deprecation: No breaking changes identified.
  • Implementation: Policy takeover can retain manual motion or send reverse commands under navigation; stop preceding motion and reset applied-command history when navigation takes control.
  • Style consistency: The deployment module docstring duplicates README controls, examples, and safety instructions; retain concise protocol constraints and keep operator instructions in README and argparse.
  • Test quality: The terminal-accounting test builds 16,384 robots without an independent scaling contract; reduce it to three terminal cases and one live control while retaining distinct physical, frame, and determinism coverage.

Significant concerns. Posted 25 inline findings.

Automated review; human maintainers own approval decisions.

safety = f"stop: {cmin:.2f} m ahead"
drives = pad["policy"] and stick.any() and stick[0] >= 0 # the proxy only uses our command then
# Feed back the final command, including operator overrides and the extra deployment brake.
nav.prev_applied = (sent if drives else stick).astype(np.float32).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.

🔴 Critical · Implementation — Reset reverse command history at takeover

Manual reverse motion becomes prev_applied. On a forward takeover, slew limiting can therefore send negative forward velocity while the proxy enables navigation. Reset the history at takeover and enforce the forward-only limit after slew.

with state_lock:
state["req"], state["req_t"] = req, time.monotonic()
drives = policy_drives()
if not drives:

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.

🔴 Critical · Implementation — Stop motion on policy takeover

A forward request suppresses the gamepad move without stopping the preceding manual move; nav_driving remains false until a laptop command arrives. An expired request can also clear it before the watchdog stops. Stop active motion…

steps_per_apply = env.cfg.decimation if env.sim.backend_manager.handles_decimation() else 1
if cfg.low_level_decimation % steps_per_apply:
raise ValueError("Walking policy period must be divisible by the backend's batched physics steps.")
cfg.low_level_decimation //= steps_per_apply

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.

🔴 Critical · Implementation — Do not mutate walking configuration

Construction divides cfg.low_level_decimation in place and also replaces its observation callback. Reusing that configuration changes the walking cadence or fails divisibility. Clone it before either modification.

# dependencies = ["numpy>=1.24", "onnxruntime>=1.16", "onnx>=1.14"]
# ///

"""Drive a MicroDuck with a gamepad while a learned ToF policy steers it around obstacles.

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 — Remove duplicated operator tutorial

The module docstring repeats README controls, safety instructions, and examples, creating two maintained tutorials. Keep a concise protocol and safety summary; leave usage instructions in the README and argparse help.

# --- the robot side ---------------------------------------------------------------------------


class Robot:

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 — Flatten the SSH wrapper

Robot stores only a target string and owns no connection or cleanup lifecycle. Replace the forwarding class with functions that take the target explicitly.

recorders = None
events: MicroDuckObstacleEventsCfg = MicroDuckObstacleEventsCfg()

def __post_init__(self):

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 — Declare defaults in their owners

post_init imperatively rewires command, event, termination, and scene defaults across configuration owners. Declare those defaults in their respective configuration classes.

rotation[:, 1] = torch.sin(pitch / 2.0)
rotation[:, 3] = torch.cos(pitch / 2.0)
# Update native mounting buffers so every ray follows the articulated head.
wp.to_torch(self._offset_pos_wp)[env_ids] = nominal_pos + quat_apply(nominal_quat, height)

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 — Write Warp-owned mounts in Warp

Mount reset converts private Warp-owned offset buffers to Torch for mutation, contrary to the array-ownership rule. Apply selected offset updates in Warp.


def _update_buffers_impl(self, env_mask: wp.array) -> None:
"""Acquire ideal depths, corrupt one packet, then deliver the delayed packet."""
env_ids = wp.to_torch(env_mask).nonzero(as_tuple=False).flatten()

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 acquisition masks device-side

Every acquisition converts a Warp mask to Torch and compacts it with nonzero before packet processing, synchronizing the device. Process masked rows without dynamic host-visible index compaction.

@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA))
def test_microduck_native_navigation_terminations_and_episode_reset(device, walking_policy_path, record_property):
"""Real contact, fall and timeout propagate through native navigation accounting and autoreset."""
cfg = parse_env_cfg(TASK, device=device, num_envs=16384, overrides=("presets=backlash",))

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 — Reduce terminal-test scene scale

Only environments 0–2 have terminal assertions; 16,381 other robots add scene and GPU cost without a scale contract. Use three terminal environments and one live control.

torch.testing.assert_close(env.microduck_front_obstacle_index[1::2], front_before[1::2])
for name in OBSTACLE_CELLS:
torch.testing.assert_close(scene[name].data.root_pos_w.torch[1::2], before[name][1::2])
reset_obstacle_field(env, torch.empty(0, dtype=torch.long), layout=layout, shuffle_groups=groups)

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 assertion-free empty resets

Both shuffle-layout rows invoke an empty reset without checking poses, layout, front indices, or RNG state. Remove the calls or assert a distinct empty-selection invariant.

@AntoineRichard
AntoineRichard merged commit 863dbd2 into isaac-sim:exp/microduck Nov 16, 2026
25 checks passed
Comment on lines +112 to +113
cmd = prev_applied + np.clip(cmd - prev_applied, -CMD_SLEW * dt, CMD_SLEW * dt)
cmd[1] = np.clip(cmd[1], -0.35 * cmd[0], 0.35 * cmd[0])

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.

P1 Navigation can keep reversing

When the operator moves the stick directly from reverse to forward, tick has saved the reverse command in nav.prev_applied. The slew limit can leave cmd[0] negative, which also reverses the lateral bounds passed to np.clip. The final bounds allow that command through while navigation is active, so the duck keeps moving backwards without rear sensing.

Keep the command history for observations, but reset or constrain the slew state when switching from manual reverse to navigation.

self.prev_dq = dq_now
ranges, valid, rx = self.tof
now = time.monotonic()
age = max(st["rx"] - rx, now - self.tof_received_at, 0.0)

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.

P1 Delayed data looks fresh

If SSH delivers both body state and ToF data more than 0.25 seconds late, this check can still treat them as fresh. It measures the gap between two robot timestamps, so their shared network delay cancels out. Meanwhile, read_lines and on_tof assign fresh laptop receive times to the old messages.

With a steady delay, navigation can keep sending commands based on an old view without triggering the stale-data stop. Include transport delay in the age check, or compare the source timestamps with the robot's current clock before applying commands.

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.

2 participants