torch_tensorrt.executorch#
ExecuTorch compilation and export integration.
Import torch_tensorrt_executorch_runtime to register the TensorRT delegate,
then load and run programs through ExecuTorch’s Module API.
Note
This module needs the executorch extra. It runs on Linux and on Windows x86-64. See
ExecuTorch Deployment.
Overview#
The executorch module lowers exported programs into an ExecuTorch Edge
program with TensorRT engines delegated to the TensorRT backend. Use it when you
want to inspect or customize the Edge program before serialization, or when a
single .pte has to carry more than one method.
import torch_tensorrt.executorch
edge = torch_tensorrt.executorch.export({"forward": exported_program})
program = edge.to_executorch()
with open("model.pte", "wb") as f:
program.write_to_file(f)
For the simpler case where no inspection is needed, torch_tensorrt.save(...,
output_format="executorch") writes the file in one call.
Functions#
- torch_tensorrt.executorch.export(source: ExportedProgram | torch.fx.GraphModule | Mapping[str, ExportedProgram], *, inputs: Sequence[Any] | None = None, arg_inputs: Sequence[Any] | None = None, kwarg_inputs: Mapping[str, Any] | None = None, dynamic_shapes: Any | None = None, retrace: bool | None = None, transform_passes: Any | None = None, partitioners: Sequence['Partitioner'] | Mapping[str, Sequence['Partitioner'] | None] | None = None, compile_specs: Sequence['CompileSpec'] | Mapping[str, Sequence['CompileSpec'] | None] | None = None, compile_config: EdgeCompileConfig | None = None, constant_methods: Mapping[str, Any] | None = None, zero_copy_kv: bool = False, generate_etrecord: bool = False, weight_streaming_budget_per_engine: int | None = None, use_cuda_graphs: bool | None = None, external_engine_data: str | None = None) EdgeProgramManager[source]#
Prepare TensorRT-compiled programs for composable ExecuTorch lowering.
TensorRT claims engine nodes first. Additional partitioners run afterward in caller-provided order. The returned EdgeProgramManager is the standard ExecuTorch inspection and customization boundary; call
to_executorch()on it when ready to perform final memory planning and serialization.Export stages independent graph and metadata containers while sharing tensor payload storage with the source programs, so transform passes must treat a shared payload value as immutable. Engines are never deep copied, since that would serialize and deserialize them, but each one is decoded into a byte buffer the returned program owns, so the bytes of a multi-gigabyte engine are resident twice while both programs are alive. Method mappings preserve independent entry points but do not imply shared mutable state between them.
When exporting more than one method, give each method its own partitioner instances via
partitioners={"method": [...]}. A partitioner may carry method-specific state. Give each instance the compile spec for the method it serves, since a backend that reads its method name from the specs cannot find it otherwise. Sharing one instance across methods is rejected when its specs name a method, because every method sharing it would be tagged with the same name. Sharing an instance whose specs name no method is not rejected here, but a backend that reads its own method name from its specs, such as the CUDA backend, then raises during lowering.zero_copy_kv=Truelets a TensorRT engine update an aliased mutable buffer – a KV cache – in place, instead of ExecuTorch handing the delegate a staging copy and copying the engine’s result back afterwards. It is opt-in rather than automatic for two reasons: the resulting.pteneeds a runtime that understands a delegate with its aliased outputs elided, so producing one silently would break an older runner; and it is only half the change. Finalize such a program withto_executorch(torch_tensorrt.executorch.zero_copy_backend_config(config))– without it the buffer is still staged and its updates would be discarded.Nothing here enforces that pairing. The manager returned is ExecuTorch’s own, and its
to_executorchfinalizes whatever config it is given: with an ordinary one it succeeds and writes a.ptewhose caches never update – for a KV cache, wrong output rather than a crash. Finalizing azero_copy_kv=Trueexport yourself therefore owes two calls that nothing checks: passtorch_tensorrt.executorch.zero_copy_backend_config()as the config, and hand the program it returns totorch_tensorrt.executorch.check_zero_copy_kv(), which reads back what the config alone cannot say.torch_tensorrt.save(output_format="executorch", zero_copy_kv=True)owns both ends and does both for you.Only a buffer the engine declares aliased is affected. A method may hold both kinds at once: a mutable buffer with no aliasing available – a convolution state, say – keeps its staging copy and the copy-back that writes it, while the aliased caches beside it go zero-copy. The two are told apart by the engine’s own
aliased_io, not by the graph, in which they look identical.generate_etrecord=Trueis outside the payload sharing described above. It makes ExecuTorch deep copy the whole program, so peak memory grows by roughly the size of the program including engines.Each engine is serialized once, into base64 text. Every method is serialized before the first one is rewritten, and a method’s text is released once that method is rewritten. On top of the engine bytes the exported program itself carries, peak memory adds at most roughly 1.33x the engine bytes of every method together, which is the base64 text, plus about 2.3x the bytes of the largest engine, which is what decoding one method’s text holds at once. For methods whose engines are the same size that is about 3.7x for one method, 2.5x for two, and 1.9x for four.
constant_methodskeys are restricted to valid Python identifiers here, which is narrower than ExecuTorch itself accepts.- Parameters:
source (Union(torch.export.ExportedProgram, torch.fx.GraphModule, Dict[str, torch.export.ExportedProgram])) – A TensorRT-compiled source. A GraphModule is exported first, and a mapping becomes one method per key. An ExportedProgram and a mapping both need their engines already compiled, so
inputs,arg_inputs,kwarg_inputs,dynamic_shapesandretrace=Trueare rejected for them.- Keyword Arguments:
inputs (Sequence[Union(Input, torch.Tensor)]) – Example positional inputs used to export a GraphModule source. Mutually exclusive with
arg_inputs, which is the same argument under the newer name.arg_inputs (Sequence[Union(Input, torch.Tensor)]) – See
inputs.kwarg_inputs (Dict[str, Any]) – Example keyword inputs used to export a GraphModule source.
dynamic_shapes (Any) – Dynamic shape specification passed through to
torch.export. Inferred from anytorch_tensorrt.Inputin the example inputs when omitted, which requires every input to be anInput.retrace (bool) – Re-trace a GraphModule source instead of wrapping its existing graph. Unset behaves as False, and True requires example inputs.
transform_passes (Union(Sequence[Any], Dict[str, Sequence[Any]], PassManager)) – ExecuTorch transform passes, either for every method or per method.
partitioners (Union(Sequence[Partitioner], Dict[str, Sequence[Partitioner]])) – Extra partitioners to run after the TensorRT one, either for every method or per method. Give each method its own instances.
compile_specs (Union(Sequence[CompileSpec], Dict[str, Sequence[CompileSpec]])) – Compile specs for the TensorRT partitioner, either for every method or per method.
compile_config (executorch.exir.EdgeCompileConfig) – Edge compile config. Defaults to
get_edge_compile_config().constant_methods (Dict[str, Any]) – Methods returning a constant, such as a vocab size. Keys must be valid Python identifiers and must not name a method of
source.zero_copy_kv (bool) – Let a TensorRT engine write its aliased mutable buffer – a KV cache – in place, instead of receiving a staging copy that ExecuTorch copies back. Requires finalizing the returned program with
torch_tensorrt.executorch.zero_copy_backend_config(), and checking the result withtorch_tensorrt.executorch.check_zero_copy_kv(); neither is enforced, and finalizing without the config leaves the buffer staged and every update discarded.torch_tensorrt.save(output_format="executorch", zero_copy_kv=True)owns both steps and needs only the one flag.generate_etrecord (bool) – Ask ExecuTorch for an ETRecord for later debugging. This copies the whole program, engines included. Saving the record does not work for a program with TensorRT engines: it raises a
SerializeError.weight_streaming_budget_per_engine (Optional[python:int]) – Bytes of engine weights that may stay resident in GPU memory, with the rest streamed from host memory. It applies to each TensorRT engine separately, not as a total for the program, so a program with N engines can hold up to N times this value resident: every delegate is initialized when its method loads and they stay resident together. Requires the engine to have been compiled with
enable_weight_streaming=True; it is ignored, with a log message, on an engine that cannot stream. Leave it unset, the default, so each engine gets TensorRT’s own automatic budget, sized against free memory on the device it actually loads on. This is a different unit fromtorch_tensorrt.runtime.weight_streaming(...).device_budget, which is a program total split proportionally across engines.use_cuda_graphs (Optional[bool]) – Bake CUDA graph replay on (True) or off (False) into every method’s TensorRT compile specs. None leaves the choice unset so the runtime default applies. A load option, or a process option set to False, overrides this value. Non-booleans and raw
CompileSpec("use_cuda_graphs", ...)entries are rejected; use this keyword instead.external_engine_data (Optional[str]) – Write every TensorRT engine to an ExecuTorch data file named
<external_engine_data>.ptdinstead of into the.pte, which then holds only a key per engine. Pass the name without the.ptdextension. Use only ASCII letters, digits,.,-and_, and start with a letter, a digit or_. The engine is the same bytes either way. Load the program with that file as its data file, for exampleRuntime.get().load_program(pte, data_path=ptd); without it the method fails to load. That loader takes one data file. If another backend in the program writes its own.ptd, pass that backend’s name here so both share one file. For the CUDA backend that name isaoti_cuda_blob. Afterto_executorch(), write the.ptdwithwrite_tensor_data_to_file(directory);torch_tensorrt.savedoes this next to the.pte. None, the default, keeps every engine in the.pte.
- Returns:
The Edge program, ready for inspection, further transformation, or
to_executorch().- Return type:
executorch.exir.EdgeProgramManager
- torch_tensorrt.executorch.get_edge_compile_config() EdgeCompileConfig[source]#
Return the EdgeCompileConfig used for Torch-TensorRT ExecuTorch export.
- torch_tensorrt.executorch.zero_copy_backend_config(config: ExecutorchBackendConfig | None = None) ExecutorchBackendConfig[source]#
Build the
ExecutorchBackendConfiga zero-copy KV program needs.This is the second half of
export(..., zero_copy_kv=True). Export has already removed ExecuTorch’s copy-back of the aliased buffers; this installs the pass that removes their staging, so the engine writes the caller’s buffer instead of a scratch copy that is thrown away.The feature is split across two calls because
to_executorch()belongs to ExecuTorch, not to Torch-TensorRT:export()hands back anEdgeProgramManagerat the Edge boundary and never sees the config the program is finalized with.configis your own configuration – every field is preserved, and ato_out_var_passyou already set runs after the un-staging. Omit it to start from ExecuTorch’s defaults. Two fields are not merely carried:enable_non_cpu_memory_planningis read. Zero-copy needs the caches planned in device memory, soFalse– which plans every tensor into the one host arena – has the pass refuse each cache it finds rather than write a.ptewhose everyexecute()fails. It is read off the config returned here, at the moment the pass runs, so setting the field on that object afterwards is honoured: the pass and the finalizer then cannot disagree about it. There are two cases the field decides nothing in, and that the pass therefore refuses nothing on. One is building a new config out of this one withdataclasses.replace: the field is a bool, copied by value, while the pass is copied by reference and goes on reading the config returned here, so call this function again on the derived config and the pass it builds reads that one. The other is amemory_planning_passof your own that does not already carry an attribute of that name –to_executorchassigns the flag onto the planner rather than passing it, and only onto a planner that has it, so for any other the field reaches nothing and where the caches land is that planner’s own business. Neither is left to the runtime to discover:check_zero_copy_kv()reads the arena memory planning actually chose and refuses the program either mistake produces – but only where something runs it, which on the two-step path is you. The one placement it cannot settle is a method holding no host tensor to give the shared arena away and a program that records its arena devices; a planner that records nothing is refused rather than passed over, ascheck_zero_copy_kv()describes.propagate_device_config.skip_h2d_for_method_inputsis refused, wherever it is written – in the singlePropagateDeviceConfigor in a per-method dict of them – and on every valuePropagateDevicePassreads as on rather than only onTrue: it tests the field for truth without ever resolving it per method, so any non-empty dict is on for every method, one ofFalseincluded. It is ExecuTorch’s own un-staging of method inputs, and it requires each placeholder it un-stages to have exactly one user. A rewired cache always has two – the delegate, and the graph output it is its own mutation result for – soPropagateDevicePassraises on every zero-copy graph. Returning the option unchanged would hand back a config that cannot finalize at all; this says so here instead, where the caller can act on it.
Warning
Finalizing a
zero_copy_kv=Trueprogram without this config leaves the engine writing a per-call staging copy that is then discarded, so the buffer never updates – for a KV cache, wrong output rather than a crash. Nothing stops that on the two-step path.to_executorchbelongs to ExecuTorch and finalizes whatever config it is handed, so pairing the two calls is yours to get right, and so is handing the finalized program tocheck_zero_copy_kv()afterwards – which is what catches the placements this config cannot settle.torch_tensorrt.save(..., zero_copy_kv=True)owns both ends and does both for you.save(..., zero_copy_kv=True)installs this pass itself, so handing it the result of this function asbackend_configapplies the pass twice. That is redundant rather than an error – the second run finds the buffers already wired straight to their delegates and changes nothing – but the two entry points are alternatives: use one or the other.- Parameters:
config (Optional[executorch.exir.ExecutorchBackendConfig]) – The configuration to compose onto. Omit it to start from ExecuTorch’s defaults.
- Returns:
A new config, every field of the given one preserved, whose
to_out_var_passun-stages the aliased buffers before running theto_out_var_passthat was there.- Return type:
executorch.exir.ExecutorchBackendConfig
- Raises:
ValueError – If the configuration sets
propagate_device_config.skip_h2d_for_method_inputs, which cannot be combined with zero-copy KV.
- torch_tensorrt.executorch.check_zero_copy_kv(program: Any) None[source]#
Raise unless a finalized program really updates its KV buffers in place.
programis whatto_executorch()returns. Both halves of zero-copy do nothing quietly when they find nothing to do:zero_copy_kv=Truewarns and carries on when the model holds no aliased buffer mutation, and the passunstage_aliased_buffers_pass()builds, handed a program with nothing marked, un-stages nothing and returns. Neither of those is wrong output – nothing removed a copy-back, so the.ptestages its cache and updates it like any other – but the optimization the caller asked for is silently not there, and a caller who reads the successfulsaveas proof it is gets neither an error nor the speedup. The wrong-output case is the one below: a rewiring that did happen and then lost its mark.Six shapes are refused: a marked buffer that is not a direct argument of a TensorRT delegate carrying the zero-copy compile spec, a stamped delegate that takes fewer marked buffers than its own spec says it elided aliased outputs – including one in a method with no marked buffer at all, which is the lost-mark case – a marked buffer that reaches such a delegate directly but is planned in a host arena, one whose placement the program records nowhere, one planned in a device arena the program records for another GPU, and a program carrying neither a marked buffer nor a stamped delegate in any of its methods. The first three are what finalizing without
zero_copy_backend_config()leaves behind – all but the lost-mark case folded into the second, which no finalization choice produces. That config’s pass gets to all three earlier, off the configuration and the graph: it removes the staging copy the first two come from, and refuses outright when there is none to remove or when the configuration plans nothing onto a device. What it cannot see is the arena planning then chose, which is what this reads.The spec is what narrows the delegates that count. The mark is put on a buffer because one TensorRT engine writes it in place, and only a delegate whose own engine elided an aliased output is stamped, so another backend’s delegate taking the buffer says nothing about whether the engine did, and neither does an unrelated TensorRT engine that happens to read it. Either would stand in for the delegate whose write was elided while that one still reads a staging copy whose contents are discarded. Being stamped is not enough on its own either: in a method that lowers to two of them, one stamped delegate holding both caches leaves every marked buffer reaching some stamped delegate while the other’s write is still thrown away. So each stamped delegate is also counted against its own spec, the same cross-check
_unstage_aliased_buffers()makes, against the same spec and with the same fallback: a spec that names none – listing none, or not decoding – cannot say how many to expect, so it demands at least one. What that count cannot separate is an exact swap – two stamped delegates each taking one marked buffer, each the other’s. The mark records only that some engine writes the buffer in place, never which one, and the spec lists engine output binding names rather than buffers, so there is nothing left to match on; that pass has the same blind spot for the same reason.Placement is read from where memory planning actually put the buffer – the
mem_idon itsTensorSpec– rather than from the spec’s own device, which does not settle it:PropagateDevicePasswrites CUDA onto the spec of a buffer that reaches a CUDA delegate directly, andenable_non_cpu_memory_planning=Falsethen plans that same buffer into the one host arena, which is the shape whose everyexecute()fails on the runtime’s alias-target guard. Two independent grounds answer whether thatmem_idnames a host arena. An arena that also holds one of the program’s host tensors is one whatever the program records (see_host_planned_arenas()); failing that, an arena missing from the CUDA ones the program does record innon_const_buffer_deviceis one too.A placement the program does not record at all is a refusal of its own rather than either of those, because it is not an accusation about the planner’s choice – a buffer with no
mem_idwas not planned, and a program with nonon_const_buffer_deviceentries says nothing about any of its arenas. It is refused because of what the runtime makes of it:MethodMeta::memory_planned_buffer_deviceanswersCPUfor an arena the.pterecords nothing for, so a runner that honours it –examples/executorch_reference_runnerdoes – backs that arena with host memory and the engine then fails the alias-target guard on every call. Onlyapply_algowrites that record, so a caller-suppliedmemory_planning_passthat does not go through it leaves a.ptein exactly that state whatever it planned; a planner for a zero-copy cache has to leave the record behind, which means going throughapply_algowithenable_non_cpu_memory_planning=True. That parameter defaults toFalse, and with it offapply_algoplans every spec into one CPU bucket and writes no record either.Where the record does name a GPU it is read as one: an arena recorded for
cuda:1holding a cache whose own spec asks forcuda:0is an address on the wrong device, which fails the same way a host one does, so the index is compared and not only the type. An unrecorded index on either side says nothing and is accepted, since the arena’s device type is already settled by then.Every method is read, not only
forward.export()rewires each method on its own, so a check that stopped atforwardwould pass a program whose decode had degenerated to staged – and on the prefill/decode pair the user guide’s zero-copy example exports it would not get that far, since a multi-method program need not have aforwardat all. Within a method the marks and the stamped delegates are enumerated independently and a method is passed over only when it carries neither, because the disagreement between those two records is the whole subject: starting from the marks and looking the delegates up leaves anything recorded only on the delegate side outside the walk. The last refusal is about the program rather than about one method, matching the warningexport()emits: a method with no aliased buffer mutation of its own is not an error, so a model that rewires only its decode step is accepted.This reads the graph and the finalized specs, so it says what the program does rather than what the passes recorded. It still says nothing about whether the engine’s write itself is correct.
save(..., zero_copy_kv=True)runs this for you, before it writes the file. The two-step path does not, and this is the limitation of that path:export(..., zero_copy_kv=True)hands back an ExecuTorchEdgeProgramManager, whoseto_executorchis ExecuTorch’s own and finalizes whatever config it is given. So finalizing a zero-copy export yourself owes two calls, and nothing enforces either – passzero_copy_backend_config()as the config, and hand the program that comes back to this before writing the.pte. Skipping the config is the consequential one: it writes a.ptewhose caches never update, which is what the first three refusals above are.- Parameters:
program (executorch.exir.ExecutorchProgramManager) – The finalized program
to_executorch()returned. Every method it holds is read.- Returns:
a program that passes is left exactly as it was.
- Return type:
None
- Raises:
RuntimeError – If the program does not update its KV buffers in place, naming the buffers or delegates and the method each is in.
Classes#
- class torch_tensorrt.executorch.TensorRTPartitioner(compile_specs: List[CompileSpec] | None = None)[source]#
Partitions the graph for TensorRT delegation.
Only nodes that are torch.ops.tensorrt.execute_engine are supported; each such node becomes its own partition so the backend can serialize the engine to the same format as the TRT runtime.
If compile_specs has no
target_deviceentry, each partition gets one naming the GPU its own engine was built on, orcuda:0if that cannot be read. ACompileSpec("target_device", b"cuda:<index>")incompile_specssets it for every partition instead.Note:
target_deviceis AOT metadata only – it drives ExecuTorch’s PropagateDevicePass tagging at export time. At runtime the C++ backend selects the GPU from the device baked into the serialized engine blob, not from this value.
- final class torch_tensorrt.executorch.TensorRTBackend[source]#
Backend that serializes TensorRT engines for the native ExecuTorch runtime.
The partition contains a single execute_engine node; we extract the engine and metadata, store the engine as named data (in the .pte, or with external_engine_data in a .ptd file), and encode its key and the metadata as a standalone blob. The C++ runtime backend parses that blob directly without the legacy Torch-TensorRT C++ runtime.