Download simulation/scripts/export_sonic_dynamic_batch.py from hk239/v2d: direct link, hf CLI and curl.
- Browser
- Download file 6.64 kB
-
https://huggingface.co/datasets/hk239/v2d/resolve/main/simulation/scripts/export_sonic_dynamic_batch.py
- Command line
-
hf download hf://datasets/hk239/v2d/simulation/scripts/export_sonic_dynamic_batch.py
-
curl -L -o export_sonic_dynamic_batch.py https://huggingface.co/datasets/hk239/v2d/resolve/main/simulation/scripts/export_sonic_dynamic_batch.py
6.64 kB
| #!/usr/bin/env python3 | |
| """Re-export the SONIC v1.1 ONNX pair with a dynamic batch dimension. | |
| The checkpoints NVIDIA ships are traced at batch 1, so an RL rollout would need | |
| one inference call per environment per control tick. Both graphs are batch | |
| agnostic apart from bookkeeping: | |
| * the decoder is pure MatMul/Add/Sigmoid and only needs its declared shapes | |
| relaxed; | |
| * the encoder additionally has Reshape targets that spell the batch out as a | |
| literal ``1``. None of them uses ``-1`` elsewhere, so the leading dim can be | |
| replaced by ``-1`` and inferred instead. | |
| Writes ``model_{encoder,decoder}_batch.onnx`` next to the originals and checks | |
| that a batched call reproduces the per-sample batch-1 result. | |
| python scripts/export_sonic_dynamic_batch.py [--checkpoint DIR] [--batch N] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| from pathlib import Path | |
| import numpy as np | |
| import onnx | |
| from onnx import numpy_helper | |
| _DEFAULT_CKPT = Path(__file__).resolve().parents[2] / "checkpoints" / "sonic" / "sonic_v1_1" | |
| _BATCH_SYMBOL = "batch" | |
| def _relax_value_info(vi) -> bool: | |
| dim = vi.type.tensor_type.shape.dim | |
| if not dim: | |
| return False | |
| if dim[0].dim_value == 1: | |
| dim[0].ClearField("dim_value") | |
| dim[0].dim_param = _BATCH_SYMBOL | |
| return True | |
| return False | |
| def _relax_reshape_targets(graph) -> int: | |
| """Turn a literal leading ``1`` in Reshape targets into ``-1``.""" | |
| consumed: dict[str, list[str]] = {} | |
| for node in graph.node: | |
| if node.op_type == "Reshape" and len(node.input) > 1: | |
| consumed.setdefault(node.input[1], []).append(node.name) | |
| patched = 0 | |
| for node in graph.node: | |
| if node.op_type != "Constant" or node.output[0] not in consumed: | |
| continue | |
| for attr in node.attribute: | |
| if attr.name != "value": | |
| continue | |
| arr = numpy_helper.to_array(attr.t) | |
| if arr.ndim != 1 or arr.size == 0 or arr[0] != 1 or (arr == -1).any(): | |
| continue | |
| new = arr.copy() | |
| new[0] = -1 | |
| attr.t.CopyFrom(numpy_helper.from_array(new, attr.t.name)) | |
| patched += 1 | |
| return patched | |
| def _rebuild_encoder_onehot(graph, num_encoders: int = 3) -> bool: | |
| """Replace the traced encoder-index one-hot with a batch-aware equivalent. | |
| ``EncodersOnlyWrapper`` builds the one-hot by scattering into | |
| ``torch.zeros((batch, num_encoders))`` at ``torch.arange(batch)``. At batch 1 | |
| the arange folds to the constant ``[0]`` and the zeros tensor freezes at | |
| shape ``[1, 3]``, so the ScatterND can only ever fill row 0. Rebuild it as | |
| ``onehot[b, k] = (encoder_index[b] == k)``, which broadcasts over any batch. | |
| """ | |
| scatter = next((n for n in graph.node if n.op_type == "ScatterND"), None) | |
| if scatter is None: | |
| return False | |
| index = next(n for n in graph.node if n.op_type == "Cast" and n.output[0] == "/Cast_output_0") | |
| axes = onnx.helper.make_node( | |
| "Constant", | |
| [], | |
| ["sonic_onehot_axes"], | |
| value=numpy_helper.from_array(np.array([1], dtype=np.int64), "sonic_onehot_axes_v"), | |
| ) | |
| ids = onnx.helper.make_node( | |
| "Constant", | |
| [], | |
| ["sonic_onehot_ids"], | |
| value=numpy_helper.from_array( | |
| np.arange(num_encoders, dtype=np.int64), "sonic_onehot_ids_v" | |
| ), | |
| ) | |
| col = onnx.helper.make_node("Unsqueeze", [index.output[0], "sonic_onehot_axes"], ["sonic_onehot_col"]) | |
| eq = onnx.helper.make_node("Equal", ["sonic_onehot_col", "sonic_onehot_ids"], ["sonic_onehot_eq"]) | |
| cast = onnx.helper.make_node( | |
| "Cast", ["sonic_onehot_eq"], [scatter.output[0]], to=onnx.TensorProto.FLOAT | |
| ) | |
| at = list(graph.node).index(scatter) | |
| graph.node.remove(scatter) | |
| for offset, node in enumerate((axes, ids, col, eq, cast)): | |
| graph.node.insert(at + offset, node) | |
| return True | |
| def make_dynamic(src: Path, dst: Path) -> None: | |
| model = onnx.load(str(src)) | |
| if _rebuild_encoder_onehot(model.graph): | |
| print(f"{src.name}: rebuilt encoder-index one-hot for dynamic batch") | |
| n_reshape = _relax_reshape_targets(model.graph) | |
| n_io = sum(_relax_value_info(vi) for vi in list(model.graph.input) + list(model.graph.output)) | |
| # Stale inferred shapes would contradict the new symbolic batch. | |
| del model.graph.value_info[:] | |
| onnx.checker.check_model(model) | |
| onnx.save(model, str(dst)) | |
| print(f"{src.name} -> {dst.name}: {n_reshape} reshape targets, {n_io} io dims relaxed") | |
| def verify(src: Path, dst: Path, dim_in: int, batch: int, seed: int) -> float: | |
| import onnxruntime as ort | |
| opts = ort.SessionOptions() | |
| opts.log_severity_level = 3 | |
| # A PBS job owns a cpuset, not the whole host. Left to its defaults ORT sizes | |
| # its pool from the host CPU count and every worker fails pthread_setaffinity_np. | |
| try: | |
| opts.intra_op_num_threads = max(1, min(8, len(os.sched_getaffinity(0)))) | |
| except (AttributeError, OSError): | |
| opts.intra_op_num_threads = 4 | |
| opts.inter_op_num_threads = 1 | |
| one = ort.InferenceSession(str(src), opts, providers=["CPUExecutionProvider"]) | |
| many = ort.InferenceSession(str(dst), opts, providers=["CPUExecutionProvider"]) | |
| rng = np.random.default_rng(seed) | |
| x = rng.normal(size=(batch, dim_in)).astype(np.float32) | |
| if dim_in == 1751: # encoder_index must stay a valid mode id | |
| x[:, 0] = rng.integers(0, 3, size=batch) | |
| batched = many.run(None, {many.get_inputs()[0].name: x})[0] | |
| single = np.concatenate( | |
| [one.run(None, {one.get_inputs()[0].name: x[i : i + 1]})[0] for i in range(batch)], axis=0 | |
| ) | |
| err = float(np.abs(batched - single).max()) | |
| print(f" batch={batch} vs {batch}x batch-1: max abs diff {err:.3e} shape {batched.shape}") | |
| return err | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--checkpoint", type=Path, default=_DEFAULT_CKPT) | |
| ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--seed", type=int, default=0) | |
| args = ap.parse_args() | |
| worst = 0.0 | |
| for stem, dim_in in (("model_encoder", 1751), ("model_decoder", 994)): | |
| src = args.checkpoint / f"{stem}.onnx" | |
| dst = args.checkpoint / f"{stem}_batch.onnx" | |
| if not src.is_file(): | |
| raise SystemExit(f"missing {src}") | |
| make_dynamic(src, dst) | |
| worst = max(worst, verify(src, dst, dim_in, args.batch, args.seed)) | |
| ok = worst < 1e-4 | |
| print(f"\n{'OK' if ok else 'MISMATCH'}: worst max abs diff {worst:.3e}") | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |