// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if !defined(REDUCED_OPS_BUILD) // may not work with excluded op kernel implementations #include "core/common/logging/logging.h" #include "core/framework/compute_capability.h" #include "core/framework/utils.h" #include "core/session/inference_session.h" #include "test/unittest_util/framework_test_utils.h" #include "test/internal_testing_ep/internal_testing_execution_provider.h" #include "test/test_environment.h" #include "test/util/include/asserts.h" #include "test/util/include/inference_session_wrapper.h" #include "test/util/include/temp_dir.h" #include "test/util/include/test_utils.h" #include "onnxruntime_cxx_api.h" #if !defined(ORT_MINIMAL_BUILD) #include "core/framework/config_options.h" #include "core/framework/execution_providers.h" #include "core/framework/ep_context_options.h" #include "core/framework/fuse_nodes_funcs.h" #include "core/framework/graph_partitioner.h" #include "core/framework/kernel_registry_manager.h" #include "core/framework/model_metadef_id_generator.h" #include "core/framework/resource_accountant.h" #include "core/graph/constants.h" #include "core/optimizer/graph_optimizer_registry.h" #include "core/providers/partitioning_utils.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "test/unittest_util/graph_transform_test_builder.h" #endif // !defined(ORT_MINIMAL_BUILD) #include "gtest/gtest.h" #include "gmock/gmock.h" #include #include #include #include using namespace ONNX_NAMESPACE; using namespace onnxruntime::logging; namespace onnxruntime { namespace test { using namespace onnxruntime::internal_testing_ep; // tests use onnx format models currently so exclude them from a minimal build. // it would be possible to use ORT format models but the same partitioning code would run either way #if !defined(ORT_MINIMAL_BUILD) // These NHWC two-pass partitioning helpers and tests only use ONNX-domain ops // (Conv, LogSoftmax) and core framework utilities, so they are intentionally not // guarded by DISABLE_CONTRIB_OPS and provide regression coverage in contrib-disabled builds. namespace { constexpr size_t kNhwcSurvivorWorkspaceBytes = 700 * 1024; constexpr size_t kNhwcDroppedWorkspaceBytes = 50 * 1024; constexpr size_t kNhwcPass2OnlyWorkspaceBytes = 350 * 1024; Level1MemoryEstimate GetNhwcAccountingTestEstimate(const std::string& op_type) { if (op_type == "Conv") { return {/*runtime_workspace_bytes=*/kNhwcSurvivorWorkspaceBytes, /*persistent_prepack_bytes=*/102, /*initialization_scratch_bytes=*/103}; } if (op_type == "Relu") { return {/*runtime_workspace_bytes=*/kNhwcPass2OnlyWorkspaceBytes, /*persistent_prepack_bytes=*/302, /*initialization_scratch_bytes=*/303}; } return {/*runtime_workspace_bytes=*/kNhwcDroppedWorkspaceBytes, /*persistent_prepack_bytes=*/202, /*initialization_scratch_bytes=*/203}; } class TwoPassNhwcTestExecutionProvider : public IExecutionProvider { public: TwoPassNhwcTestExecutionProvider() : IExecutionProvider{"TwoPassNhwcTestExecutionProvider"} { } DataLayout GetPreferredLayout() const override { return DataLayout::NHWC; } std::vector> GetCapability(const GraphViewer& graph_viewer, const IKernelLookup&, const GraphOptimizerRegistry&, IResourceAccountant*) const override { // Detect second pass by checking if any node already has our EP type assigned // (set during the first-pass assignment). Real NHWC EPs use this pattern to // recognize nodes that were transformed into kMSInternalNHWCDomain. bool second_pass = false; for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const Node* node = graph_viewer.GetNode(node_index); if (node != nullptr && node->GetExecutionProviderType() == Type()) { second_pass = true; break; } } auto generate_metadef_name = [this, &graph_viewer]() { HashValue model_hash; const int metadef_id = metadef_id_generator_.GenerateId(graph_viewer, model_hash); return std::string(Type()) + "_" + std::to_string(model_hash) + "_" + std::to_string(metadef_id); }; std::vector> capabilities; for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const Node* node = graph_viewer.GetNode(node_index); if (node == nullptr) { continue; } const bool is_conv = node->OpType() == "Conv"; const bool is_log_softmax = node->OpType() == "LogSoftmax"; if (!is_conv && !is_log_softmax) { continue; } if (second_pass && is_log_softmax) { continue; } const auto& assigned_ep = node->GetExecutionProviderType(); if (!assigned_ep.empty() && assigned_ep != Type()) { continue; } capabilities.push_back(utils::MakeComputeCapability(graph_viewer, std::vector{node}, generate_metadef_name, Type(), false)); } return capabilities; } Status Compile(const std::vector& fused_nodes, std::vector& node_compute_funcs) override { for (size_t i = 0; i < fused_nodes.size(); ++i) { NodeComputeInfo compute_info; compute_info.create_state_func = [](ComputeContext*, FunctionState*) { return 0; }; compute_info.release_state_func = [](FunctionState) {}; compute_info.compute_func = [](FunctionState, const OrtApi*, OrtKernelContext*) { return Status::OK(); }; node_compute_funcs.push_back(std::move(compute_info)); } return Status::OK(); } private: mutable ModelMetadefIdGenerator metadef_id_generator_; }; struct DirectAssignmentEpContextTestOptions { DataLayout preferred_layout = DataLayout::Default; bool enable_resource_accountant = false; bool drop_after_layout = false; bool assigned_to_other_ep = false; std::optional embed_mode = 0; bool output_embed_mode = false; }; class DirectAssignmentEpContextTestExecutionProvider : public IExecutionProvider { public: explicit DirectAssignmentEpContextTestExecutionProvider(bool produces_ep_context_nodes = false, bool* get_ep_context_nodes_called = nullptr, uint32_t ep_context_data_support = OrtEpContextDataCallbackSupportFlags_NONE, bool claims_ep_context_node = true, const DirectAssignmentEpContextTestOptions& options = {}) : IExecutionProvider{options.enable_resource_accountant ? kCudaExecutionProvider : "DirectAssignmentEpContextTestExecutionProvider"}, produces_ep_context_nodes_{produces_ep_context_nodes}, get_ep_context_nodes_called_{get_ep_context_nodes_called}, ep_context_data_support_{ep_context_data_support}, claims_ep_context_node_{claims_ep_context_node}, options_{options} { } DataLayout GetPreferredLayout() const override { return options_.preferred_layout; } std::vector> GetCapability(const GraphViewer& graph_viewer, const IKernelLookup&, const GraphOptimizerRegistry&, IResourceAccountant* resource_accountant) const override { const bool after_layout = get_capability_call_count_++ > 0; std::vector> capabilities; for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const auto* node = graph_viewer.GetNode(node_index); if (claims_ep_context_node_ && node != nullptr && node->Domain() == kMSDomain && node->OpType() == "EPContext") { if (after_layout && options_.drop_after_layout) { continue; } // The accountant retains independently runnable survivors even when the final // budgeted pass omits their capabilities. if (resource_accountant != nullptr && node->GetExecutionProviderType() == Type()) { continue; } ep_context_node_ = node; auto sub_graph = std::make_unique(); sub_graph->nodes.push_back(node_index); if (resource_accountant != nullptr && node->GetExecutionProviderType().empty()) { sub_graph->SetAccountant(resource_accountant); sub_graph->AppendNodeCost(resource_accountant->ComputeResourceCount(*node)); } capabilities.push_back(std::make_unique(std::move(sub_graph))); } } last_capability_count_ = capabilities.size(); return capabilities; } const InlinedVector GetEpContextNodes() const override { if (get_ep_context_nodes_called_ != nullptr) { *get_ep_context_nodes_called_ = true; } InlinedVector nodes; if (produces_ep_context_nodes_ && ep_context_node_ != nullptr) { nodes.push_back(ep_context_node_); } return nodes; } uint32_t GetEpContextDataCallbackRequirements(const GraphViewer& /*graph_viewer*/) const override { return produces_ep_context_nodes_ ? OrtEpContextDataCallbackSupportFlags_WRITE : OrtEpContextDataCallbackSupportFlags_NONE; } Status GetEpContextDataCallbackSupport(uint32_t& supported_flags) const override { ++support_query_count_; supported_flags = ep_context_data_support_; return Status::OK(); } size_t get_capability_call_count() const { return get_capability_call_count_; } size_t last_capability_count() const { return last_capability_count_; } size_t support_query_count() const { return support_query_count_; } private: const bool produces_ep_context_nodes_; bool* const get_ep_context_nodes_called_; const uint32_t ep_context_data_support_; const bool claims_ep_context_node_; const DirectAssignmentEpContextTestOptions options_; mutable const Node* ep_context_node_{nullptr}; mutable size_t get_capability_call_count_ = 0; mutable size_t last_capability_count_ = 0; mutable size_t support_query_count_ = 0; }; // Variant of the two-pass NHWC EP used to validate that the resource accountant // is updated correctly across the NHWC two-pass partitioning flow. // // It reports kCudaExecutionProvider as its type so that the SizeBasedResourceAccountant // (which CreateAccountants registers under kCudaExecutionProvider) is wired to it, // mirroring the real in-tree CUDA EP. Like the CUDA EP, it attaches accounting costs // only to newly claimed capabilities. Independently runnable second-pass survivors keep // their provisional reservation; survivors grouped with new nodes are re-probed and carry // the complete capability cost. Dropped nodes therefore never leak budget. enum class SurvivorCapabilityMode { kSeparate, kFused, kPartialOverlap, kSplitCoverage, kMixedWithPass2Node, kAccountedMixedOverlap, kOptimizationOnly, }; class AccountingNhwcTestExecutionProvider : public IExecutionProvider { public: explicit AccountingNhwcTestExecutionProvider( std::optional unassignable_capability_node_index = std::nullopt, SurvivorCapabilityMode survivor_capability_mode = SurvivorCapabilityMode::kSeparate, std::optional second_pass_dropped_node_index = std::nullopt, std::optional accounted_overlap_dropped_node_index = std::nullopt) : IExecutionProvider{kCudaExecutionProvider}, unassignable_capability_node_index_(unassignable_capability_node_index), survivor_capability_mode_(survivor_capability_mode), second_pass_dropped_node_index_(second_pass_dropped_node_index), accounted_overlap_dropped_node_index_(accounted_overlap_dropped_node_index) { } DataLayout GetPreferredLayout() const override { return DataLayout::NHWC; } std::vector> GetCapability(const GraphViewer& graph_viewer, const IKernelLookup&, const GraphOptimizerRegistry&, IResourceAccountant* resource_accountant) const override { if (resource_accountant != nullptr) { observed_accountant_ = resource_accountant; } bool second_pass = false; for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const Node* node = graph_viewer.GetNode(node_index); if (node != nullptr && node->GetExecutionProviderType() == Type()) { second_pass = true; break; } } auto generate_metadef_name = [this, &graph_viewer]() { HashValue model_hash; const int metadef_id = metadef_id_generator_.GenerateId(graph_viewer, model_hash); return std::string(Type()) + "_" + std::to_string(model_hash) + "_" + std::to_string(metadef_id); }; std::vector> capabilities; std::vector fused_pass1_survivors; const bool return_partial_survivor_overlap = second_pass && survivor_capability_mode_ == SurvivorCapabilityMode::kPartialOverlap && resource_accountant != nullptr; if (return_partial_survivor_overlap) { for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const Node* node = graph_viewer.GetNode(node_index); if (node != nullptr && node->OpType() == "Conv") { capabilities.push_back(utils::MakeComputeCapability( graph_viewer, std::vector{node}, generate_metadef_name, Type(), false)); break; } } } size_t consumed_memory = 0; size_t memory_threshold = std::numeric_limits::max(); if (resource_accountant != nullptr) { consumed_memory = std::get(resource_accountant->GetConsumedAmount()); last_observed_consumed_ = consumed_memory; if (const auto threshold = resource_accountant->GetThreshold(); threshold.has_value()) { memory_threshold = std::get(*threshold); } } for (const auto node_index : graph_viewer.GetNodesInTopologicalOrder()) { const Node* node = graph_viewer.GetNode(node_index); if (node == nullptr) { continue; } const bool is_conv = node->OpType() == "Conv"; const bool is_log_softmax = node->OpType() == "LogSoftmax"; const bool is_relu = node->OpType() == "Relu"; const bool is_add = node->OpType() == "Add"; if (!is_conv && !is_log_softmax && !is_relu && !is_add) { continue; } const auto& assigned_ep = node->GetExecutionProviderType(); if (!assigned_ep.empty() && assigned_ep != Type()) { continue; } const bool already_claimed = (assigned_ep == Type()); const bool drop_accounted_overlap_survivor = second_pass && survivor_capability_mode_ == SurvivorCapabilityMode::kAccountedMixedOverlap && resource_accountant != nullptr && (is_log_softmax || (accounted_overlap_dropped_node_index_.has_value() && node_index == *accounted_overlap_dropped_node_index_)); // Drop a provisional survivor on the second pass to model the EP changing // capability grouping. Relu models a node that becomes claimable only in pass 2. if ((second_pass && is_log_softmax && (survivor_capability_mode_ == SurvivorCapabilityMode::kSeparate || survivor_capability_mode_ == SurvivorCapabilityMode::kMixedWithPass2Node || survivor_capability_mode_ == SurvivorCapabilityMode::kOptimizationOnly)) || drop_accounted_overlap_survivor || (!second_pass && is_relu) || (second_pass && is_relu && survivor_capability_mode_ == SurvivorCapabilityMode::kSplitCoverage) || (second_pass_dropped_node_index_.has_value() && second_pass && node_index == *second_pass_dropped_node_index_)) { continue; } if (return_partial_survivor_overlap && is_conv) { continue; } const bool collect_fused_survivors = second_pass && (survivor_capability_mode_ == SurvivorCapabilityMode::kFused || (survivor_capability_mode_ == SurvivorCapabilityMode::kPartialOverlap && resource_accountant == nullptr) || (survivor_capability_mode_ == SurvivorCapabilityMode::kSplitCoverage && resource_accountant == nullptr) || survivor_capability_mode_ == SurvivorCapabilityMode::kMixedWithPass2Node || survivor_capability_mode_ == SurvivorCapabilityMode::kAccountedMixedOverlap); const bool collect_mixed_capability = survivor_capability_mode_ == SurvivorCapabilityMode::kMixedWithPass2Node || (survivor_capability_mode_ == SurvivorCapabilityMode::kAccountedMixedOverlap && resource_accountant != nullptr); const bool collect_for_fusion = collect_fused_survivors && (survivor_capability_mode_ == SurvivorCapabilityMode::kAccountedMixedOverlap ? (resource_accountant == nullptr ? already_claimed : (already_claimed || is_relu)) : (collect_mixed_capability ? (is_conv || is_relu) : (is_conv || is_log_softmax))); if (collect_for_fusion) { fused_pass1_survivors.push_back(node); continue; } if (unassignable_capability_node_index_.has_value() && !second_pass && is_log_softmax) { auto sub_graph = std::make_unique(); sub_graph->SetAccountant(resource_accountant); sub_graph->nodes.push_back(node->Index()); sub_graph->nodes.push_back(*unassignable_capability_node_index_); sub_graph->AppendNodeCost(resource_accountant->ComputeResourceCount( *node, GetNhwcAccountingTestEstimate(node->OpType()))); sub_graph->AppendNodeCost(ResourceCount{size_t{0}}); capabilities.push_back(std::make_unique(std::move(sub_graph))); continue; } std::unique_ptr capability; if (second_pass && is_conv && survivor_capability_mode_ == SurvivorCapabilityMode::kOptimizationOnly) { auto sub_graph = std::make_unique(); sub_graph->nodes.push_back(node_index); capability = std::make_unique(std::move(sub_graph)); auto optimization_sub_graph = std::make_unique(); optimization_sub_graph->nodes.push_back(node_index); auto optimization_capability = std::make_unique(std::move(optimization_sub_graph)); optimization_capability->optimization_func = [this](Graph&, const ComputeCapability&, ComputeCapability&, const GraphOptimizerRegistry&) { optimization_invoked_ = true; return Status::OK(); }; capability->nodes_to_optimize.push_back(std::move(optimization_capability)); } else { capability = utils::MakeComputeCapability(graph_viewer, std::vector{node}, generate_metadef_name, Type(), false); } // Mirror the in-tree CUDA EP: only newly claimed capabilities carry accounting // costs. Already-tagged second-pass survivors take the "previously assigned" // branch and carry no cost. if (resource_accountant != nullptr && !already_claimed) { capability->sub_graph->SetAccountant(resource_accountant); for (auto cost_node_index : capability->sub_graph->nodes) { const Node* cost_node = graph_viewer.GetNode(cost_node_index); const ResourceCount cost = resource_accountant->ComputeResourceCount( *cost_node, GetNhwcAccountingTestEstimate(cost_node->OpType())); const size_t cost_bytes = std::get(cost); if (consumed_memory > memory_threshold || cost_bytes > memory_threshold - consumed_memory) { resource_accountant->SetStopAssignment(); capability.reset(); break; } consumed_memory += cost_bytes; capability->sub_graph->AppendNodeCost(cost); } } if (capability != nullptr) { capabilities.push_back(std::move(capability)); } else { break; } } if (!fused_pass1_survivors.empty() && (resource_accountant == nullptr || !resource_accountant->IsStopIssued())) { auto capability = utils::MakeComputeCapability( graph_viewer, fused_pass1_survivors, generate_metadef_name, Type(), false); if (resource_accountant != nullptr) { capability->sub_graph->SetAccountant(resource_accountant); for (NodeIndex node_index : capability->sub_graph->nodes) { const Node* node = graph_viewer.GetNode(node_index); const ResourceCount cost = node != nullptr && node->GetExecutionProviderType().empty() ? resource_accountant->ComputeResourceCount( *node, GetNhwcAccountingTestEstimate(node->OpType())) : ResourceCount{size_t{0}}; const size_t cost_bytes = std::get(cost); if (consumed_memory > memory_threshold || cost_bytes > memory_threshold - consumed_memory) { resource_accountant->SetStopAssignment(); capability.reset(); break; } consumed_memory += cost_bytes; capability->sub_graph->AppendNodeCost(cost); } } if (capability != nullptr) { capabilities.push_back(std::move(capability)); } } return capabilities; } Status Compile(const std::vector& fused_nodes, std::vector& node_compute_funcs) override { for (size_t i = 0; i < fused_nodes.size(); ++i) { NodeComputeInfo compute_info; compute_info.create_state_func = [](ComputeContext*, FunctionState*) { return 0; }; compute_info.release_state_func = [](FunctionState) {}; compute_info.compute_func = [](FunctionState, const OrtApi*, OrtKernelContext*) { return Status::OK(); }; node_compute_funcs.push_back(std::move(compute_info)); } return Status::OK(); } IResourceAccountant* observed_accountant() const { return observed_accountant_; } std::optional last_observed_consumed() const { return last_observed_consumed_; } bool optimization_invoked() const { return optimization_invoked_; } private: mutable ModelMetadefIdGenerator metadef_id_generator_; mutable IResourceAccountant* observed_accountant_ = nullptr; mutable std::optional last_observed_consumed_; mutable bool optimization_invoked_ = false; std::optional unassignable_capability_node_index_; SurvivorCapabilityMode survivor_capability_mode_; std::optional second_pass_dropped_node_index_; std::optional accounted_overlap_dropped_node_index_; }; OrtStatus* ORT_API_CALL NoopEpContextWriteCallback(void*, const char*, const void*, size_t) { return nullptr; } OrtStatus* ORT_API_CALL NoopModelWriteCallback(void*, const void*, size_t) { return nullptr; } struct EpContextPreflightTestOptions { bool read_during_discovery = true; bool write_during_compile = false; bool has_context_node = true; int64_t input_embed_mode = 0; bool register_read_callback = true; bool register_write_callback = false; bool generate_context_model = false; bool output_embed_mode = true; uint32_t supported_flags = OrtEpContextDataCallbackSupportFlags_NONE; bool fail_support_query = false; }; struct EpContextPreflightTestState { size_t capability_calls = 0; size_t aot_capability_calls = 0; size_t compile_calls = 0; size_t support_queries = 0; size_t file_reads = 0; size_t file_writes = 0; size_t read_callbacks = 0; size_t write_callbacks = 0; }; OrtStatus* ORT_API_CALL PreflightReadCallback(void* state, const char*, OrtAllocator*, void** buffer, size_t* buffer_size) { ++static_cast(state)->read_callbacks; *buffer = nullptr; *buffer_size = 0; return nullptr; } OrtStatus* ORT_API_CALL PreflightWriteCallback(void* state, const char*, const void*, size_t) { ++static_cast(state)->write_callbacks; return nullptr; } class EpContextPreflightTestExecutionProvider : public InternalTestingExecutionProvider { public: EpContextPreflightTestExecutionProvider(const EpContextPreflightTestOptions& options, EpContextPreflightTestState& state, const std::filesystem::path& context_path) : InternalTestingExecutionProvider{{"EPContext", "Identity"}}, options_{options}, state_{state}, context_path_{context_path} {} uint32_t GetEpContextDataCallbackRequirements(const GraphViewer& graph_viewer) const override { uint32_t flags = options_.write_during_compile ? OrtEpContextDataCallbackSupportFlags_WRITE : OrtEpContextDataCallbackSupportFlags_NONE; if (ReadsExternalContext(graph_viewer)) { flags |= OrtEpContextDataCallbackSupportFlags_READ; } return flags; } Status GetEpContextDataCallbackSupport(uint32_t& supported_flags) const override { ++state_.support_queries; ORT_RETURN_IF(options_.fail_support_query, "EPContext test support query failed"); supported_flags = options_.supported_flags; return Status::OK(); } std::vector> GetCapability(const GraphViewer& graph_viewer, const IKernelLookup& kernel_lookup, const GraphOptimizerRegistry& optimizer_registry, IResourceAccountant* accountant) const override { ++state_.capability_calls; for (const auto& node : graph_viewer.Nodes()) { if (node.Domain() == "epcontext.preflight" && node.OpType() == "PreflightIdentity") { ++state_.aot_capability_calls; break; } } if (ReadsExternalContext(graph_viewer)) { if (options_.register_read_callback && (options_.supported_flags & OrtEpContextDataCallbackSupportFlags_READ) != 0) { Ort::AllocatorWithDefaultOptions allocator; void* buffer = nullptr; size_t buffer_size = 0; Ort::ThrowOnError(PreflightReadCallback(&state_, "context.bin", allocator, &buffer, &buffer_size)); } else { ++state_.file_reads; std::ifstream stream(context_path_, std::ios::binary); std::string contents; ORT_ENFORCE(std::getline(stream, contents) && contents == "test context", "Failed to read test context"); } } return InternalTestingExecutionProvider::GetCapability(graph_viewer, kernel_lookup, optimizer_registry, accountant); } Status Compile(const std::vector& fused_nodes, std::vector& node_compute_funcs) override { ++state_.compile_calls; if (options_.write_during_compile) { if (options_.register_write_callback && (options_.supported_flags & OrtEpContextDataCallbackSupportFlags_WRITE) != 0) { Ort::ThrowOnError(PreflightWriteCallback(&state_, "context.bin", "test context", 12)); } else { ++state_.file_writes; std::ofstream stream(context_path_, std::ios::binary); ORT_RETURN_IF_NOT(stream.write("test context", 12), "Failed to write test context"); } } return InternalTestingExecutionProvider::Compile(fused_nodes, node_compute_funcs); } private: bool ReadsExternalContext(const GraphViewer& graph_viewer) const { if (!options_.read_during_discovery) { return false; } for (const auto& node : graph_viewer.Nodes()) { if (node.Domain() == kMSDomain && node.OpType() == "EPContext") { const auto embed_mode = node.GetAttributes().find("embed_mode"); if (embed_mode != node.GetAttributes().end() && embed_mode->second.i() == 0) { return true; } } } return false; } const EpContextPreflightTestOptions options_; EpContextPreflightTestState& state_; const std::filesystem::path context_path_; }; Status PartitionDirectAssignmentExternalEpContext(bool produces_ep_context_nodes, bool read_callback_registered, bool write_callback_required, GraphPartitioner::Mode mode = GraphPartitioner::Mode::kNormal, bool* get_ep_context_nodes_called = nullptr, uint32_t ep_context_data_support = OrtEpContextDataCallbackSupportFlags_NONE, bool claims_ep_context_node = true, const DirectAssignmentEpContextTestOptions& options = {}) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model("PartitionDirectAssignmentExternalEpContext", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); const std::vector tensor_shape{1}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); auto& ep_context_node = builder.AddNode("EPContext", {input}, {output}, kMSDomain); if (options.embed_mode.has_value()) { ep_context_node.AddAttribute("embed_mode", *options.embed_mode); } ep_context_node.AddAttribute("ep_cache_context", "external_context.bin"); ep_context_node.AddAttribute("partition_name", "direct_assignment_partition"); ep_context_node.AddAttribute("source", "DirectAssignmentEpContextTestExecutionProvider"); if (options.assigned_to_other_ep) { ep_context_node.SetExecutionProviderType(kCpuExecutionProvider); } builder.SetGraphOutputs(); ORT_RETURN_IF_ERROR(graph.Resolve()); ExecutionProviders execution_providers; auto& default_logger = DefaultLoggingManager().DefaultLogger(); auto ep = std::make_unique( produces_ep_context_nodes, get_ep_context_nodes_called, ep_context_data_support, claims_ep_context_node, options); const auto* ep_raw = ep.get(); ep->SetLogger(&default_logger); const std::string ep_type = ep->Type(); ORT_RETURN_IF_ERROR(execution_providers.Add(ep_type, std::move(ep))); ConfigOptions config_options; if (options.enable_resource_accountant) { ORT_RETURN_IF_ERROR(config_options.AddConfigEntry(kOrtSessionOptionsResourceCudaPartitioningSettings, "1048576,")); } KernelRegistryManager krm; ORT_RETURN_IF_ERROR(krm.RegisterKernels(execution_providers)); auto graph_optimizer_registry = std::make_unique( nullptr /*session_options*/, nullptr /*cpu_ep*/, &default_logger); GraphPartitioner partitioner(krm, execution_providers, std::move(graph_optimizer_registry), []() -> bool { return false; }); layout_transformation::TransformLayoutFunction transform_layout_fn = [](Graph&, bool& modified, const IExecutionProvider&, const layout_transformation::DebugGraphFn&) -> Status { modified = false; return Status::OK(); }; epctx::ModelGenOptions model_gen_options; if (write_callback_required) { model_gen_options.enable = true; model_gen_options.embed_ep_context_in_model = options.output_embed_mode; model_gen_options.ep_context_data_write_func = {NoopEpContextWriteCallback, nullptr}; model_gen_options.output_model_location = epctx::BufferWriteFuncHolder{NoopModelWriteCallback, nullptr}; } FuncManager func_mgr; const auto status = partitioner.Partition(graph, func_mgr, transform_layout_fn, config_options, default_logger, nullptr /*layering_index*/, mode, model_gen_options, read_callback_registered); if (options.preferred_layout == DataLayout::NHWC && mode != GraphPartitioner::Mode::kAssignOnly && claims_ep_context_node && !write_callback_required) { EXPECT_EQ(ep_raw->get_capability_call_count(), options.enable_resource_accountant ? 3u : 2u); const std::string expected_ep_type = options.assigned_to_other_ep ? kCpuExecutionProvider : (options.drop_after_layout ? std::string{} : ep_type); EXPECT_EQ(ep_context_node.GetExecutionProviderType(), expected_ep_type); const bool read_support_required = read_callback_registered && options.embed_mode == 0 && !options.drop_after_layout && !options.assigned_to_other_ep; EXPECT_EQ(ep_raw->support_query_count(), read_support_required ? 1u : 0u); if (options.enable_resource_accountant && !options.assigned_to_other_ep) { EXPECT_EQ(ep_raw->last_capability_count(), 0u); } } return status; } } // namespace #define ORT_MODEL_FOLDER ORT_TSTR("testdata/") #if !defined(DISABLE_CONTRIB_OPS) TEST(InternalTestingEP, StaticKernelEpGraphAssignmentInfoAfterFunctionInlining) { class OnnxOnlyStaticExecutionProvider : public InternalTestingExecutionProvider { public: explicit OnnxOnlyStaticExecutionProvider(DataLayout layout) : InternalTestingExecutionProvider({}, {}, layout) { EnableStaticKernels().TakeAllNodes(); } std::vector> GetCapability( const GraphViewer& graph_viewer, const IKernelLookup& kernel_lookup, const GraphOptimizerRegistry& optimizer_registry, IResourceAccountant* accountant) const override { auto capabilities = InternalTestingExecutionProvider::GetCapability( graph_viewer, kernel_lookup, optimizer_registry, accountant); capabilities.erase(std::remove_if(capabilities.begin(), capabilities.end(), [&](const auto& capability) { return graph_viewer.GetNode(capability->sub_graph->nodes[0])->Domain() != kOnnxDomain; }), capabilities.end()); return capabilities; } }; FunctionProto function; function.set_domain("local"); function.set_name("IdentityFunction"); function.add_input("X"); function.add_output("Y"); function.add_opset_import()->set_version(13); auto* body = function.add_node(); body->set_op_type("Identity"); body->add_input("X"); body->add_output("Y"); // AOT inlining covers one partitioning round; fallback inlining must not re-report the assigned Add. for (DataLayout layout : {DataLayout::NCHW, DataLayout::NHWC}) { for (bool disable_aot : {false, true}) { SCOPED_TRACE(layout == DataLayout::NHWC ? "NHWC" : "NCHW"); SCOPED_TRACE(disable_aot ? "Fallback inlining" : "AOT inlining"); Model model("StaticKernelEpGraphAssignmentInfoAfterFunctionInlining", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), {{kOnnxDomain, 13}, {"local", 1}}, {function}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); auto* input_a = builder.MakeInput(std::vector{3}); auto* input_b = builder.MakeInput(std::vector{3}); auto* intermediate = builder.MakeIntermediate(std::vector{3}); auto* output = builder.MakeOutput(std::vector{3}); const std::string add_name = builder.AddNode("Add", {input_a, input_b}, {intermediate}).Name(); builder.AddNode("IdentityFunction", {intermediate}, {output}, "local"); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); SessionOptions options; options.graph_optimization_level = TransformerLevel::Default; ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsRecordEpGraphAssignmentInfo, "1")); ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsDisableCPUEPFallback, "1")); ASSERT_STATUS_OK(options.config_options.AddConfigEntry( kOrtSessionOptionsDisableAheadOfTimeFunctionInlining, disable_aot ? "1" : "0")); InferenceSessionWrapper session(options, GetEnvironment()); ASSERT_STATUS_OK(session.RegisterExecutionProvider(std::make_unique(layout))); const std::string model_bytes = model.ToProto().SerializeAsString(); ASSERT_STATUS_OK(session.Load(model_bytes.data(), static_cast(model_bytes.size()))); ASSERT_STATUS_OK(session.Initialize()); const auto& subgraphs = session.GetEpGraphAssignmentInfo(); ASSERT_EQ(subgraphs.size(), 2u); InlinedVector assigned_ops; for (const auto* subgraph : subgraphs) { EXPECT_EQ(subgraph->ep_name, kInternalTestingExecutionProvider); ASSERT_EQ(subgraph->nodes.size(), 1u); const auto* node = subgraph->nodes[0]; EXPECT_EQ(node->domain, kOnnxDomain); assigned_ops.push_back(node->op_type); if (node->op_type == "Add") { EXPECT_EQ(node->name, add_name); } } EXPECT_THAT(assigned_ops, testing::UnorderedElementsAre("Add", "Identity")); } } } TEST(InternalTestingEP, NhwcTransformedStaticKernelEpGraphAssignmentInfo) { Model model("NhwcTransformedStaticKernelEpGraphAssignmentInfo", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), {{kOnnxDomain, 13}}, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); auto* input = builder.MakeInput(std::vector{1, 1, 3, 3}); auto* weights = builder.MakeInitializer(std::vector{1, 1, 1, 1}, std::vector{1.0f}); auto* output = builder.MakeOutput(std::vector{1, 1, 3, 3}); builder.AddConvNode(input, weights, output); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); SessionOptions options; options.graph_optimization_level = TransformerLevel::Default; ASSERT_STATUS_OK(options.config_options.AddConfigEntry(kOrtSessionOptionsRecordEpGraphAssignmentInfo, "1")); InferenceSessionWrapper session(options, GetEnvironment()); auto ep = std::make_unique( std::unordered_set{"Conv"}, std::unordered_set{}, DataLayout::NHWC); ep->EnableStaticKernels(); ASSERT_STATUS_OK(session.RegisterExecutionProvider(std::move(ep))); const std::string model_bytes = model.ToProto().SerializeAsString(); ASSERT_STATUS_OK(session.Load(model_bytes.data(), static_cast(model_bytes.size()))); ASSERT_STATUS_OK(session.Initialize()); size_t conv_count = 0; for (const auto* subgraph : session.GetEpGraphAssignmentInfo()) { for (const auto* node : subgraph->nodes) { if (node->op_type == "Conv") { ++conv_count; EXPECT_EQ(subgraph->ep_name, kInternalTestingExecutionProvider); EXPECT_EQ(node->domain, kMSInternalNHWCDomain); } } } EXPECT_EQ(conv_count, 1u); } #endif // !defined(DISABLE_CONTRIB_OPS) auto RunTest(const std::string& op, const ORTCHAR_T* model_path) { SessionOptions so; auto session = std::make_unique(so, GetEnvironment()); const std::unordered_set supported_ops{op}; ASSERT_STATUS_OK(session->RegisterExecutionProvider( std::make_unique(supported_ops))); ASSERT_STATUS_OK(session->Load(model_path)); const auto& graph = session->GetGraph(); GraphViewer viewer{graph}; ASSERT_STATUS_OK(session->Initialize()); auto& func_mgr = const_cast(session->GetSessionState()).GetMutableFuncMgr(); const NodeComputeInfo* compute_func = nullptr; int num_partitions{0}, num_other_nodes{0}; for (const auto& node : graph.Nodes()) { EXPECT_EQ(supported_ops.count(node.OpType()), size_t(0)) << "Nodes with supported op types should have been replaced. Node with type " << node.OpType() << " was not."; if (node.GetExecutionProviderType() == kInternalTestingExecutionProvider) { EXPECT_STATUS_OK(func_mgr.GetFuncs(node.Name(), compute_func)); EXPECT_NE(compute_func, nullptr); ++num_partitions; } else { ++num_other_nodes; } } ASSERT_EQ(num_partitions, 1) << "Partition aware topological sort should have resulted in a single partition." << " Op=" << op << " Partitions=" << num_partitions << " OtherNodes=" << num_other_nodes; }; // model has an unsupported node between the supported nodes after the initial topo sort. // the partition aware topo sort should result in the unsupported node moving to earlier in the order, // and allow a single partition of supported nodes to be created. TEST(InternalTestingEP, TestSortResultsInSinglePartition) { // see testdata/ep_partitioning_tests.py for model description // There should be only one partition, regardless of whether Add or Sub is supported by the EP. const ORTCHAR_T* model_path = ORT_TSTR("testdata/ep_partitioning_test_1.onnx"); RunTest("Add", model_path); RunTest("Sub", model_path); } // mode has Resize op with optional input roi which is just a placeholder. // partition function should skip the placeholder inputs. TEST(InternalTestingEP, TestResizeWithOptionalInput) { // Resize op has optional input roi which is just a placeholder const ORTCHAR_T* model_path = ORT_TSTR("testdata/model_resize_empty_optional_input.onnx"); RunTest("Resize", model_path); } // Test that when doing the partition aware sort and selecting groups that input dependencies are correctly handled TEST(InternalTestingEP, TestDependenciesCorrectlyHandled) { SessionOptions so; auto session = std::make_unique(so, GetEnvironment()); const std::unordered_set supported_ops{"Add"}; ASSERT_STATUS_OK(session->RegisterExecutionProvider( std::make_unique(supported_ops))); const ORTCHAR_T* model_path = ORT_MODEL_FOLDER "ep_partitioning_test_2.onnx"; ASSERT_STATUS_OK(session->Load(model_path)); const auto& graph = session->GetGraph(); GraphViewer viewer{graph}; ASSERT_STATUS_OK(session->Initialize()); // this should fail if we don't process dependencies correctly auto& func_mgr = const_cast(session->GetSessionState()).GetMutableFuncMgr(); const NodeComputeInfo* compute_func = nullptr; int num_partitions{0}; int num_other_nodes{0}; for (const auto& node : graph.Nodes()) { EXPECT_EQ(supported_ops.count(node.OpType()), size_t(0)) << "Nodes with supported op types should have been replaced. Node with type " << node.OpType() << " was not."; if (node.GetExecutionProviderType() == kInternalTestingExecutionProvider) { EXPECT_STATUS_OK(func_mgr.GetFuncs(node.Name(), compute_func)); EXPECT_NE(compute_func, nullptr); ++num_partitions; } else { ++num_other_nodes; } } ASSERT_EQ(num_partitions, 2); ASSERT_EQ(num_other_nodes, 2); } TEST(InternalTestingEP, NhwcSecondPassDropFallsBackFromCpuKernelNode) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model("NhwcSecondPassDropFallsBackFromCpuKernelNode", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); const std::vector tensor_shape{1, 1, 3, 3}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* weights = builder.MakeInitializer(std::vector{1, 1, 1, 1}, std::vector{1.0f}); auto* conv_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); builder.AddConvNode(input, weights, conv_output); builder.AddNode("LogSoftmax", std::vector{conv_output}, std::vector{output}); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); std::string model_data; ASSERT_TRUE(model.ToProto().SerializeToString(&model_data)); SessionOptions so; auto session = std::make_unique(so, GetEnvironment()); ASSERT_STATUS_OK(session->RegisterExecutionProvider(std::make_unique())); ASSERT_STATUS_OK(session->Load(model_data.data(), static_cast(model_data.size()))); ASSERT_STATUS_OK(session->Initialize()); bool saw_log_softmax = false; int num_ep_nodes = 0; for (const auto& node : session->GetGraph().Nodes()) { if (node.GetExecutionProviderType() == "TwoPassNhwcTestExecutionProvider") { ++num_ep_nodes; } if (node.OpType() == "LogSoftmax") { saw_log_softmax = true; EXPECT_NE(node.GetExecutionProviderType(), "TwoPassNhwcTestExecutionProvider"); } } EXPECT_GT(num_ep_nodes, 0); EXPECT_TRUE(saw_log_softmax); } TEST(InternalTestingEP, ExternalEpContextReadCallbackRequiresSupportForDirectAssignment) { const auto status = PartitionDirectAssignmentExternalEpContext( false /*produces_ep_context_nodes*/, true /*read_callback_registered*/, false /*write_callback_required*/); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data read callback")); } TEST(InternalTestingEP, ExternalEpContextWriteCallbackRequiresSupportForNonCompileProducer) { bool get_ep_context_nodes_called = false; const auto status = PartitionDirectAssignmentExternalEpContext( true /*produces_ep_context_nodes*/, false /*read_callback_registered*/, true /*write_callback_required*/, GraphPartitioner::Mode::kNormal, &get_ep_context_nodes_called); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data write callback")); EXPECT_FALSE(get_ep_context_nodes_called); } TEST(InternalTestingEP, ExternalEpContextWriteCallbackRequiresSupportForProducerWithoutCapabilities) { bool get_ep_context_nodes_called = false; const auto status = PartitionDirectAssignmentExternalEpContext( true /*produces_ep_context_nodes*/, false /*read_callback_registered*/, true /*write_callback_required*/, GraphPartitioner::Mode::kNormal, &get_ep_context_nodes_called, OrtEpContextDataCallbackSupportFlags_NONE, false /*claims_ep_context_node*/); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data write callback")); EXPECT_FALSE(get_ep_context_nodes_called); } TEST(InternalTestingEP, ExternalEpContextWriteCallbackAllowsDirectAssignmentWithoutProducedContext) { const auto status = PartitionDirectAssignmentExternalEpContext( false /*produces_ep_context_nodes*/, false /*read_callback_registered*/, true /*write_callback_required*/); EXPECT_STATUS_OK(status); } TEST(InternalTestingEP, ExternalEpContextWriteCallbackAllowsSupportedNonCompileProducer) { bool get_ep_context_nodes_called = false; const auto status = PartitionDirectAssignmentExternalEpContext( true /*produces_ep_context_nodes*/, false /*read_callback_registered*/, true /*write_callback_required*/, GraphPartitioner::Mode::kNormal, &get_ep_context_nodes_called, OrtEpContextDataCallbackSupportFlags_WRITE); EXPECT_STATUS_OK(status); EXPECT_TRUE(get_ep_context_nodes_called); } TEST(InternalTestingEP, ExternalEpContextNonCompileProducerOverridesCoreEmbedMode) { bool get_ep_context_nodes_called = false; DirectAssignmentEpContextTestOptions options; options.output_embed_mode = true; const auto status = PartitionDirectAssignmentExternalEpContext( true /*produces_ep_context_nodes*/, false /*read_callback_registered*/, true /*write_callback_required*/, GraphPartitioner::Mode::kNormal, &get_ep_context_nodes_called, OrtEpContextDataCallbackSupportFlags_NONE, true /*claims_ep_context_node*/, options); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data write callback")); EXPECT_FALSE(get_ep_context_nodes_called); } enum class EpContextDiscoveryStage { Onnx, OrtFormat, Aot }; class EpContextCallbackPreflightTest : public testing::TestWithParam { protected: void ConfigureWriter() { options_.read_during_discovery = false; options_.write_during_compile = true; options_.has_context_node = false; options_.register_read_callback = false; options_.register_write_callback = true; options_.generate_context_model = true; } Status Partition() { state_ = {}; const auto context_path = std::filesystem::path(temp_dir_.Path()) / "context.bin"; if (options_.has_context_node) { std::ofstream stream(context_path, std::ios::binary); ORT_RETURN_IF_NOT(stream.write("test context", 12), "Failed to create test context"); } auto& logger = DefaultLoggingManager().DefaultLogger(); const bool aot = GetParam() == EpContextDiscoveryStage::Aot; std::unordered_map domain_versions{{kOnnxDomain, 13}, {kMSDomain, 1}, {"epcontext.preflight", 1}}; std::vector functions; if (aot) { FunctionProto function; function.set_name("PreflightIdentity"); function.set_domain("epcontext.preflight"); function.add_input("X"); function.add_output("Y"); function.add_opset_import()->set_version(13); auto* node = function.add_node(); node->set_op_type("Identity"); node->add_input("X"); node->add_output("Y"); functions.push_back(std::move(function)); } Model model("EpContextCallbackPreflight", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_versions, functions, logger); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); const std::optional> shape{std::vector{1}}; auto* input = builder.MakeInput(shape); auto* output = builder.MakeOutput(shape); auto* primary_output = aot ? builder.MakeIntermediate(shape) : output; if (options_.has_context_node) { auto& node = builder.AddNode("EPContext", {input}, {primary_output}, kMSDomain); node.AddAttribute("embed_mode", options_.input_embed_mode); node.AddAttribute("ep_cache_context", "context.bin"); node.AddAttribute("partition_name", "preflight_partition"); node.AddAttribute("source", kInternalTestingExecutionProvider); } else { builder.AddNode("Identity", {input}, {primary_output}); } if (aot) { builder.AddNode("PreflightIdentity", {primary_output}, {output}, "epcontext.preflight"); } builder.SetGraphOutputs(); ORT_RETURN_IF_ERROR(graph.Resolve()); auto ep = std::make_unique(options_, state_, context_path); ep->SetLogger(&logger); epctx::ModelGenOptions model_gen_options; model_gen_options.enable = options_.generate_context_model; model_gen_options.embed_ep_context_in_model = options_.output_embed_mode; model_gen_options.output_model_location = epctx::BufferWriteFuncHolder{NoopModelWriteCallback, nullptr}; if (options_.register_write_callback) { model_gen_options.ep_context_data_write_func = {PreflightWriteCallback, &state_}; } if (aot) { SessionOptions session_options; session_options.graph_optimization_level = TransformerLevel::Default; session_options.ep_context_gen_options = model_gen_options; if (options_.register_read_callback) { session_options.ep_context_data_read_func = PreflightReadCallback; session_options.ep_context_data_read_state = &state_; } InferenceSessionWrapper session(session_options, GetEnvironment()); ORT_RETURN_IF_ERROR(session.RegisterExecutionProvider(std::move(ep))); std::string model_data; ORT_RETURN_IF_NOT(model.ToProto().SerializeToString(&model_data), "Failed to serialize test model"); ORT_RETURN_IF_ERROR(session.Load(model_data.data(), static_cast(model_data.size()))); const auto status = session.Initialize(); if (status.IsOK()) { EXPECT_GT(state_.aot_capability_calls, 0u); } return status; } ExecutionProviders providers; const std::string ep_type = ep->Type(); ORT_RETURN_IF_ERROR(providers.Add(ep_type, std::move(ep))); KernelRegistryManager krm; ORT_RETURN_IF_ERROR(krm.RegisterKernels(providers)); auto optimizer_registry = std::make_unique(nullptr, nullptr, &logger); GraphPartitioner partitioner(krm, providers, std::move(optimizer_registry), [] { return false; }); FuncManager func_mgr; const auto mode = GetParam() == EpContextDiscoveryStage::OrtFormat ? GraphPartitioner::Mode::kOrtFormatLoad : GraphPartitioner::Mode::kNormal; return partitioner.Partition(graph, func_mgr, {}, ConfigOptions{}, logger, nullptr, mode, model_gen_options, options_.register_read_callback); } EpContextPreflightTestOptions options_; EpContextPreflightTestState state_; TemporaryDirectory temp_dir_{ORT_TSTR("ep_context_callback_preflight_test"), false}; }; TEST_P(EpContextCallbackPreflightTest, RejectsReadBeforeCapabilityIo) { for (uint32_t support : {OrtEpContextDataCallbackSupportFlags_NONE, OrtEpContextDataCallbackSupportFlags_WRITE}) { SCOPED_TRACE(support); options_.supported_flags = support; const auto status = Partition(); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data read callback")); EXPECT_EQ(state_.capability_calls, 0u); EXPECT_EQ(state_.file_reads, 0u); EXPECT_EQ(state_.compile_calls, 0u); } } TEST_P(EpContextCallbackPreflightTest, SupportQueryFailurePreventsCapabilityIo) { options_.fail_support_query = true; const auto status = Partition(); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("EPContext test support query failed")); EXPECT_EQ(state_.capability_calls, 0u); EXPECT_EQ(state_.file_reads, 0u); } TEST_P(EpContextCallbackPreflightTest, AdvertisedReadSupportAllowsDiscovery) { options_.supported_flags = OrtEpContextDataCallbackSupportFlags_READ; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.capability_calls, 0u); EXPECT_GT(state_.read_callbacks, 0u); EXPECT_EQ(state_.file_reads, 0u); } TEST_P(EpContextCallbackPreflightTest, NoReadCallbackPreservesLegacyReads) { options_.register_read_callback = false; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.file_reads, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, WriteCallbackDoesNotRequireReadSupport) { options_.register_read_callback = false; options_.register_write_callback = true; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.file_reads, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, EmbeddedContextDoesNotRequireReadSupport) { options_.input_embed_mode = 1; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.capability_calls, 0u); EXPECT_EQ(state_.file_reads, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, OrdinaryGraphDoesNotRequireReadSupport) { options_.has_context_node = false; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.capability_calls, 0u); EXPECT_EQ(state_.file_reads, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, ProviderExternalModeOverridesCoreEmbedMode) { ConfigureWriter(); for (uint32_t support : {OrtEpContextDataCallbackSupportFlags_NONE, OrtEpContextDataCallbackSupportFlags_READ}) { SCOPED_TRACE(support); options_.supported_flags = support; const auto status = Partition(); EXPECT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data write callback")); EXPECT_EQ(state_.capability_calls, 0u); EXPECT_EQ(state_.compile_calls, 0u); EXPECT_EQ(state_.file_writes, 0u); EXPECT_FALSE(std::filesystem::exists(std::filesystem::path(temp_dir_.Path()) / "context.bin")); } } TEST_P(EpContextCallbackPreflightTest, AdvertisedWriteSupportAllowsProviderExternalMode) { ConfigureWriter(); options_.supported_flags = OrtEpContextDataCallbackSupportFlags_WRITE; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.compile_calls, 0u); EXPECT_GT(state_.write_callbacks, 0u); EXPECT_EQ(state_.file_writes, 0u); } TEST_P(EpContextCallbackPreflightTest, NoWriteCallbackPreservesProviderExternalMode) { ConfigureWriter(); options_.register_write_callback = false; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.file_writes, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, ReadCallbackDoesNotRequireWriteSupport) { ConfigureWriter(); options_.register_write_callback = false; options_.register_read_callback = true; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.file_writes, 0u); EXPECT_EQ(state_.support_queries, 0u); } TEST_P(EpContextCallbackPreflightTest, EmbeddedProviderOutputDoesNotRequireWriteSupport) { ConfigureWriter(); options_.write_during_compile = false; EXPECT_STATUS_OK(Partition()); EXPECT_GT(state_.compile_calls, 0u); EXPECT_EQ(state_.file_writes, 0u); EXPECT_EQ(state_.write_callbacks, 0u); EXPECT_EQ(state_.support_queries, 0u); } INSTANTIATE_TEST_SUITE_P( Discovery, EpContextCallbackPreflightTest, testing::Values(EpContextDiscoveryStage::Onnx, EpContextDiscoveryStage::OrtFormat, EpContextDiscoveryStage::Aot), [](const testing::TestParamInfo& info) { switch (info.param) { case EpContextDiscoveryStage::Onnx: return "Onnx"; case EpContextDiscoveryStage::OrtFormat: return "OrtFormat"; case EpContextDiscoveryStage::Aot: return "Aot"; } ORT_THROW("Unexpected discovery stage"); }); TEST(InternalTestingEP, OrtFormatExternalEpContextReadCallbackRequiresSupportForDirectAssignment) { const auto status = PartitionDirectAssignmentExternalEpContext( false /*produces_ep_context_nodes*/, true /*read_callback_registered*/, false /*write_callback_required*/, GraphPartitioner::Mode::kOrtFormatLoad); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data read callback")); } class NhwcEpContextReadCallbackTest : public testing::TestWithParam> { protected: void SetUp() override { options_.preferred_layout = DataLayout::NHWC; options_.enable_resource_accountant = std::get<1>(GetParam()); } Status Partition(uint32_t support = OrtEpContextDataCallbackSupportFlags_NONE, bool read_callback_registered = true) { return PartitionDirectAssignmentExternalEpContext( false /*produces_ep_context_nodes*/, read_callback_registered, false /*write_callback_required*/, std::get<0>(GetParam()), nullptr /*get_ep_context_nodes_called*/, support, true /*claims_ep_context_node*/, options_); } DirectAssignmentEpContextTestOptions options_; }; TEST_P(NhwcEpContextReadCallbackTest, RetainedExternalContextRequiresReadSupport) { for (uint32_t support : {OrtEpContextDataCallbackSupportFlags_NONE, OrtEpContextDataCallbackSupportFlags_WRITE}) { SCOPED_TRACE(support); const auto status = Partition(support); ASSERT_FALSE(status.IsOK()); EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("does not support the registered EPContext data read callback")); } } TEST_P(NhwcEpContextReadCallbackTest, RetainedExternalContextAcceptsReadSupport) { EXPECT_STATUS_OK(Partition(OrtEpContextDataCallbackSupportFlags_READ)); } TEST_P(NhwcEpContextReadCallbackTest, NoReadCallbackDoesNotRequireSupport) { EXPECT_STATUS_OK(Partition(OrtEpContextDataCallbackSupportFlags_NONE, false /*read_callback_registered*/)); } TEST_P(NhwcEpContextReadCallbackTest, EmbeddedContextDoesNotRequireReadSupport) { options_.embed_mode = 1; EXPECT_STATUS_OK(Partition()); } TEST_P(NhwcEpContextReadCallbackTest, DefaultEmbedModeDoesNotRequireReadSupport) { options_.embed_mode = std::nullopt; EXPECT_STATUS_OK(Partition()); } TEST_P(NhwcEpContextReadCallbackTest, DroppedTentativeContextDoesNotRequireReadSupport) { options_.drop_after_layout = true; EXPECT_STATUS_OK(Partition()); } TEST_P(NhwcEpContextReadCallbackTest, OtherProviderContextDoesNotRequireReadSupport) { options_.assigned_to_other_ep = true; EXPECT_STATUS_OK(Partition()); } INSTANTIATE_TEST_SUITE_P( Partitioning, NhwcEpContextReadCallbackTest, testing::Values(std::make_tuple(GraphPartitioner::Mode::kNormal, false), std::make_tuple(GraphPartitioner::Mode::kOrtFormatLoad, false), std::make_tuple(GraphPartitioner::Mode::kNormal, true)), [](const testing::TestParamInfo& info) { if (std::get<1>(info.param)) { return "OnnxWithAccounting"; } return std::get<0>(info.param) == GraphPartitioner::Mode::kNormal ? "Onnx" : "OrtFormat"; }); // Validates that the resource accountant is updated correctly across the NHWC two-pass // partitioning flow: a node tentatively claimed on the first pass but dropped on the // second pass must NOT consume budget (no phantom), while a node that survives must be // committed exactly once (no double-count). A dropped pass-1 node must be rolled back before // final admission so it cannot block a pass-2-only node that fits with the actual survivors. void RunNhwcTwoPassAccountingRetryTest(bool pass2_node_precedes_survivor, SurvivorCapabilityMode survivor_capability_mode = SurvivorCapabilityMode::kSeparate) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model(pass2_node_precedes_survivor ? "NhwcTwoPassAccountingPreservesLaterSurvivorReservation" : "NhwcTwoPassAccountingRetriesAdmissionAfterDroppedCostRollback", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); const std::vector tensor_shape{1, 1, 3, 3}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* weights = builder.MakeInitializer(std::vector{1, 1, 1, 1}, std::vector{1.0f}); auto* conv_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* relu_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); if (pass2_node_precedes_survivor) { builder.AddNode("Relu", std::vector{input}, std::vector{relu_output}); builder.AddConvNode(relu_output, weights, conv_output); } else { builder.AddConvNode(input, weights, conv_output); builder.AddNode("Relu", std::vector{conv_output}, std::vector{relu_output}); } if (pass2_node_precedes_survivor) { builder.AddNode("LogSoftmax", std::vector{conv_output}, std::vector{output}); } else { builder.AddNode("LogSoftmax", std::vector{relu_output}, std::vector{output}); } builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); // Helper to read the size_t held by a ResourceCount. auto get_size = [](const ResourceCount& rc) -> size_t { const auto* value = std::get_if(&rc); EXPECT_NE(value, nullptr) << "ResourceCount does not hold size_t"; return value != nullptr ? *value : 0; }; // Build a fresh ad-hoc accountant (no stats file) via the real factory. auto make_accountant = [](std::optional& acc_map) -> IResourceAccountant* { ConfigOptions config; // Large memory limit so reference costs are always available; empty stats file => ad-hoc mode. EXPECT_STATUS_OK(config.AddConfigEntry(kOrtSessionOptionsResourceCudaPartitioningSettings, "1048576,")); EXPECT_STATUS_OK(CreateAccountants(config, PathString(), acc_map)); EXPECT_TRUE(acc_map.has_value()); auto it = acc_map->find(kCudaExecutionProvider); return it != acc_map->end() ? it->second.get() : nullptr; }; // Reference per-node costs computed independently on fresh accountants. const Node* conv_node = nullptr; const Node* relu_node = nullptr; const Node* log_softmax_node = nullptr; for (const auto& node : graph.Nodes()) { if (node.OpType() == "Conv") { conv_node = &node; } else if (node.OpType() == "Relu") { relu_node = &node; } else if (node.OpType() == "LogSoftmax") { log_softmax_node = &node; } } ASSERT_NE(conv_node, nullptr); ASSERT_NE(relu_node, nullptr); ASSERT_NE(log_softmax_node, nullptr); const NodeIndex relu_node_index = relu_node->Index(); const NodeIndex log_softmax_node_index = log_softmax_node->Index(); std::optional ref_conv_map; std::optional ref_relu_map; std::optional ref_ls_map; IResourceAccountant* ref_conv_acc = make_accountant(ref_conv_map); IResourceAccountant* ref_relu_acc = make_accountant(ref_relu_map); IResourceAccountant* ref_ls_acc = make_accountant(ref_ls_map); ASSERT_NE(ref_conv_acc, nullptr); ASSERT_NE(ref_relu_acc, nullptr); ASSERT_NE(ref_ls_acc, nullptr); const Level1MemoryEstimate conv_estimate = GetNhwcAccountingTestEstimate("Conv"); const Level1MemoryEstimate relu_estimate = GetNhwcAccountingTestEstimate("Relu"); const Level1MemoryEstimate log_softmax_estimate = GetNhwcAccountingTestEstimate("LogSoftmax"); const size_t expected_conv_cost = get_size(ref_conv_acc->ComputeResourceCount(*conv_node, conv_estimate)); const size_t expected_relu_cost = get_size(ref_relu_acc->ComputeResourceCount(*relu_node, relu_estimate)); const size_t expected_log_softmax_cost = get_size(ref_ls_acc->ComputeResourceCount(*log_softmax_node, log_softmax_estimate)); ASSERT_GT(expected_conv_cost, 0u); ASSERT_GT(expected_relu_cost, 0u); ASSERT_GT(expected_log_softmax_cost, 0u); const size_t budget_bytes = (pass2_node_precedes_survivor ? 1000 : 1075) * 1024; ASSERT_LT(expected_conv_cost + expected_log_softmax_cost, budget_bytes); const bool log_softmax_survives = survivor_capability_mode == SurvivorCapabilityMode::kFused || survivor_capability_mode == SurvivorCapabilityMode::kPartialOverlap || survivor_capability_mode == SurvivorCapabilityMode::kSplitCoverage || (survivor_capability_mode == SurvivorCapabilityMode::kAccountedMixedOverlap && pass2_node_precedes_survivor); const bool expect_relu_rejected = pass2_node_precedes_survivor || survivor_capability_mode == SurvivorCapabilityMode::kPartialOverlap || survivor_capability_mode == SurvivorCapabilityMode::kSplitCoverage; if (expect_relu_rejected) { const size_t survivor_cost = expected_conv_cost + (log_softmax_survives ? expected_log_softmax_cost : 0); ASSERT_GT(survivor_cost + expected_relu_cost, budget_bytes); } else { ASSERT_LT(expected_conv_cost + expected_relu_cost, budget_bytes); ASSERT_GT(expected_conv_cost + expected_log_softmax_cost + expected_relu_cost, budget_bytes); } // Drive partitioning directly with the accounting-aware NHWC EP. The accountant is // created internally by GraphPartitioner from the config option below (keyed to // kCudaExecutionProvider, which matches the EP's type). ExecutionProviders execution_providers; auto& default_logger = DefaultLoggingManager().DefaultLogger(); auto ep = std::make_unique( std::nullopt, survivor_capability_mode); auto* ep_raw = ep.get(); ep->SetLogger(&default_logger); ASSERT_STATUS_OK(execution_providers.Add(kCudaExecutionProvider, std::move(ep))); KernelRegistryManager krm; ASSERT_STATUS_OK(krm.RegisterKernels(execution_providers)); SessionOptions sess_options; const std::string partitioning_settings = std::to_string(budget_bytes / 1024) + ","; ASSERT_STATUS_OK(sess_options.config_options.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, partitioning_settings.c_str())); // The assignment callback runs before the current capability's cost is committed. // Capture the already-committed survivor state when the pass-2-only Relu is assigned. std::optional observed_consumed; std::optional observed_workspace; std::optional observed_persistent_prepack; std::optional observed_initialization_scratch; std::optional observed_source_counts; bool pass2_only_relu_assigned = false; bool conv_survivor_capability_assigned = false; bool fused_pass1_survivors_assigned = false; bool mixed_survivor_capability_assigned = false; size_t mixed_survivor_capability_cost = 0; std::optional mixed_consumed_before_assignment; OnPartitionAssignmentFunction on_assignment = [&](const Graph& assignment_graph, const ComputeCapability& capability, const std::string& assigned_ep_type) { if (assigned_ep_type == kCudaExecutionProvider && ep_raw->observed_accountant() != nullptr) { size_t survivor_count = 0; bool capability_has_relu = false; bool capability_has_conv = false; for (NodeIndex node_index : capability.sub_graph->nodes) { const Node* assigned_node = assignment_graph.GetNode(node_index); if (assigned_node != nullptr && assigned_node->OpType() == "Relu") { capability_has_relu = true; pass2_only_relu_assigned = true; observed_consumed = get_size(ep_raw->observed_accountant()->GetConsumedAmount()); observed_workspace = ep_raw->observed_accountant()->GetCommittedWorkspaceEstimate(); observed_persistent_prepack = ep_raw->observed_accountant()->GetCommittedPersistentPrepackEstimate(); observed_initialization_scratch = ep_raw->observed_accountant()->GetCommittedInitializationScratchEstimate(); observed_source_counts = ep_raw->observed_accountant()->GetWorkspaceEstimateSourceCounts(); } if (assigned_node != nullptr && (assigned_node->OpType() == "Conv" || assigned_node->OpType() == "LogSoftmax")) { ++survivor_count; } if (assigned_node != nullptr && assigned_node->OpType() == "Conv") { capability_has_conv = true; conv_survivor_capability_assigned = true; } } if (survivor_count == 2) { fused_pass1_survivors_assigned = true; } if (capability.sub_graph->nodes.size() == 2 && capability_has_relu && capability_has_conv) { mixed_survivor_capability_assigned = true; if (!mixed_consumed_before_assignment.has_value()) { mixed_consumed_before_assignment = get_size(ep_raw->observed_accountant()->GetConsumedAmount()); } if (capability.sub_graph->IsAccountingEnabled()) { for (size_t i = 0; i < capability.sub_graph->nodes.size(); ++i) { mixed_survivor_capability_cost += get_size(capability.sub_graph->GetNodeCost(i)); } } } } }; auto graph_optimizer_registry = std::make_unique( &sess_options, nullptr /*cpu_ep*/, &default_logger); GraphPartitioner partitioner(krm, execution_providers, std::move(graph_optimizer_registry), []() -> bool { return false; }, on_assignment); layout_transformation::TransformLayoutFunction transform_layout_fn = [](Graph&, bool& modified, const IExecutionProvider&, const layout_transformation::DebugGraphFn&) -> Status { modified = false; return Status::OK(); }; layout_transformation::DebugGraphFn debug_graph_fn; FuncManager func_mgr; ASSERT_STATUS_OK( partitioner.Partition(graph, func_mgr, transform_layout_fn, sess_options.config_options, default_logger, nullptr /*layering_index*/, GraphPartitioner::Mode::kNormal, epctx::ModelGenOptions{}, false /*ep_context_data_read_callback_registered*/, debug_graph_fn)); if (survivor_capability_mode == SurvivorCapabilityMode::kAccountedMixedOverlap && !expect_relu_rejected) { EXPECT_TRUE(mixed_survivor_capability_assigned); EXPECT_EQ(mixed_survivor_capability_cost, expected_relu_cost) << "The retained Conv reservation must not be duplicated by the mixed final capability."; ASSERT_TRUE(mixed_consumed_before_assignment.has_value()); EXPECT_EQ(*mixed_consumed_before_assignment, expected_conv_cost) << "The overlapping final capability must win without retaining the uncovered LogSoftmax."; const Node* final_log_softmax_node = graph.GetNode(log_softmax_node_index); EXPECT_TRUE(final_log_softmax_node == nullptr || final_log_softmax_node->GetExecutionProviderType().empty()); } else if (survivor_capability_mode == SurvivorCapabilityMode::kMixedWithPass2Node) { EXPECT_TRUE(mixed_survivor_capability_assigned); EXPECT_EQ(mixed_survivor_capability_cost, expected_conv_cost + expected_relu_cost) << "The pass-1 Conv must be re-probed and priced with the pass-2 Relu capability."; ASSERT_TRUE(mixed_consumed_before_assignment.has_value()); EXPECT_EQ(*mixed_consumed_before_assignment, size_t{0}); } else if (expect_relu_rejected) { EXPECT_FALSE(pass2_only_relu_assigned) << "Relu must be rejected when the survivor reservations make it exceed the budget."; ASSERT_TRUE(ep_raw->last_observed_consumed().has_value()); const size_t expected_survivor_cost = expected_conv_cost + (log_softmax_survives ? expected_log_softmax_cost : 0); EXPECT_EQ(*ep_raw->last_observed_consumed(), expected_survivor_cost) << "The final admission pass must reserve all later survivors before evaluating Relu."; const Node* final_relu_node = graph.GetNode(relu_node_index); EXPECT_TRUE(final_relu_node == nullptr || final_relu_node->GetExecutionProviderType().empty()); if (log_softmax_survives) { EXPECT_TRUE(fused_pass1_survivors_assigned) << "The discovery capability for the fused pass-1 survivors must be preserved."; } else { EXPECT_TRUE(conv_survivor_capability_assigned) << "The single-node discovery capability must be preserved when it carries a MetaDef."; } } else { ASSERT_TRUE(observed_consumed.has_value()) << "Expected the pass-2-only Relu partition to be assigned to the EP."; EXPECT_EQ(*observed_consumed, expected_conv_cost) << "The Conv survivor should be reserved exactly once before Relu admission."; EXPECT_NE(*observed_consumed, expected_conv_cost + expected_log_softmax_cost) << "Dropped LogSoftmax must not consume budget."; EXPECT_TRUE(pass2_only_relu_assigned) << "Dropped LogSoftmax must not block the pass-2-only Relu that fits with the Conv survivor."; ASSERT_TRUE(observed_workspace.has_value()); ASSERT_TRUE(observed_persistent_prepack.has_value()); ASSERT_TRUE(observed_initialization_scratch.has_value()); ASSERT_TRUE(observed_source_counts.has_value()); EXPECT_EQ(*observed_workspace, *conv_estimate.runtime_workspace_bytes); EXPECT_EQ(*observed_persistent_prepack, conv_estimate.persistent_prepack_bytes); EXPECT_EQ(*observed_initialization_scratch, conv_estimate.initialization_scratch_bytes); EXPECT_EQ(observed_source_counts->estimator, size_t{1}); EXPECT_EQ(observed_source_counts->fallback, size_t{0}); } if (survivor_capability_mode == SurvivorCapabilityMode::kOptimizationOnly) { EXPECT_TRUE(ep_raw->optimization_invoked()) << "A single-node survivor capability with optimization work must be re-probed and processed."; } } TEST(InternalTestingEP, NhwcTwoPassAccountingRetriesAdmissionAfterDroppedCostRollback) { RunNhwcTwoPassAccountingRetryTest(false); } TEST(InternalTestingEP, NhwcTwoPassAccountingPreservesLaterSurvivorReservation) { RunNhwcTwoPassAccountingRetryTest(true); } TEST(InternalTestingEP, NhwcTwoPassAccountingPreservesLaterFusedSurvivorCapability) { RunNhwcTwoPassAccountingRetryTest(true, SurvivorCapabilityMode::kFused); } TEST(InternalTestingEP, NhwcTwoPassAccountingReplacesPartialSurvivorOverlap) { RunNhwcTwoPassAccountingRetryTest(true, SurvivorCapabilityMode::kPartialOverlap); } TEST(InternalTestingEP, NhwcTwoPassAccountingPreservesSurvivorCapabilityGrouping) { RunNhwcTwoPassAccountingRetryTest(true, SurvivorCapabilityMode::kSplitCoverage); } TEST(InternalTestingEP, NhwcTwoPassAccountingReprobesMixedSurvivorCapability) { RunNhwcTwoPassAccountingRetryTest(false, SurvivorCapabilityMode::kMixedWithPass2Node); } TEST(InternalTestingEP, NhwcTwoPassAccountingKeepsAccountedMixedOverlap) { RunNhwcTwoPassAccountingRetryTest(false, SurvivorCapabilityMode::kAccountedMixedOverlap); } TEST(InternalTestingEP, NhwcTwoPassAccountingRestoresDisplacedSurvivorsWhenOverlapExceedsBudget) { RunNhwcTwoPassAccountingRetryTest(true, SurvivorCapabilityMode::kAccountedMixedOverlap); } TEST(InternalTestingEP, NhwcTwoPassAccountingReprobesOptimizationOnlySurvivorCapability) { RunNhwcTwoPassAccountingRetryTest(false, SurvivorCapabilityMode::kOptimizationOnly); } TEST(InternalTestingEP, NhwcTwoPassAccountingReassignsSharedInitializerToSurvivor) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model("NhwcTwoPassAccountingReassignsSharedInitializerToSurvivor", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); constexpr int64_t kElementCount = 16384; const std::vector tensor_shape{kElementCount}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* shared_initializer = builder.MakeInitializer(tensor_shape, -1.0f, 1.0f); auto* first_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); Node& dropped_node = builder.AddNode("Add", std::vector{input, shared_initializer}, std::vector{first_output}); Node& survivor_node = builder.AddNode("Add", std::vector{first_output, shared_initializer}, std::vector{output}); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); ConfigOptions reference_config; ASSERT_STATUS_OK(reference_config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1048576,")); std::optional reference_accountants; ASSERT_STATUS_OK(CreateAccountants(reference_config, PathString(), reference_accountants)); ASSERT_TRUE(reference_accountants.has_value()); auto reference_it = reference_accountants->find(kCudaExecutionProvider); ASSERT_NE(reference_it, reference_accountants->end()); const size_t expected_survivor_cost = std::get( reference_it->second->ComputeResourceCount( survivor_node, GetNhwcAccountingTestEstimate("Add"))); ExecutionProviders execution_providers; auto& default_logger = DefaultLoggingManager().DefaultLogger(); auto ep = std::make_unique( std::nullopt, SurvivorCapabilityMode::kSeparate, dropped_node.Index()); auto* ep_raw = ep.get(); ep->SetLogger(&default_logger); ASSERT_STATUS_OK(execution_providers.Add(kCudaExecutionProvider, std::move(ep))); KernelRegistryManager krm; ASSERT_STATUS_OK(krm.RegisterKernels(execution_providers)); SessionOptions sess_options; ASSERT_STATUS_OK(sess_options.config_options.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "4096,")); std::optional consumed_before_survivor_assignment; OnPartitionAssignmentFunction on_assignment = [&](const Graph&, const ComputeCapability& capability, const std::string& assigned_ep_type) { if (assigned_ep_type == kCudaExecutionProvider && std::find(capability.sub_graph->nodes.begin(), capability.sub_graph->nodes.end(), survivor_node.Index()) != capability.sub_graph->nodes.end()) { consumed_before_survivor_assignment = std::get(ep_raw->observed_accountant()->GetConsumedAmount()); } }; auto graph_optimizer_registry = std::make_unique( &sess_options, nullptr /*cpu_ep*/, &default_logger); GraphPartitioner partitioner( krm, execution_providers, std::move(graph_optimizer_registry), []() -> bool { return false; }, on_assignment); layout_transformation::TransformLayoutFunction transform_layout_fn = [](Graph&, bool& modified, const IExecutionProvider&, const layout_transformation::DebugGraphFn&) -> Status { modified = false; return Status::OK(); }; FuncManager func_mgr; ASSERT_STATUS_OK( partitioner.Partition(graph, func_mgr, transform_layout_fn, sess_options.config_options, default_logger, nullptr /*layering_index*/)); ASSERT_TRUE(consumed_before_survivor_assignment.has_value()); EXPECT_EQ(*consumed_before_survivor_assignment, expected_survivor_cost) << "The survivor must inherit the shared initializer charge when its original owner is dropped."; } TEST(InternalTestingEP, NhwcTwoPassAccountingReassignsSharedInitializerAfterOverlapDisplacement) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model("NhwcTwoPassAccountingReassignsSharedInitializerAfterOverlapDisplacement", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); constexpr int64_t kElementCount = 16384; const std::vector tensor_shape{kElementCount}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* shared_initializer = builder.MakeInitializer(tensor_shape, -1.0f, 1.0f); auto* first_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* second_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); Node& displaced_node = builder.AddNode("Add", std::vector{input, shared_initializer}, std::vector{first_output}); Node& retained_node = builder.AddNode("Add", std::vector{first_output, shared_initializer}, std::vector{second_output}); Node& pass2_node = builder.AddNode("Relu", std::vector{second_output}, std::vector{output}); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); ConfigOptions reference_config; ASSERT_STATUS_OK(reference_config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1048576,")); std::optional reference_accountants; ASSERT_STATUS_OK(CreateAccountants(reference_config, PathString(), reference_accountants)); ASSERT_TRUE(reference_accountants.has_value()); auto reference_it = reference_accountants->find(kCudaExecutionProvider); ASSERT_NE(reference_it, reference_accountants->end()); const size_t expected_retained_cost = std::get( reference_it->second->ComputeResourceCount( retained_node, GetNhwcAccountingTestEstimate("Add"))); std::optional shared_reference_accountants; ASSERT_STATUS_OK(CreateAccountants( reference_config, PathString(), shared_reference_accountants)); ASSERT_TRUE(shared_reference_accountants.has_value()); auto shared_reference_it = shared_reference_accountants->find(kCudaExecutionProvider); ASSERT_NE(shared_reference_it, shared_reference_accountants->end()); shared_reference_it->second->ComputeResourceCount( displaced_node, GetNhwcAccountingTestEstimate("Add")); const size_t retained_cost_without_shared_initializer = std::get( shared_reference_it->second->ComputeResourceCount( retained_node, GetNhwcAccountingTestEstimate("Add"))); ASSERT_GT(expected_retained_cost, retained_cost_without_shared_initializer); ExecutionProviders execution_providers; auto& default_logger = DefaultLoggingManager().DefaultLogger(); auto ep = std::make_unique( std::nullopt, SurvivorCapabilityMode::kAccountedMixedOverlap, std::nullopt, displaced_node.Index()); auto* ep_raw = ep.get(); ep->SetLogger(&default_logger); ASSERT_STATUS_OK(execution_providers.Add(kCudaExecutionProvider, std::move(ep))); KernelRegistryManager krm; ASSERT_STATUS_OK(krm.RegisterKernels(execution_providers)); SessionOptions sess_options; ASSERT_STATUS_OK(sess_options.config_options.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "4096,")); std::optional consumed_before_overlap_assignment; OnPartitionAssignmentFunction on_assignment = [&](const Graph&, const ComputeCapability& capability, const std::string& assigned_ep_type) { if (assigned_ep_type != kCudaExecutionProvider || ep_raw->observed_accountant() == nullptr) { return; } const bool has_retained_node = std::find(capability.sub_graph->nodes.begin(), capability.sub_graph->nodes.end(), retained_node.Index()) != capability.sub_graph->nodes.end(); const bool has_pass2_node = std::find(capability.sub_graph->nodes.begin(), capability.sub_graph->nodes.end(), pass2_node.Index()) != capability.sub_graph->nodes.end(); if (has_retained_node && has_pass2_node) { consumed_before_overlap_assignment = std::get(ep_raw->observed_accountant()->GetConsumedAmount()); } }; auto graph_optimizer_registry = std::make_unique( &sess_options, nullptr /*cpu_ep*/, &default_logger); GraphPartitioner partitioner( krm, execution_providers, std::move(graph_optimizer_registry), []() -> bool { return false; }, on_assignment); layout_transformation::TransformLayoutFunction transform_layout_fn = [](Graph&, bool& modified, const IExecutionProvider&, const layout_transformation::DebugGraphFn&) -> Status { modified = false; return Status::OK(); }; FuncManager func_mgr; ASSERT_STATUS_OK( partitioner.Partition(graph, func_mgr, transform_layout_fn, sess_options.config_options, default_logger, nullptr /*layering_index*/)); ASSERT_TRUE(consumed_before_overlap_assignment.has_value()); EXPECT_EQ(*consumed_before_overlap_assignment, expected_retained_cost) << "The retained survivor must inherit a shared initializer owned by a displaced survivor."; } TEST(InternalTestingEP, NhwcTwoPassAccountingDoesNotReserveUnassignedCapability) { std::unordered_map domain_to_version{{kOnnxDomain, 13}, {kMSDomain, 1}}; Model model("NhwcTwoPassAccountingDoesNotReserveUnassignedCapability", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), domain_to_version, {}, DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ModelTestBuilder builder(graph); const std::vector tensor_shape{1, 1, 3, 3}; auto* input = builder.MakeInput(std::optional>{tensor_shape}); auto* weights = builder.MakeInitializer(std::vector{1, 1, 1, 1}, std::vector{1.0f}); auto* conv_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* log_softmax_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* removed_output = builder.MakeIntermediate(std::optional>{tensor_shape}); auto* output = builder.MakeOutput(std::optional>{tensor_shape}); builder.AddConvNode(input, weights, conv_output); builder.AddNode( "LogSoftmax", std::vector{conv_output}, std::vector{log_softmax_output}); builder.AddNode("Relu", std::vector{log_softmax_output}, std::vector{output}); Node& removed_node = builder.AddNode( "Identity", std::vector{input}, std::vector{removed_output}); const NodeIndex removed_node_index = removed_node.Index(); graph.RemoveNode(removed_node_index); builder.SetGraphOutputs(); ASSERT_STATUS_OK(graph.Resolve()); Node* conv_node = nullptr; Node* log_softmax_node = nullptr; Node* relu_node = nullptr; for (auto& node : graph.Nodes()) { if (node.OpType() == "Conv") { conv_node = &node; } else if (node.OpType() == "LogSoftmax") { log_softmax_node = &node; } else if (node.OpType() == "Relu") { relu_node = &node; } } ASSERT_NE(conv_node, nullptr); ASSERT_NE(log_softmax_node, nullptr); ASSERT_NE(relu_node, nullptr); ConfigOptions reference_config; ASSERT_STATUS_OK(reference_config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1048576,")); std::optional reference_accountants; ASSERT_STATUS_OK(CreateAccountants(reference_config, PathString(), reference_accountants)); ASSERT_TRUE(reference_accountants.has_value()); auto* reference_accountant = reference_accountants->at(kCudaExecutionProvider).get(); const size_t expected_conv_cost = std::get(reference_accountant->ComputeResourceCount( *conv_node, GetNhwcAccountingTestEstimate("Conv"))); const size_t conflicting_cost = std::get(reference_accountant->ComputeResourceCount( *log_softmax_node, GetNhwcAccountingTestEstimate("LogSoftmax"))); const size_t expected_relu_cost = std::get(reference_accountant->ComputeResourceCount( *relu_node, GetNhwcAccountingTestEstimate("Relu"))); ExecutionProviders execution_providers; auto& default_logger = DefaultLoggingManager().DefaultLogger(); auto ep = std::make_unique(removed_node_index); ep->SetLogger(&default_logger); ASSERT_STATUS_OK(execution_providers.Add(kCudaExecutionProvider, std::move(ep))); KernelRegistryManager krm; ASSERT_STATUS_OK(krm.RegisterKernels(execution_providers)); SessionOptions sess_options; const size_t memory_threshold = expected_conv_cost + expected_relu_cost; const std::string partitioning_settings = std::to_string(memory_threshold) + ","; ASSERT_STATUS_OK(sess_options.config_options.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, partitioning_settings.c_str())); bool pass2_only_relu_assigned = false; OnPartitionAssignmentFunction on_assignment = [&](const Graph& assignment_graph, const ComputeCapability& capability, const std::string& assigned_ep_type) { if (assigned_ep_type != kCudaExecutionProvider) { return; } for (NodeIndex node_index : capability.sub_graph->nodes) { const Node* assigned_node = assignment_graph.GetNode(node_index); if (assigned_node != nullptr && assigned_node->OpType() == "Relu") { pass2_only_relu_assigned = true; } } }; auto graph_optimizer_registry = std::make_unique( &sess_options, nullptr /*cpu_ep*/, &default_logger); GraphPartitioner partitioner( krm, execution_providers, std::move(graph_optimizer_registry), []() -> bool { return false; }, on_assignment); layout_transformation::TransformLayoutFunction transform_layout_fn = [](Graph&, bool& modified, const IExecutionProvider&, const layout_transformation::DebugGraphFn&) -> Status { modified = false; return Status::OK(); }; layout_transformation::DebugGraphFn debug_graph_fn; FuncManager func_mgr; ASSERT_STATUS_OK( partitioner.Partition(graph, func_mgr, transform_layout_fn, sess_options.config_options, default_logger, nullptr /*layering_index*/, GraphPartitioner::Mode::kNormal, epctx::ModelGenOptions{}, false /*ep_context_data_read_callback_registered*/, debug_graph_fn)); EXPECT_TRUE(pass2_only_relu_assigned) << "The pass-2 Relu must fit when the rejected LogSoftmax capability is not reserved."; EXPECT_GT(conflicting_cost, size_t{0}); } // Infrastructure that was used to check NNAPI coverage. // Ideally this could be updated to read the model paths, supported ops and stop ops from input files // and provide info on the partitions so no code changes are required to investigate different scenarios. static std::unordered_set GetNnapiSupportedOps() { return std::unordered_set{ "Add", "Sub", "Mul", "Div", "QLinearAdd", "Pow", "Relu", "Transpose", "Reshape", "BatchNormalization", "GlobalAveragePool", "GlobalMaxPool", "AveragePool", "MaxPool", "QLinearAveragePool", "Conv", "QLinearConv", "Cast", "Softmax", "Identity", "Gemm", "MatMul", "QLinearMatMul", "Abs", "Exp", "Floor", "Log", "Sigmoid", "Neg", "Sin", "Sqrt", "Tanh", "QLinearSigmoid", "Concat", "Squeeze", "QuantizeLinear", "DequantizeLinear", "LRN", "Clip", "Resize", "Flatten", "Min", "Max"}; } struct PartitionStats { int num_nodes_handled; int num_nodes_not_handled; int num_compiled_nodes; }; static void TestNnapiPartitioning(const std::string& test_name, const std::string& model_uri, bool optimize, bool debug_output, const std::unordered_set& stop_ops, const std::vector& additional_supported_ops, PartitionStats& stats) { SessionOptions so; so.graph_optimization_level = optimize ? TransformerLevel::Level3 : TransformerLevel::Level1; auto session = std::make_unique(so, GetEnvironment()); // we disable NCHWc in mobile scenarios as it's not relevant to ARM if (optimize) { ASSERT_STATUS_OK(session->FilterEnabledOptimizers({"NchwcTransformer"})); } auto ops = GetNnapiSupportedOps(); for (const auto& op_type : additional_supported_ops) { ops.insert(op_type); } auto ep = std::make_unique(ops, stop_ops, DataLayout::NHWC); if (debug_output) { ep->SetDebugOutput(true); } ASSERT_STATUS_OK(session->RegisterExecutionProvider(std::move(ep))); ASSERT_STATUS_OK(session->Load(model_uri)); const auto& graph = session->GetGraph(); GraphViewer viewer{graph}; // save node count before optimization/partitioning. we lose some accuracy if optimizations replace nodes const auto num_nodes = graph.NumberOfNodes(); ASSERT_STATUS_OK(session->Initialize()); // log the unsupported ops after initializer so that anything removed by constant folding etc. isn't listed. std::unordered_map unsupported_ops; std::ostringstream oss; std::string unsupported_op_str; for (const Node& node : graph.Nodes()) { if (node.GetExecutionProviderType() != kInternalTestingExecutionProvider && ops.count(node.OpType()) == 0) { auto entry = unsupported_ops.find(node.OpType()); if (entry != unsupported_ops.end()) { ++entry->second; } else { unsupported_ops[node.OpType()] = 1; } } } if (!unsupported_ops.empty()) { bool add_comma = false; for (const auto& pair : unsupported_ops) { if (add_comma) { oss << ","; } oss << pair.first << "(" << pair.second << ")"; add_comma = true; } unsupported_op_str = oss.str(); } auto& func_mgr = const_cast(session->GetSessionState()).GetMutableFuncMgr(); const NodeComputeInfo* compute_func = nullptr; stats.num_nodes_not_handled = 0; stats.num_compiled_nodes = 0; // find the nodes downstream of the excluded nodes to check that they were assigned correctly std::unordered_set excluded_nodes; if (!stop_ops.empty()) { for (const auto& node : graph.Nodes()) { if (stop_ops.find(node.OpType()) != stop_ops.cend()) { excluded_nodes.insert(&node); // add all the downstream nodes to the excluded list std::queue nodes_to_add; nodes_to_add.push(&node); while (!nodes_to_add.empty()) { const Node* cur_node = nodes_to_add.front(); nodes_to_add.pop(); std::for_each(cur_node->OutputNodesBegin(), cur_node->OutputNodesEnd(), [&nodes_to_add, &excluded_nodes](const Node& output_node) { nodes_to_add.push(&output_node); excluded_nodes.insert(&output_node); }); } } } } for (const auto& node : graph.Nodes()) { if (stop_ops.empty() || excluded_nodes.find(&node) == excluded_nodes.cend()) { EXPECT_EQ(ops.count(node.OpType()), size_t(0)) << "Nodes with supported op types should have been replaced. Node with type " << node.OpType() << " was not."; } else { EXPECT_NE(node.GetExecutionProviderType(), kInternalTestingExecutionProvider) << "Node is downstream from a 'stop at' node and should not have been taken. Node:" << node.Name(); } if (node.GetExecutionProviderType() == kInternalTestingExecutionProvider) { EXPECT_STATUS_OK(func_mgr.GetFuncs(node.Name(), compute_func)); EXPECT_NE(compute_func, nullptr); ++stats.num_compiled_nodes; } else { ++stats.num_nodes_not_handled; } } stats.num_nodes_handled = num_nodes - stats.num_nodes_not_handled; auto pad_str = [](std::string const& str, size_t len = 10) { return (str.size() < len) ? str + std::string(len - str.size(), ' ') : str; }; std::cout << pad_str(test_name, 25) << ": Compiled=" << stats.num_compiled_nodes << " Handled=" << stats.num_nodes_handled << " NotHandled=" << stats.num_nodes_not_handled << " UnsupportedOps=" << unsupported_op_str << "\n"; } // DISABLED - manually update model_paths and enable to test coverage as needed TEST(InternalTestingEP, DISABLED_TestNnapiPartitioningMlPerfModels) { const auto supported_ops = GetNnapiSupportedOps(); // list the models you want to test here std::vector model_paths = { "deeplabv3_mnv2_ade20k_float.onnx", "mobilebert.onnx", "mobiledet.onnx", }; for (const auto& model_uri : model_paths) { auto run_tests = [&](bool optimize) { std::cout << "\n================================\n"; std::cout << "Model: " << model_uri; if (optimize) { std::cout << " (optimized)"; } std::cout << std::endl; constexpr bool debug_output = false; PartitionStats stats{}, stop_at_nms_stats{}, slice_stats{}; // arbitrary examples of running different combinations to test what partitioning results TestNnapiPartitioning("Base", model_uri, optimize, debug_output, {}, {}, stats); TestNnapiPartitioning("StopAt[NMS]", model_uri, optimize, debug_output, {"NonMaxSuppression"}, {}, stop_at_nms_stats); TestNnapiPartitioning("ExtraOps[Slice]", model_uri, optimize, debug_output, {}, {"Slice"}, slice_stats); }; run_tests(false); // run_tests(true); // optimized - if models have already be optimized this isn't helpful } } #endif // !defined(ORT_MINIMAL_BUILD) } // namespace test } // namespace onnxruntime #endif // !defined(REDUCED_OPS_BUILD)