Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[Skills] Improve frontend efficiency and PyTorch review guidance (#38784)

Maxim Vafin423688c840db
diff --git a/.claude/skills/code-review/references/frontend.md b/.claude/skills/code-review/references/frontend.md
index 82c3691c867..33854958ffa 100644
--- a/.claude/skills/code-review/references/frontend.md
+++ b/.claude/skills/code-review/references/frontend.md
@@ -4,82 +4,93 @@ Apply to changes under `src/frontends/`, frontend Python decoders and bindings
under `src/bindings/python/src/openvino/frontend/` and
`src/bindings/python/src/pyopenvino/frontend/`, and their conversion tests.
-## Review focus
+## Conversion semantics
-- Keep frontend code hardware- and plugin-agnostic. Conversion must preserve
- framework semantics without targeting a specific device or plugin. Flag
- device-dependent conversion branches or backend-specific optimizations;
- those belong in the relevant plugin's transformation or execution pipeline.
-- Check rank, dimension, element type, layout, optional inputs, attributes,
- opset or framework-version behavior, and dynamic-shape handling.
-- Support the broadest dynamism allowed by framework semantics, including
- dynamic ranks, dimensions, and element types. Always assume input element
- types may be dynamic during conversion; avoid creating constants with a
- type taken from an input. When a constant must match an input's type, create
- it with a concrete type and use `ConvertLike` to match the input without
- requiring its type to be known during conversion.
-- Work with `ov::Output<ov::Node>` values when constructing the graph. Avoid
- extracting nodes with `get_node_shared_ptr()` just to pass them as inputs
- to another operation: this discards the original output index. Passing a
- node implicitly selects its default output (normally output 0), which can
- miswire a multi-output producer or fail if it has no default output.
- Preserve the original output value or explicitly select `node->output(i)`.
-- Verify that conversion emits the intended OpenVINO graph and preserves
- framework semantics for valid inputs.
-- Check malformed, missing, out-of-range, duplicated, and unsupported values
- for deterministic validation and useful errors.
-- Check registration tables, opset ranges, translator dispatch, normalization
- passes, and framework-specific entry points for consistency.
-- Check that conversion does not depend on unavailable compile-time shape or
- type information when runtime graph computation is required.
-- Check that user-visible frontend behavior has focused regression tests,
- including dynamic, boundary, and malformed-input cases where applicable.
-- Check that conversion tests actually run inference and compare the results
- with expected values; a test that only prepares inputs and expected outputs
- verifies nothing. Flag expected values that look like placeholders; they
- should come from the framework or a trusted reference.
-- When a change lets inputs that had to be constants be runtime values, require
- a positive test that feeds them at runtime and exercises output shapes that
- depend on them, not only rejection tests.
-- Check that test tolerances fit the magnitude of the outputs. An absolute
- tolerance that ignores the output scale can hide real errors or make the test
- flaky.
-- When a change adds support for an operation or case, check the frontend's
- expected-failure and skip lists for tests it now fixes. Newly passing strict
- xfails fail CI.
-- Do not ask for frontend workarounds for plugin or reference-evaluator
- limitations, such as a missing f64 kernel. Report them against the plugin.
+- Keep conversion hardware- and plugin-agnostic. Device-specific rewrites
+ belong in plugin pipelines; do not request frontend workarounds for missing
+ plugin or reference-evaluator kernels.
+- Check framework semantics, operator versions, optional inputs, defaults,
+ layouts, and translator registration. Report unsupported behavior only
+ when the diff claims support or changes its error handling; placeholder
+ nodes are not full support.
+- When modifying an existing conversion to support another operation mode or
+ fix a bug, preserve the emitted graph for previously working cases unless
+ a concrete benefit, such as improved performance or graph simplification,
+ justifies the change.
+ Equivalent graphs can break downstream transformation matching. Always
+ flag changes to those cases for human review, stating the affected graph
+ form, rationale, and transformation risk, even when the risk is justified.
+- Preserve the dynamism allowed by the framework, including ranks, dimensions,
+ and element types. Avoid requiring compile-time shape or type information
+ for runtime calculations. To match a possibly dynamic input type, create a
+ concretely typed constant and use `ConvertLike`.
+- Connect graph inputs with `ov::Output<ov::Node>`. Passing
+ `get_node_shared_ptr()` instead loses the output index and can miswire a
+ multi-output producer; use the original value or `node->output(i)`.
+- Review Python decoders as conversion logic: preserve types, shapes,
+ constants, attributes, input/output order, and framework-object lifetimes.
-## Framework-specific guidance
+## Graph efficiency
-- ONNX frontend (`src/frontends/onnx/`): also apply [ONNX frontend review](onnx.md).
+- Consider equivalent decompositions with less computation, data movement,
+ extraction/reconstruction, or shape work, even when numerical tests pass.
+ Look beyond duplicate elimination for ways to use fewer operations.
+- Compare input, intermediate, and output element counts and byte sizes.
+ Smaller tensors usually cost less to process and store: three small
+ operations can outperform two large ones. Account for operation and copy
+ costs; avoid early broadcasts or large intermediates when semantics allow.
+- Avoid equal nodes unnecessarily, but account for
+ [`ov::pass::SharedOpOptimization`](../../../../src/common/transformations/include/transformations/common_optimizations/shared_ops_optimization.hpp).
+ It merges eligible nodes with matching operation types, inputs, and
+ attributes when the pipeline runs it; duplication it removes is normally
+ a minor issue. The same operation on different inputs is not a duplicate.
+- Attribute equality matters even when values are equivalent for the current
+ calculation: `Reshape` with `special_zero=true` will not merge with
+ `special_zero=false`, even for a shared constant shape without zeros.
+ When variants are equivalent for all supported inputs, prefer values common
+ in surrounding translators/helpers to improve merging chances. Check dynamic
+ values and edge cases before treating an attribute as irrelevant.
+- For `ComplexTypeMark`, consider processing combined `get_data()` instead of
+ extracting `get_real()`/`get_imag()`, processing both, and reconstructing.
+ Preserve the trailing component dimension in `[..., 2]`, complex-part type,
+ and logical axes/shape. Slicing can operate once over the logical axes, and
+ shape bounds need not extract a component solely for `ShapeOf`. Balance
+ packing/extraction costs and tensor sizes; separate formulas may be needed
+ for operations that mix real and imaginary components.
-## Python decoders and bindings
+## Element types
-- Review Python decoder changes as conversion logic. Check the graph, tensor
- types, shapes, constants, attributes, and input/output ordering exposed to
- the C++ frontend, including decoder and framework-object lifetimes.
-- For PyTorch, check the affected
- [TorchScript](../../../../src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py)
- or [FX/export](../../../../src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py)
- path. Preserve mutation and alias semantics and verify that regression tests
- exercise the changed capture path.
-- For [JAX](../../../../src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.py),
- check Jaxpr variable identity, literals and captured constants, primitive
- parameters, and output ordering against the C++ decoder contract.
-- Apply [bindings guidance](bindings.md) when Python API, exception handling,
- ownership, or C++/Python interaction changes.
+Prefer framework output types and promotion rules, including `i64` and `f64`.
+Distinguish these from internal constants and intermediates; plugin lowering
+of unsupported computations to `i32`/`f32` is not a frontend defect.
+
+Dtype fidelity alone is a non-blocking `P3` issue. Accept justified `i32`/`f32`
+conversions when preserving 64-bit types causes conversion problems or
+substantial code changes and the range/precision tradeoff is reasonable.
+Do not demand broad refactors or flag every 32-bit constant. Escalate based
+on demonstrated overflow, wrong indexing, conversion failure, or material
+numerical error for a supported scenario, rather than type width alone.
-## Transformations
+## Conversion tests
-For frontend normalization and decomposition passes, also apply the
-[transformation review guidance](transformations.md). Verify that pass ordering
-and handling of framework placeholder nodes preserve conversion semantics.
-These passes must follow the same hardware- and plugin-agnostic rules as
-operation translators and Python decoders.
+- Verify tests actually run inference and compare against the framework or a
+ trusted reference, with tolerances appropriate to output magnitude.
+- When constant-only inputs become runtime inputs, check positive coverage
+ with runtime values and dependent output shapes, not only rejection cases.
+- Check expected-failure and skip lists when support expands; newly passing
+ strict xfails fail CI.
-## Evidence and scope
+## Additional guidance
+
+- ONNX: [ONNX frontend review](onnx.md).
+- PyTorch: [PyTorch frontend review](pytorch.md).
+- [JAX decoder](../../../../src/bindings/python/src/openvino/frontend/jax/jaxpr_decoder.py):
+ check Jaxpr variable identity, literals/captured constants, primitive
+ parameters, and output ordering against the C++ decoder contract.
+- Frontend passes: apply [transformation guidance](transformations.md),
+ checking pass ordering and framework placeholder handling.
+- Python API or language-boundary changes: apply [bindings guidance](bindings.md).
-Do not report unsupported framework behavior unless the diff claims to
-support it or changes its error handling. Check that fallback nodes or
-placeholder translators are not presented as full support.
+Include concrete efficiency or dtype improvements as non-blocking
+recommendations even with no defects. Explain the changed location, avoidable
+work or tradeoff, and minimal fix; claim measured speedups only with profiling.
diff --git a/.claude/skills/code-review/references/pytorch.md b/.claude/skills/code-review/references/pytorch.md
new file mode 100644
index 00000000000..46bd7607084
--- /dev/null
+++ b/.claude/skills/code-review/references/pytorch.md
@@ -0,0 +1,67 @@
+# PyTorch Frontend Review
+
+Apply alongside [frontend guidance](frontend.md) to PyTorch translators,
+passes, decoders, and conversion tests.
+
+## Capture and dispatch
+
+- Identify the actual capture path: scripted/traced
+ [TorchScript](../../../../src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py),
+ `torch.export.ExportedProgram`, or `torch.compile` through the
+ [FX decoder](../../../../src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py).
+ Inspect the captured graph and configured decomposition/functionalization;
+ sharing a decoder does not imply identical operators, metadata, or mutations.
+ Do not assume decompositions run or require them just to hide missing support.
+- Trace dispatch through the [operation table](../../../../src/frontends/pytorch/src/op_table.cpp)
+ and [translation session](../../../../src/frontends/pytorch/src/translate_session.cpp).
+ `aten::add` and `aten.add.Tensor` may use shared translators or FX overrides.
+ Check overload schemas, keyword arguments, omitted defaults, `None`, and
+ inlined scalars/lists before sharing logic across capture paths or versions.
+- `context.input_is_none(i)` checks bounds and returns `true` when
+ `i >= context.get_input_size()`, as well as for an explicit `None`. It can
+ guard optional inputs without a separate range check; do not flag calls
+ beyond the input count as out-of-bounds access.
+- Distinguish capture specialization from conversion defects. Do not turn
+ symbolic shape calculations into example-input constants, or reorder user
+ inputs, parameters, buffers, and flattened container outputs.
+
+## Type alignment
+
+- Reuse [promotion helpers](../../../../src/frontends/pytorch/src/utils.cpp)
+ (`align_eltwise_input_types`, `get_inputs_with_promoted_types`,
+ `is_python_scalar_input`, `align_output_types`) and
+ [wrappers](../../../../src/frontends/pytorch/src/utils.hpp) where their rules apply.
+- Distinguish Python scalars, zero-dimensional tensors, and other tensors.
+ Promotion depends on numeric category and operand kind, not just stored
+ dtype. Preserve decoder `PyScalar` information and pass correct scalar flags.
+- Align operands before arithmetic; casting afterward cannot repair overflow,
+ truncation, or wrong division. Check result types separately, especially
+ comparisons, reductions, integer true division, and explicit/default dtype.
+ Decoder output metadata may be dynamic, so it cannot replace promotion logic.
+- Apply operator-specific rules: in-place destination dtype, allowed `out=`
+ casts, and scalar arguments such as `alpha` differ from ordinary promotion.
+ When dtype decoding changes, keep Python mappings and C++ ScalarType
+ interpretation consistent. Use shared frontend rules for 64-bit tradeoffs.
+
+## Mutation and aliases
+
+Follow `NodeContext::mutate_input` and session alias handling, not only the
+returned value: later base/view uses must see updates, while values computed
+before mutation remain unchanged. Check in-place return aliases and `out=`
+destinations when affected. Preserve view/copy distinctions: non-contiguous
+reshape may copy, and `*_copy` variants must not gain aliases merely because
+values match. Use the captured graph and decoder alias contract as evidence.
+
+## Regression coverage
+
+Confirm the actual mode in the
+[layer-test harness](../../../../tests/layer_tests/pytorch_tests/pytorch_layer_test_class.py):
+`PYTORCH_TRACING_MODE=EXPORT` selects export, `TORCHFX` selects the compile
+backend, and the ordinary path uses TorchScript scripting/tracing options.
+Check affected paths when shared logic receives different schemas or metadata;
+do not demand unsupported capture modes.
+
+Verify the expected operator/overload survives capture and decomposition.
+For the changed rule, check mixed dtype/scalar kinds, multiple permitted
+shapes, or observable mutation of bases/views. Assert converted types for
+dtype changes; numerical agreement alone does not establish type fidelity.