Skip to content
Merged
Show file tree
Hide file tree
Changes from 50 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
d345c26
update
chilo-ms Oct 6, 2025
cb52305
Modify to make it work correctly
chilo-ms Oct 6, 2025
fb5a424
Save scalar value after data propagation
chilo-ms Oct 7, 2025
bd14235
correctly save the inferred shape values in NodeArg for other ops' da…
chilo-ms Oct 9, 2025
e2c532f
refactor the code and add comments
chilo-ms Oct 9, 2025
f79f65b
add tests
chilo-ms Oct 9, 2025
dbe36a8
update error message
chilo-ms Oct 9, 2025
d310a26
fix warnings from pipelines
chilo-ms Oct 10, 2025
3fa22a0
handle for Unsqueeze 11 and eariler that axes is node attribute
chilo-ms Oct 11, 2025
92c71be
fix issue for 'indices' input to Gather has negative value
chilo-ms Oct 13, 2025
f652eec
address issue from pipeline
chilo-ms Oct 14, 2025
78ed993
fix pipeline warning
chilo-ms Oct 14, 2025
035a66e
fix warning in pipeline
chilo-ms Oct 14, 2025
e3e26a0
refactor the code
chilo-ms Oct 14, 2025
6d478cb
Merge branch 'main' into chi/fix_shape_inference
chilo-ms Oct 14, 2025
9dc51aa
address reviewer's comments
chilo-ms Oct 14, 2025
1ec4bf9
fix bug after using std::optional to store value
chilo-ms Oct 14, 2025
1391a15
address reviewer's comments
chilo-ms Oct 14, 2025
21d5e33
add check for get initializer as in-memory external
chilo-ms Oct 14, 2025
e59216b
fix type issue
chilo-ms Oct 15, 2025
eb8be39
Merge branch 'main' into chi/fix_shape_inference
chilo-ms Oct 16, 2025
2616c6f
refactor code and address corner case
chilo-ms Oct 20, 2025
73e38ad
Add clean up for inferred shape values and fix bugs
chilo-ms Oct 21, 2025
8bbebf4
add more tests
chilo-ms Oct 21, 2025
de2ad68
revert
chilo-ms Oct 21, 2025
24ed992
Add test model
chilo-ms Oct 21, 2025
40c8d09
lintrunner -a
chilo-ms Oct 21, 2025
8b444c4
address reviewer's comments
chilo-ms Oct 23, 2025
49f7063
use utils::UnpackTensor
chilo-ms Oct 23, 2025
4649a73
address reviewer's comments
chilo-ms Oct 25, 2025
2043c3a
remove commented code
chilo-ms Oct 25, 2025
f6b3f63
lintrunner -a
chilo-ms Oct 25, 2025
89faeab
fix pipeline issue
chilo-ms Oct 25, 2025
037c5cb
refactor code and fix bug
chilo-ms Oct 25, 2025
6bf5e97
add try/catch for HandleNegativeAxis()
chilo-ms Oct 26, 2025
114a0fb
refactor
chilo-ms Oct 27, 2025
2e263ae
address reviewer's comments
chilo-ms Oct 28, 2025
dad69a5
update
chilo-ms Oct 29, 2025
a2d12dd
fix logic
chilo-ms Oct 29, 2025
9abfc68
address reviewer's comments
chilo-ms Nov 15, 2025
7754921
address reveiwer's comments
chilo-ms Nov 17, 2025
745e095
address reveiwer's comments
chilo-ms Nov 17, 2025
b959403
update class comments
chilo-ms Nov 17, 2025
29ff80f
address revewer's comments
chilo-ms Nov 19, 2025
d08da8c
address reviewer's comments
chilo-ms Nov 19, 2025
5f9f09a
Merge branch 'main' into chi/fix_shape_inference
chilo-ms Nov 19, 2025
9b35eee
update comment
chilo-ms Nov 19, 2025
2c59c09
update ORT_TRY/ORT_CATCH
chilo-ms Nov 19, 2025
58c1711
update
chilo-ms Nov 19, 2025
9af5e28
fix compile warning
chilo-ms Nov 19, 2025
280ebf9
add node_arg.Exists() check
chilo-ms Nov 19, 2025
b431a1c
address reviewer's comments
chilo-ms Dec 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions include/onnxruntime/core/graph/graph.h
Original file line number Diff line number Diff line change
Expand Up @@ -1753,6 +1753,15 @@ class Graph { // NOLINT(clang-analyzer-optin.performance.Padding): preserve exi
std::vector<const ONNX_NAMESPACE::TypeProto*>& output_types,
const Graph::ResolveOptions& options);

