// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include #include #include #include "gtest/gtest.h" #include "gmock/gmock.h" #include "core/common/narrow.h" #include "core/graph/constants.h" #include "core/session/onnxruntime_c_api.h" #include "core/session/onnxruntime_cxx_api.h" #include "core/session/onnxruntime_lite_custom_op.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "test/shared_lib/test_fixture.h" #include "test/shared_lib/utils.h" #include "test/util/include/api_asserts.h" #include "test/util/include/test_allocator.h" #include "onnxruntime_config.h" // generated file in build output dir extern std::unique_ptr ort_env; using namespace Ort; namespace { Ort::Session CreateSession(Ort::Env& env, Model& graph_api_model, Ort::SessionOptions* session_options_for_test = nullptr) { Ort::SessionOptions default_session_options; Ort::SessionOptions& session_options = session_options_for_test ? *session_options_for_test : default_session_options; // Set this to save the model if you want to debug. // session_options.SetOptimizedModelFilePath(ORT_TSTR("model_builder_output.onnx")); Ort::Session session(env, graph_api_model, session_options); // Session should not require the model to stay alive so free it now to validate. graph_api_model = Model(nullptr); return session; } template void TestInference(Ort::Session& session, const std::vector>& inputs, const char* output_name, const std::vector& expected_dims, const std::vector& expected_values) { auto default_allocator = std::make_unique(); // without preallocated output tensor RunSession(default_allocator.get(), session, inputs, output_name, expected_dims, expected_values, nullptr); } // Create OrtNode using the C API OrtNode* CreateNode(const OrtModelEditorApi& api, const char* operator_name, const char* node_name, const gsl::span input_names, const gsl::span output_names, const gsl::span attributes = {}, const char* domain_name = onnxruntime::kOnnxDomain) { OrtNode* node = nullptr; Ort::ThrowOnError(api.CreateNode(operator_name, domain_name, node_name, input_names.data(), input_names.size(), output_names.data(), output_names.size(), attributes.data(), attributes.size(), &node)); return node; } // convenience func to convert initalizer lists to gsl::span OrtNode* CreateNode(const OrtModelEditorApi& api, const char* operator_name, const char* node_name, const std::initializer_list input_names, const std::initializer_list output_names, const std::initializer_list attributes = {}, const char* domain_name = onnxruntime::kOnnxDomain) { std::vector inputs(input_names); std::vector outputs(output_names); std::vector attrs(attributes); return CreateNode(api, operator_name, node_name, inputs, outputs, attrs, domain_name); } } // namespace struct TestAllocator : public OrtAllocator { TestAllocator() { version = ORT_API_VERSION; Info = [](const struct OrtAllocator* this_ptr) -> const struct OrtMemoryInfo* { auto* test_allocator = static_cast(this_ptr); return test_allocator->memory_info; }; Free = [](struct OrtAllocator* allocator, void* p) -> void { auto* test_allocator = static_cast(allocator); // find the matching pointer and remove it auto it = std::find_if(test_allocator->weights.begin(), test_allocator->weights.end(), [p](const std::unique_ptr>& v) { return v->data() == p; }); if (it == test_allocator->weights.end()) { throw std::runtime_error("Free called with unknown pointer"); } test_allocator->weights.erase(it); }; Alloc = [](struct OrtAllocator* /*this*/, size_t /*size*/) -> void* { throw std::runtime_error("This should not be used"); }; Reserve = [](struct OrtAllocator* /*this*/, size_t /*size*/) -> void* { throw std::runtime_error("This should not be used"); }; GetStats = nullptr; AllocOnStream = nullptr; Shrink = nullptr; } // initializers that are used directly by the model. as there's no copy they must remain valid. // we store them in the test allocator so we can validate that Free is called std::vector>> weights; Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtAllocatorType::OrtDeviceAllocator, OrtMemType::OrtMemTypeDefault); }; // Test the ModelEditorAPI C api // Uses the ORT C++ api for the rest for simplicity TEST(ModelEditorAPITest, Basic_CApi) { const auto& api = Ort::GetApi(); const auto& model_editor_api = Ort::GetModelEditorApi(); TestAllocator deleter; // return void so we can use ASSERT_* in the lambda const auto build_model = [&](bool use_constant_node, OrtModel*& model) -> void { OrtGraph* graph = nullptr; Ort::ThrowOnError(model_editor_api.CreateGraph(&graph)); // // Create OrtModel with a Gemm. X input is 3x4, Y input is 4x8, Z output is 3x8. // X is model input. Y is initializer. // Set the alpha attribute of the Gemm node to 2.0 to test attribute handling. // // model input OrtTensorTypeAndShapeInfo* tensor_type_info = nullptr; std::vector input_dims = {3, 4}; // can use api.SetSymbolicDimensions to set symbolic dimensions. // the input array should have the same rank as the call to SetDimensions. // e.g. call SetDimensions with {-1, 3, 2} and SetSymbolicDimensions with {"N", nullptr, nullptr} to create // a shape of {"N", 3, 2} Ort::ThrowOnError(api.CreateTensorTypeAndShapeInfo(&tensor_type_info)); Ort::ThrowOnError(api.SetTensorElementType(tensor_type_info, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)); Ort::ThrowOnError(api.SetDimensions(tensor_type_info, input_dims.data(), input_dims.size())); OrtTypeInfo* input_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(tensor_type_info, &input_type_info)); api.ReleaseTensorTypeAndShapeInfo(tensor_type_info); // input_type_info took a copy // create ValueInfo and release the type info as CreateValueInfo takes a copy. OrtValueInfo* input_value_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateValueInfo("X", input_type_info, &input_value_info)); api.ReleaseTypeInfo(input_type_info); // input_value_info took a copy tensor_type_info = nullptr; // model outputs OrtTypeInfo* output_type_info = nullptr; std::vector output_dims = {3, 8}; Ort::ThrowOnError(api.CreateTensorTypeAndShapeInfo(&tensor_type_info)); Ort::ThrowOnError(api.SetTensorElementType(tensor_type_info, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)); Ort::ThrowOnError(api.SetDimensions(tensor_type_info, output_dims.data(), output_dims.size())); Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(tensor_type_info, &output_type_info)); api.ReleaseTensorTypeAndShapeInfo(tensor_type_info); // input_type_info took a copy OrtValueInfo* output_value_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateValueInfo("Z", output_type_info, &output_value_info)); api.ReleaseTypeInfo(output_type_info); std::vector graph_inputs = {input_value_info}; std::vector graph_outputs = {output_value_info}; Ort::ThrowOnError(model_editor_api.SetGraphInputs(graph, graph_inputs.data(), graph_inputs.size())); Ort::ThrowOnError(model_editor_api.SetGraphOutputs(graph, graph_outputs.data(), graph_outputs.size())); input_value_info = nullptr; // graph now owns the input/output values output_value_info = nullptr; // // Gemm node // OrtOpAttr* alpha_attr = nullptr; float alpha_value = 2.0; Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT, &alpha_attr)); std::vector node_input_names = {"X", "Y"}; const std::string gemm_output_name = use_constant_node ? "Z_temp" : "Z"; std::vector node_output_names = {gemm_output_name.c_str()}; std::vector node_attributes{alpha_attr}; OrtNode* node = CreateNode(model_editor_api, "Gemm", "Gemm1", node_input_names, node_output_names, node_attributes); alpha_attr = nullptr; // Node now owns Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node)); node = nullptr; // graph now owns node // Y input // As it's 128 bytes it could either be allocated using CreateTensorAsOrtValue or use existing memory. // Under 128 bytes must use CreateTensorAsOrtValue. std::vector y_dims = {4, 8}; deleter.weights.emplace_back(std::make_unique>(32)); auto& y_values = *deleter.weights.back(); std::iota(y_values.begin(), y_values.end(), 1.0f); // create an initializer for the Y input. add to `weights` so the memory remains valid. OrtValue* y_tensor = nullptr; Ort::ThrowOnError( api.CreateTensorWithDataAndDeleterAsOrtValue(&deleter, y_values.data(), y_values.size() * sizeof(y_values[0]), y_dims.data(), y_dims.size(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &y_tensor)); Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "Y", y_tensor, /*data is external*/ true)); y_tensor = nullptr; // graph now owns if (use_constant_node) { // Test that a Constant node is converted to an initializer // create Constant nodes for min/max to limit output range OrtOpAttr* min_attr = nullptr; float min = 400.0f; Ort::ThrowOnError(api.CreateOpAttr("value", &min, sizeof(min), ORT_OP_ATTR_FLOAT, &min_attr)); node = CreateNode(model_editor_api, "Constant", "clip_min", {}, {"min"}, {min_attr}); Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node)); node = nullptr; // graph now owns node OrtOpAttr* max_attr = nullptr; float max = 900.0f; Ort::ThrowOnError(api.CreateOpAttr("value", &max, sizeof(max), ORT_OP_ATTR_FLOAT, &max_attr)); node = CreateNode(model_editor_api, "Constant", "clip_max", {}, {"max"}, {max_attr}); Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node)); node = nullptr; // graph now owns node node = CreateNode(model_editor_api, "Clip", "Clip1", {gemm_output_name.c_str(), "min", "max"}, {"Z"}); Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, node)); node = nullptr; // graph now owns node } // Normal usage would be to add kOnnxDomain. We use the alias to test the implementation converts to kOnnxDomain. // std::vector domain_names = {onnxruntime::kOnnxDomain}; std::vector domain_names = {onnxruntime::kOnnxDomainAlias}; std::vector opset_versions = {18}; Ort::ThrowOnError(model_editor_api.CreateModel(domain_names.data(), opset_versions.data(), domain_names.size(), &model)); Ort::ThrowOnError(model_editor_api.AddGraphToModel(model, graph)); graph = nullptr; // model now owns }; auto run_test = [&](bool use_constant_node) -> void { OrtModel* model = nullptr; build_model(use_constant_node, model); ASSERT_NE(model, nullptr) << "build_model should have created a model"; std::vector> inputs(1); auto& input = inputs[0]; input.name = "X"; input.dims = {3, 4}; input.values = {1.0f, 2.0f, 3.0f, 4.0f, 8.0f, 7.0f, 6.0f, 5.0f, 9.0f, 3.0f, 5.0f, 7.0f}; std::vector expected_dims = {3, 8}; Ort::SessionOptions session_options; auto saved_model_path = ORT_TSTR("model_editor_test_output.onnx"); session_options.SetOptimizedModelFilePath(saved_model_path); Model cxx_model(model); auto session = CreateSession(*ort_env, cxx_model, &session_options); std::vector expected_output; if (use_constant_node) { // clipped with min 400 and max 900 expected_output = {400.0f, 400.0f, 400.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f, 596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 900.0f, 900.0f, 592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 900.0f}; } else { expected_output = {340.0f, 360.0f, 380.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f, 596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 908.0f, 960.0f, 592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 928.0f}; } TestInference(session, inputs, "Z", expected_dims, expected_output); api.ReleaseSession(session.release()); ASSERT_EQ(deleter.weights.size(), size_t(0)) << "All weights should have been freed"; // make sure the saved model can be loaded Ort::Session session2(*ort_env, saved_model_path, Ort::SessionOptions()); // make sure entries for the internal domains were added to the opset imports in the saved model std::vector buffer(std::filesystem::file_size(saved_model_path)); std::ifstream file(saved_model_path, std::ios::binary); ASSERT_TRUE(file.read(buffer.data(), buffer.size())); std::string_view buffer_view(buffer.data(), buffer.size()); ASSERT_NE(buffer_view.find(onnxruntime::kMSInternalNHWCDomain), std::string_view::npos); ASSERT_NE(buffer_view.find(onnxruntime::kMSNchwcDomain), std::string_view::npos); }; run_test(false); run_test(true); // use Constant node for initializer } TEST(ModelEditorAPITest, Basic_CxxApi) { // initializers that are used directly by the model. as there's no copy they must remain valid std::vector>> weights; Ort::Graph graph; // // Create OrtModel with a Gemm. X input is 3x4, Y input is 4x8, Z output is 3x8. // X is model input. Y is initializer. // Set the alpha attribute of the Gemm node to 2.0 to test attribute handling. // std::vector graph_inputs; std::vector graph_outputs; // model input. it's {3, 4} but use a symbolic dim to test that works. std::vector input_dims({-1, 4}); std::vector input_symbolic_dims({"multiple_of_3", ""}); TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, input_dims, &input_symbolic_dims); auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst()); graph_inputs.emplace_back("X", input_type_info.GetConst()); // model outputs std::vector output_dims = {-1, 8}; std::vector output_symbolic_dims({"multiple_of_3", ""}); TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, output_dims, &output_symbolic_dims); auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst()); graph_outputs.emplace_back("Z", output_type_info.GetConst()); graph.SetInputs(graph_inputs); graph.SetOutputs(graph_outputs); // // Gemm node // std::vector attributes; float alpha_value = 2.0; attributes.push_back(OpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT)); Node node("Gemm", onnxruntime::kOnnxDomain, "Gemm1", {"X", "Y"}, {"Z"}, attributes); graph.AddNode(node); // create an initializer for the Y input. // add to `weights` so it remains valid for the lifetime of the session and we can avoid copying the data. // As it's 128 bytes it could either be allocated using CreateTensorAsOrtValue or use existing memory. // Under 128 bytes must use CreateTensorAsOrtValue. std::vector y_dims = {4, 8}; weights.emplace_back(std::make_unique>(32)); auto& y_values = *weights.back(); std::iota(y_values.begin(), y_values.end(), 1.0f); auto info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); // if you use this API the initializer data MUST remain valid for the lifetime of the InferenceSession auto y_tensor = Value::CreateTensor(info, y_values.data(), y_values.size(), y_dims.data(), y_dims.size()); graph.AddInitializer("Y", y_tensor, /*data is external*/ true); std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); model.AddGraph(graph); std::vector> inputs(1); auto& input = inputs[0]; input.name = "X"; input.dims = {3, 4}; input.values = {1.0f, 2.0f, 3.0f, 4.0f, 8.0f, 7.0f, 6.0f, 5.0f, 9.0f, 3.0f, 5.0f, 7.0f}; std::vector expected_dims = {3, 8}; auto session = CreateSession(*ort_env, model); TestInference(session, inputs, "Z", expected_dims, {340.0f, 360.0f, 380.0f, 400.0f, 420.0f, 440.0f, 460.0f, 480.0f, 596.0f, 648.0f, 700.0f, 752.0f, 804.0f, 856.0f, 908.0f, 960.0f, 592.0f, 640.0f, 688.0f, 736.0f, 784.0f, 832.0f, 880.0f, 928.0f}); } TEST(ModelEditorAPITest, BasicModelEdit_CxxApi) { // // Load existing model // Add Cast to change the model input from float to int64 // Update model inputs to match // Run // SessionOptions so; // Set this to save the model if you want to debug. // so.SetOptimizedModelFilePath(ORT_TSTR("model_builder_edited.onnx")); Session session = Session::CreateModelEditorSession(*ort_env, TSTR("testdata/mnist.onnx"), so); ASSERT_EQ(session.GetOpset(""), 8); // ONNX domain is empty string // we augment the original model with nodes, initializers and the updated model inputs/outputs from this model. // the original graph is unchanged. nodes can be added before/after it. initializers can be added. // new nodes must conform to the original domain:opset of the model. // additional operator domain:opset pairs can be added. std::vector opsets; // no additional opsets required Model model(opsets); std::vector graph_inputs = session.GetInputs(); ASSERT_EQ(graph_inputs.size(), size_t(1)); ASSERT_EQ(graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetElementType(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); // typically this isn't needed. we replace this input but need to read info from it later on in the test // validation so we save the info locally to keep it accessible. auto orig_input_name = graph_inputs[0].GetName(); auto input_shape = graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetShape(); const std::string new_input_name = "Int64Input"; // Add Cast node to convert input from float to int64 std::vector attributes; int64_t to = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; attributes.push_back(OpAttr("to", &to, 1, OrtOpAttrType::ORT_OP_ATTR_INT)); Ort::Node node("Cast", onnxruntime::kOnnxDomain, new_input_name, {"Int64Input"}, // the existing node will now consume the output from the Cast instead of a graph input {orig_input_name}, attributes); // we're replacing the only input. the shape is the same but the name and data type change. TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, input_shape); auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst()); graph_inputs[0] = ValueInfo(new_input_name, input_type_info.GetConst()); Graph graph; // new info to augment the model with graph.AddNode(node); graph.SetInputs(graph_inputs); // the node we added does not require any new opsets. model.AddGraph(graph); session.FinalizeModelEditorSession(model, so); std::vector> inputs(1); auto& input = inputs[0]; input.name = new_input_name.c_str(); input.dims = input_shape; auto num_values = std::accumulate(input.dims.begin(), input.dims.end(), int64_t(1), std::multiplies()); input.values.resize(size_t(num_values)); std::iota(input.values.begin(), input.values.end(), 1); std::vector expected_dims = {1, 10}; std::vector expected_output = {-48.5088f, -1040.2948f, -347.0959f, 101.7392f, 421.3352f, 750.92145f, 231.5060f, -1694.4152f, 681.5623f, 378.1689f}; TestInference(session, inputs, session.GetOutputNames()[0].c_str(), expected_dims, expected_output); // double check with original model { SessionOptions expected_so; Session expected_session = Session(*ort_env, TSTR("testdata/mnist.onnx"), expected_so); std::vector> expected_inputs(1); auto& expected_input = expected_inputs[0]; expected_input.name = orig_input_name.c_str(); expected_input.dims = input_shape; expected_input.values.reserve(size_t(num_values)); std::transform(input.values.begin(), input.values.end(), std::back_inserter(expected_input.values), [&](int64_t value) { return float(value); }); TestInference(expected_session, expected_inputs, session.GetOutputNames()[0].c_str(), expected_dims, expected_output); } } TEST(ModelEditorAPITest, InvalidDimension) { try { std::vector input_dims = {-2, 2}; TensorTypeAndShapeInfo tensor_type_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, input_dims); // invalid dim of -2 should cause exception TypeInfo::CreateTensorInfo(tensor_type_info.GetConst()); FAIL() << "Expected exception for invalid dimension"; } catch (const Ort::Exception& e) { ASSERT_STREQ(e.what(), "dim_values must be -1 (symbolic dimension) or larger."); } } TEST(ModelEditorAPITest, CreateInvalidModel_NoOpsets) { Ort::Graph graph; std::vector graph_inputs; std::vector graph_outputs; std::vector dims({4}); TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims); auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst()); graph_inputs.emplace_back("X", type_info.GetConst()); graph_outputs.emplace_back("Z", type_info.GetConst()); graph.SetInputs(graph_inputs); graph.SetOutputs(graph_outputs); Ort::Node node("Add", onnxruntime::kOnnxDomain, "Add1", {"X", "X"}, {"Z"}); graph.AddNode(node); std::vector opsets; Model model(opsets); model.AddGraph(graph); try { auto session = CreateSession(*ort_env, model); FAIL(); } catch (const Ort::Exception& e) { ASSERT_THAT(e.what(), ::testing::HasSubstr("The opset for the ONNX domain must be explicitly specified")); } } TEST(ModelEditorAPITest, CreateInvalidModel_MissingValue) { Ort::Graph graph; std::vector graph_inputs; std::vector graph_outputs; std::vector dims({4}); TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims); auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst()); graph_inputs.emplace_back("X", type_info.GetConst()); graph_outputs.emplace_back("Z", type_info.GetConst()); graph.SetInputs(graph_inputs); graph.SetOutputs(graph_outputs); Ort::Node node("Add", onnxruntime::kOnnxDomain, "Add1", {"X", "missing"}, {"Z"}); graph.AddNode(node); std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); model.AddGraph(graph); try { auto session = CreateSession(*ort_env, model); FAIL(); } catch (const Ort::Exception& e) { ASSERT_THAT(e.what(), ::testing::HasSubstr("Node input 'missing' is not a graph input, " "initializer, or output of a previous node.")); } } TEST(ModelEditorAPITest, InvalidModelEdit) { // Add a node but make the edit invalid in various ways // - add node but don't update graph inputs // - add node with invalid domain const auto edit_model = [](bool invalid_domain) { SessionOptions so; // Set this to save the model if you want to debug. // so.SetOptimizedModelFilePath(ORT_TSTR("model_builder_edited.onnx")); Session session = Session::CreateModelEditorSession(*ort_env, TSTR("testdata/mnist.onnx"), so); ASSERT_EQ(session.GetOpset(""), 8); // ONNX domain is empty string std::vector opsets; // no additional opsets required Model model(opsets); Graph graph; // new info to augment the model with const char* domain = invalid_domain ? "invalid_domain" : onnxruntime::kOnnxDomain; std::vector graph_inputs = session.GetInputs(); ASSERT_EQ(graph_inputs.size(), size_t(1)); ASSERT_EQ(graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetElementType(), ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); const std::string new_input_name = "Int64Input"; // Add Cast node to convert input from float to int64 std::vector attributes; int64_t to = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; attributes.push_back(OpAttr("to", &to, 1, OrtOpAttrType::ORT_OP_ATTR_INT)); Node node("Cast", domain, "NewInputNode", {new_input_name}, // the existing node will now consume the output from the Cast instead of a graph input {graph_inputs[0].GetName()}, attributes); graph.AddNode(node); if (invalid_domain) { // we're replacing the only input. the shape is the same but the name and data type change. TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, graph_inputs[0].TypeInfo().GetTensorTypeAndShapeInfo().GetShape()); auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst()); graph_inputs[0] = ValueInfo(new_input_name, input_type_info.GetConst()); graph.SetInputs(graph_inputs); } else { // model should be invalid as we didn't connect the new node up to the graph inputs } // the node we added does not require any new opsets. model.AddGraph(graph); try { session.FinalizeModelEditorSession(model, so); FAIL() << "Should have failed to resolve graph due to invalid edits."; } catch (const Ort::Exception& e) { if (invalid_domain) { ASSERT_THAT(e.what(), ::testing::HasSubstr("Error No opset import for domain 'invalid_domain'")); } else { ASSERT_THAT(e.what(), ::testing::HasSubstr("This is an invalid model")); } } }; edit_model(false); edit_model(true); // add node with invalid domain } TEST(ModelEditorAPITest, CreateTypeInfo) { const auto& api = Ort::GetApi(); const auto& model_editor_api = Ort::GetModelEditorApi(); TensorTypeAndShapeInfo base_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, {2, 4}); OrtTypeInfo* base_tensor_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateTensorTypeInfo(base_tensor_info, &base_tensor_type_info)); ONNXType onnx_type = ONNX_TYPE_UNKNOWN; const OrtTensorTypeAndShapeInfo* tensor_info = nullptr; ONNXTensorElementDataType onnx_element_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; // sparse tensor OrtTypeInfo* sparse_tensor_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateSparseTensorTypeInfo(base_tensor_info, &sparse_tensor_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sparse_tensor_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_SPARSETENSOR); Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(sparse_tensor_type_info, &tensor_info)); Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type)); ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); api.ReleaseTypeInfo(sparse_tensor_type_info); // sequence OrtTypeInfo* sequence_type_info = nullptr; const OrtSequenceTypeInfo* sequence_info = nullptr; OrtTypeInfo* sequence_element_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateSequenceTypeInfo(base_tensor_type_info, &sequence_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sequence_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_SEQUENCE); Ort::ThrowOnError(api.CastTypeInfoToSequenceTypeInfo(sequence_type_info, &sequence_info)); Ort::ThrowOnError(api.GetSequenceElementType(sequence_info, &sequence_element_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(sequence_element_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR); Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(sequence_element_type_info, &tensor_info)); Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type)); ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); api.ReleaseTypeInfo(sequence_element_type_info); api.ReleaseTypeInfo(sequence_type_info); // map OrtTypeInfo* map_type_info = nullptr; const OrtMapTypeInfo* map_info = nullptr; ONNXTensorElementDataType map_key_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; OrtTypeInfo* map_value_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateMapTypeInfo(ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, base_tensor_type_info, &map_type_info)); // clones map_type_info Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(map_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_MAP); Ort::ThrowOnError(api.CastTypeInfoToMapTypeInfo(map_type_info, &map_info)); Ort::ThrowOnError(api.GetMapKeyType(map_info, &map_key_type)); ASSERT_EQ(map_key_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64); Ort::ThrowOnError(api.GetMapValueType(map_info, &map_value_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(map_value_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR); Ort::ThrowOnError(api.CastTypeInfoToTensorInfo(map_value_type_info, &tensor_info)); Ort::ThrowOnError(api.GetTensorElementType(tensor_info, &onnx_element_type)); ASSERT_EQ(onnx_element_type, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); api.ReleaseTypeInfo(map_value_type_info); api.ReleaseTypeInfo(map_type_info); // optional OrtTypeInfo* optional_type_info = nullptr; const OrtOptionalTypeInfo* optional_info = nullptr; OrtTypeInfo* optional_contained_type_info = nullptr; Ort::ThrowOnError(model_editor_api.CreateOptionalTypeInfo(base_tensor_type_info, &optional_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(optional_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_OPTIONAL); Ort::ThrowOnError(api.CastTypeInfoToOptionalTypeInfo(optional_type_info, &optional_info)); Ort::ThrowOnError(api.GetOptionalContainedTypeInfo(optional_info, &optional_contained_type_info)); Ort::ThrowOnError(api.GetOnnxTypeFromTypeInfo(optional_contained_type_info, &onnx_type)); ASSERT_EQ(onnx_type, ONNXType::ONNX_TYPE_TENSOR); api.ReleaseTypeInfo(optional_contained_type_info); api.ReleaseTypeInfo(optional_type_info); api.ReleaseTypeInfo(base_tensor_type_info); } // // Tests for Model Editor API + Compile API integration // namespace { // Helper to create a simple model for testing with Model Editor API // Creates a model with a Gemm operation: Z = X * Y where X is input and Y is initializer Ort::Model CreateSimpleGemmModel(std::vector>>& weights) { Ort::Graph graph; std::vector graph_inputs; std::vector graph_outputs; // Input: X is 3x4 std::vector input_dims({3, 4}); TensorTypeAndShapeInfo input_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, input_dims); auto input_type_info = TypeInfo::CreateTensorInfo(input_tensor_info.GetConst()); graph_inputs.emplace_back("X", input_type_info.GetConst()); // Output: Z is 3x8 std::vector output_dims = {3, 8}; TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, output_dims); auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst()); graph_outputs.emplace_back("Z", output_type_info.GetConst()); graph.SetInputs(graph_inputs); graph.SetOutputs(graph_outputs); // Gemm node with alpha=2.0 std::vector attributes; float alpha_value = 2.0; attributes.push_back(OpAttr("alpha", &alpha_value, 1, OrtOpAttrType::ORT_OP_ATTR_FLOAT)); Node node("Gemm", onnxruntime::kOnnxDomain, "Gemm1", {"X", "Y"}, {"Z"}, attributes); graph.AddNode(node); // Y initializer: 4x8 std::vector y_dims = {4, 8}; weights.emplace_back(std::make_unique>(32)); auto& y_values = *weights.back(); std::iota(y_values.begin(), y_values.end(), 1.0f); auto info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); auto y_tensor = Value::CreateTensor(info, y_values.data(), y_values.size(), y_dims.data(), y_dims.size()); graph.AddInitializer("Y", y_tensor, /*data is external*/ true); std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); model.AddGraph(graph); return model; } // Helper to run inference on the simple Gemm model and verify all output values. // Model is Z = 2.0 * X * Y where X is 3x4 (all ones) and Y is 4x8 (iota 1..32). // Expected output: each row is 2 * column_sums_of_Y = {104, 112, 120, 128, 136, 144, 152, 160}. void RunAndVerifySimpleGemmModel(const Ort::Model& model) { Ort::SessionOptions session_options; Ort::Session session(*ort_env, model, session_options); ASSERT_EQ(session.GetInputCount(), 1u); ASSERT_EQ(session.GetOutputCount(), 1u); std::vector input_data(3 * 4, 1.0f); std::vector input_dims = {3, 4}; auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); auto input_tensor = Ort::Value::CreateTensor(memory_info, input_data.data(), input_data.size(), input_dims.data(), input_dims.size()); const char* input_names[] = {"X"}; const char* output_names[] = {"Z"}; auto outputs = session.Run(Ort::RunOptions{}, input_names, &input_tensor, 1, output_names, 1); ASSERT_EQ(outputs.size(), 1u); ASSERT_TRUE(outputs[0].IsTensor()); auto output_shape = outputs[0].GetTensorTypeAndShapeInfo().GetShape(); ASSERT_EQ(output_shape, (std::vector{3, 8})); const float* output_data = outputs[0].GetTensorData(); // alpha=2.0, X is all ones, so each output row = 2 * sum of each column of Y (iota 1..32 in 4x8) const std::vector expected_row = {104.0f, 112.0f, 120.0f, 128.0f, 136.0f, 144.0f, 152.0f, 160.0f}; for (int row = 0; row < 3; ++row) { for (int col = 0; col < 8; ++col) { EXPECT_FLOAT_EQ(output_data[row * 8 + col], expected_row[col]) << "Mismatch at row=" << row << " col=" << col; } } } } // namespace // Test basic compilation from OrtModel TEST(ModelEditorCompileAPITest, BasicCompileFromOrtModel) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); // Set the OrtModel as input compile_options.SetInputModel(static_cast(model)); // Set output to buffer - use embed mode for simplicity compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); // Compile should succeed (note: may not produce EPContext nodes without specific EP, but validation passes) ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); // Verify output was produced EXPECT_NE(output_buffer, nullptr); EXPECT_GT(output_size, 0u); // Cleanup if (output_buffer != nullptr) { allocator->Free(output_buffer); } // Verify the model still produces correct inference results after compilation RunAndVerifySimpleGemmModel(model); } TEST(ModelEditorCompileAPITest, CompileFromNullModel_Fails) { Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); try { compile_options.SetInputModel(nullptr); FAIL() << "Expected exception for null model pointer"; } catch (const Ort::Exception& e) { EXPECT_THAT(e.what(), ::testing::HasSubstr("null")); } } // Test validation: model with no graph TEST(ModelEditorCompileAPITest, CompileFromModelWithNoGraph_Fails) { // Create a model but don't add a graph std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); Ort::Status status = Ort::CompileModel(*ort_env, compile_options); EXPECT_FALSE(status.IsOK()) << "Expected CompileModel to fail for model with no graph"; EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("graph")); } // Test validation: model with no outputs (one input but zero outputs). // 0 outputs is still rejected because compilation produces an output model that // would have no consumers for any computed values. TEST(ModelEditorCompileAPITest, CompileFromModelWithEmptyOutputs_Fails) { Ort::Graph graph; // Provide a single input but no outputs, to isolate the output-count check. std::vector graph_inputs; std::vector dims({4}); TensorTypeAndShapeInfo tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, dims); auto type_info = TypeInfo::CreateTensorInfo(tensor_info.GetConst()); graph_inputs.emplace_back("X", type_info.GetConst()); graph.SetInputs(graph_inputs); // Intentionally do not call SetOutputs. std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); model.AddGraph(graph); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); Ort::Status status = Ort::CompileModel(*ort_env, compile_options); EXPECT_FALSE(status.IsOK()) << "Expected CompileModel to fail for model with no outputs"; EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("at least one output")); } // Test: model with zero graph inputs is now accepted by CompileModel. // Mirrors what CreateSessionFromModel already accepts (e.g., a graph composed of // zero-input generator ops like RandomNormal that produces output without external input). // Regression test for https://github.com/microsoft/onnxruntime/issues/28135. // // Scope: this test exercises only the ORT-side validation in ModelCompilationOptions::Check(). // EP-specific validation (e.g., whether the WebNN EP's partitioner accepts a 0-input subgraph) // is owned by the respective EP and is not covered here. TEST(ModelEditorCompileAPITest, CompileFromModelWithEmptyInputs_Succeeds) { Ort::Graph graph; // Zero graph inputs; one graph output produced by a RandomNormal node. // RandomNormal takes 0 inputs and produces a tensor with shape specified via attribute. // Use RandomNormal rather than Constant because Constant nodes are folded into initializers // at load time (see graph.cc Graph::LoadFromModelEditorApiModel) and would not exercise // the true 0-input producer path. std::vector output_dims = {2, 3}; TensorTypeAndShapeInfo output_tensor_info(ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, output_dims); auto output_type_info = TypeInfo::CreateTensorInfo(output_tensor_info.GetConst()); std::vector graph_outputs; graph_outputs.emplace_back("Y", output_type_info.GetConst()); graph.SetOutputs(graph_outputs); // Intentionally do not call SetInputs (zero graph inputs). std::vector attributes; std::vector shape_attr_value = {2, 3}; attributes.push_back(OpAttr("shape", shape_attr_value.data(), static_cast(shape_attr_value.size()), OrtOpAttrType::ORT_OP_ATTR_INTS)); Node node("RandomNormal", onnxruntime::kOnnxDomain, "RandomNormal1", /*input_names*/ {}, /*output_names*/ {"Y"}, attributes); graph.AddNode(node); std::vector opsets{{onnxruntime::kOnnxDomain, 18}}; Model model(opsets); model.AddGraph(graph); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); // Compile should succeed. No specific compiling EP is required; the default // kGenerateModel action emits an output model even when no EPContext nodes are produced. ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); // Fatal: a compile that returns OK but produces no artifact bytes is a regression. ASSERT_NE(output_buffer, nullptr); ASSERT_GT(output_size, 0u); allocator->Free(output_buffer); } // Test: model can be reused after compilation. // NOTE: This is not an explicit API guarantee. It documents current behavior so that if a future change // breaks model reuse, the regression is surfaced and can be evaluated. TEST(ModelEditorCompileAPITest, ModelCanBeReusedAfterCompilation) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); // First compilation { Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); if (output_buffer != nullptr) { allocator->Free(output_buffer); } } // Second compilation with same model { Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); if (output_buffer != nullptr) { allocator->Free(output_buffer); } } // Model should still be usable for creating a session and running inference RunAndVerifySimpleGemmModel(model); } // Test: SetInputModel overrides previous input source (file path) TEST(ModelEditorCompileAPITest, SetInputModelOverridesPreviousInputPath) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); // First set a file path (doesn't need to exist since we'll override it) compile_options.SetInputModelPath(ORT_TSTR("nonexistent_file.onnx")); // Then override with OrtModel compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); // Should use the OrtModel, not the nonexistent file ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); if (output_buffer != nullptr) { allocator->Free(output_buffer); } } // Test: SetInputModelPath overrides previous OrtModel setting TEST(ModelEditorCompileAPITest, SetInputModelPathOverridesPreviousModel) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); // First set an OrtModel compile_options.SetInputModel(static_cast(model)); // Then override with a real file path compile_options.SetInputModelPath(ORT_TSTR("testdata/matmul_1.onnx")); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); // Should use the file path, not the OrtModel ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); if (output_buffer != nullptr) { allocator->Free(output_buffer); } } // Test: Compile with output to file TEST(ModelEditorCompileAPITest, CompileFromOrtModelToFile) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); auto output_path = ORT_TSTR("test_compile_from_ortmodel_output.onnx"); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetOutputModelPath(output_path); compile_options.SetEpContextEmbedMode(true); ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); // Verify output file exists EXPECT_TRUE(std::filesystem::exists(output_path)); // Verify the output model can be loaded Ort::Session session(*ort_env, output_path, Ort::SessionOptions()); EXPECT_GE(session.GetInputCount(), 1u); EXPECT_GE(session.GetOutputCount(), 1u); // Cleanup std::filesystem::remove(output_path); } // Test: Validation error for OrtModel with no model_path, no output location, and no embed mode. TEST(ModelEditorCompileAPITest, NoOutputLocationNoModelPathFails) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); // Intentionally do NOT call SetEpContextEmbedMode, SetOutputModelPath, or SetOutputModelBuffer Ort::Status status = Ort::CompileModel(*ort_env, compile_options); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("output")); } // Test: Setting embed mode with buffer output satisfies the output location requirement // for OrtModel with no model_path. TEST(ModelEditorCompileAPITest, EmbedModeWithBufferOutputSatisfiesValidation) { std::vector>> weights; auto model = CreateSimpleGemmModel(weights); Ort::SessionOptions session_options; Ort::ModelCompilationOptions compile_options(*ort_env, session_options); compile_options.SetInputModel(static_cast(model)); compile_options.SetEpContextEmbedMode(true); std::unique_ptr allocator = std::make_unique(); void* output_buffer = nullptr; size_t output_size = 0; compile_options.SetOutputModelBuffer(allocator.get(), &output_buffer, &output_size); ASSERT_ORTSTATUS_OK(Ort::CompileModel(*ort_env, compile_options)); if (output_buffer != nullptr) { allocator->Free(output_buffer); } } TEST(ModelEditorAPITest, CreateNode_DuplicateAttributePointer_Fails) { const auto& api = Ort::GetApi(); const auto& model_editor_api = Ort::GetModelEditorApi(); float alpha_value = 1.0f; OrtOpAttr* attr = nullptr; Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, ORT_OP_ATTR_FLOAT, &attr)); std::vector input_names = {"X"}; std::vector output_names = {"Y"}; // Pass the same attribute pointer twice — should fail without releasing it std::vector attrs = {attr, attr}; OrtNode* node = nullptr; Ort::Status status{model_editor_api.CreateNode("Relu", onnxruntime::kOnnxDomain, "relu1", input_names.data(), input_names.size(), output_names.data(), output_names.size(), attrs.data(), attrs.size(), &node)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate")); EXPECT_EQ(node, nullptr); // Caller still owns the attribute since CreateNode failed before taking ownership api.ReleaseOpAttr(attr); } TEST(ModelEditorAPITest, CreateNode_NullAttributeEntry_Fails) { const auto& api = Ort::GetApi(); const auto& model_editor_api = Ort::GetModelEditorApi(); float alpha_value = 1.0f; OrtOpAttr* attr = nullptr; Ort::ThrowOnError(api.CreateOpAttr("alpha", &alpha_value, 1, ORT_OP_ATTR_FLOAT, &attr)); std::vector input_names = {"X"}; std::vector output_names = {"Y"}; std::vector attrs = {attr, nullptr}; OrtNode* node = nullptr; Ort::Status status{model_editor_api.CreateNode("Relu", onnxruntime::kOnnxDomain, "relu1", input_names.data(), input_names.size(), output_names.data(), output_names.size(), attrs.data(), attrs.size(), &node)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("null")); EXPECT_EQ(node, nullptr); api.ReleaseOpAttr(attr); } // Regression: passing the same OrtValue* twice to AddInitializerToGraph must be rejected. // Without the duplicate-pointer guard, the graph would own two unique_ptrs to the same allocation // and double-free on destruction. TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicatePointer_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; // Create a CPU tensor via the C++ API (RAII). std::vector data(4, 0.0f); std::vector dims = {2, 2}; auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); Ort::Value value = Ort::Value::CreateTensor(memory_info, data.data(), data.size(), dims.data(), dims.size()); // First add transfers ownership of the raw OrtValue* to the graph. Detach the C++ wrapper // so it does not also try to release it on destruction. OrtValue* raw = value; Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W1", raw, /*data_is_external*/ false)); static_cast(value.release()); // Second add of the same raw pointer (under a different name) must fail without taking ownership. Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W2", raw, /*data_is_external*/ false)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added")); } // Regression: passing the same OrtNode* twice to AddNodeToGraph must be rejected. TEST(ModelEditorAPITest, AddNodeToGraph_DuplicatePointer_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; Ort::Node node("Relu", onnxruntime::kOnnxDomain, "relu1", {"X"}, {"Y"}); // First add transfers ownership of the raw OrtNode* to the graph. Detach the C++ wrapper. OrtNode* raw = node; Ort::ThrowOnError(model_editor_api.AddNodeToGraph(graph, raw)); static_cast(node.release()); // Second add of the same raw pointer must fail without taking ownership. Ort::Status status{model_editor_api.AddNodeToGraph(graph, raw)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added")); } namespace { // Helper: create a CPU OrtValue tensor of `num_floats` zero floats backed by `storage`. // The returned Ort::Value owns only the OrtValue wrapper; the underlying buffer remains in // `storage`, so the caller must keep `storage` alive for as long as the tensor may be accessed. Ort::Value MakeCpuFloatTensor(std::vector& storage, size_t num_floats, const std::vector& dims) { storage.assign(num_floats, 0.0f); auto memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeDefault); return Ort::Value::CreateTensor(memory_info, storage.data(), storage.size(), dims.data(), dims.size()); } } // namespace // Reject a second initializer with the same name (within the regular initializer map). TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicateName_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; std::vector storage_a, storage_b; Ort::Value a = MakeCpuFloatTensor(storage_a, 4, {2, 2}); Ort::Value b = MakeCpuFloatTensor(storage_b, 4, {2, 2}); OrtValue* raw_a = a; Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W", raw_a, /*data_is_external*/ false)); static_cast(a.release()); OrtValue* raw_b = b; Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw_b, /*data_is_external*/ false)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("name")); // Caller still owns `b` and Ort::Value's destructor releases it. No leak, no double-free. } // Reject a duplicate name that collides across the regular/external boundary. TEST(ModelEditorAPITest, AddInitializerToGraph_DuplicateNameAcrossExternal_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; // First initializer: regular, small. std::vector storage_small; Ort::Value small = MakeCpuFloatTensor(storage_small, 4, {2, 2}); OrtValue* raw_small = small; Ort::ThrowOnError(model_editor_api.AddInitializerToGraph(graph, "W", raw_small, /*data_is_external*/ false)); static_cast(small.release()); // Second initializer: external, large enough to satisfy the size guard, same name. std::vector storage_big; Ort::Value big = MakeCpuFloatTensor(storage_big, 64, {64}); // 256 bytes, > kSmallTensorExternalDataThreshold OrtValue* raw_big = big; Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw_big, /*data_is_external*/ true)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("name")); } // data_is_external=true with a tensor at or below kSmallTensorExternalDataThreshold must be rejected // because the resulting in-memory external-data reference would be unusable by ONNX shape inferencing. TEST(ModelEditorAPITest, AddInitializerToGraph_SmallExternal_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; std::vector storage; Ort::Value small = MakeCpuFloatTensor(storage, 4, {2, 2}); // 16 bytes OrtValue* raw = small; Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", raw, /*data_is_external*/ true)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("data_is_external")); // Ownership not transferred; Ort::Value destructor releases `small`. } // AddInitializerToGraph rejects null arguments without taking ownership. TEST(ModelEditorAPITest, AddInitializerToGraph_NullArgs_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; std::vector storage; Ort::Value v = MakeCpuFloatTensor(storage, 4, {2, 2}); OrtValue* raw = v; // Null graph. { Ort::Status status{model_editor_api.AddInitializerToGraph(nullptr, "W", raw, false)}; EXPECT_FALSE(status.IsOK()); } // Null name. { Ort::Status status{model_editor_api.AddInitializerToGraph(graph, nullptr, raw, false)}; EXPECT_FALSE(status.IsOK()); } // Empty name. { Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "", raw, false)}; EXPECT_FALSE(status.IsOK()); } // Null tensor. { Ort::Status status{model_editor_api.AddInitializerToGraph(graph, "W", nullptr, false)}; EXPECT_FALSE(status.IsOK()); } // None of the above transferred ownership; Ort::Value destructor releases `v`. } // AddNodeToGraph rejects null arguments. TEST(ModelEditorAPITest, AddNodeToGraph_NullArgs_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; Ort::Node node("Relu", onnxruntime::kOnnxDomain, "relu1", {"X"}, {"Y"}); { Ort::Status status{model_editor_api.AddNodeToGraph(nullptr, node)}; EXPECT_FALSE(status.IsOK()); } { Ort::Status status{model_editor_api.AddNodeToGraph(graph, nullptr)}; EXPECT_FALSE(status.IsOK()); } // Ownership not transferred; Ort::Node destructor releases the node. } // AddGraphToModel rejects a second graph and rejects null arguments. TEST(ModelEditorAPITest, AddGraphToModel_Twice_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); std::vector domains = {onnxruntime::kOnnxDomain}; std::vector versions = {18}; OrtModel* raw_model = nullptr; Ort::ThrowOnError(model_editor_api.CreateModel(domains.data(), versions.data(), domains.size(), &raw_model)); Ort::Model model{raw_model}; Ort::Graph g1; OrtGraph* raw_g1 = g1; Ort::ThrowOnError(model_editor_api.AddGraphToModel(model, raw_g1)); static_cast(g1.release()); // Second AddGraphToModel must fail without taking ownership of g2. Ort::Graph g2; OrtGraph* raw_g2 = g2; Ort::Status status{model_editor_api.AddGraphToModel(model, raw_g2)}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("graph")); // g2 destructor releases the still-owned raw_g2. } TEST(ModelEditorAPITest, AddGraphToModel_NullArgs_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); std::vector domains = {onnxruntime::kOnnxDomain}; std::vector versions = {18}; OrtModel* raw_model = nullptr; Ort::ThrowOnError(model_editor_api.CreateModel(domains.data(), versions.data(), domains.size(), &raw_model)); Ort::Model model{raw_model}; Ort::Graph graph; { Ort::Status status{model_editor_api.AddGraphToModel(nullptr, graph)}; EXPECT_FALSE(status.IsOK()); } { Ort::Status status{model_editor_api.AddGraphToModel(model, nullptr)}; EXPECT_FALSE(status.IsOK()); } } namespace { // Build a CPU float `Ort::ValueInfo` of rank-1 shape {1} for the given name. Ort::ValueInfo MakeFloatValueInfo(const char* name) { Ort::TensorTypeAndShapeInfo tts(ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, std::vector{1}); Ort::TypeInfo ti = Ort::TypeInfo::CreateTensorInfo(tts.GetConst()); return Ort::ValueInfo(name, ti.GetConst()); } } // namespace // Reject the same OrtValueInfo* appearing twice within the SetGraphInputs array. TEST(ModelEditorAPITest, SetGraphInputs_DuplicatePointerInArray_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; Ort::ValueInfo vi = MakeFloatValueInfo("X"); // Implicit Base::operator T*() yields the raw pointer without releasing. OrtValueInfo* raw = vi; std::vector inputs = {raw, raw}; Ort::Status status{model_editor_api.SetGraphInputs(graph, inputs.data(), inputs.size())}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate")); EXPECT_NE(inputs[0], nullptr); // ownership not transferred on failure EXPECT_NE(inputs[1], nullptr); // `vi` destructor releases the still-owned OrtValueInfo. No double-free. } // Reject the same OrtValueInfo* appearing twice within the SetGraphOutputs array. TEST(ModelEditorAPITest, SetGraphOutputs_DuplicatePointerInArray_Fails) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; Ort::ValueInfo vi = MakeFloatValueInfo("Y"); OrtValueInfo* raw = vi; std::vector outputs = {raw, raw}; Ort::Status status{model_editor_api.SetGraphOutputs(graph, outputs.data(), outputs.size())}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("Duplicate")); EXPECT_NE(outputs[0], nullptr); EXPECT_NE(outputs[1], nullptr); } // Reject reusing an OrtValueInfo* already owned by the graph (input -> output). TEST(ModelEditorAPITest, SetGraph_RejectsAlreadyOwnedPointer) { const auto& model_editor_api = Ort::GetModelEditorApi(); Ort::Graph graph; Ort::ValueInfo input_vi = MakeFloatValueInfo("X"); // Transfer to graph as an input via the C++ wrapper (which calls release() on success). OrtValueInfo* still_owned_by_graph = input_vi; // capture before release() std::vector inputs; inputs.emplace_back(std::move(input_vi)); graph.SetInputs(inputs); // Re-using the same raw pointer (now owned by graph) as an output must be rejected. std::vector outputs = {still_owned_by_graph}; Ort::Status status{model_editor_api.SetGraphOutputs(graph, outputs.data(), outputs.size())}; EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.GetErrorMessage(), ::testing::HasSubstr("already been added")); EXPECT_NE(outputs[0], nullptr); // ownership not transferred on failure // graph still owns the pointer; Graph destructor releases it. }