// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include #include #include #include #include #include #include #include #include namespace onnx_transpose_optimization { namespace api { /* This file defines the API for the transpose optimizer and layout transformation tool. The API consists of a set of * abstract classes and methods for graph manipulation that must be implemented to utilize the optimizer tool. The * tool attempts to make no assumptions about how ONNX models are represented, other than named values (node outputs, * initializers, etc.) should have names representable as string_view objects. * * Abstract classes like api::GraphRef and api::NodeRef should be thought of as interfaces for manipulating a * graph/node, not the graph/node itself. This allows the implementer to use their existing model representation and * create interface instances on the fly as they are requested by the optimizer. * * Since abstract class instances are created on the fly at the optimizer's request (when finding a node with a * certain output, for example), they are returned from the implementer as unique_ptr types. Consequently, the * implementer does not need to worry about memory management for these classes and no cache of created classes needs * to be maintained. However they should be small, ideally containing only pointers to the concrete objects that they * manipulate. * * All editing methods are guaranteed to maintain graph integrity (acyclic, valid input/output names), but validity * as an ONNX model may be temporarily violated (ops may have fewer inputs than allowed, incorrect datatypes, etc). * Node/output names are generated by the implementer. To avoid having an output generated by multiple nodes during * editing, output nodes cannot be directly manipulated by the API. The only method that changes a node's outputs is * the MoveOutput method, which transfers an output and all its consumers from one node to another. * * Some methods for querying value producers/consumers can only be implemented efficiently through the use of indexes, * which may be queried regularly between edits and must be carefully maintained. */ /// /// Enum of DataTypes using standard ONNX values. Casting to/from int32_t is encouraged. /// enum class DataType : int32_t { UNDEFINED = 0, FLOAT = 1, // float UINT8 = 2, // uint8_t INT8 = 3, // int8_t UINT16 = 4, // uint16_t INT16 = 5, // int16_t INT32 = 6, // int32_t INT64 = 7, // int64_t STRING = 8, // string BOOL = 9, // bool FLOAT16 = 10, DOUBLE = 11, UINT32 = 12, UINT64 = 13, COMPLEX64 = 14, COMPLEX128 = 15, BFLOAT16 = 16, FLOAT8E4M3FN = 17, FLOAT8E4M3FNUZ = 18, FLOAT8E5M2 = 19, FLOAT8E5M2FNUZ = 20, }; /// /// An interface for a constant tensor value used by initializers /// class TensorRef { public: /// The shape of the tensor. Values are nonnegative. virtual std::vector Shape() const = 0; virtual size_t NumElements() const = 0; /// The dtype of the tensor. virtual DataType DType() const = 0; /// /// Retrieves copy of raw data bytes from the tensor. Used for reading initializers specifying axes/pads/scales. /// /// Flattened tensor data in bytes virtual std::vector Data() const = 0; virtual ~TensorRef() {}; }; /// /// Interface for accessing/manipulating type/shape information about a value in a graph. The value is either from a /// graph input, graph initializer, or node output. Must be able to provide up-to-date information on the value of /// that name unless that value is removed from the graph (in which case behavior is undefined). /// class ValueInfoRef { public: /// The name of the value in the graph virtual std::string_view Name() const = 0; /// /// The inferred/declared tensor shape of the value. nullopt if rank is unknown, otherwise a vector with entries /// representing the dimensions of the value. Use -1 for unknown dimensions. /// virtual std::optional> Shape() const = 0; /// /// The inferred/declared rank of the value's tensor shape, or nullopt if the rank is unknown. A scalar /// has a rank of 0. /// virtual std::optional ShapeRank() const = 0; /// The inferred/declared dtype of the value. UNDEFINED (0) if dtype is unknown. virtual DataType DType() const = 0; /// /// Set the inferred tensor shape. Only used for values that are node outputs. Graph inputs will not change shape /// and initializers are expected to update corresponding ValueInfo shapes when the initializer tensor is modified. /// /// nullptr to set an unknown shape. Else, a vector of dim values, with -1 for unknown. virtual void SetShape(const std::vector* shape) = 0; /// /// Reorders the dimensions of the inferred tensor shape. Only used for values that are node outputs. Has no effect /// if rank is unknown. Behavior is undefined if rank does not match number of dimensions in perm. Preferred to /// SetShape since it can maintain symbolic shape information. /// /// Permutation for dimensions. An ordering of the values 0 ... rank - 1. virtual void PermuteDims(const std::vector& perm) = 0; /// /// Inserts constant dimensions of value 1 at the specified axes of the inferred tensor shape. Only used for values /// that are node outputs. Has no effect if rank is unknown. Behavior is undefined if axes are negative or exceed /// rank + axes.size() - 1. Preferred to SetShape since it can maintain symbolic shape information. /// /// Indices of dimensions to add. Indices are relative to final shape. virtual void UnsqueezeDims(const std::vector& axes) = 0; virtual ~ValueInfoRef() {}; }; /// /// Interface for accessing/manipulating a node in a graph. Information should remain up-to-date even if node is /// modified, unless it is removed from the graph. Behavior is undefined for methods called on removed nodes. /// class NodeRef { public: /// Node name virtual std::string_view Name() const = 0; /// Op computed by the node virtual std::string_view OpType() const = 0; /// Domain containing the op. Empty string if node has no domain set. virtual std::string_view Domain() const = 0; /// Names of input values. Empty string may be included for optional inputs. virtual std::vector Inputs() const = 0; /// Names of output values. Empty string may be included for optional outputs. virtual std::vector Outputs() const = 0; /// Name of the attribute to return /// /// The attribute value, or nullopt if the attribute is not present on the node, or is not of type int. /// virtual std::optional GetAttributeInt(std::string_view name) const = 0; /// Name of the attribute to return /// /// The attribute value, or nullopt if the attribute is not present on the node, or is not of type string. /// virtual std::optional GetAttributeString(std::string_view name) const = 0; /// Name of the attribute to return /// /// The attribute value, or nullopt if the attribute is not present on the node, or is not of type int[]. /// virtual std::optional> GetAttributeInts(std::string_view name) const = 0; /// /// Sets an int attribute with name and value. Overwrites existing value if present. /// /// Name of the attribute to set /// New value of attribute virtual void SetAttributeInt(std::string_view name, int64_t value) = 0; /// /// Sets an int[] attribute with name and value. Overwrites existing value if present. /// /// Name of the attribute to set /// New value of attribute virtual void SetAttributeInts(std::string_view name, const std::vector& value) = 0; /// /// Copies all attributes from a node to this node /// /// Node to copy attributes from virtual void CopyAttributes(const NodeRef& node) = 0; /// /// Removes attribute with name if present /// /// Name of the attribute to clear virtual void ClearAttribute(std::string_view name) = 0; /// /// Sets the ith input of this node. Supports optional inputs. Expands size if i is out of bounds, padding with "" /// as needed. /// /// Index of the input to update. /// Name of value to use as input or "" for missing optional values. virtual void SetInput(size_t i, std::string_view name) = 0; /// /// Convenience method. Returns whether node is of the specified op type and domain /// /// Op type /// Domain. Empty string and "onnx.ai" are treated as equal. /// virtual bool IsOp(std::string_view op_type, std::string_view domain = "") const { if (OpType() != op_type) { return false; } std::string_view node_domain = Domain(); return node_domain == domain || ((domain == "" || domain == "ai.onnx") && (node_domain == "" || node_domain == "ai.onnx")); } /// /// Convenience method. Returns value of int attribute with name, or given default if unset. /// /// Attribute name /// Default value /// Attribute value or default value virtual int64_t GetAttributeIntDefault(std::string_view name, int64_t default_value) const { return GetAttributeInt(name).value_or(default_value); } /// /// Returns the Execution Provider assigned to this node. Any empty string means this node is /// not assigned to any EP. /// /// EP type or empty string virtual std::string_view GetExecutionProviderType() const = 0; /// /// Returns the schema since version for the op_type of this node. Value of -1 means it is not set. /// /// since version or default value -1 virtual int SinceVersion() const = 0; /// /// Get the unique id of the node. /// /// Id virtual int64_t Id() const = 0; /// /// Get the layering annotation of the node. /// /// annotation virtual std::string_view GetLayeringAnnotation() const = 0; /// /// Set layering annotation /// /// virtual void SetLayeringAnnotation(std::string_view annotation) = 0; virtual ~NodeRef() {}; }; /// /// Information regarding the consumers of a value. /// struct ValueConsumers { /// /// List of nodes in the current graph containing value as an input /// std::vector> nodes; /// /// True if all consumers of the value are present in the nodes list. False if the value is used as a graph output /// or within subgraphs. /// bool comprehensive = true; }; /// /// Interface for accessing/manipulating a graph or subregion of a graph in a model. Additionally contains methods /// for querying some model-level information (like model opsets). /// /// No ability to access subgraphs is provided, but values that are not used exclusively in this graph can be /// indicated as such by setting `comprehensive` to `false` on `GetValueConsumers` queries. /// /// In most use cases, the interface will allow for access to the entire graph, but to restrict access to a portion, /// implementers should refrain from returning references to nodes outside of the subregion. Filtering the outputs of /// the `Nodes`, `GetValueConsumers`, and `GetNodeProducingOutput` methods is sufficient (and `comprehensive` /// should be set to `false` as needed). /// /// Access to parent graphs should be restricted, except GetConstant which may return initializers from parent graphs. /// class GraphRef { public: /// Domain name to find in model opset_import /// Opset of domain declared in model, or nullopt if domain is not present virtual std::optional Opset(std::string_view domain) const = 0; /// Topologically-sorted list of nodes in the graph virtual std::vector> Nodes() const = 0; /// /// Checks whether the value name refers to a constant initializer and if so, returns a Tensor corresponding to it. /// Constants from parent graphs may be included. /// /// Value name. Must be nonempty. /// Tensor corresponding to the constant initializer or nullptr virtual std::unique_ptr GetConstant(std::string_view name) const = 0; /// /// Checks whether the value name refers to a constant initializer in the current graph and if so, returns a Tensor /// corresponding to it. The constant must be mutable (able to be edited by Transpose/ReshapeInitializer). /// /// Value name. Must be nonempty. /// Tensor corresponding to the mutable constant initializer from this graph, or nullptr virtual std::unique_ptr GetLocalConstant(std::string_view name) const = 0; /// /// Returns a ValueInfo instance for querying info about the value with the given name. Behavior is undefined if /// the name does not refer to a value in the graph. /// Value name. Must be nonempty. /// A ValueInfo instance corresponding to the value with the given name virtual std::unique_ptr GetValueInfo(std::string_view name) const = 0; /// /// Returns a ValueConsumers object characterizing the current consumers of the value with the specified name. nodes /// contains nodes consuming the value as an input. comprehensive is true if the nodes in the result are the only /// references to the value within the model (it isn't referenced in subgraphs or graph outputs). /// /// The name of the value. Must be nonempty. /// ValueConsumers corresponding to usage of specified value within the model virtual std::unique_ptr GetValueConsumers(std::string_view name) const = 0; /// /// Determines if the specified value is a node output and if so returns that node. /// /// The name of the value. Must be nonempty. /// Node producing the value or nullptr (or nullptr if value is not a node output) virtual std::unique_ptr GetNodeProducingOutput(std::string_view name) const = 0; /// /// Transposes an initializer "in place". Existing ValueInfo for the initializer must subsequently return the /// updated shape. Behavior is undefined if name does not correspond to an initializer in this graph, or if rank of /// initializer does not match length of perm. /// /// The name of the initializer /// Permutation for transpose. An ordering of the values 0 ... rank - 1. virtual void TransposeInitializer(std::string_view name, const std::vector& perm) = 0; // Like TransposeInitializer. Product of dims will always match number of elements. Should be fast since // data buffer is unchanged. /// /// Reshapes an initializer "in place". Existing ValueInfo for the initializer must subsequently return the /// updated shape. Behavior is undefined if name does not correspond to an initializer in this graph, or if number /// of elements does not match requested shape. /// /// The name of the initializer /// New shape. Dimensions are nonnegative. virtual void ReshapeInitializer(std::string_view name, const std::vector& shape) = 0; /// /// Creates a new node in the graph with the specified op type. Node name and output names are automatically /// generated. Outputs of created node have unspecified shapes/dtypes. They will be populated afterwards using /// CopyValueInfo. /// /// The new node's name /// The new node's op type /// Inputs for the node. "" for missing optional inputs. /// /// Number of outputs for the node. Names automatically generated. Optional outputs not supported. /// /// The new node's domain. Empty string signifies default onnx domain. /// The new node virtual std::unique_ptr AddNode(std::string_view name, std::string_view op_type, const std::vector& inputs, size_t num_outputs, std::string_view domain = /*kOnnxDomain*/ "") = 0; /// /// Creates a copy of the provided node in the graph with the specified op type and domain. /// /// The new node's op type /// The new node's domain. Empty string signifies default onnx domain. /// The new node's since_version. If unspecified, use that of the old node. /// The new node virtual std::unique_ptr CopyNode(const api::NodeRef& source_node, std::string_view op_type, std::string_view domain = "", std::optional since_version = std::nullopt) = 0; /// /// Deletes a node from the graph. Behavior is undefined if node has any consumers. /// /// Node to remove virtual void RemoveNode(NodeRef& node) = 0; /// /// Removes an initializer. Behavior is undefined if initializer has any consumers, or if name does not refer to an /// initializer. /// /// Name of initializer to remove virtual void RemoveInitializer(std::string_view name) = 0; /// /// Creates an initializer with the specified dtype, shape, and data. Returns the name. /// /// DataType for new initializer. /// Dimensions for new initializer. Entries are Nonnegative. /// /// Raw bytes for new initializer. Length matches product of dimensions and size of the dtype /// /// Generated name for the initializer virtual std::string_view AddInitializer(DataType dtype, const std::vector& shape, const std::vector& data) = 0; /// /// "Moves" an output from one node to another, (effectively transferring the output name, shape, type, /// and all consumers, even those in subgraphs). Creates a new output for the source node where the moved output. /// was taken from (with unspecified shape/dtype). The destination node's output is guaranteed to have no consumers /// before the call and can be deleted once replaced. /// /// For example, to remove two canceling transposes we could create an Identity node and use MoveOutput to move /// the output from the last Transpose to the identity. All former consumers of the transpose op would then /// consume the identity op. /// /// The replacement output is useful when the old op will still need to be used. For example, when pushing /// a transpose through a Relu op, we create a new Transpose and move the output from the Relu to it. Then assign /// the input of the Transpose to be the newly-generated output from the Relu. /// /// Node to move the output from. Will be given a new replacement output. /// Index of the output to move and then generate a replacement for. /// Node to mode the output to. /// Index of the output to replace and delete. Has no consumers. virtual void MoveOutput(NodeRef& src_node, size_t src_idx, NodeRef& dst_node, size_t dst_idx) = 0; /// /// Copies shape and dtype value info from one output to another, potentially including data that cannot be encoded /// in the ValueInfo class (like symbolic shape information). If already set, the destination dtype should be equal /// to the source dtype. /// /// /// virtual void CopyValueInfo(std::string_view src_name, std::string_view dst_name) = 0; /// /// Returns whether there are any consumers of the value with the given name. Override default implementation to /// avoid call to GetValueConsumers. /// /// The name of the value. Must be nonempty. /// true if the value is not currently referenced anywhere in the model virtual bool HasValueConsumers(std::string_view name) const { auto consumers = GetValueConsumers(name); bool unused = consumers->comprehensive && consumers->nodes.size() == 0; return !unused; } /// /// Is the value a graph output. /// /// Value name. /// True if output of the Graph. virtual bool IsGraphOutput(std::string_view name) const = 0; virtual ~GraphRef() {}; }; } // namespace api constexpr int64_t kMinSupportedOpset = 7; constexpr int64_t kMaxSupportedOpset = 27; // enum of results that a CostCheckFn can return. enum class CostCheckResult { kStop, // pushing Transpose is expected to negatively impact performance kPushTranspose, // pushing Transpose is expected to improve performance kFallThrough // fall through to default cost check }; /// /// Function to allow overriding the default cost check to determine whether it is worth pushing a Transpose through /// a node. /// /// The graph being optimized /// The node we're considering pushing a Transpose through /// The perm value of the Transpose /// The set of outputs that lead to another Transpose in the graph. /// If we can successfully push the Transpose until it meets another Transpose they can either cancel each other out, /// or be merged into a single Transpose. /// using CostCheckFn = std::function& perm, const std::unordered_set& outputs_leading_to_transpose)>; /// /// Gets a list of layout sensitive ops defined by ONNX standard. /// /// const reference to an unordered set of op_types which are layout sensitive const std::unordered_set& GetLayoutSensitiveOps(); struct OptimizeResult { std::optional error_msg; // set if there was an error bool graph_modified{false}; }; // see transpose_optimizer.h if you wish to provide extended handlers struct HandlerInfo; using HandlerMap = std::unordered_map; /// /// Performs transpose optimization on a graph. Returns true if the graph was modified. /// /// Models outside the supported opset range will be returned unchanged. /// /// Optimization generally consists of swapping Transpose ops with following ops until a matching Transpose op is /// encountered. Transpose ops with inverse permutations are canceled. Uses heuristics to attempt to minimize the /// total cost of Transpose ops and only push Transposes when doing so has some benefit. /// /// The graph to optimize (or a portion of a graph, see api::GraphRef docs) /// Execution provider to assign new nodes to. /// If not specified, graph partitioning must be run later to assign nodes to EPs. /// /// Optional cost checking function to determine whether it is worth pushing a Transpose /// through a node. /// /// Map of handlers for non-ONNX operators and/or ONNX operators where special handling /// is required (e.g. ONNX Resize is layout agnostic but may be implemented in a layout sensitive way). /// /// OptimizeResult. If error_msg is set the Optimize failed. If not set, graph_modified indicates whether /// any changes were required during optimization. OptimizeResult Optimize(api::GraphRef& graph, const std::string& provider_type = "", CostCheckFn cost_check_fn = nullptr, const HandlerMap& extended_handlers = {}); } // namespace onnx_transpose_optimization