Repository navigation
Batch Newton visualization markers with direct Torch-to-Warp transfers - #9038
Conversation
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (1), Compatibility and deprecation (1), Implementation (2), Style consistency (2), Test quality (1). Other reviewed categories look good.
- PR description: Qualify the title as removing per-instance host conversions; make the 0.56→0.20 ms CPU claim reproducible with baseline/candidate revisions, command, hardware, backend, environment count, warmup, and metric, preserving template sections.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: Extend NewtonVisualizationMarkers in newton_visualization_markers.py; no source modules were added and no parallel layers need removal. Keep initialization-time geometry grouping and viewer-local registration, but restrict transform and Warp color preparation to mesh batches; frame batches need only line preparation. Retain the focused tests and changelog. Scope is cohesive; no split recommended.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: construction-time fallback scale and color tables ignore configuration edits previously read during rendering; preserve live reads or provide a functional deprecation bridge, migration guidance, removal schedule, and transition coverage.
- Implementation: Rendering copies stored int32 indices to int64 unnecessarily; reuse the stored selection and create default indices as int32.
- Style consistency: Prototype scale and color tables lack the concrete attribute annotations required by repository guidance and adjacent state; annotate their element types.
- Test quality: The registration and batching checks protect distinct contracts, but both lack required kitless markers; mark them so kitless selections exercise the coverage.
Significant concerns. Posted 7 inline findings.
Automated review; human maintainers own approval decisions.
| name: _infer_newton_marker_cfg(marker_cfg) for name, marker_cfg in cfg.markers.items() | ||
| } | ||
| self._marker_batches: list[tuple[str, _NewtonMarkerSpec, list[int]]] = [] | ||
| self._prototype_scales = [] |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate prototype tables
The new scale and color attributes omit element types beside the annotated batch attribute. Add concrete list annotations so their stored values are explicit.
| self._prototype_colors = [] | ||
| for index, (name, marker_cfg) in enumerate(cfg.markers.items()): | ||
| spec = _infer_newton_marker_cfg(marker_cfg) | ||
| self._prototype_scales.append(spec.scale or _extract_scale_hint(marker_cfg)) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve live prototype styling
Scale and color fallbacks were read from marker configurations on each render. Caching them at construction ignores later configuration edits; retain live reads or a functional, documented deprecation bridge.
| num_markers = translations.shape[0] | ||
| if orientations is None: | ||
| orientations = translations.new_tensor((0.0, 0.0, 0.0, 1.0)).expand(num_markers, -1) | ||
| xforms = wp.from_torch(torch.cat((translations, orientations), dim=1).float(), dtype=wp.transform).to( |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Skip mesh preparation for frames
Frame-only groups now construct transforms and convert colors to Warp, although log_lines consumes neither. Prepare these arrays only when a mesh batch exists.
| indices = ( | ||
| torch.zeros(num_markers, device=translations.device, dtype=torch.long) | ||
| if (marker_indices is None) | ||
| else marker_indices.long() |
There was a problem hiding this comment.
🟡 Warning · Implementation — Reuse stored marker indices
visualize() already stores int32 indices, which Torch indexing and membership checks accept. Converting the full selection to int64 copies it every render; use the stored tensor and create default indices as int32.
| viewer.log_lines(batch_name, None, None, None, hidden=True) | ||
| continue | ||
|
|
||
| shown = torch.isin(indices, indices.new_tensor(prototype_indices)) |
There was a problem hiding this comment.
🟡 Warning · Implementation — Reuse batch membership data
Each render rebuilds every unchanged prototype-index tensor from a Python list, uploading it on CUDA. Retain device-side membership data per batch and device instead.
| NewtonVisualizationMarkers, | ||
| _NewtonMarkerSpec, | ||
| ) | ||
| def test_marker_render_handles_none_normals_and_uvs(monkeypatch, marker_registry): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Mark both marker tests kitless
Both changed marker tests run without Isaac Sim but lack pytest.mark.kitless, so kitless CI omits their registration and batching checks. Mark both tests.
| @pytest.mark.parametrize("device", test_devices()) | ||
| def test_marker_batches_preserve_selected_instances(device, marker_registry): | ||
| """Shared geometry keeps each prototype's color/scale, filtering, and live tensor updates.""" | ||
| from contextlib import nullcontext |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Move nullcontext to module imports
nullcontext is a standard-library import with no deferred dependency. Move it to the module-level import group required by the contribution guide.
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (2), Compatibility and deprecation (1), Style consistency (3). Other reviewed categories look good.
- PR description: Qualify the title because frame widths still read host scalars; make the reported CPU timing reproducible with baseline/candidate revisions, command, hardware, backend, environment count, warmup, and the measured preparation/readback metric.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: extend NewtonVisualizationMarkers.init for geometry grouping and render for shared preparation and viewer-local registration; allocate transforms and colors only for mesh batches and use equality for singleton masks. No source modules were added, and no existing layer needs extraction. Keep the essential selection, appearance, visibility, and viewer submission flow in the existing backend. Scope is cohesive; no split recommended.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: construction-time appearance caches suppress fallback color and scale edits previously read during rendering, without a functional bridge or deprecation cycle; restore render-time resolution.
- Implementation: Implementation looks good.
- Style consistency: Prototype collections and changed test returns lack required annotations, while nullcontext is imported locally without a runtime dependency reason; add concrete annotations and move the import to module scope.
- Test quality: Test quality looks good.
Significant concerns. Posted 6 inline findings.
Automated review; human maintainers own approval decisions.
| name: _infer_newton_marker_cfg(marker_cfg) for name, marker_cfg in cfg.markers.items() | ||
| } | ||
| self._marker_batches: list[tuple[str, _NewtonMarkerSpec, list[int]]] = [] | ||
| self._prototype_scales = [] |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate prototype collections
The new scale and color attributes lack concrete collection annotations, unlike the adjacent batch field. Annotate both as lists of three-component tuples so their stored layout is explicit.
| self._prototype_colors = [] | ||
| for index, (name, marker_cfg) in enumerate(cfg.markers.items()): | ||
| spec = _infer_newton_marker_cfg(marker_cfg) | ||
| self._prototype_scales.append(spec.scale or _extract_scale_hint(marker_cfg)) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Keep prototype appearance updates live
Fallback scales and colors previously came from marker.cfg on each render. Storing them at construction makes later configuration edits invisible. Resolve those values at render time to preserve the existing behavior.
| num_markers = translations.shape[0] | ||
| if orientations is None: | ||
| orientations = translations.new_tensor((0.0, 0.0, 0.0, 1.0)).expand(num_markers, -1) | ||
| xforms = wp.from_torch(torch.cat((translations, orientations), dim=1).float(), dtype=wp.transform).to( |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Skip unused frame-only instance buffers
Frame-only groups construct and transfer transforms and prototype colors on every render, although log_lines consumes neither. Prepare those buffers only when a mesh batch exists.
| viewer.log_lines(batch_name, None, None, None, hidden=True) | ||
| continue | ||
|
|
||
| shown = torch.isin(indices, indices.new_tensor(prototype_indices)) |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Use equality for singleton batches
Each ungrouped prototype allocates an index tensor and runs torch.isin for a single value. Use the previous equality mask for singleton batches; retain membership testing for shared batches.
| NewtonVisualizationMarkers, | ||
| _NewtonMarkerSpec, | ||
| ) | ||
| def test_marker_render_handles_none_normals_and_uvs(monkeypatch, marker_registry): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate new test returns
Both changed test functions omit the required -> None return annotation. Add it to this test and test_marker_batches_preserve_selected_instances.
| @pytest.mark.parametrize("device", test_devices()) | ||
| def test_marker_batches_preserve_selected_instances(device, marker_registry): | ||
| """Shared geometry keeps each prototype's color/scale, filtering, and live tensor updates.""" | ||
| from contextlib import nullcontext |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Move nullcontext to module imports
nullcontext is an unconditional standard-library import. Keeping it inside the test violates the module-level import rule; move it to the standard-library import group.
[Medium impact] The PR appears safe to merge. SummaryThis PR reduces repeated work when drawing Newton markers while preserving separate prototype colors in Rerun.
All three previous findings are addressed. No new actionable issues were found. Reviews (3) · Last reviewed commit: "Merge branch 'main' into codex/newton-ma..." · Reviewed by Greptile |
| colors = translations.new_tensor(self._prototype_colors)[selected] | ||
| colors = wp.from_torch(colors.float().contiguous(), dtype=wp.vec3).to(device) |
There was a problem hiding this comment.
Rerun marker colors become wrong. Every batch now receives colors selected from all markers, including markers belonging to other shapes.
NewtonViewerRerun uses the first color as the batch appearance and compares only that color before dropping later updates. A red sphere followed by a green box therefore gives both batches the sphere's first color; merging differently colored prototypes has the same problem. Keep separate color batches for Rerun, or update its color support before sending these mixed arrays.
| if not self._marker_batches or (translations is None and not hidden): | ||
| return |
There was a problem hiding this comment.
Existing marker tests now fail. The new render path requires
_marker_batches, _prototype_scales, and _prototype_colors, but _make_newton_marker_for_render in test_visualization_markers.py still builds objects with only the old fields. Its render tests now raise AttributeError here. That file also calls the removed _ensure_mesh_registered method. Update those fixtures and checks alongside the tests changed in this PR.
| self._prototype_scales.append(spec.scale or _extract_scale_hint(marker_cfg)) | ||
| self._prototype_colors.append(spec.color or _extract_color(marker_cfg)) | ||
| if spec.renderer == "none": | ||
| logger.warning("Unsupported Newton marker prototype '%s' in '%s'; skipping.", name, self.group_id) | ||
| continue |
There was a problem hiding this comment.
Unsupported prototypes can crash construction.
_extract_color now runs before the unsupported-prototype check and directly reads visual_material. The marker configuration accepts any SpawnerCfg, but types such as GroundPlaneCfg have no such field. These previously reached the warning-and-skip path; now they stop the entire marker group from being created. Use a fallback color for skipped prototypes while keeping their index slots.
|
Thanks for this, batching shared geometry and dropping the CPU round trip are both good wins. A few things I'd like to see fixed before merging, plus a suggestion for simplifying the batching logic. Issues
Suggestion: resolve prototypes into lookup tablesThe batching state (list of # __init__
self._batches: list[tuple[str, str, _NewtonMarkerSpec, int]] = [] # (batch, mesh, spec, first prototype)
batch_ids: dict[object, int] = {}
proto_batch, proto_style = [], []
for p, (name, marker_cfg) in enumerate(cfg.markers.items()):
spec = _infer_newton_marker_cfg(marker_cfg)
if spec.renderer == "none":
logger.warning("Unsupported Newton marker prototype '%s' in '%s'; skipping.", name, self.group_id)
proto_batch.append(-1)
proto_style.append((0.0,) * 6)
continue
# Primitives with identical params share a batch; frames and USD meshes stay separate.
key = (spec.mesh_type, tuple(spec.mesh_params.items())) if spec.mesh_params else name
if key not in batch_ids:
batch_ids[key] = len(self._batches)
self._batches.append((f"{self.group_id}/{name}", f"{self.group_id}/meshes/{name}", spec, p))
proto_batch.append(batch_ids[key])
proto_style.append((*(spec.scale or _extract_scale_hint(marker_cfg)), *(spec.color or _extract_color(marker_cfg))))
self._proto_batch = torch.tensor(proto_batch)
self._proto_style = torch.tensor(proto_style) # [P, 6]: scale xyz, rgb# render(), after the existing env selection
if not self.visible or count == 0:
return self._hide(viewer)
if translations is None:
return
n = translations.shape[0]
if orientations is None:
orientations = translations.new_tensor((0.0, 0.0, 0.0, 1.0)).expand(n, -1)
self._proto_batch = self._proto_batch.to(translations.device) # no-op after the first frame
self._proto_style = self._proto_style.to(translations)
proto = translations.new_zeros(n, dtype=torch.long) if marker_indices is None else marker_indices.long()
inst_batch = self._proto_batch[proto]
inst_scale, inst_color = self._proto_style[proto].split(3, dim=1)
if scales is not None:
inst_scale = inst_scale * scales
xforms = _to_warp(torch.cat((translations, orientations), dim=1), wp.transform, viewer.device)
stream = wp.stream_from_torch(translations.device) if translations.is_cuda else None
with wp.ScopedStream(stream, sync_exit=True):
for b, (batch, mesh, spec, p0) in enumerate(self._batches):
shown = (inst_batch == b).unsqueeze(1)
batch_scale = inst_scale * shown
if spec.renderer == "frame":
lines = _build_frame_lines(translations, orientations, batch_scale)
viewer.log_lines(batch, *(_to_warp(t, wp.vec3, viewer.device) for t in lines), width=spec.line_width, hidden=False)
continue
self._register_mesh(viewer, mesh, spec)
# Hidden slots take this batch's color, since Rerun uses colors[0] for the whole batch.
colors = torch.where(shown, inst_color, self._proto_style[p0, 3:])
materials = translations.new_tensor((0.0, 0.0, 0.0, float(spec.texture is not None))).expand(n, -1)
viewer.log_instances(
batch,
mesh,
xforms,
_to_warp(batch_scale, wp.vec3, viewer.device),
_to_warp(colors, wp.vec3, viewer.device),
_to_warp(materials, wp.vec4, viewer.device),
hidden=False,
)
What this gets us:
Smaller things
|
|
run-ci |
Description
Newton markers currently rebuild and upload a full instance batch for every prototype—even when only color or scale differs. This change groups shared primitive geometry and passes Torch tensors directly to Warp, eliminating repeated transform construction and CPU round trips.
The focused marker-preparation timing in Improvements is historical, measured at
8879a84ada25641fd3846f8598bf458c61f94090. The environment throughput below was rerun on November 18 with the revised implementation ata94c2e11bef41e0b2219cdc10d55883b0e3faa3c.Improvements
Measured with 2,560 markers and four color prototypes sharing one geometry, after five warmup renders and over 100 measured renders:
The timing measures marker preparation and sink readback, not browser FPS. Instance counts are structural counts, not measured network bytes. GPU timings are omitted because another playback process was using the GPU.
Existing-environment throughput
Fresh measurements from November 18, 2026. Values are median vector-environment updates/s (range) across six accepted 15-second intervals per variant, from two fresh processes. These measure full simulation and visualization with a connected Viser WebSocket client and uncapped visualization, not browser FPS.
8879a84ad)a94c2e11b)For each scene, run order was original → Newton only → previous PR → revised PR → revised PR → previous PR → Newton only → original. Each process warms up for 10 seconds, then collects three 15-second intervals. The GPU monitor samples compute processes once per second; no competing process was observed on the measured GPU during any of the 48 accepted intervals. Two additional intervals were discarded because of observed contention. Other work could run on the shared host or the other GPU; CPU resources were not reserved.
All runs used RTX 5090 GPU 1, Torch 2.11.0+cu130 with 24 Torch CPU threads, stock Viser 1.1.1, and the same Newton physics runtime (
9ca16d498). Original uses the unoptimized viewer and markers. Newton only adds the viewer changes from Newton #5380, backported onto that fixed runtime; the previous/revised PR variants also select their respective marker implementations. Runtime source hashes confirm that only the three Newton viewer files differ. The same Viser line-width API adjustment is applied to both runtimes.KUKA uses zero actions, seed 42, and goal markers. ANYmal uses checkpoint
6b7z0qkf/model_18800.pt, seed 43, and the full 8×8 terrain. Scene source was frozen from the current local scene checkout and used unchanged for all variants; that checkout has evolved since the historical experiment. These fresh results replace the earlier throughput numbers and are not pooled with them.What changed
torch.isin, or int64 index copy.Production changes for the complete PR: 101 additions, 136 deletions (net −35) in the existing marker module. No new production modules or dependency changes. Batch layouts remain owned by this backend; Rerun's separate layout represents its actual appearance limitation.
Newton viewer cleanup remains in the independent Newton #5380. No Viser patch is required. Direct Torch-to-Warp handoff removes per-instance CPU/NumPy copies;
sync_exit=Truestill provides stream synchronization.Validation
uv run python -m pytest source/isaaclab_visualizers/test/test_newton_adapter.py -k marker -q: 7 passed, including CPU and CUDA/non-default-stream coverage.uv run python -m pytest source/isaaclab/test/markers/test_visualization_markers.py -k newton_marker -q: 12 passed.GroundPlaneCfg, invalid indices, selected environments, in-place updates, visibility, viewer-local registration, and Rerun's separate color batches. It forbids per-rendertorch.isin.GroundPlaneCfg; disabling Rerun's separate layout or invalid-index masking independently makes the updated test fail.ModelBuilder.add_usd() got an unexpected keyword argument 'allow_unsafe_torch_checkpoints'in the installed Newton runtime. The same isolated camera test fails at the previous PR head with that error.uv run isaaclab --format, changelog gate against the PR base, andgit diff --checkpass.Type of change
Checklist