-
Notifications
You must be signed in to change notification settings - Fork 66
[ML] Harden pytorch_inference with TorchScript model graph validation #2999
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
edsavage
merged 11 commits into
elastic:main
from
edsavage:feature/harden-pytorch-inference-v2
Mar 19, 2026
+3,449
−181
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
efb9d68
Revert "[ML] Revert #2991 and #2936 (#2995)"
edsavage 09c1d20
[ML] Fix YAML parse failure in QA pipeline when commit message contai…
edsavage ab64455
[ML] Add rerank model ops to pytorch_inference allowlist
edsavage 9e518a2
[ML] Add additional model ops to pytorch_inference allowlist
edsavage 780ac44
[ML] Update golden file and allowlist with rerank, Eland-deployed, an…
edsavage a0fef0e
[ML] Add ES inference integration tests to CI pipeline
edsavage 6465c50
[ML] Refactor ES test scripts to share common setup
edsavage e84563a
Merge upstream/main into feature/harden-pytorch-inference-v2
edsavage 83b9d72
[ML] Address review feedback on pytorch inference hardening
edsavage f9c8902
Merge upstream/main into feature/harden-pytorch-inference-v2
edsavage 46b3870
[ML] Address second round of review feedback
edsavage File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| #!/bin/bash | ||
| # Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| # or more contributor license agreements. Licensed under the Elastic License | ||
| # 2.0 and the following additional limitation. Functionality enabled by the | ||
| # files subject to the Elastic License 2.0 may only be used in production when | ||
| # invoked by an Elasticsearch process with a license key installed that permits | ||
| # use of machine learning features. You may not use this file except in | ||
| # compliance with the Elastic License 2.0 and the foregoing additional | ||
| # limitation. | ||
|
|
||
| cat <<EOL | ||
| steps: | ||
| - label: "Java :java: Inference Integration Tests for x86_64 :hammer:" | ||
| key: "java_inference_tests_x86_64" | ||
| command: | ||
| - 'sudo rpm --import https://yum.corretto.aws/corretto.key' | ||
| - 'sudo curl -L -o /etc/yum.repos.d/corretto.repo https://yum.corretto.aws/corretto.repo' | ||
| - 'sudo dnf install -y java-21-amazon-corretto-devel' | ||
| - 'buildkite-agent artifact download "build/*" . --step build_test_linux-x86_64-RelWithDebInfo' | ||
| - '.buildkite/scripts/steps/run_es_inference_tests.sh || (cd ../elasticsearch && find x-pack -name logs | xargs tar cvzf logs.tgz && buildkite-agent artifact upload logs.tgz && false)' | ||
| depends_on: "build_test_linux-x86_64-RelWithDebInfo" | ||
| agents: | ||
| provider: aws | ||
| instanceType: m6i.2xlarge | ||
| imagePrefix: core-amazonlinux-2023 | ||
| diskSizeGb: 100 | ||
| diskName: '/dev/xvda' | ||
| env: | ||
| IVY_REPO: "../ivy" | ||
| GRADLE_JVM_OPTS: "-Dorg.gradle.jvmargs=-Xmx16g" | ||
| notify: | ||
| - github_commit_status: | ||
| context: "Java Inference Integration Tests for x86_64" | ||
| EOL |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| #!/bin/bash | ||
| # Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| # or more contributor license agreements. Licensed under the Elastic License | ||
| # 2.0 and the following additional limitation. Functionality enabled by the | ||
| # files subject to the Elastic License 2.0 may only be used in production when | ||
| # invoked by an Elasticsearch process with a license key installed that permits | ||
| # use of machine learning features. You may not use this file except in | ||
| # compliance with the Elastic License 2.0 and the foregoing additional | ||
| # limitation. | ||
|
|
||
| set -euo pipefail | ||
|
|
||
| echo "pwd = $(pwd)" | ||
|
|
||
| export HARDWARE_ARCH=$(uname -m | sed 's/arm64/aarch64/') | ||
|
|
||
| VERSION=$(cat ${REPO_ROOT}/gradle.properties | grep '^elasticsearchVersion' | awk -F= '{ print $2 }' | xargs echo) | ||
| if [ "${BUILD_SNAPSHOT:=true}" = "true" ] ; then | ||
| VERSION=${VERSION}-SNAPSHOT | ||
| fi | ||
| export VERSION | ||
|
|
||
| export PR_AUTHOR=$(expr "$BUILDKITE_BRANCH" : '\(.*\):.*') | ||
| export PR_SOURCE_BRANCH=$(expr "$BUILDKITE_BRANCH" : '.*:\(.*\)') | ||
| export PR_TARGET_BRANCH=${BUILDKITE_PULL_REQUEST_BASE_BRANCH} | ||
|
|
||
| mkdir -p "${IVY_REPO}/maven/org/elasticsearch/ml/ml-cpp/$VERSION" | ||
| cp "build/distributions/ml-cpp-$VERSION-linux-$HARDWARE_ARCH.zip" "${IVY_REPO}/maven/org/elasticsearch/ml/ml-cpp/$VERSION/ml-cpp-$VERSION.zip" | ||
| cp "build/distributions/ml-cpp-$VERSION-linux-$HARDWARE_ARCH.zip" "${IVY_REPO}/maven/org/elasticsearch/ml/ml-cpp/$VERSION/ml-cpp-$VERSION-nodeps.zip" | ||
| cp dev-tools/minimal.zip "${IVY_REPO}/maven/org/elasticsearch/ml/ml-cpp/$VERSION/ml-cpp-$VERSION-deps.zip" | ||
| ./dev-tools/run_es_inference_tests.sh ".." "$(cd "${IVY_REPO}" && pwd)" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0 and the following additional limitation. Functionality enabled by the | ||
| * files subject to the Elastic License 2.0 may only be used in production when | ||
| * invoked by an Elasticsearch process with a license key installed that permits | ||
| * use of machine learning features. You may not use this file except in | ||
| * compliance with the Elastic License 2.0 and the foregoing additional | ||
| * limitation. | ||
| */ | ||
|
|
||
| #include "CModelGraphValidator.h" | ||
|
|
||
| #include "CSupportedOperations.h" | ||
|
|
||
| #include <core/CLogger.h> | ||
|
|
||
| #include <torch/csrc/jit/passes/inliner.h> | ||
|
|
||
| #include <algorithm> | ||
|
|
||
| namespace ml { | ||
| namespace torch { | ||
|
|
||
| CModelGraphValidator::SResult CModelGraphValidator::validate(const ::torch::jit::Module& module) { | ||
|
|
||
| TStringSet observedOps; | ||
| std::size_t nodeCount{0}; | ||
| collectModuleOps(module, observedOps, nodeCount); | ||
|
|
||
| if (nodeCount > MAX_NODE_COUNT) { | ||
| LOG_ERROR(<< "Model graph is too large: " << nodeCount | ||
| << " nodes exceeds limit of " << MAX_NODE_COUNT); | ||
| return {false, {}, {}, nodeCount}; | ||
| } | ||
|
|
||
| LOG_DEBUG(<< "Model graph contains " << observedOps.size() | ||
| << " distinct operations across " << nodeCount << " nodes"); | ||
| for (const auto& op : observedOps) { | ||
| LOG_DEBUG(<< " observed op: " << op); | ||
| } | ||
|
|
||
| auto result = validate(observedOps, CSupportedOperations::ALLOWED_OPERATIONS, | ||
| CSupportedOperations::FORBIDDEN_OPERATIONS); | ||
| result.s_NodeCount = nodeCount; | ||
| return result; | ||
| } | ||
|
|
||
| CModelGraphValidator::SResult | ||
| CModelGraphValidator::validate(const TStringSet& observedOps, | ||
| const std::unordered_set<std::string_view>& allowedOps, | ||
| const std::unordered_set<std::string_view>& forbiddenOps) { | ||
|
|
||
| SResult result; | ||
|
|
||
| // Two-pass check: forbidden ops first, then unrecognised. This lets us | ||
| // fail fast when a known-dangerous operation is present and avoids the | ||
| // cost of scanning for unrecognised ops on a model we will reject anyway. | ||
| for (const auto& op : observedOps) { | ||
| if (forbiddenOps.contains(op)) { | ||
| result.s_IsValid = false; | ||
| result.s_ForbiddenOps.push_back(op); | ||
| } | ||
| } | ||
|
|
||
| if (result.s_ForbiddenOps.empty()) { | ||
| for (const auto& op : observedOps) { | ||
| if (allowedOps.contains(op) == false) { | ||
| result.s_IsValid = false; | ||
| result.s_UnrecognisedOps.push_back(op); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| std::sort(result.s_ForbiddenOps.begin(), result.s_ForbiddenOps.end()); | ||
| std::sort(result.s_UnrecognisedOps.begin(), result.s_UnrecognisedOps.end()); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| void CModelGraphValidator::collectBlockOps(const ::torch::jit::Block& block, | ||
| TStringSet& ops, | ||
| std::size_t& nodeCount) { | ||
| for (const auto* node : block.nodes()) { | ||
| if (++nodeCount > MAX_NODE_COUNT) { | ||
| return; | ||
| } | ||
| ops.emplace(node->kind().toQualString()); | ||
| for (const auto* subBlock : node->blocks()) { | ||
| collectBlockOps(*subBlock, ops, nodeCount); | ||
| if (nodeCount > MAX_NODE_COUNT) { | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| void CModelGraphValidator::collectModuleOps(const ::torch::jit::Module& module, | ||
| TStringSet& ops, | ||
| std::size_t& nodeCount) { | ||
| for (const auto& method : module.get_methods()) { | ||
| // Inline all method calls so that operations hidden behind | ||
| // prim::CallMethod are surfaced. After inlining, any remaining | ||
| // prim::CallMethod indicates a call that could not be resolved | ||
| // statically and will be flagged as unrecognised. | ||
| auto graph = method.graph()->copy(); | ||
| ::torch::jit::Inline(*graph); | ||
| collectBlockOps(*graph->block(), ops, nodeCount); | ||
| if (nodeCount > MAX_NODE_COUNT) { | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0 and the following additional limitation. Functionality enabled by the | ||
| * files subject to the Elastic License 2.0 may only be used in production when | ||
| * invoked by an Elasticsearch process with a license key installed that permits | ||
| * use of machine learning features. You may not use this file except in | ||
| * compliance with the Elastic License 2.0 and the foregoing additional | ||
| * limitation. | ||
| */ | ||
|
|
||
| #ifndef INCLUDED_ml_torch_CModelGraphValidator_h | ||
| #define INCLUDED_ml_torch_CModelGraphValidator_h | ||
|
|
||
| #include <torch/script.h> | ||
|
|
||
| #include <string> | ||
| #include <string_view> | ||
| #include <unordered_set> | ||
| #include <vector> | ||
|
|
||
| namespace ml { | ||
| namespace torch { | ||
|
|
||
| //! \brief | ||
| //! Validates TorchScript model computation graphs against a set of | ||
| //! allowed operations. | ||
| //! | ||
| //! DESCRIPTION:\n | ||
| //! Provides defense-in-depth by statically inspecting the TorchScript | ||
| //! graph of a loaded model and rejecting any model that contains | ||
| //! operations not present in the allowlist derived from supported | ||
| //! transformer architectures. | ||
| //! | ||
| //! IMPLEMENTATION DECISIONS:\n | ||
| //! The validation walks all methods of the module and its submodules | ||
| //! recursively, collecting every distinct operation. Any operation | ||
| //! that appears in the forbidden set causes immediate rejection. | ||
| //! Any operation not in the allowed set is collected and reported. | ||
| //! This ensures that even operations buried in helper methods or | ||
| //! nested submodules are inspected. | ||
| //! | ||
| class CModelGraphValidator { | ||
| public: | ||
| using TStringSet = std::unordered_set<std::string>; | ||
| using TStringVec = std::vector<std::string>; | ||
|
|
||
| //! Upper bound on the number of graph nodes we are willing to inspect. | ||
| //! Transformer models typically have O(10k) nodes after inlining; a | ||
| //! limit of 1M provides generous headroom while preventing a | ||
| //! pathologically large graph from consuming unbounded memory or CPU. | ||
| static constexpr std::size_t MAX_NODE_COUNT{1000000}; | ||
|
|
||
| //! Result of validating a model graph. | ||
| struct SResult { | ||
| bool s_IsValid{true}; | ||
| TStringVec s_ForbiddenOps; | ||
| TStringVec s_UnrecognisedOps; | ||
| std::size_t s_NodeCount{0}; | ||
| }; | ||
|
|
||
| public: | ||
| //! Validate the computation graph of the given module against the | ||
| //! supported operation allowlist. Recursively inspects all methods | ||
| //! across all submodules. | ||
| static SResult validate(const ::torch::jit::Module& module); | ||
|
|
||
| //! Validate a pre-collected set of operation names. Useful for | ||
| //! unit testing the matching logic without requiring a real model. | ||
| static SResult validate(const TStringSet& observedOps, | ||
| const std::unordered_set<std::string_view>& allowedOps, | ||
| const std::unordered_set<std::string_view>& forbiddenOps); | ||
|
|
||
| private: | ||
| //! Collect all operation names from a block, recursing into sub-blocks. | ||
| static void collectBlockOps(const ::torch::jit::Block& block, | ||
| TStringSet& ops, | ||
| std::size_t& nodeCount); | ||
|
|
||
| //! Inline all method calls and collect ops from the flattened graph. | ||
| //! After inlining, prim::CallMethod should not appear; if it does, | ||
| //! the call could not be resolved statically and is treated as | ||
| //! unrecognised. | ||
| static void collectModuleOps(const ::torch::jit::Module& module, | ||
| TStringSet& ops, | ||
| std::size_t& nodeCount); | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| #endif // INCLUDED_ml_torch_CModelGraphValidator_h |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great that you are fixing this test gap!