// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) #include "core/common/inlined_containers.h" #include "core/common/status.h" #include "core/graph/basic_types.h" #include "core/common/logging/logging.h" #include "gsl/gsl" #include #include #include #include #include struct OrtEpDevice; namespace onnxruntime { class ExecutionProviders; class Graph; /// /// Annotation extracted from kOrtSessionOptionsLayerAssignmentSettings session configuration option. /// struct LayerAnnotation { std::string device; std::string annotation; bool prefix_match; }; /// /// This struct is a container for layering rules extracted from the kOrtSessionOptionsLayerAssignmentSettings /// session configuration option. /// struct LayeringRules { std::vector rules; /// /// Parses the layering rules from the given configuration string. /// The configuration string is in the following format.: /// 'cpu(L1,L2); gpu(L3,=L4)' where cpu or gpu denote the target EP. /// L1, L2, L3 are annotations that can be matched to node annotations in the graph. The '=' prefix denotes /// exact match. The position of the annotation (L1, L2, L3) in the list denotes its priority in matching (left to right). /// However, the prefix annotations will always have higher priority than the exact match annotations regardless /// of their position in the list. In the above example, L1 has the highest priority, followed by L2, /// then L3 and finally L4. The rules are separated by ';' and there can be multiple rules for different EPs. /// /// The configuration string to parse. /// Output parameter where the parsed rules will be stored. /// Status indicating success or failure (e.g. due to format errors). static common::Status FromConfigString(const std::string& config_value, LayeringRules& rules); }; /// /// This class matches node annotations against layering rules. /// class LayeringRuleMatcher { public: /// The annotation-based layering rules to index. explicit LayeringRuleMatcher(const LayeringRules& rules); /// /// The method returns the index of the best matching rule for the given annotation /// if it exists /// /// annotation retrieved from protobuf node metadata /// index of the matching LayeringRule if it exists std::optional Match(const std::string& node_annotation) const; private: struct TrieNode { InlinedHashMap> children; std::optional rule_index; }; TrieNode root_; InlinedHashMap exact_match_rules_; void AddExactRule(const std::string& annotation, size_t index); void AddPrefixRule(const std::string& annotation, size_t index); void UpdateBestMatch(std::optional& current_best, size_t candidate) const; }; /// /// Performs substring matching against node names. Unlike LayeringRuleMatcher (which does /// prefix/exact matching from position 0), this matches patterns appearing anywhere in the /// input string. Longest matching pattern wins. /// class SubstringMatcher { public: /// The rules whose annotations become substring patterns. /// The '=' prefix (exact match) qualifier is rejected during config parsing — all patterns /// must be substrings. explicit SubstringMatcher(const LayeringRules& rules); /// /// Returns the index of the best matching rule for the given node name. /// "Best" = longest pattern that appears as a substring in the name. /// /// the node's name to match against /// index of the matching LayeringRule if a substring match is found std::optional Match(std::string_view node_name) const; private: struct PatternEntry { std::string pattern; size_t rule_index; }; // Sorted by pattern length descending. First match wins (longest-match priority). InlinedVector patterns_; }; namespace EpLayeringMatcher { /// /// Matches a list of available OrtEpDevices against the device string specified in the LayerAnnotation. /// Returns the EP Type string of the first device that matches the rule. /// /// The list of available EP devices. /// The rule containing the device designator. /// Optional containing the matched EP type, nullopt otherwise. std::optional Match(gsl::span ep_devices, const LayerAnnotation& rule); /// /// Matches a collection of ExecutionProviders against the device string specified in the LayerAnnotation. /// Returns the EP Type string of the first provider that matches the rule. /// /// The collection of available Execution Providers. /// The rule containing the device designator. /// Optional containing the matched EP type, nullopt otherwise. std::optional Match(const ExecutionProviders& providers, const LayerAnnotation& rule); } // namespace EpLayeringMatcher // This class contains indexing information about the entire graph // per sub-graph info is stored in graph_index_ class LayeringIndex { public: // mapping of EP name/type to a set of LayeringRule indices mapped to that EP. using EpNameToLayeringIndices = InlinedHashMap>; // mapping of LayeringRule index to EP name/type, reverse of the above using LayeringIndexToEpName = InlinedHashMap; /// /// Creates a fully initialized LayeringIndex. /// /// The graph to traverse and index. /// Pre-populated mapping of EP names to their applicable rule indices. /// Pre-populated mapping of rule indices to EP names. /// Matcher to resolve node annotations to rule indices. static LayeringIndex Create(const Graph& graph, EpNameToLayeringIndices ep_map, LayeringIndexToEpName rule_map, LayeringRules layering_rules); /// /// Creates a fully initialized LayeringIndex with a SubstringMatcher for name-based matching. /// In this mode, annotation matching is disabled and no subgraph inheritance is applied. /// static LayeringIndex Create(const Graph& graph, EpNameToLayeringIndices ep_map, LayeringIndexToEpName rule_map, LayeringRules layering_rules, SubstringMatcher substring_matcher); /// /// Factory method that creates a LayeringIndex by parsing configuration, matching rules against /// available devices/providers, and indexing the graph. /// Annotation-based and name-based options are mutually exclusive — setting both returns an error. /// /// The graph to index. /// The annotation-based configuration string (prefix/exact match on metadata). /// The name-based configuration string (substring match on Node::Name()). /// May be empty if name-based matching is not configured. /// Available OrtEpDevices to match rules against. /// Available ExecutionProviders to match rules against (fallback). /// Logger for reporting information/errors. /// Output parameter for the created LayeringIndex. Returns no index if /// no valid layering rules discovered. /// Status indicating success or failure. static Status Create(const Graph& graph, const std::string& config_string, const std::string& name_based_config_string, gsl::span ep_devices, const ExecutionProviders& ep_providers, const logging::Logger& logger, std::optional& layering_index); // Returns the Layering Rule indices mapped to the EP if any std::optional>> GetLayeringRulesForThisEp(const std::string& ep_type) const; // Returns the parsed layering rules const LayeringRules& GetRules() const noexcept { return rules_; } // This function returns an index for the Layering rule the node is assigned to if any std::optional GetNodeAssignment(const Graph& graph, NodeIndex node_id) const; // This is used when an EP fails to claim a node during partitioning so we make it // available for other EPs void MakeNodeUnassigned(const Graph& graph, NodeIndex node_id); /// /// Updates the layering index for a specific set of nodes in a graph. /// This checks if the nodes have annotations, and if so, matches them against the rules /// and updates the assignment. /// /// The graph containing the nodes. /// Indices of nodes to check and update. void Update(const Graph& graph, gsl::span nodes); private: LayeringRules rules_; LayeringRuleMatcher matcher_; // These stay constant EpNameToLayeringIndices ep_name_to_layering_indices_; LayeringIndexToEpName layering_index_to_ep_name_; using SetOfNodes = InlinedHashSet; using LayerIndexToNodes = InlinedHashMap; using NodeIndexToLayeringIndex = InlinedHashMap; /// /// This struct contains the result of layering assignment for a graph. /// The struct first reflects pre-assignment according to the configuration. /// However, as we partition the graph, some nodes may be moved to unassigned sections /// to make them available to subsequent partitioning passes. /// struct GraphLayeringIndex { // Node to layering idx assignment map 1:1 // If the node is not in this map, it is unassigned NodeIndexToLayeringIndex node_to_layering_index_; // This map contains mapping of LayeringRule index to the list of node ids // Reverse from the above 1:M LayerIndexToNodes layer_to_node_ids_; }; LayeringIndex(LayeringRules layering_rules, EpNameToLayeringIndices ep_name_to_layering_indices, LayeringIndexToEpName layering_index_to_ep_name, std::optional substring_matcher = std::nullopt) : rules_(std::move(layering_rules)), matcher_(rules_), ep_name_to_layering_indices_(std::move(ep_name_to_layering_indices)), layering_index_to_ep_name_(std::move(layering_index_to_ep_name)), substring_matcher_(std::move(substring_matcher)) {} // Optional substring matcher for name-based layer assignment std::optional substring_matcher_; // Graph and sub-graphs mapping to their indices InlinedHashMap graph_index_; void ProcessGraph(const Graph& graph, std::optional parent_layer_id); }; } // namespace onnxruntime #else namespace onnxruntime { class LayeringIndex; } #endif // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)