diff --git a/ckpts/universal/global_step120/zero/13.attention.query_key_value.weight/exp_avg.pt b/ckpts/universal/global_step120/zero/13.attention.query_key_value.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..d84d3c62a15492de7a7791f751948f8788fe7b93 --- /dev/null +++ b/ckpts/universal/global_step120/zero/13.attention.query_key_value.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:531f2995a2db0536147e6e42164f2cde65629fcb7255ac518b14518ac0bde2bd +size 50332828 diff --git a/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/exp_avg.pt b/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..5eff94c57f4aca55cd147e45b7550484d2621425 --- /dev/null +++ b/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:207fe8b12a35a86a1fee9a325b98a9df613987cfb35840dbc9a37a6e3d7afd28 +size 50332828 diff --git a/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/fp32.pt b/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..ac558129e49dcfe4f25ceaf04bc21ea9e1c1b61b --- /dev/null +++ b/ckpts/universal/global_step120/zero/20.attention.query_key_value.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f46754b6aa3945f5fc64c195bfd2e00e4f1b6aa661a75ec0a16e759110aa594 +size 50332749 diff --git a/ckpts/universal/global_step120/zero/20.mlp.dense_h_to_4h.weight/fp32.pt b/ckpts/universal/global_step120/zero/20.mlp.dense_h_to_4h.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..c805374011119b869b9d189ec01ad3b353f708b8 --- /dev/null +++ b/ckpts/universal/global_step120/zero/20.mlp.dense_h_to_4h.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4c1447572379687b48cdb44389ebcc56babcd74e6d13ad89b0fa79398c68640 +size 33555533 diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e2a0198e0ef829b68bcbba8cc2206ea07207992 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/_beartype.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/_beartype.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cca334eb6518c2be051964257c65591324c87a55 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/_beartype.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/exporter.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/exporter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eed12a0070938622b994a4118a216e2ea51ea92 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/exporter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/io_adapter.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/io_adapter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..360b191e093b2c89ca6f2975265fa2c9fe8195e7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/io_adapter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/jit_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/jit_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1ffb44a966c4d6fcbc440be511421cb4a781f2e Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/jit_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnx_proto_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnx_proto_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf52575c05ce1c77634ceb618033833255e5e389 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnx_proto_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnxruntime.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnxruntime.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..208fb96a92fe8de17b878d28e3b26417a6812a02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/onnxruntime.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/registration.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/registration.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00b9def1074daac556546d4019150dd68ba3055e Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/__pycache__/registration.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7659c9763bf67d1d89b2ac80ff69b3165e139bb4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_diagnostic.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_diagnostic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e839f65b316a34e6109f8a0ba33b12639e76e43d Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_diagnostic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_rules.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_rules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56f8528afe811b261828fd0a7e0a7e800f3dccb Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/__pycache__/_rules.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cc36f5e3771fd0e88bd6c2304610f02074893ab Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/_infra.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/_infra.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3561bbf9685d8e4afd3654d6e752551ba207018a Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/_infra.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52394746c4c64cebc47466a6c14e5b7d4b91c899 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/decorator.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b480ead7eb838a5822cf1d3bdadb942b7abebee5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/decorator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/formatter.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/formatter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f38130f24f0186374221a98480ec13c4b8d26e8b Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/formatter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f54fdfa4f51f7f997bf23183a8bf5e7f422e314 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0ac412993bf3683c8d1339c1b4e8e9fa10ce2fd Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_address.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_address.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0b44a9bfe5ad390585b5b9b394e422036106ed0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_address.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d32f222a2768986bb55ab4b2f009ef028a2afc56 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_change.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_change.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..106859d8cfd7199502acdedfa5cd5172c9e2a22d Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_change.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_content.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_content.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d618103f1524d13b5e084c1603272880e1fc21 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_content.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_location.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_location.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34e644763b8547224652eea1071ebed052263c17 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_artifact_location.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_attachment.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_attachment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc9539d6c38bb9d1ffc65a49f88e67fea89e66f Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_attachment.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_code_flow.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_code_flow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73d8b77263f769718e3b646626a40a414c698582 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_code_flow.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_configuration_override.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_configuration_override.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0251f5f3555bbc618e82e18e6b595b010f2ffc27 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_configuration_override.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_conversion.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_conversion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2817a9beb654cd7361f0915bee857149fd2606cb Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_conversion.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63fce7ea3842d6caf33c2035dfbffec66a11d26 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge_traversal.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge_traversal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5cb6718d4a147615b7230446699672cfe614298 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_edge_traversal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_exception.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_exception.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..587ce56a1dc702393f900373420ae67a83161e52 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_exception.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_properties.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_properties.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98f619601e48111ce9fd412ab653989ef93e2a5f Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_properties.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_reference.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_reference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f03fd5037cef179ac06dad1a508c24ee9d249b53 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_reference.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_references.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_references.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de78b03d0f455f7c0dc4b059df43c56fc4ac8ac4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_external_property_file_references.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd16a091254fe671c924121b10fe02584551ea54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph_traversal.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph_traversal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6093eecb7cf46ce97dd842afe64a11bc5ec5d8b Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_graph_traversal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_invocation.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_invocation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a01f43cf330f3e17ba7980afe8fc4fdd1adf5b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_invocation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aefc70af77e4adcf2c0a8e0f0f77685acf6b6787 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location_relationship.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location_relationship.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5b3ebb621b0222c627929428c31411b2507e733 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_location_relationship.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_logical_location.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_logical_location.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f135f14794af0fcf664b67bf16063c8e4f4de7e3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_logical_location.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_message.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_message.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d94c4340b3b9b258187a31555123504ddf162d1a Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_message.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_multiformat_message_string.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_multiformat_message_string.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d7d0b73fdb01c046e4b09d0d5d5f73c6aac62c8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_multiformat_message_string.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_node.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_node.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a072166fa56015353becd21bf1e8391ccee7c22 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_node.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_notification.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_notification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18f961aca180008976cb93128243384615d668c5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_notification.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_property_bag.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_property_bag.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bffc57333b695feba754fea5975a80f44b25754 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_property_bag.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_rectangle.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_rectangle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2db5975ff44bf9aa3c839c398dff45f6490b2682 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_rectangle.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_region.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_region.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c77b6c76d9dbe0b29b7e2b0110f6bc342b74244 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_region.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_replacement.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_replacement.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0e913a50b557f73bdbe8bbbceb465c1aa7ddf16 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_replacement.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_configuration.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_configuration.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ab5afa418cca7ab291220f941a1460b0f1670a1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_configuration.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ee98a13437658cd1611a2eb1ceb1500ec96a5e8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_reference.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_reference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57937c94fc3ecf9a69cc95c49766811e8ba32330 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_reference.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_relationship.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_relationship.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18fb63024f9c5160b29471775716983e1fa09486 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_reporting_descriptor_relationship.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ed65685facb4508ebf01f5e186da2b2390c6ab Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result_provenance.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result_provenance.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed2c8daed271971a17dc5b5415218a0cf6e9554b Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_result_provenance.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1044181708c2e9e155ea4d4647142dd1fc0faa9d Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run_automation_details.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run_automation_details.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9b2b39494e152d3954391fb4c23f5d8167b5ad3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_run_automation_details.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_sarif_log.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_sarif_log.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1584ee8953dc92479a5b3c2df4424265d6bb6e36 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_sarif_log.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_special_locations.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_special_locations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a8ad215d2c76a9c0ec638bc478eebca81ea5dff Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_special_locations.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23260638cec026009190d69dc8f3deb083d9d4cc Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack_frame.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack_frame.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0f0ef1d0632d23f218e2cdb0a210e34fff8a5a0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_stack_frame.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_suppression.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_suppression.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7663ba1f0fea1ba31a4cb6a25524d98016c917d Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_suppression.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..906a426359d5f21f58e6cae1cfd1f8820966785e Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow_location.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow_location.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de8cad042f4dd77cf6a237d81ecd180d36b786dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_thread_flow_location.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e103f30f129b2f906cf5f1581c76e73015639e19 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff471107b87bd099ee9e2f9bd07dd2022b59654b Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component_reference.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component_reference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06bc4b7b52117aebf2a319fdb3afbc9508e0de8e Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_tool_component_reference.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_translation_metadata.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_translation_metadata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b933bcf981bb948eab42c28e7f58d1af95148f Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_translation_metadata.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_version_control_details.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_version_control_details.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6220716465d70ef380b4776f0ec36ca19a4c0c97 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_version_control_details.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_request.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c92a0130bb42cf2b80e05ce357d21e9f5658013 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_response.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_response.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99ad74e0378c4ac373482537abc3f4307b63b3ab Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/_web_response.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e9a29b5c92bf89ce2affddff122553a80094094 Binary files /dev/null and b/venv/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/sarif/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/decomposition_table.py b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/decomposition_table.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3f705ca8676d38809f1b4d66f032340f7e6d1e --- /dev/null +++ b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/decomposition_table.py @@ -0,0 +1,114 @@ +"""Dispatcher for AtenLib functions from onnx-script.""" + +from __future__ import annotations + +from typing import Callable, Dict, Set, Union + +import torch +import torch._ops +import torch.fx + +from torch.onnx._internal import _beartype + +from torch.onnx._internal.fx import registration + + +# NOTE: OnnxRegistry annotation: beartype is a runtime type checker for python3, +# so it doesn't work with TYPE_CHECKING +@_beartype.beartype +def _create_onnx_supports_op_overload_table( + registry, +) -> Set[Union[torch._ops.OperatorBase, Callable]]: + """ + Creates a set of OperatorBase and Callable objects that represent ONNX-supported PyTorch operations. + + Args: + registry (OnnxRegistry): The ONNX registry for PyTorch. + + Returns: + A collection of OperatorBase and Callable objects representing ONNX-supported PyTorch operations. + """ + table: Set[Union[torch._ops.OperatorBase, Callable]] = set() + + # Some ops in `torch.ops.aten` are not discoverable through `dir(torch.ops.aten)`, + # but retrievable via explicit lookup. + # https://github.com/pytorch/pytorch/issues/99681 + # This is a workaround to make sure we register ONNX symbolic functions for these. + onnx_supported_aten_lookup_table = [ + k.split("::")[1].split(".")[0] + for k in registry._all_registered_ops() + if k.startswith("aten::") + ] + + for op_namespace in (torch.ops.aten, torch.ops.prims): + attr_names = dir(op_namespace) + if op_namespace is torch.ops.aten: + attr_names += onnx_supported_aten_lookup_table + for attr_name in attr_names: + if not hasattr(op_namespace, attr_name): + # torchlib owns some attributes that are not aten ops. + continue + op_overload_packet = getattr(op_namespace, attr_name) + if not isinstance(op_overload_packet, torch._ops.OpOverloadPacket): + continue + + for overload_name in op_overload_packet.overloads(): + op_overload = getattr(op_overload_packet, overload_name) + internal_op_name = registration.OpName.from_qualified_name( + qualified_name=op_overload.name() + ) + # NOTE: If the overload is supported in registry or it's default overload is supported in registry, + # we add it to the table. + if registry.is_registered_op( + namespace=internal_op_name.namespace, + op_name=internal_op_name.op_name, + overload=internal_op_name.overload, + ) or registry.is_registered_op( + namespace=internal_op_name.namespace, + op_name=internal_op_name.op_name, + overload=None, + ): + # This line maps torch.ops.aten.add.Tensor, torch.ops.aten.add.Scalar, torch.ops.aten.add.out, etc + # to "aten::add". This means the exporter for "aten::add" is used for all overloads of "aten::add". + # This is applied to all ops under torch.ops.aten. + table.add(op_overload) + return table + + +@_beartype.beartype +def create_onnx_friendly_decomposition_table( + registry, +) -> Dict[torch._ops.OperatorBase, Callable]: + """ + This function creates a dictionary of op overloads and their decomposition functions + for ops that do not have ONNX symbolic functions. If an op already has an ONNX symbolic function, + its decomposition function is excluded from the table. The decomposition table is a subset of PyTorch's + built-in aten-to-aten decomposition. + + Args: + registry (torch.onnx.OnnxRegistry): The ONNX registry for PyTorch. + + Returns: + Dict[torch._ops.OperatorBase, Callable]: A dictionary that maps op overloads to their corresponding + decomposition functions. + """ + decomposition_table: Dict[torch._ops.OperatorBase, Callable] = {} + # Dictionary that maps torch.ops.aten.* to exporter look up key; e.g., + # _OP_OVERLOAD_TO_EXPORTER_KEY_TABLE[torch.add.Tensor] is "aten::add". + _ONNX_SUPPORT_OP_OVERLOADS = _create_onnx_supports_op_overload_table(registry) + + # NOTE: If we import torch._decomp, we will get RuntimeError: Only a single + # TORCH_LIBRARY can be used to register the namespace nvprims; please put all of your + # definitions in a single TORCH_LIBRARY block. + for op_overload, decomp_fn in torch._decomp.decomposition_table.items(): # type: ignore[attr-defined] + # Skip decomposition into "prim::*" ops (defined in 'torch._refs'), because they + # are not generally supported by ONNX. + # Skip decomposition for op_overload as long as that op_overload has a corresponding ONNX + # symbolic function. + if ( + "torch._refs" in decomp_fn.__module__ + or op_overload in _ONNX_SUPPORT_OP_OVERLOADS + ): + continue + decomposition_table[op_overload] = decomp_fn + return decomposition_table diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/diagnostics.py b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..11e4c79f2e1a3400c435f6aafcc80fb451de549e --- /dev/null +++ b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/diagnostics.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +import dataclasses + +import functools +import logging + +from typing import Any, Optional + +import onnxscript # type: ignore[import] +from onnxscript.function_libs.torch_lib import graph_building # type: ignore[import] + +import torch +import torch.fx +from torch.onnx._internal import diagnostics +from torch.onnx._internal.diagnostics import infra +from torch.onnx._internal.diagnostics.infra import decorator, formatter +from torch.onnx._internal.fx import registration, type_utils as fx_type_utils + +# NOTE: The following limits are for the number of items to display in diagnostics for +# a list, tuple or dict. The limit is picked such that common useful scenarios such as +# operator arguments are covered, while preventing excessive processing loads on considerably +# large containers such as the dictionary mapping from fx to onnx nodes. +_CONTAINER_ITEM_LIMIT: int = 10 + +# NOTE(bowbao): This is a shim over `torch.onnx._internal.diagnostics`, which is +# used in `torch.onnx`, and loaded with `torch`. Hence anything related to `onnxscript` +# cannot be put there. + +# [NOTE: `dynamo_export` diagnostics logging] +# The 'dynamo_export' diagnostics leverages the PT2 artifact logger to handle the verbosity +# level of logs that are recorded in each SARIF log diagnostic. In addition to SARIF log, +# terminal logging is by default disabled. Terminal logging can be activated by setting +# the environment variable `TORCH_LOGS="onnx_diagnostics"`. When the environment variable +# is set, it also fixes logging level to `logging.DEBUG`, overriding the verbosity level +# specified in the diagnostic options. +# See `torch/_logging/__init__.py` for more on PT2 logging. +_ONNX_DIAGNOSTICS_ARTIFACT_LOGGER_NAME = "onnx_diagnostics" +diagnostic_logger = torch._logging.getArtifactLogger( + "torch.onnx", _ONNX_DIAGNOSTICS_ARTIFACT_LOGGER_NAME +) + + +def is_onnx_diagnostics_log_artifact_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled( + _ONNX_DIAGNOSTICS_ARTIFACT_LOGGER_NAME + ) + + +@functools.singledispatch +def _format_argument(obj: Any) -> str: + return formatter.format_argument(obj) + + +def format_argument(obj: Any) -> str: + formatter = _format_argument.dispatch(type(obj)) + return formatter(obj) + + +# NOTE: EDITING BELOW? READ THIS FIRST! +# +# The below functions register the `format_argument` function for different types via +# `functools.singledispatch` registry. These are invoked by the diagnostics system +# when recording function arguments and return values as part of a diagnostic. +# Hence, code with heavy workload should be avoided. Things to avoid for example: +# `torch.fx.GraphModule.print_readable()`. + + +@_format_argument.register +def _torch_nn_module(obj: torch.nn.Module) -> str: + return f"torch.nn.Module({obj.__class__.__name__})" + + +@_format_argument.register +def _torch_fx_graph_module(obj: torch.fx.GraphModule) -> str: + return f"torch.fx.GraphModule({obj.__class__.__name__})" + + +@_format_argument.register +def _torch_fx_node(obj: torch.fx.Node) -> str: + node_string = f"fx.Node({obj.target})[{obj.op}]:" + if "val" not in obj.meta: + return node_string + "None" + return node_string + format_argument(obj.meta["val"]) + + +@_format_argument.register +def _torch_fx_symbolic_bool(obj: torch.SymBool) -> str: + return f"SymBool({obj})" + + +@_format_argument.register +def _torch_fx_symbolic_int(obj: torch.SymInt) -> str: + return f"SymInt({obj})" + + +@_format_argument.register +def _torch_fx_symbolic_float(obj: torch.SymFloat) -> str: + return f"SymFloat({obj})" + + +@_format_argument.register +def _torch_tensor(obj: torch.Tensor) -> str: + return f"Tensor({fx_type_utils.from_torch_dtype_to_abbr(obj.dtype)}{_stringify_shape(obj.shape)})" + + +@_format_argument.register +def _int(obj: int) -> str: + return str(obj) + + +@_format_argument.register +def _float(obj: float) -> str: + return str(obj) + + +@_format_argument.register +def _bool(obj: bool) -> str: + return str(obj) + + +@_format_argument.register +def _str(obj: str) -> str: + return obj + + +@_format_argument.register +def _registration_onnx_function(obj: registration.ONNXFunction) -> str: + # TODO: Compact display of `param_schema`. + return f"registration.ONNXFunction({obj.op_full_name}, is_custom={obj.is_custom}, is_complex={obj.is_complex})" + + +@_format_argument.register +def _list(obj: list) -> str: + list_string = f"List[length={len(obj)}](\n" + if not obj: + return list_string + "None)" + for i, item in enumerate(obj): + if i >= _CONTAINER_ITEM_LIMIT: + # NOTE: Print only first _CONTAINER_ITEM_LIMIT items. + list_string += "...,\n" + break + list_string += f"{format_argument(item)},\n" + return list_string + ")" + + +@_format_argument.register +def _tuple(obj: tuple) -> str: + tuple_string = f"Tuple[length={len(obj)}](\n" + if not obj: + return tuple_string + "None)" + for i, item in enumerate(obj): + if i >= _CONTAINER_ITEM_LIMIT: + # NOTE: Print only first _CONTAINER_ITEM_LIMIT items. + tuple_string += "...,\n" + break + tuple_string += f"{format_argument(item)},\n" + return tuple_string + ")" + + +@_format_argument.register +def _dict(obj: dict) -> str: + dict_string = f"Dict[length={len(obj)}](\n" + if not obj: + return dict_string + "None)" + for i, (key, value) in enumerate(obj.items()): + if i >= _CONTAINER_ITEM_LIMIT: + # NOTE: Print only first _CONTAINER_ITEM_LIMIT items. + dict_string += "...\n" + break + dict_string += f"{key}: {format_argument(value)},\n" + return dict_string + ")" + + +@_format_argument.register +def _torch_nn_parameter(obj: torch.nn.Parameter) -> str: + return f"Parameter({format_argument(obj.data)})" + + +@_format_argument.register +def _onnxscript_torch_script_tensor(obj: graph_building.TorchScriptTensor) -> str: + return f"`TorchScriptTensor({fx_type_utils.from_torch_dtype_to_abbr(obj.dtype)}{_stringify_shape(obj.shape)})`" # type: ignore[arg-type] # noqa: B950 + + +@_format_argument.register +def _onnxscript_onnx_function(obj: onnxscript.OnnxFunction) -> str: + return f"`OnnxFunction({obj.name})`" + + +@_format_argument.register +def _onnxscript_traced_onnx_function(obj: onnxscript.TracedOnnxFunction) -> str: + return f"`TracedOnnxFunction({obj.name})`" + + +# from torch/fx/graph.py to follow torch format +def _stringify_shape(shape: Optional[torch.Size]) -> str: + if shape is None: + return "" + return f"[{', '.join(str(x) for x in shape)}]" + + +rules = diagnostics.rules +levels = diagnostics.levels +RuntimeErrorWithDiagnostic = infra.RuntimeErrorWithDiagnostic +LazyString = formatter.LazyString +DiagnosticOptions = infra.DiagnosticOptions + + +@dataclasses.dataclass +class Diagnostic(infra.Diagnostic): + logger: logging.Logger = dataclasses.field(init=False, default=diagnostic_logger) + + def log(self, level: int, message: str, *args, **kwargs) -> None: + if self.logger.isEnabledFor(level): + formatted_message = message % args + if is_onnx_diagnostics_log_artifact_enabled(): + # Only log to terminal if artifact is enabled. + # See [NOTE: `dynamo_export` diagnostics logging] for details. + self.logger.log(level, formatted_message, **kwargs) + + self.additional_messages.append(formatted_message) + + +@dataclasses.dataclass +class DiagnosticContext(infra.DiagnosticContext[Diagnostic]): + logger: logging.Logger = dataclasses.field(init=False, default=diagnostic_logger) + _bound_diagnostic_type: type[Diagnostic] = dataclasses.field( + init=False, default=Diagnostic + ) + + def __enter__(self): + self._previous_log_level = self.logger.level + # Adjust the logger level based on `options.verbosity_level` and the environment + # variable `TORCH_LOGS`. See [NOTE: `dynamo_export` diagnostics logging] for details. + if not is_onnx_diagnostics_log_artifact_enabled(): + return super().__enter__() + else: + return self + + +diagnose_call = functools.partial( + decorator.diagnose_call, + diagnostic_type=Diagnostic, + format_argument=format_argument, +) + + +@dataclasses.dataclass +class UnsupportedFxNodeDiagnostic(Diagnostic): + unsupported_fx_node: Optional[torch.fx.Node] = None + + def __post_init__(self) -> None: + super().__post_init__() + # NOTE: This is a hack to make sure that the additional fields must be set and + # not None. Ideally they should not be set as optional. But this is a known + # limitation with `dataclasses`. Resolvable in Python 3.10 with `kw_only=True`. + # https://stackoverflow.com/questions/69711886/python-dataclasses-inheritance-and-default-values + if self.unsupported_fx_node is None: + raise ValueError("unsupported_fx_node must be specified.") diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d230f1d121f8d3d8f16426453acfdb4af9b5c1dd --- /dev/null +++ b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py @@ -0,0 +1,903 @@ +"""Dispatcher for AtenLib functions from onnx-script.""" + +from __future__ import annotations + +import logging +import operator +import types +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Sequence, + Set, + Tuple, + TYPE_CHECKING, + Union, +) + +import torch +import torch._ops +import torch.fx +from torch.onnx._internal import _beartype +from torch.onnx._internal.fx import ( + diagnostics, + registration, + type_utils as fx_type_utils, +) + +if TYPE_CHECKING: + import onnxscript # type: ignore[import] + + from torch.onnx import OnnxRegistry + + +# For beartype +from onnxscript.function_libs.torch_lib import ( # type: ignore[import] + graph_building as onnxscript_graph_building, +) + + +@_beartype.beartype +def _find_opschema_matched_symbolic_function_disagnostic_message_formatter( + fn: Callable, + self, + node: torch.fx.Node, + default_and_custom_functions: List[registration.ONNXFunction], + *args, + **kwargs, +) -> str: + """Format the diagnostic message for the nearest match warning.""" + all_function_overload_names = "" + for symbolic_func in default_and_custom_functions: + overload_func = symbolic_func.onnx_function + all_function_overload_names += f"ONNX Node: {overload_func.name}[opset={overload_func.opset};is_custom={symbolic_func.is_custom}]. \n" # noqa: B950 + return f"FX Node: {node.target}. \n" f"{all_function_overload_names}" + + +@_beartype.beartype +def _find_operator_overloads_in_onnx_registry_disagnostic_message_formatter( + fn: Callable, + self, + node: torch.fx.Node, + *args, + **kwargs, +) -> str: + """Format the diagnostic message for the nearest match warning.""" + return f"Searching operator overload: '{node.target}' in onnx registry...\n" + + +class OnnxFunctionDispatcher: + """A dispatcher that finds the best ONNX Function for ATen/Custom operators. + + It uses the `torch.ops` name to find the function. If not found, it falls back to default. + Otherwise, the best match is found among all function overloads. An exact match has + higher precedence over the closest ones. + + Below is a breakdown on how the dispatch mechanism works: + + 1. Use the torch.ops name to find the function: + a. Check if the ATen overload exists in the registry. + b. If not, check if the default overload exists in the registry. + + 2. Find the nearest match among all overloaded functions: + a. If the types match perfectly, select the function. + b. Otherwise, find the nearest one with the highest matching score. Because of + the potential wrongly annotated dtypes and attributes matching, we use + nearest match to find the best function once the aten name is targeted. + + 3. Tie-breaker: If there are multiple nearest matches, we will select the one with + the highest matching score. + + NOTE: The nearest match `doesn't guarantee` a correct match, and a warning message is logged. + """ + + def __init__( + self, + onnx_registry: "OnnxRegistry", + diagnostic_context: diagnostics.DiagnosticContext, + ): + """Initialize the ONNX Function dispatcher. + + Args: + onnx_registry: The ONNX registry. + diagnostic_context: The diagnostic context to use for reporting errors. + """ + self.onnx_registry = onnx_registry + self.diagnostic_context = diagnostic_context + + @_beartype.beartype + def dispatch( + self, + node: torch.fx.Node, + onnx_args: Sequence[ + Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, complex] + ] + ], + onnx_kwargs: Dict[str, fx_type_utils.Argument], + diagnostic_context: diagnostics.DiagnosticContext, + ) -> Union["onnxscript.OnnxFunction", "onnxscript.TracedOnnxFunction"]: + """Dispatches an ONNX function based on the given FX node, arguments, and keyword arguments. + Args: + node: The TorchFX node to dispatch the function for. + onnx_args: The arguments of the ONNX function. + onnx_kwargs: The keyword arguments of the ONNX function. + diagnostic_context: The diagnostic context to use for reporting errors. + Returns: + Either an `onnxscript.OnnxFunction` or `onnxscript.TracedOnnxFunction` instance based on the dispatch algorithm. + Raises: + RuntimeError: If there are no overloaded functions available for the given FX node. + """ + # If there are no overloaded functions available for the given FX node, raise an + # unsupported error + default_and_custom_functions = self.get_function_overloads( + node, diagnostic_context + ) + + # If there are overloaded functions available, we will find one that perfect or + # nearest matches the given arguments and keyword arguments + return self._find_the_perfect_or_nearest_match_onnxfunction( + node, + default_and_custom_functions, + onnx_args, + onnx_kwargs, + diagnostic_context, + ) + + @_beartype.beartype + def _filter_or_keep_complex( + self, + node, + default_and_custom_functions: List[registration.ONNXFunction], + diagnostic_context: diagnostics.DiagnosticContext, + ) -> List[registration.ONNXFunction]: + """Filter the complex functions if the input has complex dtype.""" + + args_with_complex_dtype = [_is_arg_with_complex_dtype(arg) for arg in node.args] + if any(args_with_complex_dtype): + default_and_custom_functions = [ + func for func in default_and_custom_functions if func.is_complex + ] + # If we can't find the complex function group, raise error. + if not default_and_custom_functions: + op_full_name = self._get_aten_name( + node, diagnostic_context + ).qualified_name() + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Cannot find any COMPLEX symbolic function for {op_full_name}, " + f"which should be registered under {node.target}.", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + else: + default_and_custom_functions = [ + func for func in default_and_custom_functions if not func.is_complex + ] + # If we can't find the complex function group, raise error. + if not default_and_custom_functions: + op_full_name = self._get_aten_name( + node, diagnostic_context + ).qualified_name() + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Can ONLY find COMPLEX symbolic function for {op_full_name}, " + f"which should be registered under {node.target}.", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + return default_and_custom_functions + + @_beartype.beartype + @diagnostics.diagnose_call( + diagnostics.rules.find_opschema_matched_symbolic_function, + diagnostic_message_formatter=_find_opschema_matched_symbolic_function_disagnostic_message_formatter, + ) + def _find_the_perfect_or_nearest_match_onnxfunction( + self, + node: torch.fx.Node, # this is used in diagnostic_message_formatter + default_and_custom_functions: List[registration.ONNXFunction], + onnx_args: Sequence[ + Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, complex] + ] + ], + onnx_kwargs: Dict[str, fx_type_utils.Argument], + diagnostic_context: diagnostics.DiagnosticContext, + ): + """Find the perfect/nearest matched OnnxFunction for the given FX node, arguments, and keyword arguments. + + Args: + default_and_custom_functions: The list includes overloaded functions, with + custom ones appearing after the default ones. + onnx_args: Arguments organized in PyTorch inputs way. + onnx_kwargs: Keyword arguments organized in PyTorch inputs way. + diagnostic_context: The diagnostic context to use for reporting errors. + + Returns: + Either an `onnxscript.OnnxFunction` or `onnxscript.TracedOnnxFunction` instance based on the dispatch algorithm. + Raises: + RuntimeError: If there are no overloaded functions available for the given FX node. + """ + overload_match_ranking: Dict[registration.ONNXFunction, Optional[int]] = {} + diagnostic = diagnostic_context.inflight_diagnostic() + + # Iterate the overloaded functions in reverse order to prioritize the custom ones + # over the default ones, and find the perfect match. + for symbolic_function in reversed(default_and_custom_functions): + function_opschema = _OnnxSchemaChecker(symbolic_function.onnx_function) + + # NOTE: 1. If the perfect match is found, return the function + if function_opschema.perfect_match_inputs( + diagnostic, onnx_args, onnx_kwargs + ): + return symbolic_function.onnx_function + # Record the match score for the nearest match if it's not the perfect match + overload_match_ranking[symbolic_function] = function_opschema.match_score + + # NOTE: 2. If there is no perfect match, find the nearest match among the nearest matche candidates + # If there is no nearest match, raise an error + overload_match_ranking = { + k: v for k, v in overload_match_ranking.items() if v is not None + } + if not overload_match_ranking: + # If there are no overloaded functions available for the given FX node, raise an + # unsupported error + op_full_name = self._get_aten_name( + node, diagnostic_context + ).qualified_name() + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Cannot find any perfect/nearest match of symbolic function for {op_full_name}," + f"which should be registered under {node.target}.", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + + diagnostic.warning( + "### Exact match is not found!\n" + "Cannot find a perfect match of symbolic overload, " + "a nearest match is found. Please check the ONNX output carefully. \n", + ) + diagnostic.level = diagnostics.levels.WARNING + # NOTE: 3. Tie breaker: if there are multiple nearest matches, we will choose the one + # that is custom first. If there are multiple custom ones, we will choose the one + # that is added lastly in the list. + symbolic_function_list: List[registration.ONNXFunction] = sorted( + overload_match_ranking, + key=lambda k: ( + overload_match_ranking[k], + k.is_custom, + default_and_custom_functions.index(k), + ), + reverse=True, + ) + return symbolic_function_list[0].onnx_function + + @_beartype.beartype + def _get_aten_name( + self, node: torch.fx.Node, diagnostic_context: diagnostics.DiagnosticContext + ) -> registration.OpName: + """Get the OpName from the target. + + Args: + node: The TorchFX node to get the aten name for. + diagnostic_context: The diagnostic context to use for reporting errors. + + Returns: + The internal op name within dataclass: registration.OpName. + """ + if node.target == operator.getitem: + return registration.OpName.from_name_parts( + namespace="aten", op_name="getitem" + ) + if isinstance(node.target, torch._ops.OpOverloadPacket): + # aten::sym_size is the only OverloadPacket that we support. + # schema: aten::sym_size(Tensor self, int dim) -> Tensor + if node.target != torch.ops.aten.sym_size: + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Unsupported OverloadPacket: {node.target}, aten.sym_size is the only allowed OverloadPacket!", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + # TODO(titaiwang): aten::sym_size has overload, but fx graph is using + # overloadpacket for some reasons. + # https://github.com/pytorch/pytorch/issues/97201 + aten_op_default = node.target.default + return registration.OpName.from_op_overload(op_overload=aten_op_default) # type: ignore[no-any-return] + + if isinstance(node.target, types.BuiltinFunctionType): + # Make sure it's symint/symfloat consuming builtin ops. + for node_arg in node.args: + if (not isinstance(node_arg, (torch.fx.Node, int, float))) or ( + isinstance(node_arg, torch.fx.Node) + and not fx_type_utils.is_torch_symbolic_type(node_arg.meta["val"]) + ): + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Unsupported node arg: {node_arg} (type {type(node_arg)}) with builtin function: {node.target}," + " only int/float/SymInt/SymFloat is supported with built-in ops!", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + return registration.OpName.from_builtin_function(node.target) + + if isinstance(node.target, torch._ops.OpOverload): + return registration.OpName.from_op_overload(op_overload=node.target) + + # Unexpected target, raise error. + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Unknown call_function target: {node.target}", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + + @_beartype.beartype + @diagnostics.diagnose_call( + diagnostics.rules.find_operator_overloads_in_onnx_registry, + diagnostic_message_formatter=_find_operator_overloads_in_onnx_registry_disagnostic_message_formatter, + ) + def get_function_overloads( + self, + node: torch.fx.Node, + diagnostic_context: diagnostics.DiagnosticContext, + ) -> List[registration.ONNXFunction]: + """Get the function overloads from the registry. + + Args: + node: The node to get the function overloads for. + diagnostic_context: The diagnostic context to use for reporting errors. + + Returns: + The list contains ONNXFunctions, starting with the default ones and + followed by any custom ones. + """ + + internal_opname: registration.OpName = self._get_aten_name( + node=node, diagnostic_context=diagnostic_context + ) + + # If the ATen/Custom operators are not registered, the group will be None. + # And non-registered ATen/Custom operators will trigger error in the next step. + function_group: Optional[List[registration.ONNXFunction]] = None + + function_group = self.onnx_registry.get_op_functions( + namespace=internal_opname.namespace, + op_name=internal_opname.op_name, + overload=internal_opname.overload, + ) + + # NOTE: Fall back to default overload if the ONNX registry doesn't have the overload. + if function_group is None: + function_group = self.onnx_registry.get_op_functions( + namespace=internal_opname.namespace, + op_name=internal_opname.op_name, + overload=None, + ) + if function_group is not None: + op_full_name = internal_opname.qualified_name() + diagnostic = diagnostic_context.inflight_diagnostic() + diagnostic.warning( + "### The operator overload is not found in onnx registry!\n" + "Cannot find the operator overload in onnx registry, but " + "the default overload is found. Please check the ONNX output carefully. \n", + ) + diagnostic.level = diagnostics.levels.WARNING + + if function_group is not None: + # NOTE: If the input has complex dtype, we will only dispatch to the complex functions. + function_group = self._filter_or_keep_complex( + node, function_group, diagnostic_context + ) + return function_group # type: ignore[return-value] + + op_full_name = internal_opname.qualified_name() + diagnostic = diagnostics.UnsupportedFxNodeDiagnostic( + diagnostics.rules.no_symbolic_function_for_call_function, + diagnostics.levels.ERROR, + f"Cannot find symbolic function for {op_full_name}, " + f"which should be registered under {node.target}.", + unsupported_fx_node=node, + ) + diagnostic_context.log(diagnostic) + raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic) + + +class _OnnxSchemaChecker: + """ + The OnnxSchemaChecker class is a checker for ONNX OpSchema and param schema. + + It provides methods to check for input compatibility based on the OpSchema. It also + provides a matching score to indicate how well the OpSchema matches the input and + kwargs types. A function will be evaluated as perfect match, nearest match eligible, + or no match. + + Here are some common examples in categories: + + 1. [NOTE: Perfect match]: The number of inputs and attributes are exactly the same as + the OpSchema. The types of inputs and attributes are exactly the same as the + OpSchema. + + ```python + inputs = (Tensor[2, 3], Tensor[2, 3]) + attributes = {"alpha": 1.0} + + @torch_op("aten::op") + def aten_op(self: TReal, other: TReal, alpha: float = 1) -> TReal: + ... + + ``` + Result: Perfect match. + + 2. [NOTE: Optional input]: The dispatcher recognizes optional inputs. However, + the input can't be ignored. None must be provided. + + ```python + inputs = (Tensor([2, 3]), None) + attributes = {} + + aten_op(X: TTensor, Y: Optional[INT64]): + ... + ``` + Result: Perfect match. + Real example: `aten::convolution`. + + 3. [NOTE: Different attributes]: If an attribute is provided with value, it's + a must to match the attribute in function signature. + ```python + inputs = (Tensor([2, 3]),) + attributes = {"a":1, "b":2} + + aten_op(X: TTensor, a: int): + ... + ``` + Result: No match. + Real example: `aten::div` vs `aten::div.Tensor_mode`. + + 4. [NOTE: Default attributes]: Default attribute will fill in the value into + inputs/attributes. + ```python + inputs = (Tensor([2, 3]),) + attributes = {} + + aten_op(X: TTensor, a: int = 3): + ... + ``` + Result: Perfect match. + Real example: `aten::clone` + + 5. [NOTE: Ignore attribute with None value]: The attributes with None value + will be ignored in matching. + ```python + inputs = (Tensor([2, 3]),) + attributes = {"a": None} + + aten_op(X: TTensor): + ... + ``` + Result: Perfect match. + + ```python + inputs = (Tensor([2, 3]),) + attributes = {"a": None} + + aten_op(X: TTensor, a: int = 3): + ... + ``` + Result: Nearest match eligible. + + Real example: `aten::div` vs `aten::div.Tensor_mode`. + + Attributes: + onnxfunction: The OnnxFunction. + param_schema: The parameter schema defined in the OnnxFunction. + op_schema: The ONNX OpSchema. + type_constraints: The type constraints defined in the OpSchema. + attributes: The attributes defined in the OpSchema. + _matching_score: The matching score of the OnnxSchemaChecker . + + """ + + def __init__( + self, + onnxfunction: Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction], + ): + """Initialize the OnnxSchemaChecker . + + Args: + onnxfunction: The OnnxFunction. + """ + self.onnxfunction = onnxfunction + self.param_schema = self.onnxfunction.param_schemas() + op_schema = self.onnxfunction.op_schema + # Both `OnnxFunction` and `TracedOnnxFunction` never return None for `op_schema`. + # However their base class would. Hence return type is annotated as Optional[OpSchema]. + assert op_schema is not None + self.op_schema = op_schema + self.type_constraints = { + # "T": {"tensor(int64)"} + constraint.type_param_str: set(constraint.allowed_type_strs) + for constraint in self.op_schema.type_constraints + } + self.attributes = self.op_schema.attributes + self._matching_score: Optional[int] = None + + @property + def match_score(self) -> Optional[int]: + """The matching score of the OnnxSchemaChecker . + + If this remains None, it means the matching score has not been calculated, + and it's not a nearest match candidate. + + Returns: + The matching score of the OnnxSchemaChecker . + """ + return self._matching_score + + @_beartype.beartype + def perfect_match_inputs( + self, + diagnostic: diagnostics.Diagnostic, + args: Sequence[ + Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, complex] + ] + ], + kwargs: Dict[str, fx_type_utils.Argument], + ) -> bool: + """Check if the inputs perfectly match the OpSchema requirements. + + The definition of perfect match is that the input types are all in the type + constraints and the number of inputs matches the number of inputs in the + OpSchema. + + Checking steps: + 1. The function signature matches the inputs number, and attribute names. + 2. The input/attribute types are all in the type constraints. + + A function should at least pass the first step to be eligible for the + nearest matching. + + Args: + diagnostic: The diagnostic to use for logging detailed info. + args: The input arguments organized in PyTorch inputs way. + kwargs: The input keyword arguments organized in PyTorch inputs way. + + Returns: + True if the inputs match the requirements, False otherwise. + """ + + # NOTE: OnnxFunction does not have the same function signature as the original + # PyTorch operator. We need to separate the input/attributes from the arguments. + ( + function_inputs, + function_attributes, + ) = self._separate_input_attributes_from_arguments( + self.param_schema, + args, + kwargs, + fill_defaults=True, # fill defaults for optional arguments to match + ) + with diagnostic.log_section(logging.INFO, "Checking perfect match..."): + diagnostic.info( + "%s", + diagnostics.LazyString(diagnostics.format_argument, self.onnxfunction), + ) + # NOTE: 1. Check if the input number and attribute names match the + # OpSchema. If it's not, we know the function is not eligible to be a perfect + # match, nor a nearest match. + # We use is_perfect_match to postpone the return value to the end + # of the function, as we want to log all the mismatch info. + is_perfect_match = True + if len(function_inputs) != len(self.op_schema.inputs): + with diagnostic.log_section( + logging.INFO, "Failed: input number mismatch!" + ): + diagnostic.info( + "Actual %d vs expected %d", + len(function_inputs), + len(self.op_schema.inputs), + ) + diagnostic.info("The function is not a nearest match candidate.") + is_perfect_match = False + + if set(function_attributes) != set(self.attributes): + with diagnostic.log_section( + logging.INFO, "Failed: attribute mismatch!" + ): + diagnostic.info( + "%s", + diagnostics.LazyString( + lambda: f"Actual {set(function_attributes)} vs expected {set(self.attributes)}", + ), + ) + diagnostic.info("The function is not a nearest match candidate.") + is_perfect_match = False + + # If it's already not a perfect match, we can return False directly. Further + # checking is only for the functions that are eligible for nearest match. + if not is_perfect_match: + return False + + # NOTE: 2. The dtypes of inputs and attributes should be in the + # type constraints of the OpSchema. If they are not, we know the function is not + # eligible to be a perfect match, but can be a nearest match candidate. + for schema_input, torch_input in zip( + self.op_schema.inputs, function_inputs + ): + torch_input_compatible_types = _find_onnx_data_type(torch_input) + allowed_types = self.type_constraints[schema_input.type_str] + if not allowed_types.intersection( + torch_input_compatible_types + ) and not any( + fx_type_utils.is_optional_onnx_dtype_str(onnx_type_str) + for onnx_type_str in allowed_types + ): + # If torch_input_compatible_types isn't in allowed_types + # of this input defined in the OpSchema, we know the function + # and the input are not compatible + with diagnostic.log_section( + logging.INFO, + "Failed: input type mismatch for input '%s'!", + schema_input.name, + ): + diagnostic.info( + "Actual %s vs\nExpected %s", + torch_input_compatible_types, + allowed_types, + ) + is_perfect_match = False + + for attribute_name, attribute in function_attributes.items(): + if not self._match_onnx_attribute_type(attribute_name, attribute): + # If the attribute type of the OpSchema and the attribute type don't match, + # we know the function and the input are not compatible + with diagnostic.log_section( + logging.INFO, + "Failed: attribute '%s' type mismatch!", + attribute_name, + ): + diagnostic.info( + "Actual %s vs\nExpected %s", + type(attribute), + self.attributes[attribute_name].type, + ) + is_perfect_match = False + + # NOTE: This is still a candidate for nearest match, as it only mismatches attributes on dtype. + self._record_matching_score(function_inputs, function_attributes) + diagnostic.info("match score: %d", self.match_score) + return is_perfect_match + + @_beartype.beartype + def _match_onnx_attribute_type( + self, + attribute_name: str, + attribute: Union[ + fx_type_utils.Argument, onnxscript_graph_building.TorchScriptTensor + ], + is_sequence: bool = False, + ) -> bool: + if isinstance(attribute, (int, float, bool, str)): + attribute_onnx_type = fx_type_utils.from_python_type_to_onnx_attribute_type( + type(attribute), is_sequence=is_sequence + ) + if attribute_onnx_type != self.attributes[attribute_name].type: + return False + # If the attribute is an empty list, we don't know the type of the list + # so it's a mismatch + elif isinstance(attribute, (list, tuple)) and attribute: + return self._match_onnx_attribute_type( + attribute_name, attribute[0], is_sequence=True + ) + else: + # NOTE: Unrecognized attribute type + return False + return True + + @_beartype.beartype + def _record_matching_score( + self, + inputs: Sequence[ + Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, complex] + ] + ], + attributes: Dict[str, fx_type_utils.Argument], + ): + """Calculate the inputs matching score of the OpSchema requirements to find the nearest match. + + Only the functions which have the same number of inputs and attributes as the + OpSchema are eligible to be a nearest match candidate. Thus, we don't need to + check the length of inputs and attributes here, and only check the types of + inputs and attributes. + + How the matchsing score is calculated: + score += 1 if one input/attribute type is in the type constraints. + + Limitations: + None/NoeType/[] could result in zero matches, and the same score of overloads, + which will be recorded in SARIF. + + Args: + inputs: The input arguments. + attributes: The input keyword arguments. + + Returns: + True if the inputs match the requirements, False otherwise. + """ + self._matching_score = 0 + # If they have different length of arguments, the score would be lower to those + # functions which have the same length of arguments. + for schema_input, torch_input in zip(self.op_schema.inputs, inputs): + torch_input_compatible_types = _find_onnx_data_type(torch_input) + allowed_types = self.type_constraints[schema_input.type_str] + if allowed_types.intersection(torch_input_compatible_types): + # If torch_input_compatible_types is in allowed_types + # of this input defined in the OpSchema, we know the function + # and the input are compatible + self._matching_score += 1 + # NOTE: The penalty is applied to those functions which have different attributes. + for attribute_name, attribute_proto in self.attributes.items(): + attribute = attributes[attribute_name] + attribute_onnx_type = fx_type_utils.from_python_type_to_onnx_attribute_type( + type(attribute) + ) + if attribute_onnx_type != attribute_proto.type: + # If the attribute type of the OpSchema and the attribute type don't match, + # we know the function and the input are not compatible + self._matching_score -= 1 + + # NOTE: Referenced from onnxscript internal function. + # Importing this function makes the code less robust, as it is not a public API. + @_beartype.beartype + def _separate_input_attributes_from_arguments( + self, + param_schemas: Sequence["onnxscript.values.ParamSchema"], + args: Sequence[ + Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, complex] + ] + ], + kwargs: Dict[str, fx_type_utils.Argument], + fill_defaults: bool = True, + ) -> Tuple[List[Any], Dict[str, Any]]: + """Separate Python args and kwargs into ONNX inputs and attributes. + + Extra_kwargs are ignored if their values are None. For example, if the + OpSchema has an attribute "rounding_mode" and the caller provides + "rounding_mode=None", the attribute "rounding_mode" will not be included + in the returned attributes when the OnnxFunction signature doesn't have + "rounding_mode" as an attribute. + + Args: + param_schemas: The parameter schemas of an Op or a OnnxFunction. + args: The Python positional arguments supplied by the caller. + kwargs: The Python keyword arguments supplied by the caller. + fill_defaults: Whether to fill the default values for attributes. + + Returns: + A tuple of two elements: + - A list of ONNX inputs. + - An dictionary of ONNX attribute names and values. + + Raises: + TypeError: When allow_extra_kwargs is False and there are unknown kwargs. + TypeError: When a required input is not provided. + """ + # args, kwargs and param_schemas should be all in order + # user may not specify all inputs or attributes + + import onnx + + onnx_inputs: List[Any] = [] + onnx_attributes: Dict[str, Any] = dict() + # NOTE: We need to copy kwargs because we will mutate it + copy_kwargs = kwargs.copy() + for i, param in enumerate(param_schemas): + if param.is_variadic_input: + # Exhaust all remaining args + onnx_inputs.extend(args[i:]) + args = [] + continue + if i < len(args): + if param.is_input: + onnx_inputs.append(args[i]) + else: + onnx_attributes[param.name] = args[i] + elif param.name in copy_kwargs: + if param.is_input: + # Move the input from kwargs to inputs + onnx_inputs.append(copy_kwargs[param.name]) + copy_kwargs.pop(param.name) + else: + onnx_attributes[param.name] = copy_kwargs[param.name] + elif ( + param.is_attribute + and self.attributes[param.name].default_value.type + != onnx.AttributeProto.UNDEFINED # type: ignore[attr-defined] + ): + # User did not provide the attribute + if fill_defaults: + onnx_attributes[param.name] = param.default + # optional input + elif param.is_input: + if fill_defaults: + onnx_inputs.append(None) + + # NOTE: Pick up extra kwargs if it's not None. None is not expected + # as an attribute value in torchlib. + for k, v in copy_kwargs.items(): + if k not in onnx_attributes and v is not None: + onnx_attributes[k] = v + return onnx_inputs, onnx_attributes + + +@_beartype.beartype +def _is_arg_with_complex_dtype(arg: fx_type_utils.Argument) -> bool: + """Check if the node has complex dtype recursively.""" + if ( + isinstance(arg, torch.fx.Node) + and "val" in arg.meta + and isinstance(arg.meta["val"], torch.Tensor) + and torch.is_complex(arg.meta["val"]) + ): + return True + elif isinstance(arg, list): + for item in arg: + return _is_arg_with_complex_dtype(item) + return False + + +@_beartype.beartype +def _find_onnx_data_type( + torch_input: Optional[ + Union[fx_type_utils.TensorLike, str, int, float, bool, list, tuple, complex] + ] +) -> Set[str]: + """Convert inputs data type from torch acceptable dtype to the compatible onnx dtype string.""" + if ( + isinstance(torch_input, fx_type_utils.TensorLike) + and torch_input.dtype is not None + ): + return fx_type_utils.from_torch_dtype_to_onnx_dtype_str(torch_input.dtype) + if isinstance(torch_input, (int, float, bool, str, complex)): + return fx_type_utils.from_torch_dtype_to_onnx_dtype_str(type(torch_input)) + if isinstance(torch_input, (list, tuple)) and torch_input: # [Tensor, Tensor] + set_dtype = _find_onnx_data_type(torch_input[0]) + if any(isinstance(input, fx_type_utils.TensorLike) for input in torch_input): + # NOTE: Any Tensor involved in a list would make it a seq(tensor(onnx_type)) + return {f"seq({dtype})" for dtype in set_dtype} + else: + # constant list of non-tensor type + return set_dtype + if ( + torch_input is None + or ( + isinstance(torch_input, fx_type_utils.TensorLike) + and torch_input.dtype is None + ) + or (isinstance(torch_input, (list, tuple)) and not torch_input) + ): + # NOTE: None, No dtype, and empty list are edge cases, we allow it to be any type to relax the type check + # seq(tensor) also goes to here, as it is not supported in torchscript, and it would be None in this case. + return set() + + raise RuntimeError(f"Unknown input type from input: {torch_input}") diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/op_validation.py b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/op_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b306bc2141de00eb03cc7962d46371f752f6c168 --- /dev/null +++ b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/op_validation.py @@ -0,0 +1,389 @@ +"""Module for handling op-level validation during exporting.""" + +from __future__ import annotations + +import logging + +from typing import Any, Callable, Dict, List, Sequence, Tuple, Union + +import onnxscript # type: ignore[import] +from onnxscript import evaluator # type: ignore[import] + +import torch +import torch.fx + +from torch.fx.experimental import symbolic_shapes +from torch.onnx import _constants, _type_utils as jit_type_utils +from torch.onnx._internal import _beartype +from torch.onnx._internal.fx import ( + diagnostics, + fx_onnx_interpreter, + type_utils as fx_type_utils, +) +from torch.utils import _pytree + + +@_beartype.beartype +def _op_level_debug_message_formatter( + fn: Callable, + self, + node: torch.fx.Node, + symbolic_fn: Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction], + *args, + **kwargs, +) -> str: + return ( + f"FX Node: {node.op}::{node.target}[name={node.name}]. \n" + f"ONNX Node: {symbolic_fn.name}[opset={symbolic_fn.opset}]." + ) + + +@_beartype.beartype +@diagnostics.diagnose_call( + diagnostics.rules.op_level_debugging, + diagnostic_message_formatter=_op_level_debug_message_formatter, +) +def validate_op_between_ort_torch( + diagnostic_context: diagnostics.DiagnosticContext, + node: torch.fx.Node, + symbolic_fn: Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction], + fx_args: List[fx_type_utils.Argument], + fx_kwargs: Dict[str, fx_type_utils.Argument], + fx_graph_module: torch.fx.GraphModule, +): + """Validate the op between ONNX Runtime and PyTorch. + + The function will run the op in ONNX Runtime and PyTorch and compare the + results. It doesn't break the exporting process, but saves each op validated + result into SARIF, under the section of `fx_onnx_interpreter`. + + There are three signs can be found: + 1. Blue: Pass + 2. Yellow: Bypass + + Args: + node (torch.fx.Node): The validated fx.node + symbolic_fn (Union[onnxscript.OnnxFunction, onnxscript.TracedOnnxFunction]): The corresponded ONNX node + torch_args (list): torch argument inputs + torch_kwargs (dict): torch keyword argument inputs + fx_graph_module (torch.fx.GraphModule): The fx.GraphModule that contains the nodes + """ + # op-level validation + # Symbolic_fn should have the same output as node.target (torch ops) + + try: + torch_args, torch_kwargs = _wrap_fx_args_as_torch_args( + fx_args, fx_kwargs, fx_graph_module + ) + except ValueError as value_error: + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section( + logging.WARNING, "Op level debug fails due to unsupported input types" + ): + diagnostic.log_source_exception(logging.WARNING, value_error) + diagnostic.level = diagnostics.levels.WARNING + return + + with evaluator.default_as(evaluator.ort_evaluator): + try: + expected_outputs = node.target(*torch_args, **torch_kwargs) # type: ignore[operator] + # NOTE: randomly generating indices/dim: INT64 could go out of bounds + except IndexError as index_error: + # TODO(titaiwang): How to bound indices/dim: INT64 + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section(logging.WARNING, "Op level debug is bypassed"): + diagnostic.log_source_exception(logging.WARNING, index_error) + diagnostic.level = diagnostics.levels.WARNING + return + # NOTE: Error in torch ops with random inputs generated from FakTensors + except RuntimeError as runtime_error: + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section( + logging.WARNING, "Op level debug fails on PyTorch" + ): + diagnostic.log_source_exception(logging.WARNING, runtime_error) + diagnostic.level = diagnostics.levels.WARNING + return + + try: + ( + function_eager_inputs, + function_eager_attributes, + ) = _convert_torch_args_to_onnxfunction_args( + symbolic_fn.param_schemas(), + torch_args, + torch_kwargs, + allow_extra_kwargs=True, + ) + # NOTE: Apply kwargs preprocessing AFTER they are split + function_eager_attributes = ( + fx_onnx_interpreter.filter_incompatible_and_dtype_convert_kwargs( + function_eager_attributes + ) + ) + # NOTE: Incompatible kwargs or missing required args + except TypeError as type_error: + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section(logging.WARNING, "Op level debug is bypassed"): + diagnostic.log_source_exception(logging.WARNING, type_error) + diagnostic.level = diagnostics.levels.WARNING + return + try: + ort_outputs = symbolic_fn( + *function_eager_inputs, **function_eager_attributes + ) + # NOTE: Error in ONNX Runtime with random inputs generated from FakTensors + except RuntimeError as runtime_error: + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section( + logging.WARNING, "Op level debug fails on ONNXRUNTIME" + ): + diagnostic.log_source_exception(logging.WARNING, runtime_error) + diagnostic.level = diagnostics.levels.WARNING + return + + flattened_torch_outputs, _ = _pytree.tree_flatten(expected_outputs) + flattened_function_outputs, _ = _pytree.tree_flatten(ort_outputs) + + assert flattened_torch_outputs + assert len(flattened_torch_outputs) == len(flattened_function_outputs) + + for torch_output, function_output in zip( + flattened_torch_outputs, flattened_function_outputs + ): + if isinstance( + torch_output, torch.Tensor + ) and fx_type_utils.is_torch_complex_dtype(torch_output.dtype): + torch_output = torch.view_as_real(torch_output.resolve_conj()) + try: + if isinstance(function_output, onnxscript.tensor.Tensor): + function_output = function_output.value + + # Use torch.testing as opposed to np.testing to ensure dtypes and shapes match + torch.testing.assert_close( + torch.tensor(function_output).cpu(), + torch_output.cpu() + if isinstance(torch_output, torch.Tensor) + else torch.tensor(torch_output).cpu(), + rtol=1e-4, + atol=1e-3, + ) + except AssertionError as e: + diagnostic = diagnostic_context.inflight_diagnostic() + with diagnostic.log_section(logging.WARNING, "Validation failed"): + diagnostic.log_source_exception(logging.WARNING, e) + diagnostic.level = diagnostics.levels.WARNING + + +@_beartype.beartype +def _convert_symint_to_int_in_shape(shape: torch.Size) -> torch.Size: + """Convert SymInt to int in shape + + Args: + shape (torch.Size): The shape of a tensor + Raises: + ValueError: When SymInt is found in shape + Returns: + torch.Size: The shape of a tensor with SymInt converted to int + + """ + list_int_shape = [] + for dim in shape: + if isinstance(dim, torch.SymInt): + if symbolic_shapes.has_hint(dim): + list_int_shape.append(symbolic_shapes.hint_int(dim)) + else: + raise ValueError( + f"An unbacked SymInt found in shape. SymInt: {dim}; " + f"torch.Size: {shape}. There is no hint for SymInt." + ) + else: + list_int_shape.append(dim) + return torch.Size(list_int_shape) + + +@_beartype.beartype +def generate_random_tensors(shape: torch.Size, dtype: torch.dtype): + shape = _convert_symint_to_int_in_shape(shape) + + if dtype == torch.uint8: + return torch.randint( + low=_constants.UINT8_MIN, high=_constants.UINT8_MAX, size=shape, dtype=dtype + ) + if dtype == torch.int8: + return torch.randint( + low=_constants.INT8_MIN, high=_constants.INT8_MAX, size=shape, dtype=dtype + ) + if dtype == torch.int16: + return torch.randint( + low=_constants.INT16_MIN, high=_constants.INT16_MAX, size=shape, dtype=dtype + ) + if dtype == torch.int32: + return torch.randint( + low=_constants.INT32_MIN, high=_constants.INT32_MAX, size=shape, dtype=dtype + ) + if dtype == torch.int64: + return torch.randint( + low=_constants.INT64_MIN, high=_constants.INT64_MAX, size=shape, dtype=dtype + ) + if dtype == torch.bool: + random_numbers = torch.rand(shape) + return torch.where( + random_numbers > 0.5, torch.tensor(True), torch.tensor(False) + ) + if fx_type_utils.is_torch_complex_dtype(dtype): + # ONNX does not support complex values, but supports their real representation + return torch.view_as_complex( + torch.randn((*shape, 2), dtype=fx_type_utils.from_complex_to_float(dtype)) + ) + return torch.randn(shape, dtype=dtype) + + +@_beartype.beartype +def _fx_args_to_torch_args( + fx_args: List[fx_type_utils.Argument], fx_graph_module: torch.fx.GraphModule +) -> List[fx_type_utils.Argument]: + """Recursively convert fx args to torch args""" + wrapped_args: List[fx_type_utils.Argument] = [] + for arg in fx_args: + if isinstance(arg, torch.fx.Node): + fake_tensor = arg.meta.get("val") + if fake_tensor is None and arg.op == "get_attr": + fake_tensor = getattr(fx_graph_module, arg.target) # type: ignore[operator] + # NOTE: Currently, we are aware of + # FakeTensor/Tensor/SymInt/SymFloat/Symbool/int/float/bool could be in + # arg.meta["val"]/get_attr. + if isinstance(fake_tensor, torch.Tensor): + real_tensor = generate_random_tensors( + fake_tensor.shape, fake_tensor.dtype + ) + wrapped_args.append(real_tensor) + elif isinstance(fake_tensor, (int, float, bool)): + wrapped_args.append(fake_tensor) + elif symbolic_shapes.has_hint(fake_tensor): + wrapped_args.append(symbolic_shapes.hint_int(fake_tensor)) + else: + raise ValueError( + f"Unexpected input argument type found inside fx.Node. arg: {arg}; " + f"arg.meta['val']/get_attr: {fake_tensor}; type(arg.meta['val']/get_attr): " + f"{type(fake_tensor)}." + ) + elif isinstance(arg, Sequence): + wrapped_args.append(_fx_args_to_torch_args(arg, fx_graph_module)) + elif isinstance(arg, (int, float, torch.dtype)) or arg is None: + wrapped_args.append(arg) + elif isinstance(arg, torch.device): + wrapped_args.append(str(arg)) + else: + raise ValueError( + f"Unexpected input argument type is found in node arguments. arg: {arg}; " + ) + + return wrapped_args + + +@_beartype.beartype +def _wrap_fx_args_as_torch_args( + fx_args: List[fx_type_utils.Argument], + fx_kwargs: Dict[str, fx_type_utils.Argument], + fx_graph_module: torch.fx.GraphModule, +) -> Tuple[List[fx_type_utils.Argument], Dict[str, fx_type_utils.Argument]]: + """Prepare torch format args and kwargs for op-level validation by using fake tensor to create real tensor to feed in ops""" + + # NOTE: This function only supports FakeTensor with concrete shapes + torch_args: List[fx_type_utils.Argument] = _fx_args_to_torch_args( + fx_args, fx_graph_module + ) + return torch_args, fx_kwargs + + +# NOTE: Referenced from onnxscript internal function: _tag_arguments_with_param_schemas. +@_beartype.beartype +def _convert_torch_args_to_onnxfunction_args( + param_schemas: Sequence[onnxscript.values.ParamSchema], + args: List[fx_type_utils.Argument], + kwargs: Dict[str, fx_type_utils.Argument], + allow_extra_kwargs: bool = False, +) -> Tuple[List[Any], Dict[str, Any],]: + """Convert Python args and kwargs to OnnxFunction acceptable with matching ONNX ParamSchema. + + NOTE: This is different from the param_schema separating in dispatcher, since at this point + we are already sure that the args and kwargs are in order and matched. + + Args: + param_schemas: The parameter schemas of an Op or a OnnxFunction. + args: The Python positional arguments supplied by the caller. + kwargs: The Python keyword arguments supplied by the caller. + allow_extra_kwargs: Whether to allow extra keyword arguments. + When set to True, extra/unknown arguments will be ignored. + + Returns: + A tuple of two elements: + - A list of Python positional argument. + - An ordered dictionary of Python keyword argument names and its values. + + Raises: + TypeError: When allow_extra_kwargs is False and there are unknown kwargs. + TypeError: When a required input is not provided. + """ + # args, kwargs and param_schemas should be all in order + # user may not specify all inputs or attributes + + all_param_names = {param.name for param in param_schemas} + extra_kwargs = set(kwargs).difference(all_param_names) + if extra_kwargs and not allow_extra_kwargs: + raise TypeError(f"Unexpected keyword arguments '{extra_kwargs}'") + + tagged_args: list[Any] = [] + tagged_kwargs: dict[str, Any] = {} + + for i, param in enumerate(param_schemas): + if param.is_variadic_input: + # Exhaust all remaining args + tagged_args.extend(arg for arg in args[i:]) + args = [] + continue + if i < len(args): + if param.is_input or isinstance(args[i], torch.dtype): + tagged_args.append(_convert_tensor_to_numpy(args[i])) + else: + tagged_args.append(args[i]) + elif param.name in kwargs: + if param.is_input: + tagged_kwargs[param.name] = _convert_tensor_to_numpy(kwargs[param.name]) + else: + tagged_kwargs[param.name] = kwargs[param.name] + elif param.required: + raise TypeError(f"Required input/attribute '{param}' was not provided") + + return tagged_args, tagged_kwargs + + +@_beartype.beartype +def _convert_tensor_to_numpy(input: fx_type_utils.Argument) -> Any: + try: + import numpy as np + except ImportError as exc: + raise ImportError(f"{__name__} needs numpy, but it's not installed.") from exc + + if isinstance(input, torch.Tensor): + if torch.is_complex(input): + # from complex to real representation + input = torch.view_as_real(input.resolve_conj()) + return input.detach().cpu().numpy() + if isinstance(input, torch.dtype): + return int(jit_type_utils.JitScalarType.from_dtype(input).onnx_type()) # type: ignore[union-attr] + if isinstance(input, (tuple, list)): + if len(input) == 0: + return np.array((), dtype=np.int64) + if isinstance(input[0], torch.Tensor): + return [_convert_tensor_to_numpy(x) for x in input] + if isinstance(input[0], bool): + return np.array(input, dtype=np.bool_) + + # Just a sequence of numbers + if isinstance(input[0], int): + return np.array(input, dtype=np.int64) + if isinstance(input[0], float): + return np.array(input) + return input diff --git a/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/registration.py b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/registration.py new file mode 100644 index 0000000000000000000000000000000000000000..164c052fc86239b9533253727408f5d726349369 --- /dev/null +++ b/venv/lib/python3.10/site-packages/torch/onnx/_internal/fx/registration.py @@ -0,0 +1,91 @@ +"""Module for handling ATen to ONNX functions registration.""" + +from __future__ import annotations + +import dataclasses +import types +from typing import Optional, TYPE_CHECKING, Union + +import torch._ops +from torch.onnx._internal import _beartype + +# We can only import onnx from this module in a type-checking context to ensure that +# 'import torch.onnx' continues to work without having 'onnx' installed. We fully +# 'import onnx' inside of dynamo_export (by way of _assert_dependencies). +if TYPE_CHECKING: + import onnxscript # type: ignore[import] + + +@dataclasses.dataclass(frozen=True, eq=True) +class ONNXFunction: + """A wrapper of onnx-script function. + + op_full_name: The qualified name of the function. In the form of '::.'. + onnx_function: The onnx-script function from torchlib. + is_custom: Whether the function is a custom function. + is_complex: Whether the function is a function that handles complex valued inputs. + + """ + + onnx_function: Union["onnxscript.OnnxFunction", "onnxscript.TracedOnnxFunction"] + op_full_name: str + is_custom: bool = False + is_complex: bool = False + + +@dataclasses.dataclass(frozen=True, eq=True) +class OpName: + """A class representing an operator name in internal ONNX converter.""" + + namespace: str + op_name: str + overload: str + + @classmethod + @_beartype.beartype + def from_name_parts( + cls, namespace: str, op_name: str, overload: Optional[str] = None + ) -> OpName: + # NOTE: in PyTorch, the overload could be unprovided to indicate the + # default overload + if overload is None or overload == "": + overload = "default" + return cls(namespace, op_name, overload) + + @classmethod + @_beartype.beartype + def from_qualified_name(cls, qualified_name: str) -> OpName: + """When the name is ::[.]""" + namespace, opname_overload = qualified_name.split("::") + op_name, *overload = opname_overload.split(".", 1) + overload = overload[0] if overload else "default" + return cls(namespace, op_name, overload) + + @classmethod + @_beartype.beartype + def from_op_overload(cls, op_overload: torch._ops.OpOverload) -> OpName: + return cls.from_qualified_name(op_overload.name()) + + @classmethod + @_beartype.beartype + def from_builtin_function( + cls, builtin_function: types.BuiltinFunctionType + ) -> OpName: + """From a builtin function, e.g. operator.add, math.ceil, etc, get the OpName. + + FX graph uses built-in functions to caculate sympy expression. This function + is used to get the OpName from a builtin function. + + Args: + builtin_function (types.BuiltinFunctionType): operator.add, math.ceil, etc. + + Returns: + OpName: _description_ + """ + op = builtin_function.__name__ # add, sub, etc. + module = builtin_function.__module__ # _operators or math + return cls.from_qualified_name(module + "::" + op) + + @_beartype.beartype + def qualified_name(self) -> str: + return f"{self.namespace}::{self.op_name}.{self.overload}"