// If ONNX operator's PartialDataPropagationFunction() infers concrete shape values in the output
// save them to the output NodeArg as a TensorShapeProto or a scalar value so that downstream (consumer) nodes
// can use them later for their TypeAndShapeInferenceFunction() and PartialDataPropagationFunction().
common::Status SaveShapeValuesFromDataPropagation(const Node& node, NodeArg& output_def,
const ONNX_NAMESPACE::TypeProto& propagated_value_as_type_proto) const;

// Remove intermediate inferred shape values stored in all NodeArgs to reduce memory usage.
common::Status CleanUpShapeValuesFromDataPropagation();

// Apply type-inference and type-checking to all inputs and initializers:
common::Status TypeCheckInputsAndInitializers();

Expand Down
32 changes: 32 additions & 0 deletions include/onnxruntime/core/graph/node_arg.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
#include "core/common/status.h"
#include "core/common/logging/logging.h"

#include <optional>

Check warning on line 12 in include/onnxruntime/core/graph/node_arg.h

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Found C++ system header after other header. Should be: node_arg.h, c system, c++ system, other. [build/include_order] [4] Raw Output: include/onnxruntime/core/graph/node_arg.h:12: Found C++ system header after other header. Should be: node_arg.h, c system, c++ system, other. [build/include_order] [4]

namespace onnxruntime {

// Node argument definition, for both input and output,
Expand Down Expand Up @@ -107,6 +109,18 @@
/** Gets this NodeArg as a NodeArgInfo, AKA ValueInfoProto. */
const NodeArgInfo& ToProto() const noexcept { return node_arg_info_; }

/** Gets the inferred shape values as a TensorShapeProto. */
const std::optional<ONNX_NAMESPACE::TensorShapeProto>& GetInferredShapeValues() const noexcept { return inferred_shape_values_; }

/** Gets mutable inferred shape values as a TensorShapeProto. */
std::optional<ONNX_NAMESPACE::TensorShapeProto>& GetMutableInferredShapeValues() noexcept { return inferred_shape_values_; }

/** Gets the inferred shape scalar value */
const std::optional<int64_t> GetInferredShapeScalarValue() const noexcept { return inferred_scalar_value_; }

/** Sets the inferred shape scalar value */
void SetInferredShapeScalarValue(int64_t value) noexcept { inferred_scalar_value_ = value; }

/** Gets a flag indicating whether this NodeArg exists or not.
Optional inputs are allowed in ONNX and an empty #Name represents a non-existent input argument. */
bool Exists() const noexcept;
Expand All @@ -128,6 +142,24 @@
// Node arg name, type and shape.
NodeArgInfo node_arg_info_;

// This variable stores the actual tensor data of the shape as a TensorShapeProto after executing
// the ONNX operator's PartialDataPropagationFunction(). It's used for shape inference purpose.
//
// Calling an operator's TypeAndShapeInferenceFunction() alone is sometimes insufficient
// for complete shape inference. For example, the Shape operator's TypeAndShapeInferenceFunction()
// only provides the output's rank which is 1 but not its actual shape values.
//
// The PartialDataPropagationFunction(), defined in the ONNX operator schema, must also
// be executed to obtain the concrete shape values output, allowing accurate propagation
// of shape information throughout the graph. If the concrete shape values output is not
// computed, nothing is stored here that's why this is optional.
std::optional<ONNX_NAMESPACE::TensorShapeProto> inferred_shape_values_;

// This variable stores the actual scalar value.
// It is also used for shape inference and data propagation to ensure consistent shape and
// value information throughout the graph.
std::optional<int64_t> inferred_scalar_value_;

// Flag indicates whether <*this> node arg exists or not.
bool exists_;
};
Expand Down
32 changes: 32 additions & 0 deletions onnxruntime/core/graph/data_propagation/add_op_data_propagation.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#include "add_op_data_propagation.h"

