Skip to content

[Feature] export_onnx_policy: export TensorDict policies to ONNX with torch.onnx.export - #4626

Merged
theap06 merged 14 commits into
microduck/robot-obsfrom
microduck/robot-policy
Nov 1, 2026
Merged

theap06 merged 14 commits into
microduck/robot-obsfrom
microduck/robot-policy

Conversation

@theap06

@theap06 theap06 commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

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 main once #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 calling torch.onnx.export on the policy itself. There is no tensor-level wrapper.

  • The policy is called through tensordict's dispatch, so the graph takes and returns plain tensors. Inputs are policy.in_keys and outputs are out_keys, in that order, each named after its key with nested keys joined by "_" (("robot", "observation") becomes robot_observation).
  • out_keys defaults to "action" plus the next recurrent state the policy writes, so a recurrent policy exports as (obs, state..., is_init) -> (action, next_state...).
  • example is an unbatched tensordict holding the policy inputs, for instance the observation plus lstm.make_tensordict_primer().primers.zero().
  • Any policy that torch.export can trace works: feed-forward, LSTMModule and GRUModule are tested.
  • The policy is exported as configured. The caller puts it in eval mode and chooses the exploration type and recurrent mode around the call; the docstring example shows this.
  • A ValueError is raised for a batched example, 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.
  • After export, the graph's inputs and outputs are named after their keys. Values the exporter generates (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.
  • Observation normalization must be part of the policy, since env transforms are not exported.
  • New onnx extra (pip install torchrl[onnx]) for onnx and onnxscript>=0.7.1. onnxscript 0.7.0 and older export nn.GRU with linear_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:

  • ObservationNorm branched on its standard_normal tensor buffer with a Python if, which torch.export and torch.compile(fullgraph=True) cannot trace. Both directions now compute (value * mul - sub) / div + add with the four coefficients selected by torch.where. Each mode performs the same float operations as before, so results are unchanged from main, and no unused branch divides by scale, so gradients stay finite.
  • GRUModule checked is_init.any() before resetting its state, a data-dependent branch that blocks export. The reset is now the unconditional torch.where that LSTMModule already uses; results are unchanged.

Motivation and Context

Robot runtimes load ONNX policies with plain tensor inputs and outputs. Exporting through torch.onnx.export directly 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 an ObservationNorm and 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, loc and scale with a zero scale entry.

onnx, onnxscript>=0.7.1 and onnxruntime are added to the Linux test dependencies so the export tests run in CI.

The two failing checks also fail on main and are unrelated to this change: test_example[replay-buffer-checkpoint] in Examples Tests on Linux, and test_dreamer_components.py::TestDreamerV3Components::test_discrete_actor[cuda-autocast] in tests-stable-gpu.

  • I have raised an issue to propose this change (required for new features and bug fixes)

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds core functionality)

Checklist

  • I have read the CONTRIBUTION guide (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly (required for a bug fix or a new feature).
  • I have updated the documentation accordingly.

@pytorch-bot

pytorch-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

🔗 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 Pending

As of commit d9ebfbc with merge base c0ca870 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@github-actions github-actions Bot added Feature New feature Documentation Improvements or additions to documentation CI Has to do with CI setup (e.g. wheels & builds, tests...) Environments Adds or modifies an environment wrapper Examples Modules Integrations/torch_geometric Integrations and removed Feature New feature labels Oct 27, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 27, 2026
@theap06
theap06 added this pull request to stack #4627 October 27, 2026 09:31
@theap06 theap06 changed the title [Feature] MicroDuckMLPPolicy: robot-deployable policy with ONNX export [Feature] export_onnx_policy: feed-forward and LSTM policies to ONNX with explicit state Oct 27, 2026
@theap06
theap06 marked this pull request as ready for review October 28, 2026 03:54
Comment thread torchrl/modules/utils/export.py Outdated
Comment on lines +75 to +87
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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea I'll rewrite this tomorrow. I think it can be made clearer as well in hindsight.

Comment thread torchrl/modules/utils/export.py Outdated
:class:`~torchrl.modules.GRUModule` or more than one
:class:`~torchrl.modules.LSTMModule`.

.. note:: Exporting requires the ``onnx`` and ``onnxscript`` packages.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to add an optional extra for these?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea i can add it to the toml file. no harm in doing so.

Comment on lines +156 to +158
onnx \
onnxscript \
onnxruntime

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add these to the pyproject, if they're an optional dependency.

Comment on lines +292 to +294
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea i think we can keep that within this pr.

Comment on lines +302 to +304
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise I think it's worth adding a torch.compile test for this with fullgraph=True (for the forward and inverse paths)

Comment thread torchrl/modules/utils/export.py Outdated
Comment on lines +148 to +158
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."
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. We may need to do select_keys on the policy output to get only the observations we want as outputs, and then export that policy+select
  2. 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_names that 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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@theap06
theap06 requested a review from bsprenger October 31, 2026 01:34
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread torchrl/modules/utils/export.py Resolved
Comment thread torchrl/modules/utils/export.py Resolved
Comment thread torchrl/modules/utils/export.py Resolved
Comment thread torchrl/modules/utils/export.py Resolved
@theap06
theap06 requested a review from bsprenger October 31, 2026 21:06

@bsprenger bsprenger left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thanks for addressing all the comments!

Comment thread torchrl/modules/utils/export.py Outdated
graph = TensorDictSequential(policy, selected_out_keys=list(out_keys))
graph.training = policy.training
names = {}
for key in (*graph.in_keys, *graph.out_keys):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really sure but maybe these can be evaluated separately? Not sure if it is an issue if output keys overlap with input keys?

@theap06 theap06 changed the title [Feature] export_onnx_policy: feed-forward and LSTM policies to ONNX with explicit state [Feature] export_onnx_policy: export TensorDict policies to ONNX with torch.onnx.export Nov 1, 2026
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).
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.
@theap06
theap06 force-pushed the microduck/robot-policy branch from 8e924a0 to d9ebfbc Compare November 1, 2026 06:55
@theap06
theap06 merged commit 61cf3dc into main Nov 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI Has to do with CI setup (e.g. wheels & builds, tests...) CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Documentation Improvements or additions to documentation Environments Adds or modifies an environment wrapper Examples Feature New feature Integrations/torch_geometric Integrations Modules Transforms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants