// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include #include #include #include #include #include #include #include #include "core/common/common.h" #include "core/common/inlined_containers.h" #include "core/framework/level1_memory_estimate.h" #include "core/framework/max_shape_override.h" namespace onnxruntime { struct ConfigOptions; #ifndef SHARED_PROVIDER class Node; #else struct Node; #endif // Common holder for potentially different resource accounting // for different EPs using ResourceCount = std::variant; enum class WorkspaceEstimateSource { kNone, kFallback, kProfile, kEstimator, kProfileAndEstimator, }; struct WorkspaceEstimateSelection { size_t bytes = 0; WorkspaceEstimateSource source = WorkspaceEstimateSource::kNone; size_t profiled_bytes = 0; size_t level1_estimated_bytes = 0; size_t persistent_prepack_bytes = 0; size_t initialization_scratch_bytes = 0; }; struct WorkspaceEstimateSourceCounts { size_t fallback = 0; size_t profile = 0; size_t estimator = 0; size_t profile_and_estimator = 0; }; struct WorkspaceEstimateComparisonSummary { size_t node_count = 0; size_t profile_larger = 0; size_t estimator_larger = 0; size_t equal = 0; size_t profiled_bytes = 0; size_t level1_estimated_bytes = 0; }; struct WorkspaceEstimatorConfig { std::optional cuda_fpa_intb_gemm; std::optional cuda_fpa_intb_profile_m; // Validated nonnegative int64 envelope; zero means unspecified. // Reader-only until the GQA workspace estimator consumes the envelope. int64_t cuda_gqa_workspace_max_total_sequence_length = 0; }; using NodeWorkspaceReservationMap = InlinedHashMap; using WorkspaceReservationMap = InlinedHashMap; void ConsolidateWorkspaceReservations( NodeWorkspaceReservationMap& reservations, gsl::span source_node_indices, size_t destination_node_index); // Type-erased arithmetic for ResourceCount values. // Implementations use std::visit so the compiler enforces exhaustive handling // of all variant members — adding a new type to ResourceCount will produce // build errors at each call site that must be addressed. // // NOTE: These functions are NOT available through the provider bridge (shared library EPs). // Budget enforcement for bridge-based EPs (e.g., in-tree CUDA EP) will be moved to the // graph partitioner in a follow-up PR. ResourceCount AddResourceCounts(const ResourceCount& a, const ResourceCount& b); bool ResourceCountExceeds(const ResourceCount& a, const ResourceCount& b); std::string FormatResourceCount(const ResourceCount& rc); /// /// This class is used for graph partitioning by EPs /// It stores the cumulative amount of the resource such as /// memory that would be consumed by the graph nodes if it is assigned to the EP. /// /// It provides interfaces to add, remove and query the resource consumption. /// /// Each provider may assign its own meaning to the resource according to its constraints. /// class IResourceAccountant { protected: IResourceAccountant() = default; IResourceAccountant(const ResourceCount& threshold) : threshold_(threshold) {} public: virtual ~IResourceAccountant() = default; virtual ResourceCount GetConsumedAmount() const = 0; virtual void AddConsumedAmount(const ResourceCount& amount) = 0; virtual void RemoveConsumedAmount(const ResourceCount& amount) = 0; // Computes the complete resource cost for a candidate node. A supplied // Level-1 estimate contributes prepack memory and uses its runtime workspace // instead of fallback workspace, or maximizes it with profiled workspace. virtual ResourceCount ComputeResourceCount( const Node& node, std::optional level1_memory_estimate) = 0; ResourceCount ComputeResourceCount(const Node& node) { return ComputeResourceCount(node, std::nullopt); } std::optional GetThreshold() const { return threshold_; } void SetThreshold(const ResourceCount& threshold) { threshold_ = threshold; } void SetThreshold(std::optional threshold) { threshold_ = std::move(threshold); } void SetStopAssignment() noexcept { stop_assignment_ = true; } bool IsStopIssued() const noexcept { return stop_assignment_; } // Called before each GetCapability pass to reset per-pass state: // clears the stop flag (which only applies to the pass that set it) // and discards pending resource tracking from a previous (discarded) pass. void ResetForNewPass() { stop_assignment_ = false; ResetPendingResourcesImpl(); } // Called when a node's cost is committed (AccountForNode/AccountForAllNodes). // Commits any per-node resource breakdown tracked while ComputeResourceCount() // was called. Default no-op for accountants without a resource breakdown. virtual void CommitResourcesForNode(size_t /*node_index*/) {} // Returns the pending workspace selection recorded while computing a node's cost. // Used when layout transformation defers committing first-pass capabilities. virtual WorkspaceEstimateSelection GetPendingWorkspaceEstimateSelection( size_t /*node_index*/) const { return {}; } // Commits a workspace estimate whose original pending state is no longer available. // Used for nodes that survive a layout-transformation second pass. virtual void AddCommittedWorkspaceEstimate( const void* /*graph_identity*/, size_t /*node_index*/, WorkspaceEstimateSelection /*selection*/) {} // Consolidates committed reservations for constituent nodes onto their surviving fused node. virtual void ConsolidateCommittedWorkspaceReservations( const void* /*graph_identity*/, gsl::span /*source_node_indices*/, size_t /*destination_node_index*/) {} static std::string MakeUniqueNodeName(const Node& node); /// Set the max shape overrides for workspace estimation. /// Called during graph partitioner initialization when session.max_shape_override is set. void SetMaxShapeOverrides(MaxShapeOverrideMap overrides) { max_shape_overrides_ = std::move(overrides); } const MaxShapeOverrideMap& GetMaxShapeOverrides() const { return max_shape_overrides_; } void SetMaxShapeInferenceResult(MaxShapeInferenceResult result) { max_shape_inference_result_ = std::move(result); } const MaxShapeInferenceResult& GetMaxShapeInferenceResult() const { return max_shape_inference_result_; } void SetWorkspaceEstimatorConfig(WorkspaceEstimatorConfig config) { workspace_estimator_config_ = std::move(config); } const WorkspaceEstimatorConfig& GetWorkspaceEstimatorConfig() const { return workspace_estimator_config_; } /// Returns workspace for nodes that were accepted and committed by partitioning. virtual size_t GetCommittedWorkspaceEstimate() const { return 0; } /// Returns persistent prepack memory conservatively charged for accepted nodes. virtual size_t GetCommittedPersistentPrepackEstimate() const { return 0; } /// Returns the peak initialization scratch estimate across accepted nodes. /// This diagnostic is not included in the additive partitioning budget. virtual size_t GetCommittedInitializationScratchEstimate() const { return 0; } /// Returns accepted-node counts grouped by the workspace source used for budgeting. virtual WorkspaceEstimateSourceCounts GetWorkspaceEstimateSourceCounts() const { return {}; } /// Compares profile and estimator workspace values for accepted nodes where both were available. virtual WorkspaceEstimateComparisonSummary GetWorkspaceEstimateComparisonSummary() const { return {}; } /// Returns selected workspace reservations for accepted nodes, keyed by graph identity and node index. virtual WorkspaceReservationMap GetCommittedWorkspaceReservations() const { return {}; } protected: // Override to discard per-pass state for capabilities that were only probed. virtual void ResetPendingResourcesImpl() {} private: bool stop_assignment_ = false; std::optional threshold_; MaxShapeOverrideMap max_shape_overrides_; MaxShapeInferenceResult max_shape_inference_result_; WorkspaceEstimatorConfig workspace_estimator_config_; }; // A map of Ep Type to a resource accountant for this EP using ResourceAccountantMap = InlinedHashMap>; // This struct keeps accounting of the memory allocation stats // for a kernel during runtime if enabled. // Each metric describes max value seen as a result of inference run(s) struct NodeAllocationStats { // Total input sizes for the node size_t input_sizes = 0; // consumed initializer sizes size_t initializers_sizes = 0; // dynamically allocated outputs that actually occurred // at inference time. (usually not fixed size and not pre-allocated) size_t total_dynamic_sizes = 0; // Temporary allocations that took place at this execution. size_t total_temp_allocations = 0; NodeAllocationStats& operator+=(const NodeAllocationStats& other) { input_sizes += other.input_sizes; initializers_sizes += other.initializers_sizes; total_dynamic_sizes += other.total_dynamic_sizes; total_temp_allocations += other.total_temp_allocations; return *this; } void UpdateIfGreater(const NodeAllocationStats& other) { input_sizes = std::max(input_sizes, other.input_sizes); initializers_sizes = std::max(initializers_sizes, other.initializers_sizes); total_dynamic_sizes = std::max(total_dynamic_sizes, other.total_dynamic_sizes); total_temp_allocations = std::max(total_temp_allocations, other.total_temp_allocations); } }; class NodeStatsRecorder { public: explicit NodeStatsRecorder(const std::filesystem::path& stats_file_name); ~NodeStatsRecorder(); ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(NodeStatsRecorder); const std::filesystem::path& GetNodeStatsFileName() const noexcept; bool ShouldAccountFor(const std::string& input_output_name) const; void ResetPerRunNameDeduper(); void ReportNodeStats(const std::string& node_name, const NodeAllocationStats& stats); void DumpStats(const std::filesystem::path& model_path) const; private: void DumpStats(std::ostream& os) const; struct Impl; std::unique_ptr impl_; }; Status CreateAccountants( const ConfigOptions& config_options, const std::filesystem::path& model_path, std::optional& acc_map); } // namespace onnxruntime