Check warning on line 4 in onnxruntime/core/graph/data_propagation/add_op_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/add_op_data_propagation.cc:4: Include the directory when naming header files [build/include_subdir] [4]
#include "core/common/common.h"
#include "core/graph/node_arg.h"
#include "core/graph/onnx_protobuf.h"
#include "core/providers/common.h"

namespace onnxruntime {

Status AddOpDataPropagation::infer() {
// Get "A" input
const auto* input_0 = node_.InputDefs()[0];
// Get "B" input
const auto* input_1 = node_.InputDefs()[1];

// Return and do nothing if input doesn't exist
if (!input_0 || !input_1) {
return Status::OK();
}

if (input_0->GetInferredShapeScalarValue().has_value() && input_1->GetInferredShapeScalarValue().has_value()) {
output_def_.SetInferredShapeScalarValue(
input_0->GetInferredShapeScalarValue().value() +
input_1->GetInferredShapeScalarValue().value());
}

return Status::OK();
}

} // namespace onnxruntime
52 changes: 52 additions & 0 deletions onnxruntime/core/graph/data_propagation/add_op_data_propagation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#pragma once

#include "custom_data_propagation.h"

Check warning on line 6 in onnxruntime/core/graph/data_propagation/add_op_data_propagation.h

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/add_op_data_propagation.h:6: Include the directory when naming header files [build/include_subdir] [4]
#include "core/graph/graph.h"

namespace onnxruntime {

/**
* @brief Class to infer the output scalar for 'Add' operator given the input is a scalar related to shape.
*
*
* For example:
*
* (input with the shape as float32[1, 3, 64, 64])
* |
* v
* Shape (It saves [1, 3, 64, 64] in inferred_shape_values_ in output's node_arg
* | during Graph::SaveShapeValuesFromDataPropagation())
* |
* | ______
* | |
* v v
* Gather Gather (First 'Gather' saves 3 in inferred_scalar_value_ in output node_arg, and
* | | second 'Gather' saves 64 in inferred_scalar_value_ in output node_arg
* | | during GatherOpDataPropagation(), if the 'index' attributes
* | | are 1 and 2 respectively)
* \ /
* \ /
* | |
* v v
* Add (It gets 3 from inferred_scalar_value_ in input A's node_arg and 64 from inferred_scalar_value_
* | in input B's node_arg, then performs add operation to get 67 and saves in inferred_scalar_value_
* | in output's node_arg)
* v
* ...
*/
class AddOpDataPropagation : public CustomDataPropagationBase {
public:
AddOpDataPropagation(const Node& node,
NodeArg& output_def,
std::function<Status(const std::string&, TensorShapeVector&)> func,

Check warning on line 44 in onnxruntime/core/graph/data_propagation/add_op_data_propagation.h

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Add #include <string> for string [build/include_what_you_use] [4] Raw Output: onnxruntime/core/graph/data_propagation/add_op_data_propagation.h:44: Add #include <string> for string [build/include_what_you_use] [4]
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation,
const logging::Logger& logger) noexcept
: CustomDataPropagationBase(node, output_def, func, output_from_onnx_op_data_propagation, logger) {}

Status infer() override;
};

} // namespace onnxruntime
53 changes: 53 additions & 0 deletions onnxruntime/core/graph/data_propagation/custom_data_propagation.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#include "custom_data_propagation.h"

