Repository navigation
[Feature] export_onnx_policy: export TensorDict policies to ONNX with torch.onnx.export - #4626
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/rl/4626
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 69 PendingAs of commit d9ebfbc with merge base c0ca870 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| The graph maps one observation (batch size 1) to the action the policy | ||
| takes under ``ExplorationType.DETERMINISTIC``: ``obs -> actions`` for a | ||
| feed-forward policy, and ``(obs, h_in, c_in) -> (actions, h_out, c_out)`` | ||
| with states of shape ``(num_layers, 1, hidden_size)`` for a policy holding | ||
| one :class:`~torchrl.modules.LSTMModule`. That is the explicit-state layout | ||
| of ``rsl_rl`` and ``mjlab`` exports, which robot runtimes such as | ||
| MicroDuck's load. The caller owns the state and starts an episode by | ||
| feeding zeros, so ``is_init`` is not a graph input. | ||
|
|
||
| Observation normalization must be part of ``policy`` so the graph reads raw | ||
| observations: put the training env's :class:`~torchrl.envs.ObservationNorm` | ||
| (or :meth:`~torchrl.envs.VecNorm.to_observation_norm`) in front of the | ||
| actor. A CPU copy of ``policy`` is exported; ``policy`` is not modified. |
There was a problem hiding this comment.
I personally find this a little hard to understand. Perhaps this can be reworded to be clearer, more step-by-step (the density of code makes it hard to parse)
There was a problem hiding this comment.
Yea I'll rewrite this tomorrow. I think it can be made clearer as well in hindsight.
| :class:`~torchrl.modules.GRUModule` or more than one | ||
| :class:`~torchrl.modules.LSTMModule`. | ||
|
|
||
| .. note:: Exporting requires the ``onnx`` and ``onnxscript`` packages. |
There was a problem hiding this comment.
do we need to add an optional extra for these?
There was a problem hiding this comment.
yea i can add it to the toml file. no harm in doing so.
| onnx \ | ||
| onnxscript \ | ||
| onnxruntime |
There was a problem hiding this comment.
We should add these to the pyproject, if they're an optional dependency.
| gain = torch.where(self.standard_normal, self.scale.reciprocal(), self.scale) | ||
| bias = torch.where(self.standard_normal, -self.loc * gain, self.loc) | ||
| return torch.addcmul(bias, obs, gain) |
There was a problem hiding this comment.
Nice, really great simplification! Maybe this deserves a torch.compile test since it is now compile compatible (or maybe can even be it's own PR in the stack below this, if we want to be really picky)
There was a problem hiding this comment.
yea i think we can keep that within this pr.
| gain = torch.where(self.standard_normal, self.scale, self.scale.reciprocal()) | ||
| bias = torch.where(self.standard_normal, self.loc, -self.loc * gain) | ||
| return torch.addcmul(bias, state, gain) |
There was a problem hiding this comment.
Likewise I think it's worth adding a torch.compile test for this with fullgraph=True (for the forward and inverse paths)
| if any(isinstance(module, GRUModule) for module in policy.modules()): | ||
| raise NotImplementedError( | ||
| "The explicit-state ONNX layout carries LSTM states (h, c); " | ||
| "GRUModule policies cannot be exported with it." | ||
| ) | ||
| lstms = [module for module in policy.modules() if isinstance(module, LSTMModule)] | ||
| if len(lstms) > 1: | ||
| raise NotImplementedError( | ||
| f"The explicit-state ONNX layout carries one LSTM state, but the " | ||
| f"policy holds {len(lstms)} LSTMModules." | ||
| ) |
There was a problem hiding this comment.
I think this might work for now, but is not the best long-term architecture, it will get tough to maintain all the variants of policies to work with this exporter.
From what I can tell, the main abstraction is that we need to wrap a TorchRL tensordict-based policy with a tensor-based policy.
I was originally thinking a small, generic adapter class that inherits from nn.Module and holds onto a torchRL policy and does something like:
class TensorDictTensorAdapter(nn.Module):
def __init__(self, module, example, *, input_keys, output_keys):
super().__init__()
self.module = module
self.input_keys = tuple(unravel_key(key) for key in input_keys)
self.output_keys = tuple(unravel_key(key) for key in output_keys)
self.batch_ndim = len(example.batch_size)
# The prototype also validates the supplied keys.
def forward(self, *inputs):
tensordict = TensorDict(
dict(zip(self.input_keys, inputs)),
batch_size=inputs[0].shape[: self.batch_ndim],
)
result = self.module(tensordict)
return tuple(result.get(key) for key in self.output_keys)This could directly be exported to onnx:
adapter = TensorDictTensorAdapter(
policy,
example_tensordict,
input_keys=policy.in_keys,
output_keys=["action", ("next", "recurrent_state_h"),
("next", "recurrent_state_c")],
).eval()
example_inputs = tuple(example_tensordict.get(key) for key in policy.in_keys)
onnx_program = torch.onnx.export(
adapter,
example_inputs,
input_names=["obs", "h_in", "c_in", "is_init"],
output_names=["action", "h_out", "c_out"],
dynamo=True,
)
onnx_program.save("policy.onnx")
However, I am also not even certain we need that. I did some research and I think you can actually export using normal standard torch.onnx.export by using example tensordicts:
# example_td has batch_size=[2] and contains:
# observation, hidden state, cell state, and is_init
with set_exploration_type(ExplorationType.DETERMINISTIC), \
set_recurrent_mode(False):
onnx_program = torch.onnx.export(
policy,
(example_td,),
dynamo=True,
)
onnx_program.save("policy.onnx")I think this does work, but:
- We may need to do
select_keyson the policy output to get only the observations we want as outputs, and then export that policy+select - During export, Pytorch flattens the tensordict pytree in order to pass it to the policy. The ordering of the flattened keys is not obvious to me, and this is maybe an area we can either add an API here, or to tensordict to make this clear / somehow configure this to match
input_namesthat we may choose to provide the onnx export. What do you think?
Maybe for now we can add something like get_names_in_pytree_order and then
# Inspect the example to get names in PyTorch's flattening order.
input_names = get_names_in_pytree_order(example_td, names_by_key)
onnx_program = torch.onnx.export(
policy,
(example_td,),
input_names=input_names,
dynamo=True,
)wdyt? Maybe this free function becomes a helper that combines a few of these things together?
There was a problem hiding this comment.
Yea i think it makes sense to leverage the torch.onnx.export instead as the api is already familiar to folks. also, instead of the helper functions, im using dispatch from td as the output is returned in out_keys order.
| return obs * scale + loc | ||
| gain = torch.where(self.standard_normal, self.scale.reciprocal(), self.scale) | ||
| bias = torch.where(self.standard_normal, -self.loc * gain, self.loc) | ||
| return torch.addcmul(bias, obs, gain) |
There was a problem hiding this comment.
I asked an agent to stress-test the numerical change here and I think this may substantially change numerical behaviour enough that we should rework this a bit. With float32 obs = loc = 1e8 and scale = 3, (obs - loc) / scale gives 0, while this formulation gives about 0.327 in my test. The inverse has the analogous issue.
Selecting between the original expressions with torch.where may work, but its unused branch is still evaluated: for example, a zero tensor scale can produce a NaN gradient in the inactive division. Could we add precision-sensitive and gradient coverage for both directions and modes?
bsprenger
left a comment
There was a problem hiding this comment.
Looks great, thanks for addressing all the comments!
| graph = TensorDictSequential(policy, selected_out_keys=list(out_keys)) | ||
| graph.training = policy.training | ||
| names = {} | ||
| for key in (*graph.in_keys, *graph.out_keys): |
There was a problem hiding this comment.
Not really sure but maybe these can be evaluated separately? Not sure if it is an issue if output keys overlap with input keys?
Add MicroDuckMLPPolicy to the module zoo: a feed-forward actor with the architecture of the policies Pollen Robotics ships for the MicroDuck (512-256-128 ELU, Gaussian head, TanhNormal over normalized joint targets) that reads the env's ``policy_observation``. ``to_onnx`` writes the deterministic policy as the single ``obs [1, 61] -> actions [1, 14]`` graph the robot runtime loads, with optional observation normalization baked in and the joint, observation and command names plus the action scale recorded in the model metadata. The PPO example gains ``policy.architecture=mlp``: the zoo actor on the robot observation and a feed-forward critic on the privileged observation and task index, with ``policy.export_onnx`` writing the trained actor. The MuJoCo CI environment installs onnx, onnxscript and onnxruntime so the export test runs under ``--error-for-skips``.
The zoo class only bundled stock TorchRL modules, and its hand-written export graph re-implemented TanhNormal's deterministic action. Policies are built from TorchRL components instead and exported with export_onnx_policy.
…ch.where `standard_normal` is a tensor buffer, so branching on it with a Python `if` is a data-dependent guard: `torch.export` (and therefore `torch.onnx.export(dynamo=True)`) fails on any policy holding an ObservationNorm, and `torch.compile` graph-breaks on it. Both directions are now computed and selected with `torch.where`.
…with explicit state Writes a TensorDict policy as a self-contained ONNX graph taking one observation and returning the deterministic action. A policy holding one LSTMModule exports as (obs, h_in, c_in) -> (actions, h_out, c_out) with states of shape (num_layers, 1, hidden_size), the explicit-state layout of rsl_rl / mjlab exports that robot runtimes such as MicroDuck's load. is_init is folded into the caller feeding zero state. GRU policies raise. The test checks the graph against the TorchRL policy over an episode (LSTM run in recurrent mode with is_init, ONNX stepped while carrying h/c), with an ObservationNorm in front and a nested observation key. onnx, onnxscript and onnxruntime are added to the Linux test deps.
The torch.where fix evaluated both normalization directions on every observation, which made the transform about 3x slower than the Python branch it replaced. Selecting the gain and bias on the (per-feature) parameters and applying them with one addcmul keeps it export- and fullgraph-compile-friendly and is 1.6-1.9x faster than the original branch on 4096x61 states and 64x3x84x84 pixels. dtype promotion is unchanged (uint8 -> float32, float64 stays float64).
…rror, tighten docs and test
Inputs and outputs share one ONNX namespace, so the up-front check keeps them together: a key that is read and returned, or two keys that join to the same name, raise a ValueError that says how to fix it. Values the exporter generates (linear, tanh, ...) are renamed out of the way after export, so an out key with such a name no longer writes a model onnxruntime refuses to load, and an input returned unchanged keeps its name instead of becoming <key>_orig.
onnxscript up to 0.7.0 exports nn.GRU with linear_before_reset=0 while PyTorch's GRU needs 1, so a GRU policy exported without error but its actions were wrong. The onnx extra and the Linux test install now require onnxscript>=0.7.1. The docstring lists the RuntimeError raised when the exported graph cannot be named after its keys, and its example normalizes into a separate key so the rollout keeps the raw observation.
8e924a0 to
d9ebfbc
Compare
Stacked on #4625 for branch history only: the diff against it is the export alone, which does not depend on #4625 and can be retargeted to
mainonce #4625 lands.Description
Adds
torchrl.modules.export_onnx_policy(policy, path, example, *, out_keys=None, opset_version=18), which exports a TensorDict policy to ONNX by callingtorch.onnx.exporton the policy itself. There is no tensor-level wrapper.dispatch, so the graph takes and returns plain tensors. Inputs arepolicy.in_keysand outputs areout_keys, in that order, each named after its key with nested keys joined by"_"(("robot", "observation")becomesrobot_observation).out_keysdefaults to"action"plus the next recurrent state the policy writes, so a recurrent policy exports as(obs, state..., is_init) -> (action, next_state...).exampleis an unbatched tensordict holding the policy inputs, for instance the observation pluslstm.make_tensordict_primer().primers.zero().torch.exportcan trace works: feed-forward,LSTMModuleandGRUModuleare tested.ValueErroris raised for a batchedexample, or when two input or output keys would get the same graph name. Inputs and outputs share one ONNX namespace, so a key the policy reads and also returns (an in-place transform requested as an output) is rejected; writing the transformed entry to its own key avoids it.linear,tanh, ...) are renamed out of the way, so an out key with such a name no longer writes a model onnxruntime refuses to load, and an input the policy returns unchanged keeps its name instead of becoming<key>_orig.onnxextra (pip install torchrl[onnx]) foronnxandonnxscript>=0.7.1. onnxscript 0.7.0 and older exportnn.GRUwithlinear_before_reset=0, which does not match PyTorch's GRU, so GRU policies exported without error but returned wrong actions.Two fixes needed for export are included:
ObservationNormbranched on itsstandard_normaltensor buffer with a Pythonif, whichtorch.exportandtorch.compile(fullgraph=True)cannot trace. Both directions now compute(value * mul - sub) / div + addwith the four coefficients selected bytorch.where. Each mode performs the same float operations as before, so results are unchanged frommain, and no unused branch divides byscale, so gradients stay finite.GRUModulecheckedis_init.any()before resetting its state, a data-dependent branch that blocks export. The reset is now the unconditionaltorch.wherethatLSTMModulealready uses; results are unchanged.Motivation and Context
Robot runtimes load ONNX policies with plain tensor inputs and outputs. Exporting through
torch.onnx.exportdirectly keeps TorchRL's code small and the API familiar, and supports any traceable policy without per-architecture special cases.Tests:
test/modules/test_actor.py::TestExportOnnxPolicy: for feed-forward, LSTM and GRU policies with anObservationNormand a nested observation key, the graph's input and output names and shapes, and the actions over a 6-step episode against the eager policy. The state is fed back by output name, so a mix-up between outputs fails the test. Also: the training-mode warning follows the policy's mode without changing it, name clashes are rejected, a batched example is rejected, and an out key named like an exporter-generated value (linear) plus an input returned unchanged keep their key names and match the eager policy.test/transforms/test_observation_transforms.py::TestObservationNorm:torch.compile(fullgraph=True)for both directions and modes, precision far from the origin (loc=1e8) against float64 references, and exact gradients for the value,locandscalewith a zero scale entry.onnx,onnxscript>=0.7.1andonnxruntimeare added to the Linux test dependencies so the export tests run in CI.The two failing checks also fail on
mainand are unrelated to this change:test_example[replay-buffer-checkpoint]in Examples Tests on Linux, andtest_dreamer_components.py::TestDreamerV3Components::test_discrete_actor[cuda-autocast]in tests-stable-gpu.Types of changes
Checklist