|
| 1 | +"""Benchmark gaussian splat rendering throughput inside a jax.lax.scan rollout. |
| 2 | +
|
| 3 | +Loads a splat scene and a drone splat, then renders RGB images from the drone camera for a fixed |
| 4 | +number of frames inside a single scanned rollout, doubling the number of parallel worlds each run |
| 5 | +(1, 2, 4, 8, ...). The whole rollout is jitted, so the loop runs entirely on device and the frame |
| 6 | +count reported is the number of images XLA actually rasterizes. |
| 7 | +
|
| 8 | +Requires splax and a CUDA-capable GPU because the splat camera sensor uses splax's GPU rasterizer. |
| 9 | +
|
| 10 | +Run with:: |
| 11 | +
|
| 12 | + pixi run -e benchmark python benchmark/splat.py --resolution "(64,64)" --n_frames 100 |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | +import time |
| 20 | +from datetime import datetime |
| 21 | +from pathlib import Path |
| 22 | +from typing import TYPE_CHECKING, Callable |
| 23 | + |
| 24 | +# splax rasterizes with warp, which needs GPU memory outside JAX's pool. Disable JAX preallocation |
| 25 | +# before it initializes so both share the device. Must run before the first jax import. |
| 26 | +os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false" |
| 27 | + |
| 28 | +import fire |
| 29 | +import jax |
| 30 | +import jax.numpy as jnp |
| 31 | +import numpy as np |
| 32 | +from jax.errors import JaxRuntimeError |
| 33 | +from splax.io import fetch |
| 34 | + |
| 35 | +from crazyflow.sim import Sim |
| 36 | +from crazyflow.sim.sensors.splat import build_render_splat_fn |
| 37 | +from crazyflow.sim.splat import attach_splats |
| 38 | + |
| 39 | +if TYPE_CHECKING: |
| 40 | + from jax import Array |
| 41 | + |
| 42 | + from crazyflow.sim.data import SimData |
| 43 | + |
| 44 | +ASSETS_URL = "https://huggingface.co/datasets/amacati/splats/resolve/main" |
| 45 | + |
| 46 | + |
| 47 | +def build_rollout( |
| 48 | + sim: Sim, resolution: tuple[int, int], n_frames: int, steps_per_frame: int |
| 49 | +) -> Callable[[SimData], Array]: |
| 50 | + """Build a jitted rollout that steps the sim and renders one image per frame. |
| 51 | +
|
| 52 | + Each frame advances the simulation, rasterizes the splats from the first drone's camera for |
| 53 | + every world, and reduces the image to a scalar sum. Reducing inside the loop keeps XLA from |
| 54 | + eliminating the render as dead code while avoiding materializing the full |
| 55 | + (n_frames, n_worlds, H, W, 3) stack. |
| 56 | + """ |
| 57 | + step_fn = sim.build_step_fn() |
| 58 | + render = build_render_splat_fn(sim, drones=0, resolution=resolution) |
| 59 | + |
| 60 | + @jax.jit |
| 61 | + def rollout(data: SimData) -> Array: |
| 62 | + def frame(data: SimData, _: None) -> tuple[SimData, Array]: |
| 63 | + data = step_fn(data, n_steps=steps_per_frame) |
| 64 | + return data, render(data).sum() |
| 65 | + |
| 66 | + data, sums = jax.lax.scan(frame, data, length=n_frames) |
| 67 | + return sums.sum() |
| 68 | + |
| 69 | + return rollout |
| 70 | + |
| 71 | + |
| 72 | +def benchmark( |
| 73 | + resolution: tuple[int, int] = (64, 64), |
| 74 | + n_frames: int = 100, |
| 75 | + max_worlds_exp: int = 12, |
| 76 | + fps: int = 30, |
| 77 | + n_repeats: int = 3, |
| 78 | + scene_ply: str = "robot_hall.ply", |
| 79 | + drone_ply: str = "cf21B_500.ply", |
| 80 | +): |
| 81 | + """Benchmark splat rendering throughput for a growing number of parallel worlds. |
| 82 | +
|
| 83 | + Args: |
| 84 | + resolution: Rendered image resolution as (width, height). |
| 85 | + n_frames: Number of frames rendered per scanned rollout. |
| 86 | + max_worlds_exp: Largest world count is ``2 ** max_worlds_exp``. |
| 87 | + fps: Camera frame rate. Determines the physics steps taken between frames. |
| 88 | + n_repeats: Number of timed rollouts per world count. The fastest run is reported. |
| 89 | + scene_ply: Scene splat file name on the assets host. |
| 90 | + drone_ply: Drone splat file name on the assets host. |
| 91 | + """ |
| 92 | + logging.info("Fetching splat assets...") |
| 93 | + scene = fetch(f"{ASSETS_URL}/{scene_ply}") |
| 94 | + drone = fetch(f"{ASSETS_URL}/{drone_ply}") |
| 95 | + |
| 96 | + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| 97 | + csv_file = Path(__file__).parent / "data" / f"benchmark_results_{timestamp}.csv" |
| 98 | + csv_file.parent.mkdir(exist_ok=True) |
| 99 | + with open(csv_file, "w", newline="") as f: |
| 100 | + f.write( |
| 101 | + "test_type,n_drones,n_worlds,n_steps,total_time_s,avg_step_time_s," |
| 102 | + "fps,real_time_factor,device\n" |
| 103 | + ) |
| 104 | + |
| 105 | + print( |
| 106 | + f"\nSplat rendering benchmark, resolution {resolution[0]}x{resolution[1]}, {n_frames} " |
| 107 | + f"frames per rollout" |
| 108 | + ) |
| 109 | + print("-" * 80) |
| 110 | + print(f"{'n_worlds':>10} {'rollout_s':>12} {'frame_ms':>12} {'fps':>14}") |
| 111 | + print("-" * 80) |
| 112 | + |
| 113 | + for n_worlds in [2**i for i in range(max_worlds_exp + 1)]: |
| 114 | + try: |
| 115 | + sim = Sim(n_worlds=n_worlds, control="state", device="gpu") |
| 116 | + attach_splats(sim, scene=scene, drone=drone) |
| 117 | + steps_per_frame = max(1, sim.freq // fps) |
| 118 | + |
| 119 | + # Hold a constant target so the drone keeps moving and each frame renders a distinct |
| 120 | + # pose. A static scene would let XLA hoist the render out of the loop. |
| 121 | + cmd = np.zeros((sim.n_worlds, sim.n_drones, 13), dtype=np.float32) |
| 122 | + cmd[..., 2] = 0.5 |
| 123 | + sim.reset() |
| 124 | + sim.state_control(jnp.asarray(cmd, device=sim.device)) |
| 125 | + |
| 126 | + rollout = build_rollout(sim, resolution, n_frames, steps_per_frame) |
| 127 | + |
| 128 | + # Warmup triggers JIT compilation of the full rollout. |
| 129 | + jax.block_until_ready(rollout(sim.data)) |
| 130 | + |
| 131 | + times = [] |
| 132 | + for _ in range(n_repeats): |
| 133 | + tstart = time.perf_counter() |
| 134 | + jax.block_until_ready(rollout(sim.data)) |
| 135 | + times.append(time.perf_counter() - tstart) |
| 136 | + |
| 137 | + assert rollout._cache_size() == 1, "rollout must only be jitted once" |
| 138 | + |
| 139 | + rollout_s = min(times) |
| 140 | + frame_ms = rollout_s / n_frames * 1e3 |
| 141 | + images_per_s = n_frames * n_worlds / rollout_s |
| 142 | + print(f"{n_worlds:>10} {rollout_s:>12.4f} {frame_ms:>12.4f} {images_per_s:>14.3e}") |
| 143 | + sim.close() |
| 144 | + |
| 145 | + real_time_factor = (n_frames / fps) * n_worlds / rollout_s |
| 146 | + with open(csv_file, "a", newline="") as f: |
| 147 | + f.write( |
| 148 | + f"splat,{sim.n_drones},{n_worlds},{n_frames},{rollout_s}," |
| 149 | + f"{rollout_s / n_frames},{images_per_s},{real_time_factor},gpu\n" |
| 150 | + ) |
| 151 | + except (JaxRuntimeError, MemoryError) as e: |
| 152 | + print(f"{n_worlds:>10} out of memory, stopping ({type(e).__name__})") |
| 153 | + break |
| 154 | + |
| 155 | + print("-" * 80) |
| 156 | + print("fps is total images rendered per second across all parallel worlds.\n") |
| 157 | + print(f"Benchmark results saved to {csv_file}") |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + logging.basicConfig(level=logging.INFO) |
| 162 | + logging.getLogger("jax").setLevel(logging.WARNING) |
| 163 | + fire.Fire(benchmark) |
0 commit comments