From c5b84e5decc4d52f2af9d4a42a0db2d39e381741 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 13:56:14 -0500 Subject: [PATCH 1/8] docs: freeze MuJoCo Warp benchmark protocol --- docs/notes/mujoco-warp-benchmark-protocol.md | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/notes/mujoco-warp-benchmark-protocol.md diff --git a/docs/notes/mujoco-warp-benchmark-protocol.md b/docs/notes/mujoco-warp-benchmark-protocol.md new file mode 100644 index 0000000..fde0abd --- /dev/null +++ b/docs/notes/mujoco-warp-benchmark-protocol.md @@ -0,0 +1,23 @@ +# MuJoCo Warp offline benchmark protocol + +This protocol freezes the inputs and decision rules for [#22](https://github.com/ThePyProgrammer/argus/issues/22). The reference is classic MuJoCo 3.6.0. The candidate is MuJoCo Warp 3.6.0 with Warp 1.12.0, explicitly on CUDA. This experiment covers latency, throughput, and compatibility. Camera qualification, production migration and live exploration are outside its scope. + +## Inputs + +- Dashboard uses the flat Go2 scene, two robots with the dashboard spawn helper, 320 × 240, five physics substeps per frame and the default 200-step settle. With the viewer and perception disabled, replay a fixed stand and low-speed alternating-turn command schedule. Save the exact XML/assets, compiled model, post-settle integration state, actuator inputs per substep, and CPU-forwarded transforms per frame. Render comparisons use those CPU-forwarded transforms. A separate stepping comparison starts at the saved integration state and applies the same actuator inputs. +- E33 uses the original stationary recipe and four fixed variants from `tests/slam/test_free_space_camera_campaign.py` at 1920 × 1440. Run the original classic owned-capture and refusal checks. Compare both outputs for camera A on all five variants, and use both cameras for timing the full-resolution baseline. Use the calibrated off-axis pixel geometry and known probe depths to distinguish axial depth and ray range. Record raw and cleaned depth, invalid-mask differences, clipping and group behavior, visible-control response and current free-space refusal. Renderer outputs here are offline observations with no source qualification. +- Save each run in a fresh directory below `outputs/exploration-planning/mujoco-warp-benchmark/`. Save package versions, revision, platform, power mode, observed OpenGL vendor/renderer or explicit Warp CUDA device, IDs, dimensions, timestamps, clipping settings and raw timing rows. Keep exact host hardware and driver details with local diagnostics. + +## Cases and scoring + +| Case | Work | Comparison | +| --- | --- | --- | +| Dashboard bridge | Classic bridge step, both cameras and both ICP/SLAM consumers | Default classic adapter, then the requested discrete adapter if verified | +| Dashboard frozen render | CPU-forwarded transforms, two RGB-D readbacks and depth cleaning, one world | Same input and two consumers on classic and Warp | +| Dashboard replay | Five physics steps per iteration on recorded controls | Classic CPU and Warp CUDA, compare trajectory and contact geometry pairs separately | +| Dashboard batch | One, 8, 32, and 64 worlds, two cameras per world | Report physics and render throughput separately. Identify the classic worker count and stage comparability | +| Stationary E33 | Owned classic capture, Warp ray-cast comparison on the same states, render batch starting at one world | Only try larger batches when their minimum output allocation fits with at least 1 GiB device headroom. Stop on allocation failure or inadequate measured headroom | + +Start each timed run in a separate process. Report process/workload startup separately, then discard 20 warm-up iterations and collect at least 100 timed iterations in each of three runs per runnable case. Report median and p95 in milliseconds and for batch cases completed world-steps/s and camera frames/s. Capture-to-consumer spans the arrival of the frozen state at the capture harness through the second consumer. Log classic render, readback, and metric-depth conversion as one combined measurement where the public renderer combines them. Synchronize Warp work around timed boundaries and measure transfer, unpacking and depth cleaning separately where supported. Record contact/constraint capacity exceedances and device-wide VRAM before startup and sampled during each run, with measurement limits. Preserve the first omitted or failed batch and its reason. + +Require at least 10% lower median capture-to-consumer latency and no p95 regression against the fastest verified classic adapter in paired single-world runs, or at least 10% higher batch throughput against a comparable classic case. A positive feasibility recommendation additionally requires at least 1 GiB measured device headroom and no unresolved overflows. Missing device verification, memory, comparators, or sufficient repetitions leave the corresponding recommendation inconclusive. Camera differences must be reported even when timing passes. From 3dca5ff27e5d0b767e920eb815a7f9ab8d1f929f Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 14:03:41 -0500 Subject: [PATCH 2/8] feat: add offline MuJoCo Warp benchmark --- docs/provenance/catalogue.json | 64 +++ scripts/benchmark_mujoco_warp.py | 671 ++++++++++++++++++++++++++++ tests/test_mujoco_warp_benchmark.py | 53 +++ 3 files changed, 788 insertions(+) create mode 100644 scripts/benchmark_mujoco_warp.py create mode 100644 tests/test_mujoco_warp_benchmark.py diff --git a/docs/provenance/catalogue.json b/docs/provenance/catalogue.json index 8a477e9..e95d56f 100644 --- a/docs/provenance/catalogue.json +++ b/docs/provenance/catalogue.json @@ -641,6 +641,17 @@ "read": "Query returns distances and vertex indices; missing neighbours use self.n. E35 uses selected in-range indices only, not returned distances or nearest accuracy, and recomputes exact nominal geometry distances.", "verified_on": "2026-12-03", "verification": "Official versioned API and installed1.17.1 docstring inspected. Acceleration is a witness selector, not a geometry/source bound or native correctness certificate." + }, + "mujoco-warp-360": { + "title": "MuJoCo Warp 3.6.0 implementation and API", + "authors": "Google DeepMind and NVIDIA", + "year": 2026, + "kind": "upstream implementation", + "url": "https://github.com/google-deepmind/mujoco_warp/tree/v3.6.0", + "peer_reviewed": false, + "read": "Pinned source for CUDA physics, BVH ray casting, axial-depth output and packed colour.", + "verified_on": "2026-12-04", + "verification": "Official v3.6.0 sources, versioned API and installed render, buffer, broadphase and data-transfer implementation reviewed. This does not validate the native kernels or certify output equivalence." } }, "components": [ @@ -4244,6 +4255,59 @@ "sensor-budget" ], "lineage": "Project-authored complete finite nominal volume-cover and transfer argument closing the missing upper component from E34. Conditional analytical model geometry only; all actual-source/world/motion premises remain separate." + }, + { + "id": "mujoco-warp-offline-benchmark", + "title": "Offline classic MuJoCo and Warp comparison", + "basis": "upstream", + "runtime": "offline", + "summary": "Separately compare synchronized CUDA ray-cast readback on frozen CPU-forwarded rigid states and CUDA stepping under frozen actuator inputs. Time the existing classic bridge and the owned E33 capture, and measure diagnostic pixels, contact pairs, host consumption and sampled device-wide memory.", + "files": [ + "scripts/benchmark_mujoco_warp.py", + "tests/test_mujoco_warp_benchmark.py" + ], + "depends_on": [ + "gl-audit" + ], + "assumptions": "MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection.", + "differences": "Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight.", + "evidence": [ + "tests/test_mujoco_warp_benchmark.py", + "tests/slam/test_free_space_camera_campaign.py", + "docs/notes/mujoco-warp-benchmark-protocol.md" + ], + "gaps": "Desktop device allocation peaks are sampled, not certified. Camera probes, contact counts, geometry-pair differences and observed latency do not certify general renderer or physics equivalence.", + "entrypoints": [ + { + "file": "scripts/benchmark_mujoco_warp.py", + "symbol": "main" + }, + { + "file": "scripts/benchmark_mujoco_warp.py", + "symbol": "timed_frames" + }, + { + "file": "scripts/benchmark_mujoco_warp.py", + "symbol": "step_replay" + }, + { + "file": "scripts/benchmark_mujoco_warp.py", + "symbol": "e33" + } + ], + "references": [ + { + "source": "mujoco-warp-360", + "relation": "upstream", + "note": "Pinned put_model, put_data, step, render and buffer layout." + }, + { + "source": "mujoco-renderer-360", + "relation": "upstream", + "note": "Classic GLFW camera readback returns metric axis depth; the public renderer bundles draw and transfer." + } + ], + "lineage": "Pinned upstream implementations with project-defined fixture replay, timing and compatibility scoring." } ] } diff --git a/scripts/benchmark_mujoco_warp.py b/scripts/benchmark_mujoco_warp.py new file mode 100644 index 0000000..92fe900 --- /dev/null +++ b/scripts/benchmark_mujoco_warp.py @@ -0,0 +1,671 @@ +"""Offline, opt-in MuJoCo 3.6.0 / Warp 3.6.0 comparison for issue #22.""" + +from __future__ import annotations + +import argparse +from contextlib import ExitStack, contextmanager +from dataclasses import asdict +from datetime import datetime, timezone +import importlib.metadata +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +from time import perf_counter +import traceback +from types import SimpleNamespace +from unittest.mock import patch + +PROCESS_START = perf_counter() +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import mujoco +import numpy as np + +from src.bridge.depth import clean_metric_depth +from src.bridge.gl_readback_audit import inspect_classic_gl +from src.bridge.multi_bridge import MultiRobotBridge +from src.bridge.multi_robot_config import MultiRobotConfig +from src.bridge.platforms import create_platform +from src.bridge.platforms.types import RobotCommand +from src.bridge.scene_builder import build_multi_robot_scene +from src.bridge.sensor_types import SensorFrame, fixed_camera_mount +from src.coordination.spawn import generate_robot_ids, generate_spawn_positions + +STATE = mujoco.mjtState.mjSTATE_INTEGRATION +RENDER_FIELDS = ("geom_xpos", "geom_xmat", "cam_xpos", "cam_xmat", "light_xpos", "light_xdir") +GPU_FIELDS = "index,pci.bus_id,timestamp,name,driver_version,memory.total,memory.used,memory.free" +MIB = 1 << 20 + + +def save_json(path, data): + path.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n", encoding="utf-8") + + +def request(command): + try: + result = subprocess.run(command, capture_output=True, text=True, timeout=10) + return dict(exit_code=result.returncode, stdout=result.stdout.strip(), stderr=result.stderr.strip()) + except (OSError, subprocess.TimeoutExpired) as error: + return dict(error=str(error)) + + +@contextmanager +def record_vram(output, report): + prefix = ["nvidia-smi", f"--query-gpu={GPU_FIELDS}", "--format=csv,noheader,nounits"] + report["vram"] = dict(before=request(prefix), sample_interval_ms=100, scope="device-wide WDDM/NVML samples") + sampler = None + samples = output / "vram.csv" + with samples.open("wb") as log: + try: + sampler = subprocess.Popen([*prefix, "--loop-ms=100"], stdout=log, stderr=subprocess.STDOUT) + except OSError as error: + report["vram"]["sampler_error"] = str(error) + try: + yield + finally: + if sampler is not None: + sampler.terminate() + sampler.wait(timeout=10) + devices = {} + for line in samples.read_text(encoding="utf-8", errors="replace").splitlines(): + fields = [value.strip() for value in line.split(",")] + if len(fields) != 8: + continue + index, pci, _, _, _, _, used, free = fields + if not (used.isdigit() and free.isdigit()): + continue + row = devices.setdefault(index, dict(pci_bus_id=pci, peak_used_mib=0, min_free_mib=int(free), samples=0)) + row["peak_used_mib"] = max(row["peak_used_mib"], int(used)) + row["min_free_mib"] = min(row["min_free_mib"], int(free)) + row["samples"] += 1 + report["vram"]["devices"] = devices + + +def dashboard(model_factory=None): + platform = create_platform("go2") + ids = generate_robot_ids(2) + config = MultiRobotConfig(robot_ids=ids, spawn_positions=generate_spawn_positions( + ids, "flat", spawn_height=platform.metadata.spawn_height), launch_viewer=False) + return MultiRobotBridge(config, model_factory=model_factory), config, platform + + +def command_frame(bridge, index): + phase = (index // 20) % 3 + for robot, sign in zip(bridge.robot_ids, (1, -1)): + command = RobotCommand.stand() if phase == 0 else RobotCommand.velocity( + (0.15, 0.0), sign * (0.2 if phase == 1 else -0.2)) + bridge.set_command(robot, command) + + +def freeze_dashboard(output, count): + _, config, platform = dashboard() + xml, assets = build_multi_robot_scene(platform, config.spawn_positions) + model = mujoco.MjModel.from_xml_string(xml, assets) + bridge, _, _ = dashboard(lambda: model) + (output / "scene.xml").write_text(xml, encoding="utf-8") + for name, raw in assets.items(): + target = output / "assets" / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + mujoco.mj_saveModel(model, str(output / "scene.mjb"), None) + states, controls, physics_times = [], [], [] + with patch.object(mujoco, "Renderer", lambda *args, **kwargs: SimpleNamespace(close=lambda: None)): + with patch.object(bridge, "_capture_frame", lambda robot: None): + try: + bridge.start() + data = bridge.mj_data + state = np.empty(mujoco.mj_stateSize(model, STATE)) + mujoco.mj_getState(model, data, state, STATE) + states.append(state.copy()) + bridge.add_physics_step_observer( + lambda m, d, start, end: (controls.append(d.ctrl.copy()), physics_times.append(end))) + for index in range(count): + command_frame(bridge, index) + bridge.step() + mujoco.mj_getState(model, data, state, STATE) + states.append(state.copy()) + np.savez_compressed(output / "replay.npz", states=states, controls=controls, physics_times=physics_times) + save_json(output / "input.json", dict(config=asdict(config), camera_ids=bridge._cam_ids, + boot_elapsed_s=bridge.settled_sim_time, frame_dt_s=bridge.frame_dt, frames=count, + qpos_starts={rid: int(start) for rid, start in bridge._qpos_starts.items()}, command="20-frame phases: stand, forward + turn, forward + reversed turn")) + finally: + bridge.stop() + + +def camera_settings(model, cameras, width, height): + return dict(width=width, height=height, ids=cameras, + names=[model.cam(i).name for i in cameras], + fovy_deg=model.cam_fovy[cameras].tolist(), + near_m=float(model.vis.map.znear * model.stat.extent), + far_m=float(model.vis.map.zfar * model.stat.extent), + classic_geom_groups=np.flatnonzero(mujoco.MjvOption().geomgroup).tolist(), + classic_offscreen_samples=int(model.vis.quality.offsamples)) + + +def verify_frame(rgb, depth, width, height, actual_s, expected_s): + if rgb.shape != (height, width, 3) or rgb.dtype != np.uint8: + raise ValueError("Unexpected RGB shape or dtype") + if depth.shape != (height, width) or depth.dtype != np.float32: + raise ValueError("Unexpected metric depth shape or dtype") + if not np.isfinite([actual_s, expected_s]).all() or abs(actual_s - expected_s) > 1e-10: + raise ValueError(f"Simulation timestamp {actual_s} differs from {expected_s}") + + +def verify_gl(renderer, expected, report): + audit = inspect_classic_gl(renderer).snapshot() + report.setdefault("opengl", []).append(audit) + if audit["status"] != "observed" or not audit["context_restored"]: + raise RuntimeError(f"OpenGL adapter unverified: {audit['reason']}") + actual = audit["facts"]["vendor"] + " " + audit["facts"]["renderer"] + if expected.casefold() not in actual.casefold(): + raise RuntimeError(f"Requested OpenGL adapter {expected!r}; observed {actual!r}") + + +def unpack_rgb(packed): + return np.stack((packed >> 16, packed >> 8, packed), axis=-1).astype(np.uint8) + + +class ClassicCamera: + def __init__(self, model, cameras, width, height, expected, report): + self.settings = camera_settings(model, cameras, width, height) + self.cameras = cameras + self.stack = ExitStack() + try: + self.renderer = self.stack.enter_context(mujoco.Renderer(model, height=height, width=width)) + # The full audit needs a rendered frame to query the effective projection. + initial = mujoco.MjData(model) + mujoco.mj_forward(model, initial) + self.renderer.update_scene(initial, camera=self.cameras[0]) + self.renderer.render() + verify_gl(self.renderer, expected, report) + except BaseException: + self.stack.close() + raise + + def capture(self, data, worlds): + before = perf_counter() + images = [] + for _ in range(worlds): + row = [] + for camera in self.cameras: + self.renderer.update_scene(data, camera=camera) + rgb = self.renderer.render() + self.renderer.enable_depth_rendering() + try: + depth = self.renderer.render() + finally: + self.renderer.disable_depth_rendering() + row.append((rgb, depth)) + images.append(row) + return images, dict(render_readback_conversion_ms=(perf_counter() - before) * 1e3) + + def close(self): + self.stack.close() + + +class WarpCamera: + def __init__(self, model, data, cameras, width, height, worlds, report): + import mujoco_warp as mjw + import warp as wp + + if model.nflex: + raise ValueError("Frozen camera upload only supports rigid scenes") + self.w = wp + self.mjw = mjw + self.device = wp.get_device("cuda:0") + report["cuda"] = dict(device=str(self.device), name=self.device.name, + warp_lang=wp.__version__) + self.model = mjw.put_model(model) + self.data = mjw.put_data(model, data, nworld=worlds) + settings = camera_settings(model, cameras, width, height) + active = [camera in cameras for camera in range(model.ncam)] + self.rc = mjw.create_render_context(model, nworld=worlds, cam_res=(width, height), + render_rgb=True, render_depth=True, use_textures=True, use_shadows=False, + enabled_geom_groups=settings["classic_geom_groups"], cam_active=active) + self.targets = [(field, getattr(self.data, field)) for field in RENDER_FIELDS] + self.width, self.height = width, height + rgb_offsets, depth_offsets = self.rc.rgb_adr.numpy(), self.rc.depth_adr.numpy() + self.offsets = list(zip(rgb_offsets, depth_offsets)) + if len(self.offsets) != len(cameras) or any(min(a, b) < 0 for a, b in self.offsets): + raise ValueError("Unexpected active-camera buffer layout") + report["warp_render"] = dict(enabled_geom_groups=settings["classic_geom_groups"], + textures=True, shadows=False, buffer_offsets=self.offsets) + report["warp_render"]["buffer_offsets"] = [[int(a), int(b)] for a, b in self.offsets] + + def capture(self, data, worlds): + before = perf_counter() + for field, target in self.targets: + values = np.repeat(getattr(data, field)[None, ...].astype(np.float32), worlds, axis=0) + if field.endswith("_xmat"): + values = values.reshape((*target.shape, 3, 3)) + source = self.w.array(values, dtype=target.dtype, device="cpu") + self.w.copy(target, source) + self.w.synchronize_device(self.device) + uploaded = perf_counter() + self.mjw.refit_bvh(self.model, self.data, self.rc) + self.mjw.render(self.model, self.data, self.rc) + self.w.synchronize_device(self.device) + rendered = perf_counter() + packed, depth = self.rc.rgb_data.numpy(), self.rc.depth_data.numpy() + self.w.synchronize_device(self.device) + read = perf_counter() + size = self.width * self.height + rgb = unpack_rgb(packed) + shape = self.height, self.width + images = [[(rgb[world, a:a + size].reshape((*shape, 3)), + depth[world, b:b + size].reshape(shape)) for a, b in self.offsets] + for world in range(worlds)] + return images, dict(upload_ms=(uploaded - before) * 1e3, render_ms=(rendered - uploaded) * 1e3, + readback_ms=(read - rendered) * 1e3, unpack_ms=(perf_counter() - read) * 1e3) + + def close(self): + self.w.synchronize_device(self.device) + + +def make_consumers(model, cameras, width, height): + from src.bridge.sensor_types import CameraIntrinsics + from src.slam.slam_pipeline import SLAMPipeline + from src.slam.uncertainty import AUTHORED_SEED + + return [SLAMPipeline(CameraIntrinsics.from_fov(width, height, float(model.cam_fovy[i])), + initial_pose=np.eye(4), initial_pose_provenance=AUTHORED_SEED) for i in cameras] + + +def summarize(rows): + if not rows: + return {} + return {key: dict(median=float(np.median(values)), p95=float(np.percentile(values, 95))) + for key in rows[0] if key.endswith("_ms") + for values in [[row[key] for row in rows]]} + + +def timed_frames(args, report, output, model, data, cameras, width, height, advance, *, consume): + settings = camera_settings(model, cameras, width, height) + report["camera"] = settings + if args.backend == "warp": + import warp as wp + scope = wp.ScopedDevice("cuda:0") + else: + scope = ExitStack() + with scope, ExitStack() as stack: + if args.backend == "warp": + camera = WarpCamera(model, data, cameras, width, height, args.worlds, report) + else: + camera = ClassicCamera(model, cameras, width, height, args.expect_gl, report) + report["classic_workers"] = 1 + stack.callback(camera.close) + consumers = make_consumers(model, cameras, width, height) if consume else [] + for index in range(args.warmup + args.iterations): + expected = advance(index) + before = perf_counter() + images, row = camera.capture(data, args.worlds) + captured = perf_counter() + cleaned = [[(rgb, clean_metric_depth(depth, settings["far_m"])) + for rgb, depth in world] for world in images] + ready = perf_counter() + for world in cleaned: + for rgb, depth in world: + verify_frame(rgb, depth, width, height, float(data.time), expected) + validation_done = perf_counter() + for camera_id, consumer, (rgb, depth) in zip(cameras, consumers, cleaned[0]): + consumer.process_frame(SensorFrame(rgb=rgb, depth=depth, ground_truth_pose=None, + sim_time=float(data.time), body_from_camera=fixed_camera_mount( + model, camera_id, int(model.cam_bodyid[camera_id])))) + finished = perf_counter() + if index == 0: + report["startup_ms_through_first_frame"] = (finished - PROCESS_START) * 1e3 + np.savez_compressed(output / "first-frame.npz", rgb=[p[0] for p in images[0]], + raw_depth=[p[1] for p in images[0]], depth=[p[1] for p in cleaned[0]], + sim_time=data.time) + if index >= args.warmup: + row.update(iteration=index, sim_time_s=float(data.time), depth_clean_ms=(ready - captured) * 1e3, + capture_ms=(ready - before) * 1e3, frame_validation_ms=(validation_done - ready) * 1e3) + if consume: + row.update(slam_ms=(finished - validation_done) * 1e3, + capture_to_consumer_ms=(ready - before + finished - validation_done) * 1e3) + report["rows"].append(row) + total_s = sum(row["capture_ms"] for row in report["rows"]) / 1e3 + report["camera_frames_per_s"] = args.worlds * len(cameras) * len(report["rows"]) / total_s + + +def frozen_render(args, report, output): + meta = json.loads((args.inputs / "input.json").read_text(encoding="utf-8")) + model = mujoco.MjModel.from_binary_path(str(args.inputs / "scene.mjb")) + data = mujoco.MjData(model) + with np.load(args.inputs / "replay.npz") as saved: + states = saved["states"] + mujoco.mj_setState(model, data, states[0], STATE) + mujoco.mj_forward(model, data) + + def advance(index): + mujoco.mj_setState(model, data, states[index + 1], STATE) + mujoco.mj_forward(model, data) + return meta["boot_elapsed_s"] + (index + 1) * meta["frame_dt_s"] + + timed_frames(args, report, output, model, data, list(meta["camera_ids"].values()), + *meta["config"]["resolution"], advance, consume=args.worlds == 1) + + +def bridge_run(args, report, output): + import src.bridge.multi_bridge as bridge_module + from src.slam.slam_pipeline import SLAMPipeline + + bridge, config, _ = dashboard() + robot_ids = bridge.robot_ids + width, height = config.resolution + stages = {} + + def measure(key, function): + def measured(*args, **kwargs): + start = perf_counter() + try: + return function(*args, **kwargs) + finally: + stages[key] = stages.get(key, 0.0) + (perf_counter() - start) * 1e3 + return measured + + with ExitStack() as stack: + stack.callback(bridge.stop) + for obj, name, stage in ( + (mujoco, "mj_step", "physics_ms"), + (mujoco, "mj_forward", "forward_ms"), + (bridge, "_capture_frame", "capture_ms"), + (bridge_module, "clean_metric_depth", "depth_clean_ms"), + ): + stack.enter_context(patch.object(obj, name, measure(stage, getattr(obj, name)))) + bridge.start() + for renderer in bridge._renderers.values(): + verify_gl(renderer, args.expect_gl, report) + report["camera"] = camera_settings(bridge.mj_model, list(bridge._cam_ids.values()), width, height) + consumers = {rid: SLAMPipeline(bridge.camera_intrinsics(rid)) for rid in robot_ids} + report["startup_ms_through_first_frame"] = (perf_counter() - PROCESS_START) * 1e3 + for index in range(args.warmup + args.iterations): + command_frame(bridge, index) + stages.clear() + start = perf_counter() + frames = bridge.step() + captured = perf_counter() + expected = (index + 1) * bridge.frame_dt + for frame in frames.values(): + verify_frame(frame.rgb, frame.depth, width, height, frame.sim_time, expected) + if abs(bridge.mj_data.time - bridge.settled_sim_time - expected) > 1e-10: + raise ValueError("Bridge frame timestamp and MuJoCo clock diverged") + validated = perf_counter() + for rid, consumer in consumers.items(): + consumer.process_frame(frames[rid]) + finished = perf_counter() + if index >= args.warmup: + report["rows"].append(dict(stages, iteration=index, sim_time_s=expected, + capture_and_pack_without_clean_ms=stages["capture_ms"] - stages["depth_clean_ms"], + bridge_ms=(captured - start) * 1e3, slam_ms=(finished - validated) * 1e3, + capture_to_consumer_ms=stages["capture_ms"] + (finished - validated) * 1e3, + step_to_consumer_ms=(captured - start + finished - validated) * 1e3)) + + +def contact_pairs(data): + return sorted({tuple(sorted((int(c.geom1), int(c.geom2)))) for c in data.contact[:data.ncon]}) + + +def step_replay(args, report): + config = json.loads((args.inputs / "input.json").read_text(encoding="utf-8")) + substeps = config["config"]["sim_steps_per_frame"] + model = mujoco.MjModel.from_binary_path(str(args.inputs / "scene.mjb")) + with np.load(args.inputs / "replay.npz") as saved: + initial, controls = saved["states"][0], saved["controls"] + data = mujoco.MjData(model) + mujoco.mj_setState(model, data, initial, STATE) + mujoco.mj_forward(model, data) + steps = args.warmup + args.iterations + if len(controls) < steps * substeps: + raise ValueError("The frozen input does not contain enough actuator controls") + starts = list(config["qpos_starts"].values()) + report["trajectory"] = [] + with ExitStack() as stack: + if args.backend == "warp": + import mujoco_warp as mjw + import warp as wp + + device = wp.get_device("cuda:0") + stack.enter_context(wp.ScopedDevice(device)) + report["cuda"] = dict(device=str(device), name=device.name) + wm = mjw.put_model(model) + wd = mjw.put_data(model, data, nworld=args.worlds) + control_buffer = wp.empty(wd.ctrl.shape, dtype=wp.float32, device="cpu") + report["capacity"] = dict(contacts=wd.naconmax, ccd_contacts=wd.naccdmax, + constraints_per_world=wd.njmax) + report["capacity_exceedances"] = 0 + + def step(control): + control_buffer.numpy()[:] = control + wp.copy(wd.ctrl, control_buffer) + mjw.step(wm, wd) + wp.synchronize_device(device) + + def counters(): + ncon = int(wd.nacon.numpy()[0]) + nefc = int(np.max(wd.nefc.numpy())) + candidates = int(wd.ncollision.numpy()[0]) + report["capacity_exceedances"] += int(ncon > wd.naconmax or nefc > wd.njmax or candidates > wd.naconmax) + return dict(contacts=ncon, constraints=nefc, collision_candidates=candidates) + + def observe(): + if args.worlds == 1: + mjw.get_data_into(data, model, wd) + + # Outside stage timing. Read every substep so a transient overflow remains visible. + report["overflow_sampling"] = "every physics substep; counters read outside physics timing" + else: + worlds = [data] + [mujoco.MjData(model) for _ in range(args.worlds - 1)] + for world in worlds[1:]: + mujoco.mj_setState(model, world, initial, STATE) + mujoco.mj_forward(model, world) + report["classic_workers"] = 1 + + def step(control): + for world in worlds: + world.ctrl[:] = control + mujoco.mj_step(model, world) + + def counters(): + return dict(contacts=max(world.ncon for world in worlds), + constraints=max(world.nefc for world in worlds)) + + def observe(): + pass + + for index in range(steps): + physics_ms = 0.0 + telemetry = [] + for control in controls[index * substeps:(index + 1) * substeps]: + before = perf_counter() + step(control) + physics_ms += (perf_counter() - before) * 1e3 + counts = counters() + if args.worlds == 1: + observe() + counts["contact_pairs"] = contact_pairs(data) + telemetry.append(counts) + if index == 0: + report["startup_ms_through_first_physics_interval"] = (perf_counter() - PROCESS_START) * 1e3 + if args.worlds == 1: + expected = config["boot_elapsed_s"] + (index + 1) * config["frame_dt_s"] + tolerance_s = 5e-5 if args.backend == "warp" else 1e-10 + if abs(data.time - expected) > tolerance_s: + raise ValueError(f"Unexpected replay clock: {data.time} for {expected}, tolerance {tolerance_s}s") + report["trajectory"].append(dict(iteration=index, sim_time_s=float(data.time), + qpos=data.qpos.tolist(), root_positions_m=[data.qpos[s:s + 3].tolist() for s in starts], + substeps=telemetry)) + if index >= args.warmup: + report["rows"].append(dict(iteration=index, physics_control_upload_ms=physics_ms, substeps=telemetry)) + seconds = sum(row["physics_control_upload_ms"] for row in report["rows"]) / 1e3 + report["world_steps_per_s"] = args.worlds * len(report["rows"]) * substeps / seconds + + +def e33(args, report, output): + from src.bridge.capture_session import OwnedCaptureSession + from src.slam.empirical_map_contract import assess_empirical_map_request + from src.slam.scene_rgbd_reference import CAMERAS, HEIGHT, WIDTH + from tests.slam.test_free_space_camera_campaign import recipes + + cases, assets, _, _ = recipes() + for name, raw in assets.items(): + target = output / "assets" / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + for name, xml, _ in cases: + (output / (name + ".xml")).write_text(xml, encoding="utf-8") + if args.case == "e33-timed": + name, xml, _ = cases[0] + model = mujoco.MjModel.from_xml_string(xml, assets) + data = mujoco.MjData(model) + mujoco.mj_forward(model, data) + cameras = [model.cam(name).id for _, name in CAMERAS.values()] + timed_frames(args, report, output, model, data, cameras, WIDTH, HEIGHT, lambda index: 0.0, consume=False) + if args.backend == "classic" and args.worlds == 1: + rows = report["rows"] + with OwnedCaptureSession(xml, CAMERAS, assets=assets, width=WIDTH, height=HEIGHT) as owner: + for index in range(args.warmup + args.iterations): + before = perf_counter() + for camera in CAMERAS: + result = owner.capture(camera) + verify_frame(result.rgb, result.depth, WIDTH, HEIGHT, result.simulation_time_s, 0.0) + if index == 0: + for renderer in owner._renderers.values(): + verify_gl(renderer, args.expect_gl, report) + report["owned_startup_ms"] = (perf_counter() - before) * 1e3 + if index >= args.warmup: + rows[index - args.warmup]["owned_capture_pair_ms"] = (perf_counter() - before) * 1e3 + return + + report["cases"] = [] + report["cameras_per_world"] = 1 + baseline = None + if args.backend == "warp": + import warp as wp + scope = wp.ScopedDevice("cuda:0") + else: + scope = ExitStack() + with scope: + for name, xml, probe in cases: + model = mujoco.MjModel.from_xml_string(xml, assets) + data = mujoco.MjData(model) + mujoco.mj_forward(model, data) + cameras = [model.cam("robot_a_cam").id] + settings = camera_settings(model, cameras, WIDTH, HEIGHT) + if args.backend == "warp": + camera = WarpCamera(model, data, cameras, WIDTH, HEIGHT, 1, report) + else: + camera = ClassicCamera(model, cameras, WIDTH, HEIGHT, args.expect_gl, report) + try: + worlds, _ = camera.capture(data, 1) + finally: + camera.close() + rgb, raw = worlds[0][0] + depth = clean_metric_depth(raw, settings["far_m"]) + verify_frame(rgb, depth, WIDTH, HEIGHT, data.time, 0.0) + np.savez_compressed(output / (name + ".npz"), rgb=rgb, raw_depth=raw, depth=depth) + if baseline is None: + baseline = depth.copy() + samples = {} + if probe is not None: + fx = HEIGHT / (2 * np.tan(np.deg2rad(settings["fovy_deg"][0]) / 2)) + for dx, dy in ((0, 0), (11, 11)): + axial = probe["reference_front_axial_m"] + factor = np.sqrt(1 + ((dx + .5) / fx) ** 2 + ((dy + .5) / fx) ** 2) + samples[f"{dx},{dy}"] = dict(observed_m=float(depth[HEIGHT // 2 + dy, WIDTH // 2 + dx]), + probe_axial_m=axial, probe_range_m=float(axial * factor)) + row = dict(case=name, settings=settings, sim_time_s=float(data.time), + valid_pixels=int(np.count_nonzero(depth)), changed_depth_pixels=int(np.count_nonzero(depth != baseline)), + center_depth_m=float(depth[HEIGHT // 2, WIDTH // 2]), probe_pixel_samples=samples) + if args.reference is not None: + with np.load(args.reference / (name + ".npz")) as reference: + classic = reference["depth"] + both = (classic > 0) & (depth > 0) + delta = np.abs(depth[both] - classic[both]) + row.update(valid_mask_disagreements=int(np.count_nonzero((classic > 0) != (depth > 0))), + shared_valid_pixels=int(delta.size), shared_valid_delta_m_p95=float(np.percentile(delta, 95)) if delta.size else None, + shared_valid_delta_m_max=float(np.max(delta)) if delta.size else None, + rgb_pixel_difference=int(np.count_nonzero(np.any(reference["rgb"] != rgb, axis=-1)))) + # The actual evidence consumer explicitly rejects a raw RGB-D observation. + refusal = assess_empirical_map_request(depth, expected_identity=None, + now_s=float(data.time), operation="free_sensing_volume") + row["free_space_preflight"] = refusal.snapshot() + if refusal.status != "refused": + raise RuntimeError("The empirical free-space consumer accepted a raw depth image") + report["cases"].append(row) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("case", choices=("freeze", "bridge", "render", "step", "e33", "e33-timed")) + parser.add_argument("output", type=Path) + parser.add_argument("--inputs", type=Path) + parser.add_argument("--reference", type=Path) + parser.add_argument("--backend", choices=("classic", "warp"), default="classic") + parser.add_argument("--expect-gl", default="", help="Required case-insensitive substring of observed GL strings") + parser.add_argument("--worlds", type=int, default=1) + parser.add_argument("--iterations", type=int, default=100) + parser.add_argument("--warmup", type=int, default=20) + args = parser.parse_args() + if args.worlds < 1 or args.iterations < 1 or args.warmup < 0: + parser.error("requires positive world and timed iteration counts, and nonnegative warm-up") + if args.case in ("render", "step") and args.inputs is None: + parser.error("requires --inputs from the freeze case") + if args.case in ("bridge", "freeze", "e33") and args.worlds != 1: + parser.error("this case is single-world") + if args.case in ("bridge", "freeze") and args.backend != "classic": + parser.error("this case uses classic MuJoCo") + + output = args.output + output.mkdir(parents=True, exist_ok=False) + report = dict(case=args.case, backend=args.backend, worlds=args.worlds, warmup=args.warmup, + planned_iterations=args.iterations, rows=[], start=datetime.now(timezone.utc).isoformat(), + argv=sys.argv, python=sys.version, platform=platform.platform(), + revision=request(["git", "rev-parse", "HEAD"]), + installed={d.metadata["Name"]: d.version for d in importlib.metadata.distributions()}, + thread_env={name: os.environ.get(name) for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MUJOCO_GL")}) + if shutil.which("powercfg"): + report["power_scheme"] = request(["powercfg", "/getactivescheme"]) + with record_vram(output, report): + try: + if mujoco.__version__ != "3.6.0": + raise RuntimeError("Protocol requires classic MuJoCo 3.6.0") + if args.backend == "warp": + for package, version in (("mujoco-warp", "3.6.0"), ("warp-lang", "1.12.0")): + if importlib.metadata.version(package) != version: + raise RuntimeError(f"Protocol requires {package} {version}") + before = report["vram"]["before"].get("stdout", "").splitlines() + if args.case == "e33-timed" and args.worlds > 1: + needed_mib = 8 * 1920 * 1440 * 2 * args.worlds / MIB + 1024 + if len(before) != 1 or not before[0].split(",")[-1].strip().isdigit(): + raise RuntimeError("Cannot verify VRAM headroom on the selected CUDA device") + if int(before[0].split(",")[-1]) < needed_mib: + raise RuntimeError(f"Insufficient VRAM headroom for output buffers: need at least {needed_mib:.1f} MiB free") + if args.case == "freeze": + freeze_dashboard(output, args.warmup + args.iterations) + elif args.case == "bridge": + bridge_run(args, report, output) + elif args.case == "render": + frozen_render(args, report, output) + elif args.case == "step": + step_replay(args, report) + else: + e33(args, report, output) + report["status"] = "completed" + except Exception: + report["status"] = "failed" + report["traceback"] = traceback.format_exc() + print(report["traceback"], file=sys.stderr) + report["stages"] = summarize(report["rows"]) + report["finish"] = datetime.now(timezone.utc).isoformat() + report["elapsed_s"] = perf_counter() - PROCESS_START + save_json(output / "report.json", report) + return int(report["status"] != "completed") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_mujoco_warp_benchmark.py b/tests/test_mujoco_warp_benchmark.py new file mode 100644 index 0000000..6abe2f8 --- /dev/null +++ b/tests/test_mujoco_warp_benchmark.py @@ -0,0 +1,53 @@ +"""Contracts of the offline harness without loading a GPU backend.""" + +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np + +from scripts.benchmark_mujoco_warp import unpack_rgb, verify_frame, verify_gl +from src.bridge.depth import clean_metric_depth +from src.slam.empirical_map_contract import assess_empirical_map_request + + +class BenchmarkContracts(unittest.TestCase): + def test_packed_rgb_order_and_axial_metres(self): + rgb = unpack_rgb(np.array([[0xFF123456, 0xFFAABBDD]], dtype=np.uint32)).reshape(1, 2, 3) + np.testing.assert_array_equal(rgb, [[[0x12, 0x34, 0x56], [0xAA, 0xBB, 0xDD]]]) + depth = clean_metric_depth(np.array([[0.249, 0.0]], dtype=np.float32), 25.) + np.testing.assert_array_equal(depth, np.array([[0.249, 0.0]], dtype=np.float32)) + verify_frame(rgb, depth, 2, 1, 0.25, 0.25) + with self.assertRaisesRegex(ValueError, "timestamp"): + verify_frame(rgb, depth, 2, 1, 250.0, 0.25) + with self.assertRaisesRegex(ValueError, "timestamp"): + verify_frame(rgb, depth, 2, 1, float("nan"), 0.25) + with self.assertRaisesRegex(ValueError, "shape"): + verify_frame(rgb, depth.T, 2, 1, 0.25, 0.25) + + def test_no_return_far_cutoff_and_free_space_refusal(self): + raw = np.array([[0, np.nan, np.inf, -1, 0.2, 19.7, 19.81, 20]], dtype=np.float32) + depth = clean_metric_depth(raw, 20.0) + np.testing.assert_array_equal(depth, np.array([[0, 0, 0, 0, 0.2, 19.7, 0, 0]], dtype=np.float32)) + refusal = assess_empirical_map_request(depth, expected_identity=None, now_s=0.0, + operation="free_sensing_volume") + self.assertEqual(refusal.status, "refused") + + def test_requested_gl_adapter_fails_closed(self): + report = {} + audit = dict(status="observed", context_restored=True, + facts=dict(vendor="Integrated vendor", renderer="Default adapter")) + with patch("scripts.benchmark_mujoco_warp.inspect_classic_gl", + return_value=SimpleNamespace(snapshot=lambda: audit)): + with self.assertRaisesRegex(RuntimeError, "Requested OpenGL adapter"): + verify_gl(object(), "discrete", report) + self.assertEqual(report["opengl"], [audit]) + audit = dict(status="unavailable", context_restored=False, reason="missing context") + with patch("scripts.benchmark_mujoco_warp.inspect_classic_gl", + return_value=SimpleNamespace(snapshot=lambda: audit)): + with self.assertRaisesRegex(RuntimeError, "adapter unverified"): + verify_gl(object(), "", report) + + +if __name__ == "__main__": + unittest.main() From 1865b9a126d137a9432942c57fbf6868a8316ac1 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 14:05:20 -0500 Subject: [PATCH 3/8] docs: record MuJoCo Warp provenance review --- docs/provenance/catalogue.md | 29 ++++++++++++++++++++++ docs/provenance/code-index.md | 45 +++++++++++++++++++++++++++++++++- docs/provenance/inventory.json | 10 ++++++++ docs/provenance/sources.md | 12 +++++++++ 4 files changed, 95 insertions(+), 1 deletion(-) diff --git a/docs/provenance/catalogue.md b/docs/provenance/catalogue.md index e4802eb..fc2df9a 100644 --- a/docs/provenance/catalogue.md +++ b/docs/provenance/catalogue.md @@ -91,6 +91,7 @@ Traceability review is not independent peer review or a correctness certificate. | [Static existing-camera free-space premise inventory and fixed Go2 diagnostics](#free-space-source-audit) | project | offline | | [Nominal same-body collision/rendered-mesh association and protrusion diagnostics](#collision-visual-correspondence) | project | offline | | [Complete conditional nominal collision-volume to mesh-surface covers](#collision-volume-cover) | project | offline | +| [Offline classic MuJoCo and Warp comparison](#mujoco-warp-offline-benchmark) | upstream | offline | @@ -2088,3 +2089,31 @@ Cover entire nominal collision primitive bounding boxes with complete closed cel - Existing evidence: [docs/notes/exploration-collision-volume-cover.md](../../docs/notes/exploration-collision-volume-cover.md) - Conceptual inputs: [collision-visual-correspondence](#collision-visual-correspondence), [sensor-budget](#sensor-budget) - Files: [`src/slam/collision_volume_cover.py`](../../src/slam/collision_volume_cover.py), [`tests/slam/test_collision_volume_cover.py`](../../tests/slam/test_collision_volume_cover.py), [`tests/slam/test_collision_volume_model_audit.py`](../../tests/slam/test_collision_volume_model_audit.py) + + + +## Offline classic MuJoCo and Warp comparison + +Separately compare synchronized CUDA ray-cast readback on frozen CPU-forwarded rigid states and CUDA stepping under frozen actuator inputs. Time the existing classic bridge and the owned E33 capture, and measure diagnostic pixels, contact pairs, host consumption and sampled device-wide memory. + +**Classification:** upstream; **wiring:** offline. + +**Historical lineage:** Pinned upstream implementations with project-defined fixture replay, timing and compatibility scoring. + +**Implementation differences:** Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. + +**Assumptions:** MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection. + +**Remaining evidence:** Desktop device allocation peaks are sampled, not certified. Camera probes, contact counts, geometry-pair differences and observed latency do not certify general renderer or physics equivalence. + +- Code: [`main`](../../scripts/benchmark_mujoco_warp.py#L602) +- Code: [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L286) +- Code: [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L413) +- Code: [`e33`](../../scripts/benchmark_mujoco_warp.py#L508) +- Reading: [mujoco-warp-360](sources.md#mujoco-warp-360) (upstream): Pinned put_model, put_data, step, render and buffer layout. +- Reading: [mujoco-renderer-360](sources.md#mujoco-renderer-360) (upstream): Classic GLFW camera readback returns metric axis depth; the public renderer bundles draw and transfer. +- Existing evidence: [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) +- Existing evidence: [tests/slam/test_free_space_camera_campaign.py](../../tests/slam/test_free_space_camera_campaign.py) +- Existing evidence: [docs/notes/mujoco-warp-benchmark-protocol.md](../../docs/notes/mujoco-warp-benchmark-protocol.md) +- Conceptual inputs: [gl-audit](#gl-audit) +- Files: [`scripts/benchmark_mujoco_warp.py`](../../scripts/benchmark_mujoco_warp.py), [`tests/test_mujoco_warp_benchmark.py`](../../tests/test_mujoco_warp_benchmark.py) diff --git a/docs/provenance/code-index.md b/docs/provenance/code-index.md index 8071f9b..c9bf65c 100644 --- a/docs/provenance/code-index.md +++ b/docs/provenance/code-index.md @@ -2,7 +2,7 @@ Generated; file ownership is explicit in `catalogue.json`. Python classes and their methods and top-level functions are indexed using AST without importing the runtime. Nested local functions and non-Python symbols are not individually indexed; their entire files are hashed. -592 files. Digests normalize CRLF to LF and preserve every other byte. Tests, fixtures, manifests, and UI files are classified as such, not counted as research algorithms. +594 files. Digests normalize CRLF to LF and preserve every other byte. Tests, fixtures, manifests, and UI files are classified as such, not counted as research algorithms. ## Simulation, sensor capture, depth sanitation and IMU @@ -7628,3 +7628,46 @@ Owner: [collision-volume-cover](catalogue.md#collision-volume-cover). - [`exact_affine`](../../tests/slam/test_collision_volume_model_audit.py#L31) - [`independent_certificate_checks`](../../tests/slam/test_collision_volume_model_audit.py#L35) - [`test_both_qualified_models_have_complete_checkable_nominal_volume_components`](../../tests/slam/test_collision_volume_model_audit.py#L104) + +## Offline classic MuJoCo and Warp comparison + +### [scripts/benchmark_mujoco_warp.py](../../scripts/benchmark_mujoco_warp.py) + +Owner: [mujoco-warp-offline-benchmark](catalogue.md#mujoco-warp-offline-benchmark). + +- [`save_json`](../../scripts/benchmark_mujoco_warp.py#L44) +- [`request`](../../scripts/benchmark_mujoco_warp.py#L48) +- [`record_vram`](../../scripts/benchmark_mujoco_warp.py#L57) +- [`dashboard`](../../scripts/benchmark_mujoco_warp.py#L88) +- [`command_frame`](../../scripts/benchmark_mujoco_warp.py#L96) +- [`freeze_dashboard`](../../scripts/benchmark_mujoco_warp.py#L104) +- [`camera_settings`](../../scripts/benchmark_mujoco_warp.py#L139) +- [`verify_frame`](../../scripts/benchmark_mujoco_warp.py#L149) +- [`verify_gl`](../../scripts/benchmark_mujoco_warp.py#L158) +- [`unpack_rgb`](../../scripts/benchmark_mujoco_warp.py#L168) +- [`ClassicCamera`](../../scripts/benchmark_mujoco_warp.py#L172) +- [`ClassicCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L173) +- [`ClassicCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L189) +- [`ClassicCamera.close`](../../scripts/benchmark_mujoco_warp.py#L206) +- [`WarpCamera`](../../scripts/benchmark_mujoco_warp.py#L210) +- [`WarpCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L211) +- [`WarpCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L239) +- [`WarpCamera.close`](../../scripts/benchmark_mujoco_warp.py#L265) +- [`make_consumers`](../../scripts/benchmark_mujoco_warp.py#L269) +- [`summarize`](../../scripts/benchmark_mujoco_warp.py#L278) +- [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L286) +- [`frozen_render`](../../scripts/benchmark_mujoco_warp.py#L335) +- [`bridge_run`](../../scripts/benchmark_mujoco_warp.py#L353) +- [`contact_pairs`](../../scripts/benchmark_mujoco_warp.py#L409) +- [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L413) +- [`e33`](../../scripts/benchmark_mujoco_warp.py#L508) +- [`main`](../../scripts/benchmark_mujoco_warp.py#L602) + +### [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) + +Owner: [mujoco-warp-offline-benchmark](catalogue.md#mujoco-warp-offline-benchmark). + +- [`BenchmarkContracts`](../../tests/test_mujoco_warp_benchmark.py#L14) +- [`BenchmarkContracts.test_packed_rgb_order_and_axial_metres`](../../tests/test_mujoco_warp_benchmark.py#L15) +- [`BenchmarkContracts.test_no_return_far_cutoff_and_free_space_refusal`](../../tests/test_mujoco_warp_benchmark.py#L28) +- [`BenchmarkContracts.test_requested_gl_adapter_fails_closed`](../../tests/test_mujoco_warp_benchmark.py#L36) diff --git a/docs/provenance/inventory.json b/docs/provenance/inventory.json index 8abc252..0329f9a 100644 --- a/docs/provenance/inventory.json +++ b/docs/provenance/inventory.json @@ -706,6 +706,11 @@ "sha256": "85cf6ff9cf3ebe325c7377b6c3dd50df40c6a0825c30346d7b08adb253afffd2", "reviewed_revision": "1f4dafa403dae96833b220d7619d563b44ef6c92" }, + "scripts/benchmark_mujoco_warp.py": { + "component": "mujoco-warp-offline-benchmark", + "sha256": "8e1ceec801259d2c4778c72ce936111a60e6d00e0818630dc605e96cd2858304", + "reviewed_revision": "02408f121eb5ae7c9de3c0be1ba57ad788c23cf9" + }, "scripts/boxer_worker.py": { "component": "boxer-detection", "sha256": "1233fdd6694c6e0ca0f0c8970738a16edb14a71e2d288c508380fa342b607992", @@ -2876,6 +2881,11 @@ "sha256": "0c18eda888b72e1fdf023d1f3dfbdfe11fbf120f57fc083de030a3476797c0cc", "reviewed_revision": "1f4dafa403dae96833b220d7619d563b44ef6c92" }, + "tests/test_mujoco_warp_benchmark.py": { + "component": "mujoco-warp-offline-benchmark", + "sha256": "8c36162e0dbc480c0367a2e32f17a260a2fabc01275ef091930a252009823dd8", + "reviewed_revision": "02408f121eb5ae7c9de3c0be1ba57ad788c23cf9" + }, "tests/test_provenance.py": { "component": "verification", "sha256": "a842a541b88cceb9b9a16714ad46a0550d08593ad02feacec81dd5e56cbcd2cc", diff --git a/docs/provenance/sources.md b/docs/provenance/sources.md index fa76e17..454e091 100644 --- a/docs/provenance/sources.md +++ b/docs/provenance/sources.md @@ -697,3 +697,15 @@ SciPy maintainers (1.17 API / installed1.17.1). Official software API documentat **Read for:** Query returns distances and vertex indices; missing neighbours use self.n. E35 uses selected in-range indices only, not returned distances or nearest accuracy, and recomputes exact nominal geometry distances. **Verification:** Official versioned API and installed1.17.1 docstring inspected. Acceleration is a witness selector, not a geometry/source bound or native correctness certificate. Checked 2026-12-03. + + + +## mujoco-warp-360: MuJoCo Warp 3.6.0 implementation and API + +Google DeepMind and NVIDIA (2026). upstream implementation. **Peer-reviewed paper:** not established / not applicable. + +[Primary source](https://github.com/google-deepmind/mujoco_warp/tree/v3.6.0). + +**Read for:** Pinned source for CUDA physics, BVH ray casting, axial-depth output and packed colour. + +**Verification:** Official v3.6.0 sources, versioned API and installed render, buffer, broadphase and data-transfer implementation reviewed. This does not validate the native kernels or certify output equivalence. Checked 2026-12-04. From a779688b99fcf6b7d43bb6435122641cfabc7df3 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 14:07:20 -0500 Subject: [PATCH 4/8] fix: verify OpenGL adapter independently of E33 audit --- docs/provenance/catalogue.json | 2 +- scripts/benchmark_mujoco_warp.py | 31 +++++++++++++++++++++++++++-- tests/test_mujoco_warp_benchmark.py | 13 +++++++++++- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/docs/provenance/catalogue.json b/docs/provenance/catalogue.json index e95d56f..f9305bb 100644 --- a/docs/provenance/catalogue.json +++ b/docs/provenance/catalogue.json @@ -4270,7 +4270,7 @@ "gl-audit" ], "assumptions": "MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection.", - "differences": "Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight.", + "differences": "Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit.", "evidence": [ "tests/test_mujoco_warp_benchmark.py", "tests/slam/test_free_space_camera_campaign.py", diff --git a/scripts/benchmark_mujoco_warp.py b/scripts/benchmark_mujoco_warp.py index 92fe900..6dcec40 100644 --- a/scripts/benchmark_mujoco_warp.py +++ b/scripts/benchmark_mujoco_warp.py @@ -155,12 +155,39 @@ def verify_frame(rgb, depth, width, height, actual_s, expected_s): raise ValueError(f"Simulation timestamp {actual_s} differs from {expected_s}") +def read_gl_identity(renderer): + """Verify the timing adapter even if the E33 compatibility audit refuses.""" + import ctypes + + import glfw + from OpenGL import GL + + owner = renderer._gl_context + previous = glfw.get_current_context() + try: + owner.make_current() + identity = {} + for name in ("vendor", "renderer", "version"): + value = GL.glGetString(getattr(GL, "GL_" + name.upper())) + if not value: + raise RuntimeError(f"Missing OpenGL {name}") + identity[name] = value.decode("utf-8", errors="replace") + finally: + glfw.make_context_current(previous) + if ctypes.cast(glfw.get_current_context(), ctypes.c_void_p).value != ctypes.cast(previous, ctypes.c_void_p).value: + raise RuntimeError("OpenGL context restoration failed") + return identity + + def verify_gl(renderer, expected, report): audit = inspect_classic_gl(renderer).snapshot() report.setdefault("opengl", []).append(audit) - if audit["status"] != "observed" or not audit["context_restored"]: + if not audit["context_restored"]: raise RuntimeError(f"OpenGL adapter unverified: {audit['reason']}") - actual = audit["facts"]["vendor"] + " " + audit["facts"]["renderer"] + identity = audit["facts"] if audit["status"] == "observed" else read_gl_identity(renderer) + actual = identity["vendor"] + " " + identity["renderer"] + report.setdefault("opengl_identity", []).append( + {key: identity[key] for key in ("vendor", "renderer", "version")}) if expected.casefold() not in actual.casefold(): raise RuntimeError(f"Requested OpenGL adapter {expected!r}; observed {actual!r}") diff --git a/tests/test_mujoco_warp_benchmark.py b/tests/test_mujoco_warp_benchmark.py index 6abe2f8..c391a7c 100644 --- a/tests/test_mujoco_warp_benchmark.py +++ b/tests/test_mujoco_warp_benchmark.py @@ -36,7 +36,7 @@ def test_no_return_far_cutoff_and_free_space_refusal(self): def test_requested_gl_adapter_fails_closed(self): report = {} audit = dict(status="observed", context_restored=True, - facts=dict(vendor="Integrated vendor", renderer="Default adapter")) + facts=dict(vendor="Integrated vendor", renderer="Default adapter", version="4.6")) with patch("scripts.benchmark_mujoco_warp.inspect_classic_gl", return_value=SimpleNamespace(snapshot=lambda: audit)): with self.assertRaisesRegex(RuntimeError, "Requested OpenGL adapter"): @@ -48,6 +48,17 @@ def test_requested_gl_adapter_fails_closed(self): with self.assertRaisesRegex(RuntimeError, "adapter unverified"): verify_gl(object(), "", report) + def test_renderer_identity_independent_of_compatibility_audit(self): + report = {} + audit = dict(status="unavailable", context_restored=True, reason="profile unsupported") + identity = dict(vendor="discrete vendor", renderer="GPU", version="4.6") + with patch("scripts.benchmark_mujoco_warp.inspect_classic_gl", + return_value=SimpleNamespace(snapshot=lambda: audit)): + with patch("scripts.benchmark_mujoco_warp.read_gl_identity", return_value=identity): + verify_gl(object(), "discrete", report) + self.assertEqual(report["opengl_identity"], [identity]) + self.assertEqual(report["opengl"], [audit]) + if __name__ == "__main__": unittest.main() From b8c4ee9d1859e03bf76e6bed1cf21be9694ca4f2 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 14:08:12 -0500 Subject: [PATCH 5/8] docs: refresh reviewed benchmark provenance --- docs/provenance/catalogue.md | 10 ++++----- docs/provenance/code-index.md | 40 ++++++++++++++++++---------------- docs/provenance/inventory.json | 8 +++---- 3 files changed, 30 insertions(+), 28 deletions(-) diff --git a/docs/provenance/catalogue.md b/docs/provenance/catalogue.md index fc2df9a..4f13aba 100644 --- a/docs/provenance/catalogue.md +++ b/docs/provenance/catalogue.md @@ -2100,16 +2100,16 @@ Separately compare synchronized CUDA ray-cast readback on frozen CPU-forwarded r **Historical lineage:** Pinned upstream implementations with project-defined fixture replay, timing and compatibility scoring. -**Implementation differences:** Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. +**Implementation differences:** Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit. **Assumptions:** MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection. **Remaining evidence:** Desktop device allocation peaks are sampled, not certified. Camera probes, contact counts, geometry-pair differences and observed latency do not certify general renderer or physics equivalence. -- Code: [`main`](../../scripts/benchmark_mujoco_warp.py#L602) -- Code: [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L286) -- Code: [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L413) -- Code: [`e33`](../../scripts/benchmark_mujoco_warp.py#L508) +- Code: [`main`](../../scripts/benchmark_mujoco_warp.py#L629) +- Code: [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L313) +- Code: [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L440) +- Code: [`e33`](../../scripts/benchmark_mujoco_warp.py#L535) - Reading: [mujoco-warp-360](sources.md#mujoco-warp-360) (upstream): Pinned put_model, put_data, step, render and buffer layout. - Reading: [mujoco-renderer-360](sources.md#mujoco-renderer-360) (upstream): Classic GLFW camera readback returns metric axis depth; the public renderer bundles draw and transfer. - Existing evidence: [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) diff --git a/docs/provenance/code-index.md b/docs/provenance/code-index.md index c9bf65c..1b855d2 100644 --- a/docs/provenance/code-index.md +++ b/docs/provenance/code-index.md @@ -7643,25 +7643,26 @@ Owner: [mujoco-warp-offline-benchmark](catalogue.md#mujoco-warp-offline-benchmar - [`freeze_dashboard`](../../scripts/benchmark_mujoco_warp.py#L104) - [`camera_settings`](../../scripts/benchmark_mujoco_warp.py#L139) - [`verify_frame`](../../scripts/benchmark_mujoco_warp.py#L149) -- [`verify_gl`](../../scripts/benchmark_mujoco_warp.py#L158) -- [`unpack_rgb`](../../scripts/benchmark_mujoco_warp.py#L168) -- [`ClassicCamera`](../../scripts/benchmark_mujoco_warp.py#L172) -- [`ClassicCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L173) -- [`ClassicCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L189) -- [`ClassicCamera.close`](../../scripts/benchmark_mujoco_warp.py#L206) -- [`WarpCamera`](../../scripts/benchmark_mujoco_warp.py#L210) -- [`WarpCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L211) -- [`WarpCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L239) -- [`WarpCamera.close`](../../scripts/benchmark_mujoco_warp.py#L265) -- [`make_consumers`](../../scripts/benchmark_mujoco_warp.py#L269) -- [`summarize`](../../scripts/benchmark_mujoco_warp.py#L278) -- [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L286) -- [`frozen_render`](../../scripts/benchmark_mujoco_warp.py#L335) -- [`bridge_run`](../../scripts/benchmark_mujoco_warp.py#L353) -- [`contact_pairs`](../../scripts/benchmark_mujoco_warp.py#L409) -- [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L413) -- [`e33`](../../scripts/benchmark_mujoco_warp.py#L508) -- [`main`](../../scripts/benchmark_mujoco_warp.py#L602) +- [`read_gl_identity`](../../scripts/benchmark_mujoco_warp.py#L158) +- [`verify_gl`](../../scripts/benchmark_mujoco_warp.py#L182) +- [`unpack_rgb`](../../scripts/benchmark_mujoco_warp.py#L195) +- [`ClassicCamera`](../../scripts/benchmark_mujoco_warp.py#L199) +- [`ClassicCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L200) +- [`ClassicCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L216) +- [`ClassicCamera.close`](../../scripts/benchmark_mujoco_warp.py#L233) +- [`WarpCamera`](../../scripts/benchmark_mujoco_warp.py#L237) +- [`WarpCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L238) +- [`WarpCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L266) +- [`WarpCamera.close`](../../scripts/benchmark_mujoco_warp.py#L292) +- [`make_consumers`](../../scripts/benchmark_mujoco_warp.py#L296) +- [`summarize`](../../scripts/benchmark_mujoco_warp.py#L305) +- [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L313) +- [`frozen_render`](../../scripts/benchmark_mujoco_warp.py#L362) +- [`bridge_run`](../../scripts/benchmark_mujoco_warp.py#L380) +- [`contact_pairs`](../../scripts/benchmark_mujoco_warp.py#L436) +- [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L440) +- [`e33`](../../scripts/benchmark_mujoco_warp.py#L535) +- [`main`](../../scripts/benchmark_mujoco_warp.py#L629) ### [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) @@ -7671,3 +7672,4 @@ Owner: [mujoco-warp-offline-benchmark](catalogue.md#mujoco-warp-offline-benchmar - [`BenchmarkContracts.test_packed_rgb_order_and_axial_metres`](../../tests/test_mujoco_warp_benchmark.py#L15) - [`BenchmarkContracts.test_no_return_far_cutoff_and_free_space_refusal`](../../tests/test_mujoco_warp_benchmark.py#L28) - [`BenchmarkContracts.test_requested_gl_adapter_fails_closed`](../../tests/test_mujoco_warp_benchmark.py#L36) +- [`BenchmarkContracts.test_renderer_identity_independent_of_compatibility_audit`](../../tests/test_mujoco_warp_benchmark.py#L51) diff --git a/docs/provenance/inventory.json b/docs/provenance/inventory.json index 0329f9a..4c89f50 100644 --- a/docs/provenance/inventory.json +++ b/docs/provenance/inventory.json @@ -708,8 +708,8 @@ }, "scripts/benchmark_mujoco_warp.py": { "component": "mujoco-warp-offline-benchmark", - "sha256": "8e1ceec801259d2c4778c72ce936111a60e6d00e0818630dc605e96cd2858304", - "reviewed_revision": "02408f121eb5ae7c9de3c0be1ba57ad788c23cf9" + "sha256": "affc84dc396130178176b3f4790e3af55ab160bf8000bc58394ed0f3a8ccba73", + "reviewed_revision": "c5e605bfcd67dc912075769648357b64eedb9f1c" }, "scripts/boxer_worker.py": { "component": "boxer-detection", @@ -2883,8 +2883,8 @@ }, "tests/test_mujoco_warp_benchmark.py": { "component": "mujoco-warp-offline-benchmark", - "sha256": "8c36162e0dbc480c0367a2e32f17a260a2fabc01275ef091930a252009823dd8", - "reviewed_revision": "02408f121eb5ae7c9de3c0be1ba57ad788c23cf9" + "sha256": "f6e994752ff7372de5ce98098be639dc2129dff13191f05bf6d7bf05997c81b8", + "reviewed_revision": "c5e605bfcd67dc912075769648357b64eedb9f1c" }, "tests/test_provenance.py": { "component": "verification", From e3d4915e075bde8660c187ab5e3fd92c7e11460c Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 14:09:47 -0500 Subject: [PATCH 6/8] perf: unpack Warp RGB without full-size integer intermediates --- docs/provenance/catalogue.json | 2 +- scripts/benchmark_mujoco_warp.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/provenance/catalogue.json b/docs/provenance/catalogue.json index f9305bb..6ddb511 100644 --- a/docs/provenance/catalogue.json +++ b/docs/provenance/catalogue.json @@ -4270,7 +4270,7 @@ "gl-audit" ], "assumptions": "MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection.", - "differences": "Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit.", + "differences": "Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit. Host byte unpack preserves the tagged renderer's 0xAARRGGBB channel order.", "evidence": [ "tests/test_mujoco_warp_benchmark.py", "tests/slam/test_free_space_camera_campaign.py", diff --git a/scripts/benchmark_mujoco_warp.py b/scripts/benchmark_mujoco_warp.py index 6dcec40..6968cbe 100644 --- a/scripts/benchmark_mujoco_warp.py +++ b/scripts/benchmark_mujoco_warp.py @@ -193,7 +193,10 @@ def verify_gl(renderer, expected, report): def unpack_rgb(packed): - return np.stack((packed >> 16, packed >> 8, packed), axis=-1).astype(np.uint8) + # The pinned renderer writes 0xAARRGGBB. Reorder its little-endian + # bytes without building three full-size uint32 intermediate images. + pixel_bytes = np.ascontiguousarray(packed, dtype=" Date: Fri, 4 Dec 2026 14:10:21 -0500 Subject: [PATCH 7/8] docs: record reviewed packed RGB handling --- docs/provenance/catalogue.md | 10 +++++----- docs/provenance/code-index.md | 34 +++++++++++++++++----------------- docs/provenance/inventory.json | 6 +++--- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/provenance/catalogue.md b/docs/provenance/catalogue.md index 4f13aba..201177b 100644 --- a/docs/provenance/catalogue.md +++ b/docs/provenance/catalogue.md @@ -2100,16 +2100,16 @@ Separately compare synchronized CUDA ray-cast readback on frozen CPU-forwarded r **Historical lineage:** Pinned upstream implementations with project-defined fixture replay, timing and compatibility scoring. -**Implementation differences:** Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit. +**Implementation differences:** Warp uses float32, ray-cast visibility and packed readback. The benchmark times prescribed transfers and clean-up; its offline observations are not source-owned evidence and cannot pass the empirical free-space preflight. The GL adapter identity query is independent of the optional full compatibility-profile readback audit. Host byte unpack preserves the tagged renderer's 0xAARRGGBB channel order. **Assumptions:** MuJoCo and MuJoCo Warp 3.6.0, Warp 1.12.0, rigid scenes with fixed cameras, matching CPU-forwarded state for the render comparison, deterministic frozen inputs, observed classic GL context and explicit CUDA selection. **Remaining evidence:** Desktop device allocation peaks are sampled, not certified. Camera probes, contact counts, geometry-pair differences and observed latency do not certify general renderer or physics equivalence. -- Code: [`main`](../../scripts/benchmark_mujoco_warp.py#L629) -- Code: [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L313) -- Code: [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L440) -- Code: [`e33`](../../scripts/benchmark_mujoco_warp.py#L535) +- Code: [`main`](../../scripts/benchmark_mujoco_warp.py#L632) +- Code: [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L316) +- Code: [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L443) +- Code: [`e33`](../../scripts/benchmark_mujoco_warp.py#L538) - Reading: [mujoco-warp-360](sources.md#mujoco-warp-360) (upstream): Pinned put_model, put_data, step, render and buffer layout. - Reading: [mujoco-renderer-360](sources.md#mujoco-renderer-360) (upstream): Classic GLFW camera readback returns metric axis depth; the public renderer bundles draw and transfer. - Existing evidence: [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) diff --git a/docs/provenance/code-index.md b/docs/provenance/code-index.md index 1b855d2..be791c4 100644 --- a/docs/provenance/code-index.md +++ b/docs/provenance/code-index.md @@ -7646,23 +7646,23 @@ Owner: [mujoco-warp-offline-benchmark](catalogue.md#mujoco-warp-offline-benchmar - [`read_gl_identity`](../../scripts/benchmark_mujoco_warp.py#L158) - [`verify_gl`](../../scripts/benchmark_mujoco_warp.py#L182) - [`unpack_rgb`](../../scripts/benchmark_mujoco_warp.py#L195) -- [`ClassicCamera`](../../scripts/benchmark_mujoco_warp.py#L199) -- [`ClassicCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L200) -- [`ClassicCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L216) -- [`ClassicCamera.close`](../../scripts/benchmark_mujoco_warp.py#L233) -- [`WarpCamera`](../../scripts/benchmark_mujoco_warp.py#L237) -- [`WarpCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L238) -- [`WarpCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L266) -- [`WarpCamera.close`](../../scripts/benchmark_mujoco_warp.py#L292) -- [`make_consumers`](../../scripts/benchmark_mujoco_warp.py#L296) -- [`summarize`](../../scripts/benchmark_mujoco_warp.py#L305) -- [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L313) -- [`frozen_render`](../../scripts/benchmark_mujoco_warp.py#L362) -- [`bridge_run`](../../scripts/benchmark_mujoco_warp.py#L380) -- [`contact_pairs`](../../scripts/benchmark_mujoco_warp.py#L436) -- [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L440) -- [`e33`](../../scripts/benchmark_mujoco_warp.py#L535) -- [`main`](../../scripts/benchmark_mujoco_warp.py#L629) +- [`ClassicCamera`](../../scripts/benchmark_mujoco_warp.py#L202) +- [`ClassicCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L203) +- [`ClassicCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L219) +- [`ClassicCamera.close`](../../scripts/benchmark_mujoco_warp.py#L236) +- [`WarpCamera`](../../scripts/benchmark_mujoco_warp.py#L240) +- [`WarpCamera.__init__`](../../scripts/benchmark_mujoco_warp.py#L241) +- [`WarpCamera.capture`](../../scripts/benchmark_mujoco_warp.py#L269) +- [`WarpCamera.close`](../../scripts/benchmark_mujoco_warp.py#L295) +- [`make_consumers`](../../scripts/benchmark_mujoco_warp.py#L299) +- [`summarize`](../../scripts/benchmark_mujoco_warp.py#L308) +- [`timed_frames`](../../scripts/benchmark_mujoco_warp.py#L316) +- [`frozen_render`](../../scripts/benchmark_mujoco_warp.py#L365) +- [`bridge_run`](../../scripts/benchmark_mujoco_warp.py#L383) +- [`contact_pairs`](../../scripts/benchmark_mujoco_warp.py#L439) +- [`step_replay`](../../scripts/benchmark_mujoco_warp.py#L443) +- [`e33`](../../scripts/benchmark_mujoco_warp.py#L538) +- [`main`](../../scripts/benchmark_mujoco_warp.py#L632) ### [tests/test_mujoco_warp_benchmark.py](../../tests/test_mujoco_warp_benchmark.py) diff --git a/docs/provenance/inventory.json b/docs/provenance/inventory.json index 4c89f50..6e4a058 100644 --- a/docs/provenance/inventory.json +++ b/docs/provenance/inventory.json @@ -708,8 +708,8 @@ }, "scripts/benchmark_mujoco_warp.py": { "component": "mujoco-warp-offline-benchmark", - "sha256": "affc84dc396130178176b3f4790e3af55ab160bf8000bc58394ed0f3a8ccba73", - "reviewed_revision": "c5e605bfcd67dc912075769648357b64eedb9f1c" + "sha256": "abb24b091ebe2988075e289f8a8cb541ab5d405c41f74fb69eec858934f70c41", + "reviewed_revision": "c8960f4799bb22b63221b137da9be805fa6dcd47" }, "scripts/boxer_worker.py": { "component": "boxer-detection", @@ -2884,7 +2884,7 @@ "tests/test_mujoco_warp_benchmark.py": { "component": "mujoco-warp-offline-benchmark", "sha256": "f6e994752ff7372de5ce98098be639dc2129dff13191f05bf6d7bf05997c81b8", - "reviewed_revision": "c5e605bfcd67dc912075769648357b64eedb9f1c" + "reviewed_revision": "c8960f4799bb22b63221b137da9be805fa6dcd47" }, "tests/test_provenance.py": { "component": "verification", From 5c38d035cbd41beff4b036302bcf112abb65c744 Mon Sep 17 00:00:00 2001 From: Prannaya Gupta Date: Fri, 4 Dec 2026 17:38:56 -0500 Subject: [PATCH 8/8] docs: record MuJoCo Warp benchmark results --- docs/notes/mujoco-warp-benchmark-results.md | 132 ++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 docs/notes/mujoco-warp-benchmark-results.md diff --git a/docs/notes/mujoco-warp-benchmark-results.md b/docs/notes/mujoco-warp-benchmark-results.md new file mode 100644 index 0000000..605b868 --- /dev/null +++ b/docs/notes/mujoco-warp-benchmark-results.md @@ -0,0 +1,132 @@ +# MuJoCo Warp benchmark field notes + +[Issue #22](https://github.com/ThePyProgrammer/argus/issues/22) compares offline simulation and rendering workloads. The [frozen protocol](mujoco-warp-benchmark-protocol.md) defines the timing and headroom thresholds. Every timed case below uses separate processes, with 20 warm-up and 100 timed iterations per complete process. The work uses classic MuJoCo 3.6.0 and the opt-in MuJoCo Warp 3.6.0 / Warp 1.12.0 path. All runs were offline. + +## Stationary camera compatibility + +The original E33 model and its four fixture variants were rendered with camera A. The table uses the verified classic integrated adapter as the reference. Counts cover the full 1920 × 1440 frame. Depth error is measured where both engines returned valid depth. + +| E33 case | Classic changed depth pixels from its baseline | Warp changed depth pixels from its baseline | Valid-mask disagreements | Shared-valid depth error p95 / max (m) | RGB pixel disagreements | +| --- | ---: | ---: | ---: | ---: | ---: | +| Baseline | 0 | 0 | 3 | 0.000093 / 1.77649 | 2,646,046 | +| Near clip | 0 | 470,596 | 66,808 | 2.83769 / 9.63200 | 2,695,776 | +| Small feature | 0 | 0 | 3 | 0.000093 / 1.77649 | 2,646,046 | +| Excluded geometry | 0 | 0 | 3 | 0.000093 / 1.77649 | 2,646,046 | +| Visible control | 1,024 | 1,024 | 3 | 0.000093 / 1.77649 | 2,646,046 | + +For the visible control, the off-centre pixel at (+11, +11) read 0.24899954 m in classic and 0.24900016 m in Warp. Its authored axial depth is 0.24900000 m and its ray range is 0.24903114 m. The observed values match axial depth for this pixel. The near-clip probe was invisible to the classic camera and returned approximately 0.003 m at the centre in Warp. The configured classic near plane was 8 mm. Classic encoded no return near the far plane and Warp wrote zero. Cleaning yielded 416,425 classic and 416,426 Warp invalid baseline pixels. Against the discrete classic adapter, the baseline and visible-control shared-valid p95 difference was 0.00490 m. The near-clip case still had 66,808 validity disagreements. The current empirical consumer explicitly refused free-space requests for all five raw camera cases on both renderers. + +The original owned-capture test produced all five artifacts in the benchmark environment. Its two baseline support checks refused the OpenCV 4.13 environment as unqualified, as the existing exact-version guard requires. The test teardown also reported a missing runtime package in that initial environment. The qualified OpenCV 5.0 environment passed the original fixture at `d80f382226ecec80119e18b01aa291ffba2100a7`. Its five unchanged free-sensing and free-collision preflights all refused. The fixture wrote its final artifact at 3:49:11 p.m. ET on December 4, 2026, after 20.02 seconds. The enclosing pytest run reported 21.80 seconds. Both attempts are preserved. + +## First campaign timing results + +Every entry below summarizes three fresh processes with 20 warm-up iterations and 100 timed iterations each. Latency is the median of the three run medians and the median of the three run p95s. Throughput is the median of the three run rates. The raw reports retain individual results and device identifiers. + +| Dashboard case, two 320 × 240 cameras | Capture (ms), median / p95 | ICP/SLAM (ms), median / p95 | Capture through SLAM (ms), median / p95 | Startup to first frame (s) | +| --- | ---: | ---: | ---: | ---: | +| Classic bridge, integrated | 473.51 / 543.64 | 198.42 / 448.81 | 691.45 / 932.82 | 3.76 | +| Classic bridge, discrete | 14.56 / 20.55 | 221.62 / 432.19 | 235.50 / 444.57 | 4.11 | +| Frozen classic, integrated | 458.64 / 521.93 | 199.32 / 447.48 | 659.13 / 928.72 | 3.15 | +| Frozen classic, discrete | 12.54 / 19.00 | 219.84 / 446.83 | 236.26 / 458.98 | 2.23 | +| Frozen Warp, discrete | 35.61 / 42.22 | 170.28 / 221.60 | 205.98 / 262.00 | 4.29 | + +The original frozen-render runs above were collected at different times. The interleaved trial uses the same executable and frozen inputs for each pair and is scored separately. The classic bridge's capture interval includes the two `_capture_frame` calls, and bridge step-to-consumer was 693.78 / 935.04 ms integrated and 237.30 / 447.82 ms discrete. CPU physics alone within those steps was 1.24 / 1.89 ms and 1.18 / 2.94 ms respectively. + +| Dashboard worlds | Classic steps/s, one CPU worker | Warp steps/s | Classic step interval (ms), median / p95 | Warp step interval (ms), median / p95 | Warp physics peak / lowest free (MiB) | Warp RGB-D frames/s | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 1 | 6,881 | 66 | 0.72 / 1.16 | 75.81 / 90.37 | 134 / 7,777 | 55.2 | +| 8 | 7,218 | 571 | 5.24 / 8.49 | 70.22 / 82.27 | 134 / 7,777 | 267.8 | +| 32 | 6,334 | 2,292 | 22.41 / 52.31 | 67.26 / 94.75 | 134 / 7,777 | 403.9 | +| 64 | 4,405 | 4,037 | 73.32 / 105.53 | 77.53 / 96.07 | 134 / 7,777 | 424.3 | + +Each replay interval spans five physics substeps and includes applying the recorded controls. The synchronized host-driven Warp path showed zero contact, broadphase and constraint capacity exceedances in the twelve timed stepping processes. The classic single-world replay ended at 1.600000 s and the float32 Warp clock ended at 1.599986 s. Across the three 600-step pairs, maximum differences in root position were 3.40 µm for robot A and 4.61 µm for robot B. In every pair, exact geometry-pair sets differed on 475 of 600 substeps, first at substep 126. The maximum is an observed trajectory difference for this short replay. + +| E33 workload, two 1920 × 1440 cameras | Capture (ms), median / p95 | RGB-D frames/s | Discrete peak / lowest free (MiB) | Three-run wall time (s) | +| --- | ---: | ---: | ---: | ---: | +| Classic integrated, 1 world | 424.25 / 488.91 | 4.94 | see WDDM supplement | 332.1 | +| Classic discrete, 1 world | 231.11 / 244.63 | 8.69 | 439 / 7,472 | 226.3 | +| Warp, 1 world | 121.56 / 216.83 | 13.35 | 312 / 7,599 | 90.6 | +| Warp, 8 worlds | 950.61 / 1,110.46 | 16.48 | 606 / 7,305 | 387.5 | +| Warp, 32 worlds | 3,643.44 / 4,230.14 | 17.15 | 1,624 / 6,287 | 1,337.4 | +| Warp, 64 worlds | 7,450.02 / 8,480.46 | 17.04 | 2,968 / 4,943 | 2,707.7 | + +The original owned classic acquisition, including capture binding, took 518.85 / 666.66 ms per camera pair integrated and 342.31 / 368.08 ms discrete. E33 timing is stationary acquisition at simulation time 0 s. The independent E33 fixture exercises the owned consumer, and Warp has no paired qualified capture-to-consumer measurement. The render-only case completed the planned full-resolution 64-world maximum with more than 1 GiB of sampled device headroom. Sizes above 64 were outside this matrix. The bottleneck widened on the host at 64 worlds. Its stage medians were 1,670.55 ms for Warp rendering, 795.99 ms for readback, 2,302.44 ms for unpack and 2,460.91 ms for depth cleaning. The rendering benchmark does not include batched SLAM. + +Dashboard batches finished at 2:27:24 p.m. ET. The full-resolution Warp render and readback campaign finished at 3:48:46 p.m. ET. The distinct discrete classic timing campaign ended at 3:56:30 p.m. ET. These runs were on December 4, 2026. Process startup, exact UTC end times and active-duration details are in the reports. + +## Interleaved single-world decision + +Both backends ran from the same disposable Python executable on the same frozen CPU-generated states. The order was classic then Warp, Warp then classic, and classic then Warp. `campaign-03` contains the command and reports. + +| Pair | Discrete classic capture through SLAM (ms), median / p95 | Warp capture through SLAM (ms), median / p95 | Warp median change | +| ---: | ---: | ---: | ---: | +| 1 | 135.40 / 259.68 | 128.05 / 166.80 | 5.4% lower | +| 2 | 125.68 / 247.54 | 135.24 / 193.86 | 7.6% higher | +| 3 | 231.13 / 487.05 | 200.33 / 265.50 | 13.3% lower | +| Median across runs | 135.40 / 259.68 | 135.24 / 193.86 | 0.1% lower | + +Keep classic for single-world dashboard use. The paired medians missed the predeclared 10% improvement threshold. Warp lowered p95 in all three pairs. Median capture alone was 11.20 ms for classic and 25.11 ms for Warp. The total interval also includes the consumer's processing of each renderer's own pixels. The first frozen pair had equal clean validity masks for both cameras at simulation time 0.41 s. Camera behaviour and SLAM workload can differ across the replay. + +Keep classic for the synchronized, host-driven physics replay. Warp trailed the serial reference at all four measured world counts. At 64 worlds it was 8.3% slower on completed steps per second, and the exact contact sets differed even when both root trajectories stayed close. This evidence covers host control upload and synchronization. GPU-resident stepping and CUDA graphs were outside the recorded timing case. + +Keep the classic path for owned E33 camera evidence. Warp's single-world acquisition was faster in the measured E33 cases, and the near plane, RGB, and a small number of baseline depth-validity decisions changed. The E33 owned policy applies to its qualified fixture and version domain. For E33 batch acquisition with full host readback, increasing from eight to 64 worlds raised the tested capacity and memory use while observed throughput stayed near 17 frames/s. The E33 matrix includes a one-world classic timing reference. Comparative E33 batch acceleration remains inconclusive. + +## Interleaved dashboard batch decision + +Each batch pair renders two cameras per world and returns both images to the host. The classic reference renders each world serially with one worker. Both paths render copies of an identical CPU-generated state. The interval includes capture and depth cleaning. The batch comparison excludes SLAM and physics, which were timed separately. + +| Worlds | Classic / Warp RGB-D frames/s | Classic capture (ms), median / p95 | Warp capture (ms), median / p95 | Warp peak / lowest free (MiB) | Individual paired throughput gains | +| ---: | ---: | ---: | ---: | ---: | --- | +| 1 | 168.8 / 72.7 | 11.20 / 18.23 | 25.11 / 35.91 | 182 / 7,729 | −51.7%, −59.5%, −66.7% | +| 8 | 183.5 / 245.0 | 85.11 / 103.48 | 64.81 / 74.49 | 182 / 7,729 | +39.3%, +30.6%, +22.5% | +| 32 | 205.5 / 470.5 | 289.15 / 382.99 | 124.91 / 177.62 | 208 / 7,703 | +127.3%, +129.0%, +104.2% | +| 64 | 205.3 / 600.0 | 621.68 / 703.81 | 215.06 / 235.86 | 246 / 7,665 | +196.4%, +150.9%, +194.1% | + +Warp meets the throughput and sampled headroom criteria for opt-in offline dashboard rendering at the measured batch sizes of 8, 32 and 64. At 64 worlds it delivered 2.92 times the median classic frame rate. The render test reused classic-generated transforms. The separate Warp physics replay produced different contact sets and lower measured throughput on the host-driven path. This distinction limits the positive result to the measured render-and-readback workload with its different camera semantics. The last paired run ended at 5:29:27 p.m. ET on December 4, 2026. The 64-world paired set took 320.14 seconds across six processes. + +## Integrated-adapter memory supplement + +The integrated adapter reported zero dedicated memory in the supplemental runs. To observe its actual use, the probe matched the verified renderer's DXGI adapter LUID to the device-wide WDDM counters and sampled typeperf every second. These runs repeated the same workloads after the timing matrix. The counters include other activity on the adapter and can miss short spikes. Shared usage and total committed memory describe different measures. [DXGI adapter identifier](https://learn.microsoft.com/en-us/windows/win32/api/dxgi/ns-dxgi-dxgi_adapter_desc1) · [Windows GPU memory segments](https://learn.microsoft.com/en-us/windows-hardware/drivers/display/gpu-segments) · [typeperf sampler](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/typeperf) + +| Workload | Before shared (MiB) | Peak dedicated / shared (MiB) | Peak committed (MiB) | Samples | Wall time (s) | End time ET | +| --- | ---: | ---: | ---: | ---: | ---: | --- | +| Dashboard classic bridge | 1,468.20 | 0.00 / 3,178.65 | 6,522.12 | 82 | 82.33 | 17:31:43 | +| Dashboard classic frozen render | 2,397.47 | 0.00 / 3,014.38 | 6,375.61 | 69 | 69.34 | 17:32:55 | +| Stationary classic E33 including owned acquisition | 2,474.22 | 0.00 / 3,083.68 | 6,517.98 | 170 | 176.65 | 17:35:54 | + +The first sampler invocation failed during process creation. The corrected run and failed log are preserved separately. + +## Validation artifacts +The worktree holds 90 complete timed process reports across the original three campaigns. The raw JSON reports, RGB-D arrays, GPU logs, failure logs, SHA-256 input manifests and replay inputs are local under `outputs/exploration-planning/mujoco-warp-benchmark/`. The first Warp stepping attempt failed with an overlong generated Windows cache path. The retry with a short cache path completed, with a 189.07-second first five-step interval and 193.21-second process duration and no observed capacity exceedance in its two intervals. A separate default discrete OpenGL probe refused the integrated renderer. A benchmark-specific Windows preference subsequently selected the requested discrete adapter in a fresh classic context. The E33 compatibility-profile audit refused that context. The harness verified its GL strings independently for timing and retained the audit reason. + +The provenance inventory check, all 16 provenance unit tests, all four benchmark contract tests and the qualified E33 fixture passed. The reports identify each measured revision. The paired comparison and the integrated memory supplement use `d80f382226ecec80119e18b01aa291ffba2100a7`. The original E33 variants and initial smoke attempts identify their own earlier revisions. + +## Reproduce the cases + +Use Python 3.12 and an isolated uv environment with the following direct dependencies. Each report records all installed distributions. The first cold Warp physics run compiled CUDA kernels on demand. A short cache path avoids Windows path-length failures in generated file names. + +```powershell +uv venv --python 3.12 .venv +uv pip install --python .venv/Scripts/python.exe mujoco==3.6.0 mujoco-warp==3.6.0 warp-lang==1.12.0 numpy==2.4.3 scipy==1.17.1 open3d==0.19.0 opencv-python-headless==4.13.0.92 PyOpenGL==3.1.10 glfw==2.10.0 trimesh==4.11.5 pytest==8.4.2 pytest-timeout==2.4.0 +$env:WARP_CACHE_PATH = Join-Path ([IO.Path]::GetTempPath()) 'argus22-warp-cache' +$env:OMP_NUM_THREADS = '4' +$env:OPENBLAS_NUM_THREADS = '1' +$python = './.venv/Scripts/python.exe' +$root = 'outputs/exploration-planning/mujoco-warp-benchmark/reproduction-01' +& $python scripts/benchmark_mujoco_warp.py freeze "$root/frozen" +& $python scripts/benchmark_mujoco_warp.py bridge "$root/bridge-classic-1" --expect-gl Intel +& $python scripts/benchmark_mujoco_warp.py render "$root/render-classic-1" --inputs "$root/frozen" --expect-gl Intel +& $python scripts/benchmark_mujoco_warp.py render "$root/render-warp-1" --inputs "$root/frozen" --backend warp +& $python scripts/benchmark_mujoco_warp.py step "$root/step-classic-1" --inputs "$root/frozen" +& $python scripts/benchmark_mujoco_warp.py step "$root/step-warp-1" --inputs "$root/frozen" --backend warp +& $python scripts/benchmark_mujoco_warp.py e33 "$root/e33-classic" --expect-gl Intel +& $python scripts/benchmark_mujoco_warp.py e33 "$root/e33-warp" --backend warp --reference "$root/e33-classic" +& $python scripts/benchmark_mujoco_warp.py e33-timed "$root/e33-timed-classic-1" --expect-gl Intel +& $python scripts/benchmark_mujoco_warp.py e33-timed "$root/e33-timed-warp-1" --backend warp +``` + +Run each timed case three times in a new process and directory. Pass `--worlds 8`, `32`, or `64` for the batch cases. Record each completed run's sampled memory headroom before increasing the E33 batch size. Match the in-process GL vendor to the intended classic adapter. On Windows, the per-app graphics preference applies to the actual Python image, which can differ from the venv launcher. The discrete measurement used a disposable clone of the same interpreter with a temporary preference scoped to that executable. The harness retained both the observed adapter and the independent compatibility-audit refusal. + +The dashboard freeze writes the exact XML, assets, compiled MJB, integration-state vectors and applied controls. Each render process recomputes camera, geom and light transforms with classic `mj_forward` on those vectors. Multiple worlds render identical copies of the same input. Batch physics applies the same recorded actuator stream to each independently stepped world. Classic batch stepping uses one serial worker. Batch render timing includes GPU upload and readback, RGB unpack and host depth cleaning. It excludes ICP. The single-world frozen render includes two SLAM consumers, each with the same explicit nominal identity seed and model camera mount on both backends. The bridge case runs the production bridge and uses its normal SLAM input. Raw row intervals exclude diagnostic validation and telemetry reads. Classic's public renderer combines drawing, readback and metric-depth conversion. + +The discrete memory numbers are device-wide samples from `nvidia-smi` at 100 ms intervals. They include any other activity on that device, and short spikes can fall between samples. On Windows the reported `used` and `free` do not sum to the nominal total because the driver reports separately reserved memory. The integrated adapter's allocation is outside the discrete-device samples. Report the observed free minimum and peak used separately. The E33 missing-depth cleaning retains ordinary classic handling. It does not retrofit classic near-plane visibility into Warp, which would require finding the next visible surface after a rejected near hit.