Check warning on line 4 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:4: Include the directory when naming header files [build/include_subdir] [4]
#include "core/common/common.h"
#include "core/graph/graph.h"
#include "core/common/logging/logging.h"
#include "size_op_data_propagation.h"

Check warning on line 8 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:8: Include the directory when naming header files [build/include_subdir] [4]
#include "squeeze_op_data_propagation.h"

Check warning on line 9 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:9: Include the directory when naming header files [build/include_subdir] [4]
#include "unsqueeze_op_data_propagation.h"

Check warning on line 10 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:10: Include the directory when naming header files [build/include_subdir] [4]
#include "gather_op_data_propagation.h"

Check warning on line 11 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:11: Include the directory when naming header files [build/include_subdir] [4]
#include "add_op_data_propagation.h"

Check warning on line 12 in onnxruntime/core/graph/data_propagation/custom_data_propagation.cc

View workflow job for this annotation

GitHub Actions / Optional Lint C++

[cpplint] reported by reviewdog 🐶 Include the directory when naming header files [build/include_subdir] [4] Raw Output: onnxruntime/core/graph/data_propagation/custom_data_propagation.cc:12: Include the directory when naming header files [build/include_subdir] [4]
#include "sub_op_data_propagation.h"
#include "mul_op_data_propagation.h"
#include "div_op_data_propagation.h"
#include <onnx/onnx-ml.pb.h>

