OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
OpenVINO PyTorch Frontend
The PyTorch Frontend (PT FE) is a C++ based OpenVINO Frontend component that is
responsible for reading and converting a PyTorch model to an ov::Model object
that can be further serialized into the Intermediate Representation (IR) format.
Key Contacts
People from the openvino-pytorch-frontend-maintainers have the rights to approve and merge PRs to the PyTorch Frontend component. They can assist with any questions about the component.
Components
The structure of OpenVINO PyTorch Frontend sources includes the following directories:
Architecture
OpenVINO PyTorch Frontend is a C++ component that uses TorchScriptPythonDecoder
in Python code to parse a PyTorch model from a Python object. Usually, the frontend is
used inside openvino.convert_model in Python code or inside
openvino backend in torch.compile_model, in which case TorchFXPythonDecoder
is used to decode torch.fx.graph. The entire model conversion workflow can be
represented by the following diagram.
flowchart TD
A[(torch.nn.Module)] --> torch.compile
subgraph torch.compile
subgraph TorchFXPythonDecoder
torch.fx.graph_module.GraphModule
end
TorchFXPythonDecoder --> E("pytorch::FrontEnd::load()")
E -->|ov::InputModel| F("pytorch::FrontEnd::convert()")
F --> G[(ov::Model)]
end
A[(torch.nn.Module)] --> openvino.convert_model
subgraph openvino.convert_model
subgraph TorchScriptPythonDecoder
torch.jit.trace ~~~ torch.jit.script
end
TorchScriptPythonDecoder --> B("pytorch::FrontEnd::load()")
B -->|ov::InputModel| C("pytorch::FrontEnd::convert()")
end
openvino.convert_model --> D[(ov::Model)]
OpenVINO PyTorch Frontend supports extensions. To add an extension, use
ov::frontend::pytorch::Frontend::add_extension() API.
In FX graphs, ConversionExtension matches plain Python function targets by their
defining module.qualified_name, which can differ from an import alias.
The following extension types are supported:
ov::frontend::tensorflow::ConversionExtensionorov::frontend::ConversionExtension- add a new Loader into the conversion pipeline.ov::TelemetryExtension- enable telemetry for the frontend.ov::BaseOpExtension- enable support for a custom operation.ov::detail::SOExtension- allow support forov::BaseOpExtensionextensions loaded from an external library.
Python module extensions
For TorchScript conversion, ModuleExtension replacement operations are assumed
to return tensors that do not alias their inputs. Returning an input or a view
of one is unsupported: aliasing is not preserved, and in-place mutations
involving aliased outputs may silently produce incorrect results.
Context-manager scopes in exported models
OpenVINO performs inference only. torch.export represents torch.no_grad(),
torch.set_grad_enabled() and torch.autocast() regions as
wrap_with_set_grad_enabled and wrap_with_autocast operations. Their bodies
are inlined into the converted graph: gradient mode is ignored, and region
outputs are converted to the element types recorded by torch.export, so an
enabled autocast region returns the same types as in PyTorch. Precision of
operations inside the region is selected by the OpenVINO device.
Outputs of such a region that are its operands or their views keep the alias relation,
so later in-place operations on them update the operands. This does not require
ExportedProgram.run_decompositions() or an additional trace.
Exported torch.vmap regions
The FX decoder replaces each exported torch.vmap region with its vectorized ATen
operations, traced from the tensor and symbolic metadata of the region operands.
Operations inside the region, including flat_apply calls, are traced as well.
This region trace runs after export for both models and supplied exported graphs.
The original graph stays unchanged, no OpenVINO loops are introduced, and the
trace must not introduce new shape guards.
Operation names in exported models
When converting with openvino.convert_model(..., dynamo=True) or converting a
torch.export.ExportedProgram, operation friendly names include the original
module path when it is available in the FX node's nn_module_stack metadata:
<module path>/<FX node name>/<PyTorch operation>/<OpenVINO operation>.
For example, encoder.0.activation/relu/aten.relu.default/Relu identifies a ReLU
inside encoder.0.activation. Functional operations use their containing
module's path, and the FX node name distinguishes repeated operations.
Nodes without a non-empty module path retain names without that prefix. This does not change input/output tensor names or TorchScript conversion names. Subsequent graph optimizations may fuse or replace operations, so names do not guarantee a one-to-one mapping to the original graph.
How to Implement Support for a New PyTorch Operation
PyTorch conversion into the OpenVINO opset operations consists of two stages:
- Conversion of PyTorch operations to OpenVINO opset using translators, which directly transforms a PyTorch operation into a sub-graph of the OpenVINO opset. This is a 1->N conversion.
- Internal Transformations that transform a sub-graph of operations into a sub-graph of the OpenVINO opset. This is an N->N conversion.
Operation Translation
Most PyTorch operations can be converted by a single translator. The
dictionary of translators is placed in the op_table.cpp
file and each translator is located in the op
directory:
The main rules for translator implementation:
- Support dynamic shapes and ranks, undefined types, including future support of new types, such as strings and complex numbers.
- Try to maintain the same algorithmic complexity of the decomposition. Fewer operations are usually better.
- Use the latest OpenVINO opset version for the translation.
- Use helper routines for operation checks and graph construction from
utils.hpp. - Call
NodeContext::mark_mode()for each created node.
Inplace and Mutable Operations
Some PyTorch operations modify the input tensor rather than the output. For example,
aten::add writes the result of addition to the output, but aten::add_ writes the result
to its first input. To correctly convert such an operation:
- Ensure that the output tensor produced by the translation has the same type and shape as the initial input.
- Call
NodeContext::mutate_input()to change the input tensor with the new value.
PtFrameworkNode Primitive
PtFrameworkNode is used to represent unconverted operation from the original
model. You can use FrontEnd::convert_partially() instead of Frontend::convert()
to get an ov::Model containing unconverted operations.
Operations Accepting Strings
At the moment, OpenVINO core does not support strings. However, since strings in models are usually constants, you can extract them as std::string directly from Python using NodeContext::const_input<std::string>().
Operations with lists, tuples, dicts
These types are also not supported by OpenVINO core and generally require
implementing transformation for N->N conversion. However, in some simple cases, lists
and tuples can be processed. Helpers for working with lists can be found in utils.hpp.
For example, get_list_as_outputs enables you to get list elements to work with them
in the translator or transformation.
Internal Transformations
In rare cases, converting PyTorch operations requires transformation. The main
difference between transformation and translation is that transformation works on the graph rather
than on the NodeContext of a single operation. This means that some functionality
provided by NodeContext is not accessible in transformation and usually
requires working with PtFramworkNode directly. General rules
for writing transformations also apply to PT FE transformations.
PyTorch Frontend Layer Tests
The layer tests are Python-based tests that check if a PyTorch operation is supported by PT FE. The testing pipeline of the layer tests consists of four steps:
- Create a simple model containing the PyTorch operation to be tested.
- Convert this model into an OpenVINO Model.
- Infer the original model using PyTorch and infer the OpenVINO Model.
- Compare the inference results between both frameworks.
To set up the environment for running the layer tests, follow these instructions.
To test the entire suite of the PyTorch operation set support, run the following command:
python -m pytest layer_tests/pytorch_tests
To run the layer tests with the torch.export (FX) conversion path, use:
PYTORCH_TRACING_MODE=EXPORT python -m pytest layer_tests/pytorch_tests -m precommit_torch_export
PyTorch Frontend Model Hub Tests
The model hub tests in tests/model_hub_tests/pytorch download real models (timm, torchvision, HuggingFace, etc.), convert them, and compare inference results with PyTorch. Each test file has its own requirements in envs, for example:
python -m pip install -r tests/requirements_pytorch -r tests/model_hub_tests/pytorch/envs/timm.txt
Tests are split into precommit (a few small models) and nightly (full model lists)
scopes. Run them from the repository root with tests/model_hub_tests in PYTHONPATH:
export PYTHONPATH=$PWD/tests/model_hub_tests:$PYTHONPATH
export TEST_DEVICE=CPU # default is "CPU;GPU"
python -m pytest tests/model_hub_tests/pytorch/test_timm.py -m precommit
python -m pytest tests/model_hub_tests/pytorch/test_timm.py -m nightly -k "convnext_atto or vit_tiny"
Model caches:
- HuggingFace models (including timm weights) are stored in
HF_HUB_CACHE, which defaults to a directory under the system temp directory. SetHF_HUB_CACHE(andHF_HOME) to a persistent directory to reuse downloaded models between runs. - Torch Hub models (torchvision) are stored in
TORCH_HOME. - Some tests (for example
test_hf_transformers.py) remove the content ofHF_HUB_CACHEafter each test ifUSE_SYSTEM_CACHE=True. KeepUSE_SYSTEM_CACHE=False(default) when you want to reuse the cache.
Nightly model lists (for example timm_models)
have the format name,link[,mark,reason], where mark is one of skip, xfail,
xfail_trace or xfail_export. The timm list is generated from timm.list_pretrained()
by filter_timm in test_timm.py,
which keeps the smallest pretrained variant of each architecture;
test_models_list_complete checks that the list matches the installed timm version.
To regenerate it after a timm version update:
cd tests/model_hub_tests/pytorch
python -c "import timm; from test_timm import filter_timm; print('\n'.join(f'{m},None' for m in filter_timm(timm.list_pretrained())))"
Then restore the marks for models that are still in the list.
Nightly tests run in parallel in CI (pytest -n 4) on a limited-memory runner, so avoid
adding very large models: each worker loads the PyTorch model, converts it, and runs both
models at the same time.
Investigation of accuracy issues
Accuracy issues can be caused by incorrect graph returned by torch.jit.trace
that do not generalize to other inputs or shapes. Such issues can be solved by
using torch.jit.script for obtaining full graph or only script part of the
graph and trace other parts. More about how to do it is described in
pytorch documentation.
Other reasons for accuracy problems can be caused by the incorrect conversion
of specific operations. To identify such operation it is usually helpful to
obtain the original TorchScript graph. That can be done using tracing,
scripting or by manually creating TorchScriptPythonDecoder.
import torch
from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
model = SomeModel()
model.eval()
example = <...> # use the valid model inputs
# get traced model graph
traced_model = torch.jit.trace(model, example)
print(traced_model.inlined_graph)
# get scripted model graph
scripted_model = torch.jit.script(model)
print(scripted_model.inlined_graph)
# get graph directly from TorchScriptPythonDecoder
decoder = TorchScriptPythonDecoder(model, example_input=example)
print(decoder.graph_element)
Also frequent reason for accuracy issues can be incorrect inputs provided to model which is sensitive to input data. So it is recommended to provide real image (audio, text) from dataset for accuracy validation. How to understand which operation causes problems? Lets consider the following model:
import torch
class example_model(torch.nn.Module):
def some_work(self, x):
return torch.randn_like(x)
def forward(self, x):
y = x * x
z = self.some_work(x)
res = x + y + z
return res
It has the following inlined graph:
graph(%self : __torch__.example_model,
%x : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu)):
%y : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu) = aten::mul(%x, %x) # /home/user/example.py:9:0
%3 : NoneType = prim::Constant()
%4 : NoneType = prim::Constant()
%5 : NoneType = prim::Constant()
%6 : bool = prim::Constant[value=0]() # /home/user/example.py:6:0
%7 : NoneType = prim::Constant()
%z : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu) = aten::randn_like(%x, %3, %4, %5, %6, %7) # /home/user/example.py:6:0
%9 : int = prim::Constant[value=1]() # /home/user/example.py:11:0
%10 : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu) = aten::add(%x, %y, %9) # /home/user/example.py:11:0
%11 : int = prim::Constant[value=1]() # /home/user/example.py:11:0
%12 : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu) = aten::add(%10, %z, %11) # /home/user/example.py:11:0
return (%12)
This model has random operation to demonstrate accuracy issues, by nature it
can't generate same results between OpenVINO and PyTorch, because random
numbers are generated differently. To compare the numbers obtained in FP32
inference scenario it is recommended to use 1e-4 as absolute threshold and
relative threshold. But if FP16 is used or model is quantized the threshold
can be increased. To check our model, lets run the following code:
import openvino as ov
import numpy as np
example = (torch.randn(1, 3, 100, 100),)
model = example_model()
ov_model = ov.convert_model(model, example_input=example)
core = ov.Core()
compiled = core.compile_model(ov_model, "CPU")
pt_res = model(*example)
ov_res = compiled(example)
np.testing.assert_allclose(pt_res.detach().numpy(), ov_res[0], atol=1e-4, rtol=1e-4)
It produce the following output:
AssertionError:
Not equal to tolerance rtol=0.0001, atol=0.0001
Mismatched elements: 29996 / 30000 (100%)
Max absolute difference: 6.0375447
Max relative difference: 16586.805
x: array([[[[ 1.124452e+00, 6.839355e-01, -1.321532e+00, ...,
-4.090581e-01, 1.400993e+00, 2.823834e+00],
[-8.246053e-01, 2.376951e-01, 2.846813e+00, ...,...
y: array([[[[-3.556393e+00, 6.779741e-01, 6.177414e-01, ...,
-1.879819e+00, -3.007278e-01, 3.827740e+00],
[-1.255121e+00, 8.543051e-01, 3.162248e+00, ...,...
Issue in your model can be caused by random operation, but it can also be a
different issue. One possible way to find such operation in the model is to
create additional outputs from the graph. We can do it by changing forward
function to return y and z value. That will allow us to see that y is
returned with good accuracy and z has accuracy issues, we can see in inlined
graph that z is produced by line 6 of our code:
%z : Float(1, 3, 100, 100, strides=[30000, 10000, 100, 1], requires_grad=0, device=cpu) = aten::randn_like(%x, %3, %4, %5, %6, %7) # /home/user/example.py:6:0
and we will see torch.randn_like function call on that line.
Possible problems in existing operation translators
Some operations can be translated incorrectly. For example PyTorch allow to
pass different data types in the operation while OpenVINO usually requires same
types for all inputs of the operation (more information about what types
OpenVINO operation can accept can be found in documentation).
PyTorch has set rules for types alignment, to solve this issue PyTorch Frontend
has align_eltwise_input_types helper function which aligns types of two
inputs. If this function is not used when needed or if it used incorrectly that
can result in incorrectly converted operation.
Other common problems are mutated outputs. PyTorch operations can modify input
tensors, which is not directly supported by OpenVINO, to workaround this problem
NodeContext has special function mutate_input it create new tensor with same
name as input tensor. However if mutate_input was omitted in translation
function, unchanged tensor will be returned after operation execution, so it is
very important to pay attention to this.