File size: 5,174 Bytes
0a3f650 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | """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))
|