// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/framework/resource_accountant.h" #include "core/framework/config_options.h" #include "core/graph/indexed_sub_graph.h" #include "core/graph/constants.h" #include "core/graph/model.h" #include "core/session/onnxruntime_session_options_config_keys.h" #include "gtest/gtest.h" #include "test/util/include/asserts.h" #include "test/util/include/test_environment.h" #include #include #include #include #include #ifdef _WIN32 #include #define ORT_TEST_PID _getpid() #else #include #define ORT_TEST_PID getpid() #endif namespace onnxruntime { namespace test { namespace { // Helper to extract size_t from ResourceCount variant. // Uses std::get_if so test failures produce a clear assertion rather than std::bad_variant_access. size_t GetSizeT(const ResourceCount& rc) { const auto* value = std::get_if(&rc); EXPECT_NE(value, nullptr) << "ResourceCount does not hold size_t"; return value != nullptr ? *value : 0; } // Helper to create a real SizeBasedResourceAccountant in ad-hoc mode (no stats file) via factory. // Must be called from within a TEST body (or via ASSERT_NO_FATAL_FAILURE) because it uses ASSERT_*. void CreateAdHocAccountant( size_t limit_kb, const std::filesystem::path& model_path, std::optional& acc_map, IResourceAccountant*& out) { ConfigOptions config; std::string setting = std::to_string(limit_kb) + ","; ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, setting.c_str())); ASSERT_STATUS_OK(CreateAccountants(config, model_path, acc_map)); ASSERT_TRUE(acc_map.has_value()); auto it = acc_map->find(kCudaExecutionProvider); ASSERT_NE(it, acc_map->end()); out = it->second.get(); } } // namespace // Two Add nodes that share a single initializer weight_W. struct SharedWeightGraph { std::unique_ptr model; Graph* graph = nullptr; Node* node_a = nullptr; Node* node_b = nullptr; static void Create(SharedWeightGraph& h) { std::unordered_map dom; dom[kOnnxDomain] = 12; h.model = std::make_unique( "test_model", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), dom, std::vector(), DefaultLoggingManager().DefaultLogger()); h.graph = &h.model->MainGraph(); ONNX_NAMESPACE::TypeProto ft; ft.mutable_tensor_type()->set_elem_type( ONNX_NAMESPACE::TensorProto_DataType_FLOAT); ft.mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(250); ONNX_NAMESPACE::TensorProto wp; wp.set_name("weight_W"); wp.set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); wp.add_dims(250); for (int i = 0; i < 250; ++i) { wp.add_float_data(0.0f); } h.graph->AddInitializedTensor(wp); auto* ia = &h.graph->GetOrCreateNodeArg("input_a", &ft); auto* ib = &h.graph->GetOrCreateNodeArg("input_b", &ft); auto* wa = &h.graph->GetOrCreateNodeArg("weight_W", &ft); auto* oa = &h.graph->GetOrCreateNodeArg("out_a", &ft); auto* ob = &h.graph->GetOrCreateNodeArg("out_b", &ft); h.node_a = &h.graph->AddNode("node_A", "Add", "A", {ia, wa}, {oa}); h.node_b = &h.graph->AddNode("node_B", "Add", "B", {ib, wa}, {ob}); ASSERT_STATUS_OK(h.graph->Resolve()); } }; // Ad-hoc path expected costs for SharedWeightGraph: // weight_W = 250 floats = 1000 bytes, each output = 250 floats = 1000 bytes // node_A: (1000 init + 1000 out) * 1.5 = 3000 // node_B: (0 deduped + 1000 out) * 1.5 = 1500 // AccountForAllNodes sums pre-stored per-node costs // that already have correct within-pass weight deduplication. TEST(ResourceAccountantTest, AccountForAllNodes_CorrectlyUsesPreStoredCosts) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); auto cost_a = accountant->ComputeResourceCount(*h.node_a); sub_graph.AppendNodeCost(cost_a); EXPECT_EQ(GetSizeT(cost_a), size_t{3000}); auto cost_b = accountant->ComputeResourceCount(*h.node_b); sub_graph.AppendNodeCost(cost_b); EXPECT_EQ(GetSizeT(cost_b), size_t{1500}); ASSERT_TRUE(sub_graph.IsAccountingEnabled()); sub_graph.AccountForAllNodes(); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{4500}) << "AccountForAllNodes should sum pre-stored costs (3000 + 1500)"; } // Verifies that ResetForNewPass + re-probe produces correct results. // After probing (which only writes to pending), resetting for a new pass and // re-probing should see the full weight cost again since nothing was committed. TEST(ResourceAccountantTest, ComputeAndAccountForNode_CorrectAfterReset) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); // Probing pass populates pending weights auto cost_a = accountant->ComputeResourceCount(*h.node_a); EXPECT_EQ(GetSizeT(cost_a), size_t{3000}); auto cost_b = accountant->ComputeResourceCount(*h.node_b); EXPECT_EQ(GetSizeT(cost_b), size_t{1500}); // Discard the pass (simulating capabilities.clear() before second GetCapability) accountant->ResetForNewPass(); // Re-probe: weight_W was never committed, so it should be counted again IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.SetAccountant(accountant); auto recomputed_cost = accountant->ComputeResourceCount(*h.node_a); sub_graph.AccountForNode(h.node_a->Index(), recomputed_cost); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{3000}) << "After ResetForNewPass, re-probe should see full weight cost"; } TEST(ResourceAccountantTest, WorkspaceEstimateCommittedOnlyForAcceptedNodes) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); // Probing records a pending estimate but does not affect the user-visible total. const auto uncommitted_cost = accountant->ComputeResourceCount(*h.node_a); ORT_UNUSED_PARAMETER(uncommitted_cost); auto pending_workspace = accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(pending_workspace.bytes, size_t{1000}); EXPECT_EQ(pending_workspace.source, WorkspaceEstimateSource::kFallback); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{0}); // Discarding the pass removes estimates for rejected or superseded capabilities. accountant->ResetForNewPass(); pending_workspace = accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(pending_workspace.bytes, size_t{0}); EXPECT_EQ(pending_workspace.source, WorkspaceEstimateSource::kNone); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{0}); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(accountant->ComputeResourceCount(*h.node_a)); sub_graph.AccountForNode(0); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{1000}); EXPECT_EQ(accountant->GetWorkspaceEstimateSourceCounts().fallback, size_t{1}); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{3000}); } TEST(ResourceAccountantTest, Level1MemoryEstimateReplacesFallbackAndReportsInitializationScratchPeak) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); const Level1MemoryEstimate level1_estimate{ /*runtime_workspace_bytes=*/250, /*persistent_prepack_bytes=*/300, /*initialization_scratch_bytes=*/400}; auto resource_count = accountant->ComputeResourceCount(*h.node_a, level1_estimate); EXPECT_EQ(GetSizeT(resource_count), size_t{2550}); const auto pending_workspace = accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(pending_workspace.bytes, size_t{250}); EXPECT_EQ(pending_workspace.source, WorkspaceEstimateSource::kEstimator); EXPECT_EQ(pending_workspace.persistent_prepack_bytes, size_t{300}); EXPECT_EQ(pending_workspace.initialization_scratch_bytes, size_t{400}); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(resource_count); sub_graph.AccountForNode(0); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{250}); EXPECT_EQ(accountant->GetCommittedPersistentPrepackEstimate(), size_t{300}); EXPECT_EQ(accountant->GetCommittedInitializationScratchEstimate(), size_t{400}); EXPECT_EQ(accountant->GetWorkspaceEstimateSourceCounts().estimator, size_t{1}); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{2550}); } TEST(ResourceAccountantTest, Level1MemoryEstimateKeepsFallbackWhenRuntimeWorkspaceIsUnknown) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); const Level1MemoryEstimate level1_estimate{ /*runtime_workspace_bytes=*/std::nullopt, /*persistent_prepack_bytes=*/300, /*initialization_scratch_bytes=*/400}; const auto resource_count = accountant->ComputeResourceCount(*h.node_a, level1_estimate); EXPECT_EQ(GetSizeT(resource_count), size_t{3300}); const auto pending_workspace = accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(pending_workspace.bytes, size_t{1000}); EXPECT_EQ(pending_workspace.source, WorkspaceEstimateSource::kFallback); EXPECT_EQ(pending_workspace.persistent_prepack_bytes, size_t{300}); EXPECT_EQ(pending_workspace.initialization_scratch_bytes, size_t{400}); } TEST(ResourceAccountantTest, InitializationScratchIsCommittedAsPeakAndExcludedFromBudget) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); const auto cost_a = accountant->ComputeResourceCount( *h.node_a, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/250, /*persistent_prepack_bytes=*/0, /*initialization_scratch_bytes=*/400}); const auto cost_b = accountant->ComputeResourceCount( *h.node_b, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/250, /*persistent_prepack_bytes=*/0, /*initialization_scratch_bytes=*/700}); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(cost_a); sub_graph.AppendNodeCost(cost_b); sub_graph.AccountForAllNodes(); EXPECT_EQ(accountant->GetCommittedInitializationScratchEstimate(), size_t{700}); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), GetSizeT(cost_a) + GetSizeT(cost_b)); } TEST(ResourceAccountantTest, RuntimeTransientIsPeakedWithFallbackOrEstimatedWorkspace) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); const auto fallback_cost = accountant->ComputeResourceCount( *h.node_a, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/std::nullopt, /*persistent_prepack_bytes=*/0, /*initialization_scratch_bytes=*/0, /*runtime_transient_bytes=*/1200}); EXPECT_EQ(GetSizeT(fallback_cost), size_t{3200}); EXPECT_EQ(accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()).bytes, size_t{1200}); const auto estimated_cost = accountant->ComputeResourceCount( *h.node_b, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/250, /*persistent_prepack_bytes=*/0, /*initialization_scratch_bytes=*/0, /*runtime_transient_bytes=*/700}); EXPECT_EQ(GetSizeT(estimated_cost), size_t{1700}); EXPECT_EQ(accountant->GetPendingWorkspaceEstimateSelection(h.node_b->Index()).bytes, size_t{700}); } TEST(ResourceAccountantTest, CommittedWorkspaceRejectsOverflow) { std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); accountant->AddCommittedWorkspaceEstimate( nullptr, 0, {std::numeric_limits::max(), WorkspaceEstimateSource::kFallback}); EXPECT_ANY_THROW(accountant->AddCommittedWorkspaceEstimate( nullptr, 1, {size_t{1}, WorkspaceEstimateSource::kEstimator})); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), std::numeric_limits::max()); const auto source_counts = accountant->GetWorkspaceEstimateSourceCounts(); EXPECT_EQ(source_counts.fallback, size_t{1}); EXPECT_EQ(source_counts.estimator, size_t{0}); } TEST(ResourceAccountantTest, FusedNodeConsolidatesConstituentWorkspaceReservations) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); const auto cost_a = accountant->ComputeResourceCount( *h.node_a, Level1MemoryEstimate{/*runtime_workspace_bytes=*/400}); const auto cost_b = accountant->ComputeResourceCount( *h.node_b, Level1MemoryEstimate{/*runtime_workspace_bytes=*/800}); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(cost_a); sub_graph.AppendNodeCost(cost_b); constexpr NodeIndex fused_node_index = 42; sub_graph.AccountForAllNodes(h.graph, fused_node_index); const auto reservations = accountant->GetCommittedWorkspaceReservations(); ASSERT_EQ(reservations.size(), size_t{1}); const auto& graph_reservations = reservations.at(h.graph); ASSERT_EQ(graph_reservations.size(), size_t{1}); EXPECT_EQ(graph_reservations.at(fused_node_index).bytes, size_t{1200}); EXPECT_EQ(graph_reservations.at(fused_node_index).source, WorkspaceEstimateSource::kEstimator); } TEST(ResourceAccountantTest, ConsolidationIncludesExistingDestinationReservation) { NodeWorkspaceReservationMap reservations{ {1, WorkspaceEstimateSelection{400, WorkspaceEstimateSource::kEstimator}}, {2, WorkspaceEstimateSelection{800, WorkspaceEstimateSource::kEstimator}}, {42, WorkspaceEstimateSelection{50, WorkspaceEstimateSource::kFallback}}, }; const std::array source_node_indices{1, 2}; ConsolidateWorkspaceReservations(reservations, source_node_indices, 42); ASSERT_EQ(reservations.size(), size_t{1}); EXPECT_EQ(reservations.at(42).bytes, size_t{1250}); EXPECT_EQ(reservations.at(42).source, WorkspaceEstimateSource::kNone); } TEST(ResourceAccountantTest, ConsumedAmountRejectsOverflowAndUnderflow) { std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); accountant->AddConsumedAmount(std::numeric_limits::max()); EXPECT_ANY_THROW(accountant->AddConsumedAmount(size_t{1})); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), std::numeric_limits::max()); accountant->RemoveConsumedAmount(std::numeric_limits::max()); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{0}); EXPECT_ANY_THROW(accountant->RemoveConsumedAmount(size_t{1})); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{0}); } // ResetForNewPass clears the stop flag so a second GetCapability pass // (e.g., after layout transformation) can run from scratch. TEST(ResourceAccountantTest, ResetForNewPass_ClearsStopFlag) { std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/1, PathString(), acc_map, accountant)); // Simulate first pass exhausting budget and setting stop. accountant->SetStopAssignment(); EXPECT_TRUE(accountant->IsStopIssued()); // Framework discards first-pass results and resets for second pass. accountant->ResetForNewPass(); EXPECT_FALSE(accountant->IsStopIssued()) << "ResetForNewPass should clear the stop flag for the next pass"; } // Each node has a unique initializer. AccountForAllNodes sums both. // weight_1 = 100 floats = 400 bytes, weight_2 = 100 floats = 400 bytes, outputs = 400 bytes each // node1: (400 init + 400 out) * 1.5 = 1200 // node2: (400 init + 400 out) * 1.5 = 1200 TEST(ResourceAccountantTest, AccountForAllNodes_NoSharedWeights) { std::unordered_map dom; dom[kOnnxDomain] = 12; Model model("test_model", false, ModelMetaData(), PathString(), IOnnxRuntimeOpSchemaRegistryList(), dom, std::vector(), DefaultLoggingManager().DefaultLogger()); Graph& graph = model.MainGraph(); ONNX_NAMESPACE::TypeProto ft; ft.mutable_tensor_type()->set_elem_type( ONNX_NAMESPACE::TensorProto_DataType_FLOAT); ft.mutable_tensor_type()->mutable_shape()->add_dim()->set_dim_value(100); const char* names[] = {"weight_1", "weight_2"}; for (const char* wn : names) { ONNX_NAMESPACE::TensorProto tp; tp.set_name(wn); tp.set_data_type(ONNX_NAMESPACE::TensorProto_DataType_FLOAT); tp.add_dims(100); for (int i = 0; i < 100; ++i) { tp.add_float_data(0.0f); } graph.AddInitializedTensor(tp); } auto* input = &graph.GetOrCreateNodeArg("input", &ft); auto* w1 = &graph.GetOrCreateNodeArg("weight_1", &ft); auto* w2 = &graph.GetOrCreateNodeArg("weight_2", &ft); auto* out1 = &graph.GetOrCreateNodeArg("out1", &ft); auto* out2 = &graph.GetOrCreateNodeArg("out2", &ft); auto& node1 = graph.AddNode("n1", "Add", "", {input, w1}, {out1}); auto& node2 = graph.AddNode("n2", "Add", "", {out1, w2}, {out2}); ASSERT_STATUS_OK(graph.Resolve()); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(node1.Index()); sub_graph.nodes.push_back(node2.Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(accountant->ComputeResourceCount(node1)); sub_graph.AppendNodeCost(accountant->ComputeResourceCount(node2)); ASSERT_TRUE(sub_graph.IsAccountingEnabled()); sub_graph.AccountForAllNodes(); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{2400}) << "No shared weights: should sum all costs (1200 + 1200)"; } // AccountForNode per-node and AccountForAllNodes bulk produce same result. TEST(ResourceAccountantTest, AccountForNode_MatchesAccountForAllNodes) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); // Per-node path std::optional acc_map1; IResourceAccountant* acc1 = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map1, acc1)); IndexedSubGraph sub1; sub1.nodes.push_back(h.node_a->Index()); sub1.nodes.push_back(h.node_b->Index()); sub1.SetAccountant(acc1); sub1.AppendNodeCost(acc1->ComputeResourceCount(*h.node_a)); sub1.AppendNodeCost(acc1->ComputeResourceCount(*h.node_b)); sub1.AccountForNode(0); sub1.AccountForNode(1); size_t per_node = GetSizeT(acc1->GetConsumedAmount()); // Bulk path std::optional acc_map2; IResourceAccountant* acc2 = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map2, acc2)); IndexedSubGraph sub2; sub2.nodes.push_back(h.node_a->Index()); sub2.nodes.push_back(h.node_b->Index()); sub2.SetAccountant(acc2); sub2.AppendNodeCost(acc2->ComputeResourceCount(*h.node_a)); sub2.AppendNodeCost(acc2->ComputeResourceCount(*h.node_b)); sub2.AccountForAllNodes(); size_t bulk = GetSizeT(acc2->GetConsumedAmount()); EXPECT_EQ(per_node, bulk) << "Per-node and bulk should produce identical results"; EXPECT_EQ(per_node, size_t{4500}); } // Cross-subgraph dedup: EP1 commits node_A, EP2 probes node_B and // correctly sees weight_W as already accounted. // node_A cost: 3000, node_B cost after commit: (0 + 1000) * 1.5 = 1500 TEST(ResourceAccountantTest, CrossSubGraph_DedupWorks) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::optional acc_map; IResourceAccountant* accountant = nullptr; ASSERT_NO_FATAL_FAILURE(CreateAdHocAccountant(/*limit_kb=*/100, PathString(), acc_map, accountant)); // EP1 probes and commits node_A IndexedSubGraph sub1; sub1.nodes.push_back(h.node_a->Index()); sub1.SetAccountant(accountant); sub1.AppendNodeCost(accountant->ComputeResourceCount(*h.node_a)); sub1.AccountForNode(0); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{3000}); // Reset for new pass to simulate new GetCapability pass accountant->ResetForNewPass(); // EP2 probes node_B: weight_W already committed, only output counted auto cost_b = accountant->ComputeResourceCount(*h.node_b); EXPECT_EQ(GetSizeT(cost_b), size_t{1500}) << "weight_W was committed by EP1, only output (1000 * 1.5) counted"; // EP2 commits node_B IndexedSubGraph sub2; sub2.nodes.push_back(h.node_b->Index()); sub2.SetAccountant(accountant); sub2.AppendNodeCost(cost_b); sub2.AccountForNode(0); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{4500}) << "Total should be 3000 + 1500 - weight_W initializer counted once"; } // --------------------------------------------------------------------------- // Stats-based path and factory tests // --------------------------------------------------------------------------- // RAII helper to remove a temp file on scope exit, even if a test assertion fails. struct ScopedFileRemover { std::filesystem::path path; ~ScopedFileRemover() { std::error_code ec; std::filesystem::remove(path, ec); } }; // Stats-based path: cost is sum of all NodeAllocationStats fields. TEST(RealAccountantTest, StatsPath_ComputesCostFromStatsFile) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); // Write a stats file with known costs (unique per PID to avoid parallel collisions) std::error_code ec; auto stats_dir = std::filesystem::temp_directory_path(ec); ASSERT_FALSE(ec) << ec.message(); std::ostringstream fname; fname << "test_resource_accountant_stats_" << ORT_TEST_PID << ".csv"; auto stats_path = stats_dir / fname.str(); ScopedFileRemover stats_cleanup{stats_path}; // Get the unique node names the accountant will look up std::string name_a = IResourceAccountant::MakeUniqueNodeName(*h.node_a); std::string name_b = IResourceAccountant::MakeUniqueNodeName(*h.node_b); { std::ofstream ofs(stats_path); ASSERT_TRUE(ofs.is_open()); ofs << "#name,input_sizes,initializers_sizes,total_dynamic_sizes,total_temp_allocations\n"; // input_sizes=100, initializers=200, dynamic=300, temp=400 -> total=1000 ofs << name_a << ",100,200,300,400\n"; // input_sizes=50, initializers=0, dynamic=150, temp=0 -> total=200 ofs << name_b << ",50,0,150,0\n"; } // Factory expects stats file relative to model_path dir ConfigOptions config; std::string setting = "500," + stats_path.filename().string(); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, setting.c_str())); std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, stats_dir / "dummy_model.onnx", acc_map)); ASSERT_TRUE(acc_map.has_value()); auto* accountant = acc_map->at(kCudaExecutionProvider).get(); auto cost_a = accountant->ComputeResourceCount(*h.node_a); EXPECT_EQ(std::get(cost_a), size_t{1000}); EXPECT_EQ(accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()).source, WorkspaceEstimateSource::kProfile); auto cost_b = accountant->ComputeResourceCount(*h.node_b); EXPECT_EQ(std::get(cost_b), size_t{200}); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(cost_a); sub_graph.AppendNodeCost(cost_b); sub_graph.AccountForAllNodes(); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{400}); EXPECT_EQ(accountant->GetWorkspaceEstimateSourceCounts().profile, size_t{2}); // Threshold should be 500 KB = 512000 bytes auto threshold = accountant->GetThreshold(); ASSERT_TRUE(threshold.has_value()); EXPECT_EQ(std::get(*threshold), size_t{500 * 1024}); } TEST(RealAccountantTest, StatsPath_Level1EstimateUsesMaximumWorkspace) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::error_code ec; auto stats_dir = std::filesystem::temp_directory_path(ec); ASSERT_FALSE(ec) << ec.message(); std::ostringstream fname; fname << "test_resource_accountant_combined_stats_" << ORT_TEST_PID << ".csv"; auto stats_path = stats_dir / fname.str(); ScopedFileRemover stats_cleanup{stats_path}; const std::string name_a = IResourceAccountant::MakeUniqueNodeName(*h.node_a); const std::string name_b = IResourceAccountant::MakeUniqueNodeName(*h.node_b); { std::ofstream ofs(stats_path); ASSERT_TRUE(ofs.is_open()); ofs << "#name,input_sizes,initializers_sizes,total_dynamic_sizes,total_temp_allocations\n"; ofs << name_a << ",100,200,300,400\n"; ofs << name_b << ",50,0,50,100\n"; } ConfigOptions config; std::string setting = "500," + stats_path.filename().string(); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, setting.c_str())); std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, stats_dir / "dummy_model.onnx", acc_map)); auto* accountant = acc_map->at(kCudaExecutionProvider).get(); auto cost_a = accountant->ComputeResourceCount( *h.node_a, Level1MemoryEstimate{/*runtime_workspace_bytes=*/250}); EXPECT_EQ(GetSizeT(cost_a), size_t{1000}); const auto pending_workspace_a = accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(pending_workspace_a.bytes, size_t{400}); EXPECT_EQ(pending_workspace_a.source, WorkspaceEstimateSource::kProfileAndEstimator); auto cost_b = accountant->ComputeResourceCount( *h.node_b, Level1MemoryEstimate{/*runtime_workspace_bytes=*/800}); EXPECT_EQ(GetSizeT(cost_b), size_t{900}); const auto pending_workspace_b = accountant->GetPendingWorkspaceEstimateSelection(h.node_b->Index()); EXPECT_EQ(pending_workspace_b.bytes, size_t{800}); EXPECT_EQ(pending_workspace_b.source, WorkspaceEstimateSource::kProfileAndEstimator); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(cost_a); sub_graph.AppendNodeCost(cost_b); sub_graph.AccountForAllNodes(); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{1900}); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{1200}); EXPECT_EQ(accountant->GetWorkspaceEstimateSourceCounts().profile_and_estimator, size_t{2}); const auto comparison = accountant->GetWorkspaceEstimateComparisonSummary(); EXPECT_EQ(comparison.node_count, size_t{2}); EXPECT_EQ(comparison.profile_larger, size_t{1}); EXPECT_EQ(comparison.estimator_larger, size_t{1}); EXPECT_EQ(comparison.equal, size_t{0}); EXPECT_EQ(comparison.profiled_bytes, size_t{500}); EXPECT_EQ(comparison.level1_estimated_bytes, size_t{1050}); std::optional transient_acc_map; ASSERT_STATUS_OK(CreateAccountants(config, stats_dir / "dummy_model.onnx", transient_acc_map)); auto* transient_accountant = transient_acc_map->at(kCudaExecutionProvider).get(); const auto transient_cost = transient_accountant->ComputeResourceCount( *h.node_a, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/std::nullopt, /*persistent_prepack_bytes=*/0, /*initialization_scratch_bytes=*/0, /*runtime_transient_bytes=*/800}); EXPECT_EQ(GetSizeT(transient_cost), size_t{1400}); const auto transient_selection = transient_accountant->GetPendingWorkspaceEstimateSelection(h.node_a->Index()); EXPECT_EQ(transient_selection.bytes, size_t{800}); EXPECT_EQ(transient_selection.source, WorkspaceEstimateSource::kProfileAndEstimator); IndexedSubGraph transient_sub_graph; transient_sub_graph.nodes.push_back(h.node_a->Index()); transient_sub_graph.SetAccountant(transient_accountant); transient_sub_graph.AppendNodeCost(transient_cost); transient_sub_graph.AccountForAllNodes(); EXPECT_EQ(transient_accountant->GetWorkspaceEstimateSourceCounts().profile_and_estimator, size_t{1}); const auto transient_comparison = transient_accountant->GetWorkspaceEstimateComparisonSummary(); EXPECT_EQ(transient_comparison.node_count, size_t{1}); EXPECT_EQ(transient_comparison.estimator_larger, size_t{1}); EXPECT_EQ(transient_comparison.profiled_bytes, size_t{400}); EXPECT_EQ(transient_comparison.level1_estimated_bytes, size_t{800}); const auto reservations = accountant->GetCommittedWorkspaceReservations(); ASSERT_EQ(reservations.size(), size_t{1}); const auto& graph_reservations = reservations.at(h.graph); EXPECT_EQ(graph_reservations.at(h.node_a->Index()).bytes, size_t{400}); EXPECT_EQ(graph_reservations.at(h.node_a->Index()).source, WorkspaceEstimateSource::kProfileAndEstimator); EXPECT_EQ(graph_reservations.at(h.node_b->Index()).bytes, size_t{800}); } // A stats file may have incomplete coverage. Preserve the historical behavior // where unknown nodes have zero cost and do not enter ad-hoc bookkeeping. TEST(RealAccountantTest, StatsPath_UnknownNodeHasZeroCost) { SharedWeightGraph h; ASSERT_NO_FATAL_FAILURE(SharedWeightGraph::Create(h)); std::error_code ec; auto stats_dir = std::filesystem::temp_directory_path(ec); ASSERT_FALSE(ec) << ec.message(); std::ostringstream fname; fname << "test_resource_accountant_empty_stats_" << ORT_TEST_PID << ".csv"; auto stats_path = stats_dir / fname.str(); ScopedFileRemover stats_cleanup{stats_path}; { std::ofstream ofs(stats_path); ASSERT_TRUE(ofs.is_open()); ofs << "#name,input_sizes,initializers_sizes,total_dynamic_sizes,total_temp_allocations\n"; ofs << IResourceAccountant::MakeUniqueNodeName(*h.node_a) << ",100,200,300,400\n"; // No entry for node_b. } ConfigOptions config; std::string setting = "1000," + stats_path.filename().string(); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, setting.c_str())); std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, stats_dir / "dummy_model.onnx", acc_map)); auto* accountant = acc_map->at(kCudaExecutionProvider).get(); auto known_cost = accountant->ComputeResourceCount(*h.node_a); EXPECT_EQ(std::get(known_cost), size_t{1000}); auto unknown_cost = accountant->ComputeResourceCount( *h.node_b, Level1MemoryEstimate{ /*runtime_workspace_bytes=*/250, /*persistent_prepack_bytes=*/300, /*initialization_scratch_bytes=*/400}); EXPECT_EQ(std::get(unknown_cost), size_t{0}); const auto pending_workspace = accountant->GetPendingWorkspaceEstimateSelection(h.node_b->Index()); EXPECT_EQ(pending_workspace.bytes, size_t{0}); EXPECT_EQ(pending_workspace.source, WorkspaceEstimateSource::kNone); IndexedSubGraph sub_graph; sub_graph.nodes.push_back(h.node_a->Index()); sub_graph.nodes.push_back(h.node_b->Index()); sub_graph.SetAccountant(accountant); sub_graph.AppendNodeCost(known_cost); sub_graph.AppendNodeCost(unknown_cost); sub_graph.AccountForAllNodes(); EXPECT_EQ(GetSizeT(accountant->GetConsumedAmount()), size_t{1000}); EXPECT_EQ(accountant->GetCommittedWorkspaceEstimate(), size_t{400}); EXPECT_EQ(accountant->GetWorkspaceEstimateSourceCounts().profile, size_t{1}); } // Factory with no limit and no stats file creates accountant with no threshold. TEST(RealAccountantTest, Factory_NoLimitNoStats) { ConfigOptions config; ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, ",")); std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, PathString(), acc_map)); ASSERT_TRUE(acc_map.has_value()); auto* accountant = acc_map->at(kCudaExecutionProvider).get(); const auto original_threshold = accountant->GetThreshold(); EXPECT_FALSE(original_threshold.has_value()); accountant->SetThreshold(ResourceCount{size_t{123}}); ASSERT_TRUE(accountant->GetThreshold().has_value()); EXPECT_EQ(GetSizeT(*accountant->GetThreshold()), size_t{123}); accountant->SetThreshold(original_threshold); EXPECT_FALSE(accountant->GetThreshold().has_value()); } TEST(RealAccountantTest, FactoryRetainsNarrowWorkspaceEstimatorConfig) { ConfigOptions config; ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1000,")); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsCudaFpAIntBGemm, "1")); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsCudaFpAIntBProfileM, "1,16")); ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength, "4096")); ASSERT_STATUS_OK(config.AddConfigEntry("unrelated.config", "not copied")); std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, PathString(), acc_map)); ASSERT_TRUE(acc_map.has_value()); auto* accountant = acc_map->at(kCudaExecutionProvider).get(); const auto& estimator_config = accountant->GetWorkspaceEstimatorConfig(); EXPECT_EQ(estimator_config.cuda_fpa_intb_gemm, std::optional{"1"}); EXPECT_EQ(estimator_config.cuda_fpa_intb_profile_m, std::optional{"1,16"}); EXPECT_EQ(estimator_config.cuda_gqa_workspace_max_total_sequence_length, int64_t{4096}); } TEST(RealAccountantTest, FactoryParsesGqaWorkspaceEnvelope) { struct Case { const char* value; int64_t expected; }; for (const auto& test_case : { Case{nullptr, 0}, Case{"0", 0}, Case{"4096", 4096}, Case{"9223372036854775807", std::numeric_limits::max()}}) { SCOPED_TRACE(test_case.value != nullptr ? test_case.value : ""); ConfigOptions config; ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1000,")); if (test_case.value != nullptr) { ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength, test_case.value)); } std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, PathString(), acc_map)); ASSERT_TRUE(acc_map.has_value()); const auto& estimator_config = acc_map->at(kCudaExecutionProvider)->GetWorkspaceEstimatorConfig(); EXPECT_EQ(estimator_config.cuda_gqa_workspace_max_total_sequence_length, test_case.expected); } } TEST(RealAccountantTest, FactoryRejectsInvalidGqaWorkspaceEnvelope) { for (bool enable_partitioning : {false, true}) { SCOPED_TRACE(enable_partitioning); for (const char* value : {"-1", "", "malformed", "4096x", "+4096", " 4096", "4096 ", "9223372036854775808"}) { SCOPED_TRACE(value); ConfigOptions config; if (enable_partitioning) { ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1000,")); } ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength, value)); std::optional acc_map; const auto status = CreateAccountants(config, PathString(), acc_map); ASSERT_FALSE(status.IsOK()); EXPECT_EQ(status.Code(), common::StatusCode::INVALID_ARGUMENT); EXPECT_NE(status.ErrorMessage().find( kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength), std::string::npos); EXPECT_FALSE(acc_map.has_value()); } } } // Factory returns empty optional when no config is set. TEST(RealAccountantTest, Factory_NoConfigReturnsEmpty) { ConfigOptions config; std::optional acc_map; ASSERT_STATUS_OK(CreateAccountants(config, PathString(), acc_map)); EXPECT_FALSE(acc_map.has_value()); } // Factory rejects malformed config (missing comma). TEST(RealAccountantTest, Factory_MalformedConfigReturnsError) { ConfigOptions config; ASSERT_STATUS_OK(config.AddConfigEntry( kOrtSessionOptionsResourceCudaPartitioningSettings, "1000")); // missing comma std::optional acc_map; auto status = CreateAccountants(config, PathString(), acc_map); EXPECT_FALSE(status.IsOK()); } } // namespace test } // namespace onnxruntime