namespace onnxruntime {

std::unique_ptr<CustomDataPropagationBase> CreateCustomDataPropagation(const Node& node,
NodeArg& output_def,
std::function<Status(const std::string&, TensorShapeVector&)> func,
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation,
const logging::Logger& logger) {
int dim_size = 0;
if (output_from_onnx_op_data_propagation.has_tensor_type() &&
output_from_onnx_op_data_propagation.tensor_type().has_shape()) {
dim_size = output_from_onnx_op_data_propagation.tensor_type().shape().dim_size();
}

if (node.OpType() == "Size") {
return std::make_unique<SizeOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Squeeze") {
return std::make_unique<SqueezeOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Unsqueeze") {
return std::make_unique<UnsqueezeOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (dim_size == 0) {
if (node.OpType() == "Gather") {
return std::make_unique<GatherOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Add") {
return std::make_unique<AddOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Sub") {
return std::make_unique<SubOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Mul") {
return std::make_unique<MulOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
} else if (node.OpType() == "Div") {
return std::make_unique<DivOpDataPropagation>(node, output_def, std::move(func), output_from_onnx_op_data_propagation, logger);
}
}
return nullptr;
}

} // namespace onnxruntime
75 changes: 75 additions & 0 deletions onnxruntime/core/graph/data_propagation/custom_data_propagation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#pragma once

#include "core/common/common.h"
#include "core/graph/graph.h"
#include "core/common/logging/logging.h"
#include <onnx/onnx-ml.pb.h>

namespace onnxruntime {

/**
* @class CustomDataPropagation
* Custom data propagation for the operator to help enhance shape inference.
*
* Calling infer() can infer the output values for the specific operator given the input is shape values
* and saves the output values in output node_arg for other operators to use later.
* The purpose of this class is to make shape values being correctly inferred and propogated through the graph.
*/
class CustomDataPropagationBase {
public:
ORT_DISALLOW_COPY(CustomDataPropagationBase);
virtual ~CustomDataPropagationBase() = default;
virtual Status infer() = 0;

protected:
CustomDataPropagationBase(const Node& node,
NodeArg& output_def,
std::function<Status(const std::string&, TensorShapeVector&)> func,
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation,
const logging::Logger& logger) noexcept
: node_(node),
output_def_(output_def),
get_initialized_input_values_func_(std::move(func)),
output_from_onnx_op_data_propagation_(output_from_onnx_op_data_propagation),
logger_(logger) {}

const Node& node_;
NodeArg& output_def_;
std::function<Status(const std::string&, TensorShapeVector&)> get_initialized_input_values_func_;
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation_;
const logging::Logger& logger_;
};

/**
* @brief Create custom data propagation for the operator.
*
* For certain operators (e.g., Size, Squeeze, Unsqueeze), ONNX's
* PartialDataPropagationFunction() does not always produce complete or accurate
* inferred shape values.
*
* In particular:
* - Scalar inputs and outputs are not handled correctly.
* - Some operators require additional logic that is not covered by the default function,
e.g. PartialDataPropagationFunction.
*
* Therefore, for these cases, we perform custom data propagation to ensure
* correct and complete inference.
*
* @param node The ORT's node
* @param output_def The node's output NodeArg to save the inferred shape values if needed
* @param func Helper function to get the input value if it's a initializer
* @param output_from_onnx_op_data_propagation The result from executing ONNX operator's data propagation
* @param logger The reference to a logger
* @return std::unique_ptr<CustomDataPropagation> Returns a CustomDataPropagation object if available
*/
std::unique_ptr<CustomDataPropagationBase> CreateCustomDataPropagation(
const Node& node,
NodeArg& output_def,
std::function<Status(const std::string&, TensorShapeVector&)> func,
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation,
const logging::Logger& logger);

} // namespace onnxruntime
32 changes: 32 additions & 0 deletions onnxruntime/core/graph/data_propagation/div_op_data_propagation.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#include "div_op_data_propagation.h"
#include "core/common/common.h"
#include "core/graph/node_arg.h"
#include "core/graph/onnx_protobuf.h"
#include "core/providers/common.h"

namespace onnxruntime {

Status DivOpDataPropagation::infer() {
// Get "A" input
const auto* input_0 = node_.InputDefs()[0];
// Get "B" input
const auto* input_1 = node_.InputDefs()[1];

// Return and do nothing if input doesn't exist
if (!input_0 || !input_1) {
return Status::OK();
}

if (input_0->GetInferredShapeScalarValue().has_value() && input_1->GetInferredShapeScalarValue().has_value()) {
output_def_.SetInferredShapeScalarValue(
input_0->GetInferredShapeScalarValue().value() /
input_1->GetInferredShapeScalarValue().value());
}

return Status::OK();
}

} // namespace onnxruntime
52 changes: 52 additions & 0 deletions onnxruntime/core/graph/data_propagation/div_op_data_propagation.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
Comment thread Fixed
// Licensed under the MIT License.

#pragma once

#include "custom_data_propagation.h"
#include "core/graph/graph.h"

namespace onnxruntime {

/**
* @brief Class to infer the output scalar for 'Div' operator given the input is a scalar related to shape.
*
*
* For example:
*
* (input with the shape as float32[1, 3, 64, 64])
* |
* v
* Shape (It saves [1, 3, 64, 64] in inferred_shape_values_ in output's node_arg
* | during graph::SaveShapeValuesFromDataPropagation())
* |
* | ______
* | |
* v v
* Gather Gather (First 'Gather' saves 64 in inferred_scalar_value_ in output node_arg, and
* | | second 'Gather' saves 1 in inferred_scalar_value_ in output node_arg
* | | during GatherOpDataPropagation(), if the 'index' attributes
* | | are 2 and 0 respectively)
* \ /
* \ /
* | |
* v v
* Div (It gets 64 from inferred_scalar_value_ in input A's node_arg and 1 from inferred_scalar_value_
* | in input B's node_arg, then performs div operation to get 64 and saves in inferred_scalar_value_
* | in output's node_arg)
* v
* ...
*/
class DivOpDataPropagation : public CustomDataPropagationBase {
public:
DivOpDataPropagation(const Node& node,
NodeArg& output_def,
std::function<Status(const std::string&, TensorShapeVector&)> func,
const ONNX_NAMESPACE::TypeProto& output_from_onnx_op_data_propagation,
const logging::Logger& logger) noexcept
: CustomDataPropagationBase(node, output_def, func, output_from_onnx_op_data_propagation, logger) {}

Status infer() override;
};

} // namespace onnxruntime
Loading
Loading