AOTInductor
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
AOTInductor is described in the PyTorch documentation as "a specialized version of TorchInductor", the compiler behind torch.compile. Where torch.compile compiles a function just in time inside a running Python process (see torch.compile), AOTInductor takes an ExportedProgram (see torch.export) and compiles it ahead of time into a package containing a shared library with generated kernels, plus the weights. The package can then be loaded and run from Python or from C++ without Python-level model code and without compilation at start-up. Its target is server-side inference; for phones and embedded devices use ExecuTorch instead, and for a framework-neutral file see Exporting to ONNX.
The Python examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31; the C++ example needs LibTorch, CMake and a CUDA GPU and was not executed. The page for AOTInductor lives in the compiler user guide at https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/torch.compiler_aot_inductor.html. The entry points are in the private-looking namespace torch._inductor; the documentation nevertheless presents them as the public API, but the leading underscore is a reminder to pin the PyTorch version and re-test on upgrades.
Workflow
-
Capture the model with
torch.export.export, optionally declaring dynamic dimensions. -
Compile and package with
torch._inductor.aoti_compile_and_package. The output is a PT2 archive (.pt2), the same container format thattorch.export.saveuses. -
Run it with
torch._inductor.aoti_load_packagein Python, or with the C++ classtorch::inductor::AOTIModelPackageLoader.
The compile step may run on a machine other than the one that trains the model: export and save with torch.export.save, load with torch.export.load on the inference platform, and compile there so that the generated code matches the target hardware.
The diagram summarises the path from a trained model to the two ways of running the package.
Compiling a model
# model.py
import os
import torch
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(10, 16)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(16, 1)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return self.sigmoid(x)
with torch.no_grad():
device = "cuda" if torch.cuda.is_available() else "cpu"
model = Model().to(device=device)
example_inputs = (torch.randn(8, 10, device=device),)
# Make the first dimension of the input x dynamic (optional)
batch_dim = torch.export.Dim("batch", min=1, max=1024)
exported = torch.export.export(
model, example_inputs, dynamic_shapes={"x": {0: batch_dim}}
)
output_path = torch._inductor.aoti_compile_and_package(
exported,
package_path=os.path.join(os.getcwd(), "model.pt2"),
inductor_configs={"max_autotune": True}, # optional: more kernel autotuning
)
print(output_path)
Source: https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/torch.compiler_aot_inductor.html
The signature in 2.15 is aoti_compile_and_package(exported_program, *, package_path=None, inductor_configs=None) and it returns the path of the generated artefact as a string.
-
package_pathis where the.pt2file is written. If it is omitted the artefact goes to the system temporary directory, which is rarely what a build script wants. -
inductor_configsis a dictionary of TorchInductor options. The documentation demonstrates onlymax_autotune, which turns on more extensive kernel autotuning (slower compilation, usually faster kernels). Other inductor options exist in the compiler configuration, but they are not documented on this page, so treat them as unstable. -
Compile under
torch.no_grad()(as the example does) and with the model ineval()mode, since the artefact is for inference. -
Compilation builds the generated C++ code, so the machine that compiles needs a working C++ compiler (and, for GPU targets, the matching CUDA or Intel GPU software stack). On a CPU-only machine the package is compiled for the CPU, and with
max_autotuneInductor benchmarks its own C++ GEMM kernels against the ATen ones and prints the choices.
An older workflow compiles several models with torch._inductor.aot_compile(..., options={"aot_inductor.package": True}) and bundles them with package_aoti into a single file that is read back by name with load_package(path, "model1"). The documentation still shows it for multi-model packages; for one model prefer the function above.
Loading from Python
import os
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
model = torch._inductor.aoti_load_package(os.path.join(os.getcwd(), "model.pt2"))
print(model(torch.randn(8, 10, device=device)))
print(model(torch.randn(3, 10, device=device))) # works because the batch dimension was dynamic
Source: https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/torch.compiler_aot_inductor.html
aoti_load_package(path, run_single_threaded=False, device_index=-1, *, num_runners=1, use_stream_affinity=False) returns a callable AOTICompiledModel:
-
run_single_threaded=Trueskips thread synchronisation; the documentation says it is useful to avoid conflicts with CUDA graphs. -
device_indexselects the GPU; the default-1means plaincuda, and1would load ontocuda:1. -
num_runnerscreates that many model instances for concurrent execution, for example to serve requests from several threads. -
use_stream_affinityis intended for controlled multi-stream benchmarking and may reduce host-side pipelining; leave it off in production. -
If a package holds several models this loads the default one.
Loading from C++
The package is meant to be consumed without Python. The C++ API ships with LibTorch (the header is torch/csrc/inductor/aoti_package/model_package_loader.h):
// inference.cpp
#include <iostream>
#include <vector>
#include <torch/torch.h>
#include <torch/csrc/inductor/aoti_package/model_package_loader.h>
int main() {
c10::InferenceMode mode;
torch::inductor::AOTIModelPackageLoader loader("model.pt2");
// Assumes the package was compiled for CUDA
std::vector<torch::Tensor> inputs = {torch::randn({8, 10}, at::kCUDA)};
std::vector<torch::Tensor> outputs = loader.run(inputs);
std::cout << outputs[0] << std::endl;
// A different batch size works because that dimension was exported as dynamic.
std::cout << loader.run({torch::randn({1, 10}, at::kCUDA)})[0] << std::endl;
return 0;
}
cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
project(aoti_example)
find_package(Torch REQUIRED)
add_executable(aoti_example inference.cpp model.pt2)
add_custom_command(
OUTPUT model.pt2
COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/model.py
DEPENDS model.py
)
target_link_libraries(aoti_example "${TORCH_LIBRARIES}")
mkdir build && cd build
CMAKE_PREFIX_PATH=/path/to/python/install/site-packages/torch/share/cmake cmake ..
cmake --build . --config Release
Source: https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/torch.compiler_aot_inductor.html
CMAKE_PREFIX_PATH must be an absolute path to the LibTorch installation (here the one inside the Python package). The generated package depends on the LibTorch version it was built with, so build and run with the same release. A package compiled for CUDA needs a CUDA device on the machine that runs it.
Shapes, dtypes and checks
The central contract: the input at inference time should have the same size, dtype and stride as the input at export time, except where a dimension was declared dynamic through torch.export.Dim. Passing anything else is undefined unless you enable the checks. Setting the environment variable AOTI_RUNTIME_CHECK_INPUTS=1 makes the package raise a RuntimeError when sizes, dtypes or strides differ from what the package expects; use it in tests and while integrating. Make dynamic dimensions as narrow as is true (min, max), because the compiled kernels are specialised using the declared ranges.
Devices and performance options
-
CUDA (when PyTorch is built with CUDA support and a device is present) produces a CUDA shared library; CPU is used otherwise; the documentation states that the same flow works on Intel GPUs.
-
For better CPU inference performance the documentation suggests exporting
TORCHINDUCTOR_FREEZING=1. -
AOTInductor accelerates a graph; it does not quantise it. Quantise first (see Quantization, Sparsity & Pruning with torchao) and export the quantised module.
Debugging
The documentation points to three tools: torch._logging (the logging switches described in the compiler user guide), the AOTInductor Debugging Guide, and the AOTInductor Minifier, which reduces a failing model to a small reproducer. Exporting is usually the first thing that fails, so resolve torch.export errors first (see torch.export and Graph Breaks, Recompilation & Dynamic Shapes). The page does not label AOTInductor as beta or prototype, but it sits in a private namespace and the surface has changed between releases, so check the release notes when upgrading.
AOTInductor or the alternatives
| Need | Choice |
|---|---|
Fast inference on a GPU server from C++ or a Python service without model code |
AOTInductor |
One file for many runtimes, hardware vendors and languages |
ONNX, see Exporting to ONNX |
Phone, tablet, microcontroller or other constrained device |
ExecuTorch, see ExecuTorch for Mobile & Edge |
Keep Python and speed up the existing code |
|
Model serving infrastructure |
See Deploying & Serving ML Models; TorchServe is archived, see Legacy APIs & Migration |