"""Simulator-free, batch-one RGB-D-to-action deployment measurement.""" import json import os import time from pathlib import Path import numpy as np import pynvml import torch from pydantic import BaseModel, ConfigDict, PositiveInt from pydantic_settings import CliApp from lim.action import decode_action from lim.observations import ObservationConfig, encode_observation from lim.policy import PointChunkPolicy, PolicyConfig class ProfileConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) checkpoint: Path """A trained fixed-final-update policy checkpoint.""" observations: Path """Recorded CPU RGB-D arrays with camera calibration and measured proprioception.""" output_dir: Path """New directory for full per-iteration measurements.""" iterations: PositiveInt = 500 """Measured fresh-observation inference iterations after warmup.""" warmup: PositiveInt = 30 """Unmeasured warmup iterations; cold first call is separately recorded.""" def process_gpu_memory(): total = 0 for index in range(pynvml.nvmlDeviceGetCount()): handle = pynvml.nvmlDeviceGetHandleByIndex(index) for process in pynvml.nvmlDeviceGetComputeRunningProcesses(handle): if process.pid == os.getpid(): total += process.usedGpuMemory return total def run_profile(config: ProfileConfig): config.output_dir.mkdir(parents=True, exist_ok=False) torch.set_num_threads(4) checkpoint = torch.load(config.checkpoint, map_location="cpu", weights_only=False) observations = torch.load( config.observations, map_location="cpu", weights_only=False ) model = PointChunkPolicy(PolicyConfig(**checkpoint["policy_config"])).cuda().eval() model.load_state_dict(checkpoint["state_dict"]) pynvml.nvmlInit() samples = [] peak_process_bytes = 0 cold_ms = None with torch.inference_mode(): for index in range(config.warmup + config.iterations): obs = observations[index % len(observations)] torch.cuda.synchronize() start = time.perf_counter() encoded = encode_observation(obs, ObservationConfig()) prepared = time.perf_counter() points = torch.as_tensor(encoded["points"][None], device="cuda") state = torch.as_tensor(encoded["state"][None], device="cuda") torch.cuda.synchronize() transferred = time.perf_counter() predicted = model(points, state)[0, 0].cpu().numpy() inferred = time.perf_counter() action = decode_action( predicted, encoded["tcp"], encoded["target"], checkpoint["frame"] ) torch.cuda.synchronize() finished = time.perf_counter() if not np.isfinite(action).all(): raise FloatingPointError("Nonfinite deployment action") row = { "preprocess_ms": (prepared - start) * 1000, "transfer_ms": (transferred - prepared) * 1000, "model_ms": (inferred - transferred) * 1000, "action_ms": (finished - inferred) * 1000, "total_ms": (finished - start) * 1000, } if index == 0: cold_ms = row["total_ms"] if index >= config.warmup: samples.append(row) peak_process_bytes = max(peak_process_bytes, process_gpu_memory()) fields = samples[0] percentiles = { key: { str(p): float(np.percentile([row[key] for row in samples], p)) for p in [50, 95, 99] } for key in fields } result = { "config": config.model_dump(mode="json"), "gpu": torch.cuda.get_device_name(), "torch": torch.__version__, "parameters": sum(p.numel() for p in model.parameters()), "observations": len(observations), "cold_ms": cold_ms, "latency_ms": percentiles, "peak_allocated_bytes": torch.cuda.max_memory_allocated(), "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "peak_process_bytes": peak_process_bytes, "median_hz": 1000 / percentiles["total_ms"]["50"], "p95_budget_hz": 1000 / percentiles["total_ms"]["95"], "meets_7GB": 0 < peak_process_bytes <= 7_000_000_000, "meets_20Hz_p95": percentiles["total_ms"]["95"] <= 50, "scope": "two128x128 CPU RGB-D frames + calibration + proprioception to normalized controller action; includes unprojection/filtering/sampling/transfers/encoder/action-head/rotation conversion; camera exposure/network transport and low-level physical controller are external; no simulator imports or cached visual features", } (config.output_dir / "result.json").write_text(json.dumps(result, indent=2)) with (config.output_dir / "iterations.jsonl").open("w") as out: for row in samples: out.write(json.dumps(row) + "\n") print("PROFILE_COMPLETE", json.dumps(result), flush=True) pynvml.nvmlShutdown() if __name__ == "__main__": run_profile(CliApp.run(ProfileConfig))