// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/flatbuffers/ort_format_version.h" #include "core/flatbuffers/schema/ort.fbs.h" #include "core/framework/data_types.h" #include "core/framework/tensorprotoutils.h" #include "core/framework/TensorSeq.h" #include "core/graph/model.h" #include "core/graph/onnx_protobuf.h" #include "core/session/onnxruntime_cxx_api.h" #include "core/session/inference_session.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "test/unittest_util/framework_test_utils.h" #include "test/common/tensor_op_test_utils.h" #include "test/test_environment.h" #include "test/unittest_util/checkers.h" #include "test/util/include/asserts.h" #include "test/util/include/inference_session_wrapper.h" #include #include #include "flatbuffers/idl.h" #include "flatbuffers/util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using namespace ONNX_NAMESPACE; namespace onnxruntime { namespace test { struct OrtModelTestInfo { std::basic_string model_filename; std::string logid; NameMLValMap inputs; std::vector output_names; std::function&)> output_verifier; std::vector> configs; bool run_use_buffer{false}; bool disable_copy_ort_buffer{false}; bool use_buffer_for_initializers{false}; bool use_memory_mapped_load{false}; TransformerLevel optimization_level = TransformerLevel::Level3; }; namespace { flatbuffers::Offset CreateFloatTensorTypeInfo(flatbuffers::FlatBufferBuilder& builder, int64_t dim_value) { const auto dim_value_off = fbs::CreateDimensionValue(builder, fbs::DimensionValueType::VALUE, dim_value); std::vector> dims{ fbs::CreateDimension(builder, dim_value_off)}; const auto shape = fbs::CreateShapeDirect(builder, &dims); const auto tensor_type = fbs::CreateTensorTypeAndShape(builder, fbs::TensorDataType::FLOAT, shape); return fbs::CreateTypeInfoDirect(builder, nullptr, fbs::TypeInfoValue::tensor_type, tensor_type.Union()); } std::vector BuildOrtModelBuffer( const std::function(flatbuffers::FlatBufferBuilder&)>& create_graph) { flatbuffers::FlatBufferBuilder builder; const auto graph = create_graph(builder); std::vector> opset_imports{ fbs::CreateOperatorSetIdDirect(builder, "", 18)}; const auto model = fbs::CreateModelDirect(builder, 8, &opset_imports, "ort-model-test", "1", "", 1, "", graph, ""); const auto session = fbs::CreateInferenceSessionDirect(builder, std::to_string(kOrtModelVersion).c_str(), model); fbs::FinishInferenceSessionBuffer(builder, session); return std::vector(builder.GetBufferPointer(), builder.GetBufferPointer() + builder.GetSize()); } Status LoadOrtBuffer(const std::vector& buffer, bool use_buffer_for_initializers = false) { SessionOptions so; ORT_RETURN_IF_ERROR(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); if (use_buffer_for_initializers) { ORT_RETURN_IF_ERROR(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseORTModelBytesDirectly, "1")); ORT_RETURN_IF_ERROR(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseORTModelBytesForInitializers, "1")); } InferenceSessionWrapper session_object{so, GetEnvironment()}; return session_object.Load(buffer.data(), static_cast(buffer.size())); } } // namespace static void RunOrtModel(const OrtModelTestInfo& test_info) { SessionOptions so; so.session_logid = test_info.logid; for (const auto& config : test_info.configs) { ASSERT_STATUS_OK(so.config_options.AddConfigEntry(config.first.c_str(), config.second.c_str())); } if (test_info.disable_copy_ort_buffer) { ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseORTModelBytesDirectly, "1")); } if (test_info.use_memory_mapped_load) { ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseMemoryMappedOrtModel, "1")); } if (test_info.use_buffer_for_initializers && (test_info.disable_copy_ort_buffer || (test_info.use_memory_mapped_load && !test_info.run_use_buffer))) { ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseORTModelBytesForInitializers, "1")); } so.graph_optimization_level = test_info.optimization_level; std::vector model_data; InferenceSessionWrapper session_object{so, GetEnvironment()}; std::filesystem::path model_path{test_info.model_filename}; const auto& model_path_str = model_path.native(); if (test_info.run_use_buffer) { // Load the file into a buffer and use the buffer to create inference session size_t num_bytes = 0; ASSERT_STATUS_OK(Env::Default().GetFileLength(model_path_str.c_str(), num_bytes)); model_data.resize(num_bytes); std::ifstream bytes_stream(model_path, std::ifstream::in | std::ifstream::binary); bytes_stream.read(model_data.data(), num_bytes); bytes_stream.close(); ASSERT_STATUS_OK(session_object.Load(model_data.data(), static_cast(num_bytes))); } else { ASSERT_STATUS_OK(session_object.Load(model_path_str)); // infer type from filename } ASSERT_STATUS_OK(session_object.Initialize()); std::vector fetches; ASSERT_STATUS_OK(session_object.Run(test_info.inputs, test_info.output_names, &fetches)); test_info.output_verifier(fetches); } #if !defined(ORT_ENABLE_GQA_VALUE_LAYOUT) TEST(OrtModelOnlyTests, RejectsGqaValueLayoutOptionWhenDisabled) { for (const char* layout : {"BNSH", "BNHS", "NHWC", ""}) { SCOPED_TRACE(layout); SessionOptions options; ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsGqaValueLayout, layout)); InferenceSessionWrapper session{options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ORT_TSTR("testdata/mnist.basic.ort"))); const Status status = session.Initialize(); EXPECT_EQ(status.Code(), common::INVALID_ARGUMENT); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("GQA layout disabled")); } } #endif #if defined(ORT_MINIMAL_BUILD) TEST(OrtModelOnlyTests, RejectsMoeExpertStatisticsInMinimalBuild) { for (const char* value : {"1", "true", ""}) { SCOPED_TRACE(value); SessionOptions options; ASSERT_STATUS_OK(options.config_options.AddConfigEntry( kOrtSessionOptionsConfigEnableMoeExpertStatistics, value)); InferenceSessionWrapper session{options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ORT_TSTR("testdata/mnist.basic.ort"))); const Status status = session.Initialize(); EXPECT_EQ(status.Code(), common::INVALID_ARGUMENT); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("is not supported in a minimal build")); } } TEST(OrtModelOnlyTests, RejectsMoeExpertCountingInMinimalBuild) { for (const auto& [key, value] : { std::pair{kOrtSessionOptionsConfigEnableMoeExpertCounting, "1"}, std::pair{kOrtSessionOptionsConfigEnableMoeExpertCounting, "true"}, std::pair{kOrtSessionOptionsConfigMoeExpertCounterStateFile, "counters.txt"}, std::pair{kOrtSessionOptionsConfigMoeExpertCounterAlpha, "0.5"}, std::pair{kOrtSessionOptionsConfigMoeExpertCounterBeta, "2"}}) { SCOPED_TRACE(key); SessionOptions options; ASSERT_STATUS_OK(options.config_options.AddConfigEntry(key, value)); InferenceSessionWrapper session{options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ORT_TSTR("testdata/mnist.basic.ort"))); const Status status = session.Initialize(); EXPECT_EQ(status.Code(), common::INVALID_ARGUMENT); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr(key)); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("is not supported in a minimal build")); } } #endif TEST(OrtModelOnlyTests, MoeExpertCountingDisabled) { SessionOptions options; ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsConfigEnableMoeExpertCounting, "0")); ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsConfigEnableMoeExpertStatistics, "0")); InferenceSessionWrapper session{options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ORT_TSTR("testdata/mnist.basic.ort"))); ASSERT_STATUS_OK(session.Initialize()); } TEST(OrtModelOnlyTests, RejectsStrictWorkspaceVerification) { SessionOptions options; ASSERT_STATUS_OK(options.config_options.AddConfigEntry( kOrtSessionOptionsStrictWorkspaceVerification, "1")); InferenceSessionWrapper session{options, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ORT_TSTR("testdata/mnist.basic.ort"))); const Status status = session.Initialize(); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("strict_workspace_verification is not supported")); } TEST(OrtModelTest, RejectsInitializerRawDataSizeMismatch) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector dims{32}; std::vector raw_data(sizeof(float) * 33, 0); std::vector> initializers{ fbs::CreateTensorDirect(builder, "bad_initializer", "", &dims, fbs::TensorDataType::FLOAT, &raw_data)}; return fbs::CreateGraphDirect(builder, &initializers); }); const auto status = LoadOrtBuffer(buffer, true); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("raw data size mismatch")); } TEST(OrtModelTest, RejectsDanglingNodeEdge) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_edges{ fbs::CreateNodeEdgeDirect(builder, 0)}; return fbs::CreateGraphDirect(builder, nullptr, nullptr, nullptr, 1, &node_edges); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("references missing node")); } TEST(OrtModelTest, RejectsAdversarialLargeNodeIndex) { // A single node with a huge index should be rejected to prevent memory amplification. const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { const uint32_t huge_index = 100'000'000; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n", "", "", 1, huge_index, "Identity")}; return fbs::CreateGraphDirect(builder, nullptr, nullptr, &nodes, huge_index + 1); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("unreasonably large")); } TEST(OrtModelTest, RejectsInvalidEdgeEndNodeIndex) { // An EdgeEnd referencing a non-existent node should be rejected gracefully // rather than crashing via ORT_ENFORCE or nullptr dereference. const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { // Create a valid node at index 0 with empty inputs/outputs so it passes node-loading validation. std::vector> empty_args; std::vector empty_arg_counts; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n0", "", "", 1, 0, "Identity", fbs::NodeType::Primitive, nullptr, &empty_args, &empty_args, nullptr, &empty_arg_counts, &empty_args)}; // Create a NodeEdge for node 0 with an input edge referencing non-existent node 99 std::vector input_edges{fbs::EdgeEnd(99, 0, 0)}; std::vector> node_edges{ fbs::CreateNodeEdgeDirect(builder, 0, &input_edges)}; return fbs::CreateGraphDirect(builder, nullptr, nullptr, &nodes, 100, &node_edges); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::AnyOf(testing::HasSubstr("out-of-range node index"), testing::HasSubstr("references missing node"))); } TEST(OrtModelTest, RejectsEdgeEndReferencingNullNodeSlot) { // Two real nodes at indices 0 and 3 force nodes_ to size 4, leaving slots 1 and 2 unpopulated. // An inner EdgeEnd that references one of those null slots (index 2) is within range but points // at a missing node, and must be rejected gracefully rather than dereferenced. const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> empty_args; std::vector empty_arg_counts; auto make_node = [&](const char* name, uint32_t index) { return fbs::CreateNodeDirect(builder, name, "", "", 1, index, "Identity", fbs::NodeType::Primitive, nullptr, &empty_args, &empty_args, nullptr, &empty_arg_counts, &empty_args); }; std::vector> nodes{make_node("n0", 0), make_node("n3", 3)}; // Edge owned by node 0 with an input edge referencing the null slot at index 2. std::vector input_edges{fbs::EdgeEnd(2, 0, 0)}; std::vector> node_edges{ fbs::CreateNodeEdgeDirect(builder, 0, &input_edges)}; return fbs::CreateGraphDirect(builder, nullptr, nullptr, &nodes, 4, &node_edges); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("references missing node")); } TEST(OrtModelTest, RejectsGraphInputWithUnknownNodeArg) { // A graph input referencing a NodeArg name that was never declared in node_args must be rejected // rather than firing a null-pointer assertion on the GetNodeArg result. const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_args{ fbs::CreateValueInfoDirect(builder, "x", "", CreateFloatTensorTypeInfo(builder, 1))}; std::vector> inputs{ builder.CreateSharedString("nonexistent")}; return fbs::CreateGraphDirect(builder, nullptr, &node_args, nullptr, 0, nullptr, &inputs); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("Graph references unknown NodeArg 'nonexistent'")); } TEST(OrtModelTest, RejectsNegativeInputArgCount) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_args{ fbs::CreateValueInfoDirect(builder, "x", "", CreateFloatTensorTypeInfo(builder, 1)), fbs::CreateValueInfoDirect(builder, "y", "", CreateFloatTensorTypeInfo(builder, 1))}; std::vector> inputs{builder.CreateSharedString("x")}; std::vector> outputs{builder.CreateSharedString("y")}; std::vector> implicit_inputs; std::vector input_arg_counts{-1}; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n0", "", "", 13, 0, "Identity", fbs::NodeType::Primitive, nullptr, &inputs, &outputs, nullptr, &input_arg_counts, &implicit_inputs)}; return fbs::CreateGraphDirect(builder, nullptr, &node_args, &nodes, 1, nullptr, &inputs, &outputs); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("input_arg_counts contains a negative value")); } TEST(OrtModelTest, RejectsMismatchedInputArgCountTotal) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_args{ fbs::CreateValueInfoDirect(builder, "x", "", CreateFloatTensorTypeInfo(builder, 1)), fbs::CreateValueInfoDirect(builder, "y", "", CreateFloatTensorTypeInfo(builder, 1))}; std::vector> inputs{builder.CreateSharedString("x")}; std::vector> outputs{builder.CreateSharedString("y")}; std::vector> implicit_inputs; std::vector input_arg_counts{2}; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n0", "", "", 13, 0, "Identity", fbs::NodeType::Primitive, nullptr, &inputs, &outputs, nullptr, &input_arg_counts, &implicit_inputs)}; return fbs::CreateGraphDirect(builder, nullptr, &node_args, &nodes, 1, nullptr, &inputs, &outputs); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("input_arg_counts total (2) does not match")); } TEST(OrtModelTest, RejectsInputArgCountTotalOverflow) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_args{ fbs::CreateValueInfoDirect(builder, "x", "", CreateFloatTensorTypeInfo(builder, 1)), fbs::CreateValueInfoDirect(builder, "y", "", CreateFloatTensorTypeInfo(builder, 1))}; std::vector> inputs{builder.CreateSharedString("x")}; std::vector> outputs{builder.CreateSharedString("y")}; std::vector> implicit_inputs; std::vector input_arg_counts{ std::numeric_limits::max(), std::numeric_limits::max(), 3}; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n0", "", "", 13, 0, "Identity", fbs::NodeType::Primitive, nullptr, &inputs, &outputs, nullptr, &input_arg_counts, &implicit_inputs)}; return fbs::CreateGraphDirect(builder, nullptr, &node_args, &nodes, 1, nullptr, &inputs, &outputs); }); const auto status = LoadOrtBuffer(buffer); ASSERT_FALSE(status.IsOK()); if constexpr (sizeof(size_t) == sizeof(uint32_t)) { EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("input_arg_counts total overflows size_t")); } else { EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not match number of explicit inputs")); } } #if !defined(ORT_MINIMAL_BUILD) TEST(OrtModelTest, NormalizesValidVariadicInputArgCounts) { const auto buffer = BuildOrtModelBuffer([](flatbuffers::FlatBufferBuilder& builder) { std::vector> node_args{ fbs::CreateValueInfoDirect(builder, "x", "", CreateFloatTensorTypeInfo(builder, 1)), fbs::CreateValueInfoDirect(builder, "y", "", CreateFloatTensorTypeInfo(builder, 1)), fbs::CreateValueInfoDirect(builder, "z", "", CreateFloatTensorTypeInfo(builder, 1))}; std::vector> inputs{ builder.CreateSharedString("x"), builder.CreateSharedString("y")}; std::vector> outputs{builder.CreateSharedString("z")}; std::vector> implicit_inputs; std::vector input_arg_counts{1, 1}; std::vector> nodes{ fbs::CreateNodeDirect(builder, "n0", "", "", 13, 0, "Sum", fbs::NodeType::Primitive, nullptr, &inputs, &outputs, nullptr, &input_arg_counts, &implicit_inputs)}; return fbs::CreateGraphDirect(builder, nullptr, &node_args, &nodes, 1, nullptr, &inputs, &outputs); }); SessionOptions so; ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); InferenceSessionWrapper session_object{so, GetEnvironment()}; ASSERT_STATUS_OK(session_object.Load(buffer.data(), static_cast(buffer.size()))); const auto& graph = session_object.GetGraph(); const auto* node = graph.GetNode(0); ASSERT_NE(node, nullptr); EXPECT_THAT(node->InputArgCount(), testing::ElementsAre(2)); } #endif // !defined(ORT_MINIMAL_BUILD) #if !defined(ORT_MINIMAL_BUILD) // Keep the CompareTypeProtos in case we need debug the difference /* static void CompareTypeProtos(const TypeProto& left_type_proto, const TypeProto& right_type_proto) { ASSERT_EQ(left_type_proto.denotation(), right_type_proto.denotation()); ASSERT_EQ(left_type_proto.has_tensor_type(), right_type_proto.has_tensor_type()); ASSERT_EQ(left_type_proto.has_sequence_type(), right_type_proto.has_sequence_type()); ASSERT_EQ(left_type_proto.has_map_type(), right_type_proto.has_map_type()); if (left_type_proto.has_tensor_type()) { const auto& left_tensor_type = left_type_proto.tensor_type(); const auto& right_tensor_type = right_type_proto.tensor_type(); ASSERT_EQ(left_tensor_type.elem_type(), right_tensor_type.elem_type()); const auto& left_shape = left_tensor_type.shape(); const auto& right_shape = right_tensor_type.shape(); ASSERT_EQ(left_shape.dim_size(), right_shape.dim_size()); for (int i = 0; i < left_shape.dim_size(); i++) { const auto& left_dim = left_shape.dim(i); const auto& right_dim = right_shape.dim(i); ASSERT_EQ(left_dim.has_dim_value(), right_dim.has_dim_value()); ASSERT_EQ(left_dim.dim_value(), right_dim.dim_value()); ASSERT_EQ(left_dim.has_dim_param(), right_dim.has_dim_param()); ASSERT_EQ(left_dim.dim_param(), right_dim.dim_param()); } } else if (left_type_proto.has_sequence_type()) { CompareTypeProtos(left_type_proto.sequence_type().elem_type(), right_type_proto.sequence_type().elem_type()); } else if (left_type_proto.has_map_type()) { const auto& left_map = left_type_proto.map_type(); const auto& right_map = right_type_proto.map_type(); ASSERT_EQ(left_map.key_type(), right_map.key_type()); CompareTypeProtos(left_map.value_type(), right_map.value_type()); } else { FAIL(); // We do not support SparseTensor and Opaque for now } } */ static void CompareValueInfos(const ValueInfoProto& left, const ValueInfoProto& right) { const auto str_left = left.SerializeAsString(); const auto str_right = right.SerializeAsString(); ASSERT_EQ(str_left, str_right); // Keep the ValueInfoProto content comparison in case we need debug the difference // ASSERT_EQ(left.name(), right.name()); // ASSERT_EQ(left.doc_string(), right.doc_string()); // CompareTypeProtos(left.type(), right.type()); } static void CompareGraphAndSessionState(const InferenceSessionWrapper& session_object_1, const InferenceSessionWrapper& session_object_2) { const auto& graph_1 = session_object_1.GetGraph(); const auto& graph_2 = session_object_2.GetGraph(); const auto& session_state_1 = session_object_1.GetSessionState(); const auto& session_state_2 = session_object_2.GetSessionState(); const auto& i1 = session_state_1.GetInitializedTensors(); const auto& i2 = session_state_2.GetInitializedTensors(); ASSERT_EQ(i1.size(), i2.size()); for (const auto& pair : i1) { auto iter = i2.find(pair.first); ASSERT_NE(iter, i2.cend()) << "Missing initializer " << pair.first; const OrtValue& left = pair.second; const OrtValue& right = iter->second; // CompareTensors(left, right); CheckOrtValuesAreEqual("initializer_" + std::to_string(pair.first), left, right); } // check all node args are fine for (const auto& input : graph_1.GetInputsIncludingInitializers()) { const auto& left = *graph_1.GetNodeArg(input->Name()); const auto* right = graph_2.GetNodeArg(input->Name()); ASSERT_TRUE(right != nullptr); const auto& left_proto = left.ToProto(); const auto& right_proto = right->ToProto(); CompareValueInfos(left_proto, right_proto); } for (const auto& left : graph_1.Nodes()) { const auto* right = graph_2.GetNode(left.Index()); ASSERT_TRUE(right != nullptr); const auto& left_outputs = left.OutputDefs(); const auto& right_outputs = right->OutputDefs(); ASSERT_EQ(left_outputs.size(), right_outputs.size()); for (size_t i = 0, end = left_outputs.size(); i < end; ++i) { const auto& left_nodearg = *left_outputs[i]; const auto& right_nodearg = *right_outputs[i]; if (left_nodearg.Exists()) { EXPECT_EQ(left_nodearg.Name(), right_nodearg.Name()); CompareValueInfos(left_nodearg.ToProto(), right_nodearg.ToProto()); } else { EXPECT_FALSE(right_nodearg.Exists()); } } } } static void CompareSessionMetadata(const InferenceSessionWrapper& session_object_1, const InferenceSessionWrapper& session_object_2) { const auto pair_1 = session_object_1.GetModelMetadata(); ASSERT_STATUS_OK(pair_1.first); const auto& metadata_1 = *pair_1.second; const auto& model_1 = session_object_1.GetModel(); const auto pair_2 = session_object_2.GetModelMetadata(); ASSERT_STATUS_OK(pair_2.first); const auto& metadata_2 = *pair_2.second; const auto& model_2 = session_object_2.GetModel(); ASSERT_EQ(metadata_1.producer_name, metadata_2.producer_name); // ORT format does not have graph name // ASSERT_EQ(metadata_1.graph_name, metadata_2.graph_name); ASSERT_EQ(metadata_1.domain, metadata_2.domain); ASSERT_EQ(metadata_1.description, metadata_2.description); ASSERT_EQ(metadata_1.graph_description, metadata_2.graph_description); ASSERT_EQ(metadata_1.version, metadata_2.version); ASSERT_EQ(metadata_1.custom_metadata_map, metadata_2.custom_metadata_map); ASSERT_EQ(model_1.IrVersion(), model_2.IrVersion()); ASSERT_EQ(model_1.ProducerVersion(), model_2.ProducerVersion()); } static void SaveAndCompareModels(const PathString& orig_file, const PathString& ort_file, TransformerLevel optimization_level = TransformerLevel::Level3, bool compare_saved_model = true) { std::filesystem::path orig_path{orig_file}; std::filesystem::path ort_path{ort_file}; if (ort_path.has_parent_path()) { std::filesystem::create_directories(ort_path.parent_path()); } SessionOptions so; so.session_logid = "SerializeToOrtFormat"; so.optimized_model_filepath = ort_path.native(); so.graph_optimization_level = optimization_level; // not strictly necessary - type should be inferred from the filename ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigSaveModelFormat, "ORT")); InferenceSessionWrapper session_object{so, GetEnvironment()}; // create .ort file during Initialize due to values in SessionOptions ASSERT_STATUS_OK(session_object.Load(orig_path.native())); ASSERT_STATUS_OK(session_object.Initialize()); SessionOptions so2; so2.session_logid = "LoadOrtFormat"; // not strictly necessary - type should be inferred from the filename, but to be sure we're testing what we // think we're testing set it. ASSERT_STATUS_OK(so2.config_options.AddConfigEntry(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); // load serialized version InferenceSessionWrapper session_object2{so2, GetEnvironment()}; ASSERT_STATUS_OK(session_object2.Load(ort_path.native())); ASSERT_STATUS_OK(session_object2.Initialize()); if (!compare_saved_model) { return; } CompareSessionMetadata(session_object, session_object2); CompareGraphAndSessionState(session_object, session_object2); } /* static void DumpOrtModelAsJson(const std::string& model_uri) { std::string ort_repo_root("path to your ORT repo root"); std::string ort_flatbuffers_dir(ort_repo_root + "onnxruntime/core/flatbuffers/"); std::string schemafile(ort_flatbuffers_dir + "ort.fbs"); std::string jsonfile; ORT_ENFORCE(flatbuffers::LoadFile(schemafile.c_str(), false, &schemafile)); flatbuffers::Parser parser; const char* include_directories[] = {ort_flatbuffers_dir.c_str(), nullptr}; ORT_ENFORCE(parser.Parse(schemafile.c_str(), include_directories)); std::string flatbuffer; std::string json; flatbuffers::LoadFile(model_uri.c_str(), true, &flatbuffer); flatbuffers::GenerateText(parser, flatbuffer.data(), &json); std::ofstream(model_uri + ".json") << json; } */ /* Validate we don't run optimizers on an ORT format model in a full build. The optimizers will remove nodes, which will create a mismatch with the saved kernel information and result in a runtime error. We could take steps to handle this scenario in a full build, but for consistency we choose to not run optimizers on any ORT format model. */ TEST(OrtModelOnlyTests, ValidateOrtFormatModelDoesNotRunOptimizersInFullBuild) { const auto ort_file = ORT_TSTR("testdata/mnist.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/mnist.onnx"), ort_file); // DumpOrtModelAsJson(ToUTF8String(ort_file)); OrtModelTestInfo test_info; test_info.model_filename = ort_file; test_info.logid = "ValidateOrtFormatModelDoesNotRunOptimizersInFullBuild"; test_info.configs.push_back(std::make_pair(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); OrtValue ml_value; std::vector data(28 * 28, 0.0); CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {1, 1, 28, 28}, data, &ml_value); test_info.inputs.insert(std::make_pair("Input3", ml_value)); // prepare outputs test_info.output_names = {"Plus214_Output_0"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output = fetches[0].Get(); ASSERT_TRUE(output.Shape().NumDimensions() == 2); }; RunOrtModel(test_info); } TEST(OrtModelOnlyTests, SerializeToOrtFormat) { const auto ort_file = ORT_TSTR("testdata/ort_github_issue_4031.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/ort_github_issue_4031.onnx"), ort_file); // DumpOrtModelAsJson(ToUTF8String(ort_file)); OrtModelTestInfo test_info; test_info.model_filename = ort_file; test_info.logid = "SerializeToOrtFormat"; test_info.configs.push_back(std::make_pair(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {1}, {123.f}, &ml_value); test_info.inputs.insert(std::make_pair("state_var_in", ml_value)); // prepare outputs test_info.output_names = {"state_var_out"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output = fetches[0].Get(); ASSERT_TRUE(output.Shape().Size() == 1); ASSERT_TRUE(output.Data()[0] == 125.f); }; RunOrtModel(test_info); } TEST(OrtModelOnlyTests, SparseInitializerHandling) { const auto ort_file = ORT_TSTR("testdata/ort_minimal_test_models/sparse_initializer_handling.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/ort_minimal_test_models/sparse_initializer_handling.onnx"), ort_file); SessionOptions so; so.session_logid = "SparseInitializerHandling"; InferenceSessionWrapper session_object{so, GetEnvironment()}; ASSERT_STATUS_OK(session_object.Load(ort_file)); ASSERT_STATUS_OK(session_object.Initialize()); // Check that there are no duplicates for initializers const auto* init_list = session_object.GetOverridableInitializers().second; ASSERT_EQ(init_list->size(), 1U); const auto& init_def = *init_list->front(); ASSERT_EQ(init_def.Name(), "x"); } // regression test to make sure the model path is correctly passed through when serializing a tensor attribute TEST(OrtModelOnlyTests, TensorAttributeSerialization) { const auto ort_file = ORT_TSTR("testdata/ort_minimal_test_models/tensor_attribute.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/ort_minimal_test_models/tensor_attribute.onnx"), ort_file); } TEST(OrtModelOnlyTests, MetadataSerialization) { const auto ort_file = ORT_TSTR("testdata/model_with_metadata.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/model_with_metadata.onnx"), ort_file); } // test we can load an old ORT format model and run it in a full build. // we changed from using kernel hashes to kernel type constraints in v5, so an old model should be able to be loaded // in a full build if we add the kernel type constraints during loading. this also means we can save the updated // ORT format model to effectively upgrade it to v5. void TestOrtModelUpdate(const PathString& onnx_file, const PathString& ort_file_v4, const PathString& generated_ort_file_v5, const std::function& output_names)>& set_up_test_inputs_and_outputs_fn, bool enable_saved_runtime_optimizations = false) { // ort_file_v4 is ORT format model using v4 where we used kernel hashes instead of constraints // update v4 model and save as v5. do not run optimizations in order to preserve the model as-is. // Loading a v4 ORT model updates it as part of deserialization, so the in-memory graph/session state is not // expected to match a separately reloaded v5 model exactly. Just validate that we can save and reload it. SaveAndCompareModels(ort_file_v4, generated_ort_file_v5, TransformerLevel::Default, false); // run the original, v4 and v5 models and check the output is the same OrtModelTestInfo test_info; set_up_test_inputs_and_outputs_fn(test_info.inputs, test_info.output_names); // keep the onnx and ort models to the same optimization level test_info.optimization_level = TransformerLevel::Level1; std::vector orig_out, v4_out, v5_out; test_info.model_filename = onnx_file; test_info.output_verifier = [&orig_out](const std::vector& fetches) { orig_out = fetches; }; RunOrtModel(test_info); // run with v4 as input. this should also update to v5 prior to execution. if (enable_saved_runtime_optimizations) { test_info.configs.emplace_back(kOrtSessionOptionsConfigEnableSavedRuntimeOptimizations, "1"); } test_info.model_filename = ort_file_v4; test_info.output_verifier = [&v4_out](const std::vector& fetches) { v4_out = fetches; }; RunOrtModel(test_info); // validate the model saved as v5 also works test_info.model_filename = generated_ort_file_v5; test_info.output_verifier = [&v5_out](const std::vector& fetches) { v5_out = fetches; }; RunOrtModel(test_info); auto compare_outputs = [](gsl::span expected, gsl::span actual) { ASSERT_EQ(expected.size(), actual.size()); for (size_t i = 0; i < expected.size(); ++i) { CheckOrtValuesAreEqual("output_" + std::to_string(i), expected[i], actual[i]); } }; compare_outputs(orig_out, v4_out); compare_outputs(v4_out, v5_out); }; TEST(OrtModelOnlyTests, UpdateOrtModelVersion) { const auto onnx_file = ORT_TSTR("testdata/mnist.onnx"); const auto ort_file_v4 = ORT_TSTR("testdata/mnist.basic.v4.ort"); const auto ort_file_v5 = ORT_TSTR("testdata/mnist.basic.v5.test_output.ort"); RandomValueGenerator random{}; // keep in scope so we get random seed trace message on failure TestOrtModelUpdate(onnx_file, ort_file_v4, ort_file_v5, [&](NameMLValMap& inputs, std::vector& output_names) { std::vector input_dims{1, 1, 28, 28}; std::vector input_data = random.Gaussian(input_dims, 0.0f, 0.9f); OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], input_dims, input_data, &ml_value); inputs = {{"Input3", ml_value}}; output_names = {"Plus214_Output_0"}; }); } // test that a model with saved runtime optimizations can also be updated // note: the saved runtime optimizations will be ignored TEST(OrtModelOnlyTests, UpdateOrtModelVersionWithSavedRuntimeOptimizations) { const auto onnx_file = ORT_TSTR("testdata/transform/runtime_optimization/qdq_convs.onnx"); const auto ort_file_v4 = ORT_TSTR("testdata/transform/runtime_optimization/qdq_convs.runtime_optimizations.v4.ort"); const auto ort_file_v5 = ORT_TSTR("testdata/transform/runtime_optimization/qdq_convs.runtime_optimizations.v5.test_output.ort"); { SessionOptions so{}; ASSERT_STATUS_OK( so.config_options.AddConfigEntry(kOrtSessionOptionsConfigEnableSavedRuntimeOptimizations, "1")); so.graph_optimization_level = TransformerLevel::Level2; InferenceSessionWrapper session{so, GetEnvironment()}; ASSERT_STATUS_OK(session.Load(ort_file_v4)); const auto loaded_ops = CountOpsInGraph(session.GetGraph()); ASSERT_STATUS_OK(session.Initialize()); EXPECT_EQ(CountOpsInGraph(session.GetGraph()), loaded_ops); } RandomValueGenerator random{}; // keep in scope so we get random seed trace message on failure TestOrtModelUpdate(onnx_file, ort_file_v4, ort_file_v5, [&](NameMLValMap& inputs, std::vector& output_names) { constexpr int n = 3; // number of QDQ convs for (size_t i = 0; i < n; ++i) { std::vector input_dims{1, 1, 5, 5}; std::vector input_data = random.Uniform(input_dims, 0, 255); OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], input_dims, input_data, &ml_value); inputs.emplace(MakeString("X_", i), std::move(ml_value)); output_names.push_back(MakeString("Y_", i)); } }, true); } #if !defined(DISABLE_ML_OPS) TEST(OrtModelOnlyTests, SerializeToOrtFormatMLOps) { const auto ort_file = ORT_TSTR("testdata/sklearn_bin_voting_classifier_soft.onnx.test_output.ort"); SaveAndCompareModels(ORT_TSTR("testdata/sklearn_bin_voting_classifier_soft.onnx"), ort_file); OrtModelTestInfo test_info; test_info.model_filename = ort_file; test_info.logid = "SerializeToOrtFormatMLOps"; test_info.configs.push_back(std::make_pair(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {3, 2}, {0.f, 1.f, 1.f, 1.f, 2.f, 0.f}, &ml_value); test_info.inputs.insert(std::make_pair("input", ml_value)); // prepare outputs test_info.output_names = {"output_label", "output_probability"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output_0 = fetches[0].Get(); int64_t tensor_size = 3; ASSERT_EQ(tensor_size, output_0.Shape().Size()); const auto& output_0_data = output_0.Data(); for (int64_t i = 0; i < tensor_size; i++) ASSERT_TRUE(output_0_data[i] == "A"); VectorMapStringToFloat expected_output_1 = {{{"A", 0.572734f}, {"B", 0.427266f}}, {{"A", 0.596016f}, {"B", 0.403984f}}, {{"A", 0.656315f}, {"B", 0.343685f}}}; const auto& actual_output_1 = fetches[1].Get(); ASSERT_EQ(actual_output_1.size(), size_t(3)); for (size_t i = 0; i < 3; i++) { const auto& expected = expected_output_1[i]; const auto& actual = actual_output_1[i]; ASSERT_EQ(actual.size(), size_t(2)); ASSERT_NEAR(expected.at("A"), actual.at("A"), 1e-6); ASSERT_NEAR(expected.at("B"), actual.at("B"), 1e-6); } }; RunOrtModel(test_info); } #endif // #if !defined(DISABLE_ML_OPS) #endif // #if !defined(ORT_MINIMAL_BUILD) // test loading ORT format model with sparse initializers TEST(OrtModelOnlyTests, LoadSparseInitializersOrtFormat) { const auto ort_file = ORT_TSTR("testdata/ort_minimal_test_models/sparse_initializer_handling.onnx.ort"); SessionOptions so; so.session_logid = "LoadOrtFormat"; ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigLoadModelFormat, "ORT")); InferenceSessionWrapper session_object{so, GetEnvironment()}; ASSERT_STATUS_OK(session_object.Load(ort_file)); ASSERT_STATUS_OK(session_object.Initialize()); } OrtModelTestInfo GetTestInfoForLoadOrtFormatModel() { OrtModelTestInfo test_info; test_info.model_filename = ORT_TSTR("testdata/ort_github_issue_4031.onnx.ort"); test_info.logid = "LoadOrtFormatModel"; OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {1}, {123.f}, &ml_value); test_info.inputs.insert(std::make_pair("state_var_in", ml_value)); // prepare outputs test_info.output_names = {"state_var_out"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output = fetches[0].Get(); ASSERT_TRUE(output.Shape().Size() == 1); ASSERT_TRUE(output.Data()[0] == 125.f); }; return test_info; } // test that we can deserialize and run a previously saved ORT format model TEST(OrtModelOnlyTests, LoadOrtFormatModel) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); RunOrtModel(test_info); } // Load the model from a buffer instead of a file path TEST(OrtModelOnlyTests, LoadOrtFormatModelFromBuffer) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); test_info.run_use_buffer = true; RunOrtModel(test_info); } // Load the model from a buffer instead of a file path, and not copy the buffer in session creation TEST(OrtModelOnlyTests, LoadOrtFormatModelFromBufferNoCopy) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); test_info.run_use_buffer = true; test_info.disable_copy_ort_buffer = true; RunOrtModel(test_info); } // Load the model from a buffer instead of a file path, and not copy the buffer in session creation TEST(OrtModelOnlyTests, LoadOrtFormatModelFromBufferNoCopyInitializersUseBuffer) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); test_info.run_use_buffer = true; test_info.disable_copy_ort_buffer = true; test_info.use_buffer_for_initializers = true; RunOrtModel(test_info); } // Load the model from a file using memory-mapped I/O TEST(OrtModelOnlyTests, LoadOrtFormatModelMemoryMapped) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); test_info.use_memory_mapped_load = true; RunOrtModel(test_info); } // Load the model from a file using memory-mapped I/O, with initializers referencing the mapped bytes TEST(OrtModelOnlyTests, LoadOrtFormatModelMemoryMappedWithInitializersFromMap) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModel(); test_info.use_memory_mapped_load = true; test_info.use_buffer_for_initializers = true; RunOrtModel(test_info); } // Verify that mmap loading fails gracefully on a non-existent file TEST(OrtModelOnlyTests, LoadOrtFormatModelMemoryMappedFailsOnMissingFile) { SessionOptions so; so.session_logid = "MemoryMappedMissingFile"; ASSERT_STATUS_OK(so.config_options.AddConfigEntry(kOrtSessionOptionsConfigUseMemoryMappedOrtModel, "1")); InferenceSessionWrapper session_object{so, GetEnvironment()}; auto status = session_object.Load(ORT_TSTR("nonexistent_model.ort")); ASSERT_FALSE(status.IsOK()); } // regression test for 2 issues covered by PR #17000 (internally reported issue). // 1) allocation planner broke in minimal build when subgraph had no nodes. // 2) usage of a sequence data type caused an exception due to IsSparseTensor() throwing // instead of allowing the calling code to have #ifdef'd code to handle when IsSparseTensor // returned true and sparse tensors were disabled. TEST(OrtModelOnlyTests, GithubIssue17000) { // need to run the model to auto model_uri = ORT_TSTR("testdata/ort_github_issue_17000.ort"); auto allocator = TestCPUExecutionProvider()->CreatePreferredAllocators()[0]; OrtValue item0, item1; CreateMLValue(allocator, {1}, {1.f}, &item0); CreateMLValue(allocator, {2}, {2.f, 3.f}, &item1); auto elem_type = DataTypeImpl::GetType(); auto tensor_seq = std::make_unique(elem_type); tensor_seq->SetElements({item0, item1}); auto mltype = DataTypeImpl::GetType(); OrtValue value(tensor_seq.release(), mltype, mltype->GetDeleteFunc()); OrtModelTestInfo test_info; test_info.model_filename = model_uri; test_info.inputs.insert(std::make_pair("seq_in", value)); test_info.output_names = {"still_has_elements"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output = fetches[0].Get(); ASSERT_EQ(output.Shape().Size(), 1); ASSERT_EQ(output.Data()[0], true); // removed one item from seq so should still have elements }; RunOrtModel(test_info); } // ICM 31000000518041. TEST(OrtModelOnlyTests, NullNodeArgNameCheck) { auto ort_file = ORT_TSTR("testdata/icm-31000000518041.ort"); SessionOptions so; InferenceSessionWrapper session_object{so, GetEnvironment()}; ASSERT_STATUS_NOT_OK_AND_HAS_SUBSTR(session_object.Load(ort_file), "NodeArg name is missing. Invalid ORT format model."); } #if !defined(DISABLE_ML_OPS) // test that we can deserialize and run a previously saved ORT format model // for a model with sequence and map outputs OrtModelTestInfo GetTestInfoForLoadOrtFormatModelMLOps() { OrtModelTestInfo test_info; test_info.model_filename = ORT_TSTR("testdata/sklearn_bin_voting_classifier_soft.onnx.ort"); test_info.logid = "LoadOrtFormatModelMLOps"; OrtValue ml_value; CreateMLValue(TestCPUExecutionProvider()->CreatePreferredAllocators()[0], {3, 2}, {0.f, 1.f, 1.f, 1.f, 2.f, 0.f}, &ml_value); test_info.inputs.insert(std::make_pair("input", ml_value)); // prepare outputs test_info.output_names = {"output_label", "output_probability"}; test_info.output_verifier = [](const std::vector& fetches) { const auto& output_0 = fetches[0].Get(); int64_t tensor_size = 3; ASSERT_EQ(tensor_size, output_0.Shape().Size()); const auto& output_0_data = output_0.Data(); for (int64_t i = 0; i < tensor_size; i++) ASSERT_TRUE(output_0_data[i] == "A"); VectorMapStringToFloat expected_output_1 = {{{"A", 0.572734f}, {"B", 0.427266f}}, {{"A", 0.596016f}, {"B", 0.403984f}}, {{"A", 0.656315f}, {"B", 0.343685f}}}; const auto& actual_output_1 = fetches[1].Get(); ASSERT_EQ(actual_output_1.size(), size_t(3)); for (size_t i = 0; i < 3; i++) { const auto& expected = expected_output_1[i]; const auto& actual = actual_output_1[i]; ASSERT_EQ(actual.size(), size_t(2)); ASSERT_NEAR(expected.at("A"), actual.at("A"), 1e-6); ASSERT_NEAR(expected.at("B"), actual.at("B"), 1e-6); } }; return test_info; } // test that we can deserialize and run a previously saved ORT format model // for a model with sequence and map outputs TEST(OrtModelOnlyTests, LoadOrtFormatModelMLOps) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModelMLOps(); RunOrtModel(test_info); } // Load the model from a buffer instead of a file path TEST(OrtModelOnlyTests, LoadOrtFormatModelMLOpsFromBuffer) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModelMLOps(); test_info.run_use_buffer = true; RunOrtModel(test_info); } // Load the model from a buffer instead of a file path, and not copy the buffer in session creation TEST(OrtModelOnlyTests, LoadOrtFormatModelMLOpsFromBufferNoCopy) { OrtModelTestInfo test_info = GetTestInfoForLoadOrtFormatModelMLOps(); test_info.run_use_buffer = true; test_info.disable_copy_ort_buffer = true; RunOrtModel(test_info); } #endif // !defined(DISABLE_ML_OPS) } // namespace test } // namespace onnxruntime