pnnx support torch exported program - #6933
mingshi2333 wants to merge 49 commits into
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0163f00c6d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1e0f4d8452
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a148f65346
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f4f905dd29
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 81892df0a4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 079fb0a9d1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2c8324a5c1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 66ff293c9d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7ae570740a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 38a9ff0e16
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Check observable local alias writes, restore view update shapes, and support bfloat16 attribute fusion. Convert shared integer constants only on native arithmetic branches and reject unsupported empty or complex native state. Keep required expression lowering at optlevel zero. Reuse six existing model tests for native PT2 inference and run the frontend/native selection on Ubuntu, macOS and Windows. Local Torch 2.13 validation: 398 passed, 6 existing skips, 0 failures; paired native selection: 14 passed.
|
Native ncnn inference coverage and correctness update in The new native PT2 tests run the full path: Python is the test harness; inference executes in ncnn's C++ CPU backend through its Python binding. These tests load the generated native model and compare its output with the original PyTorch model. They do not substitute the generated PNNX Python model for native execution.
The six model tests reuse existing fixtures, comparisons and tolerances. Weight-norm parametrizations remain intact during export. A small shared helper replaces duplicated export/conversion/import code; no new Python/C++ test files, tolerance relaxations or expected skips were added in this update. This commit also fixes observable local alias updates, BF16 Attribute reads/writes used during BatchNorm fusion, integer constants on native arithmetic branches without changing shared index storage, and required expression lowering at optlevel=0. It addresses the empty-state review at #6933 (comment): empty/complex native attributes now fail explicitly after PNNX artifacts are saved, before native artifacts are written. The corresponding tests still execute PNNX numerical checks and cannot treat a crash as expected rejection. Validation on Linux, GCC 15, Python 3.13, PyTorch/LibTorch 2.13.0+cpu, with a matching ncnn binding:
Ubuntu/macOS/Windows quick CI now builds the CPU ncnn binding from the same checkout and runs Scope remains inference correctness, not Vulkan performance, ImageNet accuracy benchmarking or universal native coverage of the PNNX operator suite. Native PT2 STFT/iSTFT deployment and derived/data-dependent dynamic shapes are not added in this update. The PR body and README now distinguish these boundaries explicitly. |
Add direct
torch.export.ExportedProgram(.pt2) input support to pnnx.Closes #6366
Usage
pnnx model.pt2 python -c 'import model_pnnx; model_pnnx.export_exported_program()'Shapes, parameters, buffers and constants come from the archive; lifted state does not become runtime input. Optional
inputshape/inputoverrides are checked against the input contract. The generatedexport_exported_program(example_inputs=None)savesmodel_pnnx.pt2and returns its ExportedProgram. It exports the generated inference model, not the original Module's training/state identity.Structure
tools/pnnx/src/model_format.*,pt2_archive.*,storezip.*json_reader.*,exported_program_schema.*exported_program_graph.*exported_program_operator.*exported_program_tensor.*load_exported_program.*main.cpp,ir.*, shared passes andsave_ncnn.*No third-party JSON/ZIP dependency or LibTorch internal PT2 serializer is added. The frontend reuses the existing PNNX/backend passes rather than maintaining a separate PT2 lowering pipeline.
Supported scope
0, with raw tensor payloads. Consumed entries use STORE; unused compressed attachments are ignored. Bounds/CRC are checked and encrypted entries are rejected.aten.sym_size.intand supported mixed constant/symbolic shape lists survive PNNX save/load and re-export. Generated Python checks input ranks, static dimensions, ranges and shared dimensions, following PyTorch's 0/1 convention for a lower bound at most 2.optlevel=0/1/2.Shared passes handle the ATen forms exposed by PT2, including convolution/transposed convolution, normalization, recurrent operators, static weight norm, windows, typed empty lists and singleton unpacking. These changes remain separate from archive parsing.
optlevel=0still runs the existing scalar/expression lowering required for valid PNNX Python, without enabling the full optional optimization passes.Correctness boundaries
2*s0,s0*s1), data-dependent dimensions, dynamic scalar arithmetic/state, keyword user inputs, dict/custom PyTrees, non-tensor user leaves or general control flow.requires_gradandstate_dictkeys are not retained as original Module identity.lower ncnn failed:after PNNX artifacts are saved and before native artifacts are written. Generated native Python rejects unsupported Double/Byte/Char/Short/Bool/BF16/complex/scalar tensor inputs. Native execution has its own operator/batch-layout limits and does not enforce PT2 range guards.Detection, import and residual-operator failures have separate diagnostics. Recognized PT2 archives are not retried as TorchScript. Unsupported native state is tested for an ordinary nonzero exit, retained PNNX artifacts and values, and absent native output in a fresh directory.
Tests and CI
Existing model/operator definitions and numerical assertions are reused. TorchScript and PT2 run in separate processes with separate artifact names; there is no monkeypatch of
torch.jit.trace, removal of weight-norm parametrizations, tolerance relaxation or new expected skip in this update. Expected failures require a matching stage/diagnostic; crashes and unexpected successes fail the test.pt2_frontendpt2_operatorpt2_ncnnpt2The Ubuntu/macOS/Windows quick jobs build pnnx against Torch 2.13 and the CPU ncnn Python binding from the same checkout, then run
pt2_frontendandpt2_ncnn. The existing Linux job retains its Torch 2.12.1 operator/model selection. No additional version-compatibility matrix is introduced. Two existing input-npy cases retain a resource lock for shared input files.Validation
Latest source update:
0c6dbb97, fast-forwarded to this PR on 2026-09-20 after the selected pnnx validation completed.The four new commits since
7af5e93dcover:cdc6ac80: module-scoped FP32 runtime options for native numeric tests, without changing ncnn deployment defaults or comparison tolerances.f01ad9af: escape generated Python path literals, including Windows backslashes, while preserving path values.84b17b47: stop parameter parsing on failed extraction/trailing whitespace and correct fp64-to-fp16 ONNX attribute element counts/allocation, with regression tests.0c6dbb97: recognize the existing Torch 2.9.0 Funnel limitation at its actual export stage. Version, exception and diagnostic checks remain constrained; unexpected success or the wrong failure still fails.This update changes nine pnnx source/test files, +295/-22 lines; no CI files. The C++ source portion is two files, +37/-17. It does not implement new Funnel support or add another expected skip.
Completed fork validation
Validation run 35472659172 completed successfully on
7e83bc91180ac883e6e219be4feb24731b8cf9b2at 2026-09-20 02:41 UTC. All 26 pnnx jobs passed, including the 19 complete Torch/Python matrix entries, three OS quick jobs, prepare, dependency/converter build, CodeQL and all-green. No mandatory job was skipped.The same-head independent CodeQL analysis, push formatting, PR formatting, PR-target formatting and labeler also succeeded before promotion. CodeRabbit's green commit status explicitly says draft review skipped, not review approval. At the pre-push review check, all 18 existing upstream review threads were resolved, with no outstanding changes-requested review.
The six diagnostic-matched expected PT2 skips are unchanged:
Tensor_index,torch_arange,torch_masked_select,quantization_shufflenet_v2_x1_0,pnnx_input_npyandtransformers_funnel_attention. The 407 PT2 entries include importer/helper/operator/native tests; they are not 407 native models.Provenance and limits of this result
The CI-referenced clean candidate
66a109e4and the regrouped four-commit source head0c6dbb97have the identical complete file tree4d50ffe2e145acdd3df45c9d2ad5ee0d201b715c. The validation head differs only by the audited 43 fork-only.github/paths; none were promoted. There was no force-push or merge of the validation PR.The fork adapter reads the candidate's existing
pnnx.ymlmatrix and build/test commands, adapting hosted-runner provisioning and parallelism. Its dependency patch checkout is pinned topnnx/pnnx@340e96f128c1a8a4209dddad2bfcc601f0214aaf, matching the candidate's LibTorch 2.12.1 / TorchVision 0.27.1 / ONNX Runtime 1.27.0 configuration. The three quick jobs use Torch 2.13.0. The older-producer PT2 runs are one-round evidence, not a new continuous compatibility promise.These are completed fork pnnx results obtained before pushing the identical source tree. Checks newly triggered in Tencent/ncnn on
0c6dbb97must be evaluated separately; results do not automatically extend to newer dependencies or a later merge-base tree. The additional whole-ncnn cross-architecture experiment is not part of this passing claim: its hardware/SDK gaps and unrelated core failures are not presented as successes.Post-push upstream blocker
The new upstream head is not yet merge-ready. Azure Pipelines reported
ACTION_REQUIRED/ Skipped due to merge conflicts (check); this is not a numerical-test failure. A non-mutating merge check against the live upstreammaster(1857775c98921d71e1ec2b34dc7d292c72529423, verified at 2026-09-20 02:56 UTC) finds conflicts in eight files:.github/workflows/pnnx.yml,tools/pnnx/src/save_ncnn.cpp, and the sixtest_transformers_{distilbert,layoutlm,longformer,openai,prophetnet,xlnet}_attention.pytests. Synchronizing with that newer upstream tree and revalidating will be a separate follow-up; no unverified merge/rebase or force-push was performed. The completed fork results above apply to the stated validated source tree, not to an unresolved future merge.